text
stringlengths 0
3.34M
|
---|
# Survival Regression with `estimators.SurvivalModel`
<hr>
Author: ***Willa Potosnak*** <[email protected]>
<div style=" float: right;">
</div>
# Contents
### 1. [Introduction](#introduction)
#### 1.1 [The SUPPORT Dataset](#support)
#### 1.2 [Preprocessing the Data](#preprocess)
### 2. [Cox Proportional Hazards (CPH)](#cph)
#### 2.1 [Fit CPH Model](#fitcph)
#### 2.2 [Evaluate CPH Model](#evalcph)
### 3. [Deep Cox Proportional Hazards (DCPH)](#fsn)
#### 3.1 [Fit DCPH Model](#fitfsn)
#### 3.2 [Evaluate DCPH Model](#evalfsn)
### 4. [Deep Survival Machines (DSM)](#dsm)
#### 4.1 [Fit DSM Model](#fitdsm)
#### 4.2 [Evaluate DSM Model](#evaldsm)
### 5. [Deep Cox Mixtures (DCM)](#dcm)
#### 5.1 [Fit DCM Model](#fitdcm)
#### 5.2 [Evaluate DCM Model](#evaldcm)
### 6. [Random Survival Forests (RSF)](#rsf)
#### 6.1 [Fit RSF Model](#fitrsf)
#### 6.2 [Evaluate RSF Model](#evalrsf)
<hr>
<a id="introduction"></a>
## 1. Introduction
The `SurvivalModels` class offers a steamlined approach to train two `auton-survival` models and three baseline survival models for right-censored time-to-event data. The fit method requires the same inputs across all five models, however, model parameter types vary and must be defined and tuned for the specified model.
### Native `auton-survival` Models
* **Faraggi-Simon Net (FSN)/DeepSurv**
* **Deep Survival Machines (DSM)**
* **Deep Cox Mixtures (DCM)**
### External Models
* **Random survival Forests (RSF)**
* **Cox Proportional Hazards (CPH)**
$\textbf{Hyperparameter tuning}$ and $\textbf{model evaluation}$ can be performed using the following metrics, among others.
* $\textbf{Brier Score (BS)}$: the Mean Squared Error (MSE) around the probabilistic prediction at a certain time horizon. The Brier Score can be decomposed into components that measure both discriminative performance and calibration.
\begin{align}
\text{BS}(t) = \mathop{\mathbf{E}}_{x\sim\mathcal{D}}\big[ ||\mathbf{1}\{ T > t \} - \widehat{\mathbf{P}}(T>t|X)\big)||_{_\textbf{2}}^\textbf{2} \big]
\end{align}
* $\textbf{Integrated Brier Score (IBS)}$: the integral of the time-dependent $\textbf{BS}$ over the interval $[t_1; t_{max}]$ where the weighting function is $w(t)= \frac{t}{t_{max}}$.
\begin{align}
\text{IBS} = \int_{t_1}^{t_{max}} \mathrm{BS}^{c}(t)dw(t)
\end{align}
* $\textbf{Area under ROC Curve (ROC-AUC)}$: survival model evaluation can be treated as binary classification to compute the **True Positive Rate (TPR)** and **False Positive Rate (FPR)** dependent on time, $t$. ROC-AUC is used to assess how well the model can distinguish samples that fail by a given time, $t$ from those that fail after this time.
\begin{align}
\widehat{AUC}(t) = \frac{\sum_{i=1}^{n} \sum_{j=1}^{n}I(y_j>t)I(y_i \leq t)w_iI(\hat{f}(x_j) \leq \hat{f}(x_i))}{(\sum_{i=1}^{n} I(y_i > t))(\sum_{i=1}^{n}I(y_i \leq t)w_i)}
\end{align}
* $\textbf{Time Dependent Concordance Index (C$^{td}$)}$: estimates ranking ability by exhaustively comparing relative risks across all pairs of individuals in the test set. We employ the ‘Time Dependent’ variant of Concordance Index that truncates the pairwise comparisons to the events occurring within a fixed time horizon.
\begin{align}
C^{td}(t) = P(\hat{F}(t|x_i) > \hat{F} (t|x_j)|\delta_i = 1, T_i < T_j, T_i \leq t)
\end{align}
<a id="support"></a>
### 1.1. The SUPPORT Dataset
*For the original datasource, please refer to the following [website](https://biostat.app.vumc.org/wiki/Main/SupportDesc).*
Data features $x$ are stored in a pandas dataframe with rows corresponding to individual samples and columns as covariates. Data outcome consists of 'time', $t$, and 'event', $e$, that correspond to the time to event and the censoring indicator, respectively.
```python
import pandas as pd
import sys
sys.path.append('../')
from auton_survival.datasets import load_dataset
```
```python
# Load the SUPPORT dataset
outcomes, features = load_dataset(dataset='SUPPORT')
# Identify categorical (cat_feats) and continuous (num_feats) features
cat_feats = ['sex', 'dzgroup', 'dzclass', 'income', 'race', 'ca']
num_feats = ['age', 'num.co', 'meanbp', 'wblc', 'hrt', 'resp',
'temp', 'pafi', 'alb', 'bili', 'crea', 'sod', 'ph',
'glucose', 'bun', 'urine', 'adlp', 'adls']
# Let's take a look at the features
display(features.head(5))
# Let's take a look at the outcomes
display(outcomes.head(5))
```
<div>
<style scoped>
.dataframe tbody tr th:only-of-type {
vertical-align: middle;
}
.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}
</style>
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>sex</th>
<th>dzgroup</th>
<th>dzclass</th>
<th>income</th>
<th>race</th>
<th>ca</th>
<th>age</th>
<th>num.co</th>
<th>meanbp</th>
<th>wblc</th>
<th>...</th>
<th>alb</th>
<th>bili</th>
<th>crea</th>
<th>sod</th>
<th>ph</th>
<th>glucose</th>
<th>bun</th>
<th>urine</th>
<th>adlp</th>
<th>adls</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>male</td>
<td>Lung Cancer</td>
<td>Cancer</td>
<td>$11-$25k</td>
<td>other</td>
<td>metastatic</td>
<td>62.84998</td>
<td>0</td>
<td>97.0</td>
<td>6.000000</td>
<td>...</td>
<td>1.799805</td>
<td>0.199982</td>
<td>1.199951</td>
<td>141.0</td>
<td>7.459961</td>
<td>NaN</td>
<td>NaN</td>
<td>NaN</td>
<td>7.0</td>
<td>7.0</td>
</tr>
<tr>
<th>1</th>
<td>female</td>
<td>Cirrhosis</td>
<td>COPD/CHF/Cirrhosis</td>
<td>$11-$25k</td>
<td>white</td>
<td>no</td>
<td>60.33899</td>
<td>2</td>
<td>43.0</td>
<td>17.097656</td>
<td>...</td>
<td>NaN</td>
<td>NaN</td>
<td>5.500000</td>
<td>132.0</td>
<td>7.250000</td>
<td>NaN</td>
<td>NaN</td>
<td>NaN</td>
<td>NaN</td>
<td>1.0</td>
</tr>
<tr>
<th>2</th>
<td>female</td>
<td>Cirrhosis</td>
<td>COPD/CHF/Cirrhosis</td>
<td>under $11k</td>
<td>white</td>
<td>no</td>
<td>52.74698</td>
<td>2</td>
<td>70.0</td>
<td>8.500000</td>
<td>...</td>
<td>NaN</td>
<td>2.199707</td>
<td>2.000000</td>
<td>134.0</td>
<td>7.459961</td>
<td>NaN</td>
<td>NaN</td>
<td>NaN</td>
<td>1.0</td>
<td>0.0</td>
</tr>
<tr>
<th>3</th>
<td>female</td>
<td>Lung Cancer</td>
<td>Cancer</td>
<td>under $11k</td>
<td>white</td>
<td>metastatic</td>
<td>42.38498</td>
<td>2</td>
<td>75.0</td>
<td>9.099609</td>
<td>...</td>
<td>NaN</td>
<td>NaN</td>
<td>0.799927</td>
<td>139.0</td>
<td>NaN</td>
<td>NaN</td>
<td>NaN</td>
<td>NaN</td>
<td>0.0</td>
<td>0.0</td>
</tr>
<tr>
<th>4</th>
<td>female</td>
<td>ARF/MOSF w/Sepsis</td>
<td>ARF/MOSF</td>
<td>NaN</td>
<td>white</td>
<td>no</td>
<td>79.88495</td>
<td>1</td>
<td>59.0</td>
<td>13.500000</td>
<td>...</td>
<td>NaN</td>
<td>NaN</td>
<td>0.799927</td>
<td>143.0</td>
<td>7.509766</td>
<td>NaN</td>
<td>NaN</td>
<td>NaN</td>
<td>NaN</td>
<td>2.0</td>
</tr>
</tbody>
</table>
<p>5 rows × 24 columns</p>
</div>
<div>
<style scoped>
.dataframe tbody tr th:only-of-type {
vertical-align: middle;
}
.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}
</style>
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>event</th>
<th>time</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>0</td>
<td>2029</td>
</tr>
<tr>
<th>1</th>
<td>1</td>
<td>4</td>
</tr>
<tr>
<th>2</th>
<td>1</td>
<td>47</td>
</tr>
<tr>
<th>3</th>
<td>1</td>
<td>133</td>
</tr>
<tr>
<th>4</th>
<td>0</td>
<td>2029</td>
</tr>
</tbody>
</table>
</div>
<a id="preprocess"></a>
### 1.2. Preprocess the Data
```python
import numpy as np
from sklearn.model_selection import train_test_split
# Split the SUPPORT data into training, validation, and test data
x_tr, x_te, y_tr, y_te = train_test_split(features, outcomes, test_size=0.2, random_state=1)
x_tr, x_val, y_tr, y_val = train_test_split(x_tr, y_tr, test_size=0.25, random_state=1)
print(f'Number of training data points: {len(x_tr)}')
print(f'Number of validation data points: {len(x_val)}')
print(f'Number of test data points: {len(x_te)}')
```
Number of training data points: 5463
Number of validation data points: 1821
Number of test data points: 1821
```python
from auton_survival.preprocessing import Preprocessor
# Fit the imputer and scaler to the training data and transform the training, validation and test data
preprocessor = Preprocessor(cat_feat_strat='ignore', num_feat_strat= 'mean')
transformer = preprocessor.fit(features, cat_feats=cat_feats, num_feats=num_feats,
one_hot=True, fill_value=-1)
x_tr = transformer.transform(x_tr)
x_val = transformer.transform(x_val)
x_te = transformer.transform(x_te)
```
<a id="cph"></a>
## 2. Cox Proportional Hazards (CPH)
<b>CPH</b> [2] model assumes that individuals across the population have constant proportional hazards overtime. In this model, the estimator of the survival function conditional on $X, S(·|X) , P(T > t|X)$, is assumed to have constant proportional hazard. Thus, the relative proportional hazard between individuals is constant across time.
*For full details on CPH, please refer to the following paper*:
[2] [Cox, D. R. (1972). Regression models and life-tables. Journal of the Royal Statistical Society: Series B (Methodological).](https://www.jstor.org/stable/2985181)
<a id="fitcph"></a>
### 2.1. Fit CPH Model
```python
from auton_survival.estimators import SurvivalModel
from auton_survival.metrics import survival_regression_metric
from sklearn.model_selection import ParameterGrid
# Define parameters for tuning the model
param_grid = {'l2' : [1e-3, 1e-4]}
params = ParameterGrid(param_grid)
# Define the times for tuning the model hyperparameters and for evaluating the model
times = np.quantile(y_tr['time'][y_tr['event']==1], np.linspace(0.1, 1, 10)).tolist()
# Perform hyperparameter tuning
models = []
for param in params:
model = SurvivalModel('cph', random_seed=2, l2=param['l2'])
# The fit method is called to train the model
model.fit(x_tr, y_tr)
# Obtain survival probabilities for validation set and compute the Integrated Brier Score
predictions_val = model.predict_survival(x_val, times)
metric_val = survival_regression_metric('ibs', y_tr, y_val, predictions_val, times)
models.append([metric_val, model])
# Select the best model based on the mean metric value computed for the validation set
metric_vals = [i[0] for i in models]
first_min_idx = metric_vals.index(min(metric_vals))
model = models[first_min_idx][1]
```
<a id="evalcph"></a>
### 2.2. Evaluate CPH Model
```python
from estimators_demo_utils import plot_performance_metrics
# Obtain survival probabilities for test set
predictions_te = model.predict_survival(x_te, times)
# Compute the Brier Score and time-dependent concordance index for the test set to assess model performance
results = dict()
results['Brier Score'] = survival_regression_metric('brs', outcomes_train=y_tr, outcomes_test=y_te,
predictions=predictions_te, times=times)
results['Concordance Index'] = survival_regression_metric('ctd', outcomes_train=y_tr, outcomes_test=y_te,
predictions=predictions_te, times=times)
plot_performance_metrics(results, times)
```
<a id="fsn"></a>
## 3. Deep Cox Proportional Hazards (DCPH)
<b>DCPH</b> [2], [3] is an extension to the CPH model. DCPH involves modeling the proportional hazard ratios over the individuals with Deep Neural Networks allowing the ability to learn non linear hazard ratios.
*For full details on DCPH models, Faraggi-Simon Net (FSN) and DeepSurv, please refer to the following papers*:
[2] [Faraggi, David, and Richard Simon. "A neural network model for survival data." Statistics in medicine 14.1 (1995): 73-82.](https://onlinelibrary.wiley.com/doi/abs/10.1002/sim.4780140108)
[3] [Katzman, Jared L., et al. "DeepSurv: personalized treatment recommender system using a Cox proportional hazards deep neural network." BMC medical research methodology 18.1 (2018): 1-12.](https://arxiv.org/abs/1606.00931v3)
<a id="fitfsn"></a>
### 3.1. Fit DCPH Model
```python
from auton_survival.estimators import SurvivalModel
from auton_survival.metrics import survival_regression_metric
from sklearn.model_selection import ParameterGrid
# Define parameters for tuning the model
param_grid = {'bs' : [100, 200],
'learning_rate' : [ 1e-4, 1e-3],
'layers' : [ [100], [100, 100] ]
}
params = ParameterGrid(param_grid)
# Define the times for tuning the model hyperparameters and for evaluating the model
times = np.quantile(y_tr['time'][y_tr['event']==1], np.linspace(0.1, 1, 10)).tolist()
# Perform hyperparameter tuning
models = []
for param in params:
model = SurvivalModel('dcph', random_seed=0, bs=param['bs'], learning_rate=param['learning_rate'], layers=param['layers'])
# The fit method is called to train the model
model.fit(x_tr, y_tr)
# Obtain survival probabilities for validation set and compute the Integrated Brier Score
predictions_val = model.predict_survival(x_val, times)
metric_val = survival_regression_metric('ibs', y_tr, y_val, predictions_val, times)
models.append([metric_val, model])
# Select the best model based on the mean metric value computed for the validation set
metric_vals = [i[0] for i in models]
first_min_idx = metric_vals.index(min(metric_vals))
model = models[first_min_idx][1]
```
100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████| 50/50 [00:03<00:00, 15.29it/s]
32%|███████████████████████████████████▌ | 16/50 [00:01<00:02, 12.67it/s]
64%|███████████████████████████████████████████████████████████████████████ | 32/50 [00:03<00:02, 8.56it/s]
20%|██████████████████████▏ | 10/50 [00:01<00:04, 8.21it/s]
100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████| 50/50 [00:02<00:00, 24.79it/s]
50%|███████████████████████████████████████████████████████▌ | 25/50 [00:01<00:01, 19.35it/s]
82%|███████████████████████████████████████████████████████████████████████████████████████████ | 41/50 [00:02<00:00, 16.10it/s]
16%|█████████████████▉ | 8/50 [00:00<00:03, 13.96it/s]
<a id="evalfsn"></a>
### 3.2. Evaluate DCPH Model
Compute the Brier Score and time-dependent concordance index for the test set. See notebook introduction for more details.
```python
from estimators_demo_utils import plot_performance_metrics
# Obtain survival probabilities for test set
predictions_te = model.predict_survival(x_te, times)
# Compute the Brier Score and time-dependent concordance index for the test set to assess model performance
results = dict()
results['Brier Score'] = survival_regression_metric('brs', outcomes_train=y_tr, outcomes_test=y_te,
predictions=predictions_te, times=times)
results['Concordance Index'] = survival_regression_metric('ctd', outcomes_train=y_tr, outcomes_test=y_te,
predictions=predictions_te, times=times)
plot_performance_metrics(results, times)
```
<a id="dsm"></a>
## 4. Deep Survival Machines (DSM)
<b>DSM</b> [5] is a fully parametric approach to modeling the event time distribution as a fixed size mixture over Weibull or Log-Normal distributions. The individual mixture distributions are parametrized with neural networks to learn complex non-linear representations of the data.
<b>Figure A:</b> DSM works by modeling the conditional distribution $P(T |X = x)$ as a mixture over $k$ well-defined, parametric distributions. DSM generates representation of the individual covariates, $x$, using a deep multilayer perceptron followed by a softmax over mixture size, $k$. This representation then interacts with the additional set of parameters, to determine the mixture weights $w$ and the parameters of each of $k$ underlying survival distributions $\{\eta_k, \beta_k\}^K_{k=1}$. The final individual survival distribution for the event time, $T$, is a weighted average over these $K$ distributions.
*For full details on Deep Survival Machines (DSM), please refer to the following paper*:
[5] [Chirag Nagpal, Xinyu Li, and Artur Dubrawski. Deep survival machines: Fully parametric survival regression and representation learning for censored data with competing risks. 2020.](https://arxiv.org/abs/2003.01176)
<a id="fitdsm"></a>
### 4.1. Fit DSM Model
```python
from auton_survival.estimators import SurvivalModel
from auton_survival.metrics import survival_regression_metric
from sklearn.model_selection import ParameterGrid
# Define parameters for tuning the model
param_grid = {'layers' : [[100], [100, 100], [200]],
'distribution' : ['Weibull', 'LogNormal'],
'max_features' : ['sqrt', 'log2']
}
params = ParameterGrid(param_grid)
# Define the times for tuning the model hyperparameters and for evaluating the model
times = np.quantile(y_tr['time'][y_tr['event']==1], np.linspace(0.1, 1, 10)).tolist()
# Perform hyperparameter tuning
models = []
for param in params:
model = SurvivalModel('dsm', random_seed=0, layers=param['layers'], distribution=param['distribution'], max_features=param['max_features'])
# The fit method is called to train the model
model.fit(x_tr, y_tr)
# Obtain survival probabilities for validation set and compute the Integrated Brier Score
predictions_val = model.predict_survival(x_val, times)
metric_val = survival_regression_metric('ibs', y_tr, y_val, predictions_val, times)
models.append([metric_val, model])
# Select the best model based on the mean metric value computed for the validation set
metric_vals = [i[0] for i in models]
first_min_idx = metric_vals.index(min(metric_vals))
model = models[first_min_idx][1]
```
18%|██████████████████▉ | 1799/10000 [00:04<00:20, 400.33it/s]
90%|████████████████████████████████████████████████████████████████████████████████████████████████████▊ | 9/10 [00:01<00:00, 5.31it/s]
18%|██████████████████▉ | 1799/10000 [00:04<00:22, 369.96it/s]
90%|████████████████████████████████████████████████████████████████████████████████████████████████████▊ | 9/10 [00:01<00:00, 4.96it/s]
18%|██████████████████▉ | 1799/10000 [00:05<00:23, 350.53it/s]
100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████| 10/10 [00:02<00:00, 4.25it/s]
18%|██████████████████▉ | 1799/10000 [00:04<00:21, 376.50it/s]
100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████| 10/10 [00:02<00:00, 4.96it/s]
18%|██████████████████▉ | 1799/10000 [00:04<00:22, 364.78it/s]
90%|████████████████████████████████████████████████████████████████████████████████████████████████████▊ | 9/10 [00:02<00:00, 4.01it/s]
18%|██████████████████▉ | 1799/10000 [00:05<00:24, 340.31it/s]
90%|████████████████████████████████████████████████████████████████████████████████████████████████████▊ | 9/10 [00:01<00:00, 4.63it/s]
12%|████████████▊ | 1224/10000 [00:03<00:21, 399.50it/s]
100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████| 10/10 [00:01<00:00, 5.22it/s]
12%|████████████▊ | 1224/10000 [00:03<00:22, 393.39it/s]
100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████| 10/10 [00:01<00:00, 5.22it/s]
12%|████████████▊ | 1224/10000 [00:03<00:23, 368.06it/s]
100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████| 10/10 [00:02<00:00, 4.61it/s]
12%|████████████▊ | 1224/10000 [00:03<00:23, 372.02it/s]
100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████| 10/10 [00:02<00:00, 4.72it/s]
12%|████████████▊ | 1224/10000 [00:02<00:16, 516.68it/s]
100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████| 10/10 [00:01<00:00, 5.32it/s]
12%|████████████▊ | 1224/10000 [00:03<00:22, 391.68it/s]
100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████| 10/10 [00:01<00:00, 5.24it/s]
<a id="evaldsm"></a>
### 4.2. Evaluate DSM Model
Compute the Brier Score and time-dependent concordance index for the test set. See notebook introduction for more details.
```python
from estimators_demo_utils import plot_performance_metrics
# Obtain survival probabilities for test set
predictions_te = model.predict_survival(x_te, times)
# Compute the Brier Score and time-dependent concordance index for the test set to assess model performance
results = dict()
results['Brier Score'] = survival_regression_metric('brs', outcomes_train=y_tr, outcomes_test=y_te,
predictions=predictions_te, times=times)
results['Concordance Index'] = survival_regression_metric('ctd', outcomes_train=y_tr, outcomes_test=y_te,
predictions=predictions_te, times=times)
plot_performance_metrics(results, times)
```
<a id="dcm"></a>
## 5. Deep Cox Mixtures (DCM)
<b>DCM</b> [2] generalizes the proportional hazards assumption via a mixture model, by assuming that there are latent groups and within each, the proportional hazards assumption holds. DCM allows the hazard ratio in each latent group, as well as the latent group membership, to be flexibly modeled by a deep neural network.
<b>Figure B:</b> DCM works by generating representation of the individual covariates, $x$, using an encoding neural network. The output representation, $xe$, then interacts with linear functions, $f$ and $g$, that determine the proportional hazards within each cluster $Z ∈ {1, 2, ...K}$ and the mixing weights $P(Z|X)$ respectively. For each cluster, baseline survival rates $Sk(t)$ are estimated non-parametrically. The final individual survival curve $S(t|x)$ is an average over the cluster specific individual survival curves weighted by the mixing probabilities $P(Z|X = x)$.
*For full details on Deep Cox Mixtures (DCM), please refer to the following paper*:
[2] [Nagpal, C., Yadlowsky, S., Rostamzadeh, N., and Heller, K. (2021c). Deep cox mixtures for survival regression. In
Machine Learning for Healthcare Conference, pages 674–708. PMLR.](https://arxiv.org/abs/2101.06536)
<a id="fitdcm"></a>
### 5.1. Fit DCM Model
```python
from auton_survival.estimators import SurvivalModel
from auton_survival.metrics import survival_regression_metric
from sklearn.model_selection import ParameterGrid
# Define parameters for tuning the model
param_grid = {'k' : [2, 3],
'learning_rate' : [1e-3, 1e-4],
'layers' : [[100], [100, 100]]
}
params = ParameterGrid(param_grid)
# Define the times for tuning the model hyperparameters and for evaluating the model
times = np.quantile(y_tr['time'][y_tr['event']==1], np.linspace(0.1, 1, 10)).tolist()
# Perform hyperparameter tuning
models = []
for param in params:
model = SurvivalModel('dcm', random_seed=7, k=param['k'], learning_rate=param['learning_rate'], layers=param['layers'])
# The fit method is called to train the model
model.fit(x_tr, y_tr)
# Obtain survival probabilities for validation set and compute the Integrated Brier Score
predictions_val = model.predict_survival(x_val, times)
metric_val = survival_regression_metric('ibs', y_tr, y_val, predictions_val, times)
models.append([metric_val, model])
# Select the best model based on the mean metric value computed for the validation set
metric_vals = [i[0] for i in models]
first_min_idx = metric_vals.index(min(metric_vals))
model = models[first_min_idx][1]
```
0%| | 0/50 [00:00<?, ?it/s]C:\Users\Willa Potosnak\OneDrive\Documents\CMU Research\CMU_Projects\auton-survival\examples\..\auton_survival\models\dcm\dcm_utilities.py:105: RuntimeWarning: invalid value encountered in log
probs = gates+np.log(event_probs)
14%|███████████████▋ | 7/50 [00:02<00:14, 3.04it/s]C:\Users\Willa Potosnak\OneDrive\Documents\CMU Research\CMU_Projects\auton-survival\examples\..\auton_survival\models\dcm\dcm_utilities.py:105: RuntimeWarning: divide by zero encountered in log
probs = gates+np.log(event_probs)
32%|███████████████████████████████████▌ | 16/50 [00:05<00:12, 2.75it/s]C:\Users\Willa Potosnak\OneDrive\Documents\CMU Research\CMU_Projects\auton-survival\examples\..\auton_survival\models\dcm\dcm_utilities.py:58: RuntimeWarning: invalid value encountered in power
return spl(ts)**risks
C:\Users\Willa Potosnak\OneDrive\Documents\CMU Research\CMU_Projects\auton-survival\examples\..\auton_survival\models\dcm\dcm_utilities.py:53: RuntimeWarning: invalid value encountered in power
s0ts = (-risks)*(spl(ts)**(risks-1))
34%|█████████████████████████████████████▋ | 17/50 [00:06<00:12, 2.64it/s]
0%| | 0/50 [00:00<?, ?it/s]C:\Users\Willa Potosnak\OneDrive\Documents\CMU Research\CMU_Projects\auton-survival\examples\..\auton_survival\models\dcm\dcm_utilities.py:105: RuntimeWarning: invalid value encountered in log
probs = gates+np.log(event_probs)
14%|███████████████▋ | 7/50 [00:02<00:14, 3.02it/s]C:\Users\Willa Potosnak\OneDrive\Documents\CMU Research\CMU_Projects\auton-survival\examples\..\auton_survival\models\dcm\dcm_utilities.py:105: RuntimeWarning: divide by zero encountered in log
probs = gates+np.log(event_probs)
72%|███████████████████████████████████████████████████████████████████████████████▉ | 36/50 [00:12<00:04, 2.90it/s]
0%| | 0/50 [00:00<?, ?it/s]C:\Users\Willa Potosnak\OneDrive\Documents\CMU Research\CMU_Projects\auton-survival\examples\..\auton_survival\models\dcm\dcm_utilities.py:105: RuntimeWarning: invalid value encountered in log
probs = gates+np.log(event_probs)
6%|██████▋ | 3/50 [00:01<00:19, 2.41it/s]C:\Users\Willa Potosnak\OneDrive\Documents\CMU Research\CMU_Projects\auton-survival\examples\..\auton_survival\models\dcm\dcm_utilities.py:105: RuntimeWarning: divide by zero encountered in log
probs = gates+np.log(event_probs)
54%|███████████████████████████████████████████████████████████▉ | 27/50 [00:12<00:10, 2.18it/s]
0%| | 0/50 [00:00<?, ?it/s]C:\Users\Willa Potosnak\OneDrive\Documents\CMU Research\CMU_Projects\auton-survival\examples\..\auton_survival\models\dcm\dcm_utilities.py:105: RuntimeWarning: invalid value encountered in log
probs = gates+np.log(event_probs)
30%|█████████████████████████████████▎ | 15/50 [00:06<00:15, 2.22it/s]C:\Users\Willa Potosnak\OneDrive\Documents\CMU Research\CMU_Projects\auton-survival\examples\..\auton_survival\models\dcm\dcm_utilities.py:105: RuntimeWarning: divide by zero encountered in log
probs = gates+np.log(event_probs)
100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████| 50/50 [00:22<00:00, 2.27it/s]
0%| | 0/50 [00:00<?, ?it/s]C:\Users\Willa Potosnak\OneDrive\Documents\CMU Research\CMU_Projects\auton-survival\examples\..\auton_survival\models\dcm\dcm_utilities.py:105: RuntimeWarning: invalid value encountered in log
probs = gates+np.log(event_probs)
6%|██████▋ | 3/50 [00:01<00:21, 2.20it/s]C:\Users\Willa Potosnak\OneDrive\Documents\CMU Research\CMU_Projects\auton-survival\examples\..\auton_survival\models\dcm\dcm_utilities.py:105: RuntimeWarning: divide by zero encountered in log
probs = gates+np.log(event_probs)
52%|█████████████████████████████████████████████████████████▋ | 26/50 [00:11<00:10, 2.26it/s]C:\Users\Willa Potosnak\OneDrive\Documents\CMU Research\CMU_Projects\auton-survival\examples\..\auton_survival\models\dcm\dcm_utilities.py:58: RuntimeWarning: invalid value encountered in power
return spl(ts)**risks
C:\Users\Willa Potosnak\OneDrive\Documents\CMU Research\CMU_Projects\auton-survival\examples\..\auton_survival\models\dcm\dcm_utilities.py:53: RuntimeWarning: invalid value encountered in power
s0ts = (-risks)*(spl(ts)**(risks-1))
70%|█████████████████████████████████████████████████████████████████████████████▋ | 35/50 [00:15<00:06, 2.21it/s]
0%| | 0/50 [00:00<?, ?it/s]C:\Users\Willa Potosnak\OneDrive\Documents\CMU Research\CMU_Projects\auton-survival\examples\..\auton_survival\models\dcm\dcm_utilities.py:105: RuntimeWarning: invalid value encountered in log
probs = gates+np.log(event_probs)
4%|████▍ | 2/50 [00:00<00:15, 3.03it/s]C:\Users\Willa Potosnak\OneDrive\Documents\CMU Research\CMU_Projects\auton-survival\examples\..\auton_survival\models\dcm\dcm_utilities.py:105: RuntimeWarning: divide by zero encountered in log
probs = gates+np.log(event_probs)
72%|███████████████████████████████████████████████████████████████████████████████▉ | 36/50 [00:15<00:07, 1.84it/s]C:\Users\Willa Potosnak\OneDrive\Documents\CMU Research\CMU_Projects\auton-survival\examples\..\auton_survival\models\dcm\dcm_utilities.py:58: RuntimeWarning: invalid value encountered in power
return spl(ts)**risks
C:\Users\Willa Potosnak\OneDrive\Documents\CMU Research\CMU_Projects\auton-survival\examples\..\auton_survival\models\dcm\dcm_utilities.py:53: RuntimeWarning: invalid value encountered in power
s0ts = (-risks)*(spl(ts)**(risks-1))
100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████| 50/50 [00:23<00:00, 2.17it/s]
0%| | 0/50 [00:00<?, ?it/s]C:\Users\Willa Potosnak\OneDrive\Documents\CMU Research\CMU_Projects\auton-survival\examples\..\auton_survival\models\dcm\dcm_utilities.py:105: RuntimeWarning: invalid value encountered in log
probs = gates+np.log(event_probs)
2%|██▏ | 1/50 [00:00<00:27, 1.78it/s]C:\Users\Willa Potosnak\OneDrive\Documents\CMU Research\CMU_Projects\auton-survival\examples\..\auton_survival\models\dcm\dcm_utilities.py:105: RuntimeWarning: divide by zero encountered in log
probs = gates+np.log(event_probs)
78%|██████████████████████████████████████████████████████████████████████████████████████▌ | 39/50 [00:20<00:05, 1.91it/s]
0%| | 0/50 [00:00<?, ?it/s]C:\Users\Willa Potosnak\OneDrive\Documents\CMU Research\CMU_Projects\auton-survival\examples\..\auton_survival\models\dcm\dcm_utilities.py:105: RuntimeWarning: invalid value encountered in log
probs = gates+np.log(event_probs)
20%|██████████████████████▏ | 10/50 [00:04<00:21, 1.83it/s]C:\Users\Willa Potosnak\OneDrive\Documents\CMU Research\CMU_Projects\auton-survival\examples\..\auton_survival\models\dcm\dcm_utilities.py:105: RuntimeWarning: divide by zero encountered in log
probs = gates+np.log(event_probs)
100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████| 50/50 [00:22<00:00, 2.27it/s]
<a id="evaldcm"></a>
### 5.2. Evaluate DCM Model
Compute the Brier Score and time-dependent concordance index for the test set. See notebook introduction for more details.
```python
from estimators_demo_utils import plot_performance_metrics
# Obtain survival probabilities for test set
predictions_te = model.predict_survival(x_te, times)
# Compute the Brier Score and time-dependent concordance index for the test set to assess model performance
results = dict()
results['Brier Score'] = survival_regression_metric('brs', outcomes_train=y_tr, outcomes_test=y_te,
predictions=predictions_te, times=times)
results['Concordance Index'] = survival_regression_metric('ctd', outcomes_train=y_tr, outcomes_test=y_te,
predictions=predictions_te, times=times)
plot_performance_metrics(results, times)
```
<a id="rsf"></a>
## 6. Random Survival Forests (RSF)
<b>RSF</b> [4] is an extension of Random Forests to the survival settings where risk scores are computed by creating Nelson-Aalen estimators in the splits induced by the Random Forest.
We observe that performance of the Random Survival Forest model, especially in terms of calibration is strongly influenced by the choice for the hyperparameters for the number of features considered at each split and the minimum number of data samples to continue growing a tree. We thus advise carefully tuning these hyper-parameters while benchmarking RSF.
*For full details on Random Survival Forests (RSF), please refer to the following paper*:
[4] [Hemant Ishwaran et al. Random survival forests. The annals of applied statistics, 2(3):841–860, 2008.](https://arxiv.org/abs/0811.1645)
<a id="fitrsf"></a>
### 6.1. Fit RSF Model
```python
from auton_survival.estimators import SurvivalModel
from auton_survival.metrics import survival_regression_metric
from sklearn.model_selection import ParameterGrid
# Define parameters for tuning the model
param_grid = {'n_estimators' : [100, 300],
'max_depth' : [3, 5],
'max_features' : ['sqrt', 'log2']
}
params = ParameterGrid(param_grid)
# Define the times for tuning the model hyperparameters and for evaluating the model
times = np.quantile(y_tr['time'][y_tr['event']==1], np.linspace(0.1, 1, 10)).tolist()
# Perform hyperparameter tuning
models = []
for param in params:
model = SurvivalModel('rsf', random_seed=8, n_estimators=param['n_estimators'], max_depth=param['max_depth'], max_features=param['max_features'])
# The fit method is called to train the model
model.fit(x_tr, y_tr)
# Obtain survival probabilities for validation set and compute the Integrated Brier Score
predictions_val = model.predict_survival(x_val, times)
metric_val = survival_regression_metric('ibs', y_tr, y_val, predictions_val, times)
models.append([metric_val, model])
# Select the best model based on the mean metric value computed for the validation set
metric_vals = [i[0] for i in models]
first_min_idx = metric_vals.index(min(metric_vals))
model = models[first_min_idx][1]
```
<a id="evalrsf"></a>
### 6.2. Evaluate RSF Model
Compute the Brier Score and time-dependent concordance index for the test set. See notebook introduction for more details.
```python
from estimators_demo_utils import plot_performance_metrics
# Obtain survival probabilities for test set
predictions_te = model.predict_survival(x_te, times)
# Compute the Brier Score and time-dependent concordance index for the test set to assess model performance
results = dict()
results['Brier Score'] = survival_regression_metric('brs', outcomes_train=y_tr, outcomes_test=y_te,
predictions=predictions_te, times=times)
results['Concordance Index'] = survival_regression_metric('ctd', outcomes_train=y_tr, outcomes_test=y_te,
predictions=predictions_te, times=times)
plot_performance_metrics(results, times)
```
```python
```
|
"""Position and Quaternion orientation math"""
import math
import cgtypes # cgkit 1.x
import numpy as nx
import numpy as np
import numpy
import time
nan = nx.nan
class NoIndexChangedClass:
pass
no_index_changed = NoIndexChangedClass()
L_i = nx.array([0,0,0,1,3,2])
L_j = nx.array([1,2,3,2,1,3])
def Lmatrix2Lcoords(Lmatrix):
return Lmatrix[L_i,L_j]
#pluecker_to_orient is flydra_core.reconstruct.line_direction
def pluecker_to_quat(line3d):
'''cannot set roll angle'''
import flydra_core.reconstruct
orient = flydra_core.reconstruct.line_direction(line3d)
return orientation_to_quat(orient)
def pluecker_from_verts(A,B):
if len(A)==3:
A = A[0], A[1], A[2], 1.0
if len(B)==3:
B = B[0], B[1], B[2], 1.0
A=nx.reshape(A,(4,1))
B=nx.reshape(B,(4,1))
L = nx.matrixmultiply(A,nx.transpose(B)) - nx.matrixmultiply(B,nx.transpose(A))
return Lmatrix2Lcoords(L)
def norm_vec(V):
Va = nx.asarray(V)
if len(Va.shape)==1:
# vector
U = Va/math.sqrt(Va[0]**2 + Va[1]**2 + Va[2]**2) # normalize
else:
assert Va.shape[1] == 3
Vamags = nx.sqrt(Va[:,0]**2 + Va[:,1]**2 + Va[:,2]**2)
U = Va/Vamags[:,nx.newaxis]
return U
def rotate_velocity_by_orientation(vel,orient):
# this is backwards from a normal quaternion rotation
return orient.inverse()*vel*orient
def is_unit_vector(U,eps=1e-10):
V = nx.asarray(U)
Visdim1=False
if len(V.shape)==1:
V = V[nx.newaxis,:]
Visdim1=True
V = V**2
mag = nx.sqrt(nx.sum(V,axis=1))
result = abs(mag-1.0) < eps
# consider nans to be unit vectors
if Visdim1:
if np.isnan(mag[0]):
result = True
else:
result[ np.isnan(mag) ] = True
return result
def world2body( U, roll_angle = 0 ):
"""convert world coordinates to body-relative coordinates
inputs:
U is a unit vector indicating directon of body long axis
roll_angle is the roll angle (in radians)
output:
M (3x3 matrix), get world coords via nx.dot(M,X)
"""
assert is_unit_vector(U)
# notation from Wagner, 1986a, Appendix 1
Bxy = math.atan2( U[1], U[0] ) # heading angle
Bxz = math.asin( U[2] ) # pitch (body) angle
Byz = roll_angle # roll angle
cos = math.cos
sin = math.sin
M = nx.array( (( cos(Bxy)*cos(-Bxz), sin(Bxy)*cos(-Bxz), -sin(-Bxz)),
( cos(Bxy)*sin(-Bxz)*sin(Byz) - sin(Bxy)*cos(Byz), sin(Bxy)*sin(-Bxz)*sin(Byz) + cos(Bxy)*cos(Byz), cos(-Bxz)*sin(Byz)),
( cos(Bxy)*sin(-Bxz)*cos(Byz) + sin(Bxy)*sin(Byz), sin(Bxy)*sin(-Bxz)*cos(Byz) - cos(Bxy)*sin(Byz), cos(-Bxz)*cos(Byz))))
return M
def cross(vec1,vec2):
return ( vec1[1]*vec2[2] - vec1[2]*vec2[1],
vec1[2]*vec2[0] - vec1[0]*vec2[2],
vec1[0]*vec2[1] - vec1[1]*vec2[0] )
def make_quat(angle_radians, axis_of_rotation):
half_angle = angle_radians/2.0
a = math.cos(half_angle)
b,c,d = math.sin(half_angle)*norm_vec(axis_of_rotation)
return cgtypes.quat(a,b,c,d)
def euler_to_orientation( yaw=0.0, pitch = 0.0 ):
"""convert euler angles into orientation vector"""
z = math.sin( pitch )
xyr = math.cos( pitch )
y = xyr*math.sin( yaw )
x = xyr*math.cos( yaw )
return x, y, z
def test_euler_to_orientation():
xyz = euler_to_orientation(0,0)
assert np.allclose( xyz, (1.0, 0.0, 0.0))
xyz = euler_to_orientation(math.pi,0)
assert np.allclose( xyz, (-1.0, 1.2246063538223773e-16, 0.0))
xyz = euler_to_orientation(math.pi,math.pi/2)
assert np.allclose( xyz, (-6.1230317691118863e-17, 7.4983036091106872e-33, 1.0))
xyz = euler_to_orientation(math.pi,-math.pi/2)
assert np.allclose( xyz, (-6.1230317691118863e-17, 7.4983036091106872e-33, -1.0))
xyz = euler_to_orientation(math.pi,-math.pi/4)
assert np.allclose( xyz, (-0.70710678118654757, 8.6592745707193554e-17, -0.70710678118654746))
xyz = euler_to_orientation(math.pi/2,-math.pi/4)
assert np.allclose( xyz, (4.3296372853596777e-17, 0.70710678118654757, -0.70710678118654746))
def euler_to_quat(roll=0.0,pitch=0.0,yaw=0.0):
# see http://www.euclideanspace.com/maths/geometry/rotations/conversions/eulerToQuaternion/index.htm
# Supposedly the order is heading first, then attitude, the bank.
heading = yaw
attitude = pitch
bank = roll
c1 = math.cos(heading/2);
s1 = math.sin(heading/2);
c2 = math.cos(attitude/2);
s2 = math.sin(attitude/2);
c3 = math.cos(bank/2);
s3 = math.sin(bank/2);
c1c2 = c1*c2;
s1s2 = s1*s2;
w =c1c2*c3 - s1s2*s3;
x =c1c2*s3 + s1s2*c3;
y =s1*c2*c3 + c1*s2*s3;
z =c1*s2*c3 - s1*c2*s3;
z, y = y, -z
return cgtypes.quat(w,x,y,z)
## a,b,c=roll,-pitch,yaw
## Qx = cgtypes.quat( math.cos(a/2.0), math.sin(a/2.0), 0, 0 )
## Qy = cgtypes.quat( math.cos(b/2.0), 0, math.sin(b/2.0), 0 )
## Qz = cgtypes.quat( math.cos(c/2.0), 0, 0, math.sin(c/2.0) )
## return Qx*Qy*Qz
def orientation_to_euler( U ):
"""
convert orientation to euler angles (in radians)
results are yaw, pitch (no roll is provided)
>>> print orientation_to_euler( (1, 0, 0) )
(0.0, 0.0)
>>> print orientation_to_euler( (0, 1, 0) )
(1.5707963267948966, 0.0)
>>> print orientation_to_euler( (-1, 0, 0) )
(3.141592653589793, 0.0)
>>> print orientation_to_euler( (0, -1, 0) )
(-1.5707963267948966, 0.0)
>>> print orientation_to_euler( (0, 0, 1) )
(0.0, 1.5707963267948966)
>>> print orientation_to_euler( (0, 0, -1) )
(0.0, -1.5707963267948966)
>>> print orientation_to_euler( (0,0,0) ) # This is not a unit vector.
Traceback (most recent call last):
...
AssertionError
>>> r1=math.sqrt(2)/2
>>> print math.pi/4
0.785398163397
>>> print orientation_to_euler( (r1,0,r1) )
(0.0, 0.7853981633974483)
>>> print orientation_to_euler( (r1,r1,0) )
(0.7853981633974483, 0.0)
"""
if numpy.isnan(U[0]):
return (nan,nan)
assert is_unit_vector(U)
yaw = math.atan2( U[1],U[0] )
xy_r = math.sqrt(U[0]**2+U[1]**2)
pitch = math.atan2( U[2], xy_r )
return yaw, pitch
def orientation_to_quat( U, roll_angle=0, force_pitch_0=False ):
"""convert world coordinates to body-relative coordinates
inputs:
U is a unit vector indicating directon of body long axis
roll_angle is the roll angle (in radians)
output:
quaternion (4 tuple)
"""
if roll_angle != 0:
# I presume this has an effect on the b component of the quaternion
raise NotImplementedError('')
#if type(U) == nx.NumArray and len(U.shape)==2: # array of vectors
if 0:
result = QuatSeq()
for u in U:
if numpy.isnan(u[0]):
result.append( cgtypes.quat((nan,nan,nan,nan)))
else:
yaw, pitch = orientation_to_euler( u )
result.append( euler_to_quat(yaw=yaw, pitch=pitch, roll=roll_angle))
return result
else:
if numpy.isnan(U[0]):
return cgtypes.quat((nan,nan,nan,nan))
yaw, pitch = orientation_to_euler( U )
if force_pitch_0:
pitch=0
return euler_to_quat(yaw=yaw, pitch=pitch, roll=roll_angle)
def quat_to_orient(S3):
"""returns x, y, z for unit quaternions
Parameters
----------
S3 : {quaternion, QuatSeq instance}
The quaternion or sequence of quaternions to transform into an
orientation vector.
Returns
-------
orient : {tuple, ndarray}
If the input was a single quaternion, the output is (x,y,z). If
the input was a QuatSeq instance of length N, the output is an
ndarray of shape (N,3).
"""
u = cgtypes.quat(0,1,0,0)
if type(S3)()==QuatSeq(): # XXX isinstance(S3,QuatSeq)
V = [q*u*q.inverse() for q in S3]
return nx.array([(v.x, v.y, v.z) for v in V])
else:
V=S3*u*S3.inverse()
return V.x, V.y, V.z
def quat_to_euler(q):
"""returns yaw, pitch, roll
at singularities (north and south pole), assumes roll = 0
"""
# See http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToEuler/
eps=1e-14
qw = q.w; qx = q.x; qy = q.z; qz = -q.y
pitch_y = 2*qx*qy + 2*qz*qw
if pitch_y > (1.0-eps): # north pole]
yaw = 2*math.atan2( qx, qw)
pitch = math.asin(1.0)
roll = 0.0
elif pitch_y < -(1.0-eps): # south pole
yaw = -2*math.atan2( qx, qw)
pitch = math.asin(-1.0)
roll = 0.0
else:
yaw = math.atan2(2*qy*qw-2*qx*qz , 1 - 2*qy**2 - 2*qz**2)
pitch = math.asin(pitch_y)
roll = math.atan2(2*qx*qw-2*qy*qz , 1 - 2*qx**2 - 2*qz**2)
return yaw, pitch, roll
def quat_to_absroll(q):
qw = q.w; qx = q.x; qy = q.z; qz = -q.y
roll = math.atan2(2*qx*qw-2*qy*qz , 1 - 2*qx**2 - 2*qz**2)
return abs(roll)
class ObjectiveFunctionPosition:
"""methods from Kim, Hsieh, Wang, Wang, Fang, Woo"""
def __init__(self, p, h, alpha, no_distance_penalty_idxs=None):
"""
no_distance_penalty_idxs -- indexes into p where fit data
should not be penalized (probably because 'original data'
was interpolated and is of no value)
"""
self.p = p
self.h = h
self.alpha = alpha
self.p_err_weights = nx.ones( (len(p),) )
if no_distance_penalty_idxs is not None:
for i in no_distance_penalty_idxs:
self.p_err_weights[i] = 0
def _getDistance(self, ps):
result = nx.sum(self.p_err_weights*nx.sum((self.p - ps)**2, axis=1))
assert not np.isnan(result)
return result
def _getEnergy(self, ps):
d2p = (ps[2:] - 2*ps[1:-1] + ps[:-2]) / (self.h**2)
return nx.sum( nx.sum(d2p**2,axis=1))
def eval(self,ps):
D = self._getDistance(ps)
E = self._getEnergy(ps)
return D + self.alpha*E # eqn. 22
def get_del_F(self,P):
class PDfinder:
def __init__(self,objective_function,P):
self.objective_function = objective_function
self.P = P
self.F_P = self.objective_function.eval(P)
self.ndims = P.shape[1]
def eval_pd(self,i):
# evaluate 3 values (perturbations in x,y,z directions)
PERTURB = 1e-6 # perturbation amount (in meters)
dFdP = []
for j in range(self.ndims):
P_i_j = self.P[i,j]
# temporarily perturb P_i
self.P[i,j] = P_i_j+PERTURB
F_Pj = self.objective_function.eval(P)
self.P[i,j] = P_i_j
dFdP.append( (F_Pj-self.F_P)/PERTURB )
return dFdP
_pd_finder = PDfinder(self,P)
PDs = nx.array([ _pd_finder.eval_pd(i) for i in range(len(P)) ])
return PDs
def smooth_position( P, delta_t, alpha, lmbda, eps, verbose=False ):
"""smooth a sequence of positions
see the following citation for details:
"Noise Smoothing for VR Equipment in Quaternions," C.C. Hsieh,
Y.C. Fang, M.E. Wang, C.K. Wang, M.J. Kim, S.Y. Shin, and
T.C. Woo, IIE Transactions, vol. 30, no. 7, pp. 581-587, 1998
P are the positions as in an n x m array, where n is the number of
data points and m is the number of dimensions in which the data is
measured.
inputs
------
P positions (m by n array, m = number of samples, n = dimensionality)
delta_t temporal interval, in seconds, between samples
alpha relative importance of acceleration versus position
lmbda step size when descending gradient
eps termination criterion
output
------
Pstar smoothed positions (same format as P)
"""
h = delta_t
Pstar = P
err = 2*eps # cycle at least once
of = ObjectiveFunctionPosition(P,h,alpha)
while err > eps:
del_F = of.get_del_F(Pstar)
err = nx.sum( nx.sum( del_F**2 ) )
Pstar = Pstar - lmbda*del_F
if verbose:
print 'err %g (eps %g)'%(err,eps)
return Pstar
class QuatSeq(list):
def __abs__(self):
return nx.array([ abs(q) for q in self ])
def __add__(self,other):
if isinstance(other,QuatSeq):
assert len(self) == len(other)
return QuatSeq([ p+q for p,q in zip(self,other) ])
else:
raise ValueError('only know how to add QuatSeq with QuatSeq')
def __sub__(self,other):
if isinstance(other,QuatSeq):
assert len(self) == len(other)
return QuatSeq([ p-q for p,q in zip(self,other) ])
else:
raise ValueError('only know how to subtract QuatSeq with QuatSeq')
def __mul__(self,other):
if isinstance(other,QuatSeq):
assert len(self) == len(other)
return QuatSeq([ p*q for p,q in zip(self,other) ])
elif hasattr(other,'shape'): # ndarray
assert len(other.shape)==2
if other.shape[1] == 3:
other = nx.concatenate( (nx.zeros((other.shape[0],1)),
other), axis=1 )
assert other.shape[1] == 4
other = QuatSeq([cgtypes.quat(o) for o in other])
return self*other
else:
try:
other = float(other)
except (ValueError, TypeError):
raise TypeError('only know how to multiply QuatSeq with QuatSeq, n*3 array or float')
return QuatSeq([ p*other for p in self])
def copy(self):
"""return a deep copy of self"""
return QuatSeq([cgtypes.quat(q) for q in self])
def __div__(self,other):
try:
other = float(other)
except ValueError:
raise ValueError('only know how to divide QuatSeq with floats')
return QuatSeq([ p/other for p in self])
def __pow__(self,n):
return QuatSeq([ q**n for q in self ])
def __neg__(self):
return QuatSeq([ -q for q in self ])
def __str__(self):
return 'QuatSeq('+list.__str__(self)+')'
def __repr__(self):
return 'QuatSeq('+list.__repr__(self)+')'
def inverse(self):
return QuatSeq([ q.inverse() for q in self ])
def exp(self):
return QuatSeq([ q.exp() for q in self ])
def log(self):
return QuatSeq([ q.log() for q in self ])
def __getslice__(self,*args,**kw):
return QuatSeq( list.__getslice__(self,*args,**kw) )
def get_w(self):
return nx.array([ q.w for q in self])
w = property(get_w)
def get_x(self):
return nx.array([ q.x for q in self])
x = property(get_x)
def get_y(self):
return nx.array([ q.y for q in self])
y = property(get_y)
def get_z(self):
return nx.array([ q.z for q in self])
z = property(get_z)
def to_numpy(self):
return numpy.vstack( (self.w, self.x, self.y, self.z) )
def _calc_idxs_and_fixup_q(no_distance_penalty_idxs,q):
valid_cond = None
if no_distance_penalty_idxs is not None:
valid_cond = np.ones( len(q),dtype=np.bool )
for i in no_distance_penalty_idxs:
valid_cond[i] = 0
# Set missing quaternion to some arbitrary value. The
# _getEnergy() cost term should push it around to
# minimize accelerations and it won't get counted in
# the distance penalty.
q[i] = cgtypes.quat(1,0,0,0)
else:
no_distance_penalty_idxs = []
for i,qi in enumerate(q):
if numpy.any(numpy.isnan([qi.w,qi.x,qi.y,qi.z])):
if not i in no_distance_penalty_idxs:
raise ValueError("you are passing data with 'nan' "
"values, but have not set the "
"no_distance_penalty_idxs argument")
return valid_cond, no_distance_penalty_idxs, q
class ObjectiveFunctionQuats(object):
"""methods from Kim, Hsieh, Wang, Wang, Fang, Woo"""
def __init__(self, q, h, beta, gamma,
ignore_direction_sign=False,
no_distance_penalty_idxs=None):
"""
parameters
==========
ignore_direction_sign - on each timestep, the distance term
for each orientation will be the smallest of 2 possibilities:
co-directional and anti-directional with the original
direction vector. Note that this may make the derivative
non-continuous and hence the entire operation unstable.
"""
q = q.copy() # make copy so we don't screw up original below
(self.valid_cond, no_distance_penalty_idxs, q) = _calc_idxs_and_fixup_q(no_distance_penalty_idxs,q)
if 1:
if 0:
# XXX this hasn't been tested in a long time...
# convert back and forth from orientation to eliminate roll
#ori = quat_to_orient(self.q)
#no_roll_quat = orientation_to_quat(quat_to_orient(self.q))
self.q_inverse = orientation_to_quat(quat_to_orient(self.q)).inverse()
else:
self.qorients = quat_to_orient(q)
else:
self.q_inverse = q.inverse()
self.h = h
self.h2 = self.h**2
self.beta = beta
self.gamma = gamma
self.no_distance_penalty_idxs = no_distance_penalty_idxs
self.ignore_direction_sign = ignore_direction_sign
def _getDistance(self, qs,changed_idx=None):
# This distance function is independent of "roll" angle, and
# thus doesn't penalize changes in roll.
if 0:
# XXX this hasn't been tested in a long time...
if 0:
# convert back and forth from orientation to eliminate roll
qs = orientation_to_quat(quat_to_orient(qs))
return sum( (abs( (self.q_inverse * qs).log() )**2))
else:
# test distance of orientations in R3 (L2 norm)
qtest_orients = quat_to_orient(qs)
if self.ignore_direction_sign:
# test both directions, take the minimum distance
L2dist1 = nx.sum((qtest_orients-self.qorients)**2,axis=1)
L2dist2 = nx.sum((qtest_orients+self.qorients)**2,axis=1)
L2dist = np.min( L2dist1, L2dist2, axis=1 )
else:
L2dist = nx.sum((qtest_orients-self.qorients)**2,axis=1)
result = nx.sum(L2dist[self.valid_cond])
assert not np.isnan(result)
return result
def _getRoll(self, qs,changed_idx=None):
return sum([quat_to_absroll(q) for q in qs])
def _getEnergy(self, qs,changed_idx=None):
# We do not hide values at no_distance_penalty_idxs here
# because we want qs to be any value -- that's the point. (Not
# a good idea to set to nan.)
omega_dot = ((qs[1:-1].inverse()*qs[2:]).log() -
(qs[:-2].inverse()*qs[1:-1]).log()) / self.h2
result = nx.sum( abs( omega_dot )**2 )
assert not np.isnan(result)
return result
def eval(self,qs,changed_idx=None):
D = self._getDistance(qs,changed_idx=changed_idx)
E = self._getEnergy(qs,changed_idx=changed_idx)
if self.gamma == 0:
return D + self.beta*E # eqn. 23
R = self._getRoll(qs,changed_idx=changed_idx)
return D + self.beta*E + self.gamma*R # eqn. 23
def get_del_G(self,Q):
class PDfinder:
"""partial derivative finder"""
def __init__(self,objective_function,Q,no_distance_penalty_idxs=None):
if no_distance_penalty_idxs is None:
self.no_distance_penalty_idxs = []
else:
self.no_distance_penalty_idxs = no_distance_penalty_idxs
self.objective_function = objective_function
self.Q = Q
# G evaluated at Q
self.G_Q = self.objective_function.eval(Q,
changed_idx=no_index_changed, # nothing has changed yet
)
def eval_pd(self,i):
# evaluate 3 values (perturbations in x,y,z directions)
PERTURB = 1e-6 # perturbation amount (must be less than sqrt(pi))
#PERTURB = 1e-10 # perturbation amount (must be less than sqrt(pi))
q_i = self.Q[i]
q_i_inverse = q_i.inverse()
qx = q_i*cgtypes.quat(0,PERTURB,0,0).exp()
self.Q[i] = qx
G_Qx = self.objective_function.eval(self.Q,changed_idx=i)
dist_x = abs((q_i_inverse*qx).log())
qy = q_i*cgtypes.quat(0,0,PERTURB,0).exp()
self.Q[i] = qy
G_Qy = self.objective_function.eval(self.Q,changed_idx=i)
dist_y = abs((q_i_inverse*qy).log())
qz = q_i*cgtypes.quat(0,0,0,PERTURB).exp()
self.Q[i] = qz
G_Qz = self.objective_function.eval(self.Q,changed_idx=i)
dist_z = abs((q_i_inverse*qz).log())
self.Q[i] = q_i
qdir = cgtypes.quat(0,
(G_Qx-self.G_Q)/dist_x,
(G_Qy-self.G_Q)/dist_y,
(G_Qz-self.G_Q)/dist_z)
return qdir
##print 'Q',Q,'='*200
pd_finder = PDfinder(self,Q)
del_G_Q = QuatSeq([ pd_finder.eval_pd(i) for i in range(len(Q)) ])
return del_G_Q
def set_cache_qs(self,qs):
# no-op
pass
class CachingObjectiveFunctionQuats(ObjectiveFunctionQuats):
"""This class should is a fast version of ObjectiveFunctionQuats when used properly"""
def __init__(self, *args, **kwargs):
super( CachingObjectiveFunctionQuats, self ).__init__(*args, **kwargs)
self.cache_qs = None
def set_cache_qs(self,qs):
# initialize the cache
self.cache_qs = qs.copy() # copy
self._getDistance(self.cache_qs,init_cache=True)
self._getEnergy(self.cache_qs,init_cache=True)
def _calc_changed(self,qs):
1/0
import warnings
warnings.warn('maximum performance not acheived because search forced')
changed_idx = None
for i in range(len(qs)):
if not qs[i] == self.cache_qs[i]:
changed_idx = i
break
return changed_idx
def _getDistance(self, qs, init_cache=False, changed_idx=None):
# This distance function is independent of "roll" angle, and
# thus doesn't penalize changes in roll.
if init_cache:
# test distance of orientations in R3 (L2 norm)
qtest_orients = quat_to_orient(qs)
self._cache_L2dist = nx.sum((qtest_orients-self.qorients)**2,axis=1)
assert changed_idx is None
elif changed_idx is None:
changed_idx = self._calc_changed(qs)
mixin_new_results_with_cache = ((changed_idx is not None) and
(not isinstance(changed_idx,NoIndexChangedClass)))
if mixin_new_results_with_cache:
qtest_orient = quat_to_orient(qs[changed_idx])
if self.ignore_direction_sign:
# test both directions, take the minimum distance
new_val1 = nx.sum((qtest_orient-self.qorients[changed_idx])**2) # no axis, 1 dim
new_val2 = nx.sum((qtest_orient+self.qorients[changed_idx])**2) # no axis, 1 dim
new_val = np.min(new_val1,new_val2)
else:
new_val = nx.sum((qtest_orient-self.qorients[changed_idx])**2) # no axis, 1 dim
orig_val = self._cache_L2dist[changed_idx]
self._cache_L2dist[changed_idx] = new_val
result = nx.sum( self._cache_L2dist[self.valid_cond] )
if mixin_new_results_with_cache:
self._cache_L2dist[changed_idx] = orig_val # restore cache
assert not np.isnan(result)
return result
def _getEnergy(self, qs, init_cache=False, changed_idx=None):
if init_cache:
self._cache_omega_dot = ((qs[1:-1].inverse()*qs[2:]).log() -
(qs[:-2].inverse()*qs[1:-1]).log()) / self.h2
assert changed_idx is None
elif changed_idx is None:
changed_idx = self._calc_changed(qs)
mixin_new_results_with_cache = ((changed_idx is not None) and
(not isinstance(changed_idx,NoIndexChangedClass)))
if mixin_new_results_with_cache:
fix_idx_center = changed_idx-1 # central index into cache_omega_dot
context_info = []
for offset in [-1,0,1]: # results aren't entirely local
idx = fix_idx_center+offset
if (idx < 0) or (idx >= len(self._cache_omega_dot)):
continue
orig_val = self._cache_omega_dot[idx]
new_val = ((qs[ idx+1 ].inverse()*qs[ idx+2 ]).log() -
(qs[ idx ].inverse()*qs[ idx+1 ]).log())/ self.h2
context_info.append( (idx,orig_val))
self._cache_omega_dot[idx] = new_val
result = nx.sum( abs( self._cache_omega_dot )**2 )
if mixin_new_results_with_cache:
for (idx,orig_val) in context_info:
self._cache_omega_dot[idx] = orig_val
assert not np.isnan(result)
return result
class QuatSmoother(object):
def __init__(self,
frames_per_second=None,
beta=1.0,
gamma=0.0,
lambda2=1e-11,
percent_error_eps_quats=9,
epsilon2 = 0,
max_iter2 = 2000,
):
self.delta_t = 1.0/frames_per_second
self.beta= beta
self.gamma= gamma
self.lambda2= lambda2
self.percent_error_eps_quats=percent_error_eps_quats
self.epsilon2 = epsilon2
self.max_iter2 = max_iter2
def smooth_directions(self, direction_vec,**kwargs):
assert len(direction_vec.shape)==2
assert direction_vec.shape[1]==3
Q = QuatSeq([ orientation_to_quat(U) for U in direction_vec ])
Qsmooth = self.smooth_quats(Q,**kwargs)
direction_vec_smooth = quat_to_orient(Qsmooth)
return direction_vec_smooth
def smooth_quats(self,
Q,
display_progress=False,
objective_func_name='CachingObjectiveFunctionQuats',
no_distance_penalty_idxs=None,
):
if objective_func_name == 'CachingObjectiveFunctionQuats':
of_class = CachingObjectiveFunctionQuats
elif objective_func_name == 'ObjectiveFunctionQuats':
of_class = ObjectiveFunctionQuats
if display_progress: print 'constructing objective function...'
of = of_class(Q, self.delta_t, self.beta, self.gamma,no_distance_penalty_idxs=no_distance_penalty_idxs)
if display_progress: print 'done constructing objective function.'
#lambda2 = 2e-9
#lambda2 = 1e-9
#lambda2 = 1e-11
Q_k = Q.copy() # make copy
# make all Q_k elements valid so that we can improve them.
(valid_cond, no_distance_penalty_idxs, Q_k) = _calc_idxs_and_fixup_q(no_distance_penalty_idxs,Q_k)
last_err = None
count = 0
while count<self.max_iter2:
count += 1
if display_progress: start = time.time()
if display_progress: print 'initializing cache'
of.set_cache_qs(Q_k) # set the cache (no-op on non-caching version)
if display_progress: print 'computing del_G'
del_G = of.get_del_G(Q_k)
if display_progress: print 'del_G done'
D = of._getDistance(Q_k,changed_idx=no_index_changed) # no change since we set the cache a few lines ago
if display_progress: print 'D done'
E = of._getEnergy(Q_k,changed_idx=no_index_changed) # no change since we set the cache a few lines ago
if display_progress: print 'E done'
R = of._getRoll(Q_k)
if display_progress: print ' G = %s + %s*%s + %s*%s'%(str(D),str(self.beta),str(E),str(self.gamma),str(R))
if display_progress: stop = time.time()
err = np.sqrt(np.sum(np.array(abs(del_G))**2))
if err < self.epsilon2:
if display_progress: print 'reached epsilon2'
break
elif last_err is not None:
pct_err = (last_err-err)/last_err*100.0
if display_progress: print 'Q elapsed: % 6.2f secs,'%(stop-start,),
if display_progress: print 'current gradient:',err,
if display_progress: print ' (%4.2f%%)'%(pct_err,)
if err > last_err:
if display_progress: print 'ERROR: error is increasing, aborting'
break
if pct_err < self.percent_error_eps_quats:
if display_progress: print 'reached percent_error_eps_quats'
break
else:
if display_progress: print 'Q elapsed: % 6.2f secs,'%(stop-start,),
if display_progress: print 'current gradient:',err
pass
last_err = err
Q_k = Q_k*(del_G*-self.lambda2).exp()
if count>=self.max_iter2:
if display_progress: print 'reached max_iter2'
pass
Qsmooth = Q_k
return Qsmooth
def _test():
# test math
eps=1e-7
yaws = list( nx.arange( -math.pi, math.pi, math.pi/16.0 ) )
yaws.append( math.pi )
pitches = list( nx.arange( -math.pi/2, math.pi/2, math.pi/16.0 ) )
pitches.append( math.pi/2 )
err_count = 0
total_count = 0
for yaw in yaws:
for pitch in pitches:
had_err = False
# forward and backward test 1
yaw2,pitch2 = orientation_to_euler(euler_to_orientation(yaw,pitch))
if abs(yaw-yaw2)>eps or abs(pitch-pitch2)>eps:
print 'orientation problem at',repr((yaw,pitch))
had_err = True
if 1:
# forward and backward test 2
rolls = list( nx.arange( -math.pi/2, math.pi/2, math.pi/16.0 ) )
rolls.append( math.pi/2 )
for roll in rolls:
if pitch == math.pi/2 or pitch == -math.pi/2:
at_singularity=True
else:
at_singularity=False
yaw3, pitch3, roll3 = quat_to_euler( euler_to_quat( yaw=yaw, pitch=pitch, roll=roll ))
# relax criteria at singularities
singularity_is_ok = not (at_singularity and abs(pitch3)-abs(pitch)<eps)
if abs(yaw-yaw3)>eps or abs(pitch-pitch3)>eps:
if not (abs(yaw)==math.pi and (abs(yaw)-abs(yaw3)<eps)):
if not (at_singularity or singularity_is_ok):
print 'quat problem at',repr((yaw,pitch,roll))
print ' ',repr((yaw3, pitch3, roll3))
print ' ',abs(yaw-yaw3)
print ' ',abs(pitch-pitch3)
print
had_err = True
# triangle test 1
xyz1=euler_to_orientation(yaw,pitch)
xyz2=quat_to_orient( euler_to_quat( yaw=yaw, pitch=pitch ))
l2dist = math.sqrt(nx.sum((nx.array(xyz1)-nx.array(xyz2))**2))
if l2dist > eps:
print 'other problem at',repr((yaw,pitch))
print ' ',xyz1
print ' ',xyz2
print
had_err = True
# triangle test 2
yaw4, pitch4, roll4 = quat_to_euler(orientation_to_quat( xyz1 ))
if abs(yaw-yaw4)>eps or abs(pitch-pitch4)>eps:
print 'yet another problem at',repr((yaw,pitch))
print
had_err = True
total_count += 1
if had_err:
err_count += 1
print 'Error count: (%d of %d)'%(err_count,total_count)
# do doctest
import doctest, PQmath
return doctest.testmod(PQmath)
if __name__ == "__main__":
_test()
|
Some scholars have indicated that Sholay contains homosocial themes . Ted Shen describes the male bonding shown in the film as bordering on camp style . Dina Holtzman , in her book Bollywood and Globalization : Indian Popular Cinema , Nation , and Diaspora , states that the death of Jai , and resultant break of bonding between the two male leads , is necessary for the sake of establishing a normative heterosexual relationship ( that of Veeru and Basanti ) .
|
\par
\section{Driver programs for the {\tt BPG} object}
\label{section:BPG:drivers}
\par
This section contains brief descriptions of the driver programs.
\par
%=======================================================================
\begin{enumerate}
%-----------------------------------------------------------------------
\item
\begin{verbatim}
testIO msglvl msgFile inFile outFile
\end{verbatim}
This driver program reads and write {\tt BPG} files, useful for
converting formatted files to binary files and vice versa.
One can also read in a {\tt BPG} file and print out just the
header information (see the {\tt BPG\_writeStats()} method).
\par
\begin{itemize}
\item
The {\tt msglvl} parameter determines the amount of output ---
taking {\tt msglvl >= 3} means the {\tt BPG} object is written
to the message file.
\item
The {\tt msgFile} parameter determines the message file --- if {\tt
msgFile} is {\tt stdout}, then the message file is {\it stdout},
otherwise a file is opened with {\it append} status to receive any
output data.
\item
The {\tt inFile} parameter is the input file for the {\tt BPG}
object. It must be of the form {\tt *.bpgf} or {\tt *.bpgb}.
The {\tt BPG} object is read from the file via the
{\tt BPG\_readFromFile()} method.
\item
The {\tt outFile} parameter is the output file for the {\tt BPG}
object.
If {\tt outFile} is {\tt none} then the {\tt BPG} object is not
written to a file.
Otherwise, the {\tt BPG\_writeToFile()} method is called to write
the graph to
a formatted file (if {\tt outFile} is of the form {\tt *.bpgf}),
or
a binary file (if {\tt outFile} is of the form {\tt *.bpgb}).
\end{itemize}
%-----------------------------------------------------------------------
\item
\begin{verbatim}
extractBPG msglvl msgFile inGraphFile inCompidsIVfile
icomp outMapFile outBPGfile
\end{verbatim}
This driver program reads in a {\tt Graph} object
and an {\tt IV} object that contains the component ids.
(A separator vertex has component id zero; other vertices have
positive component ids to identify the subgraph that contains
them.)
It then extracts out the bipartite graph formed by the separator
and nodes in the target component that are adjacent to the separator.
\begin{itemize}
\item
The {\tt msglvl} parameter determines the amount of output ---
taking {\tt msglvl >= 3} means that all objects are written
to the message file.
\item
The {\tt msgFile} parameter determines the message file --- if {\tt
msgFile} is {\tt stdout}, then the message file is {\it stdout},
otherwise a file is opened with {\it append} status to receive any
message data.
\item
The {\tt inGraphFile} parameter is the input file for the {\tt Graph}
object. It must be of the form {\tt *.graphf} or {\tt *.graphb}.
The {\tt Graph} object is read from the file via the
{\tt Graph\_readFromFile()} method.
\item
The {\tt inCompidsIVfile} parameter is the input file for the {\tt IV}
object that contains the component ids.
It must be of the form {\tt *.ivf} or {\tt *.ivb}.
The {\tt IV} object is read from the file via the
{\tt IV\_readFromFile()} method.
\item
The {\tt icomp} parameter defines the target component to form the
$Y$ nodes of the bipartite graph.
(The separator nodes, component zero, form the $X$ nodes.)
\item
The {\tt outMapFile} parameter is the output file for the {\tt IV}
object that holds the map from vertices in the bipartite graph to
vertices in the original graph.
If {\tt outMapFile} is {\tt none} then the {\tt IV} object is not
written to a file.
Otherwise, the {\tt IV\_writeToFile()} method is called to write
the {\tt IV} object to
a formatted file (if {\tt outMapFile} is of the form {\tt *.ivf}),
or
a binary file (if {\tt outMapFile} is of the form {\tt *.ivb}).
\item
The {\tt outBPGFile} parameter is the output file for the
compressed {\tt BPG} object.
If {\tt outBPGFile} is {\tt none} then the {\tt BPG} object is not
written to a file.
Otherwise, the {\tt BPG\_writeToFile()} method is called to write
the graph to
a formatted file (if {\tt outBPGFile} is of the form {\tt *.graphf}),
or
a binary file (if {\tt outBPGFile} is of the form {\tt *.graphb}).
\end{itemize}
%-----------------------------------------------------------------------
\item
\begin{verbatim}
testDM msglvl msgFile inBPGfile
\end{verbatim}
This driver program reads in a {\tt BPG} object from a file.
It then finds the Dulmage-Mendelsohn decomposition using two
methods.
\begin{itemize}
\item
{\tt BPG\_DMdecomposition()} which uses matching
techniques on the weighted graph.
\item
{\tt BPG\_DMviaMaxFlow()} which forms bipartite network and solves
the max flow problem using a simple Ford-Fulkerson algorithm.
\end{itemize}
This provides a good check on the two programs (they must have the
same output) and writes their execution times.
\begin{itemize}
\item
The {\tt msglvl} parameter determines the amount of output ---
taking {\tt msglvl >= 3} means that all objects are written
to the message file.
\item
The {\tt msgFile} parameter determines the message file --- if {\tt
msgFile} is {\tt stdout}, then the message file is {\it stdout},
otherwise a file is opened with {\it append} status to receive any
message data.
\item
The {\tt inBPGFile} parameter is the input file for the {\tt BPG}
object. It must be of the form {\tt *.graphf} or {\tt *.graphb}.
The {\tt BPG} object is read from the file via the
{\tt BPG\_readFromFile()} method.
\end{itemize}
%-----------------------------------------------------------------------
\end{enumerate}
|
# Exponentials, Radicals, and Logs
Up to this point, all of our equations have included standard arithmetic operations, such as division, multiplication, addition, and subtraction. Many real-world calculations involve exponential values in which numbers are raised by a specific power.
## Exponentials
A simple case of using an exponential is squaring a number; in other words, multipying a number by itself. For example, 2 squared is 2 times 2, which is 4. This is written like this:
\begin{equation}2^{2} = 2 \cdot 2 = 4\end{equation}
Similarly, 2 cubed is 2 times 2 times 2 (which is of course 8):
\begin{equation}2^{3} = 2 \cdot 2 \cdot 2 = 8\end{equation}
In Python, you use the ****** operator, like this example in which **x** is assigned the value of 5 raised to the power of 3 (in other words, 5 x 5 x 5, or 5-cubed):
```python
x = 5**3
print(x)
```
125
Multiplying a number by itself twice or three times to calculate the square or cube of a number is a common operation, but you can raise a number by any exponential power. For example, the following notation shows 4 to the power of 7 (or 4 x 4 x 4 x 4 x 4 x 4 x 4), which has the value:
\begin{equation}4^{7} = 16384 \end{equation}
In mathematical terminology, **4** is the *base*, and **7** is the *power* or *exponent* in this expression.
## Radicals (Roots)
While it's common to need to calculate the solution for a given base and exponential, sometimes you'll need to calculate one or other of the elements themselves. For example, consider the following expression:
\begin{equation}?^{2} = 9 \end{equation}
This expression is asking, given a number (9) and an exponent (2), what's the base? In other words, which number multipled by itself results in 9? This type of operation is referred to as calculating the *root*, and in this particular case it's the *square root* (the base for a specified number given the exponential **2**). In this case, the answer is 3, because 3 x 3 = 9. We show this with a **√** symbol, like this:
\begin{equation}\sqrt{9} = 3 \end{equation}
Other common roots include the *cube root* (the base for a specified number given the exponential **3**). For example, the cube root of 64 is 4 (because 4 x 4 x 4 = 64). To show that this is the cube root, we include the exponent **3** in the **√** symbol, like this:
\begin{equation}\sqrt[3]{64} = 4 \end{equation}
We can calculate any root of any non-negative number, indicating the exponent in the **√** symbol.
The **math** package in Python includes a **sqrt** function that calculates the square root of a number. To calculate other roots, you need to reverse the exponential calculation by raising the given number to the power of 1 divided by the given exponent:
```python
import math
# Calculate square root of 25
x = math.sqrt(25)
print (x)
# Calculate cube root of 64
cr = round(64 ** (1. / 3))
print(cr)
```
5.0
4
The code used in Python to calculate roots other than the square root reveals something about the relationship between roots and exponentials. The exponential root of a number is the same as that number raised to the power of 1 divided by the exponential. For example, consider the following statement:
\begin{equation} 8^{\frac{1}{3}} = \sqrt[3]{8} = 2 \end{equation}
Note that a number to the power of 1/3 is the same as the cube root of that number.
Based on the same arithmetic, a number to the power of 1/2 is the same as the square root of the number:
\begin{equation} 9^{\frac{1}{2}} = \sqrt{9} = 3 \end{equation}
You can see this for yourself with the following Python code:
```python
import math
print (9**0.5)
print (math.sqrt(9))
```
## Logarithms
Another consideration for exponential values is the requirement occassionally to determine the exponent for a given number and base. In other words, how many times do I need to multiply a base number by itself to get the given result. This kind of calculation is known as the *logarithm*.
For example, consider the following expression:
\begin{equation}4^{?} = 16 \end{equation}
In other words, to what power must you raise 4 to produce the result 16?
The answer to this is 2, because 4 x 4 (or 4 to the power of 2) = 16. The notation looks like this:
\begin{equation}log_{4}(16) = 2 \end{equation}
In Python, you can calculate the logarithm of a number using the **log** function in the **math** package, indicating the number and the base:
```python
import math
x = math.log(16, 4)
print(x)
```
The final thing you need to know about exponentials and logarithms is that there are some special logarithms:
The *common* logarithm of a number is its exponential for the base **10**. You'll occassionally see this written using the usual *log* notation with the base omitted:
\begin{equation}log(1000) = 3 \end{equation}
Another special logarithm is something called the *natural log*, which is a exponential of a number for base ***e***, where ***e*** is a constant with the approximate value 2.718. This number occurs naturally in a lot of scenarios, and you'll see it often as you work with data in many analytical contexts. For the time being, just be aware that the natural log is sometimes written as ***ln***:
\begin{equation}log_{e}(64) = ln(64) = 4.1589 \end{equation}
The **math.log** function in Python returns the natural log (base ***e***) when no base is specified. Note that this can be confusing, as the mathematical notation *log* with no base usually refers to the common log (base **10**). To return the common log in Python, use the **math.log10** function:
```python
import math
# Natural log of 29
print (math.log(29))
# Common log of 100
print(math.log10(100))
```
3.367295829986474
2.0
## Solving Equations with Exponentials
OK, so now that you have a basic understanding of exponentials, roots, and logarithms; let's take a look at some equations that involve exponential calculations.
Let's start with what might at first glance look like a complicated example, but don't worry - we'll solve it step-by-step and learn a few tricks along the way:
\begin{equation}2y = 2x^{4} ( \frac{x^{2} + 2x^{2}}{x^{3}} ) \end{equation}
First, let's deal with the fraction on the right side. The numerator of this fraction is x<sup>2</sup> + 2x<sup>2</sup> - so we're adding two exponential terms. When the terms you're adding (or subtracting) have the same exponential, you can simply add (or subtract) the coefficients. In this case, x<sup>2</sup> is the same as 1x<sup>2</sup>, which when added to 2x<sup>2</sup> gives us the result 3x<sup>2</sup>, so our equation now looks like this:
\begin{equation}2y = 2x^{4} ( \frac{3x^{2}}{x^{3}} ) \end{equation}
Now that we've condolidated the numerator, let's simplify the entire fraction by dividing the numerator by the denominator. When you divide exponential terms with the same variable, you simply divide the coefficients as you usually would and subtract the exponential of the denominator from the exponential of the numerator. In this case, we're dividing 3x<sup>2</sup> by 1x<sup>3</sup>: The coefficient 3 divided by 1 is 3, and the exponential 2 minus 3 is -1, so the result is 3x<sup>-1</sup>, making our equation:
\begin{equation}2y = 2x^{4} ( 3x^{-1} ) \end{equation}
So now we've got rid of the fraction on the right side, let's deal with the remaining multiplication. We need to multiply 3x<sup>-1</sup> by 2x<sup>4</sup>. Multiplication, is the opposite of division, so this time we'll multipy the coefficients and add the exponentials: 3 multiplied by 2 is 6, and -1 + 4 is 3, so the result is 6x<sup>3</sup>:
\begin{equation}2y = 6x^{3} \end{equation}
We're in the home stretch now, we just need to isolate y on the left side, and we can do that by dividing both sides by 2. Note that we're not dividing by an exponential, we simply need to divide the whole 6x<sup>3</sup> term by two; and half of 6 times x<sup>3</sup> is just 3 times x<sup>3</sup>:
\begin{equation}y = 3x^{3} \end{equation}
Now we have a solution that defines y in terms of x. We can use Python to plot the line created by this equation for a set of arbitrary *x* and *y* values:
```python
import pandas as pd
# Create a dataframe with an x column containing values from -10 to 10
df = pd.DataFrame ({'x': range(-10, 11)})
# Add a y column by applying the slope-intercept equation to x
df['y'] = 3*df['x']**3
#Display the dataframe
print(df)
# Plot the line
%matplotlib inline
from matplotlib import pyplot as plt
plt.plot(df.x, df.y, color="magenta")
plt.xlabel('x')
plt.ylabel('y')
plt.grid()
plt.axhline()
plt.axvline()
plt.show()
```
Note that the line is curved. This is symptomatic of an exponential equation: as values on one axis increase or decrease, the values on the other axis scale *exponentially* rather than *linearly*.
Let's look at an example in which x is the exponential, not the base:
\begin{equation}y = 2^{x} \end{equation}
We can still plot this as a line:
```python
import pandas as pd
# Create a dataframe with an x column containing values from -10 to 10
df = pd.DataFrame ({'x': range(-10, 11)})
# Add a y column by applying the slope-intercept equation to x
df['y'] = 2.0**df['x']
#Display the dataframe
print(df)
# Plot the line
%matplotlib inline
from matplotlib import pyplot as plt
plt.plot(df.x, df.y, color="magenta")
plt.xlabel('x')
plt.ylabel('y')
plt.grid()
plt.axhline()
plt.axvline()
plt.show()
```
Note that when the exponential is a negative number, Python reports the result as 0. Actually, it's a very small fractional number, but because the base is positive the exponential number will always positive. Also, note the rate at which y increases as x increases - exponential growth can be be pretty dramatic.
**So what's the practical application of this?**
Well, let's suppose you deposit $100 in a bank account that earns 5% interest per year. What would the balance of the account be in twenty years, assuming you don't deposit or withdraw any additional funds?
To work this out, you could calculate the balance for each year:
After the first year, the balance will be the initial deposit ($100) plus 5% of that amount:
\begin{equation}y_1 = 100 + (100 \cdot 0.05) \end{equation}
Another way of saying this is:
\begin{equation}y_1 = 100 \cdot 1.05 \end{equation}
At the end of year two, the balance will be the year one balance plus 5%:
\begin{equation}y_2 = 100 \cdot 1.05 \cdot 1.05 \end{equation}
Note that the interest for year two, is the interest for year one multiplied by itself - in other words, squared. So another way of saying this is:
\begin{equation}y_2 = 100 \cdot 1.05^{2} \end{equation}
It turns out, if we just use the year as the exponent, we can easily calculate the growth after twenty years like this:
\begin{equation}y_{20} = 100 \cdot 1.05^{20} \end{equation}
Let's apply this logic in Python to see how the account balance would grow over twenty years:
```python
import pandas as pd
# Create a dataframe with 20 years
df = pd.DataFrame ({'Year': range(1, 21)})
# Calculate the balance for each year based on the exponential growth from interest
df['Balance'] = 100 * (1.05**df['Year'])
#Display the dataframe
print(df)
# Plot the line
%matplotlib inline
from matplotlib import pyplot as plt
plt.plot(df.Year, df.Balance, color="green")
plt.xlabel('Year')
plt.ylabel('Balance')
plt.show()
```
|
------------------------------------------------------------------------
-- Embeddings with erased "proofs"
------------------------------------------------------------------------
-- Partially following the HoTT book.
{-# OPTIONS --without-K --safe #-}
open import Equality
module Embedding.Erased
{reflexive} (eq : ∀ {a p} → Equality-with-J a p reflexive) where
open import Prelude hiding (id; _∘_)
open import Bijection eq using (_↔_)
open Derived-definitions-and-properties eq
open import Embedding eq as Emb using (Is-embedding; Embedding)
open import Equivalence eq as Eq using (_≃_)
open import Equivalence.Erased eq as EEq
using (_≃ᴱ_; Is-equivalenceᴱ)
open import Equivalence.Erased.Contractible-preimages eq as ECP
using (_⁻¹ᴱ_)
open import Erased.Level-1 eq using (Erased; []-cong-axiomatisation)
open import Function-universe eq hiding (id; _∘_; equivalence)
open import H-level.Closure eq
open import Preimage eq using (_⁻¹_)
private
variable
a b ℓ t : Level
A B C : Type a
f k x y : A
------------------------------------------------------------------------
-- Embeddings
-- The property of being an embedding with erased "proofs".
Is-embeddingᴱ : {A : Type a} {B : Type b} → (A → B) → Type (a ⊔ b)
Is-embeddingᴱ f = ∀ x y → Is-equivalenceᴱ (cong {x = x} {y = y} f)
-- Is-embeddingᴱ is propositional in erased contexts (assuming
-- extensionality).
@0 Is-embeddingᴱ-propositional :
{A : Type a} {B : Type b} {f : A → B} →
Extensionality (a ⊔ b) (a ⊔ b) →
Is-proposition (Is-embeddingᴱ f)
Is-embeddingᴱ-propositional {b = b} ext =
Π-closure (lower-extensionality b lzero ext) 1 λ _ →
Π-closure (lower-extensionality b lzero ext) 1 λ _ →
EEq.Is-equivalenceᴱ-propositional ext _
-- Embeddings with erased proofs.
record Embeddingᴱ (From : Type f) (To : Type t) : Type (f ⊔ t) where
field
to : From → To
is-embedding : Is-embeddingᴱ to
equivalence : (x ≡ y) ≃ᴱ (to x ≡ to y)
equivalence = EEq.⟨ _ , is-embedding _ _ ⟩
------------------------------------------------------------------------
-- Some conversion functions
-- The type family above could have been defined using Σ.
Embeddingᴱ-as-Σ : Embeddingᴱ A B ↔ ∃ λ (f : A → B) → Is-embeddingᴱ f
Embeddingᴱ-as-Σ = record
{ surjection = record
{ logical-equivalence = record
{ to = λ emb → Embeddingᴱ.to emb , Embeddingᴱ.is-embedding emb
; from = λ { (f , is) → record { to = f; is-embedding = is } }
}
; right-inverse-of = refl
}
; left-inverse-of = refl
}
-- Conversions between Is-embedding and Is-embeddingᴱ.
Is-embedding→Is-embeddingᴱ : Is-embedding f → Is-embeddingᴱ f
Is-embedding→Is-embeddingᴱ {f = f} =
(∀ x y → Eq.Is-equivalence (cong {x = x} {y = y} f)) ↝⟨ (∀-cong _ λ _ → ∀-cong _ λ _ → EEq.Is-equivalence→Is-equivalenceᴱ) ⟩□
(∀ x y → Is-equivalenceᴱ (cong {x = x} {y = y} f)) □
@0 Is-embedding≃Is-embeddingᴱ :
{A : Type a} {B : Type b} {f : A → B} →
Is-embedding f ↝[ a ∣ a ⊔ b ] Is-embeddingᴱ f
Is-embedding≃Is-embeddingᴱ {f = f} {k = k} ext =
(∀ x y → Eq.Is-equivalence (cong {x = x} {y = y} f)) ↝⟨ (∀-cong ext λ _ → ∀-cong ext λ _ → from-equivalence
EEq.Is-equivalence≃Is-equivalenceᴱ) ⟩□
(∀ x y → Is-equivalenceᴱ (cong {x = x} {y = y} f)) □
@0 Is-embeddingᴱ→Is-embedding : Is-embeddingᴱ f → Is-embedding f
Is-embeddingᴱ→Is-embedding = inverse-ext? Is-embedding≃Is-embeddingᴱ _
-- Conversions between Embedding and Embeddingᴱ.
Embedding→Embeddingᴱ : Embedding A B → Embeddingᴱ A B
Embedding→Embeddingᴱ {A = A} {B = B} =
Embedding A B ↔⟨ Emb.Embedding-as-Σ ⟩
(∃ λ (f : A → B) → Is-embedding f) ↝⟨ (∃-cong λ _ → Is-embedding→Is-embeddingᴱ) ⟩
(∃ λ (f : A → B) → Is-embeddingᴱ f) ↔⟨ inverse Embeddingᴱ-as-Σ ⟩□
Embeddingᴱ A B □
@0 Embedding≃Embeddingᴱ :
{A : Type a} {B : Type b} →
Embedding A B ↝[ a ∣ a ⊔ b ] Embeddingᴱ A B
Embedding≃Embeddingᴱ {A = A} {B = B} ext =
Embedding A B ↔⟨ Emb.Embedding-as-Σ ⟩
(∃ λ (f : A → B) → Is-embedding f) ↝⟨ (∃-cong λ _ → Is-embedding≃Is-embeddingᴱ ext) ⟩
(∃ λ (f : A → B) → Is-embeddingᴱ f) ↔⟨ inverse Embeddingᴱ-as-Σ ⟩□
Embeddingᴱ A B □
@0 Embeddingᴱ→Embedding : Embeddingᴱ A B → Embedding A B
Embeddingᴱ→Embedding = inverse-ext? Embedding≃Embeddingᴱ _
-- Data corresponding to the erased proofs of an embedding with
-- erased proofs.
Erased-proofs :
{A : Type a} {B : Type b} →
(to : A → B) →
(∀ {x y} → to x ≡ to y → x ≡ y) →
Type (a ⊔ b)
Erased-proofs to from =
∀ {x y} → EEq.Erased-proofs (cong {x = x} {y = y} to) from
-- Extracts "erased proofs" from a regular embedding.
[proofs] :
(A↝B : Embedding A B) →
Erased-proofs
(Embedding.to A↝B)
(_≃_.from (Embedding.equivalence A↝B))
[proofs] A↝B = EEq.[proofs] (Embedding.equivalence A↝B)
-- Converts two functions and some erased proofs to an embedding with
-- erased proofs.
--
-- Note that Agda can in many cases infer "to" and "from" from the
-- first explicit argument, see (for instance) _∘_ below.
[Embedding]→Embeddingᴱ :
{to : A → B} {from : ∀ {x y} → to x ≡ to y → x ≡ y} →
@0 Erased-proofs to from →
Embeddingᴱ A B
[Embedding]→Embeddingᴱ {to = to} {from = from} ep = record
{ to = to
; is-embedding = λ _ _ → _≃ᴱ_.is-equivalence (EEq.[≃]→≃ᴱ ep)
}
------------------------------------------------------------------------
-- Preorder
-- Embeddingᴱ is a preorder.
id : Embeddingᴱ A A
id = Embedding→Embeddingᴱ Emb.id
infixr 9 _∘_
_∘_ : Embeddingᴱ B C → Embeddingᴱ A B → Embeddingᴱ A C
f ∘ g =
[Embedding]→Embeddingᴱ
([proofs] (Embeddingᴱ→Embedding f Emb.∘ Embeddingᴱ→Embedding g))
------------------------------------------------------------------------
-- "Preimages"
-- If f is an embedding (with erased proofs), then f ⁻¹ᴱ y is
-- propositional (in an erased context).
--
-- This result is based on the proof of Theorem 4.6.3 in the HoTT book
-- (first edition).
@0 embedding→⁻¹ᴱ-propositional :
Is-embeddingᴱ f →
∀ y → Is-proposition (f ⁻¹ᴱ y)
embedding→⁻¹ᴱ-propositional {f = f} =
Is-embeddingᴱ f ↝⟨ Is-embeddingᴱ→Is-embedding ⟩
Is-embedding f ↝⟨ Emb.embedding→⁻¹-propositional ⟩
(∀ y → Is-proposition (f ⁻¹ y)) ↝⟨ (∀-cong _ λ _ → H-level-cong _ 1 ECP.⁻¹≃⁻¹ᴱ) ⟩□
(∀ y → Is-proposition (f ⁻¹ᴱ y)) □
------------------------------------------------------------------------
-- Results that depend on an axiomatisation of []-cong (for a single
-- universe level)
module []-cong₁ (ax : []-cong-axiomatisation ℓ) where
----------------------------------------------------------------------
-- More conversion functions
-- Equivalences (with erased proofs) from Erased A to B are
-- embeddings (with erased proofs).
Is-equivalenceᴱ→Is-embeddingᴱ-Erased :
{A : Type ℓ} {f : Erased A → B} →
Is-equivalenceᴱ f → Is-embeddingᴱ f
Is-equivalenceᴱ→Is-embeddingᴱ-Erased eq _ _ =
_≃ᴱ_.is-equivalence $ inverse $
EEq.[]-cong₁.to≡to≃ᴱ≡-Erased ax EEq.⟨ _ , eq ⟩
-- Equivalences with erased proofs between Erased A and B can be
-- converted to embeddings with erased proofs.
Erased≃→Embedding :
{A : Type ℓ} →
Erased A ≃ᴱ B → Embeddingᴱ (Erased A) B
Erased≃→Embedding EEq.⟨ f , is-equiv ⟩ = record
{ to = f
; is-embedding = Is-equivalenceᴱ→Is-embeddingᴱ-Erased is-equiv
}
------------------------------------------------------------------------
-- Results that depend on an axiomatisation of []-cong (for all
-- universe levels)
module []-cong (ax : ∀ {ℓ} → []-cong-axiomatisation ℓ) where
private
open module BC₁ {ℓ} =
[]-cong₁ (ax {ℓ = ℓ})
public
|
State Before: α : Type u_1
β : Type u_2
γ : Type ?u.383429
δ : Type ?u.383432
inst✝⁴ : TopologicalSpace α
inst✝³ : TopologicalSpace β
inst✝² : TopologicalSpace γ
inst✝¹ : TopologicalSpace δ
p : Prop
f g : α → β
inst✝ : Decidable p
hf : p → Continuous f
hg : ¬p → Continuous g
⊢ Continuous fun a => if p then f a else g a State After: case inl
α : Type u_1
β : Type u_2
γ : Type ?u.383429
δ : Type ?u.383432
inst✝⁴ : TopologicalSpace α
inst✝³ : TopologicalSpace β
inst✝² : TopologicalSpace γ
inst✝¹ : TopologicalSpace δ
p : Prop
f g : α → β
inst✝ : Decidable p
hf : p → Continuous f
hg : ¬p → Continuous g
h : p
⊢ Continuous fun a => f a
case inr
α : Type u_1
β : Type u_2
γ : Type ?u.383429
δ : Type ?u.383432
inst✝⁴ : TopologicalSpace α
inst✝³ : TopologicalSpace β
inst✝² : TopologicalSpace γ
inst✝¹ : TopologicalSpace δ
p : Prop
f g : α → β
inst✝ : Decidable p
hf : p → Continuous f
hg : ¬p → Continuous g
h : ¬p
⊢ Continuous fun a => g a Tactic: split_ifs with h State Before: case inl
α : Type u_1
β : Type u_2
γ : Type ?u.383429
δ : Type ?u.383432
inst✝⁴ : TopologicalSpace α
inst✝³ : TopologicalSpace β
inst✝² : TopologicalSpace γ
inst✝¹ : TopologicalSpace δ
p : Prop
f g : α → β
inst✝ : Decidable p
hf : p → Continuous f
hg : ¬p → Continuous g
h : p
⊢ Continuous fun a => f a
case inr
α : Type u_1
β : Type u_2
γ : Type ?u.383429
δ : Type ?u.383432
inst✝⁴ : TopologicalSpace α
inst✝³ : TopologicalSpace β
inst✝² : TopologicalSpace γ
inst✝¹ : TopologicalSpace δ
p : Prop
f g : α → β
inst✝ : Decidable p
hf : p → Continuous f
hg : ¬p → Continuous g
h : ¬p
⊢ Continuous fun a => g a State After: no goals Tactic: exacts [hf h, hg h]
|
(* Author: Tobias Nipkow *)
section "AVL Tree with Balance Factors (2)"
theory AVL_Bal2_Set
imports
Cmp
Isin2
begin
text \<open>This version passes a flag (\<open>Same\<close>/\<open>Diff\<close>) back up to signal if the height changed.\<close>
datatype bal = Lh | Bal | Rh
type_synonym 'a tree_bal = "('a * bal) tree"
text \<open>Invariant:\<close>
fun avl :: "'a tree_bal \<Rightarrow> bool" where
"avl Leaf = True" |
"avl (Node l (a,b) r) =
((case b of
Bal \<Rightarrow> height r = height l |
Lh \<Rightarrow> height l = height r + 1 |
Rh \<Rightarrow> height r = height l + 1)
\<and> avl l \<and> avl r)"
subsection \<open>Code\<close>
datatype 'a alt = Same 'a | Diff 'a
type_synonym 'a tree_bal2 = "'a tree_bal alt"
fun tree :: "'a alt \<Rightarrow> 'a" where
"tree(Same t) = t" |
"tree(Diff t) = t"
fun rot2 where
"rot2 A a B c C = (case B of
(Node B\<^sub>1 (b, bb) B\<^sub>2) \<Rightarrow>
let b\<^sub>1 = if bb = Rh then Lh else Bal;
b\<^sub>2 = if bb = Lh then Rh else Bal
in Node (Node A (a,b\<^sub>1) B\<^sub>1) (b,Bal) (Node B\<^sub>2 (c,b\<^sub>2) C))"
fun balL :: "'a tree_bal2 \<Rightarrow> 'a \<Rightarrow> bal \<Rightarrow> 'a tree_bal \<Rightarrow> 'a tree_bal2" where
"balL AB' c bc C = (case AB' of
Same AB \<Rightarrow> Same (Node AB (c,bc) C) |
Diff AB \<Rightarrow> (case bc of
Bal \<Rightarrow> Diff (Node AB (c,Lh) C) |
Rh \<Rightarrow> Same (Node AB (c,Bal) C) |
Lh \<Rightarrow> (case AB of
Node A (a,Lh) B \<Rightarrow> Same(Node A (a,Bal) (Node B (c,Bal) C)) |
Node A (a,Rh) B \<Rightarrow> Same(rot2 A a B c C))))"
fun balR :: "'a tree_bal \<Rightarrow> 'a \<Rightarrow> bal \<Rightarrow> 'a tree_bal2 \<Rightarrow> 'a tree_bal2" where
"balR A a ba BC' = (case BC' of
Same BC \<Rightarrow> Same (Node A (a,ba) BC) |
Diff BC \<Rightarrow> (case ba of
Bal \<Rightarrow> Diff (Node A (a,Rh) BC) |
Lh \<Rightarrow> Same (Node A (a,Bal) BC) |
Rh \<Rightarrow> (case BC of
Node B (c,Rh) C \<Rightarrow> Same(Node (Node A (a,Bal) B) (c,Bal) C) |
Node B (c,Lh) C \<Rightarrow> Same(rot2 A a B c C))))"
fun ins :: "'a::linorder \<Rightarrow> 'a tree_bal \<Rightarrow> 'a tree_bal2" where
"ins x Leaf = Diff(Node Leaf (x, Bal) Leaf)" |
"ins x (Node l (a, b) r) = (case cmp x a of
EQ \<Rightarrow> Same(Node l (a, b) r) |
LT \<Rightarrow> balL (ins x l) a b r |
GT \<Rightarrow> balR l a b (ins x r))"
definition insert :: "'a::linorder \<Rightarrow> 'a tree_bal \<Rightarrow> 'a tree_bal" where
"insert x t = tree(ins x t)"
fun baldR :: "'a tree_bal \<Rightarrow> 'a \<Rightarrow> bal \<Rightarrow> 'a tree_bal2 \<Rightarrow> 'a tree_bal2" where
"baldR AB c bc C' = (case C' of
Same C \<Rightarrow> Same (Node AB (c,bc) C) |
Diff C \<Rightarrow> (case bc of
Bal \<Rightarrow> Same (Node AB (c,Lh) C) |
Rh \<Rightarrow> Diff (Node AB (c,Bal) C) |
Lh \<Rightarrow> (case AB of
Node A (a,Lh) B \<Rightarrow> Diff(Node A (a,Bal) (Node B (c,Bal) C)) |
Node A (a,Bal) B \<Rightarrow> Same(Node A (a,Rh) (Node B (c,Lh) C)) |
Node A (a,Rh) B \<Rightarrow> Diff(rot2 A a B c C))))"
fun baldL :: "'a tree_bal2 \<Rightarrow> 'a \<Rightarrow> bal \<Rightarrow> 'a tree_bal \<Rightarrow> 'a tree_bal2" where
"baldL A' a ba BC = (case A' of
Same A \<Rightarrow> Same (Node A (a,ba) BC) |
Diff A \<Rightarrow> (case ba of
Bal \<Rightarrow> Same (Node A (a,Rh) BC) |
Lh \<Rightarrow> Diff (Node A (a,Bal) BC) |
Rh \<Rightarrow> (case BC of
Node B (c,Rh) C \<Rightarrow> Diff(Node (Node A (a,Bal) B) (c,Bal) C) |
Node B (c,Bal) C \<Rightarrow> Same(Node (Node A (a,Rh) B) (c,Lh) C) |
Node B (c,Lh) C \<Rightarrow> Diff(rot2 A a B c C))))"
fun split_max :: "'a tree_bal \<Rightarrow> 'a tree_bal2 * 'a" where
"split_max (Node l (a, ba) r) =
(if r = Leaf then (Diff l,a) else let (r',a') = split_max r in (baldR l a ba r', a'))"
fun del :: "'a::linorder \<Rightarrow> 'a tree_bal \<Rightarrow> 'a tree_bal2" where
"del _ Leaf = Same Leaf" |
"del x (Node l (a, ba) r) =
(case cmp x a of
EQ \<Rightarrow> if l = Leaf then Diff r
else let (l', a') = split_max l in baldL l' a' ba r |
LT \<Rightarrow> baldL (del x l) a ba r |
GT \<Rightarrow> baldR l a ba (del x r))"
definition delete :: "'a::linorder \<Rightarrow> 'a tree_bal \<Rightarrow> 'a tree_bal" where
"delete x t = tree(del x t)"
lemmas split_max_induct = split_max.induct[case_names Node Leaf]
lemmas splits = if_splits tree.splits alt.splits bal.splits
subsection \<open>Proofs\<close>
subsubsection "Proofs about insertion"
lemma avl_ins_case: "avl t \<Longrightarrow> case ins x t of
Same t' \<Rightarrow> avl t' \<and> height t' = height t |
Diff t' \<Rightarrow> avl t' \<and> height t' = height t + 1 \<and>
(\<forall>l a r. t' = Node l (a,Bal) r \<longrightarrow> a = x \<and> l = Leaf \<and> r = Leaf)"
apply(induction x t rule: ins.induct)
apply(auto simp: max_absorb1 split!: splits)
done
corollary avl_insert: "avl t \<Longrightarrow> avl(insert x t)"
using avl_ins_case[of t x] by (simp add: insert_def split: splits)
(* The following aux lemma simplifies the inorder_ins proof *)
lemma ins_Diff[simp]: "avl t \<Longrightarrow>
ins x t \<noteq> Diff Leaf \<and>
(ins x t = Diff (Node l (a,Bal) r) \<longleftrightarrow> t = Leaf \<and> a = x \<and> l=Leaf \<and> r=Leaf) \<and>
ins x t \<noteq> Diff (Node l (a,Rh) Leaf) \<and>
ins x t \<noteq> Diff (Node Leaf (a,Lh) r)"
by(drule avl_ins_case[of _ x]) (auto split: splits)
theorem inorder_ins:
"\<lbrakk> avl t; sorted(inorder t) \<rbrakk> \<Longrightarrow> inorder(tree(ins x t)) = ins_list x (inorder t)"
apply(induction t)
apply (auto simp: ins_list_simps split!: splits)
done
subsubsection "Proofs about deletion"
lemma inorder_baldL:
"\<lbrakk> ba = Rh \<longrightarrow> r \<noteq> Leaf; avl r \<rbrakk>
\<Longrightarrow> inorder (tree(baldL l a ba r)) = inorder (tree l) @ a # inorder r"
by (auto split: splits)
lemma inorder_baldR:
"\<lbrakk> ba = Lh \<longrightarrow> l \<noteq> Leaf; avl l \<rbrakk>
\<Longrightarrow> inorder (tree(baldR l a ba r)) = inorder l @ a # inorder (tree r)"
by (auto split: splits)
lemma avl_split_max:
"\<lbrakk> split_max t = (t',a); avl t; t \<noteq> Leaf \<rbrakk> \<Longrightarrow> case t' of
Same t' \<Rightarrow> avl t' \<and> height t = height t' |
Diff t' \<Rightarrow> avl t' \<and> height t = height t' + 1"
apply(induction t arbitrary: t' a rule: split_max_induct)
apply(fastforce simp: max_absorb1 max_absorb2 split!: splits prod.splits)
apply simp
done
lemma avl_del_case: "avl t \<Longrightarrow> case del x t of
Same t' \<Rightarrow> avl t' \<and> height t = height t' |
Diff t' \<Rightarrow> avl t' \<and> height t = height t' + 1"
apply(induction x t rule: del.induct)
apply(auto simp: max_absorb1 max_absorb2 dest: avl_split_max split!: splits prod.splits)
done
corollary avl_delete: "avl t \<Longrightarrow> avl(delete x t)"
using avl_del_case[of t x] by(simp add: delete_def split: splits)
lemma inorder_split_maxD:
"\<lbrakk> split_max t = (t',a); t \<noteq> Leaf; avl t \<rbrakk> \<Longrightarrow>
inorder (tree t') @ [a] = inorder t"
apply(induction t arbitrary: t' rule: split_max.induct)
apply(fastforce split!: splits prod.splits)
apply simp
done
lemma neq_Leaf_if_height_neq_0[simp]: "height t \<noteq> 0 \<Longrightarrow> t \<noteq> Leaf"
by auto
theorem inorder_del:
"\<lbrakk> avl t; sorted(inorder t) \<rbrakk> \<Longrightarrow> inorder (tree(del x t)) = del_list x (inorder t)"
apply(induction t rule: tree2_induct)
apply(auto simp: del_list_simps inorder_baldL inorder_baldR avl_delete inorder_split_maxD
simp del: baldR.simps baldL.simps split!: splits prod.splits)
done
subsubsection \<open>Set Implementation\<close>
interpretation S: Set_by_Ordered
where empty = Leaf and isin = isin
and insert = insert
and delete = delete
and inorder = inorder and inv = avl
proof (standard, goal_cases)
case 1 show ?case by (simp)
next
case 2 thus ?case by(simp add: isin_set_inorder)
next
case 3 thus ?case by(simp add: inorder_ins insert_def)
next
case 4 thus ?case by(simp add: inorder_del delete_def)
next
case 5 thus ?case by (simp)
next
case 6 thus ?case by (simp add: avl_insert)
next
case 7 thus ?case by (simp add: avl_delete)
qed
end
|
(* Title: HOL/Auth/n_g2kAbsAfter_lemma_inv__34_on_rules.thy
Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
*)
header{*The n_g2kAbsAfter Protocol Case Study*}
theory n_g2kAbsAfter_lemma_inv__34_on_rules imports n_g2kAbsAfter_lemma_on_inv__34
begin
section{*All lemmas on causal relation between inv__34*}
lemma lemma_inv__34_on_rules:
assumes b1: "r \<in> rules N" and b2: "(f=inv__34 )"
shows "invHoldForRule s f r (invariants N)"
proof -
have c1: "(\<exists> d. d\<le>N\<and>r=n_n_Store_i1 d)\<or>
(\<exists> d. d\<le>N\<and>r=n_n_AStore_i1 d)\<or>
(r=n_n_SendReqS_j1 )\<or>
(r=n_n_SendReqEI_i1 )\<or>
(r=n_n_SendReqES_i1 )\<or>
(r=n_n_RecvReq_i1 )\<or>
(r=n_n_SendInvE_i1 )\<or>
(r=n_n_SendInvS_i1 )\<or>
(r=n_n_SendInvAck_i1 )\<or>
(r=n_n_RecvInvAck_i1 )\<or>
(r=n_n_SendGntS_i1 )\<or>
(r=n_n_SendGntE_i1 )\<or>
(r=n_n_RecvGntS_i1 )\<or>
(r=n_n_RecvGntE_i1 )\<or>
(r=n_n_ASendReqIS_j1 )\<or>
(r=n_n_ASendReqSE_j1 )\<or>
(r=n_n_ASendReqEI_i1 )\<or>
(r=n_n_ASendReqES_i1 )\<or>
(r=n_n_SendReqEE_i1 )\<or>
(r=n_n_ARecvReq_i1 )\<or>
(r=n_n_ASendInvE_i1 )\<or>
(r=n_n_ASendInvS_i1 )\<or>
(r=n_n_ASendInvAck_i1 )\<or>
(r=n_n_ARecvInvAck_i1 )\<or>
(r=n_n_ASendGntS_i1 )\<or>
(r=n_n_ASendGntE_i1 )\<or>
(r=n_n_ARecvGntS_i1 )\<or>
(r=n_n_ARecvGntE_i1 )"
apply (cut_tac b1, auto) done
moreover {
assume d1: "(\<exists> d. d\<le>N\<and>r=n_n_Store_i1 d)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_Store_i1Vsinv__34) done
}
moreover {
assume d1: "(\<exists> d. d\<le>N\<and>r=n_n_AStore_i1 d)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_AStore_i1Vsinv__34) done
}
moreover {
assume d1: "(r=n_n_SendReqS_j1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_SendReqS_j1Vsinv__34) done
}
moreover {
assume d1: "(r=n_n_SendReqEI_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_SendReqEI_i1Vsinv__34) done
}
moreover {
assume d1: "(r=n_n_SendReqES_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_SendReqES_i1Vsinv__34) done
}
moreover {
assume d1: "(r=n_n_RecvReq_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_RecvReq_i1Vsinv__34) done
}
moreover {
assume d1: "(r=n_n_SendInvE_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_SendInvE_i1Vsinv__34) done
}
moreover {
assume d1: "(r=n_n_SendInvS_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_SendInvS_i1Vsinv__34) done
}
moreover {
assume d1: "(r=n_n_SendInvAck_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_SendInvAck_i1Vsinv__34) done
}
moreover {
assume d1: "(r=n_n_RecvInvAck_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_RecvInvAck_i1Vsinv__34) done
}
moreover {
assume d1: "(r=n_n_SendGntS_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_SendGntS_i1Vsinv__34) done
}
moreover {
assume d1: "(r=n_n_SendGntE_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_SendGntE_i1Vsinv__34) done
}
moreover {
assume d1: "(r=n_n_RecvGntS_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_RecvGntS_i1Vsinv__34) done
}
moreover {
assume d1: "(r=n_n_RecvGntE_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_RecvGntE_i1Vsinv__34) done
}
moreover {
assume d1: "(r=n_n_ASendReqIS_j1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ASendReqIS_j1Vsinv__34) done
}
moreover {
assume d1: "(r=n_n_ASendReqSE_j1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ASendReqSE_j1Vsinv__34) done
}
moreover {
assume d1: "(r=n_n_ASendReqEI_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ASendReqEI_i1Vsinv__34) done
}
moreover {
assume d1: "(r=n_n_ASendReqES_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ASendReqES_i1Vsinv__34) done
}
moreover {
assume d1: "(r=n_n_SendReqEE_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_SendReqEE_i1Vsinv__34) done
}
moreover {
assume d1: "(r=n_n_ARecvReq_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ARecvReq_i1Vsinv__34) done
}
moreover {
assume d1: "(r=n_n_ASendInvE_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ASendInvE_i1Vsinv__34) done
}
moreover {
assume d1: "(r=n_n_ASendInvS_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ASendInvS_i1Vsinv__34) done
}
moreover {
assume d1: "(r=n_n_ASendInvAck_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ASendInvAck_i1Vsinv__34) done
}
moreover {
assume d1: "(r=n_n_ARecvInvAck_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ARecvInvAck_i1Vsinv__34) done
}
moreover {
assume d1: "(r=n_n_ASendGntS_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ASendGntS_i1Vsinv__34) done
}
moreover {
assume d1: "(r=n_n_ASendGntE_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ASendGntE_i1Vsinv__34) done
}
moreover {
assume d1: "(r=n_n_ARecvGntS_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ARecvGntS_i1Vsinv__34) done
}
moreover {
assume d1: "(r=n_n_ARecvGntE_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ARecvGntE_i1Vsinv__34) done
}
ultimately show "invHoldForRule s f r (invariants N)"
by satx
qed
end
|
import category_theory.closed.monoidal
import category_theory.monoidal.braided
import tactic
namespace category_theory.monoidal
open category_theory
open category_theory.monoidal_category
universes v u
variables {C : Type u} [category.{v} C] [monoidal_category.{v} C]
class right_closed (X : C) :=
(is_adj : is_left_adjoint (tensor_right X))
attribute [instance, priority 100] right_closed.is_adj
variable (C)
class monoidal_closed_right :=
(closed : Π (X : C), right_closed X)
attribute [instance, priority 100] monoidal_closed_right.closed
variable [monoidal_closed_right.{v} C]
variable {C}
def internal_hom (X Y : C) : C :=
(right_adjoint (tensor_right X)).obj Y
def internal_hom_equiv (X Y Z : C) :
(X ⊗ Y ⟶ Z) ≃ (X ⟶ internal_hom Y Z) :=
(adjunction.of_left_adjoint (tensor_right Y)).hom_equiv X Z
def internal_hom_postcompose (X : C) {Y₁ Y₂ : C} (f : Y₁ ⟶ Y₂) :
internal_hom X Y₁ ⟶ internal_hom X Y₂ :=
(right_adjoint (tensor_right X)).map f
@[simp]
lemma internal_hom_postcompose_id (X Y : C) :
internal_hom_postcompose X (𝟙 Y) = 𝟙 _ :=
(right_adjoint (tensor_right X)).map_id _
@[simp]
lemma internal_hom_postcompose_comp (X : C) {Y₁ Y₂ Y₃ : C} (f₁ : Y₁ ⟶ Y₂) (f₂ : Y₂ ⟶ Y₃) :
internal_hom_postcompose X (f₁ ≫ f₂) =
internal_hom_postcompose X f₁ ≫ internal_hom_postcompose X f₂ :=
(right_adjoint (tensor_right X)).map_comp _ _
def internal_hom_precompose {X₁ X₂ : C} (f : X₁ ⟶ X₂) (Y : C) :
internal_hom X₂ Y ⟶ internal_hom X₁ Y :=
(internal_hom_equiv _ _ _) $ (tensor_hom (𝟙 _) f ≫ (internal_hom_equiv _ _ _).symm (𝟙 _))
lemma split_left {A₁ A₂ B₁ B₂ : C} (f : A₁ ⟶ A₂) (g : B₁ ⟶ B₂) :
(f ⊗ g) = (f ⊗ 𝟙 _) ≫ (𝟙 _ ⊗ g) := by simp
lemma split_right {A₁ A₂ B₁ B₂ : C} (f : A₁ ⟶ A₂) (g : B₁ ⟶ B₂) :
(f ⊗ g) = (𝟙 _ ⊗ g) ≫ (f ⊗ 𝟙 _) := by simp
lemma internal_hom_equiv_tensor_right {X Y₁ Y₂ Z : C} (f : Y₁ ⟶ Y₂) (g : X ⊗ Y₂ ⟶ Z) :
internal_hom_equiv _ _ _ ((𝟙 _ ⊗ f) ≫ g) =
internal_hom_equiv _ _ _ g ≫ internal_hom_precompose f _ :=
begin
apply_fun (internal_hom_equiv _ _ _).symm,
simp,
dsimp [internal_hom_precompose, internal_hom_equiv, internal_hom],
simp only [adjunction.hom_equiv_unit, adjunction.hom_equiv_counit, tensor_right_map,
tensor_id, adjunction.hom_equiv_naturality_right, functor.map_comp,
category_theory.functor.map_id, category.id_comp, category.assoc,
adjunction.hom_equiv_naturality_left_symm, adjunction.hom_equiv_naturality_right_symm],
simp only [← tensor_right_map],
rw (adjunction.of_left_adjoint (tensor_right Y₁)).counit_naturality_assoc,
rw (adjunction.of_left_adjoint (tensor_right Y₁)).left_triangle_components_assoc,
dsimp,
simp only [← category.assoc, ← tensor_comp, category.id_comp, category.comp_id],
conv_rhs { rw [split_right _ f, category.assoc] },
rw ← tensor_right_map,
simp only [functor.map_comp, category.assoc],
rw (adjunction.of_left_adjoint (tensor_right Y₂)).counit_naturality,
erw (adjunction.of_left_adjoint (tensor_right Y₂)).left_triangle_components_assoc,
end
@[simp]
lemma internal_hom_precompose_id (X Y : C) :
internal_hom_precompose (𝟙 X) Y = 𝟙 _ :=
by { dsimp [internal_hom_precompose, internal_hom_equiv, internal_hom], simp, dsimp, simp }
@[simp]
lemma internal_hom_precompose_comp {X₁ X₂ X₃ : C} (f₁ : X₁ ⟶ X₂) (f₂ : X₂ ⟶ X₃) (Y : C) :
internal_hom_precompose (f₁ ≫ f₂) Y =
internal_hom_precompose f₂ Y ≫ internal_hom_precompose f₁ Y :=
begin
change _ = internal_hom_equiv _ _ _ _ ≫ _,
rw [← internal_hom_equiv_tensor_right, ← category.assoc, ← tensor_comp, category.id_comp],
refl,
end
@[simp]
lemma internal_hom_postcompose_comp_precompose {A₁ A₂ B₁ B₂ : C}
(f : A₁ ⟶ A₂) (g : B₁ ⟶ B₂) :
internal_hom_postcompose _ f ≫ internal_hom_precompose g _ =
internal_hom_precompose g _ ≫ internal_hom_postcompose _ f :=
begin
apply_fun (internal_hom_equiv _ _ _).symm,
dsimp [internal_hom_precompose, internal_hom_postcompose, internal_hom_equiv, internal_hom],
simp only [adjunction.hom_equiv_counit, tensor_right_map, tensor_id,
adjunction.hom_equiv_naturality_right, adjunction.hom_equiv_unit, functor.map_comp,
category_theory.functor.map_id, category.id_comp, category.assoc,
adjunction.hom_equiv_naturality_left_symm, adjunction.hom_equiv_naturality_right_symm],
simp only [← tensor_right_map, adjunction.counit_naturality, adjunction.counit_naturality_assoc,
functor.map_comp, adjunction.left_triangle_components, adjunction.right_triangle_components,
adjunction.left_triangle_components_assoc, adjunction.right_triangle_components_assoc],
dsimp,
simp only [← category.assoc, ← tensor_comp, category.id_comp, category.comp_id],
rw [split_right _ g, category.assoc, ← tensor_right_map, adjunction.counit_naturality,
category.assoc],
end
@[simps]
def internal_hom_functor : Cᵒᵖ ⥤ C ⥤ C :=
{ obj := λ X,
{ obj := λ Y, internal_hom X.unop Y,
map := λ Y₁ Y₂, internal_hom_postcompose _ },
map := λ X₁ X₂ f,
{ app := λ Y, internal_hom_precompose f.unop _ } }
end category_theory.monoidal
|
section \<open>theory_decr_forest\<close>
theory theory_decr_forest
imports Main
begin
text \<open> This theory defines a notion of graphs. A graph is a record that contains a set of nodes
\<open>V\<close> and a set of edges VxV, where the values v are the unique vertex labels.\<close>
subsection \<open>Definitions\<close>
text \<open>A graph is represented by a record.\<close>
record ('v) graph =
nodes :: "'v set"
edges :: "('v \<times> 'v) set"
text \<open>In a valid graph, edges only go from nodes to nodes.\<close>
locale valid_graph =
fixes G :: "('v) graph"
assumes E_valid: "fst`edges G \<subseteq> nodes G"
"snd`edges G \<subseteq> nodes G"
begin
abbreviation "V \<equiv> nodes G"
abbreviation "E \<equiv> edges G"
lemma E_validD: assumes "(v,v')\<in>E"
shows "v\<in>V" "v'\<in>V"
apply -
apply (rule subsetD[OF E_valid(1)])
using assms apply force
apply (rule subsetD[OF E_valid(2)])
using assms apply force
done
end
subsection \<open>Basic operations on Graphs\<close>
text \<open>The empty graph.\<close>
definition empty where
"empty \<equiv> \<lparr> nodes = {}, edges = {} \<rparr>"
text \<open>Adds a node to a graph.\<close>
definition add_node where
"add_node v g \<equiv> \<lparr> nodes = insert v (nodes g), edges=edges g\<rparr>"
text \<open>Deletes a node from a graph. Also deletes all adjacent edges.\<close>
definition delete_node where "delete_node v g \<equiv> \<lparr>
nodes = nodes g - {v},
edges = edges g \<inter> (-{v})\<times>(-{v})
\<rparr>"
text \<open>Adds an edge to a graph, edges only go from smaller to larger vertex labels\<close>
definition add_edge where "add_edge v v' g \<equiv> \<lparr>
nodes = {v,v'} \<union> nodes g,
edges = (if v'>v then
insert (v,v') (edges g) else insert (v',v) (edges g))
\<rparr>"
text \<open>Deletes an edge from a graph.\<close>
definition delete_edge where "delete_edge v v' g \<equiv> \<lparr>
nodes = nodes g,
edges = edges g - {(v,v')} \<rparr>"
text \<open>Now follow some simplification lemmas.\<close>
lemma empty_valid[simp]: "valid_graph empty"
unfolding empty_def by unfold_locales auto
lemma add_node_valid[simp]: assumes "valid_graph g"
shows "valid_graph (add_node v g)"
proof -
interpret valid_graph g by fact
show ?thesis
unfolding add_node_def
by unfold_locales (auto dest: E_validD)
qed
lemma delete_node_valid[simp]: assumes "valid_graph g"
shows "valid_graph (delete_node v g)"
proof -
interpret valid_graph g by fact
show ?thesis
unfolding delete_node_def
by unfold_locales (auto dest: E_validD)
qed
lemma add_edge_valid[simp]: assumes "valid_graph g"
shows "valid_graph (add_edge v v' g)"
proof -
interpret valid_graph g by fact
show ?thesis
unfolding add_edge_def
by unfold_locales (auto dest: E_validD)
qed
lemma delete_edge_valid[simp]: assumes "valid_graph g"
shows "valid_graph (delete_edge v v' g)"
proof -
interpret valid_graph g by fact
show ?thesis
unfolding delete_edge_def
by unfold_locales (auto dest: E_validD)
qed
lemma nodes_empty[simp]: "nodes empty = {}" unfolding empty_def by simp
lemma edges_empty[simp]: "edges empty = {}" unfolding empty_def by simp
lemma nodes_add_node[simp]: "nodes (add_node v g) = insert v (nodes g)"
by (simp add: add_node_def)
lemma nodes_add_edge[simp]:
"nodes (add_edge v v' g) = insert v (insert v' (nodes g))"
by (simp add: add_edge_def)
subsection \<open>Preliminary definitions\<close>
text \<open>This function finds the connected component corresponding to the given vertex.\<close>
definition "nodes_above g v \<equiv>{v} \<union> snd ` Set.filter (\<lambda>e. fst e = v) ((edges g)\<^sup>+)"
text \<open>The function puts a component into a tree and preserves the decreasing property.\<close>
fun nodes_order :: " nat graph \<Rightarrow> nat \<Rightarrow> nat graph " where
"nodes_order g x\<^sub>1 = (let nodes\<^sub>1= nodes_above g 1 in
let nodes\<^sub>2= nodes_above g (x\<^sub>1+2) in
let max_comp\<^sub>1= Max(nodes\<^sub>1) in
let max_comp\<^sub>2= Max(nodes\<^sub>2) in
(if max_comp\<^sub>1=max_comp\<^sub>2 then g else
(if max_comp\<^sub>1 > max_comp\<^sub>2 then
let st_p=Max(Set.filter (\<lambda>v. v<max_comp\<^sub>2) nodes\<^sub>1) in
let end_p=Min(Set.filter (\<lambda>v. v>max_comp\<^sub>2) nodes\<^sub>1) in
let g1= delete_edge st_p end_p g in
let g2= add_edge st_p max_comp\<^sub>2 g1 in
let g3=add_edge max_comp\<^sub>2 end_p g2 in g3
else
add_edge max_comp\<^sub>1 max_comp\<^sub>2 g
)
)
)"
text \<open>This is an additional function. Input:
1. Order number of the current node that can be added to the graph
2. Order number of the previous node from branch1 (above 1) added to the graph
3. Order number of the previous node from branch2 (above x1+2) added to the graph
4. The current graph
5. Number sequence to encode the graph
How does the function work:
I. If the sequence (input 5.) is empty, return current graph (input 4.)
II. If the sequence is not empty and starts with a zero, add one to the order number of the
current node, delete the first number (0) from the sequence and call the function again
III. If the sequence isn't empty and doesn't start with a 0, add the current node to the graph
IIIa. If the sequence starts with a 1, add an edge to branch1 using input (2)
IIIb. If the sequence starts with a 2, add an edge to branch2 using input (3)\<close>
fun enc_to_graph :: "nat \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> nat graph \<Rightarrow> nat list \<Rightarrow> nat graph" where
"enc_to_graph curr_v prev_v1 prev_v2 g Nil = g"
| "enc_to_graph curr_v prev_v1 prev_v2 g (0#ns) =
enc_to_graph (Suc curr_v) prev_v1 prev_v2 g ns "
| "enc_to_graph curr_v prev_v1 prev_v2 g (x#ns) = (if x=1 then
enc_to_graph (Suc curr_v) curr_v prev_v2 (add_edge prev_v1 curr_v g) ns
else (if curr_v=prev_v2 then enc_to_graph (Suc curr_v) prev_v1 curr_v g ns
else enc_to_graph (Suc curr_v) prev_v1 curr_v (add_edge prev_v2 curr_v g) ns
) )"
text \<open>Define f1 to be the start graph.\<close>
definition "f1 \<equiv> \<lparr>nodes = {1::nat}, edges = {}\<rparr>"
text \<open>This is the inverse encoding function. Input:
1.x1
2. number sequence to encode into a graph
How does the function work:
I.delete the last number since it only gives information about the number of trees in the graph
but distinguish between cases in dependence of this last value
II. take first x1 numbers and build the first graph part with enc_to_graph
III. add the node x1+2 to the graph
IV. delete x1 first numbers and build the second part with the rest
V(0). if the last encoding value was 0, output tree2
V(1)(2).if the last encoding value was 1 and there are 2's in the encoding,
connect two branches into one component using the function nodes_order
V(1)(1). if the encoding only has 0 and 1 in it, build further on tree1 \<close>
fun encoding_to_graph :: "nat \<Rightarrow> nat list \<Rightarrow> nat graph" where
"encoding_to_graph x1 l = (let code_l=butlast l in
let tree\<^sub>1 = enc_to_graph 2 1 (x1+2) f1 (take x1 (code_l)) in
let max\<^sub>1 = Max (nodes tree\<^sub>1) in
let tree\<^sub>2 = enc_to_graph (x1+3) max\<^sub>1 (x1+2) (add_node (x1+2) tree\<^sub>1)
(drop x1 code_l) in
if (last l=0) then tree\<^sub>2 else
if 2\<in>set(code_l) then (nodes_order tree\<^sub>2 x1 )
else enc_to_graph (x1+3) (x1+2) (x1+2) (add_edge max\<^sub>1 (x1+2) tree\<^sub>1)
(drop (x1) code_l)
)"
text \<open>This is the main encoding function. Input:
1. Graph g to be encoded
2. x1
3. 2 as the starting node
4. x1+x2+2
5. False as the starting value for branching
How does the function work:
I. For each x from 2 (input (3)) to x1+x2+2 (input (4)), check whether
the vertex is in the graph, and if so, above which leaf does it exist
II. For the nodes above the vertex with label 1, add 1 to the encoding,For the nodes
above the vertex with label x1+2, add 2 to the encoding, change input (5) if
we found a vertex with 2 incoming edges. If the value is not on a vertex,
add 0 to the encoding
III.using the value (5), decide to put 1 or 0 for 1 or 2 connected components\<close>
fun graph_to_encoding_impl :: "nat graph \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> bool \<Rightarrow> nat list" where
"graph_to_encoding_impl f x1 x 0 c = [if c then 1 else 0]"
| "graph_to_encoding_impl f x1 x (Suc n) c = (let above_one = (1, x) \<in> (edges f)\<^sup>+ in
let above_x1_2 = (x1+2, x) \<in> (edges f)\<^sup>* in
(if x = x1 + 2 then
graph_to_encoding_impl f x1 (Suc x) n
(above_one \<and> above_x1_2)
else (if x \<in> nodes f then
(if above_one \<and> (c \<or> \<not> above_x1_2) then 1 else 2)
else 0)
# graph_to_encoding_impl f x1 (Suc x) n
(c \<or> above_one \<and> above_x1_2))
)"
text \<open>Add some computation simplifications.\<close>
lemma in_rtrancl_code [code_unfold]: "x \<in> rtrancl R \<longleftrightarrow> fst x = snd x \<or> x \<in> trancl R"
by (metis prod.exhaust_sel rtrancl_eq_or_trancl)
print_theorems
definition "graph_to_encoding f x1 x2 \<equiv> graph_to_encoding_impl f x1 2 (x1+x2+1) False"
(* Examples Part 1
definition "graph_ex1 \<equiv>
\<lparr>nodes = {1::nat,2,5,7},
edges = {(1,2),(2,5),(5,7)}\<rparr>"
definition "graph_ex2 \<equiv>
\<lparr>nodes = {1::nat,2,3,5,7},
edges = {(1,2),(2,3),(3,7),(5,7)}\<rparr>"
definition "graph_ex3 \<equiv>
\<lparr>nodes = {1::nat,4,5,6,7},
edges = {(1,4),(4,6),(5,7)}\<rparr>"
definition x1:: nat where "x1=3"
definition x2:: nat where "x2=2"
value "graph_to_encoding graph_ex1 x1 x2"
value "graph_to_encoding graph_ex2 x1 x2"
value "graph_to_encoding graph_ex3 x1 x2"
Part 2:
definition "f2 \<equiv>
\<lparr>nodes = {1::nat,2,5,6,7,8,10},
edges = {(1,2),(2,7),(7,8),
(5,6),(6,8),(8,10)}\<rparr>"
lemma "graph_to_encoding f2 3 5 = [1,0,0,2,1,2,0,1,1]" by eval
definition "f3 \<equiv>
\<lparr>nodes = {1::nat,2,5,6,7,8,10},
edges = {(1,2),(2,8),
(5,6),(6,7),(7,8),(8,10)}\<rparr>"
definition "f4 \<equiv>
\<lparr>nodes = {1::nat,2,5,6,7,8,10},
edges = {(1,2),(2,7),
(5,6),(6,8),(8,10)}\<rparr>"
definition "f6 \<equiv>
\<lparr>nodes = {1::nat,4,5,7,8},
edges = {(1,4),(4,5),(5,7),(7,8)}\<rparr>"
definition "f7 \<equiv>
\<lparr>nodes = {1::nat,5,7,10},
edges = {(1,10),(5,7),(7,10)}\<rparr>"
definition "f8 \<equiv>
\<lparr>nodes = {1::nat,5,7,10},
edges = {(1,5),(5,7),(7,10)}\<rparr>"
definition "f5 \<equiv>
\<lparr>nodes = {1::nat,3,5,6,7,8,10},
edges = {(1,3),(3,6),
(5,6),(6,7),(7,8),(8,10)}\<rparr>"
definition "f9 \<equiv>
\<lparr>nodes = {1::nat,5},
edges = {}\<rparr>"
value "(encoding_to_graph 3 (graph_to_encoding f3 3 5)) =f3"
value "(encoding_to_graph 3 (graph_to_encoding f4 3 5)) =f4"
value "(encoding_to_graph 3 (graph_to_encoding f5 3 5)) =f5"
value "(encoding_to_graph 3 (graph_to_encoding f6 3 5)) =f6"
value "(encoding_to_graph 3 (graph_to_encoding f7 3 5)) =f7"
value "(encoding_to_graph 3 (graph_to_encoding f8 3 5)) =f8"
value "(encoding_to_graph 3 (graph_to_encoding f9 3 5)) =f9"*)
text \<open>Define locales for the encoding and the forest to represent them canonically.\<close>
locale encoding =
fixes L :: "nat list"
and x1 :: "nat"
and x2 :: "nat"
assumes L_valid: "length L = x1+x2+1"
"set (take x1 L) \<subseteq> {0,1} "
"set (drop x1 L) \<subseteq> {0,1,2}"
"set (drop (x1+x2) L) \<subseteq> {0,1}"
text \<open>This is a function that finds the edges that are incident to the given vertex.\<close>
definition edges_v :: "nat graph \<Rightarrow> nat \<Rightarrow> (nat \<times> nat) set" where
" edges_v g v \<equiv> {e. e \<in> edges g \<and> (fst e = v \<or> snd e = v)}"
locale forest =
fixes T :: "nat graph"
and x1 :: "nat"
and x2 :: "nat"
assumes Ed_valid: "x1+2 \<in> nodes T"
"\<forall> (v)\<in> fst`edges T. card(snd`(edges_v T v)-{v})<2"
"\<forall> (v)\<in> snd`edges T. card(fst`(edges_v T v)-{v})<3"
"\<forall> (v,v')\<in> edges T. ( v<v')"
"nodes T \<noteq> {}"
"edges T \<noteq> {}"
"Max (nodes T) < x1+x2+3"
text \<open>This is a test section with a simplified theory. Its purpose is to define the direction of
the future research. A single tree with one leaf can be encoded as a set of its nodes. The encoding
for such a tree is just a list of Bool values, True for "node in the graph" and False for "not". \<close>
definition "valid_tree S n \<equiv> (\<forall>x. x \<in> S \<longrightarrow> 0 < x \<and> x \<le> n)"
definition "valid_encoding B n \<equiv> length B = n \<and> set B \<subseteq> {True, False}"
text \<open>Non-recursive definitions allow to use induction and prove some simple theorems.\<close>
fun tree_to_encoding :: "nat \<Rightarrow> nat \<Rightarrow> nat set \<Rightarrow> bool list" where
"tree_to_encoding x n S = map (\<lambda>i. i \<in> S) [x..<x+n]"
fun encoding_to_tree :: " nat \<Rightarrow> bool list \<Rightarrow> nat set" where
"encoding_to_tree n B = (\<lambda>i. i + n) ` {i. i < length B \<and> B ! i}"
text \<open>To show that two functions form a bijection, one should first check that the
outputs are well-defined.\<close>
lemma length_tree_to_encoding:
"length (tree_to_encoding x n S) = n"
by (induct x n S rule: tree_to_encoding.induct) auto
lemma encoding_members:
"set (tree_to_encoding x n S) \<subseteq> {True, False}"
by (induct x n S rule: tree_to_encoding.induct) auto
lemma valid_tree_to_valid_encoding:
"valid_encoding (tree_to_encoding x n S) n"
unfolding valid_encoding_def
using encoding_members length_tree_to_encoding by auto
lemma valid_encoding_to_valid_tree_aux:
"encoding_to_tree n B \<subseteq> {n..<n + length B}"
by (induction n B rule: encoding_to_tree.induct)
(auto simp: valid_encoding_def valid_tree_def)
lemma valid_encoding_to_valid_tree:
"valid_encoding B n \<Longrightarrow> valid_tree (encoding_to_tree 1 B ) n"
using valid_encoding_to_valid_tree_aux unfolding valid_encoding_def valid_tree_def
by force
end
|
Companies in the same industry as Red Book Solutions, ranked by salary.
Pay ranges for employees at Red Book Solutions by degree.
How much does Red Book Solutions pay?
Red Book Solutions pays its employees an average of $66,500 a year. Red Book Solutions employees with the job title Development Engineer make the most with an average annual salary of $76,294, while employees with the title Customer Success Manager make the least with an average annual salary of $55,023.
|
theory Boolos imports Main
begin
typedecl i
consts
e :: "i" (*one*)
s :: "i \<Rightarrow> i" (*successor*)
F :: "i \<Rightarrow> i \<Rightarrow> i" (*binary function; will be axiomatised as Ackermann function*)
D :: "i \<Rightarrow> bool" (*arbitrary unary predicate*)
axiomatization where
A1: "\<forall>n. F n e = s e" and
A2: "\<forall>y. F e (s y) = s (s (F e y))" and
A3: "\<forall>x y. F (s x) (s y) = F x (F (s x) y)" and
A4: "D e" and
A5: "\<forall>x. D x \<longrightarrow> D (s x)"
definition induct where "induct X \<equiv> (X e) \<and> (\<forall>x. X x \<longrightarrow> X (s x))" (*X inductively def. Pred.*)
definition N where "N x \<equiv> (\<forall>X::i\<Rightarrow>bool. induct X \<longrightarrow> X x)" (*Higher-order quantifier*)
definition P1 where "P1 x y \<equiv> N (F x y)"
definition P2 where "P2 x \<equiv> (\<forall>z. N z \<longrightarrow> P1 x z)"
theorem Boolos: "D (F (s (s (s (s e)))) (s (s (s (s e)))))"
proof-
have L1: "\<forall>X::i\<Rightarrow>bool. induct X \<longrightarrow> (\<forall>z. N z \<longrightarrow> X z)" using N_def by fastforce
have L2: "induct N" by (metis N_def induct_def)
have L3: "induct D" by (simp add: A4 A5 induct_def)
have L4: "N (s (s (s (s e))))" by (metis L2 induct_def)
have L5: "P1 e e" by (metis A1 L2 P1_def induct_def)
have L6: "\<forall>x. P1 e x \<longrightarrow> P1 e (s x)" by (metis A2 P1_def induct_def L2)
have L7: "induct (P1 e)" using induct_def L5 L6 by auto
have L8: "\<forall>x. P1 (s x) e" by (metis A1 P1_def induct_def L2)
have L9: "P2 e" by (metis L1 L7 P2_def)
have L10: "\<forall>x. P2 x \<longrightarrow> (\<forall>y. P1 (s x) y \<longrightarrow> P1 (s x) (s y))" by (metis A3 P1_def P2_def)
have L11: "\<forall>x. P2 x \<longrightarrow> P2 (s x)" by (metis L1 L10 L8 P2_def induct_def)
have L12: "induct P2" by (simp add: L11 L9 induct_def)
thus ?thesis using L3 L4 N_def P1_def P2_def by blast
qed
end
|
lemma openin_components_locally_connected: "\<lbrakk>locally connected S; c \<in> components S\<rbrakk> \<Longrightarrow> openin (top_of_set S) c"
|
function varargout = process_evt_simple( varargin )
% PROCESS_EVT_SIMPLE: Convert extended events to simple events
%
% USAGE: OutputFiles = process_evt_simple('Run', sProcess, sInput)
% @=============================================================================
% This function is part of the Brainstorm software:
% https://neuroimage.usc.edu/brainstorm
%
% Copyright (c) University of Southern California & McGill University
% This software is distributed under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPLv3
% license can be found at http://www.gnu.org/copyleft/gpl.html.
%
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%
% For more information type "brainstorm license" at command prompt.
% =============================================================================@
%
% Authors: Francois Tadel, 2015-2018
eval(macro_method);
end
%% ===== GET DESCRIPTION =====
function sProcess = GetDescription() %#ok<DEFNU>
% Description the process
sProcess.Comment = 'Convert to simple event';
sProcess.Category = 'File';
sProcess.SubGroup = 'Events';
sProcess.Index = 63;
sProcess.Description = 'https://neuroimage.usc.edu/brainstorm/Tutorials/EventMarkers#Other_menus';
% Definition of the input accepted by this process
sProcess.InputTypes = {'data', 'raw', 'matrix'};
sProcess.OutputTypes = {'data', 'raw', 'matrix'};
sProcess.nInputs = 1;
sProcess.nMinFiles = 1;
% Event name
sProcess.options.eventname.Comment = 'Event names: ';
sProcess.options.eventname.Type = 'text';
sProcess.options.eventname.Value = '';
% Time offset
sProcess.options.method.Comment = {'Keep the start of the events', 'Keep the middle of the events', 'Keep the end of the events'};
sProcess.options.method.Type = 'radio';
sProcess.options.method.Value = 1;
end
%% ===== FORMAT COMMENT =====
function Comment = FormatComment(sProcess) %#ok<DEFNU>
Comment = sProcess.Comment;
end
%% ===== RUN =====
function OutputFile = Run(sProcess, sInput) %#ok<DEFNU>
% Return all the input files
OutputFile = {sInput.FileName};
% ===== GET OPTIONS =====
% Time offset
switch (sProcess.options.method.Value)
case 1, Method = 'start';
case 2, Method = 'middle';
case 3, Method = 'end';
end
% Event names
EvtNames = strtrim(str_split(sProcess.options.eventname.Value, ',;'));
if isempty(EvtNames)
bst_report('Error', sProcess, [], 'No events selected.');
return;
end
% ===== LOAD FILE =====
% Get file descriptor
isRaw = strcmpi(sInput.FileType, 'raw');
% Load the raw file descriptor
if isRaw
DataMat = in_bst_data(sInput.FileName, 'F');
sEvents = DataMat.F.events;
sFreq = DataMat.F.prop.sfreq;
else
DataMat = in_bst_data(sInput.FileName, 'Events', 'Time');
sEvents = DataMat.Events;
sFreq = 1 ./ (DataMat.Time(2) - DataMat.Time(1));
end
% If no markers are present in this file
if isempty(sEvents)
bst_report('Error', sProcess, sInput, 'This file does not contain any event.');
return;
end
% Find event names
iEvtList = [];
for i = 1:length(EvtNames)
iEvt = find(strcmpi(EvtNames{i}, {sEvents.label}));
if isempty(iEvt)
bst_report('Warning', sProcess, sInput, 'This file does not contain any event.');
elseif isempty(sEvents(iEvt).times)
bst_report('Warning', sProcess, sInput, ['Event category "' sEvents(iEvt).label '" is empty.']);
elseif (size(sEvents(iEvt).times,1) == 1)
bst_report('Warning', sProcess, sInput, ['Event category "' sEvents(iEvt).label '" already contains simple events.']);
else
iEvtList(end+1) = iEvt;
end
end
% No events to process
if isempty(iEvtList)
bst_report('Error', sProcess, sInput, 'No events to process.');
return;
end
% ===== PROCESS EVENTS =====
for i = 1:length(iEvtList)
switch Method
case 'start'
sEvents(iEvtList(i)).times = sEvents(iEvtList(i)).times(1,:);
case 'middle'
sEvents(iEvtList(i)).times = mean(sEvents(iEvtList(i)).times,1);
case 'end'
sEvents(iEvtList(i)).times = sEvents(iEvtList(i)).times(2,:);
end
sEvents(iEvtList(i)).times = round(sEvents(iEvtList(i)).times .* sFreq) / sFreq;
end
% ===== SAVE RESULT =====
% Report results
if isRaw
DataMat.F.events = sEvents;
else
DataMat.Events = sEvents;
end
% Only save changes if something was change
bst_save(file_fullpath(sInput.FileName), DataMat, 'v6', 1);
end
|
# Mínimos Cuadrados
## Descomposición $QR$
```python
import numpy as np
import scipy.linalg as spla
import matplotlib.pyplot as plt
```
```python
def plotVector(A, Q):
plt.figure(figsize=(6, 6))
origin = [0], [0] # origin point
plt.quiver(*origin, A[:,0], A[:,1], angles='xy', scale_units='xy', scale=1, color=['green', 'black'])
plt.quiver(*origin, Q.T[:,0], Q.T[:,1], angles='xy', scale_units='xy', scale=1, color=['r', 'b'])
plt.axis('square')
plt.xlim([-2, 4])
plt.ylim([-2, 4])
plt.grid(True)
plt.xlabel(r"$x$")
plt.ylabel(r"$y$")
plt.show()
```
### Decomposición $QR$ reducida
```python
def QR(A, modified=True):
m, n = A.shape
Q = np.zeros((m, n))
R = np.zeros((n, n))
# Gram-Schmidt orthogonalization
for j in range(n):
y = A[:, j]
if modified:
for i in range(j):
R[i, j] = np.dot(Q[:, i], y)
y = y - R[i, j] * Q[:, i]
else:
for i in range(j):
R[i, j] = np.dot(Q[:, i], A[:, j])
y = y - R[i, j] * Q[:, i]
R[j, j] = np.linalg.norm(y)
Q[:, j] = y / R[j, j]
return Q, R
```
### Ejemplo en $\mathbb{R}^2$
Para considerar el manejo de arreglos de ```numpy```, recordar que el procedimiento lo realizamos por vectores columnas, es decir,
\begin{equation}
A=
\left[
\begin{array}{c|c}
& \\
\mathbf{a}_1 & \mathbf{a}_2 \\
& \\
\end{array}
\right].
\end{equation}
```python
A = np.array([[2., 1.], [1., 3.]])
```
```python
A
```
array([[2., 1.],
[1., 3.]])
#### Versión implementada
```python
Q, R = QR(A)
```
```python
np.dot(Q, R)
```
array([[2., 1.],
[1., 3.]])
#### Versión ```numpy```
```python
Q2, R2 = np.linalg.qr(A)
```
```python
np.dot(Q2, R2)
```
array([[2., 1.],
[1., 3.]])
```python
print("Implementado")
print("Q:\n", Q)
print("R:\n", R)
print()
print("Numpy")
print("Q:\n", Q2)
print("R:\n", R2)
```
Implementado
Q:
[[ 0.89442719 -0.4472136 ]
[ 0.4472136 0.89442719]]
R:
[[2.23606798 2.23606798]
[0. 2.23606798]]
Numpy
Q:
[[-0.89442719 -0.4472136 ]
[-0.4472136 0.89442719]]
R:
[[-2.23606798 -2.23606798]
[ 0. 2.23606798]]
La implementación de ```numpy``` no realiza la consideración de $r_{j,j} > 0$.
### ¿Son ortogonales?
```python
np.dot(Q[:,0], Q[:, 1]), np.dot(Q2[:,0], Q2[:, 1])
```
(0.0, -5.551115123125783e-17)
Al parecer sí :)
### ¿Se cumple $Q^{-1}=Q^*$?
```python
np.linalg.inv(Q), Q.T
```
(array([[ 0.89442719, 0.4472136 ],
[-0.4472136 , 0.89442719]]),
array([[ 0.89442719, 0.4472136 ],
[-0.4472136 , 0.89442719]]))
```python
np.linalg.inv(Q2), Q2.T
```
(array([[-0.89442719, -0.4472136 ],
[-0.4472136 , 0.89442719]]),
array([[-0.89442719, -0.4472136 ],
[-0.4472136 , 0.89442719]]))
Al parecer también.
### Visualmente
```python
plotVector(A, Q)
```
Los vectores verde y negro corresponde a los vectores columnas de $A$. Los vectores rojo y azul corresponde a los vectores ortonormales encontrados por $QR$.
# Ajuste de curvas
## Resolución de mínimos cuadrados utilizando $QR$
```python
def QRLS(A, b):
Q, R = QR(A) # QR reduced
x = spla.solve_triangular(R, np.dot(Q.T, b)) # Solve Rx=Q^*b
return x
```
```python
def plot(t, y, tt, yy, yyy):
plt.figure(figsize=(12, 6))
plt.plot(t, y, 'r.')
plt.plot(tt, yy, label="Normal Equations")
plt.plot(tt, yyy, label="QR")
plt.grid(True)
plt.legend()
plt.xlabel(r'$t$')
plt.ylabel(r'$y$')
plt.show()
```
## Ecuaciones normales
```python
lm = lambda c_1, c_2, t: c_1 + c_2 * t
qm = lambda c_1, c_2, c_3, t: c_1 + c_2 * t + c_3 * t ** 2
em = lambda c_1, c_2, t: c_1 * np.exp(c_2 * t)
sm = lambda c_1, c_2, c_3, c_4, t: c_1 + c_2 * np.cos(2 * np.pi * t) + c_3 * np.sin(2 * np.pi * t) + c_4 * np.cos(4 * np.pi * t)
pm = lambda c_1, c_2, t: c_1 * t ** c_2
```
```python
# A^*A x = A^* b
def normalEquations(A, b):
return np.linalg.solve(np.dot(A.T, A), np.dot(A.T, b))
```
#### Modelo lineal
```python
lm = lambda c_1, c_2, t: c_1 + c_2 * t
```
```python
n = 200
t_a, t_b = 0, 3
t = np.linspace(t_a, t_b, n)
tt = np.linspace(t_a, t_b, 3 * n)
```
```python
y_l = lm(1, 2, t) + np.random.normal(1.5, .5, n) # Data
A_l = np.ones((n, 2))
A_l[:,1] = t
b_l = y_l
```
```python
p_l = normalEquations(A_l, b_l)
```
```python
p_l_qr = QRLS(A_l, b_l)
```
```python
p_l, p_l_qr
```
(array([2.61872557, 1.92680618]), array([2.61872557, 1.92680618]))
```python
plot(t, y_l, tt, lm(*p_l, tt), lm(*p_l_qr, tt))
```
Podemos ver para ambos métodos obtenemos los mismos coeficientes del modelo lineal.
## Cuadrático
```python
y_q = qm(1, 2, 3, t) + np.random.normal(5, 3, n)
A_q = np.ones((n, 3))
A_q[:, 1] = t
A_q[:, 2] = t ** 2
b_q = y_q
```
```python
p_l = normalEquations(A_q, b_q)
```
```python
p_l_qr = QRLS(A_q, b_q)
```
```python
plot(t, y_q, tt, qm(*p_l, tt), qm(*p_l_qr, tt))
```
## Periódico
```python
y_s = sm(1, 2, 2, 1, t) + np.random.normal(10, 2, n)
A_s = np.ones((n, 4))
A_s[:, 1] = np.cos(2 * np.pi * t)
A_s[:, 2] = np.sin(2 * np.pi * t)
A_s[:, 3] = np.cos(4 * np.pi * t)
b_s = y_s
```
```python
p_l = normalEquations(A_s, b_s)
```
```python
p_l_qr = QRLS(A_s, b_s)
```
```python
plot(t, y_s, tt, sm(*p_l, tt), sm(*p_l_qr, tt))
```
## Exponencial
```python
y_e = em(1, 2, t) * np.random.normal(10, 2, n)
A_e = np.ones((n, 2))
A_e[:, 1] = t
b_e = np.log(y_e)
```
```python
p_l = normalEquations(A_e, b_e)
```
```python
p_l_qr = QRLS(A_e, b_e)
```
```python
plot(t, y_e, tt, em(np.exp(p_l[0]), p_l[1], tt), em(np.exp(p_l_qr[0]), p_l_qr[1], tt))
```
## Comentarios
Podemos obtener los mismos resultados al utilizar **Ecuaciones Normales** que al usar la **Descomposición $QR$**. En teoría hay un método que requiere menos computación, ¿puede mostrarlo experimentalmente?
## Ejemplo 4.16 del libro guía p. 219
### ¿Por qué Gram-Schmidt modificado sobre el clásico?
```python
d = 1e-10
Ab = np.array([
[1, 1, 1],
[d, 0, 0],
[0, d, 0],
[0, 0, d]
])
```
### Clásico
```python
Qbc, Rbc = QR(Ab, False)
```
```python
print("Q:\n", Qbc)
print("R:\n", Rbc)
```
Q:
[[ 1.00000000e+00 0.00000000e+00 0.00000000e+00]
[ 1.00000000e-10 -7.07106781e-01 -7.07106781e-01]
[ 0.00000000e+00 7.07106781e-01 0.00000000e+00]
[ 0.00000000e+00 0.00000000e+00 7.07106781e-01]]
R:
[[1.00000000e+00 1.00000000e+00 1.00000000e+00]
[0.00000000e+00 1.41421356e-10 0.00000000e+00]
[0.00000000e+00 0.00000000e+00 1.41421356e-10]]
¿$Q^*Q = I$?
```python
QTQ_c = np.dot(Qbc.T, Qbc)
QTQ_c
```
array([[ 1.00000000e+00, -7.07106781e-11, -7.07106781e-11],
[-7.07106781e-11, 1.00000000e+00, 5.00000000e-01],
[-7.07106781e-11, 5.00000000e-01, 1.00000000e+00]])
¿$\|Q^*Q - I_n\|_F$?
```python
print(np.linalg.norm(QTQ_c - np.eye(3)))
```
0.7071067811865477
### Modificado
```python
Qbm, Rbm = QR(Ab)
```
```python
print("Q:\n", Qbm)
print("R:\n", Rbm)
```
Q:
[[ 1.00000000e+00 0.00000000e+00 0.00000000e+00]
[ 1.00000000e-10 -7.07106781e-01 -4.08248290e-01]
[ 0.00000000e+00 7.07106781e-01 -4.08248290e-01]
[ 0.00000000e+00 0.00000000e+00 8.16496581e-01]]
R:
[[1.00000000e+00 1.00000000e+00 1.00000000e+00]
[0.00000000e+00 1.41421356e-10 7.07106781e-11]
[0.00000000e+00 0.00000000e+00 1.22474487e-10]]
¿$Q^*Q = I$?
```python
QTQ_m = np.dot(Qbm.T, Qbm)
QTQ_m
```
array([[ 1.00000000e+00, -7.07106781e-11, -4.08248290e-11],
[-7.07106781e-11, 1.00000000e+00, -1.66533454e-16],
[-4.08248290e-11, -1.66533454e-16, 1.00000000e+00]])
¿$\|Q^*Q - I_n\|_F$?
```python
print(np.linalg.norm(QTQ_m - np.eye(3)))
```
1.1547005383859233e-10
Experimentalmente podemos ver que en este ejemplo los vectores de $Q$ obtenidos con el algoritmo clásico no son ortonormales. Notamos que con el algoritmo modificado no obtenemos $I_n$ exactamente, pero el resultado es mejor.
|
(** * 6.887 Formal Reasoning About Programs, Spring 2016 - Pset 4 *)
Require Import Frap.
(* Authors: Peng Wang ([email protected]), Adam Chlipala ([email protected]) *)
(* In Lab 4, we saw a few ways to model function calls with operational
* semantics. In this problem set, we extend the picture with *exceptions*,
* including their interactions with function calls. But first, the same old
* boring language of expressions. *)
Inductive arith : Set :=
| Const (n : nat)
| Var (x : var)
| Plus (e1 e2 : arith)
| Minus (e1 e2 : arith)
| Times (e1 e2 : arith).
Definition valuation := fmap var nat.
Inductive cmd :=
| Skip
| Assign (x : var) (e : arith)
| Sequence (c1 c2 : cmd)
| If (e : arith) (then_ else_ : cmd)
| While (e : arith) (body : cmd)
| Call (lhs f : var) (arg : arith)
| InCall (v : valuation) (lhs ret : var) (c : cmd)
(* The new cases: *)
| Try (try : cmd) (exn : var) (handler : cmd)
(* Run [try]. If it throws an uncaught exception, switch to running [handler],
* with variable [exn] bound to the exception that was thrown. *)
| Throw (e : arith).
(* Abort normal execution, throwing the value of [e]. *)
(* Boring old expression interpreter *)
Fixpoint interp (e : arith) (v : valuation) : nat :=
match e with
| Const n => n
| Var x =>
match v $? x with
| None => 0
| Some n => n
end
| Plus e1 e2 => interp e1 v + interp e2 v
| Minus e1 e2 => interp e1 v - interp e2 v
| Times e1 e2 => interp e1 v * interp e2 v
end.
(* Function specifications, as in the lab *)
Record fun_spec := {
Arg : var;
Ret : var;
Body : cmd
}.
Definition environment := fmap var fun_spec.
(* To describe the results of our big-step semantics, we need this new type. *)
Inductive outcome :=
| Normal
(* Execution finished normally. *)
| Exception (exn : nat).
(* Execution finished with this uncaught exception.
* Note that our exceptions are numbers, since our expressions all evaluate to
* numbers. *)
Section env.
Variable env : environment.
(** Big-step semantics *)
Inductive eval : valuation -> cmd -> outcome * valuation -> Prop :=
| EvalSkip : forall v,
eval v Skip (Normal, v)
(* Note that the old rules tend to return [Normal] values. *)
| EvalAssign : forall v x e,
eval v (Assign x e) (Normal, v $+ (x, interp e v))
| EvalSeq : forall v c1 v1 c2 ov2,
eval v c1 (Normal, v1)
-> eval v1 c2 ov2
-> eval v (Sequence c1 c2) ov2
(* However, this rule passes along whatever is the outcome [ov2] of the
* second command, be it normal or exceptional. *)
| EvalSeqExn : forall v c1 exn v1 c2,
eval v c1 (Exception exn, v1)
-> eval v (Sequence c1 c2) (Exception exn, v1)
(* This second [Seq] rule handles the case where the first command raises an
* exception. *)
| EvalIfTrue : forall v e then_ else_ ov',
interp e v <> 0
-> eval v then_ ov'
-> eval v (If e then_ else_) ov'
| EvalIfFalse : forall v e then_ else_ ov',
interp e v = 0
-> eval v else_ ov'
-> eval v (If e then_ else_) ov'
| EvalWhileTrue : forall v e body v' ov'',
interp e v <> 0
-> eval v body (Normal, v')
-> eval v' (While e body) ov''
-> eval v (While e body) ov''
| EvalWhileTrueExn : forall v e body exn v',
interp e v <> 0
-> eval v body (Exception exn, v')
-> eval v (While e body) (Exception exn, v')
| EvalWhileFalse : forall v e body,
interp e v = 0
-> eval v (While e body) (Normal, v)
| EvalCall : forall v lhs f arg spec v',
env $? f = Some spec
-> eval ($0 $+ (spec.(Arg), interp arg v)) spec.(Body) (Normal, v')
-> eval v (Call lhs f arg) (Normal, v $+ (lhs, interp (Var spec.(Ret)) v'))
| EvalCallExn : forall v lhs f arg spec exn v',
env $? f = Some spec
-> eval ($0 $+ (spec.(Arg), interp arg v)) spec.(Body) (Exception exn, v')
-> eval v (Call lhs f arg) (Exception exn, v)
(* Note the crucial difference between the two [EvalCall] rules: with a
* normal outcome (other rule) of the called function, we extend the
* valuation with the return value. In case of an exception (this rule), we
* leave the valuation alone. *)
| EvalTry : forall v c v' x handler,
eval v c (Normal, v')
-> eval v (Try c x handler) (Normal, v')
(* Normal evaluation of a [try] body bubbles out of the [try]. *)
| EvalTryExn : forall v c exn v' x handler ov'',
eval v c (Exception exn, v')
-> eval (v' $+ (x, exn)) handler ov''
-> eval v (Try c x handler) ov''
(* Exceptional evaluation of the body switches to running the handler. *)
| EvalThrow : forall v e,
eval v (Throw e) (Exception (interp e v), v)
(* Throwing generates the expected exceptional outcome. *)
| EvalInCall : forall v0 lhs ret v c v',
eval v c (Normal, v')
-> eval v (InCall v0 lhs ret c) (Normal, v0 $+ (lhs, interp (Var ret) v'))
| EvalInCallExn : forall v0 lhs ret v c exn v',
eval v c (Exception exn, v')
-> eval v (InCall v0 lhs ret c) (Exception exn, v0).
(* Finally, two goofy rules just to make this semantics complete for
* [InCall], which we really only need for the small-step semantics. *)
(** Small-step semantics *)
Inductive step : valuation * cmd -> valuation * cmd -> Prop :=
| StepAssign : forall v x e,
step (v, Assign x e) (v $+ (x, interp e v), Skip)
| StepSeq1 : forall v c1 c2 v' c1',
step (v, c1) (v', c1')
-> step (v, Sequence c1 c2) (v', Sequence c1' c2)
| StepSeq2 : forall v c2,
step (v, Sequence Skip c2) (v, c2)
| StepSeqThrow : forall v (n : nat) c2,
step (v, Sequence (Throw (Const n)) c2) (v, Throw (Const n))
(* Note how a [Throw] can bubble up from the first part of a sequence. *)
| StepIfTrue : forall v e then_ else_,
interp e v <> 0
-> step (v, If e then_ else_) (v, then_)
| StepIfFalse : forall v e then_ else_,
interp e v = 0
-> step (v, If e then_ else_) (v, else_)
| StepWhileTrue : forall v e body,
interp e v <> 0
-> step (v, While e body) (v, Sequence body (While e body))
| StepWhileFalse : forall v e body,
interp e v = 0
-> step (v, While e body) (v, Skip)
| StepStartCall : forall v lhs f arg spec,
env $? f = Some spec
-> step (v, Call lhs f arg) ($0 $+ (spec.(Arg), interp arg v), InCall v lhs spec.(Ret) spec.(Body))
| StepInCall : forall v c v' c' v0 lhs ret,
step (v, c) (v', c')
-> step (v, InCall v0 lhs ret c) (v', InCall v0 lhs ret c')
| StepEndCall : forall v0 lhs ret v,
step (v, InCall v0 lhs ret Skip) (v0, Assign lhs (Const (interp (Var ret) v)))
| StepEndCallThrow : forall v0 lhs ret v (n : nat),
step (v, InCall v0 lhs ret (Throw (Const n))) (v0, Throw (Const n))
(* Here we also see a [Throw] bubble up out of a call. That is, the
* callee's uncaught exceptions escape to the caller. *)
| StepTry : forall v c v' c' x handler,
step (v, c) (v', c')
-> step (v, Try c x handler) (v', Try c' x handler)
| StepTryDone : forall v x handler,
step (v, Try Skip x handler) (v, Skip)
| StepTryThrow : forall v (n : nat) x handler,
step (v, Try (Throw (Const n)) x handler) (v $+ (x, n), handler)
(* Exceptions also bubble out of [Try]s, but they go to the handler instead
* of to other surrounding code. (Of course, if the handler raises another
* exception, the adventure continues.) *)
| StepThrow : forall v (e : arith),
(forall n : nat, e <> Const n)
-> step (v, Throw e) (v, Throw (Const (interp e v))).
(* If throwing an expression that isn't fully evaluated, evaluate it before
* continuing. *)
(* Notice how the small-step style was more convenient to update in some
* places. We didn't need to create dual versions of as many rules, for
* the normal and exceptional cases. On the other hand, the "bubbling" rules
* make up for it, so we get just as many rules. *)
(* See the bottom of this file for the theorems we ask you to prove about
* these semantics. *)
(** Small-step semantics with control stack *)
(* Now we take the same step that we finished up with in the lab. *)
Inductive step0 : valuation * cmd -> valuation * cmd -> Prop :=
| Step0Assign : forall v x e,
step0 (v, Assign x e) (v $+ (x, interp e v), Skip)
| Step0IfTrue : forall v e then_ else_,
interp e v <> 0
-> step0 (v, If e then_ else_) (v, then_)
| Step0IfFalse : forall v e then_ else_,
interp e v = 0
-> step0 (v, If e then_ else_) (v, else_)
| Step0WhileTrue : forall v e body,
interp e v <> 0
-> step0 (v, While e body) (v, Sequence body (While e body))
| Step0WhileFalse : forall v e body,
interp e v = 0
-> step0 (v, While e body) (v, Skip)
| Step0Throw : forall v (e : arith),
(forall n : nat, e <> Const n)
-> step0 (v, Throw e) (v, Throw (Const (interp e v))).
(* This last rule is the one new one vs. the lab. It's pretty similar to
* the last rule of the basic small-step semantics. *)
(* Call frames: just as in the lab, with a different name *)
Record call_frame := {
Val : valuation;
Cont : cmd;
LHS : var;
RetVar : var
}.
(* However, now our control stacks have *two* kinds of frames!
* The other represents a pending exception handler. *)
Record handler_frame := {
ExnVar : var; (* In case of uncaught exception, save it to this
* variable... *)
Handler : cmd; (* ...and commence running this command. *)
ExnCont : cmd (* Afterward, run this command. *)
}.
Inductive frame :=
| CallFrame (fr : call_frame)
| HandlerFrame (fr : handler_frame).
Definition stack := list frame.
(* Now we proceed much as in the lab. *)
Inductive stepcs : stack * valuation * cmd * cmd -> stack * valuation * cmd * cmd -> Prop :=
| StepcsStep0 : forall v c v' c' s k,
step0 (v, c) (v', c') ->
stepcs (s, v, c, k) (s, v', c', k)
| StepcsSeq : forall s v c1 c2 k,
stepcs (s, v, Sequence c1 c2, k) (s, v, c1, Sequence c2 k)
| StepcsCont : forall s v k1 k2,
stepcs (s, v, Skip, Sequence k1 k2) (s, v, k1, k2)
| StepcsReturn : forall fr s v,
stepcs (CallFrame fr :: s, v, Skip, Skip) (s, fr.(Val) $+ (fr.(LHS), interp (Var fr.(RetVar)) v), Skip, fr.(Cont))
| StepcsReturnHandlerFrame : forall fr s v,
stepcs (HandlerFrame fr :: s, v, Skip, Skip) (s, v, Skip, fr.(ExnCont))
(* When a command finishes normally and there is a pending exception
* handler, tell that handler "Sorry, Bub; not today!" and pop it off. *)
| StepcsThrowDiscardCont : forall s v n k,
k <> Skip ->
stepcs (s, v, Throw (Const n), k) (s, v, Throw (Const n), Skip)
(* When we throw an exception, discard the continuation, as we will never
* finish normally and get around to running it. *)
| StepcsHandleThrow : forall fr s v (n : nat),
stepcs (HandlerFrame fr :: s, v, Throw (Const n), Skip) (s, v $+ (fr.(ExnVar), n), fr.(Handler), fr.(ExnCont))
(* When throwing with a handler on top of the stack, pop it and start
* running it. *)
| StepcsThrowCallFrame : forall fr s v (n : nat),
stepcs (CallFrame fr :: s, v, Throw (Const n), Skip) (s, fr.(Val), Throw (Const n), Skip)
(* On the other hand, when throwing with a call frame on top, pop it and
* jump past it to the next frame. *)
| StepcsCall : forall s v lhs f arg k spec,
env $? f = Some spec
-> stepcs (s, v, Call lhs f arg, k) (CallFrame {| Val := v; Cont := k; LHS := lhs; RetVar := spec.(Ret)|} :: s, $0 $+ (spec.(Arg), interp arg v), spec.(Body), Skip)
(* Calls proceed as before. *)
| StepcsTry : forall s v c x handler k,
stepcs (s, v, Try c x handler, k) (HandlerFrame {| ExnVar := x; Handler := handler; ExnCont := k|} :: s, v, c, Skip)
(* To run a [Try], install its handler on top of the stack. *)
| StepcsInCall : forall s v0 lhs ret v c k,
stepcs (s, v, InCall v0 lhs ret c, k) (CallFrame {| Val := v0; Cont := k; LHS := lhs; RetVar := ret|} :: s, v, c, Skip).
(* Same goofy [InCall] rule as before *)
End env.
Module Type S.
Section env.
Variable env : environment.
Axiom big_small : forall v c v',
eval env v c (Normal, v')
-> (step env)^* (v, c) (v', Skip).
Axiom big_small_exn : forall v c n v',
eval env v c (Exception n, v')
-> (step env)^* (v, c) (v', Throw (Const n)).
Axiom small_big : forall v c v',
(step env)^* (v, c) (v', Skip)
-> eval env v c (Normal, v').
Axiom small_big_exn : forall v c v' n,
(step env)^* (v, c) (v', Throw (Const n))
-> eval env v c (Exception n, v').
Axiom eval_stepcs : forall v c v',
eval env v c (Normal, v')
-> (stepcs env)^* ([], v, c, Skip) ([], v', Skip, Skip).
Axiom eval_stepcs_exn : forall v c (n : nat) v',
eval env v c (Exception n, v')
-> (stepcs env)^* ([], v, c, Skip) ([], v', Throw (Const n), Skip).
Axiom stepcs_eval : forall v c v',
(stepcs env)^* ([], v, c, Skip) ([], v', Skip, Skip)
-> eval env v c (Normal, v').
Axiom stepcs_eval_exn : forall v c v' (n : nat),
(stepcs env)^* ([], v, c, Skip) ([], v', Throw (Const n), Skip)
-> eval env v c (Exception n, v').
End env.
End S.
|
{-# OPTIONS --sized-types #-}
module FormalLanguage.Equals{ℓ} where
import Lvl
open import FormalLanguage
open import Lang.Size
open import Logic.Propositional
open import Relator.Equals using ([≡]-intro) renaming (_≡_ to _≡ₑ_)
open import Relator.Equals.Proofs
import Structure.Relator.Names as Names
open import Structure.Setoid
open import Structure.Relator.Equivalence
open import Structure.Relator.Properties
open import Type
private variable s : Size
module _ {Σ : Alphabet{ℓ}} where
record _≅[_]≅_ (A : Language(Σ){∞ˢⁱᶻᵉ}) (s : Size) (B : Language(Σ){∞ˢⁱᶻᵉ}) : Type{ℓ} where
constructor intro
coinductive
field
accepts-ε : Language.accepts-ε(A) ≡ₑ Language.accepts-ε(B)
suffix-lang : ∀{c : Σ}{sₛ : <ˢⁱᶻᵉ s} → (Language.suffix-lang A c ≅[ sₛ ]≅ Language.suffix-lang B c)
_≅_ : ∀{s : Size} → Language(Σ){∞ˢⁱᶻᵉ} → Language(Σ){∞ˢⁱᶻᵉ} → Type
_≅_ {s} = _≅[ s ]≅_
[≅]-reflexivity-raw : Names.Reflexivity(_≅[ s ]≅_)
_≅[_]≅_.accepts-ε ([≅]-reflexivity-raw) = [≡]-intro
_≅[_]≅_.suffix-lang ([≅]-reflexivity-raw) = [≅]-reflexivity-raw
[≅]-symmetry-raw : Names.Symmetry(_≅[ s ]≅_)
_≅[_]≅_.accepts-ε ([≅]-symmetry-raw ab) = symmetry(_≡ₑ_) (_≅[_]≅_.accepts-ε ab)
_≅[_]≅_.suffix-lang ([≅]-symmetry-raw ab) = [≅]-symmetry-raw (_≅[_]≅_.suffix-lang ab)
[≅]-transitivity-raw : Names.Transitivity(_≅[ s ]≅_)
_≅[_]≅_.accepts-ε ([≅]-transitivity-raw ab bc) = transitivity(_≡ₑ_) (_≅[_]≅_.accepts-ε ab) (_≅[_]≅_.accepts-ε bc)
_≅[_]≅_.suffix-lang ([≅]-transitivity-raw ab bc) = [≅]-transitivity-raw (_≅[_]≅_.suffix-lang ab) (_≅[_]≅_.suffix-lang bc)
instance
[≅]-reflexivity : Reflexivity(_≅[ s ]≅_)
Reflexivity.proof([≅]-reflexivity) = [≅]-reflexivity-raw
instance
[≅]-symmetry : Symmetry(_≅[ s ]≅_)
Symmetry.proof([≅]-symmetry) = [≅]-symmetry-raw
instance
[≅]-transitivity : Transitivity(_≅[ s ]≅_)
Transitivity.proof([≅]-transitivity) = [≅]-transitivity-raw
instance
[≅]-equivalence : Equivalence(_≅[ s ]≅_)
[≅]-equivalence = record{}
instance
[≅]-equiv : let _ = s in Equiv(Language(Σ))
[≅]-equiv {s = s} = intro(_≅[ s ]≅_) ⦃ [≅]-equivalence ⦄
|
# Solving vertex cover with a quantum annealer
The problem of vertex cover is, given an undirected graph $G = (V, E)$, colour the smallest amount of vertices such that each edge $e \in E$ is connected to a coloured vertex.
This notebooks works through the process of creating a random graph, translating to an optimization problem, and eventually finding the ground state using a quantum annealer.
### Graph setup
The first thing we will do is create an instance of the problem, by constructing a small, random undirected graph. We are going to use the `networkx` package, which should already be installed if you have installed if you are using Anaconda.
```python
import dimod
import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
```
```python
n_vertices = 5
n_edges = 6
small_graph = nx.gnm_random_graph(n_vertices, n_edges)
```
```python
nx.draw(small_graph, with_labels=True)
```
### Constructing the Hamiltonian
I showed in class that the objective function for vertex cover looks like this:
\begin{equation}
\sum_{(u,v) \in E} (1 - x_u) (1 - x_v) + \gamma \sum_{v \in V} x_v
\end{equation}
We want to find an assignment of the $x_u$ of 1 (coloured) or 0 (uncoloured) that _minimizes_ this function. The first sum tries to force us to choose an assignment that makes sure every edge gets attached to a coloured vertex. The second sum is essentially just counting the number of coloured vertices.
**Task**: Expand out the QUBO above to see how you can convert it to a more 'traditional' looking QUBO:
\begin{equation}
\sum_{(u,v) \in E} x_u x_v + \sum_{v \in V} (\gamma - \text{deg}(x_v)) x_v
\end{equation}
where deg($x_v$) indicates the degree of vertex $x_v$ in the graph.
```python
γ = 0.8
Q = {x : 1 for x in small_graph.edges()}
r = {x : (γ - small_graph.degree[x]) for x in small_graph.nodes}
```
Let's convert it to the appropriate data structure, and solve using the exact solver.
```python
bqm = dimod.BinaryQuadraticModel(r, Q, 0, dimod.BINARY)
response = dimod.ExactSolver().sample(bqm)
print(f"Sample energy = {next(response.data(['energy']))[0]}")
```
Let's print the graph with proper colours included
```python
colour_assignments = next(response.data(['sample']))[0]
colours = ['grey' if colour_assignments[x] == 0 else 'red' for x in range(len(colour_assignments))]
nx.draw(small_graph, with_labels=True, node_color=colours)
```
### Scaling up...
That one was easy enough to solve by hand. Let's try a much larger instance...
```python
n_vertices = 20
n_edges = 60
large_graph = nx.gnm_random_graph(n_vertices, n_edges)
nx.draw(large_graph, with_labels=True)
```
```python
# Create h, J and put it into the exact solver
γ = 0.8
Q = {x : 1 for x in large_graph.edges()}
r = {x : (γ - large_graph.degree[x]) for x in large_graph.nodes}
bqm = dimod.BinaryQuadraticModel(r, Q, 0, dimod.BINARY)
response = dimod.ExactSolver().sample(bqm)
print(f"Sample energy = {next(response.data(['energy']))[0]}")
colour_assignments = next(response.data(['sample']))[0]
colours = ['grey' if colour_assignments[x] == 0 else 'red' for x in range(len(colour_assignments))]
nx.draw(large_graph, with_labels=True, node_color=colours)
print(f"Coloured {list(colour_assignments.values()).count(1)}/{n_vertices} vertices.")
```
### Running on the D-Wave
You'll only be able to run the next few cells if you have D-Wave access. We will send the same graph as before to the D-Wave QPU and see what kind of results we get back!
```python
from dwave.system.samplers import DWaveSampler
from dwave.system.composites import EmbeddingComposite
sampler = EmbeddingComposite(DWaveSampler())
```
```python
ising_conversion = bqm.to_ising()
h, J = ising_conversion[0], ising_conversion[1]
response = sampler.sample_ising(h, J, num_reads = 1000)
```
```python
best_solution =np.sort(response.record, order='energy')[0]
```
```python
print(f"Sample energy = {best_solution['energy']}")
colour_assignments_qpu = {x : best_solution['sample'][x] for x in range(n_vertices)}
for x in range(n_vertices):
if colour_assignments_qpu[x] == -1:
colour_assignments_qpu[x] = 0
colours = ['grey' if colour_assignments_qpu[x] == 0 else 'red' for x in range(len(colour_assignments_qpu))]
nx.draw(large_graph, with_labels=True, node_color=colours)
print(f"Coloured {list(colour_assignments_qpu.values()).count(1)}/{n_vertices} vertices.")
```
```python
print("Node\tExact\tQPU")
for x in range(n_vertices):
print(f"{x}\t{colour_assignments[x]}\t{colour_assignments_qpu[x]}")
```
Here is a scatter plot of all the different energies we got out, against the number of times each solution occurred.
```python
plt.scatter(response.record['energy'], response.record['num_occurrences'])
```
```python
response.record['num_occurrences']
```
|
%!TEX root = ../ESyS-ParticleNotes.tex
\chapter{ESyS-Particle Release Steps}
\label{cha:esys_particle_release_steps}
Described in this section is the steps needed to create a new release for ESyS-Particle.
\begin{enumerate}
\item Write release notes at \url{https://wiki.geocomp.uq.edu.au/index.php/Release_Notes_for_ESyS-Particle}
\item Update version information in \lstinline{configure.ac}, \lstinline{Doxyfile}, \lstinline{Doc/Tutorial/paper.tex}, \lstinline{Foundation/version.h}
\item Update the tutorial if necessary and generate the new PDF file:
\lstinline{./render.sh} in \lstinline{Doc/Tutorial/}
\item Upload the new file to \url{https://wiki.geocomp.uq.edu.au/index.php/File:ESyS-Particle_Tutorial.pdf}
\item Update the trunk:
\lstinline{bzr commit}
\item Generate an updated API by building the code using the \lstinline{--with-epydoc} option
\item Copy the API to \url{shake200:/data/www/esys/esys-particle_python_doc/esys-particle-2.3.1}
\item Generate updated source code documentation:
\lstinline{doxygen Doxyfile}
\item Copy the source code documentation to \url{shake200:/data/www/esys/esys-particle_doxygen_doc/esys-particle-2.3.1}
\item Branch from the trunk:
\lstinline{bzr branch lp:esys-particle source2.3.1}
\item Push the new branch to Launchpad:
\lstinline{bzr push lp:~esys-p-dev/esys-particle/2.3.1}
\item Change the new branch status to ``Mature'':
Code page $\rightarrow$ \lstinline{lp:~esys-p-dev/esys-particle/2.3.1} $\rightarrow$ Status
\end{enumerate}
\textit{For major version:}
\begin{enumerate} \parskip0pt \parsep0pt
\itshape
\setcounter{enumi}{12}
\item Create series 2.3:
Project overview page $\rightarrow$ Register a series
\item Link the mainline branch for the series: 2.3 Series page
\end{enumerate}
\begin{enumerate}
\setcounter{enumi}{14}
\item Create a 2.3 series milestone:
2.3 Series page $\rightarrow$ Create milestone: Name: 2.3.1
\item Link fixed and committed bugs to the milestone, if any exist:
Bugs page $\rightarrow$ Target to milestone
\item Create a 2.3 series release:
2.3 Series page $\rightarrow$ Create release
\item Make a new tarball:
\lstinline{tar -cavf ESyS-Particle-2.3.1.tar.gz --exclude-vcs *}
\item Create a signature for the tarball:
\lstinline{gpg --armor --sign --detach-sig ESyS-Particle-2.3.1.tar.gz}
\begin{itemize}
\item if no keys has been defined in the system, generate the keys by using:
\lstinline{gpg --gen-key}
\item and afterwards, the key would need to be uploaded to the server:
\lstinline{gpg --keyserver `hkp://keys.gnupg.net' --send keys <key-ids>}
the key id can be found using: \lstinline{gpg --list-keys}
\end{itemize}
\item Upload the new tarball and signature:
Milestone page $\rightarrow$ Add download file
\item Change the 2.3 series status from ``Active Development'' to ``Current Stable Release'': 2.3 Series page
\item Change the status of bugs fixed for the release from ``Fix Committed'' to ``Fix Released'': Bugs page
\end{enumerate}
|
import numpy as np
from chains.utils import validate
from .ops import Op
from .static_shape import StaticShape
from .tensor import Tensor
from ..core import utils_conv as uc
__all__ = ["MaxPool"]
class MaxPool(Op):
def __init__(self, stride=2, conv_format=uc.NCHW):
super().__init__()
validate.is_strictly_greater_than("stride", stride, 1)
self.conv_format = conv_format
self.stride = stride
self.features_nchw = None
self.max_indices = None
self.filters_shape = None
self.x_shape = None
self.xc_shape = None
def check_incoming_shapes(self, features: StaticShape):
if features.ndim != 4:
raise ValueError(f"features should be a 4 dimensional tensor "
f"but got {features.ndim} dimensions")
m, c, nh, nw = self.conv_format.nchw(features)
s = self.stride
if nh.value % s != 0:
raise ValueError(
f"Height ({nh.value}) should be a multiple of stride {s} "
f"but is not")
if nw.value % s != 0:
raise ValueError(
f"Width ({nw.value}) should be a multiple of stride {s} "
f"but is not")
def compute_out_shape(self, features: StaticShape) -> StaticShape:
m, c, nh, nw = self.conv_format.nchw(features)
out_h, out_w = uc.clip_positions_count(nh.value, nw.value, self.stride,
self.stride, 0,
self.stride)
tup = self.conv_format.nchw_inv(StaticShape(m, c, out_h, out_w))
return StaticShape.from_tuple(tup)
def compute(self, features: Tensor):
self.features_nchw = self.conv_format.nchw(features)
m, c, nh, nw = self.features_nchw.shape
out_h, out_w = uc.clip_positions_count(nh, nw, self.stride,
self.stride, 0, self.stride)
self.x_shape = (m * c, 1, nh, nw)
self.filters_shape = (m, 1, self.stride, self.stride)
x = np.reshape(self.features_nchw, self.x_shape)
xc = uc.im2col(x, self.filters_shape, padding=0, stride=self.stride)
self.xc_shape = xc.shape
self.max_indices = np.argmax(xc, axis=0)
out = xc[self.max_indices, range(self.max_indices.size)]
out = out.reshape(m, c, out_h, out_w)
self.output = self.conv_format.nchw_inv(out)
def partials(self, d_output: Tensor):
m, c, nh, nw = self.features_nchw.shape
d_out = self.conv_format.nchw(d_output)
mm, dd, out_h, out_w = d_out.shape
assert mm == m, f"Number of examples im activations({m}) is " \
f"different from number of examples in output derivatives({mm})"
d_out_flat = np.ravel(d_out)
d_xc = np.zeros(self.xc_shape)
d_xc[self.max_indices, range(self.max_indices.size)] = d_out_flat
dx = uc.col2im(d_xc, self.x_shape, self.filters_shape, padding=0,
stride=self.stride)
d_features = np.reshape(dx, self.features_nchw.shape)
return self.conv_format.nchw_inv(d_features),
|
From Undecidability Require Import TM.Util.Prelim TM.Util.TM_facts.
Set Default Goal Selector "!".
(* * Mirror Operator *)
Section Mirror.
Variable (n : nat) (sig : finType).
Definition mirror_act : (option sig * move) -> (option sig * move) :=
map_snd mirror_move.
Definition mirror_acts : Vector.t (option sig * move) n -> Vector.t (option sig * move) n :=
Vector.map mirror_act.
Variable F : finType.
Variable pM : pTM sig F n.
Definition Mirror_trans :
state (projT1 pM) * Vector.t (option sig) n ->
state (projT1 pM) *
Vector.t (option sig * move) n :=
fun qsym =>
let (q', act) := trans qsym in
(q', mirror_acts act).
Definition MirrorTM : TM sig n :=
{|
trans := Mirror_trans;
start := start (projT1 pM);
halt := halt (m := projT1 pM);
|}.
Definition Mirror : pTM sig F n :=
(MirrorTM; projT2 pM).
Definition mirrorConf : mconfig sig (state (projT1 pM)) n -> mconfig sig (state (projT1 pM)) n :=
fun c => mk_mconfig (cstate c) (mirror_tapes (ctapes c)).
Lemma mirrorConf_involution c : mirrorConf (mirrorConf c) = c.
Proof. destruct c as [q t]. unfold mirrorConf. cbn. f_equal. apply mirror_tapes_involution. Qed.
Lemma mirrorConf_injective c1 c2 : mirrorConf c1 = mirrorConf c2 -> c1 = c2.
Proof. destruct c1 as [q1 t1], c2 as [q2 t2]. unfold mirrorConf. cbn. intros H; inv H. f_equal. now apply mirror_tapes_injective. Qed.
Lemma current_chars_mirror_tapes (t : tapes sig n) :
current_chars (mirror_tapes t) = current_chars t.
Proof. apply Vector.eq_nth_iff; intros i ? <-. autounfold with tape. now simpl_tape. Qed.
Lemma doAct_mirror (t : tape sig) (act : option sig * move) :
doAct (mirror_tape t) act = mirror_tape (doAct t (mirror_act act)).
Proof. now destruct act as [ [ s | ] [ | | ]]; cbn; simpl_tape. Qed.
Lemma doAct_mirror_multi (t : tapes sig n) (acts : Vector.t (option sig * move) n) :
doAct_multi (mirror_tapes t) acts = mirror_tapes (doAct_multi t (mirror_acts acts)).
Proof. apply Vector.eq_nth_iff; intros i ? <-. unfold doAct_multi, mirror_acts, mirror_tapes. simpl_tape. apply doAct_mirror. Qed.
Lemma mirror_step c :
step (M := projT1 pM) (mirrorConf c) = mirrorConf (step (M := projT1 Mirror) c).
Proof.
unfold step; cbn -[doAct_multi]. unfold Mirror_trans. cbn.
destruct c as [q t]; cbn. rewrite current_chars_mirror_tapes.
destruct (trans (q, current_chars t)) as [q' acts].
unfold mirrorConf; cbn. f_equal. apply doAct_mirror_multi.
Qed.
Lemma mirror_lift k c1 c2 :
loopM (M := projT1 Mirror) c1 k = Some c2 ->
loopM (M := projT1 pM ) (mirrorConf c1) k = Some (mirrorConf c2).
Proof.
unfold loopM. intros HLoop.
apply loop_lift with (lift := mirrorConf) (f' := step (M:=projT1 pM)) (h' := haltConf (M:=projT1 pM)) in HLoop; auto.
- intros ? _. now apply mirror_step.
Qed.
Lemma mirror_unlift k c1 c2 :
loopM (M := projT1 pM) (mirrorConf c1) k = Some (mirrorConf c2) ->
loopM (M := projT1 Mirror) ( c1) k = Some ( c2).
Proof.
unfold loopM. intros HLoop.
apply loop_unlift with (lift := mirrorConf) (f := step (M:=MirrorTM)) (h := haltConf (M:=MirrorTM)) in HLoop
as (? & HLoop & <- % mirrorConf_injective); auto.
- intros ? _. now apply mirror_step.
Qed.
Definition Mirror_Rel (R : pRel sig F n) : pRel sig F n :=
fun t '(l, t') => R (mirror_tapes t) (l, mirror_tapes t').
Lemma Mirror_Realise R :
pM ⊨ R -> Mirror ⊨ Mirror_Rel R.
Proof.
intros HRealise. intros t i outc HLoop.
apply (HRealise (mirror_tapes t) i (mirrorConf outc)).
now apply mirror_lift in HLoop.
Qed.
Definition Mirror_T (T : tRel sig n) : tRel sig n :=
fun t k => T (mirror_tapes t) k.
Lemma Mirror_Terminates T :
projT1 pM ↓ T -> projT1 Mirror ↓ Mirror_T T.
Proof.
intros HTerm. hnf. intros t1 k H1. hnf in HTerm. specialize (HTerm (mirror_tapes t1) k H1) as (outc&H).
exists (mirrorConf outc). apply mirror_unlift. cbn. now rewrite mirrorConf_involution.
Qed.
Lemma Mirror_RealiseIn R (k : nat) :
pM ⊨c(k) R -> Mirror ⊨c(k) Mirror_Rel R.
Proof.
intros H.
eapply Realise_total. split.
- eapply Mirror_Realise. now eapply Realise_total.
- eapply TerminatesIn_monotone.
+ eapply Mirror_Terminates. now eapply Realise_total.
+ firstorder.
Qed.
End Mirror.
Arguments Mirror : simpl never.
Arguments Mirror_Rel { n sig F } R x y /.
Arguments Mirror_T { n sig } T x y /.
|
lemma prime_ge_2_int: "p \<ge> 2" if "prime p" for p :: int
|
{-
0.42
1.68
1.34
0.34
0.5 < 0.5 => False
0.5 <= 0.5 => True
0.5 == 0.5 => True
0.5 >= 0.5 => True
0.5 > 0.5 => False
0.5 compare 0.5 => EQ
0.5 max 0.5 => 0.5
0.5 min 0.5 => 0.5
0.5 < 1 => True
0.5 <= 1 => True
0.5 == 1 => False
0.5 >= 1 => False
0.5 > 1 => False
0.5 compare 1 => LT
0.5 max 1 => 1
0.5 min 1 => 0.5
1 < 0.5 => False
1 <= 0.5 => False
1 == 0.5 => False
1 >= 0.5 => True
1 > 0.5 => True
1 compare 0.5 => GT
1 max 0.5 => 1
1 min 0.5 => 0.5
1 < 1 => False
1 <= 1 => True
1 == 1 => True
1 >= 1 => True
1 > 1 => False
1 compare 1 => EQ
1 max 1 => 1
1 min 1 => 1
abs -1 => 1
- (-1) => 1
abs 1 => 1
- (1) => -1
-}
import CIL.FFI.Single
implementation Show Ordering where
show EQ = "EQ"
show LT = "LT"
show GT = "GT"
testNum : IO ()
testNum =
for_ [(*), (/), (+), (-)] $ \op =>
printLn $ single 0.84 `op` single 0.5
testOrd : IO ()
testOrd = traverse_ putStrLn (test singles singles)
where
singles = [ single 0.5, single 1.0 ]
op : Show r => String -> (Single -> Single -> r) -> (Single -> Single -> String)
op name o = \x, y => show x ++ " " ++ name ++ " " ++ show y ++ " => " ++ show (x `o` y)
operators : List (Single -> Single -> String)
operators = [ op "<" (<), op "<=" (<=), op "==" (==)
, op ">=" (>=), op ">" (>), op "compare" compare
, op "max" max, op "min" min ]
test : List Single -> List Single -> List String
test xs ys = do
x <- xs
y <- ys
map (\o => x `o` y) operators
testNeg : IO ()
testNeg =
for_ [ single (-1), single 1 ] $ \x => do
putStrLn $ "abs " ++ show x ++ " => " ++ show (abs x)
putStrLn $ "- (" ++ show x ++ ") => " ++ show (-x)
main : IO ()
main = do
testNum
testOrd
testNeg
-- Local Variables:
-- idris-load-packages: ("cil")
-- End:
|
\name{HeatmapAnnotation-class}
\docType{class}
\alias{HeatmapAnnotation-class}
\title{
Class for Heatmap Annotations
}
\description{
Class for Heatmap Annotations
}
\details{
A complex heatmap contains a list of annotations which are represented as graphics
placed on rows and columns. The \code{\link{HeatmapAnnotation-class}} contains a list of single annotations which are
represented as a list of \code{\link{SingleAnnotation-class}} objects.
}
\section{Methods}{
The \code{\link{HeatmapAnnotation-class}} provides following methods:
\itemize{
\item \code{\link{HeatmapAnnotation}}: constructor method.
\item \code{\link{draw,HeatmapAnnotation-method}}: draw the annotations.
}}
\author{
Zuguang Gu <[email protected]>
}
\examples{
# There is no example
NULL
}
|
function out = InsertDate(in)
%InsertDate - Insert date into string.
%
% Replaces %y, %m, %d and %t with current year, month, day and time.
%
% USAGE
%
% out = InsertDate(in)
%
% in string to modify
% Copyright (C) 2013 by Michaël Zugaro
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 3 of the License, or
% (at your option) any later version.
n = clock;
year = int2str(n(1));
month = int2zstr(n(2),2);
day = int2zstr(n(3),2);
time = [int2zstr(n(4)) '' int2zstr(n(5))];
out = in;
out = strrep(out,'%y',year);
out = strrep(out,'%m',month);
out = strrep(out,'%d',day);
out = strrep(out,'%t',time);
|
It seems every day, even when I’ve thoroughly researched a subject or a person and am in the middle of writing about it or her, a simple session of Internet research turns up new sources and resources that at the very least enrich, at the most reinterpret what I’m doing. This is a blessing and a curse.
I love the research, as I’ve said elsewhere on this site. Once upon a time, when all we could use were books and original sources from archives, the research phase would have to finish at a certain point or we’d never start writing. Now, despite the pitfalls of stumbling on inaccurate or misleading information about one’s subject, the Internet is always there, all the time, as a resource to mine.
I think I’ve found just about everything useful for my project, and then one day I word a search slightly differently and come up with something that sheds new light on it, or fills in a blank I’d just decided to work around. It’s wonderful, but it can also be treacherous. This shiny new object I’ve just discovered—surely there’s a place I can put it in my novel? Maybe. Maybe not.
Writing is editing: There’s never been a truer word said. As writers, we’re constantly making judgments about what to include and what to leave out; what to say and leave unsaid. The true genius in a novel is getting that balance right. And that goes for research as well. I may delight in knowing the exact route of a trolley in 1910 New York, but I don’t have to take my reader on a ride with it.
So why bother with that depth of research? Even without laying it in front of the reader’s eyes, everything I know and understand about the place, period, and personages involved informs the story. Depth of knowledge creates a solid foundation that helps ensure characters don’t take missteps into anachronism.
I just discovered the video above. It was only uploaded a few days ago, so I couldn’t have discovered it before. I’m in the middle of a complete rewrite of my WIP and immersed in 1911 in New York as we speak. I didn’t learn anything much new from this video (except something about how many people fit into a car of the time), but it gave me an atmospheric view of this period I’ve been working in for years. I could watch it over and over again.
|
Wind reports from moored buoys have smaller error than those from ships . Complicating the comparison of the two measurements are that NOMAD buoys report winds at a height of 5 metres ( 16 ft ) , while ships report winds from a height of 20 metres ( 66 ft ) to 40 metres ( 130 ft ) . Sea surface temperature measured in the intake port of large ships have a warm bias of around 0 @.@ 6 ° C ( 1 ° F ) due to the heat of the engine room . This bias has led to changes in the perception of global warming since 2000 . Fixed buoys measure the water temperature at a depth of 3 metres ( 10 ft ) .
|
Linda McCluskey’s scrapbook of memories is forged from oil paint and brush strokes.
Many of the images are familiar — Middle Street, The Worthen, downtown canalways — places you might have passed a thousand times. But when McCluskey reimagines them on canvas, the familiar begins to stir.
Brick and mortar. Cobblestones and canals. All bend, curve, twist and turn. You can almost hear the music. Feel the energy. It’s an invitation to step inside McCluskey’s world, where cityscapes seem to breathe.
Lowell, after all, is where she found inspiration to pick up a paintbrush again at age 40. Her success as a full-time working artist in Paris is proof, she says, that it’s never too late to pursue a dream.
Slogging along the daily grind, McCluskey’s art supplies ended up in boxes in a basement. She carried old photos of her favorite works with her as a reminder from time to time of who she was before becoming a mom, a wife and a cubicle dweller.
Sometimes life holds up a mirror and forces you to take a long hard look. Maybe it was the milestone, but McCluskey recalls her 40th birthday jogging something awake inside her.
And just like that, she put her dreams in action. With her kids Jake and Carly all grown up, she enrolled in college courses at UMass Lowell. Back at school, she travelled to France for a painting workshop and fell in love with her life all over again.
She was the happiest she had been in a long time, then tragedy struck. Her partner of six years, Ed McCabe, was killed in a motorcycle accident in 2001.
“I felt like my life was over,” McCluskey admits.
But in the shadow of her grief, she managed to find a sliver of light.
A close friend told her not to focus on the long and rolling highway. Follow the little paths life offers up instead. With nothing left to lose, McCluskey moved to France in January 2002. She was 44.
Picking up her brushes and paint again, she was reborn. Enter Linda McCluskey, the artist. Paris gave her freedom to rediscover and reinvent herself.
“In Paris, if you say you’re a painter, people don’t ask, ‘what do you really do?’ ” she explains.
In 2004, a move into a 6th floor studio overlooking St. Germaine Boulevard gave her a new perspective. Being a “country girl” born and raised in Chelmsford, she had never lived up so high.
The scenes unfolding on her canvas were well painted but still focused on proper form, until a trip to surrealist painter Salvador Dali’s beloved village of Cadaques in Spain pushed her brush in a whole new direction.
The natural beauty of Cadaques inspired Dali and the way he interpreted that on canvas brought attention to the region. Taking in the breathtaking view from a hillside, McCluskey did a Dali-esque painting of the village and the church melting over the mountains.
“After painting traditional views for so long, this felt like freedom to play and make up the impossible,” she says.
It was the beginning of McCluskey’s imaginative “distortion” pieces, and she gained recognition as a unique artist in Paris and in Lowell.
She returns to Lowell each year for inspiration.
Where Middle and Palmer streets intersect.
She points to her painting of Lowell’s Middle Street, one of her favorite downtown spots.
Today she has her own studio at Paris’ 59 Rivoli — one of the top three visited galleries in France — where she was accepted for a permanent residency. Her advice to others: If you love something do it.
|
{-# OPTIONS --safe #-}
open import Definition.Typed.EqualityRelation
module Definition.LogicalRelation.Substitution.Introductions.IdRefl {{eqrel : EqRelSet}} where
open EqRelSet {{...}}
open import Definition.Untyped
open import Definition.Untyped.Properties
open import Definition.Typed
open import Definition.Typed.Properties
open import Definition.LogicalRelation
open import Definition.LogicalRelation.Irrelevance
open import Definition.LogicalRelation.Properties
open import Definition.LogicalRelation.Substitution
open import Definition.LogicalRelation.Substitution.Properties
open import Definition.LogicalRelation.Substitution.Conversion
open import Definition.LogicalRelation.Substitution.Reduction
open import Definition.LogicalRelation.Substitution.Reflexivity
open import Definition.LogicalRelation.Substitution.ProofIrrelevance
open import Definition.LogicalRelation.Substitution.MaybeEmbed
open import Definition.LogicalRelation.Substitution.Introductions.Nat
open import Definition.LogicalRelation.Substitution.Introductions.Natrec
open import Definition.LogicalRelation.Substitution.Introductions.Empty
open import Definition.LogicalRelation.Substitution.Introductions.Emptyrec
open import Definition.LogicalRelation.Substitution.Introductions.Universe
open import Definition.LogicalRelation.Substitution.Introductions.Pi
open import Definition.LogicalRelation.Substitution.Introductions.Sigma
open import Definition.LogicalRelation.Substitution.Introductions.Id
open import Definition.LogicalRelation.Substitution.Introductions.IdUPiPi
open import Definition.LogicalRelation.Substitution.Introductions.Cast
open import Definition.LogicalRelation.Substitution.Introductions.CastPi
open import Definition.LogicalRelation.Substitution.Introductions.Lambda
open import Definition.LogicalRelation.Substitution.Introductions.Application
open import Definition.LogicalRelation.Substitution.Introductions.Pair
open import Definition.LogicalRelation.Substitution.Introductions.Fst
open import Definition.LogicalRelation.Substitution.Introductions.Snd
open import Definition.LogicalRelation.Substitution.Introductions.SingleSubst
open import Definition.LogicalRelation.Substitution.Introductions.Transp
open import Definition.LogicalRelation.Fundamental.Variable
import Definition.LogicalRelation.Substitution.ProofIrrelevance as PI
import Definition.LogicalRelation.Substitution.Irrelevance as S
open import Definition.LogicalRelation.Substitution.Weakening
open import Tools.Product
open import Tools.Unit
open import Tools.Nat
import Tools.PropositionalEquality as PE
Idreflᵛ : ∀{Γ A l t}
→ ([Γ] : ⊩ᵛ Γ)
→ ([A] : Γ ⊩ᵛ⟨ ∞ ⟩ A ^ [ ! , ι l ] / [Γ])
→ ([t] : Γ ⊩ᵛ⟨ ∞ ⟩ t ∷ A ^ [ ! , ι l ] / [Γ] / [A])
→ let [Id] = Idᵛ {A = A} {t = t} {u = t } [Γ] [A] [t] [t]
in Γ ⊩ᵛ⟨ ∞ ⟩ Idrefl A t ∷ Id A t t ^ [ % , ι l ] / [Γ] / [Id]
Idreflᵛ {Γ} {A} {l} {t} [Γ] [A] [t] =
let [Id] = Idᵛ {A = A} {t = t} {u = t } [Γ] [A] [t] [t]
in validityIrr {A = Id A t t} {t = Idrefl A t} [Γ] [Id] λ ⊢Δ [σ] → Idreflⱼ (escapeTerm (proj₁ ([A] ⊢Δ [σ])) (proj₁ ([t] ⊢Δ [σ])))
castreflᵛ : ∀{Γ A t}
→ ([Γ] : ⊩ᵛ Γ)
→ ([UA] : Γ ⊩ᵛ⟨ ∞ ⟩ U ⁰ ^ [ ! , next ⁰ ] / [Γ])
→ ([A]ₜ : Γ ⊩ᵛ⟨ ∞ ⟩ A ∷ U ⁰ ^ [ ! , next ⁰ ] / [Γ] / [UA] )
→ ([A] : Γ ⊩ᵛ⟨ ∞ ⟩ A ^ [ ! , ι ⁰ ] / [Γ])
→ ([t]ₜ : Γ ⊩ᵛ⟨ ∞ ⟩ t ∷ A ^ [ ! , ι ⁰ ] / [Γ] / [A])
→ let [Id] : Γ ⊩ᵛ⟨ ∞ ⟩ Id A t (cast ⁰ A A (Idrefl (U ⁰) A) t) ^ [ % , ι ⁰ ] / [Γ]
[Id] = Idᵛ {A = A} {t = t} {u = cast ⁰ A A (Idrefl (U ⁰) A) t} [Γ] [A] [t]ₜ
(castᵗᵛ {A = A} {B = A} {t = t} {e = Idrefl (U ⁰) A} [Γ] [UA] [A]ₜ [A]ₜ [A] [A] [t]ₜ
(Idᵛ {A = U _} {t = A} {u = A} [Γ] [UA] [A]ₜ [A]ₜ)
(Idreflᵛ {A = U _} {t = A} [Γ] [UA] [A]ₜ))
in Γ ⊩ᵛ⟨ ∞ ⟩ castrefl A t ∷ Id A t (cast ⁰ A A (Idrefl (U ⁰) A) t) ^ [ % , ι ⁰ ] / [Γ] / [Id]
castreflᵛ {Γ} {A} {t} [Γ] [UA] [A]ₜ [A] [t]ₜ =
let [Id] : Γ ⊩ᵛ⟨ ∞ ⟩ Id A t (cast ⁰ A A (Idrefl (U ⁰) A) t) ^ [ % , ι ⁰ ] / [Γ]
[Id] = Idᵛ {A = A} {t = t} {u = cast ⁰ A A (Idrefl (U ⁰) A) t} [Γ] [A] [t]ₜ
(castᵗᵛ {A = A} {B = A} {t = t} {e = Idrefl (U ⁰) A} [Γ] [UA] [A]ₜ [A]ₜ [A] [A] [t]ₜ
(Idᵛ {A = U _} {t = A} {u = A} [Γ] [UA] [A]ₜ [A]ₜ)
(Idreflᵛ {A = U _} {t = A} [Γ] [UA] [A]ₜ))
in validityIrr {A = Id A t (cast ⁰ A A (Idrefl (U ⁰) A) t)} {t = castrefl A t}
[Γ] [Id] λ ⊢Δ [σ] → castreflⱼ (escapeTerm (proj₁ ([UA] ⊢Δ [σ])) (proj₁ ([A]ₜ ⊢Δ [σ]))) (escapeTerm (proj₁ ([A] ⊢Δ [σ])) (proj₁ ([t]ₜ ⊢Δ [σ])))
|
@testset "maxintfloat $T" for T in (Double16, Double32, Double64)
@test isinteger(maxintfloat(T))
# Previous integer is representable, next integer is not
@test maxintfloat(T) == (maxintfloat(T) - one(T)) + one(T)
@test maxintfloat(T) != (maxintfloat(T) + one(T)) - one(T)
@test maxintfloat(T) < floatmax(T)
end
@testset "Inf and NaN generation $T" for T in (Double16, Double32, Double64)
@test isinf(T(Inf)) == isinf(inf(T))
@test isinf(T(Inf)) == isposinf(posinf(T))
@test isinf(T(-Inf)) == isneginf(neginf(T))
@test isnan(T(NaN)) == isnan(nan(T))
@test isinf(T(Inf32)) == isinf(inf(T))
@test isinf(T(Inf32)) == isposinf(posinf(T))
@test isinf(T(-Inf32)) == isneginf(neginf(T))
@test isnan(T(NaN32)) == isnan(nan(T))
@test isinf(T(Inf16)) == isinf(inf(T))
@test isinf(T(Inf16)) == isposinf(posinf(T))
@test isinf(T(-Inf16)) == isneginf(neginf(T))
@test isnan(T(NaN16)) == isnan(nan(T))
end
|
Saudi’s Shoura Council Seeks Probe Into Haramain Rail Project Delays - railmeds JimdoPage!
04/06/2014 (Gulf Business - UAE): Saudi Arabia’s Shoura Council has asked the national anti-corruption commission (Nazaha) to investigate the delay in the completion of the Haramain Railway project. The Haramain high-speed link, which will link the holy cities of Makkah and Medina, has seen a number of construction delays, which have pushed back its launch date to 2016 from 2012. The project has also seen cost revisions from $12 billion to $14 billion, according to an earlier report by Saudi Railway Organisation (SRO). “The Nazaha should also investigate the budget allocated to the Haramain Railway project and the reasons for the increase in the funds needed for the completion of the project,” the Shoura Council said in a meeting held to discuss the annual report of the SRO, Arab News reported.
02/06/2014 (Gulf News - UAE): Abu Dhabi: Etihad Rail — the developer and operator of the UAE’s national railway network — has said it has achieved more than 10 million working man-hours, or over 250 days, with zero lost-time injuries.“This achievement, which includes time dedicated to the testing and commissioning of trains since September last year, reflects that the high safety standards of the rail industry have carried over into Etihad Rail’s activities prior to the launch of commercial operations,” said Engineer Faris Saif Al Mazroui, Acting CEO of Etihad Rail. Al Mazroui added that at Etihad Rail, they believe that all accidents, injuries and work-related illnesses are preventable, with safety being a value and mind-set shared by all. “From senior management through to the frontline, each of our employees and contractors is trained and empowered to eliminate unsafe conditions and implement the necessary corrective actions to make an area or situation safe. This has resulted in a common set of principles and behaviours that ensures working safely is part of our daily business. This 10 million hours figure is a significant milestone for us, particularly considering the challenging desert conditions of the Western Region,” Al Mazroui said.
06/06/2014 (AzerNews - Azerbaijan): Kazakhstan-Turkmenistan-Iran railway will be put into operation this year. The remark was made Turkmen President Gurbanguly Berdymukhamedov at a meeting with his Kazakh counterpart Nursultan Nazarbayev in Turkey. Turkmen and Kazakh presidents met as part of the Summit of the Cooperation Council of Turkic-Speaking States (CCTS), held in Turkey's Bodrum city on June 5. During the talks the Turkmen president invited his Kazakh counterpart to take part in the solemn ceremony of opening of this strategic railway, which is an essential part of the North-South transport corridor, with a global significance. The sides also noted the new railway will provide a convenient and economical transportation of goods to South Asia, to the Gulf ports, as well as in the opposite direction - to the Eastern Europe through Russia, Turkmen media reported.
Qatar committed to schedule of GCC railway network - Min.
02/06/2014 (KUNA - Kuwait): DOHA, June 2 (KUNA) -- Qatari Minister of Transport Jassem Al-Sulaiti on Monday reaffirmed his country's commitment to the schedule of the implementation of the GCC railway network, due to go operational by 2018. "The developers of this mega project in the GCC member states are working closely together to lay out the designs of project; this process is well underway and will complete this year," the minister told reporters. Al-Sulaiti made the comments on the sidelines of the IATA's 70th Annual General Meeting (AGM) and World Air Transport Summit, being hosted by Qatar Airways (QA). "Saudi Arabia and the United Arab Emirates have already made good progress, compared with other GCC countries, in the development of technical and feasibility studies and offering them to bidders," he pointed out. "The meeting of the GCC ministers of transport and communication in Bahrain two months ago was a step forward towards the implementation of the project," he recalled, noting that undersecretary of the Bahraini Ministry of Transportation will be visiting Doha on Thursday for technical talks on the project.
03/06/2014 (The New India Express - India): As the Modi government defines its foreign policy priorities, one of the issues that needs urgent attention is the finalisation of India’s investment in the development of Chabahar Port in Iran. This is particularly important because the window of opportunity available to India to have a presence in Chabahar may be closing rapidly. India and Iran had agreed to cooperate on the development of this Iranian port way back in 2003 when Iran’s president Mohammad Khatami had visited India but nothing much has been achieved in these 11 years. It appears the previous government was close to approving US $100 million investment in the development of the port but could not take the decision. The new government could pick up the threads and quickly seal the deal. The strategic importance of Chabahar Port for India cannot be overstated. Located in the Sistan-Baluchistan province of Iran on the Makram coast and just outside the Persian Gulf, Chabahar is a natural gateway for India to Afghanistan and Central Asia. In the last 10 years, the Iranians have invested considerable sums of money in the development of Chabahar city. A 600km-long highway linking Chabahar to Zahidan in the north is operational.
01/06/2014 (Fars News - Iran): TEHRAN (FNA)- Iran's Ambassador to Moscow Mahdi Sanayee and Head of the Russian State Railways Company Alexander Yakunin pledged to do their best to complete joint railroad projects, specially the one which will link the two countries via the Azerbaijan Republic. In a meeting on Friday, the two officials voiced readiness for consolidating Tehran-Moscow economic cooperation in all domains, particularly joint railway projects. “The plan for connecting the two countries through railway is practically complete now and only a few kilometers of it have remained, whose construction will not take a long period,” said the Iranian ambassador. Sanayee went on to say that there are four other joint projects between the two countries in railway transportation field, including electrifying the two countries’ railway systems. Iran-Russia trade currently totals $5bln a year, but economists say they can at least quadruple the volume of their trade exchanges.
06/06/2014 (ABC - Azerbaijan): The Asian Development Bank (ADB) informs hat it keeps in force its proposal of technical assistance for the preparation of Multi-Financing Facility (MFF) Preparing MFF Railway Investment Program. "The Bank is ready to award a $1 million grant for MFF preparation," the ADB said. CJSC Azerbaijani Railways (ADY) remains an attractive partner for ADB. Thus, in the Country Partnership Strategy (CPS), which is being prepared for Azerbaijan and will cover the period of 2018-19, cooperation in the development of the railway system in the country remains a priority. The Strategy has not been adopted, but back in 2010 the government refused from the use of Bank’s finances under the formal pretext of lack of investment project. Then ADB planned to approve the first tranche in the amount of $200 million with overall Preparing the Railways Sector Development Program MFF loan in the amount of $500 million. The Bank-drawn consultants fulfilled successfully the first stage of technical assistance by 13 April 2010. The second stage of works on technical assistance (feasibility study and preliminary designing of first tranche of MFF) was never started.
06/06/2014 (RT - Russia): Russia will team up with North and South Korea in a railroad construction project that could restore peace between the two neighbors. The link will extend the world’s longest railroad, so goods can be shipped between Europe and Korea 3x faster. Russia’s Minister for Far East Development Aleksander Galushka announced the plan to extend the Trans-Siberian Railroad at a meeting in Vladivostok on Thursday. The expansion would provide a link between the Korean peninsula and Europe’s $17 trillion economy, making Russia a major transit route between Europe and Asia. Shipping by rail is nearly 3 times faster than via the Suez Canal, Russian Railways CEO Vladimir Bakunin has said.
04/06/2014 (Global Post - USA): URUMQI, June 4 (Xinhua) -- The trial run for the first high-speed railway in Xinjiang Uygur Autonomous Region started on Tuesday, marking a countdown to formal operations by the end of the year and a confidence boost to the region. A CRH2-061C high-speed train ran through the 300-km Urumqi-Shanshan section at speeds of 160 km to 277 km per hour. The designed speed is 250 km per hour, but the train must slow down when passing through windy areas. The train is part of the Second Double-track Line of the Lanxin Railway, which links Lanzhou City in northwestern Gansu Province and Urumqi. The 1,776-km line crosses a vast expanse of the Gobi Desert and windy areas -- a major technical feat -- and will be Xinjiang's first high-speed railway when it begins operation by the end of 2014. With the new railway, travel time between Lanzhou and Urumqi will be cut from the current 21 hours to 8 hours or less.
06/06/2014 (The Nation - Pakistan): ISLAMABAD - Ministry of Railways on Thursday signed a memorandum of understanding (MoU) with leading state-owned Chinese company, China Gezhouba Group Corporation (CGGC). The agreement was signed between RAILCOP, a subsidiary company of Pakistan Railways and the CGGC which is a subsidiary company of China Energy Engineering Corporation.
The MoU demanded RAILCOP to work as local partner of Chinese company in Pakistan to identify potential construction projects and relevant information. As per agreement RAILCOP would also ensure complete cooperation in provision of engineers and supporting staff under the clause of human resource cooperation. It is pertinent to mention here that presently, the CGGC company is working on 1.5 billion US dollars Neelum - Jhelum Hydro Project. Recently, the company has also submitted expression of interest for National Highways Authority’s Lahore - Karachi motorway project.
|
[STATEMENT]
lemma ereal_strict_mono2 [mono_intros]:
assumes "x < y"
shows "ereal x < ereal y"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. ereal x < ereal y
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
x < y
goal (1 subgoal):
1. ereal x < ereal y
[PROOF STEP]
by auto
|
"""The data structure for the factor is referenced from Prof. Daphne Koller's coursera course "Probabilistic Graphical Models"
"""
import numpy as np
def ismember(a, b):
bind = {}
for index, value in enumerate(b):
if value not in bind:
bind[value] = index
return [bind.get(value, None) for value in a]
"""
TODO:
1. vectorization
2. handle multiple variables at once in restrict, multiply and sumout
"""
class Factor:
def __init__(self, var, card, val):
"""Represent factor using a multi-dimensional array
Arguments:
var -- a np array of variable names, i.e., scope of the factor
card -- a np array of cardinality values corresponding to var, i.e., scopre of the variables
val -- a np array of values for every possible assignment to the variables. If var = X_1, X_2, X_3 and card = 2, 2, 2, then val should be given in order of (1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2), (2, 1, 1) and so on
"""
if len(var) != len(card) or np.prod(card) != len(val):
raise Exception("invalid initialization for Factor initialization")
self._var = np.copy(var)
self._card = np.copy(card)
self._val = np.copy(val)
def factor_copy(factor):
return Factor(factor.var, factor.card, factor.val)
@property
def var(self):
return self._var
@property
def card(self):
return self._card
@property
def val(self):
return self._val
@val.setter
def val(self, value):
# check validity
self._val = value
# @val.setter
# def val(self, index, value):
# # check validity
# self._val[index] = value
def assignment_to_index(assignment, cardinality):
"""Returns the index of the given assignment in a factor with card = cardinality
Arguments:
assignment -- a np array of values of the variables, e.g., X_1 = 1, X_2 = 2, X_3 = 3 => [1, 2, 3]
cardinality -- a np array of cardinality values corresponding to var
Returns:
index -- index of the given assignment in a factor with card = cardinality; note index starts from 0
"""
if any([assignment[i] < 1 for i in range(len(assignment))]):
raise Exception("invalid assignment value: %s" % str(assignment))
if len(assignment) != len(cardinality) or any(
[assignment[i] > cardinality[i] for i in range(len(assignment))]):
raise Exception("assignment[%s] and cardinality[%s] do not match" %
(str(assignment), str(cardinality)))
index = 0
for i in range(len(assignment)):
# int64 + uint64 -> float64 wtf! well documented strange thing here https://github.com/numpy/numpy/issues/5745
index = index + (assignment[i] - 1) * np.prod(cardinality[i + 1:])
return int(index)
def index_to_assignment(index, cardinality):
"""Returns the assignment of the given index in a factor with card = cardinality
Arguments:
index -- the index to be queried; note index starts from 0
cardinality -- a np array of cardinality values corresponding to var
Returns:
assignment -- a np array corresponding to assignment of the given index in a factor with card = cardinality
"""
if index < 0 or index >= np.prod(cardinality):
raise Exception("index[%d] out of range for cardinality[%s]" %
(index, str(cardinality)))
assignment = np.zeros(len(cardinality), dtype=np.uint8)
for i in range(len(cardinality)):
assignment[i] = index / np.prod(cardinality[i + 1:]) + 1
index = index % np.prod(cardinality[i + 1:])
return assignment
def get_value_of_assignment(factor, assignment):
"""Returns the value of the assignment in the factor
Arguments:
factor -- the factor to be queried
assignment -- a np array corresponding to the assignment to be queried
Returns:
val -- value of the assignment in the factor
"""
if len(assignment) != len(factor.var):
raise Exception(
"length of assignment[%d] does not match the number of variables in the factor"
% len(assignment))
index = Factor.assignment_to_index(assignment, factor.card)
return factor.val[index]
def set_value_of_assignment(factor, assignment, val):
"""Returns a new factor with the value for assignment set to val
Arguments:
factor -- the factor to be queried
assignment -- a np array corresponding to the assignment to be queried
val -- the value to be set
Returns:
ret_factor -- a new factor with the value for assignment set to val
"""
if len(assignment) != len(factor.var):
raise Exception(
"length of assignment[%d] does not match the number of variables in the factor"
% len(assignment))
ret_factor = Factor.factor_copy(factor)
index = Factor.assignment_to_index(assignment, ret_factor.card)
ret_factor.val[index] = val
return ret_factor
def restrict(factor, variable, value):
"""Restrict the variable in the factor to the value provided
Arguments:
factor -- the factor to be restricted
variable -- the variable to be restricted
value -- the value to set to
Returns
new_factor -- the new factor after setting the value
"""
if variable not in factor.var:
raise Exception("variable[%d] is not in factor" % variable)
index = np.where(factor.var == variable)[0][0]
new_factor = Factor.factor_copy(factor)
for i in range(np.prod(new_factor.card)):
assignment = Factor.index_to_assignment(i, new_factor.card)
if assignment[index] != value:
new_factor.val[i] = 0
return new_factor
def multiply(factor_A, factor_B):
"""Return a new factor which is the product of the two given factors
Arguments:
factor_A -- factor
factor_B -- factor
Returns:
new_factor -- a new factor which is the product of factor_A and factor_B
"""
# Find intersection between scopes of the two factors
common_var = np.intersect1d(factor_A.var, factor_B.var)
# Find index of the common variables in factor A
common_var_index_in_A = ismember(common_var, factor_A.var)
# Find index of the common variables in factor B
common_var_index_in_B = ismember(common_var, factor_B.var)
# Check if cardinality of common variables match in the two factors
for i in range(len(common_var)):
if factor_A.card[common_var_index_in_A[i]] != factor_B.card[common_var_index_in_B[i]]:
raise Exception(
"cardinality of variables in factor A and factor B do not match"
)
# Find the scope of the resulting factor
all_var = np.union1d(factor_A.var, factor_B.var)
# Initialize the cardinality of the resulting factor
all_card = np.zeros((len(all_var)), dtype=np.uint8)
# Find index of the variable of factor A in the resulting factor
var_A_index_in_all_var = ismember(factor_A.var, all_var)
# Find index of the variable of factor B in the resulting factor
var_B_index_in_all_var = ismember(factor_B.var, all_var)
# Set the cardinality of the resulting factor
all_card[var_A_index_in_all_var] = factor_A.card
all_card[var_B_index_in_all_var] = factor_B.card
# Initialize the values of the new factor
all_val = np.zeros((np.prod(all_card)))
for i in range(np.prod(all_card)):
# Generate one assignment of the new factor
all_assignment = Factor.index_to_assignment(i, all_card)
# Find the assignment in factor A that corresponds to the current assignment in the new factor
assignment_A = all_assignment[var_A_index_in_all_var]
# Find the assignment in factor B that corresponds to the current assignment in the new factor
assignment_B = all_assignment[var_B_index_in_all_var]
# Get assignment value from factor A
val_A = Factor.get_value_of_assignment(factor_A, assignment_A)
# Get assignment value from factor B
val_B = Factor.get_value_of_assignment(factor_B, assignment_B)
# Multiply the two assignment values to get value for the assignment in the new factor
all_val[i] = val_A * val_B
# Construct the new factor and return
new_factor = Factor(all_var, all_card, all_val)
return new_factor
def sumout(factor, variable):
"""Sum out the given variable from the factor
Arguments:
factor -- the factor to be marginalized
variable -- the variable to be summed out
Returns:
new_factor -- the given factor with the variable summed out
"""
# check whether variable is in factor
if variable not in factor.var:
raise Exception("variable[%d] is not in factor[%s]" % (variable,
factor.var))
# Find the scope of the resulting factor
new_var = np.setdiff1d(factor.var, variable)
# Find index of variable of new factor in old factor
new_var_index_in_factor = ismember(new_var, factor.var)
# Find cardinality of new factor from old factor
new_card = np.copy(factor.card[new_var_index_in_factor])
# Initialize values for new factor
new_val = np.zeros(np.prod(new_card))
for i in range(np.prod(factor.card)):
# Find assignment of old factor
assignment_in_factor = Factor.index_to_assignment(i, factor.card)
# Find assignment of old factor in new factor
assignment_in_new_factor = assignment_in_factor[
new_var_index_in_factor]
# Find index of assingment in new factor
index_in_new_factor = Factor.assignment_to_index(
assignment_in_new_factor, new_card)
# Add values in old factor to new factor
new_val[index_in_new_factor] += Factor.get_value_of_assignment(
factor, assignment_in_factor)
return Factor(new_var, new_card, new_val)
def normalize(factor):
"""Normalize a factor
Arguments:
factor -- the factor to be normalized
Returns:
new_factor -- the normalized factor
"""
new_factor = Factor.factor_copy(factor)
new_factor.val = new_factor.val / np.sum(new_factor.val)
return new_factor
def inference(factorList,
queryVariables,
orderedListOfHiddenVariables,
evidenceList,
verbose=True):
"""Perform inference on the bayes net
Arguments:
factorList -- a list of factor defining the bayes net
queryVariables -- a list of variables to query
orderedListOfHiddenVariables -- a variables elimination order
evidenceList -- a dictionary of {variable: value}
verbose -- verbose mode
Returns:
new_factor -- the factor representing the inference result
"""
# observe evidence
for idx in range(len(factorList)):
for key, value in evidenceList.items():
# If evidence in factor scope, restrict
if key in factorList[idx].var:
factorList[idx] = Factor.restrict(factorList[idx], key,
value)
# store intermediate factor
tmp_factor = None
for variable in orderedListOfHiddenVariables:
# keep track of which factor has been multipled
remove_list_idx = []
for idx in range(len(factorList)):
if variable in factorList[idx].var:
# First factor containing the variable to be eliminated => initialize intermediate
if tmp_factor == None:
tmp_factor = factorList[idx]
else:
tmp_factor = Factor.multiply(tmp_factor,
factorList[idx])
# factList[idx] was multiplied => add to removal list
remove_list_idx.append(idx)
# remove factor which has been multiplied
for idx in reversed(range(len(remove_list_idx))):
del factorList[remove_list_idx[idx]]
# All factors containing the variable to be eliminated have been multiplied => sum out the variable
tmp_factor = Factor.sumout(tmp_factor, variable)
# Print-out
tmp_factor_name = []
for var in tmp_factor.var:
for key, value in factor_name.items():
if value == var:
tmp_factor_name.append(key)
if verbose:
print("IntermediateFactor(%s): %s" % (tmp_factor_name,
tmp_factor.val))
# Add resulting factor back to factorList
factorList.append(tmp_factor)
# Set intermediate factor to be None for next iteration
tmp_factor = None
ret_factor = None
# multiply all the remaining factors in the factorList
for idx in range(len(factorList)):
if ret_factor == None:
ret_factor = factorList[idx]
else:
ret_factor = Factor.multiply(ret_factor, factorList[idx])
# Print-out
tmp_factor_name = []
for var in ret_factor.var:
for key, value in factor_name.items():
if value == var:
tmp_factor_name.append(key)
if verbose:
print("IntermediateFactor(%s): %s" % (tmp_factor_name,
ret_factor.val))
# normalize the final factor
ret_factor = Factor.normalize(ret_factor)
return ret_factor
if __name__ == "__main__":
factor_name = {"FS": 1, "FM": 2, "NA": 3, "FB": 4, "NDG": 5, "FH": 6}
variable_val = {"YES": 1, "NO": 2}
# Fido is sick factor
var_FS = np.array([factor_name["FS"]])
card_FS = np.array([2])
val_FS = np.array([0.05, 0.95])
factor_FS = Factor(var_FS, card_FS, val_FS)
# Full moon factor
var_FM = np.array([factor_name["FM"]])
card_FM = np.array([2])
val_FM = np.array([1. / 28, 27. / 28])
factor_FM = Factor(var_FM, card_FM, val_FM)
# Neighbor away factor
var_NA = np.array([factor_name["NA"]])
card_NA = np.array([2])
val_NA = np.array([0.3, 0.7])
factor_NA = Factor(var_NA, card_NA, val_NA)
# Factor of Fido is sick and food in Fido's bowl
var_FS_FB = np.array([factor_name["FS"], factor_name["FB"]])
card_FS_FB = np.array([2, 2])
val_FS_FB = np.array([0.6, 0.4, 0.1, 0.9])
factor_FS_FB = Factor(var_FS_FB, card_FS_FB, val_FS_FB)
# Factor of full moon, neighbor away and neighbor's dog is howling
var_FM_NA_NDG = np.array(
[factor_name["FM"], factor_name["NA"], factor_name["NDG"]])
card_FM_NA_NDG = np.array([2, 2, 2])
val_FM_NA_NDG = np.array([0.8, 0.2, 0.4, 0.6, 0.5, 0.5, 0, 1])
factor_FM_NA_NDG = Factor(var_FM_NA_NDG, card_FM_NA_NDG, val_FM_NA_NDG)
# Factor of full moon, neighbor's dog is howling, Fido is sick and Fido howls
var_FM_NDG_FS_FH = np.array([
factor_name["FM"], factor_name["NDG"], factor_name["FS"], factor_name["FH"]
])
card_FM_NDG_FS_FH = np.array([2, 2, 2, 2])
val_FM_NDG_FS_FH = np.array([
0.99, 0.01, 0.65, 0.35, 0.9, 0.1, 0.4, 0.6, 0.75, 0.25, 0.2, 0.8, 0.5, 0.5,
0, 1
])
factor_FM_NDG_FS_FH = Factor(var_FM_NDG_FS_FH, card_FM_NDG_FS_FH,
val_FM_NDG_FS_FH)
factor_list = [
factor_FS, factor_FM, factor_NA, factor_FS_FB, factor_FM_NA_NDG,
factor_FM_NDG_FS_FH
]
# part b
query_variables = [factor_name["FH"]]
ordered_list_of_hidden_variables = [
factor_name["NA"], factor_name["FS"], factor_name["FB"], factor_name["FM"],
factor_name["NDG"]
]
evidence_list = {}
prior_FH_howl = Factor.inference(factor_list.copy(), query_variables,
ordered_list_of_hidden_variables,
evidence_list)
print("[part b] prior probability of Fido howling is %f, not howling is %f" %
(prior_FH_howl.val[0], prior_FH_howl.val[1]))
# part c
evidence_list = {
factor_name["FH"]: variable_val["YES"],
factor_name["FM"]: variable_val["YES"]
}
query_variables = [factor_name["FS"]]
ordered_list_of_hidden_variables = [
factor_name["FH"], factor_name["FM"], factor_name["NA"],
factor_name["NDG"], factor_name["FB"]
]
posterior_FIDO_sick = Factor.inference(factor_list.copy(), query_variables,
ordered_list_of_hidden_variables,
evidence_list)
print("[part c] posterior probability of Fido is sick is %f, not sick is %f" %
(posterior_FIDO_sick.val[0], posterior_FIDO_sick.val[1]))
# part d
evidence_list = {
factor_name["FH"]: variable_val["YES"],
factor_name["FM"]: variable_val["YES"],
factor_name["FB"]: variable_val["YES"]
}
query_variables = [factor_name["FS"]]
ordered_list_of_hidden_variables = [
factor_name["FH"], factor_name["FM"], factor_name["FB"], factor_name["NA"],
factor_name["NDG"]
]
posterior_FIDO_sick = Factor.inference(factor_list.copy(), query_variables,
ordered_list_of_hidden_variables,
evidence_list)
print("[part d] posterior probability of Fido is sick is %f, not sick is %f" %
(posterior_FIDO_sick.val[0], posterior_FIDO_sick.val[1]))
|
-- 4.1.5 Exercises
-- integer arithmetic expression
data Exp = Single Int
| Add Exp Exp
| Sub Exp Exp
| Mul Exp Exp
-- more flexible syntax
-- data Exp : Type where
-- Single : Int -> Exp
-- Add : Exp -> Exp -> Exp
-- Sub : Exp -> Exp -> Exp
-- Mul : Exp -> Exp -> Exp
eval : Exp -> Int
eval (Single x) = x
eval (Add x y) = eval x + eval y
eval (Sub x y) = eval x - eval y
eval (Mul x y) = eval x * eval y
-- *Chap4> eval (Add (Single 1) (Single 2))
-- 3 : Int
data BSTree : Type -> Type where
Empty : Ord e => BSTree e
Node : Ord e => (left : BSTree e) -> (val : e) -> (right : BSTree e) -> BSTree e
-- %name BSTree left, right
-- using a %name directive to give naming hints for building definitions interactively
insert : elem -> BSTree elem -> BSTree elem
insert x Empty = Node Empty x Empty
insert x orig@(Node left val right) = case compare x val of
LT => Node (insert x left) val right
EQ => orig -- same as as-patterns in Haskell
GT => Node left val (insert x right)
-- match Ctrl-Alt-M
listToTree : Ord a => List a -> BSTree a
listToTree [] = Empty
listToTree (x :: xs) = insert x $ listToTree xs
-- *starting/Chap4> listToTree ['p', 'r', 'a', 't']
-- Node (Node Empty 'a' (Node (Node Empty 'p' Empty) 'r' Empty)) 't' Empty : BSTree Char
treeToList : BSTree a -> List a
treeToList Empty = []
treeToList (Node left val right) = treeToList left ++ [val] ++ treeToList right
|
[STATEMENT]
lemma prv_pls_zer:
assumes [simp]: "t \<in> atrm" shows "prv (eql (pls t zer) t)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. prv (eql (pls t zer) t)
[PROOF STEP]
using prv_psubst[OF _ _ _ prv_pls_zer_var, of "[(t,xx)]"]
[PROOF STATE]
proof (prove)
using this:
\<lbrakk>eql (pls (Var xx) zer) (Var xx) \<in> fmla; snd ` set [(t, xx)] \<subseteq> var; fst ` set [(t, xx)] \<subseteq> trm\<rbrakk> \<Longrightarrow> prv (psubst (eql (pls (Var xx) zer) (Var xx)) [(t, xx)])
goal (1 subgoal):
1. prv (eql (pls t zer) t)
[PROOF STEP]
by simp
|
/-
Copyright (c) 2021 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import data.fintype.basic
/-!
# Induction principles for `Π i, finset (α i)`
In this file we prove a few induction principles for functions `Π i : ι, finset (α i)` defined on a
finite type.
* `finset.induction_on_pi` is a generic lemma that requires only `[fintype ι]`, `[decidable_eq ι]`,
and `[Π i, decidable_eq (α i)]`; this version can be seen as a direct generalization of
`finset.induction_on`.
* `finset.induction_on_pi_max` and `finset.induction_on_pi_min`: generalizations of
`finset.induction_on_max`; these versions require `Π i, linear_order (α i)` but assume
`∀ y ∈ g i, y < x` and `∀ y ∈ g i, x < y` respectively in the induction step.
## Tags
finite set, finite type, induction, function
-/
open function
variables {ι : Type*} {α : ι → Type*} [fintype ι] [decidable_eq ι] [Π i, decidable_eq (α i)]
namespace finset
/-- General theorem for `finset.induction_on_pi`-style induction principles. -/
lemma induction_on_pi_of_choice (r : Π i, α i → finset (α i) → Prop)
(H_ex : ∀ i (s : finset (α i)) (hs : s.nonempty), ∃ x ∈ s, r i x (s.erase x))
{p : (Π i, finset (α i)) → Prop} (f : Π i, finset (α i)) (h0 : p (λ _, ∅))
(step : ∀ (g : Π i, finset (α i)) (i : ι) (x : α i),
r i x (g i) → p g → p (update g i (insert x (g i)))) :
p f :=
begin
induction hs : univ.sigma f using finset.strong_induction_on with s ihs generalizing f, subst s,
cases eq_empty_or_nonempty (univ.sigma f) with he hne,
{ convert h0, simpa [funext_iff] using he },
{ rcases sigma_nonempty.1 hne with ⟨i, -, hi⟩,
rcases H_ex i (f i) hi with ⟨x, x_mem, hr⟩,
set g := update f i ((f i).erase x) with hg, clear_value g,
have hx' : x ∉ g i, by { rw [hg, update_same], apply not_mem_erase },
obtain rfl : f = update g i (insert x (g i)),
by rw [hg, update_idem, update_same, insert_erase x_mem, update_eq_self],
clear hg, rw [update_same, erase_insert hx'] at hr,
refine step _ _ _ hr (ihs (univ.sigma g) _ _ rfl),
rw ssubset_iff_of_subset (sigma_mono (subset.refl _) _),
exacts [⟨⟨i, x⟩, mem_sigma.2 ⟨mem_univ _, by simp⟩, by simp [hx']⟩,
(@le_update_iff _ _ _ _ g g i _).2 ⟨subset_insert _ _, λ _ _, le_rfl⟩] }
end
/-- Given a predicate on functions `Π i, finset (α i)` defined on a finite type, it is true on all
maps provided that it is true on `λ _, ∅` and for any function `g : Π i, finset (α i)`, an index
`i : ι`, and `x ∉ g i`, `p g` implies `p (update g i (insert x (g i)))`.
See also `finset.induction_on_pi_max` and `finset.induction_on_pi_min` for specialized versions
that require `Π i, linear_order (α i)`. -/
lemma induction_on_pi {p : (Π i, finset (α i)) → Prop} (f : Π i, finset (α i)) (h0 : p (λ _, ∅))
(step : ∀ (g : Π i, finset (α i)) (i : ι) (x : α i) (hx : x ∉ g i),
p g → p (update g i (insert x (g i)))) :
p f :=
induction_on_pi_of_choice (λ i x s, x ∉ s) (λ i s ⟨x, hx⟩, ⟨x, hx, not_mem_erase x s⟩) f h0 step
/-- Given a predicate on functions `Π i, finset (α i)` defined on a finite type, it is true on all
maps provided that it is true on `λ _, ∅` and for any function `g : Π i, finset (α i)`, an index
`i : ι`, and an element`x : α i` that is strictly greater than all elements of `g i`, `p g` implies
`p (update g i (insert x (g i)))`.
This lemma requires `linear_order` instances on all `α i`. See also `finset.induction_on_pi` for a
version that `x ∉ g i` instead of ` does not need `Π i, linear_order (α i)`. -/
lemma induction_on_pi_max [Π i, linear_order (α i)] {p : (Π i, finset (α i)) → Prop}
(f : Π i, finset (α i)) (h0 : p (λ _, ∅))
(step : ∀ (g : Π i, finset (α i)) (i : ι) (x : α i),
(∀ y ∈ g i, y < x) → p g → p (update g i (insert x (g i)))) :
p f :=
induction_on_pi_of_choice (λ i x s, ∀ y ∈ s, y < x)
(λ i s hs, ⟨s.max' hs, s.max'_mem hs, λ y, s.lt_max'_of_mem_erase_max' _⟩) f h0 step
/-- Given a predicate on functions `Π i, finset (α i)` defined on a finite type, it is true on all
maps provided that it is true on `λ _, ∅` and for any function `g : Π i, finset (α i)`, an index
`i : ι`, and an element`x : α i` that is strictly less than all elements of `g i`, `p g` implies
`p (update g i (insert x (g i)))`.
This lemma requires `linear_order` instances on all `α i`. See also `finset.induction_on_pi` for a
version that `x ∉ g i` instead of ` does not need `Π i, linear_order (α i)`. -/
lemma induction_on_pi_min [Π i, linear_order (α i)] {p : (Π i, finset (α i)) → Prop}
(f : Π i, finset (α i)) (h0 : p (λ _, ∅))
(step : ∀ (g : Π i, finset (α i)) (i : ι) (x : α i),
(∀ y ∈ g i, x < y) → p g → p (update g i (insert x (g i)))) :
p f :=
@induction_on_pi_max ι (λ i, order_dual (α i)) _ _ _ _ _ _ h0 step
end finset
|
\section{Reparameterization \& Arc Length}
\noindent
VVFs can be reparameterized to trace out the same curve at different speeds by replacing $t$ in $\vec{r}(t)$ with any non-decreasing function of $t$.
This fact can come in handy to make the bounds of an integration problem more convenient.\\
\noindent
The integral of the derivative of a VVF gives the displacement vector because
\begin{equation*}
\int_{a}^{b}{\vec{r^\prime}(t)\mathrm{d}t}=\vec{r}(b)-\vec{r}(a).
\end{equation*}
This is exactly like how $\text{veclvity} \cdot \text{time} = \text{displacment}$.
\noindent
If we integrate the magnitude of $\vec{r^\prime}(t)$, we can use the fact that $\text{distance} = \text{speed} \cdot \text{time}$ to find the arc length of $\vec{r}(t)$ as
\begin{equation*}
s=\int{\norm{\vec{r^\prime}(t)}\mathrm{d}t}=\int{\sqrt{\left(\frac{\mathrm{d}x}{\mathrm{d}t}\right)^2+\left(\frac{\mathrm{d}y}{\mathrm{d}t}\right)^2+\left(\frac{\mathrm{d}z}{\mathrm{d}t}\right)^2}\mathrm{d}t}.
\end{equation*}
We can also write this as an arclength function,
\begin{equation*}
s(t)=\int_{0}^{t}{\norm{\vec{r^{\prime}}(\tau)}\mathrm{d}\tau}.
\end{equation*}
\noindent
If we have a function
\begin{equation*}
f(t)=s(t)=\int_{0}^{t}{\norm{\vec{r^{\prime}}(\tau)}\mathrm{d}\tau},
\end{equation*}
where $s$ is strictly increasing, then $f$ has an inverse by the horizontal line test.
That is, $t(s) = f^{-1}(s)$ exists and is also non-decreasing.
If we reparameterize $\vec{r}(t)$ to $\vec{r}(t(s))$, which is called the arc length parameterization, the parameterization will have a constant speed.
|
loaddict(filename::AbstractString) = Dict(lval => rval for (rval, lval) in split.(eachline(filename), " -> "))
function prettyprint(dict)
cache = Dict{AbstractString, UInt16}()
foreach(sort!(collect(keys(dict)))) do key
println(key, ": ", bobbycalculate(dict, key, cache))
end
end
bobbycalculate(filename::AbstractString, var) = bobbycalculate(loaddict(filename), var)
function bobbycalculate(dict::Dict, var::AbstractString, cache = Dict{AbstractString, UInt16}())
get!(cache, var) do
str = dict[var]
if all(isdigit, str)
parse(UInt16, str)
elseif startswith(str, "NOT")
~bobbycalculate(dict, str[5:end], cache)
elseif str in keys(dict)
bobbycalculate(dict, str, cache)
else
l, i, r = match(r"(.+) (AND|OR|[LR]SHIFT) (.+)", str)
lval = all(isdigit, l) ? parse(UInt16, l) : bobbycalculate(dict, l, cache)
instr = if i == "AND"
(&)
elseif i == "OR"
(|)
elseif i == "LSHIFT"
(<<)
elseif i == "RSHIFT"
(>>)
end
rval = all(isdigit, r) ? parse(UInt16, r) : bobbycalculate(dict, r, cache)
instr(lval, rval)
end
end
end
if basename(pwd()) == "aoc"
cd("2015/7")
end
part1() = bobbycalculate(loaddict("input.txt"), "a")
part2() = bobbycalculate(loaddict("input.txt"), "a", Dict("b"=>0xb3f1))
|
Suppose $f$ is a continuous function defined on the convex hull of three points $a$, $b$, and $c$. If the distances between these points are bounded by $K$, and if the integral of $f$ around the triangle formed by these points is at least $eK^2$, then there exists a triangle with vertices $a'$, $b'$, and $c'$ such that the distances between these points are bounded by $K/2$, and the integral of $f$ around this triangle is at least $e(K/2)^2$.
|
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
f g : α → ℝ≥0∞
⊢ ⨍⁻ (_x : α), 0 ∂μ = 0
[PROOFSTEP]
rw [laverage, lintegral_zero]
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
f✝ g f : α → ℝ≥0∞
⊢ ⨍⁻ (x : α), f x ∂0 = 0
[PROOFSTEP]
simp [laverage]
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
f✝ g f : α → ℝ≥0∞
⊢ ⨍⁻ (x : α), f x ∂μ = (∫⁻ (x : α), f x ∂μ) / ↑↑μ univ
[PROOFSTEP]
rw [laverage_eq', lintegral_smul_measure, ENNReal.div_eq_inv_mul]
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ ν : Measure α
s t : Set α
f✝ g : α → ℝ≥0∞
inst✝ : IsProbabilityMeasure μ
f : α → ℝ≥0∞
⊢ ⨍⁻ (x : α), f x ∂μ = ∫⁻ (x : α), f x ∂μ
[PROOFSTEP]
rw [laverage, measure_univ, inv_one, one_smul]
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ ν : Measure α
s t : Set α
f✝ g : α → ℝ≥0∞
inst✝ : IsFiniteMeasure μ
f : α → ℝ≥0∞
⊢ ↑↑μ univ * ⨍⁻ (x : α), f x ∂μ = ∫⁻ (x : α), f x ∂μ
[PROOFSTEP]
cases' eq_or_ne μ 0 with hμ hμ
[GOAL]
case inl
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ ν : Measure α
s t : Set α
f✝ g : α → ℝ≥0∞
inst✝ : IsFiniteMeasure μ
f : α → ℝ≥0∞
hμ : μ = 0
⊢ ↑↑μ univ * ⨍⁻ (x : α), f x ∂μ = ∫⁻ (x : α), f x ∂μ
[PROOFSTEP]
rw [hμ, lintegral_zero_measure, laverage_zero_measure, mul_zero]
[GOAL]
case inr
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ ν : Measure α
s t : Set α
f✝ g : α → ℝ≥0∞
inst✝ : IsFiniteMeasure μ
f : α → ℝ≥0∞
hμ : μ ≠ 0
⊢ ↑↑μ univ * ⨍⁻ (x : α), f x ∂μ = ∫⁻ (x : α), f x ∂μ
[PROOFSTEP]
rw [laverage_eq, ENNReal.mul_div_cancel' (measure_univ_ne_zero.2 hμ) (measure_ne_top _ _)]
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s✝ t : Set α
f✝ g f : α → ℝ≥0∞
s : Set α
⊢ ⨍⁻ (x : α) in s, f x ∂μ = (∫⁻ (x : α) in s, f x ∂μ) / ↑↑μ s
[PROOFSTEP]
rw [laverage_eq, restrict_apply_univ]
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s✝ t : Set α
f✝ g f : α → ℝ≥0∞
s : Set α
⊢ ⨍⁻ (x : α) in s, f x ∂μ = ∫⁻ (x : α), f x ∂(↑↑μ s)⁻¹ • Measure.restrict μ s
[PROOFSTEP]
simp only [laverage_eq', restrict_apply_univ]
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
f✝ g✝ f g : α → ℝ≥0∞
h : f =ᶠ[ae μ] g
⊢ ⨍⁻ (x : α), f x ∂μ = ⨍⁻ (x : α), g x ∂μ
[PROOFSTEP]
simp only [laverage_eq, lintegral_congr_ae h]
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
f g : α → ℝ≥0∞
h : s =ᶠ[ae μ] t
⊢ ⨍⁻ (x : α) in s, f x ∂μ = ⨍⁻ (x : α) in t, f x ∂μ
[PROOFSTEP]
simp only [setLaverage_eq, set_lintegral_congr h, measure_congr h]
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
f g : α → ℝ≥0∞
hs : MeasurableSet s
h : ∀ᵐ (x : α) ∂μ, x ∈ s → f x = g x
⊢ ⨍⁻ (x : α) in s, f x ∂μ = ⨍⁻ (x : α) in s, g x ∂μ
[PROOFSTEP]
simp only [laverage_eq, set_lintegral_congr_fun hs h]
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
f g : α → ℝ≥0∞
hf : ∫⁻ (x : α), f x ∂μ ≠ ⊤
⊢ ⨍⁻ (x : α), f x ∂μ < ⊤
[PROOFSTEP]
obtain rfl | hμ := eq_or_ne μ 0
[GOAL]
case inl
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
ν : Measure α
s t : Set α
f g : α → ℝ≥0∞
hf : ∫⁻ (x : α), f x ∂0 ≠ ⊤
⊢ ⨍⁻ (x : α), f x ∂0 < ⊤
[PROOFSTEP]
simp
[GOAL]
case inr
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
f g : α → ℝ≥0∞
hf : ∫⁻ (x : α), f x ∂μ ≠ ⊤
hμ : μ ≠ 0
⊢ ⨍⁻ (x : α), f x ∂μ < ⊤
[PROOFSTEP]
rw [laverage_eq]
[GOAL]
case inr
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
f g : α → ℝ≥0∞
hf : ∫⁻ (x : α), f x ∂μ ≠ ⊤
hμ : μ ≠ 0
⊢ (∫⁻ (x : α), f x ∂μ) / ↑↑μ univ < ⊤
[PROOFSTEP]
exact div_lt_top hf (measure_univ_ne_zero.2 hμ)
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
f g : α → ℝ≥0∞
⊢ ⨍⁻ (x : α), f x ∂(μ + ν) =
↑↑μ univ / (↑↑μ univ + ↑↑ν univ) * ⨍⁻ (x : α), f x ∂μ + ↑↑ν univ / (↑↑μ univ + ↑↑ν univ) * ⨍⁻ (x : α), f x ∂ν
[PROOFSTEP]
by_cases hμ : IsFiniteMeasure μ
[GOAL]
case pos
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
f g : α → ℝ≥0∞
hμ : IsFiniteMeasure μ
⊢ ⨍⁻ (x : α), f x ∂(μ + ν) =
↑↑μ univ / (↑↑μ univ + ↑↑ν univ) * ⨍⁻ (x : α), f x ∂μ + ↑↑ν univ / (↑↑μ univ + ↑↑ν univ) * ⨍⁻ (x : α), f x ∂ν
case neg
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
f g : α → ℝ≥0∞
hμ : ¬IsFiniteMeasure μ
⊢ ⨍⁻ (x : α), f x ∂(μ + ν) =
↑↑μ univ / (↑↑μ univ + ↑↑ν univ) * ⨍⁻ (x : α), f x ∂μ + ↑↑ν univ / (↑↑μ univ + ↑↑ν univ) * ⨍⁻ (x : α), f x ∂ν
[PROOFSTEP]
swap
[GOAL]
case neg
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
f g : α → ℝ≥0∞
hμ : ¬IsFiniteMeasure μ
⊢ ⨍⁻ (x : α), f x ∂(μ + ν) =
↑↑μ univ / (↑↑μ univ + ↑↑ν univ) * ⨍⁻ (x : α), f x ∂μ + ↑↑ν univ / (↑↑μ univ + ↑↑ν univ) * ⨍⁻ (x : α), f x ∂ν
[PROOFSTEP]
rw [not_isFiniteMeasure_iff] at hμ
[GOAL]
case neg
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
f g : α → ℝ≥0∞
hμ : ↑↑μ univ = ⊤
⊢ ⨍⁻ (x : α), f x ∂(μ + ν) =
↑↑μ univ / (↑↑μ univ + ↑↑ν univ) * ⨍⁻ (x : α), f x ∂μ + ↑↑ν univ / (↑↑μ univ + ↑↑ν univ) * ⨍⁻ (x : α), f x ∂ν
[PROOFSTEP]
simp [laverage_eq, hμ]
[GOAL]
case pos
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
f g : α → ℝ≥0∞
hμ : IsFiniteMeasure μ
⊢ ⨍⁻ (x : α), f x ∂(μ + ν) =
↑↑μ univ / (↑↑μ univ + ↑↑ν univ) * ⨍⁻ (x : α), f x ∂μ + ↑↑ν univ / (↑↑μ univ + ↑↑ν univ) * ⨍⁻ (x : α), f x ∂ν
[PROOFSTEP]
by_cases hν : IsFiniteMeasure ν
[GOAL]
case pos
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
f g : α → ℝ≥0∞
hμ : IsFiniteMeasure μ
hν : IsFiniteMeasure ν
⊢ ⨍⁻ (x : α), f x ∂(μ + ν) =
↑↑μ univ / (↑↑μ univ + ↑↑ν univ) * ⨍⁻ (x : α), f x ∂μ + ↑↑ν univ / (↑↑μ univ + ↑↑ν univ) * ⨍⁻ (x : α), f x ∂ν
case neg
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
f g : α → ℝ≥0∞
hμ : IsFiniteMeasure μ
hν : ¬IsFiniteMeasure ν
⊢ ⨍⁻ (x : α), f x ∂(μ + ν) =
↑↑μ univ / (↑↑μ univ + ↑↑ν univ) * ⨍⁻ (x : α), f x ∂μ + ↑↑ν univ / (↑↑μ univ + ↑↑ν univ) * ⨍⁻ (x : α), f x ∂ν
[PROOFSTEP]
swap
[GOAL]
case neg
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
f g : α → ℝ≥0∞
hμ : IsFiniteMeasure μ
hν : ¬IsFiniteMeasure ν
⊢ ⨍⁻ (x : α), f x ∂(μ + ν) =
↑↑μ univ / (↑↑μ univ + ↑↑ν univ) * ⨍⁻ (x : α), f x ∂μ + ↑↑ν univ / (↑↑μ univ + ↑↑ν univ) * ⨍⁻ (x : α), f x ∂ν
[PROOFSTEP]
rw [not_isFiniteMeasure_iff] at hν
[GOAL]
case neg
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
f g : α → ℝ≥0∞
hμ : IsFiniteMeasure μ
hν : ↑↑ν univ = ⊤
⊢ ⨍⁻ (x : α), f x ∂(μ + ν) =
↑↑μ univ / (↑↑μ univ + ↑↑ν univ) * ⨍⁻ (x : α), f x ∂μ + ↑↑ν univ / (↑↑μ univ + ↑↑ν univ) * ⨍⁻ (x : α), f x ∂ν
[PROOFSTEP]
simp [laverage_eq, hν]
[GOAL]
case pos
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
f g : α → ℝ≥0∞
hμ : IsFiniteMeasure μ
hν : IsFiniteMeasure ν
⊢ ⨍⁻ (x : α), f x ∂(μ + ν) =
↑↑μ univ / (↑↑μ univ + ↑↑ν univ) * ⨍⁻ (x : α), f x ∂μ + ↑↑ν univ / (↑↑μ univ + ↑↑ν univ) * ⨍⁻ (x : α), f x ∂ν
[PROOFSTEP]
haveI := hμ
[GOAL]
case pos
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
f g : α → ℝ≥0∞
hμ : IsFiniteMeasure μ
hν : IsFiniteMeasure ν
this : IsFiniteMeasure μ
⊢ ⨍⁻ (x : α), f x ∂(μ + ν) =
↑↑μ univ / (↑↑μ univ + ↑↑ν univ) * ⨍⁻ (x : α), f x ∂μ + ↑↑ν univ / (↑↑μ univ + ↑↑ν univ) * ⨍⁻ (x : α), f x ∂ν
[PROOFSTEP]
haveI := hν
[GOAL]
case pos
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
f g : α → ℝ≥0∞
hμ : IsFiniteMeasure μ
hν : IsFiniteMeasure ν
this✝ : IsFiniteMeasure μ
this : IsFiniteMeasure ν
⊢ ⨍⁻ (x : α), f x ∂(μ + ν) =
↑↑μ univ / (↑↑μ univ + ↑↑ν univ) * ⨍⁻ (x : α), f x ∂μ + ↑↑ν univ / (↑↑μ univ + ↑↑ν univ) * ⨍⁻ (x : α), f x ∂ν
[PROOFSTEP]
simp only [← ENNReal.mul_div_right_comm, measure_mul_laverage, ← ENNReal.add_div, ← lintegral_add_measure, ←
Measure.add_apply, ← laverage_eq]
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
f✝ g f : α → ℝ≥0∞
h : ↑↑μ s ≠ ⊤
⊢ ↑↑μ s * ⨍⁻ (x : α) in s, f x ∂μ = ∫⁻ (x : α) in s, f x ∂μ
[PROOFSTEP]
have := Fact.mk h.lt_top
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
f✝ g f : α → ℝ≥0∞
h : ↑↑μ s ≠ ⊤
this : Fact (↑↑μ s < ⊤)
⊢ ↑↑μ s * ⨍⁻ (x : α) in s, f x ∂μ = ∫⁻ (x : α) in s, f x ∂μ
[PROOFSTEP]
rw [← measure_mul_laverage, restrict_apply_univ]
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
f g : α → ℝ≥0∞
hd : AEDisjoint μ s t
ht : NullMeasurableSet t
⊢ ⨍⁻ (x : α) in s ∪ t, f x ∂μ =
↑↑μ s / (↑↑μ s + ↑↑μ t) * ⨍⁻ (x : α) in s, f x ∂μ + ↑↑μ t / (↑↑μ s + ↑↑μ t) * ⨍⁻ (x : α) in t, f x ∂μ
[PROOFSTEP]
rw [restrict_union₀ hd ht, laverage_add_measure, restrict_apply_univ, restrict_apply_univ]
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
f g : α → ℝ≥0∞
hd : AEDisjoint μ s t
ht : NullMeasurableSet t
hs₀ : ↑↑μ s ≠ 0
ht₀ : ↑↑μ t ≠ 0
hsμ : ↑↑μ s ≠ ⊤
htμ : ↑↑μ t ≠ ⊤
⊢ ⨍⁻ (x : α) in s ∪ t, f x ∂μ ∈ openSegment ℝ≥0∞ (⨍⁻ (x : α) in s, f x ∂μ) (⨍⁻ (x : α) in t, f x ∂μ)
[PROOFSTEP]
refine'
⟨μ s / (μ s + μ t), μ t / (μ s + μ t), ENNReal.div_pos hs₀ <| add_ne_top.2 ⟨hsμ, htμ⟩,
ENNReal.div_pos ht₀ <| add_ne_top.2 ⟨hsμ, htμ⟩, _, (laverage_union hd ht).symm⟩
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
f g : α → ℝ≥0∞
hd : AEDisjoint μ s t
ht : NullMeasurableSet t
hs₀ : ↑↑μ s ≠ 0
ht₀ : ↑↑μ t ≠ 0
hsμ : ↑↑μ s ≠ ⊤
htμ : ↑↑μ t ≠ ⊤
⊢ ↑↑μ s / (↑↑μ s + ↑↑μ t) + ↑↑μ t / (↑↑μ s + ↑↑μ t) = 1
[PROOFSTEP]
rw [← ENNReal.add_div, ENNReal.div_self (add_eq_zero.not.2 fun h => hs₀ h.1) (add_ne_top.2 ⟨hsμ, htμ⟩)]
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
f g : α → ℝ≥0∞
hd : AEDisjoint μ s t
ht : NullMeasurableSet t
hsμ : ↑↑μ s ≠ ⊤
htμ : ↑↑μ t ≠ ⊤
⊢ ⨍⁻ (x : α) in s ∪ t, f x ∂μ ∈ [⨍⁻ (x : α) in s, f x ∂μ-[ℝ≥0∞]⨍⁻ (x : α) in t, f x ∂μ]
[PROOFSTEP]
by_cases hs₀ : μ s = 0
[GOAL]
case pos
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
f g : α → ℝ≥0∞
hd : AEDisjoint μ s t
ht : NullMeasurableSet t
hsμ : ↑↑μ s ≠ ⊤
htμ : ↑↑μ t ≠ ⊤
hs₀ : ↑↑μ s = 0
⊢ ⨍⁻ (x : α) in s ∪ t, f x ∂μ ∈ [⨍⁻ (x : α) in s, f x ∂μ-[ℝ≥0∞]⨍⁻ (x : α) in t, f x ∂μ]
[PROOFSTEP]
rw [← ae_eq_empty] at hs₀
[GOAL]
case pos
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
f g : α → ℝ≥0∞
hd : AEDisjoint μ s t
ht : NullMeasurableSet t
hsμ : ↑↑μ s ≠ ⊤
htμ : ↑↑μ t ≠ ⊤
hs₀ : s =ᶠ[ae μ] ∅
⊢ ⨍⁻ (x : α) in s ∪ t, f x ∂μ ∈ [⨍⁻ (x : α) in s, f x ∂μ-[ℝ≥0∞]⨍⁻ (x : α) in t, f x ∂μ]
[PROOFSTEP]
rw [restrict_congr_set (hs₀.union EventuallyEq.rfl), empty_union]
[GOAL]
case pos
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
f g : α → ℝ≥0∞
hd : AEDisjoint μ s t
ht : NullMeasurableSet t
hsμ : ↑↑μ s ≠ ⊤
htμ : ↑↑μ t ≠ ⊤
hs₀ : s =ᶠ[ae μ] ∅
⊢ ⨍⁻ (x : α) in t, f x ∂μ ∈ [⨍⁻ (x : α) in s, f x ∂μ-[ℝ≥0∞]⨍⁻ (x : α) in t, f x ∂μ]
[PROOFSTEP]
exact right_mem_segment _ _ _
[GOAL]
case neg
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
f g : α → ℝ≥0∞
hd : AEDisjoint μ s t
ht : NullMeasurableSet t
hsμ : ↑↑μ s ≠ ⊤
htμ : ↑↑μ t ≠ ⊤
hs₀ : ¬↑↑μ s = 0
⊢ ⨍⁻ (x : α) in s ∪ t, f x ∂μ ∈ [⨍⁻ (x : α) in s, f x ∂μ-[ℝ≥0∞]⨍⁻ (x : α) in t, f x ∂μ]
[PROOFSTEP]
refine' ⟨μ s / (μ s + μ t), μ t / (μ s + μ t), zero_le _, zero_le _, _, (laverage_union hd ht).symm⟩
[GOAL]
case neg
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
f g : α → ℝ≥0∞
hd : AEDisjoint μ s t
ht : NullMeasurableSet t
hsμ : ↑↑μ s ≠ ⊤
htμ : ↑↑μ t ≠ ⊤
hs₀ : ¬↑↑μ s = 0
⊢ ↑↑μ s / (↑↑μ s + ↑↑μ t) + ↑↑μ t / (↑↑μ s + ↑↑μ t) = 1
[PROOFSTEP]
rw [← ENNReal.add_div, ENNReal.div_self (add_eq_zero.not.2 fun h => hs₀ h.1) (add_ne_top.2 ⟨hsμ, htμ⟩)]
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ ν : Measure α
s t : Set α
f g : α → ℝ≥0∞
inst✝ : IsFiniteMeasure μ
hs : NullMeasurableSet s
hs₀ : ↑↑μ s ≠ 0
hsc₀ : ↑↑μ sᶜ ≠ 0
⊢ ⨍⁻ (x : α), f x ∂μ ∈ openSegment ℝ≥0∞ (⨍⁻ (x : α) in s, f x ∂μ) (⨍⁻ (x : α) in sᶜ, f x ∂μ)
[PROOFSTEP]
simpa only [union_compl_self, restrict_univ] using
laverage_union_mem_openSegment aedisjoint_compl_right hs.compl hs₀ hsc₀ (measure_ne_top _ _) (measure_ne_top _ _)
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ✝ ν : Measure α
s t : Set α
f g : α → ℝ≥0∞
μ : Measure α
inst✝ : IsFiniteMeasure μ
h : NeZero μ
c : ℝ≥0∞
⊢ ⨍⁻ (_x : α), c ∂μ = c
[PROOFSTEP]
simp only [laverage, lintegral_const, measure_univ, mul_one]
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
f g : α → ℝ≥0∞
hs₀ : ↑↑μ s ≠ 0
hs : ↑↑μ s ≠ ⊤
c : ℝ≥0∞
⊢ ⨍⁻ (_x : α) in s, c ∂μ = c
[PROOFSTEP]
simp only [setLaverage_eq, lintegral_const, Measure.restrict_apply, MeasurableSet.univ, univ_inter, div_eq_mul_inv,
mul_assoc, ENNReal.mul_inv_cancel hs₀ hs, mul_one]
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ✝ ν : Measure α
s t : Set α
f✝ g : α → ℝ≥0∞
μ : Measure α
inst✝ : IsFiniteMeasure μ
f : α → ℝ≥0∞
⊢ ∫⁻ (_x : α), ⨍⁻ (a : α), f a ∂μ ∂μ = ∫⁻ (x : α), f x ∂μ
[PROOFSTEP]
obtain rfl | hμ := eq_or_ne μ 0
[GOAL]
case inl
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ ν : Measure α
s t : Set α
f✝ g f : α → ℝ≥0∞
inst✝ : IsFiniteMeasure 0
⊢ ∫⁻ (_x : α), ⨍⁻ (a : α), f a ∂0 ∂0 = ∫⁻ (x : α), f x ∂0
[PROOFSTEP]
simp
[GOAL]
case inr
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ✝ ν : Measure α
s t : Set α
f✝ g : α → ℝ≥0∞
μ : Measure α
inst✝ : IsFiniteMeasure μ
f : α → ℝ≥0∞
hμ : μ ≠ 0
⊢ ∫⁻ (_x : α), ⨍⁻ (a : α), f a ∂μ ∂μ = ∫⁻ (x : α), f x ∂μ
[PROOFSTEP]
rw [lintegral_const, laverage_eq, ENNReal.div_mul_cancel (measure_univ_ne_zero.2 hμ) (measure_ne_top _ _)]
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
f g : α → E
⊢ ⨍ (x : α), 0 ∂μ = 0
[PROOFSTEP]
rw [average, integral_zero]
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
f✝ g f : α → E
⊢ ⨍ (x : α), f x ∂0 = 0
[PROOFSTEP]
rw [average, smul_zero, integral_zero_measure]
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
f✝ g f : α → E
⊢ ⨍ (x : α), f x ∂μ = (ENNReal.toReal (↑↑μ univ))⁻¹ • ∫ (x : α), f x ∂μ
[PROOFSTEP]
rw [average_eq', integral_smul_measure, ENNReal.toReal_inv]
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ ν : Measure α
s t : Set α
f✝ g : α → E
inst✝ : IsProbabilityMeasure μ
f : α → E
⊢ ⨍ (x : α), f x ∂μ = ∫ (x : α), f x ∂μ
[PROOFSTEP]
rw [average, measure_univ, inv_one, one_smul]
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ ν : Measure α
s t : Set α
f✝ g : α → E
inst✝ : IsFiniteMeasure μ
f : α → E
⊢ ENNReal.toReal (↑↑μ univ) • ⨍ (x : α), f x ∂μ = ∫ (x : α), f x ∂μ
[PROOFSTEP]
cases' eq_or_ne μ 0 with hμ hμ
[GOAL]
case inl
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ ν : Measure α
s t : Set α
f✝ g : α → E
inst✝ : IsFiniteMeasure μ
f : α → E
hμ : μ = 0
⊢ ENNReal.toReal (↑↑μ univ) • ⨍ (x : α), f x ∂μ = ∫ (x : α), f x ∂μ
[PROOFSTEP]
rw [hμ, integral_zero_measure, average_zero_measure, smul_zero]
[GOAL]
case inr
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ ν : Measure α
s t : Set α
f✝ g : α → E
inst✝ : IsFiniteMeasure μ
f : α → E
hμ : μ ≠ 0
⊢ ENNReal.toReal (↑↑μ univ) • ⨍ (x : α), f x ∂μ = ∫ (x : α), f x ∂μ
[PROOFSTEP]
rw [average_eq, smul_inv_smul₀]
[GOAL]
case inr.hc
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ ν : Measure α
s t : Set α
f✝ g : α → E
inst✝ : IsFiniteMeasure μ
f : α → E
hμ : μ ≠ 0
⊢ ENNReal.toReal (↑↑μ univ) ≠ 0
[PROOFSTEP]
refine' (ENNReal.toReal_pos _ <| measure_ne_top _ _).ne'
[GOAL]
case inr.hc
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ ν : Measure α
s t : Set α
f✝ g : α → E
inst✝ : IsFiniteMeasure μ
f : α → E
hμ : μ ≠ 0
⊢ ↑↑μ univ ≠ 0
[PROOFSTEP]
rwa [Ne.def, measure_univ_eq_zero]
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s✝ t : Set α
f✝ g f : α → E
s : Set α
⊢ ⨍ (x : α) in s, f x ∂μ = (ENNReal.toReal (↑↑μ s))⁻¹ • ∫ (x : α) in s, f x ∂μ
[PROOFSTEP]
rw [average_eq, restrict_apply_univ]
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s✝ t : Set α
f✝ g f : α → E
s : Set α
⊢ ⨍ (x : α) in s, f x ∂μ = ∫ (x : α), f x ∂(↑↑μ s)⁻¹ • Measure.restrict μ s
[PROOFSTEP]
simp only [average_eq', restrict_apply_univ]
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
f✝ g✝ f g : α → E
h : f =ᶠ[ae μ] g
⊢ ⨍ (x : α), f x ∂μ = ⨍ (x : α), g x ∂μ
[PROOFSTEP]
simp only [average_eq, integral_congr_ae h]
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
f g : α → E
h : s =ᶠ[ae μ] t
⊢ ⨍ (x : α) in s, f x ∂μ = ⨍ (x : α) in t, f x ∂μ
[PROOFSTEP]
simp only [setAverage_eq, set_integral_congr_set_ae h, measure_congr h]
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
f g : α → E
hs : MeasurableSet s
h : ∀ᵐ (x : α) ∂μ, x ∈ s → f x = g x
⊢ ⨍ (x : α) in s, f x ∂μ = ⨍ (x : α) in s, g x ∂μ
[PROOFSTEP]
simp only [average_eq, set_integral_congr_ae hs h]
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace ℝ E
inst✝⁵ : CompleteSpace E
inst✝⁴ : NormedAddCommGroup F
inst✝³ : NormedSpace ℝ F
inst✝² : CompleteSpace F
μ ν✝ : Measure α
s t : Set α
f✝ g : α → E
inst✝¹ : IsFiniteMeasure μ
ν : Measure α
inst✝ : IsFiniteMeasure ν
f : α → E
hμ : Integrable f
hν : Integrable f
⊢ ⨍ (x : α), f x ∂(μ + ν) =
(ENNReal.toReal (↑↑μ univ) / (ENNReal.toReal (↑↑μ univ) + ENNReal.toReal (↑↑ν univ))) • ⨍ (x : α), f x ∂μ +
(ENNReal.toReal (↑↑ν univ) / (ENNReal.toReal (↑↑μ univ) + ENNReal.toReal (↑↑ν univ))) • ⨍ (x : α), f x ∂ν
[PROOFSTEP]
simp only [div_eq_inv_mul, mul_smul, measure_smul_average, ← smul_add, ← integral_add_measure hμ hν, ←
ENNReal.toReal_add (measure_ne_top μ _) (measure_ne_top ν _)]
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace ℝ E
inst✝⁵ : CompleteSpace E
inst✝⁴ : NormedAddCommGroup F
inst✝³ : NormedSpace ℝ F
inst✝² : CompleteSpace F
μ ν✝ : Measure α
s t : Set α
f✝ g : α → E
inst✝¹ : IsFiniteMeasure μ
ν : Measure α
inst✝ : IsFiniteMeasure ν
f : α → E
hμ : Integrable f
hν : Integrable f
⊢ ⨍ (x : α), f x ∂(μ + ν) = (ENNReal.toReal (↑↑μ univ + ↑↑ν univ))⁻¹ • ∫ (x : α), f x ∂(μ + ν)
[PROOFSTEP]
rw [average_eq, Measure.add_apply]
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s✝ t : Set α
f✝ g f : α → E
s : Set α
h : ↑↑μ s ≠ ⊤
⊢ ENNReal.toReal (↑↑μ s) • ⨍ (x : α) in s, f x ∂μ = ∫ (x : α) in s, f x ∂μ
[PROOFSTEP]
haveI := Fact.mk h.lt_top
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s✝ t : Set α
f✝ g f : α → E
s : Set α
h : ↑↑μ s ≠ ⊤
this : Fact (↑↑μ s < ⊤)
⊢ ENNReal.toReal (↑↑μ s) • ⨍ (x : α) in s, f x ∂μ = ∫ (x : α) in s, f x ∂μ
[PROOFSTEP]
rw [← measure_smul_average, restrict_apply_univ]
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s✝ t✝ : Set α
f✝ g f : α → E
s t : Set α
hd : AEDisjoint μ s t
ht : NullMeasurableSet t
hsμ : ↑↑μ s ≠ ⊤
htμ : ↑↑μ t ≠ ⊤
hfs : IntegrableOn f s
hft : IntegrableOn f t
⊢ ⨍ (x : α) in s ∪ t, f x ∂μ =
(ENNReal.toReal (↑↑μ s) / (ENNReal.toReal (↑↑μ s) + ENNReal.toReal (↑↑μ t))) • ⨍ (x : α) in s, f x ∂μ +
(ENNReal.toReal (↑↑μ t) / (ENNReal.toReal (↑↑μ s) + ENNReal.toReal (↑↑μ t))) • ⨍ (x : α) in t, f x ∂μ
[PROOFSTEP]
haveI := Fact.mk hsμ.lt_top
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s✝ t✝ : Set α
f✝ g f : α → E
s t : Set α
hd : AEDisjoint μ s t
ht : NullMeasurableSet t
hsμ : ↑↑μ s ≠ ⊤
htμ : ↑↑μ t ≠ ⊤
hfs : IntegrableOn f s
hft : IntegrableOn f t
this : Fact (↑↑μ s < ⊤)
⊢ ⨍ (x : α) in s ∪ t, f x ∂μ =
(ENNReal.toReal (↑↑μ s) / (ENNReal.toReal (↑↑μ s) + ENNReal.toReal (↑↑μ t))) • ⨍ (x : α) in s, f x ∂μ +
(ENNReal.toReal (↑↑μ t) / (ENNReal.toReal (↑↑μ s) + ENNReal.toReal (↑↑μ t))) • ⨍ (x : α) in t, f x ∂μ
[PROOFSTEP]
haveI := Fact.mk htμ.lt_top
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s✝ t✝ : Set α
f✝ g f : α → E
s t : Set α
hd : AEDisjoint μ s t
ht : NullMeasurableSet t
hsμ : ↑↑μ s ≠ ⊤
htμ : ↑↑μ t ≠ ⊤
hfs : IntegrableOn f s
hft : IntegrableOn f t
this✝ : Fact (↑↑μ s < ⊤)
this : Fact (↑↑μ t < ⊤)
⊢ ⨍ (x : α) in s ∪ t, f x ∂μ =
(ENNReal.toReal (↑↑μ s) / (ENNReal.toReal (↑↑μ s) + ENNReal.toReal (↑↑μ t))) • ⨍ (x : α) in s, f x ∂μ +
(ENNReal.toReal (↑↑μ t) / (ENNReal.toReal (↑↑μ s) + ENNReal.toReal (↑↑μ t))) • ⨍ (x : α) in t, f x ∂μ
[PROOFSTEP]
rw [restrict_union₀ hd ht, average_add_measure hfs hft, restrict_apply_univ, restrict_apply_univ]
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s✝ t✝ : Set α
f✝ g f : α → E
s t : Set α
hd : AEDisjoint μ s t
ht : NullMeasurableSet t
hs₀ : ↑↑μ s ≠ 0
ht₀ : ↑↑μ t ≠ 0
hsμ : ↑↑μ s ≠ ⊤
htμ : ↑↑μ t ≠ ⊤
hfs : IntegrableOn f s
hft : IntegrableOn f t
⊢ ⨍ (x : α) in s ∪ t, f x ∂μ ∈ openSegment ℝ (⨍ (x : α) in s, f x ∂μ) (⨍ (x : α) in t, f x ∂μ)
[PROOFSTEP]
replace hs₀ : 0 < (μ s).toReal
[GOAL]
case hs₀
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s✝ t✝ : Set α
f✝ g f : α → E
s t : Set α
hd : AEDisjoint μ s t
ht : NullMeasurableSet t
hs₀ : ↑↑μ s ≠ 0
ht₀ : ↑↑μ t ≠ 0
hsμ : ↑↑μ s ≠ ⊤
htμ : ↑↑μ t ≠ ⊤
hfs : IntegrableOn f s
hft : IntegrableOn f t
⊢ 0 < ENNReal.toReal (↑↑μ s)
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s✝ t✝ : Set α
f✝ g f : α → E
s t : Set α
hd : AEDisjoint μ s t
ht : NullMeasurableSet t
ht₀ : ↑↑μ t ≠ 0
hsμ : ↑↑μ s ≠ ⊤
htμ : ↑↑μ t ≠ ⊤
hfs : IntegrableOn f s
hft : IntegrableOn f t
hs₀ : 0 < ENNReal.toReal (↑↑μ s)
⊢ ⨍ (x : α) in s ∪ t, f x ∂μ ∈ openSegment ℝ (⨍ (x : α) in s, f x ∂μ) (⨍ (x : α) in t, f x ∂μ)
[PROOFSTEP]
exact ENNReal.toReal_pos hs₀ hsμ
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s✝ t✝ : Set α
f✝ g f : α → E
s t : Set α
hd : AEDisjoint μ s t
ht : NullMeasurableSet t
ht₀ : ↑↑μ t ≠ 0
hsμ : ↑↑μ s ≠ ⊤
htμ : ↑↑μ t ≠ ⊤
hfs : IntegrableOn f s
hft : IntegrableOn f t
hs₀ : 0 < ENNReal.toReal (↑↑μ s)
⊢ ⨍ (x : α) in s ∪ t, f x ∂μ ∈ openSegment ℝ (⨍ (x : α) in s, f x ∂μ) (⨍ (x : α) in t, f x ∂μ)
[PROOFSTEP]
replace ht₀ : 0 < (μ t).toReal
[GOAL]
case ht₀
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s✝ t✝ : Set α
f✝ g f : α → E
s t : Set α
hd : AEDisjoint μ s t
ht : NullMeasurableSet t
ht₀ : ↑↑μ t ≠ 0
hsμ : ↑↑μ s ≠ ⊤
htμ : ↑↑μ t ≠ ⊤
hfs : IntegrableOn f s
hft : IntegrableOn f t
hs₀ : 0 < ENNReal.toReal (↑↑μ s)
⊢ 0 < ENNReal.toReal (↑↑μ t)
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s✝ t✝ : Set α
f✝ g f : α → E
s t : Set α
hd : AEDisjoint μ s t
ht : NullMeasurableSet t
hsμ : ↑↑μ s ≠ ⊤
htμ : ↑↑μ t ≠ ⊤
hfs : IntegrableOn f s
hft : IntegrableOn f t
hs₀ : 0 < ENNReal.toReal (↑↑μ s)
ht₀ : 0 < ENNReal.toReal (↑↑μ t)
⊢ ⨍ (x : α) in s ∪ t, f x ∂μ ∈ openSegment ℝ (⨍ (x : α) in s, f x ∂μ) (⨍ (x : α) in t, f x ∂μ)
[PROOFSTEP]
exact ENNReal.toReal_pos ht₀ htμ
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s✝ t✝ : Set α
f✝ g f : α → E
s t : Set α
hd : AEDisjoint μ s t
ht : NullMeasurableSet t
hsμ : ↑↑μ s ≠ ⊤
htμ : ↑↑μ t ≠ ⊤
hfs : IntegrableOn f s
hft : IntegrableOn f t
hs₀ : 0 < ENNReal.toReal (↑↑μ s)
ht₀ : 0 < ENNReal.toReal (↑↑μ t)
⊢ ⨍ (x : α) in s ∪ t, f x ∂μ ∈ openSegment ℝ (⨍ (x : α) in s, f x ∂μ) (⨍ (x : α) in t, f x ∂μ)
[PROOFSTEP]
refine' mem_openSegment_iff_div.mpr ⟨(μ s).toReal, (μ t).toReal, hs₀, ht₀, (average_union hd ht hsμ htμ hfs hft).symm⟩
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s✝ t✝ : Set α
f✝ g f : α → E
s t : Set α
hd : AEDisjoint μ s t
ht : NullMeasurableSet t
hsμ : ↑↑μ s ≠ ⊤
htμ : ↑↑μ t ≠ ⊤
hfs : IntegrableOn f s
hft : IntegrableOn f t
⊢ ⨍ (x : α) in s ∪ t, f x ∂μ ∈ [⨍ (x : α) in s, f x ∂μ-[ℝ]⨍ (x : α) in t, f x ∂μ]
[PROOFSTEP]
by_cases hse : μ s = 0
[GOAL]
case pos
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s✝ t✝ : Set α
f✝ g f : α → E
s t : Set α
hd : AEDisjoint μ s t
ht : NullMeasurableSet t
hsμ : ↑↑μ s ≠ ⊤
htμ : ↑↑μ t ≠ ⊤
hfs : IntegrableOn f s
hft : IntegrableOn f t
hse : ↑↑μ s = 0
⊢ ⨍ (x : α) in s ∪ t, f x ∂μ ∈ [⨍ (x : α) in s, f x ∂μ-[ℝ]⨍ (x : α) in t, f x ∂μ]
[PROOFSTEP]
rw [← ae_eq_empty] at hse
[GOAL]
case pos
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s✝ t✝ : Set α
f✝ g f : α → E
s t : Set α
hd : AEDisjoint μ s t
ht : NullMeasurableSet t
hsμ : ↑↑μ s ≠ ⊤
htμ : ↑↑μ t ≠ ⊤
hfs : IntegrableOn f s
hft : IntegrableOn f t
hse : s =ᶠ[ae μ] ∅
⊢ ⨍ (x : α) in s ∪ t, f x ∂μ ∈ [⨍ (x : α) in s, f x ∂μ-[ℝ]⨍ (x : α) in t, f x ∂μ]
[PROOFSTEP]
rw [restrict_congr_set (hse.union EventuallyEq.rfl), empty_union]
[GOAL]
case pos
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s✝ t✝ : Set α
f✝ g f : α → E
s t : Set α
hd : AEDisjoint μ s t
ht : NullMeasurableSet t
hsμ : ↑↑μ s ≠ ⊤
htμ : ↑↑μ t ≠ ⊤
hfs : IntegrableOn f s
hft : IntegrableOn f t
hse : s =ᶠ[ae μ] ∅
⊢ ⨍ (x : α) in t, f x ∂μ ∈ [⨍ (x : α) in s, f x ∂μ-[ℝ]⨍ (x : α) in t, f x ∂μ]
[PROOFSTEP]
exact right_mem_segment _ _ _
[GOAL]
case neg
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s✝ t✝ : Set α
f✝ g f : α → E
s t : Set α
hd : AEDisjoint μ s t
ht : NullMeasurableSet t
hsμ : ↑↑μ s ≠ ⊤
htμ : ↑↑μ t ≠ ⊤
hfs : IntegrableOn f s
hft : IntegrableOn f t
hse : ¬↑↑μ s = 0
⊢ ⨍ (x : α) in s ∪ t, f x ∂μ ∈ [⨍ (x : α) in s, f x ∂μ-[ℝ]⨍ (x : α) in t, f x ∂μ]
[PROOFSTEP]
refine'
mem_segment_iff_div.mpr
⟨(μ s).toReal, (μ t).toReal, ENNReal.toReal_nonneg, ENNReal.toReal_nonneg, _,
(average_union hd ht hsμ htμ hfs hft).symm⟩
[GOAL]
case neg
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s✝ t✝ : Set α
f✝ g f : α → E
s t : Set α
hd : AEDisjoint μ s t
ht : NullMeasurableSet t
hsμ : ↑↑μ s ≠ ⊤
htμ : ↑↑μ t ≠ ⊤
hfs : IntegrableOn f s
hft : IntegrableOn f t
hse : ¬↑↑μ s = 0
⊢ 0 < ENNReal.toReal (↑↑μ s) + ENNReal.toReal (↑↑μ t)
[PROOFSTEP]
calc
0 < (μ s).toReal := ENNReal.toReal_pos hse hsμ
_ ≤ _ := le_add_of_nonneg_right ENNReal.toReal_nonneg
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ ν : Measure α
s✝ t : Set α
f✝ g : α → E
inst✝ : IsFiniteMeasure μ
f : α → E
s : Set α
hs : NullMeasurableSet s
hs₀ : ↑↑μ s ≠ 0
hsc₀ : ↑↑μ sᶜ ≠ 0
hfi : Integrable f
⊢ ⨍ (x : α), f x ∂μ ∈ openSegment ℝ (⨍ (x : α) in s, f x ∂μ) (⨍ (x : α) in sᶜ, f x ∂μ)
[PROOFSTEP]
simpa only [union_compl_self, restrict_univ] using
average_union_mem_openSegment aedisjoint_compl_right hs.compl hs₀ hsc₀ (measure_ne_top _ _) (measure_ne_top _ _)
hfi.integrableOn hfi.integrableOn
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ✝ ν : Measure α
s t : Set α
f g : α → E
μ : Measure α
inst✝ : IsFiniteMeasure μ
h : NeZero μ
c : E
⊢ ⨍ (_x : α), c ∂μ = c
[PROOFSTEP]
rw [average, integral_const, measure_univ, ENNReal.one_toReal, one_smul]
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ✝ ν : Measure α
s t : Set α
f✝ g : α → E
μ : Measure α
inst✝ : IsFiniteMeasure μ
f : α → E
⊢ ∫ (x : α), ⨍ (a : α), f a ∂μ ∂μ = ∫ (x : α), f x ∂μ
[PROOFSTEP]
simp
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ✝ ν : Measure α
s t : Set α
f✝ g : α → E
μ : Measure α
inst✝ : IsFiniteMeasure μ
f : α → E
⊢ ∫ (x : α), f x - ⨍ (a : α), f a ∂μ ∂μ = 0
[PROOFSTEP]
by_cases hf : Integrable f μ
[GOAL]
case pos
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ✝ ν : Measure α
s t : Set α
f✝ g : α → E
μ : Measure α
inst✝ : IsFiniteMeasure μ
f : α → E
hf : Integrable f
⊢ ∫ (x : α), f x - ⨍ (a : α), f a ∂μ ∂μ = 0
[PROOFSTEP]
rw [integral_sub hf (integrable_const _), integral_average, sub_self]
[GOAL]
case neg
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ✝ ν : Measure α
s t : Set α
f✝ g : α → E
μ : Measure α
inst✝ : IsFiniteMeasure μ
f : α → E
hf : ¬Integrable f
⊢ ∫ (x : α), f x - ⨍ (a : α), f a ∂μ ∂μ = 0
[PROOFSTEP]
refine integral_undef fun h => hf ?_
[GOAL]
case neg
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ✝ ν : Measure α
s t : Set α
f✝ g : α → E
μ : Measure α
inst✝ : IsFiniteMeasure μ
f : α → E
hf : ¬Integrable f
h : Integrable fun x => f x - ⨍ (a : α), f a ∂μ
⊢ Integrable f
[PROOFSTEP]
convert h.add (integrable_const (⨍ a, f a ∂μ))
[GOAL]
case h.e'_5
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ✝ ν : Measure α
s t : Set α
f✝ g : α → E
μ : Measure α
inst✝ : IsFiniteMeasure μ
f : α → E
hf : ¬Integrable f
h : Integrable fun x => f x - ⨍ (a : α), f a ∂μ
⊢ f = (fun x => f x - ⨍ (a : α), f a ∂μ) + fun x => ⨍ (a : α), f a ∂μ
[PROOFSTEP]
exact (sub_add_cancel _ _).symm
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ ν : Measure α
s t : Set α
f g : α → E
inst✝ : IsFiniteMeasure μ
hf : Integrable f
⊢ ∫ (x : α), ⨍ (a : α), f a ∂μ - f x ∂μ = 0
[PROOFSTEP]
rw [integral_sub (integrable_const _) hf, integral_average, sub_self]
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
f : α → ℝ
hf : Integrable f
hf₀ : 0 ≤ᶠ[ae μ] f
⊢ ENNReal.ofReal (⨍ (x : α), f x ∂μ) = (∫⁻ (x : α), ENNReal.ofReal (f x) ∂μ) / ↑↑μ univ
[PROOFSTEP]
obtain rfl | hμ := eq_or_ne μ 0
[GOAL]
case inl
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
ν : Measure α
s t : Set α
f : α → ℝ
hf : Integrable f
hf₀ : 0 ≤ᶠ[ae 0] f
⊢ ENNReal.ofReal (⨍ (x : α), f x ∂0) = (∫⁻ (x : α), ENNReal.ofReal (f x) ∂0) / ↑↑0 univ
[PROOFSTEP]
simp
[GOAL]
case inr
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
f : α → ℝ
hf : Integrable f
hf₀ : 0 ≤ᶠ[ae μ] f
hμ : μ ≠ 0
⊢ ENNReal.ofReal (⨍ (x : α), f x ∂μ) = (∫⁻ (x : α), ENNReal.ofReal (f x) ∂μ) / ↑↑μ univ
[PROOFSTEP]
rw [average_eq, smul_eq_mul, ← toReal_inv, ofReal_mul toReal_nonneg,
ofReal_toReal (inv_ne_top.2 <| measure_univ_ne_zero.2 hμ), ofReal_integral_eq_lintegral_ofReal hf hf₀,
ENNReal.div_eq_inv_mul]
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
f : α → ℝ
hf : IntegrableOn f s
hf₀ : 0 ≤ᶠ[ae (Measure.restrict μ s)] f
⊢ ENNReal.ofReal (⨍ (x : α) in s, f x ∂μ) = (∫⁻ (x : α) in s, ENNReal.ofReal (f x) ∂μ) / ↑↑μ s
[PROOFSTEP]
simpa using ofReal_average hf hf₀
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
f : α → ℝ≥0∞
hf : AEMeasurable f
hf' : ∀ᵐ (x : α) ∂μ, f x ≠ ⊤
⊢ ENNReal.toReal (⨍⁻ (x : α), f x ∂μ) = ⨍ (x : α), ENNReal.toReal (f x) ∂μ
[PROOFSTEP]
rw [average_eq, laverage_eq, smul_eq_mul, toReal_div, div_eq_inv_mul, ←
integral_toReal hf (hf'.mono fun _ => lt_top_iff_ne_top.2)]
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
f : α → ℝ≥0∞
hf : AEMeasurable f
hf' : ∀ᵐ (x : α) ∂Measure.restrict μ s, f x ≠ ⊤
⊢ ENNReal.toReal (⨍⁻ (x : α) in s, f x ∂μ) = ⨍ (x : α) in s, ENNReal.toReal (f x) ∂μ
[PROOFSTEP]
simpa [laverage_eq] using toReal_laverage hf hf'
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ
hμ : ↑↑μ s ≠ 0
hμ₁ : ↑↑μ s ≠ ⊤
hf : IntegrableOn f s
⊢ 0 < ↑↑μ {x | x ∈ s ∧ f x ≤ ⨍ (a : α) in s, f a ∂μ}
[PROOFSTEP]
refine' pos_iff_ne_zero.2 fun H => _
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ
hμ : ↑↑μ s ≠ 0
hμ₁ : ↑↑μ s ≠ ⊤
hf : IntegrableOn f s
H : ↑↑μ {x | x ∈ s ∧ f x ≤ ⨍ (a : α) in s, f a ∂μ} = 0
⊢ False
[PROOFSTEP]
replace H : (μ.restrict s) {x | f x ≤ ⨍ a in s, f a ∂μ} = 0
[GOAL]
case H
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ
hμ : ↑↑μ s ≠ 0
hμ₁ : ↑↑μ s ≠ ⊤
hf : IntegrableOn f s
H : ↑↑μ {x | x ∈ s ∧ f x ≤ ⨍ (a : α) in s, f a ∂μ} = 0
⊢ ↑↑(Measure.restrict μ s) {x | f x ≤ ⨍ (a : α) in s, f a ∂μ} = 0
[PROOFSTEP]
rwa [restrict_apply₀, inter_comm]
[GOAL]
case H
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ
hμ : ↑↑μ s ≠ 0
hμ₁ : ↑↑μ s ≠ ⊤
hf : IntegrableOn f s
H : ↑↑μ {x | x ∈ s ∧ f x ≤ ⨍ (a : α) in s, f a ∂μ} = 0
⊢ NullMeasurableSet {x | f x ≤ ⨍ (a : α) in s, f a ∂μ}
[PROOFSTEP]
exact AEStronglyMeasurable.nullMeasurableSet_le hf.1 aestronglyMeasurable_const
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ
hμ : ↑↑μ s ≠ 0
hμ₁ : ↑↑μ s ≠ ⊤
hf : IntegrableOn f s
H : ↑↑(Measure.restrict μ s) {x | f x ≤ ⨍ (a : α) in s, f a ∂μ} = 0
⊢ False
[PROOFSTEP]
haveI := Fact.mk hμ₁.lt_top
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ
hμ : ↑↑μ s ≠ 0
hμ₁ : ↑↑μ s ≠ ⊤
hf : IntegrableOn f s
H : ↑↑(Measure.restrict μ s) {x | f x ≤ ⨍ (a : α) in s, f a ∂μ} = 0
this : Fact (↑↑μ s < ⊤)
⊢ False
[PROOFSTEP]
refine' (integral_sub_average (μ.restrict s) f).not_gt _
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ
hμ : ↑↑μ s ≠ 0
hμ₁ : ↑↑μ s ≠ ⊤
hf : IntegrableOn f s
H : ↑↑(Measure.restrict μ s) {x | f x ≤ ⨍ (a : α) in s, f a ∂μ} = 0
this : Fact (↑↑μ s < ⊤)
⊢ 0 < ∫ (x : α) in s, f x - ⨍ (a : α) in s, f a ∂μ ∂μ
[PROOFSTEP]
refine' (set_integral_pos_iff_support_of_nonneg_ae _ _).2 _
[GOAL]
case refine'_1
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ
hμ : ↑↑μ s ≠ 0
hμ₁ : ↑↑μ s ≠ ⊤
hf : IntegrableOn f s
H : ↑↑(Measure.restrict μ s) {x | f x ≤ ⨍ (a : α) in s, f a ∂μ} = 0
this : Fact (↑↑μ s < ⊤)
⊢ 0 ≤ᶠ[ae (Measure.restrict μ s)] fun x => f x - ⨍ (a : α) in s, f a ∂μ
[PROOFSTEP]
refine' eq_bot_mono (measure_mono fun x hx => _) H
[GOAL]
case refine'_1
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ
hμ : ↑↑μ s ≠ 0
hμ₁ : ↑↑μ s ≠ ⊤
hf : IntegrableOn f s
H : ↑↑(Measure.restrict μ s) {x | f x ≤ ⨍ (a : α) in s, f a ∂μ} = 0
this : Fact (↑↑μ s < ⊤)
x : α
hx : x ∈ {x | (fun x => OfNat.ofNat 0 x ≤ (fun x => f x - ⨍ (a : α) in s, f a ∂μ) x) x}ᶜ
⊢ x ∈ {x | f x ≤ ⨍ (a : α) in s, f a ∂μ}
[PROOFSTEP]
simp only [Pi.zero_apply, sub_nonneg, mem_compl_iff, mem_setOf_eq, not_le] at hx
[GOAL]
case refine'_1
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ
hμ : ↑↑μ s ≠ 0
hμ₁ : ↑↑μ s ≠ ⊤
hf : IntegrableOn f s
H : ↑↑(Measure.restrict μ s) {x | f x ≤ ⨍ (a : α) in s, f a ∂μ} = 0
this : Fact (↑↑μ s < ⊤)
x : α
hx : f x < ⨍ (a : α) in s, f a ∂μ
⊢ x ∈ {x | f x ≤ ⨍ (a : α) in s, f a ∂μ}
[PROOFSTEP]
exact hx.le
[GOAL]
case refine'_2
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ
hμ : ↑↑μ s ≠ 0
hμ₁ : ↑↑μ s ≠ ⊤
hf : IntegrableOn f s
H : ↑↑(Measure.restrict μ s) {x | f x ≤ ⨍ (a : α) in s, f a ∂μ} = 0
this : Fact (↑↑μ s < ⊤)
⊢ IntegrableOn (fun x => f x - ⨍ (a : α) in s, f a ∂μ) s
[PROOFSTEP]
exact hf.sub (integrableOn_const.2 <| Or.inr <| lt_top_iff_ne_top.2 hμ₁)
[GOAL]
case refine'_3
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ
hμ : ↑↑μ s ≠ 0
hμ₁ : ↑↑μ s ≠ ⊤
hf : IntegrableOn f s
H : ↑↑(Measure.restrict μ s) {x | f x ≤ ⨍ (a : α) in s, f a ∂μ} = 0
this : Fact (↑↑μ s < ⊤)
⊢ 0 < ↑↑μ ((support fun x => f x - ⨍ (a : α) in s, f a ∂μ) ∩ s)
[PROOFSTEP]
rwa [pos_iff_ne_zero, inter_comm, ← diff_compl, ← diff_inter_self_eq_diff, measure_diff_null]
[GOAL]
case refine'_3
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ
hμ : ↑↑μ s ≠ 0
hμ₁ : ↑↑μ s ≠ ⊤
hf : IntegrableOn f s
H : ↑↑(Measure.restrict μ s) {x | f x ≤ ⨍ (a : α) in s, f a ∂μ} = 0
this : Fact (↑↑μ s < ⊤)
⊢ ↑↑μ ((support fun x => f x - ⨍ (a : α) in s, f a ∂μ)ᶜ ∩ s) = 0
[PROOFSTEP]
refine' eq_bot_mono (measure_mono _) (measure_inter_eq_zero_of_restrict H)
[GOAL]
case refine'_3
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ
hμ : ↑↑μ s ≠ 0
hμ₁ : ↑↑μ s ≠ ⊤
hf : IntegrableOn f s
H : ↑↑(Measure.restrict μ s) {x | f x ≤ ⨍ (a : α) in s, f a ∂μ} = 0
this : Fact (↑↑μ s < ⊤)
⊢ (support fun x => f x - ⨍ (a : α) in s, f a ∂μ)ᶜ ∩ s ⊆ {x | f x ≤ ⨍ (a : α) in s, f a ∂μ} ∩ s
[PROOFSTEP]
exact inter_subset_inter_left _ fun a ha => (sub_eq_zero.1 <| of_not_not ha).le
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ
hμ : ↑↑μ s ≠ 0
hμ₁ : ↑↑μ s ≠ ⊤
hf : IntegrableOn f s
⊢ 0 < ↑↑μ {x | x ∈ s ∧ ⨍ (a : α) in s, f a ∂μ ≤ f x}
[PROOFSTEP]
simpa [integral_neg, neg_div] using measure_le_setAverage_pos hμ hμ₁ hf.neg
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ
inst✝ : IsFiniteMeasure μ
hμ : μ ≠ 0
hf : Integrable f
⊢ 0 < ↑↑μ {x | f x ≤ ⨍ (a : α), f a ∂μ}
[PROOFSTEP]
simpa using measure_le_setAverage_pos (Measure.measure_univ_ne_zero.2 hμ) (measure_ne_top _ _) hf.integrableOn
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ
inst✝ : IsFiniteMeasure μ
hμ : μ ≠ 0
hf : Integrable f
⊢ 0 < ↑↑μ {x | ⨍ (a : α), f a ∂μ ≤ f x}
[PROOFSTEP]
simpa using measure_setAverage_le_pos (Measure.measure_univ_ne_zero.2 hμ) (measure_ne_top _ _) hf.integrableOn
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ
inst✝ : IsFiniteMeasure μ
hμ : μ ≠ 0
hf : Integrable f
hN : ↑↑μ N = 0
⊢ ∃ x, ¬x ∈ N ∧ f x ≤ ⨍ (a : α), f a ∂μ
[PROOFSTEP]
have := measure_le_average_pos hμ hf
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ
inst✝ : IsFiniteMeasure μ
hμ : μ ≠ 0
hf : Integrable f
hN : ↑↑μ N = 0
this : 0 < ↑↑μ {x | f x ≤ ⨍ (a : α), f a ∂μ}
⊢ ∃ x, ¬x ∈ N ∧ f x ≤ ⨍ (a : α), f a ∂μ
[PROOFSTEP]
rw [← measure_diff_null hN] at this
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ
inst✝ : IsFiniteMeasure μ
hμ : μ ≠ 0
hf : Integrable f
hN : ↑↑μ N = 0
this : 0 < ↑↑μ ({x | f x ≤ ⨍ (a : α), f a ∂μ} \ N)
⊢ ∃ x, ¬x ∈ N ∧ f x ≤ ⨍ (a : α), f a ∂μ
[PROOFSTEP]
obtain ⟨x, hx, hxN⟩ := nonempty_of_measure_ne_zero this.ne'
[GOAL]
case intro.intro
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ
inst✝ : IsFiniteMeasure μ
hμ : μ ≠ 0
hf : Integrable f
hN : ↑↑μ N = 0
this : 0 < ↑↑μ ({x | f x ≤ ⨍ (a : α), f a ∂μ} \ N)
x : α
hx : x ∈ {x | f x ≤ ⨍ (a : α), f a ∂μ}
hxN : ¬x ∈ N
⊢ ∃ x, ¬x ∈ N ∧ f x ≤ ⨍ (a : α), f a ∂μ
[PROOFSTEP]
exact ⟨x, hxN, hx⟩
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ
inst✝ : IsFiniteMeasure μ
hμ : μ ≠ 0
hf : Integrable f
hN : ↑↑μ N = 0
⊢ ∃ x, ¬x ∈ N ∧ ⨍ (a : α), f a ∂μ ≤ f x
[PROOFSTEP]
simpa [integral_neg, neg_div] using exists_not_mem_null_le_average hμ hf.neg hN
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ
inst✝ : IsProbabilityMeasure μ
hf : Integrable f
⊢ 0 < ↑↑μ {x | f x ≤ ∫ (a : α), f a ∂μ}
[PROOFSTEP]
simpa only [average_eq_integral] using measure_le_average_pos (IsProbabilityMeasure.ne_zero μ) hf
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ
inst✝ : IsProbabilityMeasure μ
hf : Integrable f
⊢ 0 < ↑↑μ {x | ∫ (a : α), f a ∂μ ≤ f x}
[PROOFSTEP]
simpa only [average_eq_integral] using measure_average_le_pos (IsProbabilityMeasure.ne_zero μ) hf
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ
inst✝ : IsProbabilityMeasure μ
hf : Integrable f
⊢ ∃ x, f x ≤ ∫ (a : α), f a ∂μ
[PROOFSTEP]
simpa only [average_eq_integral] using exists_le_average (IsProbabilityMeasure.ne_zero μ) hf
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ
inst✝ : IsProbabilityMeasure μ
hf : Integrable f
⊢ ∃ x, ∫ (a : α), f a ∂μ ≤ f x
[PROOFSTEP]
simpa only [average_eq_integral] using exists_average_le (IsProbabilityMeasure.ne_zero μ) hf
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ
inst✝ : IsProbabilityMeasure μ
hf : Integrable f
hN : ↑↑μ N = 0
⊢ ∃ x, ¬x ∈ N ∧ f x ≤ ∫ (a : α), f a ∂μ
[PROOFSTEP]
simpa only [average_eq_integral] using exists_not_mem_null_le_average (IsProbabilityMeasure.ne_zero μ) hf hN
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ
inst✝ : IsProbabilityMeasure μ
hf : Integrable f
hN : ↑↑μ N = 0
⊢ ∃ x, ¬x ∈ N ∧ ∫ (a : α), f a ∂μ ≤ f x
[PROOFSTEP]
simpa only [average_eq_integral] using exists_not_mem_null_average_le (IsProbabilityMeasure.ne_zero μ) hf hN
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ≥0∞
hμ : ↑↑μ s ≠ 0
hμ₁ : ↑↑μ s ≠ ⊤
hf : AEMeasurable f
⊢ 0 < ↑↑μ {x | x ∈ s ∧ f x ≤ ⨍⁻ (a : α) in s, f a ∂μ}
[PROOFSTEP]
obtain h | h := eq_or_ne (∫⁻ a in s, f a ∂μ) ∞
[GOAL]
case inl
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ≥0∞
hμ : ↑↑μ s ≠ 0
hμ₁ : ↑↑μ s ≠ ⊤
hf : AEMeasurable f
h : ∫⁻ (a : α) in s, f a ∂μ = ⊤
⊢ 0 < ↑↑μ {x | x ∈ s ∧ f x ≤ ⨍⁻ (a : α) in s, f a ∂μ}
[PROOFSTEP]
simpa [mul_top, hμ₁, laverage, h, top_div_of_ne_top hμ₁, pos_iff_ne_zero] using hμ
[GOAL]
case inr
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ≥0∞
hμ : ↑↑μ s ≠ 0
hμ₁ : ↑↑μ s ≠ ⊤
hf : AEMeasurable f
h : ∫⁻ (a : α) in s, f a ∂μ ≠ ⊤
⊢ 0 < ↑↑μ {x | x ∈ s ∧ f x ≤ ⨍⁻ (a : α) in s, f a ∂μ}
[PROOFSTEP]
have := measure_le_setAverage_pos hμ hμ₁ (integrable_toReal_of_lintegral_ne_top hf h)
[GOAL]
case inr
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ≥0∞
hμ : ↑↑μ s ≠ 0
hμ₁ : ↑↑μ s ≠ ⊤
hf : AEMeasurable f
h : ∫⁻ (a : α) in s, f a ∂μ ≠ ⊤
this : 0 < ↑↑μ {x | x ∈ s ∧ ENNReal.toReal (f x) ≤ ⨍ (a : α) in s, ENNReal.toReal (f a) ∂μ}
⊢ 0 < ↑↑μ {x | x ∈ s ∧ f x ≤ ⨍⁻ (a : α) in s, f a ∂μ}
[PROOFSTEP]
rw [← setOf_inter_eq_sep, ←
Measure.restrict_apply₀ (hf.aestronglyMeasurable.nullMeasurableSet_le aestronglyMeasurable_const)]
[GOAL]
case inr
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ≥0∞
hμ : ↑↑μ s ≠ 0
hμ₁ : ↑↑μ s ≠ ⊤
hf : AEMeasurable f
h : ∫⁻ (a : α) in s, f a ∂μ ≠ ⊤
this : 0 < ↑↑μ {x | x ∈ s ∧ ENNReal.toReal (f x) ≤ ⨍ (a : α) in s, ENNReal.toReal (f a) ∂μ}
⊢ 0 < ↑↑(Measure.restrict μ s) {a | f a ≤ ⨍⁻ (a : α) in s, f a ∂μ}
[PROOFSTEP]
rw [← setOf_inter_eq_sep, ←
Measure.restrict_apply₀ (hf.ennreal_toReal.aestronglyMeasurable.nullMeasurableSet_le aestronglyMeasurable_const), ←
measure_diff_null (measure_eq_top_of_lintegral_ne_top hf h)] at this
[GOAL]
case inr
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ≥0∞
hμ : ↑↑μ s ≠ 0
hμ₁ : ↑↑μ s ≠ ⊤
hf : AEMeasurable f
h : ∫⁻ (a : α) in s, f a ∂μ ≠ ⊤
this :
0 < ↑↑(Measure.restrict μ s) ({a | ENNReal.toReal (f a) ≤ ⨍ (a : α) in s, ENNReal.toReal (f a) ∂μ} \ {x | f x = ⊤})
⊢ 0 < ↑↑(Measure.restrict μ s) {a | f a ≤ ⨍⁻ (a : α) in s, f a ∂μ}
[PROOFSTEP]
refine' this.trans_le (measure_mono _)
[GOAL]
case inr
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ≥0∞
hμ : ↑↑μ s ≠ 0
hμ₁ : ↑↑μ s ≠ ⊤
hf : AEMeasurable f
h : ∫⁻ (a : α) in s, f a ∂μ ≠ ⊤
this :
0 < ↑↑(Measure.restrict μ s) ({a | ENNReal.toReal (f a) ≤ ⨍ (a : α) in s, ENNReal.toReal (f a) ∂μ} \ {x | f x = ⊤})
⊢ {a | ENNReal.toReal (f a) ≤ ⨍ (a : α) in s, ENNReal.toReal (f a) ∂μ} \ {x | f x = ⊤} ⊆
{a | f a ≤ ⨍⁻ (a : α) in s, f a ∂μ}
[PROOFSTEP]
rintro x ⟨hfx, hx⟩
[GOAL]
case inr.intro
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ≥0∞
hμ : ↑↑μ s ≠ 0
hμ₁ : ↑↑μ s ≠ ⊤
hf : AEMeasurable f
h : ∫⁻ (a : α) in s, f a ∂μ ≠ ⊤
this :
0 < ↑↑(Measure.restrict μ s) ({a | ENNReal.toReal (f a) ≤ ⨍ (a : α) in s, ENNReal.toReal (f a) ∂μ} \ {x | f x = ⊤})
x : α
hfx : x ∈ {a | ENNReal.toReal (f a) ≤ ⨍ (a : α) in s, ENNReal.toReal (f a) ∂μ}
hx : ¬x ∈ {x | f x = ⊤}
⊢ x ∈ {a | f a ≤ ⨍⁻ (a : α) in s, f a ∂μ}
[PROOFSTEP]
dsimp at hfx
[GOAL]
case inr.intro
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ≥0∞
hμ : ↑↑μ s ≠ 0
hμ₁ : ↑↑μ s ≠ ⊤
hf : AEMeasurable f
h : ∫⁻ (a : α) in s, f a ∂μ ≠ ⊤
this :
0 < ↑↑(Measure.restrict μ s) ({a | ENNReal.toReal (f a) ≤ ⨍ (a : α) in s, ENNReal.toReal (f a) ∂μ} \ {x | f x = ⊤})
x : α
hfx : ENNReal.toReal (f x) ≤ ⨍ (a : α) in s, ENNReal.toReal (f a) ∂μ
hx : ¬x ∈ {x | f x = ⊤}
⊢ x ∈ {a | f a ≤ ⨍⁻ (a : α) in s, f a ∂μ}
[PROOFSTEP]
rwa [← toReal_laverage hf, toReal_le_toReal hx (setLaverage_lt_top h).ne] at hfx
[GOAL]
case inr.intro
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ≥0∞
hμ : ↑↑μ s ≠ 0
hμ₁ : ↑↑μ s ≠ ⊤
hf : AEMeasurable f
h : ∫⁻ (a : α) in s, f a ∂μ ≠ ⊤
this :
0 < ↑↑(Measure.restrict μ s) ({a | ENNReal.toReal (f a) ≤ ⨍ (a : α) in s, ENNReal.toReal (f a) ∂μ} \ {x | f x = ⊤})
x : α
hfx : ENNReal.toReal (f x) ≤ ⨍ (a : α) in s, ENNReal.toReal (f a) ∂μ
hx : ¬x ∈ {x | f x = ⊤}
⊢ ∀ᵐ (x : α) ∂Measure.restrict μ s, f x ≠ ⊤
[PROOFSTEP]
simp_rw [ae_iff, not_ne_iff]
[GOAL]
case inr.intro
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ≥0∞
hμ : ↑↑μ s ≠ 0
hμ₁ : ↑↑μ s ≠ ⊤
hf : AEMeasurable f
h : ∫⁻ (a : α) in s, f a ∂μ ≠ ⊤
this :
0 < ↑↑(Measure.restrict μ s) ({a | ENNReal.toReal (f a) ≤ ⨍ (a : α) in s, ENNReal.toReal (f a) ∂μ} \ {x | f x = ⊤})
x : α
hfx : ENNReal.toReal (f x) ≤ ⨍ (a : α) in s, ENNReal.toReal (f a) ∂μ
hx : ¬x ∈ {x | f x = ⊤}
⊢ ↑↑(Measure.restrict μ s) {a | f a = ⊤} = 0
[PROOFSTEP]
exact measure_eq_top_of_lintegral_ne_top hf h
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ≥0∞
hμ : ↑↑μ s ≠ 0
hs : NullMeasurableSet s
hint : ∫⁻ (a : α) in s, f a ∂μ ≠ ⊤
⊢ 0 < ↑↑μ {x | x ∈ s ∧ ⨍⁻ (a : α) in s, f a ∂μ ≤ f x}
[PROOFSTEP]
obtain hμ₁ | hμ₁ := eq_or_ne (μ s) ∞
[GOAL]
case inl
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ≥0∞
hμ : ↑↑μ s ≠ 0
hs : NullMeasurableSet s
hint : ∫⁻ (a : α) in s, f a ∂μ ≠ ⊤
hμ₁ : ↑↑μ s = ⊤
⊢ 0 < ↑↑μ {x | x ∈ s ∧ ⨍⁻ (a : α) in s, f a ∂μ ≤ f x}
[PROOFSTEP]
simp [setLaverage_eq, hμ₁]
[GOAL]
case inr
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ≥0∞
hμ : ↑↑μ s ≠ 0
hs : NullMeasurableSet s
hint : ∫⁻ (a : α) in s, f a ∂μ ≠ ⊤
hμ₁ : ↑↑μ s ≠ ⊤
⊢ 0 < ↑↑μ {x | x ∈ s ∧ ⨍⁻ (a : α) in s, f a ∂μ ≤ f x}
[PROOFSTEP]
obtain ⟨g, hg, hgf, hfg⟩ := exists_measurable_le_lintegral_eq (μ.restrict s) f
[GOAL]
case inr.intro.intro.intro
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ≥0∞
hμ : ↑↑μ s ≠ 0
hs : NullMeasurableSet s
hint : ∫⁻ (a : α) in s, f a ∂μ ≠ ⊤
hμ₁ : ↑↑μ s ≠ ⊤
g : α → ℝ≥0∞
hg : Measurable g
hgf : g ≤ f
hfg : ∫⁻ (a : α) in s, f a ∂μ = ∫⁻ (a : α) in s, g a ∂μ
⊢ 0 < ↑↑μ {x | x ∈ s ∧ ⨍⁻ (a : α) in s, f a ∂μ ≤ f x}
[PROOFSTEP]
have hfg' : ⨍⁻ a in s, f a ∂μ = ⨍⁻ a in s, g a ∂μ := by simp_rw [laverage_eq, hfg]
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ≥0∞
hμ : ↑↑μ s ≠ 0
hs : NullMeasurableSet s
hint : ∫⁻ (a : α) in s, f a ∂μ ≠ ⊤
hμ₁ : ↑↑μ s ≠ ⊤
g : α → ℝ≥0∞
hg : Measurable g
hgf : g ≤ f
hfg : ∫⁻ (a : α) in s, f a ∂μ = ∫⁻ (a : α) in s, g a ∂μ
⊢ ⨍⁻ (a : α) in s, f a ∂μ = ⨍⁻ (a : α) in s, g a ∂μ
[PROOFSTEP]
simp_rw [laverage_eq, hfg]
[GOAL]
case inr.intro.intro.intro
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ≥0∞
hμ : ↑↑μ s ≠ 0
hs : NullMeasurableSet s
hint : ∫⁻ (a : α) in s, f a ∂μ ≠ ⊤
hμ₁ : ↑↑μ s ≠ ⊤
g : α → ℝ≥0∞
hg : Measurable g
hgf : g ≤ f
hfg : ∫⁻ (a : α) in s, f a ∂μ = ∫⁻ (a : α) in s, g a ∂μ
hfg' : ⨍⁻ (a : α) in s, f a ∂μ = ⨍⁻ (a : α) in s, g a ∂μ
⊢ 0 < ↑↑μ {x | x ∈ s ∧ ⨍⁻ (a : α) in s, f a ∂μ ≤ f x}
[PROOFSTEP]
rw [hfg] at hint
[GOAL]
case inr.intro.intro.intro
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ≥0∞
hμ : ↑↑μ s ≠ 0
hs : NullMeasurableSet s
hμ₁ : ↑↑μ s ≠ ⊤
g : α → ℝ≥0∞
hint : ∫⁻ (a : α) in s, g a ∂μ ≠ ⊤
hg : Measurable g
hgf : g ≤ f
hfg : ∫⁻ (a : α) in s, f a ∂μ = ∫⁻ (a : α) in s, g a ∂μ
hfg' : ⨍⁻ (a : α) in s, f a ∂μ = ⨍⁻ (a : α) in s, g a ∂μ
⊢ 0 < ↑↑μ {x | x ∈ s ∧ ⨍⁻ (a : α) in s, f a ∂μ ≤ f x}
[PROOFSTEP]
have := measure_setAverage_le_pos hμ hμ₁ (integrable_toReal_of_lintegral_ne_top hg.aemeasurable hint)
[GOAL]
case inr.intro.intro.intro
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ≥0∞
hμ : ↑↑μ s ≠ 0
hs : NullMeasurableSet s
hμ₁ : ↑↑μ s ≠ ⊤
g : α → ℝ≥0∞
hint : ∫⁻ (a : α) in s, g a ∂μ ≠ ⊤
hg : Measurable g
hgf : g ≤ f
hfg : ∫⁻ (a : α) in s, f a ∂μ = ∫⁻ (a : α) in s, g a ∂μ
hfg' : ⨍⁻ (a : α) in s, f a ∂μ = ⨍⁻ (a : α) in s, g a ∂μ
this : 0 < ↑↑μ {x | x ∈ s ∧ ⨍ (a : α) in s, ENNReal.toReal (g a) ∂μ ≤ ENNReal.toReal (g x)}
⊢ 0 < ↑↑μ {x | x ∈ s ∧ ⨍⁻ (a : α) in s, f a ∂μ ≤ f x}
[PROOFSTEP]
simp_rw [← setOf_inter_eq_sep, ← Measure.restrict_apply₀' hs, hfg']
[GOAL]
case inr.intro.intro.intro
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ≥0∞
hμ : ↑↑μ s ≠ 0
hs : NullMeasurableSet s
hμ₁ : ↑↑μ s ≠ ⊤
g : α → ℝ≥0∞
hint : ∫⁻ (a : α) in s, g a ∂μ ≠ ⊤
hg : Measurable g
hgf : g ≤ f
hfg : ∫⁻ (a : α) in s, f a ∂μ = ∫⁻ (a : α) in s, g a ∂μ
hfg' : ⨍⁻ (a : α) in s, f a ∂μ = ⨍⁻ (a : α) in s, g a ∂μ
this : 0 < ↑↑μ {x | x ∈ s ∧ ⨍ (a : α) in s, ENNReal.toReal (g a) ∂μ ≤ ENNReal.toReal (g x)}
⊢ 0 < ↑↑(Measure.restrict μ s) {a | ⨍⁻ (a : α) in s, g a ∂μ ≤ f a}
[PROOFSTEP]
rw [← setOf_inter_eq_sep, ← Measure.restrict_apply₀' hs, ←
measure_diff_null (measure_eq_top_of_lintegral_ne_top hg.aemeasurable hint)] at this
[GOAL]
case inr.intro.intro.intro
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ≥0∞
hμ : ↑↑μ s ≠ 0
hs : NullMeasurableSet s
hμ₁ : ↑↑μ s ≠ ⊤
g : α → ℝ≥0∞
hint : ∫⁻ (a : α) in s, g a ∂μ ≠ ⊤
hg : Measurable g
hgf : g ≤ f
hfg : ∫⁻ (a : α) in s, f a ∂μ = ∫⁻ (a : α) in s, g a ∂μ
hfg' : ⨍⁻ (a : α) in s, f a ∂μ = ⨍⁻ (a : α) in s, g a ∂μ
this :
0 < ↑↑(Measure.restrict μ s) ({a | ⨍ (a : α) in s, ENNReal.toReal (g a) ∂μ ≤ ENNReal.toReal (g a)} \ {x | g x = ⊤})
⊢ 0 < ↑↑(Measure.restrict μ s) {a | ⨍⁻ (a : α) in s, g a ∂μ ≤ f a}
[PROOFSTEP]
refine' this.trans_le (measure_mono _)
[GOAL]
case inr.intro.intro.intro
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ≥0∞
hμ : ↑↑μ s ≠ 0
hs : NullMeasurableSet s
hμ₁ : ↑↑μ s ≠ ⊤
g : α → ℝ≥0∞
hint : ∫⁻ (a : α) in s, g a ∂μ ≠ ⊤
hg : Measurable g
hgf : g ≤ f
hfg : ∫⁻ (a : α) in s, f a ∂μ = ∫⁻ (a : α) in s, g a ∂μ
hfg' : ⨍⁻ (a : α) in s, f a ∂μ = ⨍⁻ (a : α) in s, g a ∂μ
this :
0 < ↑↑(Measure.restrict μ s) ({a | ⨍ (a : α) in s, ENNReal.toReal (g a) ∂μ ≤ ENNReal.toReal (g a)} \ {x | g x = ⊤})
⊢ {a | ⨍ (a : α) in s, ENNReal.toReal (g a) ∂μ ≤ ENNReal.toReal (g a)} \ {x | g x = ⊤} ⊆
{a | ⨍⁻ (a : α) in s, g a ∂μ ≤ f a}
[PROOFSTEP]
rintro x ⟨hfx, hx⟩
[GOAL]
case inr.intro.intro.intro.intro
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ≥0∞
hμ : ↑↑μ s ≠ 0
hs : NullMeasurableSet s
hμ₁ : ↑↑μ s ≠ ⊤
g : α → ℝ≥0∞
hint : ∫⁻ (a : α) in s, g a ∂μ ≠ ⊤
hg : Measurable g
hgf : g ≤ f
hfg : ∫⁻ (a : α) in s, f a ∂μ = ∫⁻ (a : α) in s, g a ∂μ
hfg' : ⨍⁻ (a : α) in s, f a ∂μ = ⨍⁻ (a : α) in s, g a ∂μ
this :
0 < ↑↑(Measure.restrict μ s) ({a | ⨍ (a : α) in s, ENNReal.toReal (g a) ∂μ ≤ ENNReal.toReal (g a)} \ {x | g x = ⊤})
x : α
hfx : x ∈ {a | ⨍ (a : α) in s, ENNReal.toReal (g a) ∂μ ≤ ENNReal.toReal (g a)}
hx : ¬x ∈ {x | g x = ⊤}
⊢ x ∈ {a | ⨍⁻ (a : α) in s, g a ∂μ ≤ f a}
[PROOFSTEP]
dsimp at hfx
[GOAL]
case inr.intro.intro.intro.intro
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ≥0∞
hμ : ↑↑μ s ≠ 0
hs : NullMeasurableSet s
hμ₁ : ↑↑μ s ≠ ⊤
g : α → ℝ≥0∞
hint : ∫⁻ (a : α) in s, g a ∂μ ≠ ⊤
hg : Measurable g
hgf : g ≤ f
hfg : ∫⁻ (a : α) in s, f a ∂μ = ∫⁻ (a : α) in s, g a ∂μ
hfg' : ⨍⁻ (a : α) in s, f a ∂μ = ⨍⁻ (a : α) in s, g a ∂μ
this :
0 < ↑↑(Measure.restrict μ s) ({a | ⨍ (a : α) in s, ENNReal.toReal (g a) ∂μ ≤ ENNReal.toReal (g a)} \ {x | g x = ⊤})
x : α
hfx : ⨍ (a : α) in s, ENNReal.toReal (g a) ∂μ ≤ ENNReal.toReal (g x)
hx : ¬x ∈ {x | g x = ⊤}
⊢ x ∈ {a | ⨍⁻ (a : α) in s, g a ∂μ ≤ f a}
[PROOFSTEP]
rw [← toReal_laverage hg.aemeasurable, toReal_le_toReal (setLaverage_lt_top hint).ne hx] at hfx
[GOAL]
case inr.intro.intro.intro.intro
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ≥0∞
hμ : ↑↑μ s ≠ 0
hs : NullMeasurableSet s
hμ₁ : ↑↑μ s ≠ ⊤
g : α → ℝ≥0∞
hint : ∫⁻ (a : α) in s, g a ∂μ ≠ ⊤
hg : Measurable g
hgf : g ≤ f
hfg : ∫⁻ (a : α) in s, f a ∂μ = ∫⁻ (a : α) in s, g a ∂μ
hfg' : ⨍⁻ (a : α) in s, f a ∂μ = ⨍⁻ (a : α) in s, g a ∂μ
this :
0 < ↑↑(Measure.restrict μ s) ({a | ⨍ (a : α) in s, ENNReal.toReal (g a) ∂μ ≤ ENNReal.toReal (g a)} \ {x | g x = ⊤})
x : α
hfx : ⨍⁻ (x : α) in s, g x ∂μ ≤ g x
hx : ¬x ∈ {x | g x = ⊤}
⊢ x ∈ {a | ⨍⁻ (a : α) in s, g a ∂μ ≤ f a}
case inr.intro.intro.intro.intro
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ≥0∞
hμ : ↑↑μ s ≠ 0
hs : NullMeasurableSet s
hμ₁ : ↑↑μ s ≠ ⊤
g : α → ℝ≥0∞
hint : ∫⁻ (a : α) in s, g a ∂μ ≠ ⊤
hg : Measurable g
hgf : g ≤ f
hfg : ∫⁻ (a : α) in s, f a ∂μ = ∫⁻ (a : α) in s, g a ∂μ
hfg' : ⨍⁻ (a : α) in s, f a ∂μ = ⨍⁻ (a : α) in s, g a ∂μ
this :
0 < ↑↑(Measure.restrict μ s) ({a | ⨍ (a : α) in s, ENNReal.toReal (g a) ∂μ ≤ ENNReal.toReal (g a)} \ {x | g x = ⊤})
x : α
hfx : ⨍ (a : α) in s, ENNReal.toReal (g a) ∂μ ≤ ENNReal.toReal (g x)
hx : ¬x ∈ {x | g x = ⊤}
⊢ ∀ᵐ (x : α) ∂Measure.restrict μ s, g x ≠ ⊤
[PROOFSTEP]
exact hfx.trans (hgf _)
[GOAL]
case inr.intro.intro.intro.intro
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ≥0∞
hμ : ↑↑μ s ≠ 0
hs : NullMeasurableSet s
hμ₁ : ↑↑μ s ≠ ⊤
g : α → ℝ≥0∞
hint : ∫⁻ (a : α) in s, g a ∂μ ≠ ⊤
hg : Measurable g
hgf : g ≤ f
hfg : ∫⁻ (a : α) in s, f a ∂μ = ∫⁻ (a : α) in s, g a ∂μ
hfg' : ⨍⁻ (a : α) in s, f a ∂μ = ⨍⁻ (a : α) in s, g a ∂μ
this :
0 < ↑↑(Measure.restrict μ s) ({a | ⨍ (a : α) in s, ENNReal.toReal (g a) ∂μ ≤ ENNReal.toReal (g a)} \ {x | g x = ⊤})
x : α
hfx : ⨍ (a : α) in s, ENNReal.toReal (g a) ∂μ ≤ ENNReal.toReal (g x)
hx : ¬x ∈ {x | g x = ⊤}
⊢ ∀ᵐ (x : α) ∂Measure.restrict μ s, g x ≠ ⊤
[PROOFSTEP]
simp_rw [ae_iff, not_ne_iff]
[GOAL]
case inr.intro.intro.intro.intro
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ≥0∞
hμ : ↑↑μ s ≠ 0
hs : NullMeasurableSet s
hμ₁ : ↑↑μ s ≠ ⊤
g : α → ℝ≥0∞
hint : ∫⁻ (a : α) in s, g a ∂μ ≠ ⊤
hg : Measurable g
hgf : g ≤ f
hfg : ∫⁻ (a : α) in s, f a ∂μ = ∫⁻ (a : α) in s, g a ∂μ
hfg' : ⨍⁻ (a : α) in s, f a ∂μ = ⨍⁻ (a : α) in s, g a ∂μ
this :
0 < ↑↑(Measure.restrict μ s) ({a | ⨍ (a : α) in s, ENNReal.toReal (g a) ∂μ ≤ ENNReal.toReal (g a)} \ {x | g x = ⊤})
x : α
hfx : ⨍ (a : α) in s, ENNReal.toReal (g a) ∂μ ≤ ENNReal.toReal (g x)
hx : ¬x ∈ {x | g x = ⊤}
⊢ ↑↑(Measure.restrict μ s) {a | g a = ⊤} = 0
[PROOFSTEP]
exact measure_eq_top_of_lintegral_ne_top hg.aemeasurable hint
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ≥0∞
hμ : μ ≠ 0
hint : ∫⁻ (a : α), f a ∂μ ≠ ⊤
⊢ 0 < ↑↑μ {x | ⨍⁻ (a : α), f a ∂μ ≤ f x}
[PROOFSTEP]
simpa [hint] using @measure_setLaverage_le_pos _ _ _ _ f (measure_univ_ne_zero.2 hμ) nullMeasurableSet_univ
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ≥0∞
hμ : μ ≠ 0
hint : ∫⁻ (a : α), f a ∂μ ≠ ⊤
hN : ↑↑μ N = 0
⊢ ∃ x, ¬x ∈ N ∧ ⨍⁻ (a : α), f a ∂μ ≤ f x
[PROOFSTEP]
have := measure_laverage_le_pos hμ hint
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ≥0∞
hμ : μ ≠ 0
hint : ∫⁻ (a : α), f a ∂μ ≠ ⊤
hN : ↑↑μ N = 0
this : 0 < ↑↑μ {x | ⨍⁻ (a : α), f a ∂μ ≤ f x}
⊢ ∃ x, ¬x ∈ N ∧ ⨍⁻ (a : α), f a ∂μ ≤ f x
[PROOFSTEP]
rw [← measure_diff_null hN] at this
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ≥0∞
hμ : μ ≠ 0
hint : ∫⁻ (a : α), f a ∂μ ≠ ⊤
hN : ↑↑μ N = 0
this : 0 < ↑↑μ ({x | ⨍⁻ (a : α), f a ∂μ ≤ f x} \ N)
⊢ ∃ x, ¬x ∈ N ∧ ⨍⁻ (a : α), f a ∂μ ≤ f x
[PROOFSTEP]
obtain ⟨x, hx, hxN⟩ := nonempty_of_measure_ne_zero this.ne'
[GOAL]
case intro.intro
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ≥0∞
hμ : μ ≠ 0
hint : ∫⁻ (a : α), f a ∂μ ≠ ⊤
hN : ↑↑μ N = 0
this : 0 < ↑↑μ ({x | ⨍⁻ (a : α), f a ∂μ ≤ f x} \ N)
x : α
hx : x ∈ {x | ⨍⁻ (a : α), f a ∂μ ≤ f x}
hxN : ¬x ∈ N
⊢ ∃ x, ¬x ∈ N ∧ ⨍⁻ (a : α), f a ∂μ ≤ f x
[PROOFSTEP]
exact ⟨x, hxN, hx⟩
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ≥0∞
inst✝ : IsFiniteMeasure μ
hμ : μ ≠ 0
hf : AEMeasurable f
⊢ 0 < ↑↑μ {x | f x ≤ ⨍⁻ (a : α), f a ∂μ}
[PROOFSTEP]
simpa using measure_le_setLaverage_pos (measure_univ_ne_zero.2 hμ) (measure_ne_top _ _) hf.restrict
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ≥0∞
inst✝ : IsFiniteMeasure μ
hμ : μ ≠ 0
hf : AEMeasurable f
hN : ↑↑μ N = 0
⊢ ∃ x, ¬x ∈ N ∧ f x ≤ ⨍⁻ (a : α), f a ∂μ
[PROOFSTEP]
have := measure_le_laverage_pos hμ hf
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ≥0∞
inst✝ : IsFiniteMeasure μ
hμ : μ ≠ 0
hf : AEMeasurable f
hN : ↑↑μ N = 0
this : 0 < ↑↑μ {x | f x ≤ ⨍⁻ (a : α), f a ∂μ}
⊢ ∃ x, ¬x ∈ N ∧ f x ≤ ⨍⁻ (a : α), f a ∂μ
[PROOFSTEP]
rw [← measure_diff_null hN] at this
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ≥0∞
inst✝ : IsFiniteMeasure μ
hμ : μ ≠ 0
hf : AEMeasurable f
hN : ↑↑μ N = 0
this : 0 < ↑↑μ ({x | f x ≤ ⨍⁻ (a : α), f a ∂μ} \ N)
⊢ ∃ x, ¬x ∈ N ∧ f x ≤ ⨍⁻ (a : α), f a ∂μ
[PROOFSTEP]
obtain ⟨x, hx, hxN⟩ := nonempty_of_measure_ne_zero this.ne'
[GOAL]
case intro.intro
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ≥0∞
inst✝ : IsFiniteMeasure μ
hμ : μ ≠ 0
hf : AEMeasurable f
hN : ↑↑μ N = 0
this : 0 < ↑↑μ ({x | f x ≤ ⨍⁻ (a : α), f a ∂μ} \ N)
x : α
hx : x ∈ {x | f x ≤ ⨍⁻ (a : α), f a ∂μ}
hxN : ¬x ∈ N
⊢ ∃ x, ¬x ∈ N ∧ f x ≤ ⨍⁻ (a : α), f a ∂μ
[PROOFSTEP]
exact ⟨x, hxN, hx⟩
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ≥0∞
inst✝ : IsProbabilityMeasure μ
hf : AEMeasurable f
⊢ 0 < ↑↑μ {x | f x ≤ ∫⁻ (a : α), f a ∂μ}
[PROOFSTEP]
simpa only [laverage_eq_lintegral] using measure_le_laverage_pos (IsProbabilityMeasure.ne_zero μ) hf
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ≥0∞
inst✝ : IsProbabilityMeasure μ
hint : ∫⁻ (a : α), f a ∂μ ≠ ⊤
⊢ 0 < ↑↑μ {x | ∫⁻ (a : α), f a ∂μ ≤ f x}
[PROOFSTEP]
simpa only [laverage_eq_lintegral] using measure_laverage_le_pos (IsProbabilityMeasure.ne_zero μ) hint
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ≥0∞
inst✝ : IsProbabilityMeasure μ
hf : AEMeasurable f
⊢ ∃ x, f x ≤ ∫⁻ (a : α), f a ∂μ
[PROOFSTEP]
simpa only [laverage_eq_lintegral] using exists_le_laverage (IsProbabilityMeasure.ne_zero μ) hf
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ≥0∞
inst✝ : IsProbabilityMeasure μ
hint : ∫⁻ (a : α), f a ∂μ ≠ ⊤
⊢ ∃ x, ∫⁻ (a : α), f a ∂μ ≤ f x
[PROOFSTEP]
simpa only [laverage_eq_lintegral] using exists_laverage_le (IsProbabilityMeasure.ne_zero μ) hint
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ≥0∞
inst✝ : IsProbabilityMeasure μ
hf : AEMeasurable f
hN : ↑↑μ N = 0
⊢ ∃ x, ¬x ∈ N ∧ f x ≤ ∫⁻ (a : α), f a ∂μ
[PROOFSTEP]
simpa only [laverage_eq_lintegral] using exists_not_mem_null_le_laverage (IsProbabilityMeasure.ne_zero μ) hf hN
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁶ : NormedAddCommGroup E
inst✝⁵ : NormedSpace ℝ E
inst✝⁴ : CompleteSpace E
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace ℝ F
inst✝¹ : CompleteSpace F
μ ν : Measure α
s t N : Set α
f : α → ℝ≥0∞
inst✝ : IsProbabilityMeasure μ
hint : ∫⁻ (a : α), f a ∂μ ≠ ⊤
hN : ↑↑μ N = 0
⊢ ∃ x, ¬x ∈ N ∧ ∫⁻ (a : α), f a ∂μ ≤ f x
[PROOFSTEP]
simpa only [laverage_eq_lintegral] using exists_not_mem_null_laverage_le (IsProbabilityMeasure.ne_zero μ) hint hN
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
⊢ Tendsto (fun i => ∫ (y : α), g i y • f y ∂μ) l (𝓝 c)
[PROOFSTEP]
have g_int : ∀ᶠ i in l, Integrable (g i) μ :=
by
filter_upwards [(tendsto_order.1 hg).1 _ zero_lt_one] with i hi
contrapose hi
simp only [integral_undef hi, lt_self_iff_false, not_false_eq_true]
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
⊢ ∀ᶠ (i : ι) in l, Integrable (g i)
[PROOFSTEP]
filter_upwards [(tendsto_order.1 hg).1 _ zero_lt_one] with i hi
[GOAL]
case h
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
i : ι
hi : 0 < ∫ (y : α), g i y ∂μ
⊢ Integrable (g i)
[PROOFSTEP]
contrapose hi
[GOAL]
case h
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
i : ι
hi : ¬Integrable (g i)
⊢ ¬0 < ∫ (y : α), g i y ∂μ
[PROOFSTEP]
simp only [integral_undef hi, lt_self_iff_false, not_false_eq_true]
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
⊢ Tendsto (fun i => ∫ (y : α), g i y • f y ∂μ) l (𝓝 c)
[PROOFSTEP]
have I : ∀ᶠ i in l, ∫ y, g i y • (f y - c) ∂μ + (∫ y, g i y ∂μ) • c = ∫ y, g i y • f y ∂μ :=
by
filter_upwards [f_int, g_int, g_supp, g_bound] with i hif hig hisupp hibound
rw [← integral_smul_const, ← integral_add]
· simp only [smul_sub, sub_add_cancel]
· simp_rw [smul_sub]
apply Integrable.sub _ (hig.smul_const _)
have A : Function.support (fun y ↦ g i y • f y) ⊆ a i :=
by
apply Subset.trans _ hisupp
exact Function.support_smul_subset_left _ _
rw [← integrableOn_iff_integrable_of_support_subset A]
apply Integrable.smul_of_top_right hif
exact memℒp_top_of_bound hig.aestronglyMeasurable.restrict (K / (μ (a i)).toReal) (eventually_of_forall hibound)
· exact hig.smul_const _
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
⊢ ∀ᶠ (i : ι) in l, ∫ (y : α), g i y • (f y - c) ∂μ + (∫ (y : α), g i y ∂μ) • c = ∫ (y : α), g i y • f y ∂μ
[PROOFSTEP]
filter_upwards [f_int, g_int, g_supp, g_bound] with i hif hig hisupp hibound
[GOAL]
case h
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
i : ι
hif : IntegrableOn f (a i)
hig : Integrable (g i)
hisupp : support (g i) ⊆ a i
hibound : ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
⊢ ∫ (y : α), g i y • (f y - c) ∂μ + (∫ (y : α), g i y ∂μ) • c = ∫ (y : α), g i y • f y ∂μ
[PROOFSTEP]
rw [← integral_smul_const, ← integral_add]
[GOAL]
case h
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
i : ι
hif : IntegrableOn f (a i)
hig : Integrable (g i)
hisupp : support (g i) ⊆ a i
hibound : ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
⊢ ∫ (a : α), g i a • (f a - c) + g i a • c ∂μ = ∫ (y : α), g i y • f y ∂μ
[PROOFSTEP]
simp only [smul_sub, sub_add_cancel]
[GOAL]
case h.hf
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
i : ι
hif : IntegrableOn f (a i)
hig : Integrable (g i)
hisupp : support (g i) ⊆ a i
hibound : ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
⊢ Integrable fun y => g i y • (f y - c)
[PROOFSTEP]
simp_rw [smul_sub]
[GOAL]
case h.hf
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
i : ι
hif : IntegrableOn f (a i)
hig : Integrable (g i)
hisupp : support (g i) ⊆ a i
hibound : ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
⊢ Integrable fun y => g i y • f y - g i y • c
[PROOFSTEP]
apply Integrable.sub _ (hig.smul_const _)
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
i : ι
hif : IntegrableOn f (a i)
hig : Integrable (g i)
hisupp : support (g i) ⊆ a i
hibound : ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
⊢ Integrable fun y => g i y • f y
[PROOFSTEP]
have A : Function.support (fun y ↦ g i y • f y) ⊆ a i :=
by
apply Subset.trans _ hisupp
exact Function.support_smul_subset_left _ _
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
i : ι
hif : IntegrableOn f (a i)
hig : Integrable (g i)
hisupp : support (g i) ⊆ a i
hibound : ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
⊢ (support fun y => g i y • f y) ⊆ a i
[PROOFSTEP]
apply Subset.trans _ hisupp
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
i : ι
hif : IntegrableOn f (a i)
hig : Integrable (g i)
hisupp : support (g i) ⊆ a i
hibound : ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
⊢ (support fun y => g i y • f y) ⊆ support (g i)
[PROOFSTEP]
exact Function.support_smul_subset_left _ _
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
i : ι
hif : IntegrableOn f (a i)
hig : Integrable (g i)
hisupp : support (g i) ⊆ a i
hibound : ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
A : (support fun y => g i y • f y) ⊆ a i
⊢ Integrable fun y => g i y • f y
[PROOFSTEP]
rw [← integrableOn_iff_integrable_of_support_subset A]
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
i : ι
hif : IntegrableOn f (a i)
hig : Integrable (g i)
hisupp : support (g i) ⊆ a i
hibound : ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
A : (support fun y => g i y • f y) ⊆ a i
⊢ IntegrableOn (fun y => g i y • f y) (a i)
[PROOFSTEP]
apply Integrable.smul_of_top_right hif
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
i : ι
hif : IntegrableOn f (a i)
hig : Integrable (g i)
hisupp : support (g i) ⊆ a i
hibound : ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
A : (support fun y => g i y • f y) ⊆ a i
⊢ Memℒp (fun y => g i y) ⊤
[PROOFSTEP]
exact memℒp_top_of_bound hig.aestronglyMeasurable.restrict (K / (μ (a i)).toReal) (eventually_of_forall hibound)
[GOAL]
case h.hg
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
i : ι
hif : IntegrableOn f (a i)
hig : Integrable (g i)
hisupp : support (g i) ⊆ a i
hibound : ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
⊢ Integrable fun x => g i x • c
[PROOFSTEP]
exact hig.smul_const _
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
I : ∀ᶠ (i : ι) in l, ∫ (y : α), g i y • (f y - c) ∂μ + (∫ (y : α), g i y ∂μ) • c = ∫ (y : α), g i y • f y ∂μ
⊢ Tendsto (fun i => ∫ (y : α), g i y • f y ∂μ) l (𝓝 c)
[PROOFSTEP]
have L0 : Tendsto (fun i ↦ ∫ y, g i y • (f y - c) ∂μ) l (𝓝 0) :=
by
have := hf.const_mul K
simp only [mul_zero] at this
refine' squeeze_zero_norm' _ this
filter_upwards [g_supp, g_bound, f_int, (tendsto_order.1 hg).1 _ zero_lt_one] with i hi h'i h''i hi_int
have mu_ai : μ (a i) < ∞ := by
rw [lt_top_iff_ne_top]
intro h
simp only [h, ENNReal.top_toReal, _root_.div_zero, abs_nonpos_iff] at h'i
have : ∫ (y : α), g i y ∂μ = ∫ (y : α), 0 ∂μ := by congr; ext y; exact h'i y
simp [this] at hi_int
apply (norm_integral_le_integral_norm _).trans
simp_rw [average_eq, smul_eq_mul, ← integral_mul_left, norm_smul, ← mul_assoc, ← div_eq_mul_inv]
have : ∀ x, x ∉ a i → ‖g i x‖ * ‖(f x - c)‖ = 0 := by
intro x hx
have : g i x = 0 := by rw [← Function.nmem_support]; exact fun h ↦ hx (hi h)
simp [this]
rw [← set_integral_eq_integral_of_forall_compl_eq_zero this (μ := μ)]
refine' integral_mono_of_nonneg (eventually_of_forall (fun x ↦ by positivity)) _ (eventually_of_forall (fun x ↦ _))
· apply (Integrable.sub h''i _).norm.const_mul
change IntegrableOn (fun _ ↦ c) (a i) μ
simp [integrableOn_const, mu_ai]
· dsimp; gcongr; simpa using h'i x
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
I : ∀ᶠ (i : ι) in l, ∫ (y : α), g i y • (f y - c) ∂μ + (∫ (y : α), g i y ∂μ) • c = ∫ (y : α), g i y • f y ∂μ
⊢ Tendsto (fun i => ∫ (y : α), g i y • (f y - c) ∂μ) l (𝓝 0)
[PROOFSTEP]
have := hf.const_mul K
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
I : ∀ᶠ (i : ι) in l, ∫ (y : α), g i y • (f y - c) ∂μ + (∫ (y : α), g i y ∂μ) • c = ∫ (y : α), g i y • f y ∂μ
this : Tendsto (fun k => K * ⨍ (y : α) in a k, ‖f y - c‖ ∂μ) l (𝓝 (K * 0))
⊢ Tendsto (fun i => ∫ (y : α), g i y • (f y - c) ∂μ) l (𝓝 0)
[PROOFSTEP]
simp only [mul_zero] at this
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
I : ∀ᶠ (i : ι) in l, ∫ (y : α), g i y • (f y - c) ∂μ + (∫ (y : α), g i y ∂μ) • c = ∫ (y : α), g i y • f y ∂μ
this : Tendsto (fun k => K * ⨍ (y : α) in a k, ‖f y - c‖ ∂μ) l (𝓝 0)
⊢ Tendsto (fun i => ∫ (y : α), g i y • (f y - c) ∂μ) l (𝓝 0)
[PROOFSTEP]
refine' squeeze_zero_norm' _ this
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
I : ∀ᶠ (i : ι) in l, ∫ (y : α), g i y • (f y - c) ∂μ + (∫ (y : α), g i y ∂μ) • c = ∫ (y : α), g i y • f y ∂μ
this : Tendsto (fun k => K * ⨍ (y : α) in a k, ‖f y - c‖ ∂μ) l (𝓝 0)
⊢ ∀ᶠ (n : ι) in l, ‖∫ (y : α), g n y • (f y - c) ∂μ‖ ≤ K * ⨍ (y : α) in a n, ‖f y - c‖ ∂μ
[PROOFSTEP]
filter_upwards [g_supp, g_bound, f_int, (tendsto_order.1 hg).1 _ zero_lt_one] with i hi h'i h''i hi_int
[GOAL]
case h
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
I : ∀ᶠ (i : ι) in l, ∫ (y : α), g i y • (f y - c) ∂μ + (∫ (y : α), g i y ∂μ) • c = ∫ (y : α), g i y • f y ∂μ
this : Tendsto (fun k => K * ⨍ (y : α) in a k, ‖f y - c‖ ∂μ) l (𝓝 0)
i : ι
hi : support (g i) ⊆ a i
h'i : ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
h''i : IntegrableOn f (a i)
hi_int : 0 < ∫ (y : α), g i y ∂μ
⊢ ‖∫ (y : α), g i y • (f y - c) ∂μ‖ ≤ K * ⨍ (y : α) in a i, ‖f y - c‖ ∂μ
[PROOFSTEP]
have mu_ai : μ (a i) < ∞ := by
rw [lt_top_iff_ne_top]
intro h
simp only [h, ENNReal.top_toReal, _root_.div_zero, abs_nonpos_iff] at h'i
have : ∫ (y : α), g i y ∂μ = ∫ (y : α), 0 ∂μ := by congr; ext y; exact h'i y
simp [this] at hi_int
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
I : ∀ᶠ (i : ι) in l, ∫ (y : α), g i y • (f y - c) ∂μ + (∫ (y : α), g i y ∂μ) • c = ∫ (y : α), g i y • f y ∂μ
this : Tendsto (fun k => K * ⨍ (y : α) in a k, ‖f y - c‖ ∂μ) l (𝓝 0)
i : ι
hi : support (g i) ⊆ a i
h'i : ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
h''i : IntegrableOn f (a i)
hi_int : 0 < ∫ (y : α), g i y ∂μ
⊢ ↑↑μ (a i) < ⊤
[PROOFSTEP]
rw [lt_top_iff_ne_top]
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
I : ∀ᶠ (i : ι) in l, ∫ (y : α), g i y • (f y - c) ∂μ + (∫ (y : α), g i y ∂μ) • c = ∫ (y : α), g i y • f y ∂μ
this : Tendsto (fun k => K * ⨍ (y : α) in a k, ‖f y - c‖ ∂μ) l (𝓝 0)
i : ι
hi : support (g i) ⊆ a i
h'i : ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
h''i : IntegrableOn f (a i)
hi_int : 0 < ∫ (y : α), g i y ∂μ
⊢ ↑↑μ (a i) ≠ ⊤
[PROOFSTEP]
intro h
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
I : ∀ᶠ (i : ι) in l, ∫ (y : α), g i y • (f y - c) ∂μ + (∫ (y : α), g i y ∂μ) • c = ∫ (y : α), g i y • f y ∂μ
this : Tendsto (fun k => K * ⨍ (y : α) in a k, ‖f y - c‖ ∂μ) l (𝓝 0)
i : ι
hi : support (g i) ⊆ a i
h'i : ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
h''i : IntegrableOn f (a i)
hi_int : 0 < ∫ (y : α), g i y ∂μ
h : ↑↑μ (a i) = ⊤
⊢ False
[PROOFSTEP]
simp only [h, ENNReal.top_toReal, _root_.div_zero, abs_nonpos_iff] at h'i
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
I : ∀ᶠ (i : ι) in l, ∫ (y : α), g i y • (f y - c) ∂μ + (∫ (y : α), g i y ∂μ) • c = ∫ (y : α), g i y • f y ∂μ
this : Tendsto (fun k => K * ⨍ (y : α) in a k, ‖f y - c‖ ∂μ) l (𝓝 0)
i : ι
hi : support (g i) ⊆ a i
h''i : IntegrableOn f (a i)
hi_int : 0 < ∫ (y : α), g i y ∂μ
h : ↑↑μ (a i) = ⊤
h'i : ∀ (x : α), g i x = 0
⊢ False
[PROOFSTEP]
have : ∫ (y : α), g i y ∂μ = ∫ (y : α), 0 ∂μ := by congr; ext y; exact h'i y
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
I : ∀ᶠ (i : ι) in l, ∫ (y : α), g i y • (f y - c) ∂μ + (∫ (y : α), g i y ∂μ) • c = ∫ (y : α), g i y • f y ∂μ
this : Tendsto (fun k => K * ⨍ (y : α) in a k, ‖f y - c‖ ∂μ) l (𝓝 0)
i : ι
hi : support (g i) ⊆ a i
h''i : IntegrableOn f (a i)
hi_int : 0 < ∫ (y : α), g i y ∂μ
h : ↑↑μ (a i) = ⊤
h'i : ∀ (x : α), g i x = 0
⊢ ∫ (y : α), g i y ∂μ = ∫ (y : α), 0 ∂μ
[PROOFSTEP]
congr
[GOAL]
case e_f
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
I : ∀ᶠ (i : ι) in l, ∫ (y : α), g i y • (f y - c) ∂μ + (∫ (y : α), g i y ∂μ) • c = ∫ (y : α), g i y • f y ∂μ
this : Tendsto (fun k => K * ⨍ (y : α) in a k, ‖f y - c‖ ∂μ) l (𝓝 0)
i : ι
hi : support (g i) ⊆ a i
h''i : IntegrableOn f (a i)
hi_int : 0 < ∫ (y : α), g i y ∂μ
h : ↑↑μ (a i) = ⊤
h'i : ∀ (x : α), g i x = 0
⊢ (fun y => g i y) = fun y => 0
[PROOFSTEP]
ext y
[GOAL]
case e_f.h
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
I : ∀ᶠ (i : ι) in l, ∫ (y : α), g i y • (f y - c) ∂μ + (∫ (y : α), g i y ∂μ) • c = ∫ (y : α), g i y • f y ∂μ
this : Tendsto (fun k => K * ⨍ (y : α) in a k, ‖f y - c‖ ∂μ) l (𝓝 0)
i : ι
hi : support (g i) ⊆ a i
h''i : IntegrableOn f (a i)
hi_int : 0 < ∫ (y : α), g i y ∂μ
h : ↑↑μ (a i) = ⊤
h'i : ∀ (x : α), g i x = 0
y : α
⊢ g i y = 0
[PROOFSTEP]
exact h'i y
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
I : ∀ᶠ (i : ι) in l, ∫ (y : α), g i y • (f y - c) ∂μ + (∫ (y : α), g i y ∂μ) • c = ∫ (y : α), g i y • f y ∂μ
this✝ : Tendsto (fun k => K * ⨍ (y : α) in a k, ‖f y - c‖ ∂μ) l (𝓝 0)
i : ι
hi : support (g i) ⊆ a i
h''i : IntegrableOn f (a i)
hi_int : 0 < ∫ (y : α), g i y ∂μ
h : ↑↑μ (a i) = ⊤
h'i : ∀ (x : α), g i x = 0
this : ∫ (y : α), g i y ∂μ = ∫ (y : α), 0 ∂μ
⊢ False
[PROOFSTEP]
simp [this] at hi_int
[GOAL]
case h
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
I : ∀ᶠ (i : ι) in l, ∫ (y : α), g i y • (f y - c) ∂μ + (∫ (y : α), g i y ∂μ) • c = ∫ (y : α), g i y • f y ∂μ
this : Tendsto (fun k => K * ⨍ (y : α) in a k, ‖f y - c‖ ∂μ) l (𝓝 0)
i : ι
hi : support (g i) ⊆ a i
h'i : ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
h''i : IntegrableOn f (a i)
hi_int : 0 < ∫ (y : α), g i y ∂μ
mu_ai : ↑↑μ (a i) < ⊤
⊢ ‖∫ (y : α), g i y • (f y - c) ∂μ‖ ≤ K * ⨍ (y : α) in a i, ‖f y - c‖ ∂μ
[PROOFSTEP]
apply (norm_integral_le_integral_norm _).trans
[GOAL]
case h
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
I : ∀ᶠ (i : ι) in l, ∫ (y : α), g i y • (f y - c) ∂μ + (∫ (y : α), g i y ∂μ) • c = ∫ (y : α), g i y • f y ∂μ
this : Tendsto (fun k => K * ⨍ (y : α) in a k, ‖f y - c‖ ∂μ) l (𝓝 0)
i : ι
hi : support (g i) ⊆ a i
h'i : ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
h''i : IntegrableOn f (a i)
hi_int : 0 < ∫ (y : α), g i y ∂μ
mu_ai : ↑↑μ (a i) < ⊤
⊢ ∫ (a : α), ‖g i a • (f a - c)‖ ∂μ ≤ K * ⨍ (y : α) in a i, ‖f y - c‖ ∂μ
[PROOFSTEP]
simp_rw [average_eq, smul_eq_mul, ← integral_mul_left, norm_smul, ← mul_assoc, ← div_eq_mul_inv]
[GOAL]
case h
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
I : ∀ᶠ (i : ι) in l, ∫ (y : α), g i y • (f y - c) ∂μ + (∫ (y : α), g i y ∂μ) • c = ∫ (y : α), g i y • f y ∂μ
this : Tendsto (fun k => K * ⨍ (y : α) in a k, ‖f y - c‖ ∂μ) l (𝓝 0)
i : ι
hi : support (g i) ⊆ a i
h'i : ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
h''i : IntegrableOn f (a i)
hi_int : 0 < ∫ (y : α), g i y ∂μ
mu_ai : ↑↑μ (a i) < ⊤
⊢ ∫ (a : α), ‖g i a‖ * ‖f a - c‖ ∂μ ≤
∫ (a_1 : α) in a i, K / ENNReal.toReal (↑↑(Measure.restrict μ (a i)) univ) * ‖f a_1 - c‖ ∂μ
[PROOFSTEP]
have : ∀ x, x ∉ a i → ‖g i x‖ * ‖(f x - c)‖ = 0 := by
intro x hx
have : g i x = 0 := by rw [← Function.nmem_support]; exact fun h ↦ hx (hi h)
simp [this]
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
I : ∀ᶠ (i : ι) in l, ∫ (y : α), g i y • (f y - c) ∂μ + (∫ (y : α), g i y ∂μ) • c = ∫ (y : α), g i y • f y ∂μ
this : Tendsto (fun k => K * ⨍ (y : α) in a k, ‖f y - c‖ ∂μ) l (𝓝 0)
i : ι
hi : support (g i) ⊆ a i
h'i : ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
h''i : IntegrableOn f (a i)
hi_int : 0 < ∫ (y : α), g i y ∂μ
mu_ai : ↑↑μ (a i) < ⊤
⊢ ∀ (x : α), ¬x ∈ a i → ‖g i x‖ * ‖f x - c‖ = 0
[PROOFSTEP]
intro x hx
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
I : ∀ᶠ (i : ι) in l, ∫ (y : α), g i y • (f y - c) ∂μ + (∫ (y : α), g i y ∂μ) • c = ∫ (y : α), g i y • f y ∂μ
this : Tendsto (fun k => K * ⨍ (y : α) in a k, ‖f y - c‖ ∂μ) l (𝓝 0)
i : ι
hi : support (g i) ⊆ a i
h'i : ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
h''i : IntegrableOn f (a i)
hi_int : 0 < ∫ (y : α), g i y ∂μ
mu_ai : ↑↑μ (a i) < ⊤
x : α
hx : ¬x ∈ a i
⊢ ‖g i x‖ * ‖f x - c‖ = 0
[PROOFSTEP]
have : g i x = 0 := by rw [← Function.nmem_support]; exact fun h ↦ hx (hi h)
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
I : ∀ᶠ (i : ι) in l, ∫ (y : α), g i y • (f y - c) ∂μ + (∫ (y : α), g i y ∂μ) • c = ∫ (y : α), g i y • f y ∂μ
this : Tendsto (fun k => K * ⨍ (y : α) in a k, ‖f y - c‖ ∂μ) l (𝓝 0)
i : ι
hi : support (g i) ⊆ a i
h'i : ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
h''i : IntegrableOn f (a i)
hi_int : 0 < ∫ (y : α), g i y ∂μ
mu_ai : ↑↑μ (a i) < ⊤
x : α
hx : ¬x ∈ a i
⊢ g i x = 0
[PROOFSTEP]
rw [← Function.nmem_support]
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
I : ∀ᶠ (i : ι) in l, ∫ (y : α), g i y • (f y - c) ∂μ + (∫ (y : α), g i y ∂μ) • c = ∫ (y : α), g i y • f y ∂μ
this : Tendsto (fun k => K * ⨍ (y : α) in a k, ‖f y - c‖ ∂μ) l (𝓝 0)
i : ι
hi : support (g i) ⊆ a i
h'i : ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
h''i : IntegrableOn f (a i)
hi_int : 0 < ∫ (y : α), g i y ∂μ
mu_ai : ↑↑μ (a i) < ⊤
x : α
hx : ¬x ∈ a i
⊢ ¬x ∈ support (g i)
[PROOFSTEP]
exact fun h ↦ hx (hi h)
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
I : ∀ᶠ (i : ι) in l, ∫ (y : α), g i y • (f y - c) ∂μ + (∫ (y : α), g i y ∂μ) • c = ∫ (y : α), g i y • f y ∂μ
this✝ : Tendsto (fun k => K * ⨍ (y : α) in a k, ‖f y - c‖ ∂μ) l (𝓝 0)
i : ι
hi : support (g i) ⊆ a i
h'i : ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
h''i : IntegrableOn f (a i)
hi_int : 0 < ∫ (y : α), g i y ∂μ
mu_ai : ↑↑μ (a i) < ⊤
x : α
hx : ¬x ∈ a i
this : g i x = 0
⊢ ‖g i x‖ * ‖f x - c‖ = 0
[PROOFSTEP]
simp [this]
[GOAL]
case h
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
I : ∀ᶠ (i : ι) in l, ∫ (y : α), g i y • (f y - c) ∂μ + (∫ (y : α), g i y ∂μ) • c = ∫ (y : α), g i y • f y ∂μ
this✝ : Tendsto (fun k => K * ⨍ (y : α) in a k, ‖f y - c‖ ∂μ) l (𝓝 0)
i : ι
hi : support (g i) ⊆ a i
h'i : ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
h''i : IntegrableOn f (a i)
hi_int : 0 < ∫ (y : α), g i y ∂μ
mu_ai : ↑↑μ (a i) < ⊤
this : ∀ (x : α), ¬x ∈ a i → ‖g i x‖ * ‖f x - c‖ = 0
⊢ ∫ (a : α), ‖g i a‖ * ‖f a - c‖ ∂μ ≤
∫ (a_1 : α) in a i, K / ENNReal.toReal (↑↑(Measure.restrict μ (a i)) univ) * ‖f a_1 - c‖ ∂μ
[PROOFSTEP]
rw [← set_integral_eq_integral_of_forall_compl_eq_zero this (μ := μ)]
[GOAL]
case h
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
I : ∀ᶠ (i : ι) in l, ∫ (y : α), g i y • (f y - c) ∂μ + (∫ (y : α), g i y ∂μ) • c = ∫ (y : α), g i y • f y ∂μ
this✝ : Tendsto (fun k => K * ⨍ (y : α) in a k, ‖f y - c‖ ∂μ) l (𝓝 0)
i : ι
hi : support (g i) ⊆ a i
h'i : ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
h''i : IntegrableOn f (a i)
hi_int : 0 < ∫ (y : α), g i y ∂μ
mu_ai : ↑↑μ (a i) < ⊤
this : ∀ (x : α), ¬x ∈ a i → ‖g i x‖ * ‖f x - c‖ = 0
⊢ ∫ (x : α) in a i, ‖g i x‖ * ‖f x - c‖ ∂μ ≤
∫ (a_1 : α) in a i, K / ENNReal.toReal (↑↑(Measure.restrict μ (a i)) univ) * ‖f a_1 - c‖ ∂μ
[PROOFSTEP]
refine' integral_mono_of_nonneg (eventually_of_forall (fun x ↦ by positivity)) _ (eventually_of_forall (fun x ↦ _))
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
I : ∀ᶠ (i : ι) in l, ∫ (y : α), g i y • (f y - c) ∂μ + (∫ (y : α), g i y ∂μ) • c = ∫ (y : α), g i y • f y ∂μ
this✝ : Tendsto (fun k => K * ⨍ (y : α) in a k, ‖f y - c‖ ∂μ) l (𝓝 0)
i : ι
hi : support (g i) ⊆ a i
h'i : ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
h''i : IntegrableOn f (a i)
hi_int : 0 < ∫ (y : α), g i y ∂μ
mu_ai : ↑↑μ (a i) < ⊤
this : ∀ (x : α), ¬x ∈ a i → ‖g i x‖ * ‖f x - c‖ = 0
x : α
⊢ OfNat.ofNat 0 x ≤ (fun x => ‖g i x‖ * ‖f x - c‖) x
[PROOFSTEP]
positivity
[GOAL]
case h.refine'_1
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
I : ∀ᶠ (i : ι) in l, ∫ (y : α), g i y • (f y - c) ∂μ + (∫ (y : α), g i y ∂μ) • c = ∫ (y : α), g i y • f y ∂μ
this✝ : Tendsto (fun k => K * ⨍ (y : α) in a k, ‖f y - c‖ ∂μ) l (𝓝 0)
i : ι
hi : support (g i) ⊆ a i
h'i : ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
h''i : IntegrableOn f (a i)
hi_int : 0 < ∫ (y : α), g i y ∂μ
mu_ai : ↑↑μ (a i) < ⊤
this : ∀ (x : α), ¬x ∈ a i → ‖g i x‖ * ‖f x - c‖ = 0
⊢ Integrable fun a_1 => K / ENNReal.toReal (↑↑(Measure.restrict μ (a i)) univ) * ‖f a_1 - c‖
[PROOFSTEP]
apply (Integrable.sub h''i _).norm.const_mul
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
I : ∀ᶠ (i : ι) in l, ∫ (y : α), g i y • (f y - c) ∂μ + (∫ (y : α), g i y ∂μ) • c = ∫ (y : α), g i y • f y ∂μ
this✝ : Tendsto (fun k => K * ⨍ (y : α) in a k, ‖f y - c‖ ∂μ) l (𝓝 0)
i : ι
hi : support (g i) ⊆ a i
h'i : ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
h''i : IntegrableOn f (a i)
hi_int : 0 < ∫ (y : α), g i y ∂μ
mu_ai : ↑↑μ (a i) < ⊤
this : ∀ (x : α), ¬x ∈ a i → ‖g i x‖ * ‖f x - c‖ = 0
⊢ Integrable fun x => c
[PROOFSTEP]
change IntegrableOn (fun _ ↦ c) (a i) μ
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
I : ∀ᶠ (i : ι) in l, ∫ (y : α), g i y • (f y - c) ∂μ + (∫ (y : α), g i y ∂μ) • c = ∫ (y : α), g i y • f y ∂μ
this✝ : Tendsto (fun k => K * ⨍ (y : α) in a k, ‖f y - c‖ ∂μ) l (𝓝 0)
i : ι
hi : support (g i) ⊆ a i
h'i : ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
h''i : IntegrableOn f (a i)
hi_int : 0 < ∫ (y : α), g i y ∂μ
mu_ai : ↑↑μ (a i) < ⊤
this : ∀ (x : α), ¬x ∈ a i → ‖g i x‖ * ‖f x - c‖ = 0
⊢ IntegrableOn (fun x => c) (a i)
[PROOFSTEP]
simp [integrableOn_const, mu_ai]
[GOAL]
case h.refine'_2
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
I : ∀ᶠ (i : ι) in l, ∫ (y : α), g i y • (f y - c) ∂μ + (∫ (y : α), g i y ∂μ) • c = ∫ (y : α), g i y • f y ∂μ
this✝ : Tendsto (fun k => K * ⨍ (y : α) in a k, ‖f y - c‖ ∂μ) l (𝓝 0)
i : ι
hi : support (g i) ⊆ a i
h'i : ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
h''i : IntegrableOn f (a i)
hi_int : 0 < ∫ (y : α), g i y ∂μ
mu_ai : ↑↑μ (a i) < ⊤
this : ∀ (x : α), ¬x ∈ a i → ‖g i x‖ * ‖f x - c‖ = 0
x : α
⊢ (fun x => ‖g i x‖ * ‖f x - c‖) x ≤ (fun a_1 => K / ENNReal.toReal (↑↑(Measure.restrict μ (a i)) univ) * ‖f a_1 - c‖) x
[PROOFSTEP]
dsimp
[GOAL]
case h.refine'_2
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
I : ∀ᶠ (i : ι) in l, ∫ (y : α), g i y • (f y - c) ∂μ + (∫ (y : α), g i y ∂μ) • c = ∫ (y : α), g i y • f y ∂μ
this✝ : Tendsto (fun k => K * ⨍ (y : α) in a k, ‖f y - c‖ ∂μ) l (𝓝 0)
i : ι
hi : support (g i) ⊆ a i
h'i : ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
h''i : IntegrableOn f (a i)
hi_int : 0 < ∫ (y : α), g i y ∂μ
mu_ai : ↑↑μ (a i) < ⊤
this : ∀ (x : α), ¬x ∈ a i → ‖g i x‖ * ‖f x - c‖ = 0
x : α
⊢ |g i x| * ‖f x - c‖ ≤ K / ENNReal.toReal (↑↑(Measure.restrict μ (a i)) univ) * ‖f x - c‖
[PROOFSTEP]
gcongr
[GOAL]
case h.refine'_2.h
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
I : ∀ᶠ (i : ι) in l, ∫ (y : α), g i y • (f y - c) ∂μ + (∫ (y : α), g i y ∂μ) • c = ∫ (y : α), g i y • f y ∂μ
this✝ : Tendsto (fun k => K * ⨍ (y : α) in a k, ‖f y - c‖ ∂μ) l (𝓝 0)
i : ι
hi : support (g i) ⊆ a i
h'i : ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
h''i : IntegrableOn f (a i)
hi_int : 0 < ∫ (y : α), g i y ∂μ
mu_ai : ↑↑μ (a i) < ⊤
this : ∀ (x : α), ¬x ∈ a i → ‖g i x‖ * ‖f x - c‖ = 0
x : α
⊢ |g i x| ≤ K / ENNReal.toReal (↑↑(Measure.restrict μ (a i)) univ)
[PROOFSTEP]
simpa using h'i x
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
I : ∀ᶠ (i : ι) in l, ∫ (y : α), g i y • (f y - c) ∂μ + (∫ (y : α), g i y ∂μ) • c = ∫ (y : α), g i y • f y ∂μ
L0 : Tendsto (fun i => ∫ (y : α), g i y • (f y - c) ∂μ) l (𝓝 0)
⊢ Tendsto (fun i => ∫ (y : α), g i y • f y ∂μ) l (𝓝 c)
[PROOFSTEP]
have := L0.add (hg.smul_const c)
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
I : ∀ᶠ (i : ι) in l, ∫ (y : α), g i y • (f y - c) ∂μ + (∫ (y : α), g i y ∂μ) • c = ∫ (y : α), g i y • f y ∂μ
L0 : Tendsto (fun i => ∫ (y : α), g i y • (f y - c) ∂μ) l (𝓝 0)
this : Tendsto (fun x => ∫ (y : α), g x y • (f y - c) ∂μ + (∫ (y : α), g x y ∂μ) • c) l (𝓝 (0 + 1 • c))
⊢ Tendsto (fun i => ∫ (y : α), g i y • f y ∂μ) l (𝓝 c)
[PROOFSTEP]
simp only [one_smul, zero_add] at this
[GOAL]
α : Type u_1
E : Type u_2
F : Type u_3
m0 : MeasurableSpace α
inst✝⁵ : NormedAddCommGroup E
inst✝⁴ : NormedSpace ℝ E
inst✝³ : CompleteSpace E
inst✝² : NormedAddCommGroup F
inst✝¹ : NormedSpace ℝ F
inst✝ : CompleteSpace F
μ ν : Measure α
s t : Set α
ι : Type u_4
a : ι → Set α
l : Filter ι
f : α → E
c : E
g : ι → α → ℝ
K : ℝ
hf : Tendsto (fun i => ⨍ (y : α) in a i, ‖f y - c‖ ∂μ) l (𝓝 0)
f_int : ∀ᶠ (i : ι) in l, IntegrableOn f (a i)
hg : Tendsto (fun i => ∫ (y : α), g i y ∂μ) l (𝓝 1)
g_supp : ∀ᶠ (i : ι) in l, support (g i) ⊆ a i
g_bound : ∀ᶠ (i : ι) in l, ∀ (x : α), |g i x| ≤ K / ENNReal.toReal (↑↑μ (a i))
g_int : ∀ᶠ (i : ι) in l, Integrable (g i)
I : ∀ᶠ (i : ι) in l, ∫ (y : α), g i y • (f y - c) ∂μ + (∫ (y : α), g i y ∂μ) • c = ∫ (y : α), g i y • f y ∂μ
L0 : Tendsto (fun i => ∫ (y : α), g i y • (f y - c) ∂μ) l (𝓝 0)
this : Tendsto (fun x => ∫ (y : α), g x y • (f y - c) ∂μ + (∫ (y : α), g x y ∂μ) • c) l (𝓝 c)
⊢ Tendsto (fun i => ∫ (y : α), g i y • f y ∂μ) l (𝓝 c)
[PROOFSTEP]
exact Tendsto.congr' I this
|
This entry was posted on Wednesday, September 3rd, 2014 at 11:43 am and is filed under . You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.
|
#Start off by loading up some of the libraries that might be useful
#Manipulation
library(tidyr)
library(dplyr)
#Modeling
library(rpart)
library(randomForest)
library(rattle)
library(car)
library(caret)
library(e1071)
library(C50)
library(RWeka)
#Visualization
library(rpart.plot)
library(RColorBrewer)
library(ggplot2)
library(reshape2)
#import the train and test datasets from the directory
#import the test data from the file name test_orig
newtest <- test_orig
#insert a blank column to hold future values for Survived
newtest$Survived <- ""
#combine test and train into one dataset
titanicData <- rbind(train_orig,newtest)
#check out what the total dataset looks like now
str(titanicData)
View(titanicData)
#refactor the features Survived and Pclass into factors
titanicData$Survived <- as.factor(titanicData$Survived)
titanicData$Pclass <- as.factor(titanicData$Pclass)
#verify the changes
str(titanicData)
#Add some new features to the dataset for future use
#the first is to create a new feature called family_size to account for the family size of each passenger
#wherein the famil is the number of siblings and spouses, parents and children, and the individual
titanicData$family_size <- titanicData$SibSp + titanicData$Parch + 1
#Next, add a feature to account for the passengers title. There are several passengers that are the only
#ones with individual titles. This presents a problem for classification algorithms.
titanicData$Title <- sub(pattern = ".*,\\s(.*\\.)\\s.*", replacement = "\\1", x = titanicData$Name)
titanicData$Title[titanicData$Title %in% c("Don.", "Dona.", "the Countess.")] <- "Lady."
titanicData$Title[titanicData$Title %in% c("Ms.", "Mlle.")] <- "Miss."
titanicData$Title[titanicData$Title %in% c("Mme.", "Mrs. Martin (Elizabeth L.")] <- "Mrs."
titanicData$Title[titanicData$Title %in% c("Jonkheer.", "Don.")] <- "Sir."
titanicData$Title[titanicData$Title %in% c("Col.", "Capt.", "Major.")] <- "Officer."
titanicData$Title <- factor(titanicData$Title)
ggplot(titanicData[1:891,], aes(x=family_size, fill=Survived)) +
geom_histogram(binwidth = 1) +
facet_wrap(~Pclass + Title) +
ggtitle("Pclass, Title") +
xlab("family size") +
ylab("Total count") +
ylim(0,300) +
labs(fill = "Survived")
#Check for NA values in each feature of the dataset
table(is.na(titanicData$PassengerId))
table(is.na(titanicData$Survived))
table(is.na(titanicData$Pclass))
table(is.na(titanicData$Name))
table(is.na(titanicData$Sex))
table(is.na(titanicData$Age)) #NAs found
table(is.na(titanicData$SibSp))
table(is.na(titanicData$Parch))
table(is.na(titanicData$Ticket))
table(is.na(titanicData$Fare)) #NAs found
table(is.na(titanicData$Cabin))
table(is.na(titanicData$Embarked))
table(is.na(titanicData$family_size))
table(is.na(titanicData$Title))
#So Age has some NA values in the feature vector. One cannot exactly not have an age, so let's impute
#these missing values by predicting them based on values we know
predicted_age <- rpart(Age ~ Pclass
+ Sex
+ SibSp
+ Parch
+ Fare
+ Embarked
+ Title #new
+ family_size #new
, data = titanicData[!is.na(titanicData$Age),]
, method = "anova")
titanicData$Age[is.na(titanicData$Age)] <- predict(predicted_age, titanicData[is.na(titanicData$Age),])
#Fare also has some NA values in the feature vector. This is not helpful for solving the problem, so
#impute these missing variables as well using the median value (not the average) of the non-normal distribution
titanicData$Fare[is.na(titanicData$Fare)==TRUE] <- median(titanicData$Fare,na.rm=TRUE)
#In the dataset, two passengers do not have an embarked location. They had to come from somewhere, assuming
#they did not spawn from the ocean itself. Because most passengers embarked from "S," let's say these two
#did as well
titanicData$Embarked[c(62, 830)] <- "S"
titanicData$Embarked <- factor(titanicData$Embarked)
#Now add some new features to practice feature engineering and to see what may or may not be helpful
#These are all be binomials that might help us with our classification
titanicData$Child[titanicData$Age>=18] <- 0
titanicData$Child[titanicData$Age<18] <- 1
titanicData$Elder[titanicData$Age>=55] <- 1
titanicData$Elder[titanicData$Age<55] <- 0
titanicData$HighFare[titanicData$Fare>=200] <- 1
titanicData$HighFare[titanicData$Fare<200] <- 0
titanicData$LowFare[titanicData$Fare<=8] <- 1
titanicData$LowFare[titanicData$Fare>8] <- 0
#The group of features below are categorical in nature and polynomial
titanicData$TicketAB<-substring(titanicData$Ticket,1,1)
titanicData$TicketAB<-factor(titanicData$TicketAB)
titanicData$FamCat[titanicData$family_size == 1] <- 0
titanicData$FamCat[titanicData$family_size < 5 & titanicData$family_size > 1] <- 1
titanicData$FamCat[titanicData$family_size > 4] <- 2
titanicData$AgeGrp[titanicData$Age <= 10] <- 1
titanicData$AgeGrp[titanicData$Age > 10 & titanicData$Age <= 19] <- 2
titanicData$AgeGrp[titanicData$Age > 19 & titanicData$Age <=50] <- 3
titanicData$AgeGrp[titanicData$Age > 50] <- 4
titanicData$FareGrp[titanicData$Fare <=10] <- 1
titanicData$FareGrp[titanicData$Fare >10 & titanicData$Fare <=50] <- 2
titanicData$FareGrp[titanicData$Fare >50 & titanicData$Fare <=100] <- 3
titanicData$FareGrp[titanicData$Fare >100] <- 4
#Look at the Cabin feature
str(titanicData$Cabin)
table(titanicData$Cabin)
#This beast has 187 levels, which can lower the performance of classification algorithms
titanicData$Cabin <- as.character(titanicData$Cabin)
titanicData$Cabin[is.na(titanicData$Cabin)] <- "U"
titanicData$Cabin[titanicData$Cabin==""] <- "U"
titanicData$Cab<-substring(titanicData$Cabin,1,1)
titanicData$Cab<-factor(titanicData$Cab)
titanicData$Cabin<-factor(titanicData$Cabin)
#Our new feature, Cab, has only 9 levels and still represents most of the information from
#the Cabin feature vector
str(titanicData$Cab)
#Add some categorical features to group families into types by their size
titanicData$FamType[titanicData$family_size == 1] <- 'single'
titanicData$FamType[titanicData$family_size < 5 & titanicData$family_size > 1] <- 'small'
titanicData$FamType[titanicData$family_size > 4] <- 'large'
titanicData$FamType<-factor(titanicData$FamType)
#Some passengers are actually registered to multiple cabins. This can be related to a passengers
#socioeconomic status which can affect survivability
titanicData$MultiCab <- as.factor(ifelse(str_detect(titanicData$Cabin, " "), "Y", "N"))
#The features for Fare and Age have values that are outliers and values that disturb the distribution
#so create two new features that are normalized representations of both
#probably will not use them, but making them anyway for now
titanicData$FareNorm <- data.Normalization(titanicData$Fare, type="n1",normalization="column")
titanicData$AgeNorm <- data.Normalization(titanicData$Age, type="n12",normalization="column")
#Check on the structure of the dataset now
str(titanicData)
#Refactor some of the new features
titanicData$Child<-factor(titanicData$Child)
titanicData$Elder<-factor(titanicData$Elder)
titanicData$HighFare<-factor(titanicData$HighFare)
titanicData$LowFare<-factor(titanicData$LowFare)
titanicData$FamCat<-factor(titanicData$FamCat)
titanicData$AgeGrp<-factor(titanicData$AgeGrp)
titanicData$FareGrp<-factor(titanicData$FareGrp)
#Transform some of the others from num to int
titanicData$Age <- as.integer(titanicData$Age)
titanicData$family_size <- as.integer(titanicData$family_size)
#Now split the data back into training and test sets
train <- titanicData[1:891,]
train$Survived <- factor(train$Survived)
str(train)
test <- titanicData[892:1309,]
test$Survived <- factor(test$Survived)
str(test)
#Set seed for reproducibility
set.seed(1)
#First trying the random forest algorithm with cross validation
estPerformance <- c(0,0,0,0,0,0,0,0,0,0)
for(h in 1:10){
#For each of the ten
accs<-c(0,0,0,0)
n <- nrow(train)
shuffled <- train[sample(n),]
for (i in 1:4) {
indices <- (((i-1) * round((1/4)*nrow(shuffled))) + 1):((i*round((1/4) * nrow(shuffled))))
# Exclude them from the train set
train2 <- shuffled[-indices,]
# Include them in the test set
test2 <- shuffled[indices,]
m <- randomForest(as.factor(Survived) ~ Title +
Sex + #
Age + #
TicketAB + #
Pclass+
family_size+
FareGrp #+ #
,ntree=1500, data=train,importance=TRUE)
#Make a prediction on the test set using tree
pred <- predict(m, test2, type="class")
#Assign the confusion matrix to conf
conf<-table(test2$Survived,pred)
#Assign the accuracy of this model to the ith index in accs
accs[i]<-sum(diag(conf))/sum(conf)
}
estPerformance[h] <- mean(accs)
}
#Check out the confusion matrix
conf
#Have a look at the different features used and their performance power
varImpPlot(m)
#Check out the average of all of the folded results using this model and ensuring the records
#are shuffled prior to each evaluation
mean(estPerformance)
#The random forest performance averages around .892
#Create predictions based on the model above
myPrediction <- predict(m, test)
#Generate the solution file for the competition
mySolution <- data.frame(PassengerID=test$PassengerId, Survived=myPrediction)
write.csv(mySolution,file="my_solution(rForest).csv", row.names=FALSE)
#Now trying a J48 classification tree from Weka
m <- J48(as.factor(Survived) ~ Title
+Sex
+Age
+TicketAB
+Pclass
+family_size
+FareGrp
,data=train)
#Use the built-in evaluation methods to analyze the performance of the J48
e <- evaluate_Weka_classifier(m,cost = matrix(c(0,2,1,0), ncol = 2),
numFolds = 10, complexity = TRUE, #newdata=test,
seed = 123, class = TRUE)
#View the summary of the performance results
e$details
#Even though it is still looking at the training set, the performance is around 83%, which is a
#pretty good sign
#Now use some cross validation to further test the performance of the J48 model
estPerformance <- c(0,0,0,0,0,0,0,0,0,0)
for(h in 1:10){
#For each of the ten
accs<-c(0,0,0,0)
n <- nrow(train)
shuffled <- train[sample(n),]
for (i in 1:4) {
indices <- (((i-1) * round((1/4)*nrow(shuffled))) + 1):((i*round((1/4) * nrow(shuffled))))
# Exclude them from the train set
train2 <- shuffled[-indices,]
# Include them in the test set
test2 <- shuffled[indices,]
m <- J48(as.factor(Survived) ~ Title
+Age
+TicketAB
+FamType
+Fare
+Sex
+Pclass
+Cab
+FamCat
+family_size
+MultiCab
,train)
#Make a prediction on the test set using tree
pred <- predict(m, test2, type="class")
#Assign the confusion matrix to conf
conf<-table(test2$Survived,pred)
#Assign the accuracy of this model to the ith index in accs
accs[i]<-sum(diag(conf))/sum(conf)
}
estPerformance[h] <- mean(accs)
}
#Check out the confusion matrix
conf
#Check out the average of all of the folded results using this model and ensuring the records
#are shuffled prior to each evaluation
mean(estPerformance)
#Performance average hovers around .866, which seems good enough to make a submission to the contest
#Use the built-in evaluation methods to analyze the performance of the J48
e <- evaluate_Weka_classifier(m,cost = matrix(c(0,2,1,0), ncol = 2),
numFolds = 10, complexity = TRUE,
seed = 123, class = TRUE)
#View the summary of the performance results
e$details
#The built-in performance measurement gives the model around .829, which is still okay
#Create predictions based on the model above
myPrediction <- predict(m, test)
#Generate the solution file
mySolution <- data.frame(PassengerID=test$PassengerId, Survived=myPrediction)
write.csv(my_solution,file="my_solution(J48).csv", row.names=FALSE)
|
= = = Unbreakable Kimmy Schmidt = = =
|
#' Accrual prediction plots
#'
#' Generates an accrual prediction plot based an accrual data frame (produced by accrual_create_df)
#' and a target sample size.
#' If the accrual data frame is a list (i.e. using the by option in accrual_create_df),
#' or if center start dates are given, the number of enrolled and targeted sites is included.
#'
#' @rdname accrual_plot_predict
#' @param accrual_df accrual data frame produced by accrual_create_df (optionally with by option as a list)
#' @param target target sample size, if it is a vector with the same length as accrual_df, center-specific
#' predictions are shown
#' @param overall logical, indicates that accrual_df contains a summary with all sites (only if by is not NA)
#' @param name_overall name of the summary with all sites (if by is not NA and overall==TRUE)
#' @param fill_up whether to fill up days where no recruitment was observed,
#' otherwise these points do not contribute to the regression, default is yes
#' @param wfun function to calculate the weights based on the accrual data frame, default is
#' wfun<-function(x) seq(1 / nrow(x), 1, by = 1/nrow(x))
#' @param col.obs line color of cumulative recruitment, can be a vector with the same length as accrual_df
#' @param lty.obs line type of cumulative recruitment, can be a vector with the same length as accrual_df
#' @param col.pred line color of prediction, can be a vector with the same length as accrual_df
#' @param lty.pred line color of prediction, can be a vector with the same length as accrual_df
#' @param pch.pred point symbol for end of prediction, can be a vector with the same length as accrual_df
#' @param pos_prediction position of text with predicted end date, out, in or none
#' @param label_prediction label for predicted end date
#' @param cex_prediction text size for predicted end date
#' @param format_prediction date format for predicted end date
#' @param show_center logical, whether the center info should be shown
#' (if accrual_df is a list or if center_start_dates are given)
#' @param design design options for the center info
#' 1 (default): below plot, 2: within plot, top, 3: within plot, bottom
#' @param center_label label for the center info
#' @param center_legend either "number" to plot numbers in the center strip or "strip" to add a legend strip,
#' requires specification of center_colors
#' @param center_colors colors to be used for the strip with the centers, a vector of length targetc
#' @param targetc target number of centers, to scale the legend if it is "strip"
#' @param center_legend_text_size size of the text of the center or legend strip, only has a function
# if center and center_legend is specified
#' @param ylim limits for y-axis, can be a vector with the same length as accrual_df
#' @param xlim limits for x-axis, can be a vector with the same length as accrual_df
#' @param ylab y-axis label
#' @param xlabformat format of date on x-axis
#' @param xlabn integer giving the desired number of intervals for the xlabel, default=5
#' @param xlabminn nonnegative integer giving the minimal number of intervals
#' @param xlabformat format of date on x-axis
#' @param xlabpos position of the x-label, can be a vector with the same length as accrual_df
#' @param xlabsrt rotation of x-axis labels in degrees
#' @param xlabadj adjustment of x-label, numeric vector with length 1 or 2 for different adjustment in x- and y-direction
#' @param xlabcex size of x-axis label
#' @param mar vector of length 4 (bottom, left, top, right margins), overwrite default margins
#' @param legend.list named list with options passed to legend(), only if accrual data frame is a list
#' @param ... further options passed to plot() and axis()
#' @param center_start_dates alternative way to add center info,
#' vector with dates on which centers are enrolled
#'
#' @return A plot with cumulative accrual and the prediction to the end date.
#'
#' @export
#'
#' @importFrom grDevices heat.colors
#'
#' @examples
#' #Data
#' set.seed(2020)
#' enrollment_dates <- as.Date("2018-01-01") + sort(sample(1:30, 50, replace=TRUE))
#'
#' #Default plot
#' accrual_df<-accrual_create_df(enrollment_dates)
#' accrual_plot_predict(accrual_df=accrual_df,target=100)
#'
#' #Include site
#' set.seed(2021)
#' centers<-sample(c("Site 1","Site 2","Site 3"),length(enrollment_dates),replace=TRUE)
#' accrual_df<-accrual_create_df(enrollment_dates,by=centers)
#' accrual_plot_predict(accrual_df=accrual_df,target=100,center_label="Site")
#' ## with strip and target
#' accrual_plot_predict(accrual_df=accrual_df,target=100,center_label="Site",
#' targetc=5,center_colors=heat.colors(5),center_legend="strip")
#'
#' #Design for site
#' accrual_plot_predict(accrual_df=accrual_df,target=100,design=2)
#'
#' #Format prediction end date
#' accrual_plot_predict(accrual_df=accrual_df,target=100,
#' pos_prediction="in",label_prediction="End of accrual: ",cex_prediction=1.2,
#' format_prediction="%Y-%m-%d",ylim=c(0,150))
#'
#' #Format plot
#' accrual_plot_predict(accrual_df=accrual_df,target=100,
#' ylab="No of recruited patients",ylim=c(0,150),
#' xlabcex=1.2,xlabsrt=30,xlabn=5,xlabmin=5,
#' mgp=c(3,0.5,0),cex.lab=1.2,cex.axis=1.2)
#'
#' #predictions for all sites
#' accrual_plot_predict(accrual_df=accrual_df,target=c(30,30,30,100))
#' ## different colors
#' accrual_plot_predict(accrual_df=accrual_df,target=c(30,30,30,100),
#' col.obs=topo.colors(length(accrual_df)))
#' ##not showing center info
#' accrual_plot_predict(accrual_df=accrual_df,target=c(30,30,30,100),show_center=FALSE)
#'
accrual_plot_predict<-function(accrual_df,
target,
overall=TRUE,
name_overall=attr(accrual_df, "name_overall"),
fill_up=TRUE,
wfun=function(x) seq(1 / nrow(x), 1, by = 1/nrow(x)),
col.obs=NULL,
lty.obs=1,
col.pred="red",
lty.pred=2,
pch.pred=8,
pos_prediction=c("out","in","none"),
label_prediction="Predicted end date: ",
cex_prediction=1.1,
format_prediction="%B %d, %Y",
show_center=TRUE,
design=1,
center_label="Centers",
center_legend=c("number","strip"),
targetc=NA,
center_colors=NULL,
center_legend_text_size=0.7,
ylim=NA,xlim=NA,
ylab="Recruited patients",
xlabformat="%d%b%Y",
xlabn=5,
xlabminn= xlabn %/% 2,
xlabpos=NA,
xlabsrt=45,
xlabadj=c(1,1),
xlabcex=1,
mar=NA,
legend.list=NULL,
...,
center_start_dates=NULL) {
pos_prediction<-match.arg(pos_prediction)
center_legend<-match.arg(center_legend)
tmp <- lc_lct(accrual_df,
overall,
name_overall)
accrual_df <- tmp$accrual_df
lc <- tmp$lc
lct <- tmp$lct
overall <- tmp$overall
if (!is.na(sum(mar))) {
stopifnot(length(mar)==4)
}
if (length(target)!=1) {
#separate prediction
if (length(target)!=length(accrual_df)) {
stop("length of target has to correspond to length of accrual_df")
}
}
if (is.null(col.obs)) {
if (lc==1) {
col.obs="black"
} else {
col.obs<-gray.colors(lc)
}
}
#predictions
#&&&&&&&&&&
tmp <- pred_fn(accrual_df,
fill_up,
wfun,
lc,
overall,
target,
name_overall)
end_date <- tmp$end_date
edate <- tmp$edate
adf <- tmp$adf
#plot scaling
#&&&&&&&&&&
alim<-ascale(accrual_df,xlim=xlim,ylim=ylim,ni=xlabn,min.n=xlabminn,addxmax=edate,addymax=target)
# modification of ylim if design==3
if (show_center) {
if (lc>1 | !is.null(center_start_dates)) {
if (design==3) {
if (alim[["ylim"]][1]==0) {
alim[["ylim"]][1]<--max(target)/15
}
}
}
}
#margin
#&&&&&&&&&&
if (is.na(sum(mar))) {
#mar<-c(5.1,4.1,2.0,1.0)
mar<-c(5.1,4.1,4.1,2.1)
#centers
if (show_center) {
if (lc>1 | !is.null(center_start_dates)) {
#if (center_legend=="strip") {
#mar[4]<-2.5
#}
if (design==1)
mar[1]<-6.5
}
}
}
#plot raw data
#&&&&&&&&&&
par(mar=mar)
plot(0,type="n",ylim=alim[["ylim"]],xlim=alim[["xlim"]],
axes=FALSE,xlab="",ylab=ylab,...)
box()
#xlabel:
xlabsl<-format(alim[["xlabs"]], xlabformat)
axis(side=1,at=alim[["xlabs"]],labels=rep("",length(alim[["xlabs"]])),...)
if (is.na(xlabpos)) {
xlabpos<-par("usr")[3]-(par("usr")[4]-par("usr")[3])/30
}
text(x=alim[["xlabs"]],y=xlabpos,srt=xlabsrt,labels=xlabsl,xpd=TRUE,adj=xlabadj,cex=xlabcex)
#ylabel:
axis(side=2,las=1,...)
#only overall
if (lc==1 | (overall & length(target)==1)) {
lines(Cumulative~Date,data=adf,type="s",col=col.obs,lty=lty.obs)
lp<-adf[which.max(adf$Date),]
lines(x=c(lp$Date,end_date),y=c(lp$Cumulative,target),col=col.pred,lty=lty.pred)
points(x=end_date,y=target,pch=pch.pred,col=col.pred,xpd=TRUE)
#predicted end date
if (pos_prediction!="none") {
if (pos_prediction=="in") {
legend("topleft",paste0(label_prediction,format(end_date, format_prediction)),bty="n",
cex=cex_prediction)
} else {
text(x=par("usr")[1],y=par("usr")[4],adj=c(0,-1), xpd=TRUE,
paste0(label_prediction,format(end_date, format_prediction)),cex=cex_prediction)
}
}
} else {
#for each site:
target<-mult(target,length(adf))
col.obs<-mult(col.obs,length(adf))
lty.obs<-mult(lty.obs,length(adf))
col.pred<-mult(col.pred,length(adf))
lty.pred<-mult(lty.pred,length(adf))
pch.pred<-mult(pch.pred,length(adf))
for (k in 1:length(adf)) {
lines(Cumulative~Date,data=adf[[k]],type="s",col=col.obs[k],lty=lty.obs[k])
lp<-adf[[k]][which.max(adf[[k]]$Date),]
lines(x=c(lp$Date,end_date[[k]]),y=c(lp$Cumulative,target[k]),col=col.pred[k],lty=lty.pred[k])
points(x=end_date[[k]],y=target[k],pch=pch.pred[k],col=col.pred[k],xpd=TRUE)
}
lna<-paste0(names(adf),": ",format(do.call("c",end_date), format_prediction))
if(!is.null(legend.list)) {
ll<-legend.list
#defaults if not given:
vlist<-c("x","legend","ncol","col","lty","bty","y.intersp","seg.len")
obslist<-list("topleft",lna,1,col.obs,lty.obs,"n",0.85,1.5)
for (d in 1:length(vlist)) {
if (is.null(ll[[vlist[d]]])) {
ll[[vlist[d]]]<-obslist[[d]]
}
}
} else {
ll<-list(x = "topleft",legend = lna,ncol=1,col=col.obs,lty=lty.obs,bty="n",y.intersp=0.85,seg.len=1.5)
}
do.call("legend",ll)
}
#plot centers info
#&&&&&&&&&&
if (show_center) {
if (lc>1 | !is.null(center_start_dates)) {
plot_center(accrual_df=accrual_df,
center_start_dates=center_start_dates,
overall=overall,name_overall=name_overall,
lc=lc,lct=lct,design=design,
center_legend=center_legend,center_colors=center_colors,targetc=targetc,
center_label=center_label,center_legend_text_size=center_legend_text_size)
}
}
}
#**********************************************************************************#
#' Cumulative accrual plots
#'
#' Plot of cumulative recruitment based on accrual data frame produced by accrual_create_df
#'
#' @rdname accrual_plot_cum
#' @param accrual_df accrual data frame produced by accrual_create_df potentially with by option (i.e. as a list)
# with by option, a line is added for each element in the list
#' @param ylim limits for y-axis
#' @param xlim limits for x-axis
#' @param ylab y-axis label
#' @param xlabn integer giving the desired number of intervals for the xlabel, default=5
#' @param xlabminn nonnegative integer giving the minimal number of intervals
#' @param xlabformat format of date on x-axis
#' @param xlabpos position of the x-label
#' @param xlabsrt rotation of x-axis labels in degrees
#' @param xlabadj adjustment of x-label, numeric vector with length 1 or 2 for different adjustment in x- and y-direction
#' @param xlabcex size of x-axis label
#' @param col color for line(s) in plot
# if accrual_df is a list and overall is indicated, the first entry is used for the overall
#' @param lty line types in plot
# if accrual_df is a list and overall is indicated, the first entry is used for the overall
#' @param legend.list named list with options passed to legend()
#' @param ... further options passed to plot() and axis()
#'
#' @return A plot of the cumulative accrual, optionally by site.
#'
#' @export
#' @importFrom graphics plot
#'
#' @examples
#' set.seed(2020)
#' enrollment_dates <- as.Date("2018-01-01") + sort(sample(1:30, 50, replace=TRUE))
#' accrual_df<-accrual_create_df(enrollment_dates)
#' accrual_plot_cum(accrual_df)
#' accrual_plot_cum(accrual_df,cex.lab=1.2,cex.axis=1.1,xlabcex=1.1)
#'
#' #several sites
#' set.seed(1)
#' centers<-sample(c("Site 1","Site 2","Site 3"),length(enrollment_dates),replace=TRUE)
#' accrual_df<-accrual_create_df(enrollment_dates,by=centers)
#' accrual_plot_cum(accrual_df)
#'
#' #assuming a common start and current date
#' accrual_df<-accrual_create_df(enrollment_dates,by=centers,start_date="common",current_date="common")
#' accrual_plot_cum(accrual_df)
#'
#' #plot and legend options
#' accrual_plot_cum(accrual_df,col=c("red",rep(1,3)),lty=c(1,1:3),cex.lab=1.2,cex.axis=1.1,xlabcex=1.1)
#' accrual_plot_cum(accrual_df,legend.list=list(ncol=2,bty=TRUE,cex=0.8))
#'
#' #without overall
#' accrual_df<-accrual_create_df(enrollment_dates,by=centers,overall=FALSE)
#' accrual_plot_cum(accrual_df)
#'
accrual_plot_cum<-function(accrual_df,
ylim=NA,
xlim=NA,
ylab="Recruited patients",
xlabn=5,
xlabminn= xlabn %/% 2,
xlabformat="%d%b%Y",
xlabpos=NA,
xlabsrt=45,
xlabadj=c(1,1),
xlabcex=1,
col=rep(1:8,5),
lty=rep(1:5,each=8),
legend.list=NULL,
...) {
if (is.data.frame(accrual_df)) {
accrual_df<-list(accrual_df)
} else {
if (!all(unlist(lapply(accrual_df,function(x) is.data.frame(x))))) {
stop("accrual_df has to be a data frame or a list of data frames")
}
}
lc<-length(accrual_df)
if (lc>length(col)) {
col<-rep(col,lc)
}
if (lc>length(lty)) {
lty<-rep(lty,lc)
}
alim<-ascale(accrual_df,xlim=xlim,ylim=ylim,ni=xlabn,min.n=xlabminn)
lna<-names(accrual_df)
plot(0,type="n",ylim=alim[["ylim"]],xlim=alim[["xlim"]],
axes=FALSE,xlab="",ylab=ylab,...)
box()
#xlabel
xlabsl<-format(alim[["xlabs"]], xlabformat)
axis(side=1,at=alim[["xlabs"]],labels=rep("",length(alim[["xlabs"]])),...)
if (is.na(xlabpos)) {
xlabpos<-par("usr")[3]-(par("usr")[4]-par("usr")[3])/30
}
text(x=alim[["xlabs"]],y=xlabpos,srt=xlabsrt,labels=xlabsl,xpd=TRUE,adj=xlabadj,cex=xlabcex)
axis(side=2,las=1,...)
for (i in (1:lc)) {
dfi<-accrual_df[[i]]
lines(Cumulative~Date,data=dfi,col=col[i],lty=lty[i],type="s")
}
if (lc!=1) {
if(!is.null(legend.list)) {
ll<-legend.list
#defaults if not given:
vlist<-c("x","legend","ncol","col","lty","bty","y.intersp","seg.len")
obslist<-list("topleft",lna,1,col,lty,"n",0.85,1.5)
for (d in 1:length(vlist)) {
if (is.null(ll[[vlist[d]]])) {
ll[[vlist[d]]]<-obslist[[d]]
}
}
} else {
ll<-list(x = "topleft",legend = lna,ncol=1,col=col,lty=lty,bty="n",y.intersp=0.85,seg.len=1.5)
}
do.call("legend",ll)
}
}
#**********************************************************************************#
#' Absolute accrual plots
#'
#' Plot of absolute recruitment by time unit
#'
#' @rdname accrual_plot_abs
#' @param accrual_df accrual data frame produced by accrual_create_df (optionally with by option as a list)
#' @param unit time unit for which the bars should be plotted, any of "month","year","week","day"
#' @param target adds horizontal line for target recruitment per time unit
#' @param overall logical, indicates that accrual_df contains a summary with all sites
#' that should be removed from stacked barplot (only if by is not NA)
#' @param name_overall name of the summary with all sites (if by is not NA and overall==TRUE)
#' @param ylim limits for y-axis, numeric vector of length 2
#' @param xlim limits for x-axis, in barplot units, numeric vector of length 2
#' @param ylab y-axis label
#' @param xlabformat format of date on x-axis
#' @param xlabsel selection of x-labels if not all should be shown,
#' by default all are shown up to 15 bars, with more an automated selection is done,
#' either NA (default), NULL (show all), or a numeric vector
#' @param xlabpos position of the x-label
#' @param xlabsrt rotation of x-axis labels in degrees
#' @param xlabadj adjustment of x-label, numeric vector with length 1 or 2 for different adjustment
#' in x- and y-direction
#' @param xlabcex size of x-axis label
#' @param col colors of bars in barplot, can be a vector if accrual_df is a list, default is grayscale
#' @param legend.list named list with options passed to legend()
#' @param ... further arguments passed to barplot() and axis()
#'
#' @return Barplot of absolute recruitment by time unit, stacked if accrual_df is a list.
#'
#' @export
#'
#' @importFrom graphics abline axis barplot box grconvertX grconvertY legend lines mtext par points polygon text
#' @importFrom grDevices gray.colors
#'
#' @examples
#' set.seed(2020)
#' enrollment_dates <- as.Date("2018-01-01") + sort(sample(1:100, 50, replace=TRUE))
#' accrual_df<-accrual_create_df(enrollment_dates)
#' accrual_plot_abs(accrual_df,unit="week")
#'
#' #time unit
#' accrual_plot_abs(accrual_df,unit="day")
#'
#' #include target
#' accrual_plot_abs(accrual_df,unit="week",target=5)
#'
#' #further plot options
#' accrual_plot_abs(accrual_df,unit="week",ylab="No of recruited patients",
#' xlabformat="%Y-%m-%d",xlabsrt=30,xlabpos=-0.8,xlabadj=c(1,0.5),
#' col="pink",tck=-0.03,mgp=c(3,1.2,0))
#'
#' #accrual_df with by option
#' set.seed(2020)
#' centers<-sample(c("Site 1","Site 2","Site 3"),length(enrollment_dates),replace=TRUE)
#' centers<-factor(centers,levels=c("Site 1","Site 2","Site 3"))
#' accrual_df<-accrual_create_df(enrollment_dates,by=centers)
#' accrual_plot_abs(accrual_df=accrual_df,unit=c("week"))
#'
accrual_plot_abs<-function(accrual_df,
unit=c("month","year","week","day"),
target=NULL,
overall=TRUE,
name_overall=attr(accrual_df, "name_overall"),
ylim=NULL,
xlim=NULL,
ylab="Recruited patients",
xlabformat=NULL,
xlabsel=NA,
xlabpos=NULL,
xlabsrt=45,
xlabadj=c(1,1),
xlabcex=1,
col=NULL,
legend.list=NULL,
...) {
if (is.data.frame(accrual_df)) {
accrual_df<-list(accrual_df)
} else {
if (!all(unlist(lapply(accrual_df,function(x) is.data.frame(x))))) {
stop("accrual_df has to be a data frame or a list of data frames")
}
}
#remove overall if
if (length(accrual_df)>1 & overall==TRUE) {
if (is.null(accrual_df[[name_overall]])) {
print(paste0("'",name_overall,"' not found in accrual_df, overall set to FALSE"))
overall<-FALSE
} else {
accrual_df<-accrual_df[names(accrual_df)!=name_overall]
}
}
lc<-length(accrual_df)
unit<-match.arg(unit)
if (length(unit)!=1) {
stop("unit should be of length 1")
}
if (!is.null(ylim) & length(ylim)!=2) {
stop("ylim should be of length 2")
}
if (!is.null(xlim) & length(xlim)!=2) {
stop("xlim should be of length 2")
}
#default colors
if (is.null(col)) {
if (lc==1) {
col="grey"
} else {
col<-gray.colors(lc)
}
}
#default xlabformat
if (is.null(xlabformat)) {
if (unit=="month") {xlabformat<-"%b %Y"}
if (unit=="year") {xlabformat<-"%Y"}
if (unit=="week") {xlabformat<-"%d %b %Y"}
if (unit=="day") {xlabformat<-"%d %b %Y"}
}
for (i in 1:lc) {
accrual_dfi<-accrual_df[[i]]
#summarize data by time unit
dfi<-accrual_time_unit(accrual_dfi,unit=unit)
names(dfi)[names(dfi)=="Freq"]<-paste0("Freq",i)
if (i==1) {
#dfit<-dfi[,names(dfi)!="date"]
dfit<-dfi
} else {
#dfit<-merge(dfit,dfi[,names(dfi)!="date"],all=TRUE)
dfit<-merge(dfit,dfi,all=TRUE)
}
}
dfit<-dfit[order(dfit$date),]
ma<-as.matrix(dfit[,paste0("Freq",1:lc)])
ma[is.na(ma)]<-0
if (ncol(ma)>1) {
ma<-ma[,ncol(ma):1]
}
rownames(ma)<-rep("",nrow(ma))
if (is.null(ylim)) {
ylim<-c(0,max(apply(ma,1,function(x) sum(x,na.rm=TRUE)),target,na.rm=TRUE)+1)
}
#xscale
b<-barplot(t(ma),plot=FALSE)
if (is.null(xlim)) {
xlim<-c(min(b),max(b)) + c(-0.5,0.5)
}
#x label selection
if (is.null(xlabsel)) {
sel<-1:length(b)
} else {
if (sum(!is.na(xlabsel))==0) {
if (length(b)>15) {
sel<-round(seq(1,length(b),l=8))
sel<-sel[sel>0&sel<=length(b)]
} else {
sel<-1:length(b)
}
} else {
sel<-xlabsel
}
}
#plot
b<-barplot(t(ma),ylab=ylab,ylim=ylim,axes=FALSE,xlim=xlim,col=col,...)
box()
axis(side=2,las=2,...)
axis(side=1,at=b,labels=rep("",length(b)),...)
#xlabel
if (is.null(xlabpos)) {
xlabpos<-par("usr")[3]-(par("usr")[4]-par("usr")[3])/30
}
sel<-sel[sel<=length(b)]
bu<-b[sel]
lab<-format(dfit$date,xlabformat)
lab<-lab[sel]
text(x=bu,y=xlabpos,srt=xlabsrt,labels=lab,xpd=TRUE,adj=xlabadj,cex = xlabcex)
#line for target
if (!is.null(target)) {
abline(h=target,lty=2)
}
#legend
if (lc!=1) {
if(!is.null(legend.list)) {
ll<-legend.list
#defaults if not given:
vlist<-c("x","legend","ncol","fill","bty","y.intersp","seg.len")
obslist<-list("topright",names(accrual_df),1,rev(col),"n",0.85,1.5)
for (d in 1:length(vlist)) {
if (is.null(ll[[vlist[d]]])) {
ll[[vlist[d]]]<-obslist[[d]]
}
}
} else {
ll<-list(x = "topright",legend = names(accrual_df),ncol=1,fill=rev(col),
bty="n",y.intersp=0.85,seg.len=1.5)
}
do.call("legend",ll)
}
}
# helpers
ascale<-function(adf,xlim=NA,ylim=NA,ni=5,min.n=ni %/% 2) {
if (is.data.frame(adf)) {
adf<-list(adf)
}
if (sum(!is.na(xlim))==0) {
xlims<-c(min(do.call("c",lapply(adf,function(x) min(x$Date)))),
max(do.call("c",lapply(adf,function(x) max(x$Date)))))
} else {
xlims<-xlim
}
xlabs<-pretty(x=xlims,n=ni,min.n=min.n)
xlabs<-xlabs[xlabs>=xlims[1] & xlabs <=xlims[2]]
if (sum(!is.na(ylim))==0) {
ymax<-max(do.call("c",lapply(adf,function(x) max(x$Cumulative))))
ylims<-c(0,ymax)
} else {
ylims<-ylim
}
alim<-list(xlim=xlims,ylim=ylims,xlabs=xlabs)
return(alim)
}
mult<-function(var, accrual_df) {
if (length(var)==1) {
var<-rep(var,length(accrual_df))
return(var)
} else {
stopifnot(length(var)==length(accrual_df))
return(var)
}
}
|
import tactic natree.natree
namespace chapter3
--equational "axioms"
@[simp] def kernel {y z} : △⬝△⬝y⬝z = y := natree.kernel
@[simp] def stem {x y z} : △⬝(△⬝x)⬝y⬝z = y⬝z⬝(x⬝z) := natree.stem
@[simp] def fork {w x y z} : △⬝(△⬝w⬝x)⬝y⬝z = z⬝w⬝x := natree.fork
--K combinator (similar to Kernel rule)
def derive_K : {K : 𝕋 // ∀ x y, K⬝x⬝y = x} := begin
--metavariable ?m_1 introduced for K
split,
intros x y,
--use kernel rule
symmetry,
transitivity,
symmetry,
apply kernel,
exact y,
symmetry,
--remove trailing ys
apply congr,
apply congr,
refl,
--remove trailing xs
apply congr,
apply congr,
refl,
--?m_1 = △⬝△
--finish proof
repeat {refl},
end
def K : 𝕋 := △⬝△
--I combinator (Identity combinator)
def derive_I : {I : 𝕋 // ∀ x, I⬝x = x} := begin
--metavariable ?m_1 introduced for I
split,
intro x,
--use kernel rule
symmetry,
transitivity,
symmetry,
apply kernel,
exact △⬝x,
symmetry,
--use stem rule
symmetry,
transitivity,
symmetry,
apply stem,
symmetry,
--remove trailing xs
apply congr,
apply congr,
refl,
--?m_1 = △⬝(△⬝△)⬝(△⬝△)
--finish proof
repeat {refl},
end
def I : 𝕋 := △⬝(△⬝△)⬝(△⬝△)
--D combinator (flipped S combinator, similar to Stem rule)
def derive_D : {D : 𝕋 // ∀ x y z, D⬝x⬝y⬝z = y⬝z⬝(x⬝z)} := begin
--metavariable ?m_1 introduced for D
split,
intros x y z,
--use stem rule
symmetry,
transitivity,
symmetry,
apply stem,
symmetry,
--remove trailing zs
apply congr,
apply congr,
refl,
--remove trailing ys
apply congr,
apply congr,
refl,
--replace △ with K⬝△⬝x
symmetry,
transitivity,
apply congr,
apply congr,
refl,
symmetry,
show K⬝△⬝x = △,
apply derive_K.property,
refl,
symmetry,
--use stem rule
symmetry,
transitivity,
symmetry,
apply stem,
symmetry,
--remove trailing xs
apply congr,
apply congr,
refl,
--unfold definition of K
symmetry,
transitivity,
apply congr,
refl,
apply congr,
apply congr,
refl,
show K = △⬝△,
refl,
refl,
symmetry,
--?m_1 = △⬝(△⬝△)⬝(△⬝△⬝△)
--finish proof
repeat {refl},
end
def D : 𝕋 := △⬝(△⬝△)⬝(△⬝△⬝△)
--d function (shorter version of D)
def d (x : 𝕋) : 𝕋 := △⬝(△⬝x)
lemma d_equiv_D {x} : D⬝x = d x := by simp [d, D]
--iterated application
def iterate : ℕ → 𝕋 → 𝕋 → 𝕋
| 0 a b := b
| (n+1) a b := a⬝(iterate n a b)
notation a ^ n ⬝ b := iterate n a b
--derivation of the fundamental queries
def derive_q {a b c e} : {q : 𝕋 // ∀ x, q⬝x = △⬝x⬝a⬝b⬝c⬝e} := begin
--metavariable ?m_1 introduced for q
split,
intro x,
--replace △⬝x⬝a with D⬝(K⬝a)⬝△⬝x (utilizing Stem rule)
symmetry,
transitivity,
apply congr,
apply congr,
refl,
apply congr,
apply congr,
refl,
apply congr,
apply congr,
refl,
show △⬝x⬝a = D⬝(K⬝a)⬝△⬝x,
symmetry,
have h : D = derive_D.val := rfl,
rw h,
transitivity,
apply derive_D.property,
apply congr,
refl,
have h₂ : K = derive_K.val := rfl,
rw h₂,
apply derive_K.property,
refl,
refl,
refl,
symmetry,
--replace (D⬝(K⬝a)⬝△)⬝x⬝b with D⬝(K⬝b)⬝(D⬝(K⬝a)⬝△)⬝x (utilizing Stem rule)
symmetry,
transitivity,
apply congr,
apply congr,
refl,
apply congr,
apply congr,
refl,
show (D⬝(K⬝a)⬝△)⬝x⬝b = D⬝(K⬝b)⬝(D⬝(K⬝a)⬝△)⬝x,
symmetry,
have h : D = derive_D.val := rfl,
rw h,
transitivity,
apply derive_D.property,
apply congr,
refl,
have h₂ : K = derive_K.val := rfl,
rw h₂,
apply derive_K.property,
refl,
refl,
symmetry,
--replace D⬝(K⬝b)⬝(D⬝(K⬝a)⬝△)⬝x⬝c with D⬝(K⬝c)⬝(D⬝(K⬝b)⬝(D⬝(K⬝a)⬝△))⬝x (utilizing Stem rule)
symmetry,
transitivity,
apply congr,
apply congr,
refl,
show D⬝(K⬝b)⬝(D⬝(K⬝a)⬝△)⬝x⬝c = D⬝(K⬝c)⬝(D⬝(K⬝b)⬝(D⬝(K⬝a)⬝△))⬝x,
symmetry,
have h : D = derive_D.val := rfl,
rw h,
transitivity,
apply derive_D.property,
apply congr,
refl,
have h₂ : K = derive_K.val := rfl,
rw h₂,
apply derive_K.property,
refl,
symmetry,
--replace D⬝(K⬝c)⬝(D⬝(K⬝b)⬝(D⬝(K⬝a)⬝△))⬝x⬝d with D⬝(K⬝d)⬝(D⬝(K⬝c)⬝(D⬝(K⬝b)⬝(D⬝(K⬝a)⬝△)))⬝x (utilizing Stem rule)
symmetry,
transitivity,
show D⬝(K⬝c)⬝(D⬝(K⬝b)⬝(D⬝(K⬝a)⬝△))⬝x⬝e = D⬝(K⬝e)⬝(D⬝(K⬝c)⬝(D⬝(K⬝b)⬝(D⬝(K⬝a)⬝△)))⬝x,
symmetry,
have h : D = derive_D.val := rfl,
rw h,
transitivity,
apply derive_D.property,
apply congr,
refl,
have h₂ : K = derive_K.val := rfl,
rw h₂,
apply derive_K.property,
symmetry,
--remove xs
apply congr,
apply congr,
refl,
--replace with ds
symmetry,
repeat {
transitivity,
rw d_equiv_D,
},
symmetry,
--?m_1 = d (K⬝e)⬝(d (K⬝c)⬝(d (K⬝b)⬝(d (K⬝a)⬝△)))
--finish proof
repeat {refl},
end
def bool_to_natree : bool → 𝕋
| tt := K
| ff := K⬝I
structure solution_property (f g h k : 𝕋) (is0 is1 is2 : bool) : Prop :=
(eq0 : △⬝△⬝f⬝g⬝h⬝k = bool_to_natree is0)
(eq1 : ∀ x, △⬝(△⬝x)⬝f⬝g⬝h⬝k = bool_to_natree is1)
(eq2 : ∀ x y, △⬝(△⬝x⬝y)⬝f⬝g⬝h⬝k = bool_to_natree is2)
lemma k2 {a b c} : (K^2⬝a)⬝b⬝c = a := begin
--rewrite in terms of derive_K.val
repeat {rw iterate},
have h : K = derive_K.val := rfl,
rw h,
--remove c
transitivity,
apply congr,
apply congr,
refl,
--simplify using K-rule
apply derive_K.property,
refl,
--simplify using K-rule again
apply derive_K.property,
end
lemma k4 {a b c d e} : (K^4⬝a)⬝b⬝c⬝d⬝e = a := begin
--rewrite in terms of derive_K.val
repeat {rw iterate},
have h : K = derive_K.val := rfl,
rw h,
--remove c, d and e
transitivity,
apply congr,
apply congr,
refl,
apply congr,
apply congr,
refl,
apply congr,
apply congr,
refl,
--simplify using K-rule
apply derive_K.property,
refl,
refl,
refl,
--remove d and e
transitivity,
apply congr,
apply congr,
refl,
apply congr,
apply congr,
refl,
--simplify using K-rule
apply derive_K.property,
refl,
refl,
--remove e
transitivity,
apply congr,
apply congr,
refl,
--simplify using K-rule
apply derive_K.property,
refl,
--simplify using K-rule again
apply derive_K.property,
end
lemma kI {a b} : K⬝I⬝a⬝b = b := begin
transitivity,
apply congr,
apply congr,
refl,
have h : K = derive_K.val := rfl,
show K⬝I⬝a = I,
rw h,
apply derive_K.property,
refl,
have h₂ : I = derive_I.val := rfl,
rw h₂,
apply derive_I.property,
end
def prove_query {is0 is1 is2} : Σ' f g h k, solution_property f g h k is0 is1 is2 := begin
--apply naive solution for f (K^2⬝(bool_to_natree is0))
split,
show 𝕋,
exact K^2⬝(bool_to_natree is0),
--apply naive solution for g (K^4⬝(bool_to_natree is2))
split,
show 𝕋,
exact K^4⬝(bool_to_natree is2),
--apply derived solution for h (bool_to_natree is1)
split,
show 𝕋,
exact bool_to_natree is1,
--apply derived solution for k (bool_to_natree is1)
split,
show 𝕋,
exact bool_to_natree is1,
split,
---------------------------------------------
--remove h and k
transitivity,
apply congr,
apply congr,
refl,
apply congr,
apply congr,
refl,
--use kernel rule
apply kernel,
refl,
refl,
--use k2
apply k2,
---------------------------------------------
intro x,
--remove h and k
transitivity,
apply congr,
apply congr,
refl,
apply congr,
apply congr,
refl,
--use stem rule and k2
transitivity,
apply stem,
apply k2,
refl,
refl,
--split on cases
cases is0,
--case false
rw bool_to_natree,
apply kI,
--case true
rw bool_to_natree,
have h : K = derive_K.val := rfl,
rw h,
apply derive_K.property,
---------------------------------------------
intros x y,
--remove h and k
transitivity,
apply congr,
apply congr,
refl,
apply congr,
apply congr,
refl,
--use fork rule and k4
transitivity,
apply fork,
refl,
refl,
refl,
apply k4,
end
--D in terms of K and S
def S : 𝕋 := (d (K⬝D))⬝((d K)⬝(K⬝D))
lemma S_prop {x y z} : S⬝x⬝y⬝z = x⬝z⬝(y⬝z) := by simp [S, d, D, K]
def D' : 𝕋 := S⬝(K⬝(S⬝S))⬝K
example {x y z} : D'⬝x⬝y⬝z = y⬝z⬝(x⬝z) := by simp [D', S, d, D, K]
--Defining fst and snd
def fst : 𝕋 := S⬝(K⬝(△⬝(K⬝K)⬝△))⬝△
example {x y} : fst⬝(△⬝x⬝y) = x := by simp [fst, S, d, D, K]
def snd : 𝕋 := S⬝(K⬝(△⬝(K⬝(K⬝I))⬝△))⬝△
example {x y} : snd⬝(△⬝x⬝y) = y := by simp [snd, S, d, D, K, I]
def unseat : 𝕋 := S⬝(K⬝(S⬝I))⬝K
example {x y} : unseat⬝x⬝y = y⬝x := by simp [unseat, S, d, D, K, I]
--flip⬝(b⬝x⬝y) = b⬝y⬝x
--Exercise 8
--binary trees indexed by depth
inductive btree : ℕ → Type
| kernel : btree 0
| stem {n} : btree n → btree (n + 1)
| fork {n₁ n₂} : btree n₁ → btree n₂ → btree (max n₁ n₂)
example : fintype (btree 0) := begin
split,
show finset _,
split,
show multiset _,
exact ⟦[btree.kernel]⟧,
rw multiset.nodup,
dsimp at *,
end
/-
https://oeis.org/A002065
Two sequences:
a_0 = 0
a_1 = 1
a(n) = a(n-1) * (a(n-1) + 2) - a(n-2) * (a(n-2) + 1)
= a(n-1)^2 + (2*a(n-1) - a(n-2)^2 - a(n-2))
= a(n-1) + a(n-1)^2 + 1
a(n) gives number of binary trees where depth <= n-1
b(0) = 0
b(1) = 1
b(n) = b(n-1) + a(n-1)^2 - a(n-2)^2
= b(n-1) * (a(n-1) + a(n-2) + 1)
= b(n-1) * (2a(n-1) - b(n-1) + 1)
= a(n) - a(n-1)
= a(n-1)^2 + 1
b(n) gives number of binary trees where depth = n-1
Depth 0:
●
Depth 1:
│ ┌┴┐
● ● ●
Depth 2:
│ │ ┌┴┐ ┌┴─┐ ┌┴┐ ┌┴┐ ┌┴─┐ ┌─┴┐ ┌─┴┐ ┌─┴─┐
│ ┌┴┐ ● │ ● ┌┴┐ │ ● │ │ │ ┌┴┐ ┌┴┐ ● ┌┴┐ │ ┌┴┐ ┌┴┐
● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ●
...
-/
end chapter3
|
/*
(c) 2015 NumScale SAS
(c) 2015 LRI UMR 8623 CNRS/University Paris Sud XI
(c) 2015 Glen Joseph Fernandes
<glenjofe -at- gmail.com>
Distributed under the Boost Software
License, Version 1.0.
http://boost.org/LICENSE_1_0.txt
*/
#ifndef BOOST_ALIGN_ASSUME_ALIGNED_HPP
#define BOOST_ALIGN_ASSUME_ALIGNED_HPP
#include <boost/config.hpp>
#if defined(BOOST_MSVC)
#include <boost/align/detail/assume_aligned_msvc.hpp>
#elif defined(BOOST_CLANG) && defined(__has_builtin)
#include <boost/align/detail/assume_aligned_clang.hpp>
#elif BOOST_GCC_VERSION >= 40700
#include <boost/align/detail/assume_aligned_gcc.hpp>
#elif defined(__INTEL_COMPILER)
#include <boost/align/detail/assume_aligned_intel.hpp>
#else
#include <boost/align/detail/assume_aligned.hpp>
#endif
#endif
|
[STATEMENT]
lemma paths_in_all_paths: "paths \<subseteq> all_paths"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. paths \<subseteq> all_paths
[PROOF STEP]
unfolding all_paths_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. paths \<subseteq> {xs |xs. path xs}
[PROOF STEP]
using paths
[PROOF STATE]
proof (prove)
using this:
?xs \<in> paths \<Longrightarrow> v0 \<leadsto>?xs\<leadsto> v1
goal (1 subgoal):
1. paths \<subseteq> {xs |xs. path xs}
[PROOF STEP]
by blast
|
Formal statement is: proposition homotopic_paths_continuous_image: "\<lbrakk>homotopic_paths s f g; continuous_on s h; h ` s \<subseteq> t\<rbrakk> \<Longrightarrow> homotopic_paths t (h \<circ> f) (h \<circ> g)" Informal statement is: If $f$ and $g$ are homotopic paths in $s$, and $h$ is a continuous map from $s$ to $t$, then $h \circ f$ and $h \circ g$ are homotopic paths in $t$.
|
section \<open>Preliminaries\<close>
(*<*)
theory Prelim
imports "HOL-Library.Stream"
begin
(*>*)
abbreviation any where "any \<equiv> undefined"
lemma append_singl_rev: "a # as = [a] @ as" by simp
lemma list_pair_induct[case_names Nil Cons]:
assumes "P []" and "\<And>a b list. P list \<Longrightarrow> P ((a,b) # list)"
shows "P lista"
using assms by (induction lista) auto
lemma list_pair_case[elim, case_names Nil Cons]:
assumes "xs = [] \<Longrightarrow> P" and "\<And>a b list. xs = (a,b) # list \<Longrightarrow> P"
shows "P"
using assms by(cases xs, auto)
definition asList :: "'a set \<Rightarrow> 'a list" where
"asList A \<equiv> SOME as. distinct as \<and> set as = A"
lemma asList:
assumes "finite A" shows "distinct (asList A) \<and> set (asList A) = A"
unfolding asList_def by (rule someI_ex) (metis assms finite_distinct_list)
lemmas distinct_asList = asList[THEN conjunct1]
lemmas set_asList = asList[THEN conjunct2]
lemma map_sdrop[simp]: "sdrop 0 = id"
by (auto intro: ext)
lemma stl_o_sdrop[simp]: "stl o sdrop n = sdrop (Suc n)"
by (auto intro: ext)
lemma sdrop_o_stl[simp]: "sdrop n o stl = sdrop (Suc n)"
by (auto intro: ext)
lemma hd_stake[simp]: "i > 0 \<Longrightarrow> hd (stake i \<pi>) = shd \<pi>"
by (cases i) auto
(*<*)
end
(*>*)
|
-- Copyright 2022-2023 VMware, Inc.
-- SPDX-License-Identifier: BSD-2-Clause
import .linear
variables {a: Type} [ordered_add_comm_group a].
def positive (s: stream a) := 0 <= s.
def stream_monotone (s: stream a) := ∀ t, s t ≤ s (t+1).
def is_positive {b: Type} [ordered_add_comm_group b]
(f: stream a → stream b) := ∀ s, positive s → positive (f s).
-- TODO: could not get library monotone definition to work, possibly due to
-- partial_order.to_preorder?
-- set_option pp.notation false.
-- set_option pp.implicit true.
-- prove that [stream_monotone] can be rephrased in terms of order preservation
theorem stream_monotone_order (s: stream a) :
stream_monotone s ↔ (∀ t1 t2, t1 ≤ t2 → s t1 ≤ s t2) :=
begin
unfold stream_monotone, split; intro h; introv,
{ intros hle, have heq : t2 = t1 + (t2 - t1) := by omega,
rw heq at *,
generalize : (t2 - t1) = d,
clear_dependent t2,
induction d,
{ simp, },
{ transitivity s (t1 + d_n), assumption,
apply h, }
},
{ apply h, linarith, },
end
lemma integral_monotone (s: stream a) :
positive s → stream_monotone (I s) :=
begin
intros hp,
intros t,
repeat { rw integral_sum_vals },
repeat { simp [sum_vals] },
have h := hp (t + 1), simp at h,
assumption,
end
lemma derivative_pos (s: stream a) :
-- NOTE: paper is missing this, but it is also necessary (maybe they
-- intend `s[-1] =0` in the definition of monotone)
0 ≤ s 0 →
stream_monotone s → positive (D s) :=
begin
intros h0 hp, intros t; simp,
unfold D delay; simp,
split_ifs,
{ subst t, assumption },
{ have hle := hp (t - 1),
have heq : t - 1 + 1 = t := by omega, rw heq at hle,
assumption,
},
end
lemma derivative_pos_counter_example :
(∃ (x:a), x < 0) →
¬(∀ (s: stream a), stream_monotone s → positive (D s)) :=
begin
intros h, cases h with x hneg,
simp,
-- pushing the negation through, we're going to prove
-- ∃ (x : stream a), stream_monotone x ∧ ¬positive (D x)
use (λ _n, x),
split,
{ intros t, simp, },
{ unfold positive,
rw stream_le_ext, simp,
use 0, simp [D],
apply not_le_of_gt, assumption,
},
end
|
[STATEMENT]
lemma card_sccs_verts: "card G.sccs_verts = card H.sccs_verts"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. card G.sccs_verts = card H.sccs_verts
[PROOF STEP]
unfolding sccs_eq
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. card ((`) proj_verts_H ` H.sccs_verts) = card H.sccs_verts
[PROOF STEP]
by (intro card_image inj_on_proj_verts_H)
|
// Copyright 2007-2008 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License")
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an AS IS BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: [email protected] (Moshe Looks)
/****
Basic output and input on trees, format is e.g. f(x g(y z)). To output a
tree as an s-expression, e.g. (f x (g y z)) do
ostream << sexpr_format(tree), likewise to read do
istream >> sexpr_format(tree).
****/
#ifndef _TREE_TREE_IO_HPP_
#define _TREE_TREE_IO_HPP_
#define BOOST_SPIRIT_USE_OLD_NAMESPACE 1
#include <algorithm>
#include <istream>
#include <ostream>
#include <string>
#include <stdexcept>
#include <boost/spirit/include/classic.hpp>
#include <boost/lexical_cast.hpp>
#include "tree.hpp"
namespace TREE_TREE_NAMESPACE {
template<typename>
struct sexpr_io_wrapper;
template<typename T>
struct sexpr_io_wrapper<subtree<T> > {
explicit sexpr_io_wrapper(subtree<T> t) : _tr(t) {}
subtree<T> expr() { return _tr; }
const_subtree<T> expr() const { return _tr; }
typedef subtree<T> tree_t;
private:
subtree<T> _tr;
};
template<typename T>
struct sexpr_io_wrapper<const_subtree<T> > {
explicit sexpr_io_wrapper(const_subtree<T> t) : _tr(t) {}
const_subtree<T> expr() const { return _tr; }
typedef const_subtree<T> tree_t;
private:
const_subtree<T> _tr;
};
template<typename T>
struct sexpr_io_wrapper<tree<T>*> {
explicit sexpr_io_wrapper(tree<T>& t) : _tr(&t) {}
tree<T>& expr() { return *_tr; }
const tree<T>& expr() const { return *_tr; }
typedef tree<T> tree_t;
private:
tree<T>* _tr;
};
template<typename T>
struct sexpr_io_wrapper<const tree<T>*> {
explicit sexpr_io_wrapper(const tree<T>& t) : _tr(&t) {}
const tree<T>& expr() const { return *_tr; }
typedef tree<T> tree_t;
private:
const tree<T>* _tr;
};
template<typename T>
sexpr_io_wrapper<tree<T> > sexpr_format(subtree<T> t) {
return sexpr_io_wrapper<subtree<T> >(t);
}
template<typename T>
sexpr_io_wrapper<const_subtree<T> > sexpr_format(const_subtree<T> t) {
return sexpr_io_wrapper<const_subtree<T> >(t);
}
template<typename T>
sexpr_io_wrapper<tree<T>*> sexpr_format(tree<T>& t) {
return sexpr_io_wrapper<tree<T>*>(t);
}
template<typename T>
sexpr_io_wrapper<const tree<T>*> sexpr_format(const tree<T>& t) {
return sexpr_io_wrapper<const tree<T>*>(t);
}
// output
template<typename T>
std::ostream& operator<<(std::ostream& out,const_subtree<T> tr) {
if (tr.childless())
return out << tr.root();
out << tr.root() << "(";
for (typename const_subtree<T>::const_sub_child_iterator
it=tr.begin_sub_child();it!=tr.end_sub_child();++it)
out << *it << (boost::next(it)==tr.end_sub_child() ? ")" : " ");
return out;
}
template<typename T>
std::ostream& operator<<(std::ostream& out,subtree<T> tr) {
return out << const_subtree<T>(tr);
}
template<typename T>
std::ostream& operator<<(std::ostream& out,const tree<T>& tr) {
if (!tr.empty())
out << const_subtree<T>(tr);
return out;
}
// sexpr output
template<typename Tree>
std::ostream& operator<<(std::ostream& out,sexpr_io_wrapper<Tree> s) {
if (s.expr().empty())
return out << "()"; //empty tree
else if (s.expr().childless())
return out << s.expr().root();
out << "(" << s.expr().root() << " ";
for (typename sexpr_io_wrapper<Tree>::tree_t::const_sub_child_iterator
it=s.expr().begin_sub_child();it!=s.expr().end_sub_child();++it)
out << sexpr_format(*it)
<< (boost::next(it)==s.expr().end_sub_child() ? ")" : " ");
return out;
}
// input
namespace _tree_io_private {
using namespace boost::spirit;
using std::string;
struct tree_grammar : public boost::spirit::grammar<tree_grammar> {
mutable tree<string>* tr;
mutable tree<string>::sub_child_iterator at;
bool sexpr_io;
void begin_internal(const char* from, const char* to) const {
if (sexpr_io)
++from;
else
--to;
at=tr->insert(at,string(from,to))->begin_child();
}
void end_internal(const char) const { ++++at; }
void add_leaf(const char* from, const char* to) const {
tr->insert(at,string(from,to));
}
template<typename ScannerT>
struct definition {
definition(const tree_grammar& g) {
term=lexeme_d[(+( anychar_p - ch_p('(') - ch_p(')') - space_p))]
[boost::bind<void>(&tree_grammar::add_leaf,&g,_1,_2)];
if (g.sexpr_io)
beg=lexeme_d['(' >> (+( anychar_p - ch_p('(') - ch_p(')') - space_p))];
else
beg=lexeme_d[(+( anychar_p - ch_p('(') - ch_p(')') - space_p)) >> '('];
expr=(beg[boost::bind(&tree_grammar::begin_internal,&g,_1,_2)]
>> +expr >> ch_p(')')
[boost::bind(&tree_grammar::end_internal,&g,_1)]) |
term;
}
rule<ScannerT> expr,beg,term;
const rule<ScannerT>& start() const { return expr; }
};
};
inline bool lparen(char c) { return (c=='(' || c=='[' || c=='{'); }
inline bool rparen(char c) { return (c==')' || c==']' || c=='}'); }
inline bool whitespace(char c) { return (c==' ' || c=='\t' || c=='\n'); }
inline bool all_whitespace(const std::string& s) {
return std::find_if(s.begin(),s.end(),!boost::bind(&whitespace,_1))==s.end();
}
inline std::string chomp(const std::string& s) {
std::size_t i=0,j=s.length();
while (i<j && whitespace(s[i]))
++i;
do {
--j;
} while (i<j && whitespace(s[j]));
return s.substr(i,++j);
}
inline void read_string_tree(std::istream& in,tree<std::string>& dst,
bool sexpr_io) {
std::string str;
std::string::size_type nparen=0;
char c;
bool started=false;
do {
c=in.get();
if (lparen(c)) {
started=true;
++nparen;
} else if (rparen(c)) {
--nparen;
} else if (whitespace(c) && !started && !all_whitespace(str)) {
dst=tree<std::string>(chomp(str)); //a single node
return;
}
str.push_back(c);
} while (in && c!=EOF && (nparen>0 || !started));
if (c==EOF || whitespace(c)) {
str.erase(--str.end());
in.putback(c);
}
str=chomp(str);
if (nparen!=0)
throw std::runtime_error("paren mismatch reading: '"+str+"'");
tree_grammar g;
g.tr=&dst;
g.at=dst.begin();
g.sexpr_io=sexpr_io;
parse(str.c_str(),g,space_p);
}
template<typename T>
void rec_copy(subtree<std::string> str,subtree<T> dst) {
for (typename tree<std::string>::sub_child_iterator i=str.begin_sub_child();
i!=str.end_sub_child();++i)
rec_copy(*i,*dst.insert(dst.end_sub_child(),
boost::lexical_cast<T>(i->root())));
}
template<typename T>
std::istream& read_tree(std::istream& in,tree<T>& dst,bool sexpr_io) {
tree<std::string> str;
_tree_io_private::read_string_tree(in,str,sexpr_io);
dst.clear();
if (!str.empty()) {
rec_copy(subtree<std::string>(str),
*dst.insert(dst.end_sub(),boost::lexical_cast<T>(str.root())));
}
return in;
}
template<typename T>
std::istream& read_tree(std::istream& in,subtree<T> dst,bool sexpr_io) {
tree<std::string> str;
_tree_io_private::read_string_tree(in,str,sexpr_io);
if (str.empty())
throw std::runtime_error("can't read empty input into a subtree");
dst.prune();
dst.root()=boost::lexical_cast<T>(str.root());
rec_copy(str,dst);
return in;
}
} //namespace _tree_io_private
template<typename T>
std::istream& operator>>(std::istream& in,tree<T>& dst) {
return _tree_io_private::read_tree(in,dst,false);
}
template<typename T>
std::istream& operator>>(std::istream& in,subtree<T> dst) {
return _tree_io_private::read_tree(in,dst,false);
}
template<typename Tree>
std::istream& operator>>(std::istream& in,sexpr_io_wrapper<Tree> s) {
return _tree_io_private::read_tree(in,s.expr(),true);
}
} //namespace TREE_TREE_NAMESPACE
#endif //_TREE_TREE_IO_HPP_
|
State Before: k : Type u_2
V : Type u_3
P : Type u_1
inst✝³ : Ring k
inst✝² : AddCommGroup V
inst✝¹ : Module k V
inst✝ : AffineSpace V P
s₁ s₂ : Set P
h : affineSpan k s₁ ∥ affineSpan k s₂
⊢ vectorSpan k s₁ = vectorSpan k s₂ State After: k : Type u_2
V : Type u_3
P : Type u_1
inst✝³ : Ring k
inst✝² : AddCommGroup V
inst✝¹ : Module k V
inst✝ : AffineSpace V P
s₁ s₂ : Set P
h : affineSpan k s₁ ∥ affineSpan k s₂
⊢ direction (affineSpan k s₁) = direction (affineSpan k s₂) Tactic: simp_rw [← direction_affineSpan] State Before: k : Type u_2
V : Type u_3
P : Type u_1
inst✝³ : Ring k
inst✝² : AddCommGroup V
inst✝¹ : Module k V
inst✝ : AffineSpace V P
s₁ s₂ : Set P
h : affineSpan k s₁ ∥ affineSpan k s₂
⊢ direction (affineSpan k s₁) = direction (affineSpan k s₂) State After: no goals Tactic: exact h.direction_eq
|
State Before: M : Type w
A : Set M
L : Language
inst✝ : Structure L M
α : Type u₁
β : Type u_1
B : Set M
s✝ : Set (α → M)
f : α → β
s : Set (α → M)
h : Definable A L s
⊢ Definable A L ((fun g => g ∘ f) ⁻¹' s) State After: case intro
M : Type w
A : Set M
L : Language
inst✝ : Structure L M
α : Type u₁
β : Type u_1
B : Set M
s : Set (α → M)
f : α → β
φ : Formula (L[[↑A]]) α
⊢ Definable A L ((fun g => g ∘ f) ⁻¹' setOf (Formula.Realize φ)) Tactic: obtain ⟨φ, rfl⟩ := h State Before: case intro
M : Type w
A : Set M
L : Language
inst✝ : Structure L M
α : Type u₁
β : Type u_1
B : Set M
s : Set (α → M)
f : α → β
φ : Formula (L[[↑A]]) α
⊢ Definable A L ((fun g => g ∘ f) ⁻¹' setOf (Formula.Realize φ)) State After: case intro
M : Type w
A : Set M
L : Language
inst✝ : Structure L M
α : Type u₁
β : Type u_1
B : Set M
s : Set (α → M)
f : α → β
φ : Formula (L[[↑A]]) α
⊢ (fun g => g ∘ f) ⁻¹' setOf (Formula.Realize φ) = setOf (Formula.Realize (Formula.relabel f φ)) Tactic: refine' ⟨φ.relabel f, _⟩ State Before: case intro
M : Type w
A : Set M
L : Language
inst✝ : Structure L M
α : Type u₁
β : Type u_1
B : Set M
s : Set (α → M)
f : α → β
φ : Formula (L[[↑A]]) α
⊢ (fun g => g ∘ f) ⁻¹' setOf (Formula.Realize φ) = setOf (Formula.Realize (Formula.relabel f φ)) State After: case intro.h
M : Type w
A : Set M
L : Language
inst✝ : Structure L M
α : Type u₁
β : Type u_1
B : Set M
s : Set (α → M)
f : α → β
φ : Formula (L[[↑A]]) α
x✝ : β → M
⊢ x✝ ∈ (fun g => g ∘ f) ⁻¹' setOf (Formula.Realize φ) ↔ x✝ ∈ setOf (Formula.Realize (Formula.relabel f φ)) Tactic: ext State Before: case intro.h
M : Type w
A : Set M
L : Language
inst✝ : Structure L M
α : Type u₁
β : Type u_1
B : Set M
s : Set (α → M)
f : α → β
φ : Formula (L[[↑A]]) α
x✝ : β → M
⊢ x✝ ∈ (fun g => g ∘ f) ⁻¹' setOf (Formula.Realize φ) ↔ x✝ ∈ setOf (Formula.Realize (Formula.relabel f φ)) State After: no goals Tactic: simp only [Set.preimage_setOf_eq, mem_setOf_eq, Formula.realize_relabel]
|
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 14 15:11:13 2017
@author: Benjamin
"""
import sys
import numpy as np
from copy import deepcopy
def get_contact_bins(device, contacts, interact_mtrx):
"""
Returns the nested list "contact_starter_atom_list".
For each contact, this nested list contains another list of all the
atoms in said contact that are interacting with device atoms.
"""
contact_starter_atom_list = []
for contact in contacts:
contact_edge_list = []
for contact_idx in contact:
for device_idx in device:
if interact_mtrx[contact_idx, device_idx]:
if not contact_idx in contact_edge_list:
contact_edge_list.append(contact_idx)
contact_starter_atom_list.append(np.array(contact_edge_list))
return contact_starter_atom_list
def get_next_bins(curr_bins, prev_bins, interact_mtrx):
"""
List of bins. Each element contains the bins corresponding to a contact.
"""
next_bins = []
num_atoms = np.size(interact_mtrx, axis=0)
atoms = np.array(list(range(num_atoms)))
for curr_bin in curr_bins:
bin_candidates = np.array([])
for atom_idx in curr_bin:
# print(atom_idx)
# print(interact_mtrx[atom_idx, :])
bin_add_candidates = atoms[interact_mtrx[atom_idx, :]]
for prev_bin in prev_bins:
# print("prev_bin" + str(prev_bin))
bin_add_candidates = [x for x in bin_add_candidates if x not in prev_bin]
bin_add_candidates = np.array(bin_add_candidates)
bin_candidates = np.append(bin_candidates, bin_add_candidates)
bin_candidates = [int(x) for x in bin_candidates]
# print("bin_add_candidates" + str(bin_add_candidates))
# print("bin_candidates" + str(bin_candidates))
bin_atoms = np.unique(bin_candidates)
# print("bin_atoms: " + str(bin_atoms))
next_bins.append(bin_atoms)
return next_bins
def bins_are_neighbours(bin1, bin2, interact_mtrx):
"""
Check if bin1 and bin2 contain interacting atoms, or have atoms in common.
"""
max_atom_idx = len(interact_mtrx[:, 0])-1
for atom_idx1 in bin1:
if atom_idx1 > max_atom_idx:
sys.exit("FATAL ERROR: atom_idx out of range!")
continue
for atom_idx2 in bin2:
if atom_idx2 > max_atom_idx:
sys.exit("FATAL ERROR: atom_idx out of range!")
continue
if interact_mtrx[atom_idx1, atom_idx2]:
return True
return False
def get_chain_length(chains, chain_idx, start_gen_idx):
"""
Get length of the chain with index "chain_idx", starting from (and including)
generation "start_gen_idx" to end of chain, or until first
empty bin (while excluding empty bin).
"""
length = 0
for gen_idx, gen in enumerate(chains[start_gen_idx:]):
bn = gen[chain_idx]
if len(bn) == 0:
break
length += 1
# print("\nbn: " + str([x+1 for x in bn]))
return length
def get_dead_ends(chains, final_chain_idxs, gen_idx_of_last_collision):
vrb_local = False
dead_ends = []
dead_end_start_idx = gen_idx_of_last_collision+1
for chain_idx in final_chain_idxs:
if vrb_local: print("chain_idx = " + str(chain_idx))
if vrb_local: print("dead_end_start_idx = " + str(dead_end_start_idx))
length = get_chain_length(chains, chain_idx, dead_end_start_idx)
if vrb_local: print("length = " + str(length))
if length == 0:
dead_ends.append([])
else:
dead_end = []
for gen in chains[dead_end_start_idx:]:
if vrb_local: print("gen: " + str([x+1 for x in gen]))
dead_end.append(gen[chain_idx])
dead_ends.append(deepcopy(dead_end))
return dead_ends
|
# Used for objectives and solvers where the gradient is available/exists
mutable struct OnceDifferentiable{TF, TDF, TX} <: AbstractObjective
f # objective
df # (partial) derivative of objective
fdf # objective and (partial) derivative of objective
F::TF # cache for f output
DF::TDF # cache for df output
x_f::TX # x used to evaluate f (stored in F)
x_df::TX # x used to evaluate df (stored in DF)
f_calls::Vector{Int}
df_calls::Vector{Int}
end
### Only the objective
# Ambiguity
OnceDifferentiable(f, x::AbstractArray,
F::Real = real(zero(eltype(x))),
DF::AbstractArray = alloc_DF(x, F); inplace = true, autodiff = :finite,
chunk::ForwardDiff.Chunk = ForwardDiff.Chunk(x)) =
OnceDifferentiable(f, x, F, DF, autodiff, chunk)
#OnceDifferentiable(f, x::AbstractArray, F::AbstractArray; autodiff = :finite) =
# OnceDifferentiable(f, x::AbstractArray, F::AbstractArray, alloc_DF(x, F))
function OnceDifferentiable(f, x::AbstractArray,
F::AbstractArray, DF::AbstractArray = alloc_DF(x, F);
inplace = true, autodiff = :finite)
f! = f!_from_f(f, F, inplace)
OnceDifferentiable(f!, x::AbstractArray, F::AbstractArray, DF, autodiff)
end
function OnceDifferentiable(f, x_seed::AbstractArray{T},
F::Real,
DF::AbstractArray,
autodiff, chunk) where T
# When here, at the constructor with positional autodiff, it should already
# be the case, that f is inplace.
if typeof(f) <: Union{InplaceObjective, NotInplaceObjective}
fF = make_f(f, x_seed, F)
dfF = make_df(f, x_seed, F)
fdfF = make_fdf(f, x_seed, F)
return OnceDifferentiable(fF, dfF, fdfF, x_seed, F, DF)
else
if is_finitediff(autodiff)
# Figure out which Val-type to use for FiniteDiff based on our
# symbol interface.
fdtype = finitediff_fdtype(autodiff)
df_array_spec = DF
x_array_spec = x_seed
return_spec = typeof(F)
gcache = FiniteDiff.GradientCache(df_array_spec, x_array_spec, fdtype, return_spec)
function g!(storage, x)
FiniteDiff.finite_difference_gradient!(storage, f, x, gcache)
return
end
function fg!(storage, x)
g!(storage, x)
return f(x)
end
elseif is_forwarddiff(autodiff)
gcfg = ForwardDiff.GradientConfig(f, x_seed, chunk)
g! = (out, x) -> ForwardDiff.gradient!(out, f, x, gcfg)
fg! = (out, x) -> begin
gr_res = DiffResults.DiffResult(zero(T), out)
ForwardDiff.gradient!(gr_res, f, x, gcfg)
DiffResults.value(gr_res)
end
else
error("The autodiff value $autodiff is not support. Use :finite or :forward.")
end
return OnceDifferentiable(f, g!, fg!, x_seed, F, DF)
end
end
has_not_dep_symbol_in_ad = Ref{Bool}(true)
OnceDifferentiable(f, x::AbstractArray, F::AbstractArray, autodiff::Symbol, chunk::ForwardDiff.Chunk = ForwardDiff.Chunk(x)) =
OnceDifferentiable(f, x, F, alloc_DF(x, F), autodiff, chunk)
function OnceDifferentiable(f, x::AbstractArray, F::AbstractArray,
autodiff::Bool, chunk::ForwardDiff.Chunk = ForwardDiff.Chunk(x))
if autodiff == false
throw(ErrorException("It is not possible to set the `autodiff` keyword to `false` when constructing a OnceDifferentiable instance from only one function. Pass in the (partial) derivative or specify a valid `autodiff` symbol."))
elseif has_not_dep_symbol_in_ad[]
@warn("Setting the `autodiff` keyword to `true` is deprecated. Please use a valid symbol instead.")
has_not_dep_symbol_in_ad[] = false
end
OnceDifferentiable(f, x, F, alloc_DF(x, F), :forward, chunk)
end
function OnceDifferentiable(f, x_seed::AbstractArray, F::AbstractArray, DF::AbstractArray,
autodiff::Symbol , chunk::ForwardDiff.Chunk = ForwardDiff.Chunk(x_seed))
if typeof(f) <: Union{InplaceObjective, NotInplaceObjective}
fF = make_f(f, x_seed, F)
dfF = make_df(f, x_seed, F)
fdfF = make_fdf(f, x_seed, F)
return OnceDifferentiable(fF, dfF, fdfF, x_seed, F, DF)
else
if is_finitediff(autodiff)
# Figure out which Val-type to use for FiniteDiff based on our
# symbol interface.
fdtype = finitediff_fdtype(autodiff)
# Apparently only the third input is aliased.
j_finitediff_cache = FiniteDiff.JacobianCache(copy(x_seed), copy(F), copy(F), fdtype)
if autodiff == :finiteforward
# These copies can be done away with if we add a keyword for
# reusing arrays instead for overwriting them.
Fx = copy(F)
DF = copy(DF)
x_f, x_df = x_of_nans(x_seed), x_of_nans(x_seed)
f_calls, j_calls = [0,], [0,]
function j_finiteforward!(J, x)
# Exploit the possibility that it might be that x_f == x
# then we don't have to call f again.
# if at least one element of x_f is different from x, update
if any(x_f .!= x)
f(Fx, x)
f_calls .+= 1
end
FiniteDiff.finite_difference_jacobian!(J, f, x, j_finitediff_cache, Fx)
end
function fj_finiteforward!(F, J, x)
f(F, x)
FiniteDiff.finite_difference_jacobian!(J, f, x, j_finitediff_cache, F)
end
return OnceDifferentiable(f, j_finiteforward!, fj_finiteforward!, Fx, DF, x_f, x_df, f_calls, j_calls)
end
function fj_finitediff!(F, J, x)
f(F, x)
FiniteDiff.finite_difference_jacobian!(J, f, x, j_finitediff_cache)
F
end
function j_finitediff!(J, x)
F_cache = copy(F)
fj_finitediff!(F_cache, J, x)
end
return OnceDifferentiable(f, j_finitediff!, fj_finitediff!, x_seed, F, DF)
elseif is_forwarddiff(autodiff)
jac_cfg = ForwardDiff.JacobianConfig(f, F, x_seed, chunk)
ForwardDiff.checktag(jac_cfg, f, x_seed)
F2 = copy(F)
function j_forwarddiff!(J, x)
ForwardDiff.jacobian!(J, f, F2, x, jac_cfg, Val{false}())
end
function fj_forwarddiff!(F, J, x)
jac_res = DiffResults.DiffResult(F, J)
ForwardDiff.jacobian!(jac_res, f, F2, x, jac_cfg, Val{false}())
DiffResults.value(jac_res)
end
return OnceDifferentiable(f, j_forwarddiff!, fj_forwarddiff!, x_seed, F, DF)
else
error("The autodiff value $(autodiff) is not supported. Use :finite or :forward.")
end
end
end
### Objective and derivative
function OnceDifferentiable(f, df,
x::AbstractArray,
F::Real = real(zero(eltype(x))),
DF::AbstractArray = alloc_DF(x, F);
inplace = true)
df! = df!_from_df(df, F, inplace)
fdf! = make_fdf(x, F, f, df!)
OnceDifferentiable(f, df!, fdf!, x, F, DF)
end
function OnceDifferentiable(f, j,
x::AbstractArray,
F::AbstractArray,
J::AbstractArray = alloc_DF(x, F);
inplace = true)
f! = f!_from_f(f, F, inplace)
j! = df!_from_df(j, F, inplace)
fj! = make_fdf(x, F, f!, j!)
OnceDifferentiable(f!, j!, fj!, x, F, J)
end
### Objective, derivative and combination
function OnceDifferentiable(f, df, fdf,
x::AbstractArray,
F::Real = real(zero(eltype(x))),
DF::AbstractArray = alloc_DF(x, F);
inplace = true)
# f is never "inplace" since F is scalar
df! = df!_from_df(df, F, inplace)
fdf! = fdf!_from_fdf(fdf, F, inplace)
x_f, x_df = x_of_nans(x), x_of_nans(x)
OnceDifferentiable{typeof(F),typeof(DF),typeof(x)}(f, df!, fdf!,
copy(F), copy(DF),
x_f, x_df,
[0,], [0,])
end
function OnceDifferentiable(f, df, fdf,
x::AbstractArray,
F::AbstractArray,
DF::AbstractArray = alloc_DF(x, F);
inplace = true)
f = f!_from_f(f, F, inplace)
df! = df!_from_df(df, F, inplace)
fdf! = fdf!_from_fdf(fdf, F, inplace)
x_f, x_df = x_of_nans(x), x_of_nans(x)
OnceDifferentiable(f, df!, fdf!, copy(F), copy(DF), x_f, x_df, [0,], [0,])
end
|
Christy Marsden
Basics
I finished my Masters in Horticulture and Agronomy in 2011.
I graduated in June 2008 with a BS in Human Development, minor in Environmental Horticulture from UC Davis.
I currently live in Decorah, Iowa and work at Seed Savers Exchange. Decorah could use a wiki.
Past Work
I worked as a plant technician for the National Clonal Germplasm Repository with the USDAARS, which included frequent trips to the elusive Wolfskill Experimental Orchard Wolfskill in Winters.
During the summer, I split my time between the Repository and a plant pathology lab on campus working with Agrobacterium tumefaciens.
I drove buses for Unitrans, and was the Human Resources Manager from 20072008.
During graduate school, I was a TA for various horticulture courses. My favorite part of grad school by far.
Extras
I Davis Knit Night knit. A lot.
I enjoy playing Kubb.
I like plants.
I was the 100th member of DavisWiki, and because I love the wiki I have a weirdly vast knowledge of Davis.
Oh, Davis
I really liked Davis in the summer when the city seems to relax for a few months.
Davis Noodle City was my favorite place to eat. Taste of Thai was a close second.
Woodstocks Pizza Woodstocks is an excellent place to drink beer. And Sophias for everything else (drink wise, not food wise). de Veres Irish Pub de Veres will be when the crowds die down.
Leftovers
I was a member of Prytanean Womens Honor Society Prytanean.
I was in Integrated Studies.
I worked as a CASA.
I volunteered for four years in the Arboretum.
Hopes and Dreams
Fall in love.
Find a happy place to be.
I like to think Im a good person to know. But hey, I hardly know myself, so who knows?
20060417 21:54:36 nbsp Hey, cool. Users/CarlosOverstreet
20060502 23:25:06 nbsp Im in that Anthro class too! Users/JosephBleckman
20060724 18:42:07 nbsp PAs kick ass! Users/TracyPerkins
20060726 13:55:04 nbsp Hey there! Yeah it wasnt so much that John was conservative as he was kind of an asshole about it. Like I know so much more than you and whatever you have to say Im going to argue with just for the hell of it. Yeah but anyways... we should play more IM sports in the fall and winter! Users/AngelaPourtabib
20060728 08:22:55 nbsp Hey Christy! Do you think Friends of the Arboretum would be willing to donate one of their very cool plants for the wiki fundraiser? Im thinking you might have a contact. Users/AlphaDog
20060811 12:11:32 nbsp Nice page Christy! Users/VinceBuffalo
20060811 12:13:41 nbsp Oh and thanks for the edit! and check out my new project http://coursecollab.org ! Users/VinceBuffalo
20060820 20:18:03 nbsp I see that you have Watch every Star Wars movie listed. I dont have episodes IIII, but I have the original trilogy if you want to watch them sometime. Users/TracyPerkins
20061115 23:05:44 nbsp I mostly dont get any trouble from Unitrans drivers about the RT sticker, but that would still be helpful. Thanks. Users/NickSchmalenberger
20061120 05:32:27 nbsp Lulz, Thanks Christy! I know a lot of ppl get those, but you wouldnt believe how much spam i get back from sending them ;) Users/MaxMikalonis
20070515 11:43:33 nbsp Thank you for your positive feed back on 3rd street jeweler. it was a pleasure. Frank A. Users/3rdstreetjeweler
20070607 23:54:49 nbsp Yo yo you volunteer at CASA? Good work man... Users/AngelaPourtabib
20070724 12:13:17 nbsp Yeah, I noticed Prytanean when I was reading through the California Aggie through the 1950s and 60s. Its been in Davis longer than most of the fraternities, even, so Id love to see what kind of history you have. Users/BrentLaabs
20080621 19:59:45 nbsp I finally got my ass in gear and made a Davis Wiki account...and the first Random Page to pop up on the home page is none other than...ChristyMarsden. What are the odds? Users/TimFrazee
20080917 11:23:57 nbsp I love the Wiki and I love that youre on it! Users/AynReyes
20081219 19:31:52 nbsp Ive never heard people call baby grasses cute. Do you pat them too? Users/glyster
20090602 02:56:36 nbsp Hey, thanks for making the page! Im more of a sewing guy myself, but us strings and needles folk need to stick together. :) Users/JabberWokky
20090602 22:12:00 nbsp thanks for your comments on the growlers hop plot. I do plan to continue to update the hole process... pest management, harvesting, processing the hops, and then brewing a batch of beer with the hops. If you ever want a tour I am happy to provide, I am often down at the garden on the weekends or some weeknights. Are you a brewer? Users/matiasek
20100207 18:48:24 nbsp Agreed! Lets hope they go scurrying back to SoCal with their tail between their legs. Users/CovertProfessor
20100215 16:19:08 nbsp hey are you looking to move out of your apt this year? i am willing to pay $ for the lease pass down Users/meghanolmstead
20100310 11:26:58 nbsp That iPod thing is pretty crazy. Keep us updated! And if you want any help looking into it Id be happy to make some calls or whatever as well (nothing better to do at the moment). Users/TomGarberson
20100310 16:37:26 nbsp Wooo IS! And wow, thats pretty crazy. Thanks for the update, good to know how that works. And, if the ARC knows about it, its incredibly shady of them to keep doing it. Users/TomGarberson
20100311 08:51:41 nbsp I assume this is the UCDPD, not the DPD? My suggestion would be to drop by the Aggie office and find an enterprising journalist who wants to do some investigation for what could be a really quality article, and let them know the details of what youve learned. If theres any sort of a pattern here, thats a BIG dealwhether its the PD or the ARC responsible. Its possible the Enterprise would be interested as well... while its a pretty universitycentric thing, its definitely a story. Users/TomGarberson
20100311 08:52:35 nbsp Dang. I was hoping the best for you. Users/JabberWokky
20100311 08:57:27 nbsp Its funny... if a private citizen did what the police did, it would be wiki:wikipedia:Conversion (law) conversion. But since theyre the police, they can do what they did, even though there is no compelling reason for them to have the special ability to auction property that doesnt belong to them, especially when an iPod has identifying information on it, be it in software or the optional engraving on it. Users/WilliamLewis
I dont know that they necessarily can (I also dont know that they cant). People are just far less likely to challenge them on it. Its pretty common for PDs to just do whats convenient for them until they get a reason not to (i.e. a lawsuit or threat of a lawsuit). The same is true of businesses and pretty much everyone else, they just get called on it far more often, so they learn better. Users/TomGarberson
20100328 18:54:23 nbsp I just read your posts about your lost ipod. You should call the school paper. Thats a pretty dang good story and an issue that obviously needs attention. Users/gkrisser
20100907 10:40:20 nbsp coot puppy!
If you want to be a runner, jog in the arbo its looong
How is the plant path coming along? Users/StevenDaubert
20100910 00:34:57 nbsp Sweet, Yeah pops works in George Bruenings lab... How many career hours did you have with unitrans? Users/StevenDaubert
20100914 00:55:41 nbsp Daaamn above 3k niiice
When I was little I would take a bluebird P/G to West D for occupational therapy, this is long time ago Users/StevenDaubert
20101011 21:34:31 nbsp Wow, thanks for the info on The Dumpling House! Thats amazing news, Im going to have to take advantage. Dont hesitate to edit the main text of a page, especially with awesome stuff like thatits definitely noteworthy! I went ahead and noted it up at the top. Users/TomGarberson
20101011 22:54:38 nbsp Blerg... Honestly, just about everyone I know whos been to Bistro more than once or twice has had bad experiences there. For some reason, though, they keep going back. I prefer to give businesses feedback in the form of money. If I like them, I support them. If they give me horrible service and then treat me like Im trying to rip them off when I tell a manager about it, I stop supporting them. Im always surprised when I see it crowded (which it usually is). Users/TomGarberson
20101011 23:52:51 nbsp More pages are good pages! Just make sure you tie them into the wiki. If they dont link to anything, theyre essentially dead ends. If nothing links to them, theyre impossible to find except on Recent Changes or via a direct search. If you need help with anything, just drop it on a page or in an edit note and someones sure to swing by. Users/TomGarberson
20101014 18:35:02 nbsp Thanks! When I read his comment, first I did one of those O.o things, then I cracked up. Users/TomGarberson
20101021 23:24:13 nbsp Nice! Ive got a good friend recently out of the entomology masters program working as a PCA down in Watsonville. He loves the work, hours of the summer were brutal, though. Congrats on your success in the running department! Users/TomGarberson
20101101 16:23:49 nbsp Ew... I would have preferred it to be sap rather than poo... Unfortunately I live in an apartment complex so I really have no control over what I can do to the tree unless I take it up with the property manager I guess. Users/hankim
20101207 19:02:17 nbsp The qualifying phrase at least as Davisites go is important. Im not sure what Dunnings standards are, but I think its at least 20 years. :) Users/CovertProfessor
20101207 23:27:02 nbsp The ARC in my opinion mismanages itself or is overrun with corruption when compared to all the other gyms I have been to and I am pretty sure the university does not have a contractor running the place (so it is run by university people). Not that I have faith that the university will make a deal that benefits students if they ever did get a contractor to run the place (look at Sodexo). Here is a small slice of all the problems I have with the ARC: http://ucdbs.com/?page_id12 Users/hankim
20101208 10:31:35 nbsp Ah ha! I have discovered you are not Jewish! Of course, neither am I... I forgot it was Hanukkah until I was flipping through my Old Farmers Almanac this morning. The holiday only lasts for another day, but I figured Id toss up a nice logo to recognize the folks in Davis who are celebrating the holiday. Bashfully, I must admit I have forgotten both it and Ramadan in the past through simple ignorance, but Im generally try to catch as many holidays as possible that are commonly celebrated in Davis (thus the Picnic Day logos, etc). Anybody can contribute a logo at Wiki Logo... nobody has made one for Christmas or New Years yet! Pi Day and March 28th would be other neat ones to have (March 28th being the day Davis was incorporated). Users/JabberWokky
20101208 22:19:30 nbsp Ah, but you never know. Maybe you will get a PhD here, or postdoc... or... or...? Users/CovertProfessor
20110121 21:15:55 nbsp Since you work at Wolfskill, would you mind taking some pictures? The picture we have on there right now isnt licensed for people to use freely and we really could use some more, anyway! Users/WilliamLewis
20110121 23:16:25 nbsp Haha, actually, unfortunately (very much so), Dr. Jones isnt my dentist. I spent a lot of time trying to figure out a way to get him, because his reviews are so uniformly exemplary, but my strange insurance situation meant no PPOs for me. However, when my Users/kingjesse2 housemate (who does have a PPO) asked me if I knew any good dentists, there was really no hesitation involved. Users/JoePomidor
20110123 01:51:53 nbsp Wow, Im always amazed by the coincidences that seem to crop up. For instance, another one of my housemates mother just happen to work with my father...in Livermore. We found this out after becoming housemates. Users/JoePomidor
20110226 17:02:16 nbsp Coco and her companions have been reunited. Users/PaulThober
20110315 11:23:33 nbsp No worries! Thanks! Users/WilliamLewis
20110315 13:43:53 nbsp Sent you an email with permissions. I hope thats what you were looking for! Users/GregHirson
20110509 21:14:36 nbsp No problem, thanks for putting the event on the board! Users/TomGarberson
20110512 19:42:35 nbsp It was a blast! Pretty good turnout, lots of fun with the live Karaoke. The staff at the Grad seemed really into it, they were really engaging. Definitely a success. Users/TomGarberson
20111007 15:38:02 nbsp Im not heading up Occupy Davis. Im just pointing people in the right direction :)
It seems like someone has got some facebook stuff happening. Im not on facebook though, so I thought Id help out however I can.
Ill be there tonight though, maybe Ill see ya there.
Users/ConsciousConsumer
20111008 16:18:44 nbsp Thanks. I wasnt aware of the activity on the bikepedestrian bridge. The top 1% will surely quickly make things equitable now that the issue has been called to their attention, so there wont be any need to say anything from the bridges ha. Users/BruceHansen
20111104 19:25:49 nbsp Ah, I didnt realize it was on the page twice! I restored your edit. I thought it was funny you dont seem like the type to go around deleting history. I should have known! Users/CovertProfessor
20111128 17:17:40 nbsp Leaving Davis is sad :( Congrats on landing a job, though. Thats always something to be thankful for. I hope Decorah is good to you! Users/TomGarberson
|
/* permutation/gsl_permutation.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2004, 2007 Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_PERMUTATION_H__
#define __GSL_PERMUTATION_H__
#include <stdlib.h>
#include <gsl/gsl_types.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_inline.h>
#include <gsl/gsl_check_range.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
struct gsl_permutation_struct
{
size_t size;
size_t *data;
};
typedef struct gsl_permutation_struct gsl_permutation;
gsl_permutation *gsl_permutation_alloc (const size_t n);
gsl_permutation *gsl_permutation_calloc (const size_t n);
void gsl_permutation_init (gsl_permutation * p);
void gsl_permutation_free (gsl_permutation * p);
int gsl_permutation_memcpy (gsl_permutation * dest, const gsl_permutation * src);
int gsl_permutation_fread (FILE * stream, gsl_permutation * p);
int gsl_permutation_fwrite (FILE * stream, const gsl_permutation * p);
int gsl_permutation_fscanf (FILE * stream, gsl_permutation * p);
int gsl_permutation_fprintf (FILE * stream, const gsl_permutation * p, const char *format);
size_t gsl_permutation_size (const gsl_permutation * p);
size_t * gsl_permutation_data (const gsl_permutation * p);
int gsl_permutation_swap (gsl_permutation * p, const size_t i, const size_t j);
int gsl_permutation_valid (const gsl_permutation * p);
void gsl_permutation_reverse (gsl_permutation * p);
int gsl_permutation_inverse (gsl_permutation * inv, const gsl_permutation * p);
int gsl_permutation_next (gsl_permutation * p);
int gsl_permutation_prev (gsl_permutation * p);
int gsl_permutation_mul (gsl_permutation * p, const gsl_permutation * pa, const gsl_permutation * pb);
int gsl_permutation_linear_to_canonical (gsl_permutation * q, const gsl_permutation * p);
int gsl_permutation_canonical_to_linear (gsl_permutation * p, const gsl_permutation * q);
size_t gsl_permutation_inversions (const gsl_permutation * p);
size_t gsl_permutation_linear_cycles (const gsl_permutation * p);
size_t gsl_permutation_canonical_cycles (const gsl_permutation * q);
INLINE_DECL size_t gsl_permutation_get (const gsl_permutation * p, const size_t i);
#ifdef HAVE_INLINE
INLINE_FUN
size_t
gsl_permutation_get (const gsl_permutation * p, const size_t i)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(i >= p->size))
{
GSL_ERROR_VAL ("index out of range", GSL_EINVAL, 0);
}
#endif
return p->data[i];
}
#endif /* HAVE_INLINE */
__END_DECLS
#endif /* __GSL_PERMUTATION_H__ */
|
[STATEMENT]
lemma "all_security_requirements_fulfilled invariants policy"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. TopoS_Composition_Theory_impl.all_security_requirements_fulfilled invariants policy
[PROOF STEP]
by eval
|
#pragma once
#include <boost/beast/core.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/asio/strand.hpp>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <memory>
#include <string>
#include "session.hpp"
namespace beast_machine
{
namespace server
{
namespace beast = boost::beast; // from <boost/beast.hpp>
namespace http = beast::http; // from <boost/beast/http.hpp>
namespace websocket = beast::websocket; // from <boost/beast/websocket.hpp>
namespace net = boost::asio; // from <boost/asio.hpp>
using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp>
//------------------------------------------------------------------------------
// Echoes back all received WebSocket messages
template<class T, class FailSync>
class session : public std::enable_shared_from_this<session<T, FailSync>>, public T
{
websocket::stream<beast::tcp_stream> ws_;
beast::flat_buffer buffer_;
std::shared_ptr<FailSync> fail_sync;
public:
// Take ownership of the socket
explicit session(tcp::socket&& socket, std::shared_ptr<FailSync>& fs)
: ws_(std::move(socket))
, fail_sync(fs)
{
}
// Start the asynchronous operation
void run()
{
// Set suggested timeout settings for the websocket
ws_.set_option(websocket::stream_base::timeout::suggested(beast::role_type::server));
// Set a decorator to change the Server of the handshake
ws_.set_option(websocket::stream_base::decorator([](websocket::response_type& res) {
res.set(http::field::server, std::string(BOOST_BEAST_VERSION_STRING) + " websocket-server-async");
}));
// Accept the websocket handshake
ws_.async_accept(beast::bind_front_handler(&session::on_accept, session<T, FailSync>::shared_from_this()));
}
void process_message(size_t bytes)
{
callback_return ret = T::callback(buffer_, bytes, ws_.is_message_done());
buffer_.consume(buffer_.size());
try
{
switch (std::get<0>(ret))
{
case callback_result::read:
// Read a message into our buffer
do_read();
return;
case callback_result::need_more_reading:
// Read a message into our buffer
do_read_blob();
return;
case callback_result::need_more_writing:
// Send the message
ws_.async_write_some(false, net::buffer(std::get<1>(ret)),
beast::bind_front_handler(&session::on_write_contunue,
session<T, FailSync>::shared_from_this()));
return;
case callback_result::write_complete:
// Send the message
ws_.async_write_some(
true, net::buffer(std::get<1>(ret)),
beast::bind_front_handler(&session::on_write, session<T, FailSync>::shared_from_this()));
return;
case callback_result::write_complete_async_read:
// Send the message
ws_.async_write_some(true, net::buffer(std::get<1>(ret)),
beast::bind_front_handler(&session::on_write_complete_async_read,
session<T, FailSync>::shared_from_this()));
return;
case callback_result::close:
break;
default:
throw std::logic_error("unexpected switch state");
break;
}
}
catch (std::logic_error ex)
{
return fail(make_error_code(errc::unrecognised_state), ex.what());
}
catch (std::exception& ex)
{
return fail(make_error_code(errc::unexpected_exception), ex.what());
}
// Close the WebSocket connection
ws_.async_close(websocket::close_code::normal,
beast::bind_front_handler(&session::on_close, session<T, FailSync>::shared_from_this()));
}
void on_accept(beast::error_code ec)
{
if (ec)
return fail(ec, "accept");
// tell the business logic we have accepted a connection request
process_message(0);
}
void do_read()
{
// Read a message into our buffer
ws_.async_read(buffer_,
beast::bind_front_handler(&session::on_read, session<T, FailSync>::shared_from_this()));
}
void do_read_blob()
{
// Read a message into our buffer
ws_.async_read_some(buffer_, buffer_.capacity(),
beast::bind_front_handler(&session::on_read, session<T, FailSync>::shared_from_this()));
}
void on_read(beast::error_code ec, std::size_t bytes_transferred)
{
boost::ignore_unused(bytes_transferred);
// This indicates that the session was closed
if (ec == websocket::error::closed)
return;
if (ec)
fail(ec, "read");
process_message(bytes_transferred);
}
void on_write(beast::error_code ec, std::size_t bytes_transferred)
{
boost::ignore_unused(bytes_transferred);
if (ec)
return fail(ec, "write");
// Read a message into our buffer
do_read();
}
void on_write_complete_async_read(beast::error_code ec, std::size_t bytes_transferred)
{
boost::ignore_unused(bytes_transferred);
if (ec)
return fail(ec, "write");
// Read a message into our buffer
do_read_blob();
}
void on_write_contunue(beast::error_code ec, std::size_t bytes_transferred)
{
boost::ignore_unused(bytes_transferred);
if (ec)
return fail(ec, "write");
process_message(0);
}
void on_close(beast::error_code ec)
{
if (ec)
return fail(ec, "close");
}
private:
template<class err_code> void fail(err_code ec, char const* what) { (*fail_sync)(ec, what); }
};
//------------------------------------------------------------------------------
// Accepts incoming connections and launches the sessions
template<class T, class FailSync> class listener : public std::enable_shared_from_this<listener<T, FailSync>>
{
net::io_context& ioc_;
tcp::acceptor acceptor_;
bool single_request_;
std::shared_ptr<FailSync> fail_sync;
public:
listener(net::io_context& ioc, tcp::endpoint endpoint, bool single_request, std::shared_ptr<FailSync>& fs)
: ioc_(ioc)
, acceptor_(ioc)
, single_request_(single_request)
, fail_sync(fs)
{
beast::error_code ec;
// Open the acceptor
acceptor_.open(endpoint.protocol(), ec);
if (ec)
{
fail(ec, "open");
return;
}
// Allow address reuse
acceptor_.set_option(net::socket_base::reuse_address(true), ec);
if (ec)
{
fail(ec, "set_option");
return;
}
// Bind to the server address
acceptor_.bind(endpoint, ec);
if (ec)
{
fail(ec, "bind");
return;
}
// Start listening for connections
acceptor_.listen(net::socket_base::max_listen_connections, ec);
if (ec)
{
fail(ec, "listen");
return;
}
}
// Start accepting incoming connections
void run() { do_accept(); }
private:
void do_accept()
{
// The new connection gets its own strand
acceptor_.async_accept(
net::make_strand(ioc_),
beast::bind_front_handler(&listener::on_accept, listener<T, FailSync>::shared_from_this()));
}
void on_accept(beast::error_code ec, tcp::socket socket)
{
if (ec)
{
fail(ec, "accept");
}
else
{
// Create the session and run it
std::make_shared<session<T, FailSync>>(std::move(socket), fail_sync)->run();
}
// Accept another connection
if (!single_request_)
{
do_accept();
}
}
template<class err_code> void fail(err_code ec, char const* what) { (*fail_sync)(ec, what); }
};
} // namespace server
struct errc_category : std::error_category
{
const char* name() const noexcept override;
std::string message(int ev) const override;
};
const char* errc_category::name() const noexcept { return "websocket_server"; }
std::string errc_category::message(int ev) const
{
switch (static_cast<errc>(ev))
{
case errc::unrecognised_state:
return "unrecognised state";
case errc::unexpected_exception:
return "unexpected exception";
default:
return "(unrecognized error)";
}
}
const errc_category the_category {};
std::error_code make_error_code(beast_machine::errc e) { return {static_cast<int>(e), beast_machine::the_category}; }
} // namespace beast_machine
|
State Before: α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
σ : Perm α
s : Finset (Perm α)
h1 : ∀ (f : Perm α), f ∈ s → IsCycle f
h2 : Set.Pairwise (↑s) Disjoint
h0 : Finset.noncommProd s id (_ : Set.Pairwise ↑s fun a b => Commute (id a) (id b)) = σ
⊢ cycleType σ = map (Finset.card ∘ support) s.val State After: α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
σ : Perm α
s : Finset (Perm α)
h1 : ∀ (f : Perm α), f ∈ s → IsCycle f
h2 : Set.Pairwise (↑s) Disjoint
h0 : Finset.noncommProd s id (_ : Set.Pairwise ↑s fun a b => Commute (id a) (id b)) = σ
⊢ map (Finset.card ∘ support) (cycleFactorsFinset σ).val = map (Finset.card ∘ support) s.val Tactic: rw [cycleType_def] State Before: α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
σ : Perm α
s : Finset (Perm α)
h1 : ∀ (f : Perm α), f ∈ s → IsCycle f
h2 : Set.Pairwise (↑s) Disjoint
h0 : Finset.noncommProd s id (_ : Set.Pairwise ↑s fun a b => Commute (id a) (id b)) = σ
⊢ map (Finset.card ∘ support) (cycleFactorsFinset σ).val = map (Finset.card ∘ support) s.val State After: case e_s.e_self
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
σ : Perm α
s : Finset (Perm α)
h1 : ∀ (f : Perm α), f ∈ s → IsCycle f
h2 : Set.Pairwise (↑s) Disjoint
h0 : Finset.noncommProd s id (_ : Set.Pairwise ↑s fun a b => Commute (id a) (id b)) = σ
⊢ cycleFactorsFinset σ = s Tactic: congr State Before: case e_s.e_self
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
σ : Perm α
s : Finset (Perm α)
h1 : ∀ (f : Perm α), f ∈ s → IsCycle f
h2 : Set.Pairwise (↑s) Disjoint
h0 : Finset.noncommProd s id (_ : Set.Pairwise ↑s fun a b => Commute (id a) (id b)) = σ
⊢ cycleFactorsFinset σ = s State After: case e_s.e_self
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
σ : Perm α
s : Finset (Perm α)
h1 : ∀ (f : Perm α), f ∈ s → IsCycle f
h2 : Set.Pairwise (↑s) Disjoint
h0 : Finset.noncommProd s id (_ : Set.Pairwise ↑s fun a b => Commute (id a) (id b)) = σ
⊢ (∀ (f : Perm α), f ∈ s → IsCycle f) ∧
∃ h, Finset.noncommProd s id (_ : Set.Pairwise ↑s fun a b => Commute (id a) (id b)) = σ Tactic: rw [cycleFactorsFinset_eq_finset] State Before: case e_s.e_self
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
σ : Perm α
s : Finset (Perm α)
h1 : ∀ (f : Perm α), f ∈ s → IsCycle f
h2 : Set.Pairwise (↑s) Disjoint
h0 : Finset.noncommProd s id (_ : Set.Pairwise ↑s fun a b => Commute (id a) (id b)) = σ
⊢ (∀ (f : Perm α), f ∈ s → IsCycle f) ∧
∃ h, Finset.noncommProd s id (_ : Set.Pairwise ↑s fun a b => Commute (id a) (id b)) = σ State After: no goals Tactic: exact ⟨h1, h2, h0⟩
|
(**
「Coq/SSReflect/MathCompによる定理証明」第5章で導入された公理について
========================
@suharahiromichi
2020/12/26
*)
(**
# はじめに
文献 [1.] (以下、テキストと呼びます)の第5章では集合形式化について説明されています。
そこでは、ふたつの公理が導入されています。
5章の冒頭に記載されているとおり、形式化の方法は一通りではないため、
別な公理や公理を導入しないで済ますことができないか、考えてたいと思います。
*)
From mathcomp Require Import all_ssreflect.
Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.
Set Print All.
(**
# 集合の形式化(復習)
型 M の要素である元 x が、型Mの要素全体を母集合とする集合 A に属することを、
M型を引数とする命題型P (すなわち M -> Prop) の型をもつ命題によってあらわす
(テキストのことばでいうと「形式化」することにします。
なお、型Mは任意な型とします。あとで制限することになるので、注意しておいてください。
*)
Definition mySet (M : Type) := M -> Prop.
Definition belong {M : Type} (A : mySet M) (x : M) : Prop := A x.
Notation "x ∈ A" := (belong A x) (at level 11).
Definition myEmptySet {M : Type} : mySet M := fun (_ : M) => False.
Definition myMotherSet {M : Type} : mySet M := fun (_ : M) => True.
Definition mySub {M : Type} := fun (A B : mySet M) => forall (x : M), x ∈ A -> x ∈ B.
Notation "A ⊂ B" := (mySub A B) (at level 11).
Definition eqmySet {M : Type} (A B : mySet M) := (A ⊂ B) /\ (B ⊂ A).
Definition myComplement {M : Type} (A : mySet M) : mySet M := fun (x : M) => ~(A x).
Notation "A ^c" := (myComplement A) (at level 11).
Definition myCup {M : Type} (A B : mySet M) : mySet M := fun (x : M) => x ∈ A \/ x ∈ B.
Notation "A ∪ B" := (myCup A B) (at level 11).
(**
# CSMの第5章の公理
上記の集合の形式化の定義には問題がふたつあります。(要補足)
- 元xが集合Aに含まれることは言えても、含まれないと言えるとは限らない。
これは、Coqが採用する直観主義論理の立場から、命題が証明できればそれが真だといえます。
しかし、命題が証明できないと言い切ることができない(場合がある)ため、
偽であるとの証明ができない(できるとは限らない)からです。
- 集合AがBに含まれ、かつ、BがAに含まれることから、集合AとBが等しいことを証明できない。
これは、Coqの等号``=``は、ライプニッツの等式といって、
その型の(Inductiveな)定義に遡って「同じに見える」場合に限り成立します。
例 ``1 + 1 = 2`` は、``S (S O) = S (S O)``
この場合、集合AとBが等しいこと ``(A ⊂ B) /\ (B ⊂ A)``
は集合の帰納的な定義に基づくものでないため ``A = B`` というこができません。
結果として、テキストの本文にあるように、
「補集合の補集合がもとの集合になること」の証明ができません。
テキストではふたつの公理を導入することで解決しています。
ここでは、それぞれを「公理 1」「公理 2」と呼ぶことにします。
*)
(**
## (公理 1.) axiom_mySet
テキストの第5章に沿って、
「元xが集合Aに含まれるか、含まれないかのどちらかである」を公理として導入します。
*)
Axiom axiom_mySet : forall (M : Type) (A : mySet M), forall (x : M), x ∈ A \/ ~(x ∈ A).
(**
## (公理 2.) axiom_ExteqmySet
テキストの第5章に沿って、集合AとBが等しいことを、
集合AがBに含まれ、かつ、BがAに含まれることとして定義します。
*)
Axiom axiom_ExteqmySet : forall {M : Type} (A B : mySet M), eqmySet A B -> A = B.
(**
## 補集合の補集合の証明
*)
Section Test1.
Variable M : Type. (* 注意してください。 *)
Lemma cc_cancel (A : mySet M) : (A^c)^c = A.
Proof.
apply: axiom_ExteqmySet.
split; rewrite /myComplement => x H;
by case: (axiom_mySet A x) => HxA.
Qed.
Lemma myUnionCompMother (A : mySet M) : A ∪ (A^c) = myMotherSet.
Proof.
apply: axiom_ExteqmySet.
split=> [x | x H] //=.
case: (axiom_mySet A x); by [left | right].
Qed.
End Test1.
(**
# (公理 1.)について
## 排中律
(公理 1.)は排中律を使えば証明できます。
*)
Section ExMid.
Variable M : Type. (* 注意してください。 *)
Axiom ExMid : forall (P : Prop), P \/ ~ P. (* 排中律 *)
Lemma axiom_mySet'' : forall (A : mySet M),
forall (x : M), x ∈ A \/ ~(x ∈ A).
Proof.
move=> A x.
by apply: ExMid.
Qed.
End ExMid.
(*
## morita_hmさんの公理 ``refl_mySet``
ProofCafe において @morita_hm さんから別の公理が提案されました。より単純な、
``reflect (A x) true``
から、(公理 1.)を導くものです。
*)
Section Morita.
Variable M : Type. (* 注意してください。 *)
Axiom refl_mySet : forall (A : mySet M) (x : M), reflect (A x) true.
Lemma axiom_mySet' : forall (A : mySet M),
forall (x : M), x ∈ A \/ ~(x ∈ A).
Proof.
rewrite /belong => A x.
by case: (refl_mySet A x); [left | right].
Undo.
move: (@refl_mySet A x) => Hr. (* ここで refl_mySet に M A x を与えている。 *)
case: Hr.
- by left.
- by right.
Qed.
(**
ここで実際に証明しているのは、次の命題であることが解ります。
*)
Goal forall (A : mySet M) (x : M),
reflect (A x) true -> x ∈ A \/ ~(x ∈ A).
Proof.
move=> A x.
by case; [left | right].
Qed.
End Morita.
(**
## 別の説明
公理 ``refl_mySet`` は、かたちを変えた排中律であり、
排中律を経由して(公理 1.)を証明していることになります。これを以下で説明します。
*)
(**
文献[2.] p.101 にあるとおり、``reflect P b`` は、
- 命題(Prop型の) P がTrueであると証明できるとき、 bool型の命題が真(true)である。
- 命題(Prop型の) P がFalseであると証明できるとき、bool型の命題が偽(false)である。
と場合分けできることを示します。
*)
Section Test2.
Lemma A_ref (P : Prop) : P -> reflect P true.
Proof.
move=> H.
by apply: ReflectT.
Qed.
Lemma notA_ref (P : Prop) : ~ P -> reflect P false.
Proof.
move=> H.
by apply: ReflectF.
Qed.
(**
場合分けができ、また、bool型の命題 true が false であるとは、false のことですから、
``reflect P true`` から排中律を導くことができます。
*)
Lemma refl_exmid (P : Prop): reflect P true -> P \/ ~ P.
Proof.
case=> Hr.
- by left.
- by right.
Qed.
End Test2.
(**
## 依存和の使用
かたちを変えた排中律としては、依存和があります。
命題 P が P または ~ P のどちらかに決定可能である、
ということから排中律が求められます。
*)
Section Depend.
Lemma dec_exmid (P : Prop) : {P} + {~ P} -> P \/ ~ P.
Proof.
case=> Hd.
- by left.
- by right.
Qed.
End Depend.
(**
## finType の場合
テキストの 5.5節にあるように、
母集合にあたる型 M を任意の型から、有限型 (finType) に制限することでも、
(公理 1.)を不要にすることもできます。
*)
Section FinType.
Variable M : finType. (* これまでは ``M : Type`` だった。 *)
(**
なぜなら、有限型(母集合が有限)ならば、元が集合に含まれるかどうかを決定する命題を
定義することができるからです。
このような命題はbool型の値をとるようにすると扱いやすいので、pA であらわします。
そして、bool述語 pA が x で成り立つときことを
MathCompの演算子 \in を使って ``x \in pA`` とあらわします。
- pA は ``pred M`` 型となっていますが、これは ``M -> bool`` のことです(深い意味は無い)。
- ``x \in pA`` を ``pA x`` に置き換えても(ここでは)同じです。
ただし、単純な構文糖衣ではないので、つねに同じであるわけではありません。
以下の説明も参照してください。
https://github.com/suharahiromichi/coq/blob/master/csm/csm_4_1_ssrbool.v
*)
(**
``pA : pred M`` が ``P : mySet M`` で形式化された集合の定で使えるように、
変換する関数 p2S を定義します。
なお、テキストで定義されている構文糖衣 ``\{ x 'in' pA \}`` は使わないことにしました。
すなわち `` \{ x in M \}`` は ``p2S M`` のことで x に意味はありません。
*)
Definition p2S (pA : pred M) : mySet M :=
fun (x : M) => if x \in pA then True else False.
Lemma Mother_predT : myMotherSet = p2S M.
Proof. by []. Qed.
Lemma myFinBelongP (x : M) (pA : pred M) : reflect (x ∈ p2S pA) (x \in pA).
Proof.
rewrite /belong /p2S.
apply/(iffP idP) => H1.
- by rewrite H1.
- by case H : (x \in pA); last rewrite H in H1.
Qed.
(**
「元xが集合Aに含まれるか、含まれないかのどちらかである」ことを(公理 1.)を使わずに、
定理として導くことができます。
*)
Lemma fin_mySet (pA : pred M) (x : M) : x \in pA \/ ~(x \in pA).
Proof.
case: (myFinBelongP x pA); by [left | right].
Qed.
(**
実際の集合の証明では、``M : Type, P : mySet M``
を ``M : finType, pA : pred M`` に変更する必要があります。
*)
Lemma Mother_Sub (pA : pred M) :
myMotherSet ⊂ p2S pA -> forall x, x ∈ p2S pA.
Proof.
rewrite Mother_predT. (* 省略可能 *)
move=> H x.
Check H x : x ∈ p2S M -> x ∈ p2S pA.
apply: (H x).
done.
Qed.
Lemma transitive_Sub (pA pB pC : pred M) :
pA ⊂ pB -> pB ⊂ pC -> pA ⊂ pC.
Proof.
move=> HAB HBC t HtA.
by auto.
Qed.
(**
axiom_mySet ではなく、fin_mySet を使って証明することができます。
すなわち(公理 1.)を使用せずに証明できたことになります。
*)
Lemma cc_cancel' (pA : pred M) : (pA^c)^c = pA.
Proof.
apply: axiom_ExteqmySet.
split; rewrite /myComplement => x H;
by case: (fin_mySet pA x) => HxA.
Qed.
Lemma myUnionCompMother' (pA : pred M) : pA ∪ (pA^c) = myMotherSet.
Proof.
apply: axiom_ExteqmySet.
split=> [x | x H] //=.
case: (fin_mySet pA x); by [left | right].
Qed.
End FinType.
Section 具体的なfinType.
Definition p0 := @Ordinal 5 0 is_true_true.
Check p2S 'I_5 : mySet 'I_5.
Goal p0 ∈ p2S 'I_5.
Proof. by []. Qed.
End 具体的なfinType.
(**
## mySet を bool型であらわす場合
そもそも ``mySet M`` を bool型の ``pred M`` であらわすことで、(公理 1.)は不要になります。
belongがbool述語となるので、公理なしで決定性が保証されるからです。以下を参照してください。
https://github.com/suharahiromichi/coq/blob/master/csm/csm_5_set_theory_class.v
(ご注意。ファイル名に意味はありません)
*)
(**
# 公理 2. について
これは、外延性の公理です。
*)
Section Test3.
Variable M : finType. (* 注意してください。 *)
Definition myMotherSet' : mySet M := fun (_ : M) => true.
Lemma cc_cancel'' (pA : pred M) : (pA^c)^c =1 pA.
Proof.
move=> x.
rewrite /myComplement.
(* Goal : (~ ~ pA x) = pA x *)
Admitted.
Lemma myUnionCompMother'' (pA : pred M) : (pA ∪ (pA^c)) =1 myMotherSet'.
Proof.
move=> x.
case: (fin_mySet pA x).
move/myFinBelongP=> H.
rewrite /myCup /myComplement /myMotherSet'.
Admitted.
End Test3.
(**
# 文献
[1.] 萩原学 アフェルト・レナルド、「Coq/SSReflect/MathCompによる定理証明」、森北出版
[2.] Mathematical Components (MathComp Book) https://math-comp.github.io
*)
(* END *)
|
Text provided under a Creative Commons Attribution license, CC-BY. Code under MIT license.
(c)2014 Lorena A. Barba, Olivier Mesnard. Thanks: NSF for support via CAREER award #1149784.
[@LorenaABarba](https://twitter.com/LorenaABarba)
##### Version 0.3 -- February 2015
# Vortex
Let's recap. In the first three lessons of _AeroPython_, you computed:
1. [a source-sink pair](http://nbviewer.ipython.org/github/barbagroup/AeroPython/blob/master/lessons/01_Lesson01_sourceSink.ipynb)—you learned how to make a `streamplot()` and use `scatter()` to mark the location of the singular points. If you did your challenge task, you saw that equipotential lines are perpendicular to streamlines.
2. [a source-sink pair in a free stream](http://nbviewer.ipython.org/github/barbagroup/AeroPython/blob/master/lessons/02_Lesson02_sourceSinkFreestream.ipynb), creating a _Rankine oval_. For the first time, we see that we can model the flow around an object using potential flow solutions. You also learned to define custom functions, to make Python work for you and look even more like plain English.
3. [a doublet](http://nbviewer.ipython.org/github/barbagroup/AeroPython/blob/master/lessons/03_Lesson03_doublet.ipynb)—this one is wonderful, because the stream-line pattern gives the flow around a circular cylinder (in two dimensions). You encountered the _D'Alembert paradox_ and hopefully that got you thinking. (If not, go back to that lesson and _think_!)
Did you also do the [assignment](http://nbviewer.ipython.org/github/barbagroup/AeroPython/blob/master/lessons/03_Lesson03_Assignment.ipynb)? It shows you how a *distribution of sources* can be used to model potential flow around an airfoil. This starts looking like aerodynamics!
But what is the most important thing we want from applied aerodynamics? We want to make things fly, of course! And to fly, there must be a force of *aerodynamic lift* to counteract the weight of the object.
In this section of the course, we learn about lift. First, we will compute the flow of a potential vortex. It turns out, vortex circulation and lift are intimately related.
## What's a vortex?
This question is deeper than you might think! The simple answer is that a vortex is motion in circular streamlines. Imagine streamlines that are concentric circles about a given point—what's confusing is that this _does not mean_ that fluid elements are themselves rotating!
In an irrotational vortex, the tangential velocity is constant along a (circular) streamline and inversely proportional to the radius, while the radial velocity is zero. In polar coordinates:
\begin{equation}
u_\theta\left(r,\theta\right) = \frac{\text{constant}}{r} \quad \text{,} \quad u_r\left(r,\theta\right) = 0
\end{equation}
The vorticity is zero everywhere, except at the location of the point vortex, where the derivative of $u_\theta$ is infinite.
We introduced the concept of circulation in the first lesson ([Source & Sink](http://nbviewer.ipython.org/urls/github.com/barbagroup/AeroPython/blob/master/lessons/01_Lesson01_sourceSink.ipynb)). Let's use that. Around any circular streamline enclosing the vortex, and using the sign convention that a negative vortex circulates anti-clockwise, we have:
\begin{equation}\Gamma = -\oint \mathbf{v}\cdot d\vec{l} = -u_\theta 2 \pi r\end{equation}
Thus, the constant in the expression for $u_\theta$ in $(1)$ is equal to $\Gamma/2\pi$, and we now write:
\begin{equation}u_\theta\left(r,\theta\right) = \frac{\Gamma}{2\pi r}\end{equation}
We can get the stream function by integrating the velocity components:
\begin{equation}\psi\left(r,\theta\right) = \frac{\Gamma}{2\pi}\ln r\end{equation}
In Cartesian coordinates, the stream function is
\begin{equation}\psi\left(x,y\right) = \frac{\Gamma}{4\pi}\ln\left(x^2+y^2\right)\end{equation}
while the velocity components would be:
\begin{equation}u\left(x,y\right) = \frac{\Gamma}{2\pi}\frac{y}{x^2+y^2} \qquad v\left(x,y\right) = -\frac{\Gamma}{2\pi}\frac{x}{x^2+y^2}\end{equation}
This vortex flow is irrotational everywhere, except at the vortex center, where it is infinite. The strenth of the point vortex is equal to the circulation $\Gamma$ around it.
## Let's compute a vortex
The set-up is the same as before: we load our favorite libraries, and we create a grid of points to evaluate the velocity field.
```
import numpy
import math
from matplotlib import pyplot
```
```
N = 50 # Number of points in each direction
x_start, x_end = -2.0, 2.0 # x-direction boundaries
y_start, y_end = -1.0, 1.0 # y-direction boundaries
x = numpy.linspace(x_start, x_end, N) # computes a 1D-array for x
y = numpy.linspace(y_start, y_end, N) # computes a 1D-array for y
X, Y = numpy.meshgrid(x, y) # generates a mesh grid
```
Give your vortex a strength $\Gamma=5$ and place it at the center of your domain:
```
gamma = 5.0 # strength of the vortex
x_vortex, y_vortex = 0.0, 0.0 # location of the vortex
```
We will define two functions,
* `get_velocity_vortex()` and
* `get_stream_function_vortex()`,
to compute the velocity components and the stream function on our Cartesian grid, given the strength and the location of the vortex. Then, we will use our custom functions to evaluate everything on the grid points. Let's write those functions first.
```
def get_velocity_vortex(strength, xv, yv, X, Y):
"""Returns the velocity field generated by a vortex.
Arguments
---------
strength -- strength of the vortex.
xv, yv -- coordinates of the vortex.
X, Y -- mesh grid.
"""
u = + strength/(2*math.pi)*(Y-yv)/((X-xv)**2+(Y-yv)**2)
v = - strength/(2*math.pi)*(X-xv)/((X-xv)**2+(Y-yv)**2)
return u, v
```
```
def get_stream_function_vortex(strength, xv, yv, X, Y):
"""Returns the stream-function generated by a vortex.
Arguments
---------
strength -- strength of the vortex.
xv, yv -- coordinates of the vortex.
X, Y -- mesh grid.
"""
psi = strength/(4*math.pi)*numpy.log((X-xv)**2+(Y-yv)**2)
return psi
```
An now, call the functions with the vortex strength and position, plus the coordinates of the evaluation grid, to get the velocity and streamfunction of the vortex.
```
# computes the velocity field on the mesh grid
u_vortex, v_vortex = get_velocity_vortex(gamma, x_vortex, y_vortex, X, Y)
# computes the stream-function on the mesh grid
psi_vortex = get_stream_function_vortex(gamma, x_vortex, y_vortex, X, Y)
```
We are now able to visualize the streamlines of a vortex, and they look like concentric circles around the vortex center, as expected.
```
# plots the streamlines
%matplotlib inline
size = 10
pyplot.figure(figsize=(size, (y_end-y_start)/(x_end-x_start)*size))
pyplot.xlabel('x', fontsize=16)
pyplot.ylabel('y', fontsize=16)
pyplot.xlim(x_start, x_end)
pyplot.ylim(y_start, y_end)
pyplot.streamplot(X, Y, u_vortex, v_vortex, density=2, linewidth=1, arrowsize=1, arrowstyle='->')
pyplot.scatter(x_vortex, y_vortex, color='#CD2305', s=80, marker='o');
```
## Vortex & Sink
For fun, let's use our superposition powers. Add a vortex to a sink, using two new functions to compute the velocity components and the stream function of the sink, and adding to those of a vortex (remember that the sink can be easily replaced by a source by just changing the sign of the strength).
```
strength_sink = -1.0 # strength of the sink
x_sink, y_sink = 0.0, 0.0 # location of the sink
```
```
def get_velocity_sink(strength, xs, ys, X, Y):
"""Returns the velocity field generated by a sink.
Arguments
---------
strength -- strength of the sink.
xs, ys -- coordinates of the sink.
X, Y -- mesh grid.
"""
u = strength/(2*math.pi)*(X-xs)/((X-xs)**2+(Y-ys)**2)
v = strength/(2*math.pi)*(Y-ys)/((X-xs)**2+(Y-ys)**2)
return u, v
```
```
def get_stream_function_sink(strength, xs, ys, X, Y):
"""Returns the stream-function generated by a sink.
Arguments
---------
strength -- strength of the sink.
xs, ys -- coordinates of the sink.
X, Y -- mesh grid.
"""
psi = strength/(2*math.pi)*numpy.arctan2((Y-ys), (X-xs))
return psi
```
```
# computes the velocity field on the mesh grid
u_sink, v_sink = get_velocity_sink(strength_sink, x_sink, y_sink, X, Y)
# computes the stream-function on the mesh grid
psi_sink = get_stream_function_sink(strength_sink, x_sink, y_sink, X, Y)
```
Now, let's visualize the streamlines of the vortex-sink, and admire our artistic creation:
```
# superposition of the sink and the vortex
u = u_vortex + u_sink
v = v_vortex + v_sink
psi = psi_vortex + psi_sink
# plots the streamlines
size = 10
pyplot.figure(figsize=(size, (y_end-y_start)/(x_end-x_start)*size))
pyplot.xlabel('x', fontsize=16)
pyplot.ylabel('y', fontsize=16)
pyplot.xlim(x_start, x_end)
pyplot.ylim(y_start, y_end)
pyplot.streamplot(X, Y, u, v, density=2, linewidth=1, arrowsize=1, arrowstyle='->')
pyplot.scatter(x_vortex, y_vortex, color='#CD2305', s=80, marker='o');
```
Very cool op-art. (And a good model for your typical bath-tub vortex.) But is all this useful? Yes!
First, you will take your training wheels off and—on your own—compute the flow of an [infinite row of vortices](http://nbviewer.ipython.org/github/barbagroup/AeroPython/blob/master/lessons/05_Lesson05_InfiniteRowOfVortices.ipynb). Your mission, should you choose to accept it, is in the next notebook.
After that, we will learn about the connection between a vortex, and the force of lift. This turns out to be very important in aerodynamics!
## What's this "irrotational" vortex thing?
I know what you are thinking.
What does it mean that the vortex is *irrotational*? Surely if there's a vortex, there's rotation!
You are not crazy. It's natural to think this way, but the potential vortex is a flow where streamlines are circular, yet fluid elements do not rotate around themselves—they just go around the circular path.
This classic video will help you understand ... just watch the 25 seconds of video after time 4m 25s, and see a "vorticity meter" go around a free vortex without rotating itself.
```
from IPython.display import YouTubeVideo
from datetime import timedelta
start=int(timedelta(hours=0, minutes=4, seconds=25).total_seconds())
YouTubeVideo("loCLkcYEWD4", start=start)
```
Remember: vorticity measures the local angular velocity of each fluid element. If the fluid elements go around a circular path, but do not spin themselves, there is no vorticity!
This animation from [Wikipedia](http://en.wikipedia.org/wiki/Vortex#Irrotational_vortices) helps further illustrate what happens in an irrotational vortex: the orange markers with a line across them are going around in circles, but they are not themselves rotating (notice the white lines keep their orientation).
## Next ...
The next IPython Notebook of the *AeroPython* series presents the exercise ["Infinite row of vortices,"](http://nbviewer.ipython.org/github/barbagroup/AeroPython/blob/master/lessons/05_Lesson05_InfiniteRowOfVortices.ipynb) as independent student work.
---
Please ignore the cell below. It just loads our style for the notebook.
```
from IPython.core.display import HTML
def css_styling():
styles = open('../styles/custom.css', 'r').read()
return HTML(styles)
css_styling()
```
<link href='http://fonts.googleapis.com/css?family=Fenix' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Alegreya+Sans:100,300,400,500,700,800,900,100italic,300italic,400italic,500italic,700italic,800italic,900italic' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Source+Code+Pro:300,400' rel='stylesheet' type='text/css'>
<style>
@font-face {
font-family: "Computer Modern";
src: url('http://mirrors.ctan.org/fonts/cm-unicode/fonts/otf/cmunss.otf');
}
div.cell{
width:800px;
margin-left:16% !important;
margin-right:auto;
}
h1 {
font-family: 'Alegreya Sans', sans-serif;
}
h2 {
font-family: 'Fenix', serif;
}
h3{
font-family: 'Fenix', serif;
margin-top:12px;
margin-bottom: 3px;
}
h4{
font-family: 'Fenix', serif;
}
h5 {
font-family: 'Alegreya Sans', sans-serif;
}
div.text_cell_render{
font-family: 'Alegreya Sans',Computer Modern, "Helvetica Neue", Arial, Helvetica, Geneva, sans-serif;
line-height: 135%;
font-size: 120%;
width:600px;
margin-left:auto;
margin-right:auto;
}
.CodeMirror{
font-family: "Source Code Pro";
font-size: 90%;
}
/* .prompt{
display: None;
}*/
.text_cell_render h1 {
font-weight: 200;
font-size: 50pt;
line-height: 100%;
color:#CD2305;
margin-bottom: 0.5em;
margin-top: 0.5em;
display: block;
}
.text_cell_render h5 {
font-weight: 300;
font-size: 16pt;
color: #CD2305;
font-style: italic;
margin-bottom: .5em;
margin-top: 0.5em;
display: block;
}
.warning{
color: rgb( 240, 20, 20 )
}
</style>
|
context("consume iterator")
test_that("consume consumes an iterator when n < length(iterator)", {
it <- iterators::iter(letters)
consume(it, n=4)
expect_equal(nextElem(it), "e")
})
test_that("consume consumes an iterator when n=0 or n > length(iterator)", {
it <- iterators::iter(letters)
consume(it, n=0)
expect_error(nextElem(it), "StopIteration")
it2 <- iterators::iter(letters)
consume(it2, n=27)
expect_error(nextElem(it), "StopIteration")
})
test_that("consume rejects non-positive or non-integer n", {
it <- iterators::iter(letters)
expect_error(consume(it, -1), "n must be a non-negative integer of length 1")
expect_error(consume(it, "a"), "n must be a non-negative integer of length 1")
})
test_that("nth consumes an iterator when n < length(iterable)", {
it <- iterators::iter(letters)
expect_equal(nth(it, 5), "e")
})
test_that("nth returns the given default value when the iterator is consumed", {
it <- iterators::iter(letters)
expect_equal(nth(it, 27), NA)
})
test_that("nth rejects negative or non-integer n", {
it <- iterators::iter(letters)
expect_error(nth(it, -1), "n must be a positive integer of length 1")
expect_error(nth(it, "a"), "n must be a positive integer of length 1")
})
|
import BrownCs22.Library.Tactics
/-
In this file, we'll prove some of the identities from
https://brown-cs22.github.io/resources/math-resources/logic.pdf
Note that these identities are stated with the symbol `≡`,
meaning "the formula on the left is equivalent to the formula on the right."
In Lean, we can use iff (bi-implication, `↔`) to mean the same thing.
Remember the tactics we learned in Lecture 4.
We'll see a bit of new Lean syntax along the way.
Also remember that it doesn't matter what we name our hypotheses.
In our examples, we use patterns like `hp` for the hypothesis `p`,
`hnpq` for the hypothesis `¬ p ∧ q` (hnpq for "hypothesis not p q"), etc.
But this is just a custom. You can choose any names you want.
As they say, the hardest problem in computer science is naming variables.
Your task: fill in all the `sorry`s with proofs!
-/
variable (p q r : Prop)
-- ## Commutative Laws
-- We'll do the first for you, as an example.
-- Notice two things.
-- One, must of these problems will start with `split_goal`,
-- to turn the `iff` goal into two `implies` goals.
-- Two, we structure our proof by putting each *subproof* in `{...}`.
-- This isn't necessary but it helps with organization!
example : p ∧ q ↔ q ∧ p := by
split_goal
{ intro hpq
eliminate hpq with hp hq
split_goal
assumption
assumption }
{ intro hqp
eliminate hqp with hq hp
split_goal
assumption
assumption }
example : p ∨ q ↔ q ∨ p := by
sorry
-- ## Associative laws
-- Notice that Lean doesn't print parentheses unless it needs to.
example : (p ∧ q) ∧ r ↔ p ∧ (q ∧ r) := by
sorry
-- This is getting a little repetitive.
-- To mix it up, we'll only do one direction of the iff this time.
-- You won't start with `split_goal`, but instead, ... what?
example : (p ∨ q) ∨ r → p ∨ (q ∨ r) := by
sorry
-- ## Distributive laws
example : p ∧ (q ∨ r) ↔ (p ∧ q) ∨ (p ∧ r) := by
sorry
-- Again, let's just do one direction.
-- When we're proving an implication `→`, we'll always start with `intro`.
-- This is such a common pattern that Lean gives us special syntax for it:
-- we can do the intro "in advance," before we start the proof,
-- by naming the hypothesis to the left of the `:`.
-- Notice that at the beginning of our proof, we already have the
-- hypothesis `hpqr` in our context.
example (hpqr : p ∨ (q ∧ r)) : (p ∨ q) ∧ (p ∨ r) := by
sorry
-- ## Identity laws
/-
We'll do a few more together.
Let's sneak a new tactic in.
To prove a goal `True`, you can use the tactic `trivial`.
This is a sensible proof rule: trivially, you can always show `True` is true!
-/
example : p ∧ True ↔ p := by
split_goal
{ intro hpT
eliminate hpT
assumption }
{ intro hpT
split_goal
assumption
trivial }
-- Before, we saw `contradiction` would work if we had hypotheses
-- `p` and `¬ p` at the same time.
-- It also works if we have a hypothesis `False`!
example : p ∨ False ↔ p := by
split_goal
{ intro hpF
eliminate hpF with hp hF
assumption
contradiction }
{ intro hp
left
assumption }
/-
## Negation laws
If you're following along with the list of identities, you'll see that
we've come to some laws like `(p ∨ ¬ p) ↔ True`.
Unfortunately, we don't have the tools to prove these in Lean yet.
But, you can do the **Idempotent laws** and **Universal bound laws**.
Try stating and proving these yourself!
-/
/-
## De Morgan's Laws
These can be a bit of a challenge! Like the negation laws,
a few of the implications here will require some new tools.
But try out these directions.
Remember that to prove a negation `¬ X`, you can use a *proof by contradiction*:
add a hypothesis `h : X` using `intro h`, and then show a contradiction.
-/
example (hnpnq : ¬ p ∨ ¬ q) : ¬(p ∧ q) := by
sorry
example (hnpnq : ¬ p ∧ ¬ q) : ¬ (p ∨ q) := by
sorry
/-
That's it for the moment!
Try the **Absorption laws** and **Negation of True and False**
on your own, if you want to. Skip the definition laws for now.
-/
|
State Before: α : Type u
β : α → Type v
l✝ l₁ l₂ : List (Sigma β)
inst✝ : DecidableEq α
a : α
s : Sigma β
l : List (Sigma β)
h : a = s.fst
⊢ kerase a (s :: l) = l State After: no goals Tactic: simp [kerase, h]
|
/* interpolation/interp2d.c
*
* Copyright 2012 David Zaslavsky
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_interp.h>
#include <gsl/gsl_interp2d.h>
/**
* Triggers a GSL error if the argument is not equal to GSL_SUCCESS.
* If the argument is GSL_SUCCESS, this does nothing.
*/
#define DISCARD_STATUS(s) if ((s) != GSL_SUCCESS) { GSL_ERROR_VAL("interpolation error", (s), GSL_NAN); }
#define IDX2D(i, j, w) ((j) * ((w)->xsize) + (i))
gsl_interp2d *
gsl_interp2d_alloc(const gsl_interp2d_type * T, const size_t xsize,
const size_t ysize)
{
gsl_interp2d * interp;
if (xsize < T->min_size || ysize < T->min_size)
{
GSL_ERROR_NULL ("insufficient number of points for interpolation type",
GSL_EINVAL);
}
interp = (gsl_interp2d *) calloc(1, sizeof(gsl_interp2d));
if (interp == NULL)
{
GSL_ERROR_NULL ("failed to allocate space for gsl_interp2d struct",
GSL_ENOMEM);
}
interp->type = T;
interp->xsize = xsize;
interp->ysize = ysize;
if (interp->type->alloc == NULL)
{
interp->state = NULL;
return interp;
}
interp->state = interp->type->alloc(xsize, ysize);
if (interp->state == NULL)
{
free(interp);
GSL_ERROR_NULL ("failed to allocate space for gsl_interp2d state",
GSL_ENOMEM);
}
return interp;
} /* gsl_interp2d_alloc() */
void
gsl_interp2d_free (gsl_interp2d * interp)
{
RETURN_IF_NULL(interp);
if (interp->type->free)
interp->type->free(interp->state);
free(interp);
} /* gsl_interp2d_free() */
int
gsl_interp2d_init (gsl_interp2d * interp, const double xarr[], const double yarr[],
const double zarr[], const size_t xsize, const size_t ysize)
{
size_t i;
if (xsize != interp->xsize || ysize != interp->ysize)
{
GSL_ERROR("data must match size of interpolation object", GSL_EINVAL);
}
for (i = 1; i < xsize; i++)
{
if (xarr[i-1] >= xarr[i])
{
GSL_ERROR("x values must be strictly increasing", GSL_EINVAL);
}
}
for (i = 1; i < ysize; i++)
{
if (yarr[i-1] >= yarr[i])
{
GSL_ERROR("y values must be strictly increasing", GSL_EINVAL);
}
}
interp->xmin = xarr[0];
interp->xmax = xarr[xsize - 1];
interp->ymin = yarr[0];
interp->ymax = yarr[ysize - 1];
{
int status = interp->type->init(interp->state, xarr, yarr, zarr,
xsize, ysize);
return status;
}
} /* gsl_interp2d_init() */
/*
* A wrapper function that checks boundary conditions, calls an evaluator
* which implements the actual calculation of the function value or
* derivative etc., and checks the return status.
*/
static int
interp2d_eval(int (*evaluator)(const void *, const double xa[], const double ya[],
const double za[], size_t xsize, size_t ysize,
double x, double y, gsl_interp_accel *,
gsl_interp_accel *, double * z),
const gsl_interp2d * interp, const double xarr[],
const double yarr[], const double zarr[],
const double x, const double y,
gsl_interp_accel * xa, gsl_interp_accel * ya,
double * result)
{
if (x < interp->xmin || x > interp->xmax)
{
GSL_ERROR ("interpolation x value out of range", GSL_EDOM);
}
else if (y < interp->ymin || y > interp->ymax)
{
GSL_ERROR ("interpolation y value out of range", GSL_EDOM);
}
return evaluator(interp->state, xarr, yarr, zarr,
interp->xsize, interp->ysize,
x, y, xa, ya, result);
}
/*
* Another wrapper function that serves as a drop-in replacement for
* interp2d_eval but does not check the bounds. This can be used
* for extrapolation.
*/
static int
interp2d_eval_extrap(int (*evaluator)(const void *, const double xa[],
const double ya[], const double za[],
size_t xsize, size_t ysize,
double x, double y,
gsl_interp_accel *,
gsl_interp_accel *, double * z),
const gsl_interp2d * interp, const double xarr[],
const double yarr[], const double zarr[],
const double x, const double y,
gsl_interp_accel * xa, gsl_interp_accel * ya,
double * result)
{
return evaluator(interp->state, xarr, yarr, zarr,
interp->xsize, interp->ysize, x, y, xa, ya, result);
}
double
gsl_interp2d_eval (const gsl_interp2d * interp, const double xarr[],
const double yarr[], const double zarr[],
const double x, const double y,
gsl_interp_accel * xa, gsl_interp_accel * ya)
{
double z;
int status = gsl_interp2d_eval_e(interp, xarr, yarr, zarr, x, y, xa, ya, &z);
DISCARD_STATUS(status)
return z;
} /* gsl_interp2d_eval() */
double
gsl_interp2d_eval_extrap (const gsl_interp2d * interp,
const double xarr[],
const double yarr[],
const double zarr[],
const double x,
const double y,
gsl_interp_accel * xa,
gsl_interp_accel * ya)
{
double z;
int status =
interp2d_eval_extrap(interp->type->eval, interp,
xarr, yarr, zarr, x, y, xa, ya, &z);
DISCARD_STATUS(status)
return z;
}
int
gsl_interp2d_eval_e (const gsl_interp2d * interp, const double xarr[],
const double yarr[], const double zarr[],
const double x, const double y,
gsl_interp_accel * xa, gsl_interp_accel * ya, double * z)
{
return interp2d_eval(interp->type->eval, interp,
xarr, yarr, zarr, x, y, xa, ya, z);
} /* gsl_interp2d_eval_e() */
int
gsl_interp2d_eval_e_extrap (const gsl_interp2d * interp,
const double xarr[], const double yarr[],
const double zarr[], const double x,
const double y, gsl_interp_accel * xa,
gsl_interp_accel * ya, double * z)
{
return interp2d_eval_extrap(interp->type->eval, interp,
xarr, yarr, zarr, x, y, xa, ya, z);
}
double
gsl_interp2d_eval_deriv_x (const gsl_interp2d * interp, const double xarr[],
const double yarr[], const double zarr[],
const double x, const double y,
gsl_interp_accel * xa, gsl_interp_accel * ya)
{
double z;
int status = gsl_interp2d_eval_deriv_x_e(interp, xarr, yarr, zarr, x, y, xa, ya, &z);
DISCARD_STATUS(status)
return z;
}
int
gsl_interp2d_eval_deriv_x_e (const gsl_interp2d * interp, const double xarr[],
const double yarr[], const double zarr[],
const double x, const double y,
gsl_interp_accel * xa, gsl_interp_accel * ya, double * z)
{
return interp2d_eval(interp->type->eval_deriv_x, interp,
xarr, yarr, zarr, x, y, xa, ya, z);
}
double
gsl_interp2d_eval_deriv_y (const gsl_interp2d * interp, const double xarr[],
const double yarr[], const double zarr[],
const double x, const double y,
gsl_interp_accel * xa, gsl_interp_accel * ya)
{
double z;
int status = gsl_interp2d_eval_deriv_y_e(interp, xarr, yarr, zarr, x, y, xa, ya, &z);
DISCARD_STATUS(status)
return z;
}
int
gsl_interp2d_eval_deriv_y_e (const gsl_interp2d * interp, const double xarr[],
const double yarr[], const double zarr[],
const double x, const double y,
gsl_interp_accel * xa, gsl_interp_accel * ya, double * z)
{
return interp2d_eval(interp->type->eval_deriv_y, interp,
xarr, yarr, zarr, x, y, xa, ya, z);
}
double
gsl_interp2d_eval_deriv_xx (const gsl_interp2d * interp, const double xarr[],
const double yarr[], const double zarr[],
const double x, const double y,
gsl_interp_accel * xa, gsl_interp_accel * ya)
{
double z;
int status = gsl_interp2d_eval_deriv_xx_e(interp, xarr, yarr, zarr, x, y, xa, ya, &z);
DISCARD_STATUS(status)
return z;
}
int
gsl_interp2d_eval_deriv_xx_e (const gsl_interp2d * interp, const double xarr[],
const double yarr[], const double zarr[],
const double x, const double y,
gsl_interp_accel * xa, gsl_interp_accel * ya, double * z)
{
return interp2d_eval(interp->type->eval_deriv_xx, interp,
xarr, yarr, zarr, x, y, xa, ya, z);
}
double
gsl_interp2d_eval_deriv_yy (const gsl_interp2d * interp, const double xarr[],
const double yarr[], const double zarr[],
const double x, const double y,
gsl_interp_accel * xa, gsl_interp_accel * ya)
{
double z;
int status = gsl_interp2d_eval_deriv_yy_e(interp, xarr, yarr, zarr, x, y, xa, ya, &z);
DISCARD_STATUS(status)
return z;
}
int
gsl_interp2d_eval_deriv_yy_e (const gsl_interp2d * interp, const double xarr[],
const double yarr[], const double zarr[],
const double x, const double y,
gsl_interp_accel * xa, gsl_interp_accel * ya, double * z)
{
return interp2d_eval(interp->type->eval_deriv_yy, interp,
xarr, yarr, zarr, x, y, xa, ya, z);
}
double
gsl_interp2d_eval_deriv_xy (const gsl_interp2d * interp, const double xarr[],
const double yarr[], const double zarr[],
const double x, const double y,
gsl_interp_accel * xa, gsl_interp_accel * ya)
{
double z;
int status = gsl_interp2d_eval_deriv_xy_e(interp, xarr, yarr, zarr, x, y, xa, ya, &z);
DISCARD_STATUS(status)
return z;
}
int
gsl_interp2d_eval_deriv_xy_e (const gsl_interp2d * interp, const double xarr[],
const double yarr[], const double zarr[],
const double x, const double y,
gsl_interp_accel * xa, gsl_interp_accel * ya, double * z)
{
return interp2d_eval(interp->type->eval_deriv_xy, interp,
xarr, yarr, zarr, x, y, xa, ya, z);
}
size_t
gsl_interp2d_type_min_size(const gsl_interp2d_type * T)
{
return T->min_size;
}
size_t
gsl_interp2d_min_size(const gsl_interp2d * interp)
{
return interp->type->min_size;
}
const char *
gsl_interp2d_name(const gsl_interp2d * interp)
{
return interp->type->name;
}
size_t
gsl_interp2d_idx(const gsl_interp2d * interp,
const size_t i, const size_t j)
{
if (i >= interp->xsize)
{
GSL_ERROR_VAL ("x index out of range", GSL_ERANGE, 0);
}
else if (j >= interp->ysize)
{
GSL_ERROR_VAL ("y index out of range", GSL_ERANGE, 0);
}
else
{
return IDX2D(i, j, interp);
}
} /* gsl_interp2d_idx() */
int
gsl_interp2d_set(const gsl_interp2d * interp, double zarr[],
const size_t i, const size_t j, const double z)
{
if (i >= interp->xsize)
{
GSL_ERROR ("x index out of range", GSL_ERANGE);
}
else if (j >= interp->ysize)
{
GSL_ERROR ("y index out of range", GSL_ERANGE);
}
else
{
zarr[IDX2D(i, j, interp)] = z;
return GSL_SUCCESS;
}
} /* gsl_interp2d_set() */
double
gsl_interp2d_get(const gsl_interp2d * interp, const double zarr[],
const size_t i, const size_t j)
{
if (i >= interp->xsize)
{
GSL_ERROR_VAL ("x index out of range", GSL_ERANGE, 0);
}
else if (j >= interp->ysize)
{
GSL_ERROR_VAL ("y index out of range", GSL_ERANGE, 0);
}
else
{
return zarr[IDX2D(i, j, interp)];
}
} /* gsl_interp2d_get() */
#undef IDX2D
|
In late 1982 , Congress passed a law which forbade the United States from funding groups aiming to overthrow the Sandinista government of Nicaragua . Then , in 1983 , Bedell visited Nicaragua and Honduras along with Representative Robert G. Torricelli . During the trip , Bedell spoke with soldiers , generals , governmental officials and members of the contras . His conclusion at the end of the trip was that Ronald Reagan was aiding the contras in violation of federal law . He promised to hold hearings after returning to Congress . Bedell would later join other House Democrats in demanding documents from the White House related to the contras , but the Reagan Administration refused to provide them . Bedell became angrier with the Reagan Administration as the decade wore on . He called his Central American policies " sheer lunacy , " saying that the mining of harbors was an acts of war . Bedell would retire from Congress before Reagan 's acts in Central America would culminate with the Iran @-@ Contra Affair .
|
= = = = 2011 = = = =
|
= = = = 2011 = = = =
|
(** * A10 *)
(* Do not modify these imports. *)
Require Import List Arith Bool.
Require String.
Import ListNotations.
Module Author.
Open Scope string_scope.
Definition author := "Andrew Wang".
Definition netid := "ayw24".
Definition hours_worked := 0.
Definition collaborators := "Jack Ding".
(* The latter should be the names of other students with whom
you discussed ideas on this assignment, following the collaboration
policy stated in the handout. *)
End Author.
(********************************************************************
AAA 1111111 000000000
A:::A 1::::::1 00:::::::::00
A:::::A 1:::::::1 00:::::::::::::00
A:::::::A 111:::::1 0:::::::000:::::::0
A:::::::::A 1::::1 0::::::0 0::::::0
A:::::A:::::A 1::::1 0:::::0 0:::::0
A:::::A A:::::A 1::::1 0:::::0 0:::::0
A:::::A A:::::A 1::::l 0:::::0 000 0:::::0
A:::::A A:::::A 1::::l 0:::::0 000 0:::::0
A:::::AAAAAAAAA:::::A 1::::l 0:::::0 0:::::0
A:::::::::::::::::::::A 1::::l 0:::::0 0:::::0
A:::::AAAAAAAAAAAAA:::::A 1::::l 0::::::0 0::::::0
A:::::A A:::::A 111::::::1110:::::::000:::::::0
A:::::A A:::::A 1::::::::::1 00:::::::::::::00
A:::::A A:::::A 1::::::::::1 00:::::::::00
AAAAAAA AAAAAAA111111111111 000000000
*********************************************************************)
(**
Here is an OCaml interface for queues:
<<
(* ['a t] is a queue containing values of type ['a]. *)
type 'a t
(* [empty] is the empty queue *)
val empty : 'a t
(* [is_empty q] is whether [q] is empty *)
val is_empty : 'a t -> bool
(* [front q] is [Some x], where [x] the front element of [q],
* or [None] if [q] is empty. *)
val front : 'a t -> 'a option
(* [enq x q] is the queue that is the same as [q], but with [x]
* enqueued (i.e., inserted) at the end. *)
val enq : 'a -> 'a t -> 'a t
(* [deq x q] is the queue that is the same as [q], but with its
* front element dequeued (i.e., removed). If [q] is empty,
* [deq q] is also empty. *)
val deq : 'a t -> 'a t
>>
Note that the specification for [deq] differs from what we have given
before: the [deq] of an empty list is the empty list; there are no
options or exceptions involved.
Here is an equational specification for that interface:
<<
(1) is_empty empty = true
(2) is_empty (enq _ _ ) = false
(3) front empty = None
(4) front (enq x q) = Some x if is_empty q = true
(5) front (enq _ q) = front q if is_empty q = false
(6) deq empty = empty
(7) deq (enq _ q) = empty if is_empty q = true
(8) deq (enq x q) = enq x (deq q) if is_empty q = false
>>
Your task in the next two parts of this file is to implement the Coq equivalent
of that interface and prove that your implementation satisfies the equational
specification. Actually, you will do this twice, with two different
representation types:
- _simple queues_, which represent a queue as a singly-linked list
and have worst-case linear time performance.
- _two-list queues_, which represent a queue with two singly-linked
lists, and have amortized constant time performance.
You will find both of those implementations in section 5.9 of the textbook.
*)
(********************************************************************)
(** ** Part 1: Simple Queues *)
(********************************************************************)
Module SimpleQueue.
(** Your first task is to implement and verify simple queues.
To get you started, we provide the following definitions for
the representation type of a simple queue, and for the empty
simple queue. *)
(** [queue A] is the type that represents a queue as a
singly-linked list. The list [[x1; x2; ...; xn]] represents
the queue with [x1] at its front, then [x2], ..., and finally
[xn] at its end. The list [[]] represents the empty queue. *)
Definition queue (A : Type) := list A.
Definition empty {A : Type} : queue A := [].
(**
*** Implementation of simple queues.
Define [is_empty], [front], [enq], and [deq]. We have provided some starter code
below that type checks, but it defines those operations in trivial and incorrect
ways. _Hint:_ this isn't meant to be tricky; you just need to translate the code
you would naturally write in OCaml into Coq syntax.
*)
Definition is_empty {A : Type} (q : queue A) : bool :=
match q with
| nil => true
| cons _ _ => false
end.
Definition front {A : Type} (q : queue A) : option A :=
match q with
| nil => None
| x :: _ => Some x
end.
Fixpoint enq {A : Type} (x : A) (q : queue A) : queue A :=
match q with
| nil => x::q
| cons h t => h::enq x t
end.
Definition deq {A : Type} (q : queue A) : queue A :=
match q with
| nil => nil
| cons h t => t
end.
(**
*** Verification of simple queues.
Prove that the equations in the queue specification hold. We have written
them for you, below, but instead of a proof we have written [Admitted]. That
tells Coq to accept the theorem as true (hence it will compile) even though
there is no proof. You need to replace [Admitted] with [Proof. ... Qed.]
_Hint:_ the only tactics you need are [intros], [trivial], [discriminate],
and [destruct]. You might also find [simpl] to be useful in making a goal
easier to read. If [simpl] won't simplify a computation involving a queue,
instead try [destruct] on that queue. Always pay attention to the hypotheses
to see whether one might be false, in which case you should concentrate on it
rather than the goal.
*)
Theorem eqn1 : forall (A : Type),
is_empty (@empty A) = true.
Proof.
trivial.
Qed.
Theorem eqn2 : forall (A : Type) (x : A) (q : queue A),
is_empty (enq x q) = false.
Proof.
intros A x q.
destruct q.
all: trivial.
Qed.
Theorem eqn3 : forall (A : Type),
front (@empty A) = None.
Proof.
trivial.
Qed.
Theorem eqn4 : forall (A : Type) (x : A) (q : queue A),
is_empty q = true -> front (enq x q) = Some x.
Proof.
intros A x q empty_is_true.
destruct q.
trivial.
discriminate.
Qed.
Theorem eqn5 : forall (A : Type) (x : A) (q : queue A),
is_empty q = false -> front (enq x q) = front q.
Proof.
intros A x q empty_is_false.
destruct q.
discriminate.
trivial.
Qed.
Theorem eqn6 : forall (A : Type),
deq (@empty A) = (@empty A).
Proof.
trivial.
Qed.
Theorem eqn7 : forall (A : Type) (x : A) (q : queue A),
is_empty q = true -> deq (enq x q) = empty.
Proof.
intros A x q empty_is_true.
destruct q.
simpl. trivial.
simpl. discriminate.
Qed.
Theorem eqn8 : forall (A : Type) (x : A) (q : queue A),
is_empty q = false -> deq (enq x q) = enq x (deq q).
Proof.
intros A x q empty_is_false.
destruct q.
simpl. discriminate.
simpl. trivial.
Qed.
End SimpleQueue.
(********************************************************************)
(** ** Part 2: Two-list Queues *)
(********************************************************************)
Module TwoListQueue.
(** Your second task is to implement and verify two-list queues.
To get you started, we provide the following definitions for
the representation type of a two-list queue, and for the empty
two-list queue. *)
(** [queue A] is the type that represents a queue as a pair of two
singly-linked lists. The pair [(f,b)] represents the same
queue as does the simple queue [f ++ rev b]. The list [f] is
the front of the queue, and the list [b] is the back of the
queue stored in reversed order.
_Representation invariant:_ if [f] is [nil] then [b] is [nil].
The syntax [% type] in this definition tells Coq to treat the
[*] symbol as the pair constructor rather than multiplication.
You shouldn't need to use that syntax anywhere in your solution. *)
Definition queue (A : Type) := (list A * list A) % type.
(** [rep_ok q] holds iff [q] satisfies its RI as stated above *)
Definition rep_ok {A : Type} (q : queue A) : Prop :=
match q with
| (f,b) => f = [] -> b = []
end.
Definition empty {A : Type} : queue A := ([],[]).
(**
*** Implementation of two-list queues.
Define [is_empty], [front], [enq], and [deq]. We have provided some starter code
below that type checks, but it defines those operations in trivial and incorrect
ways. You must use the efficient implementation described in the textbook.
You may not store the entire queue in the first component of the
pair and use the inefficient implementation on that component.
_Hint:_ this isn't meant to be tricky; you just need to translate the code
you would naturally write in OCaml into Coq syntax. You will need to define
one new function as part of that.
*)
Definition is_empty {A : Type} (q : queue A) : bool :=
match q with
| (nil, _) => true
| _ => false
end.
Definition front {A : Type} (q : queue A) : option A :=
match q with
| (nil, _) => None
| (cons x _, _) => Some x
end.
Definition norm {A : Type} (q: queue A) : queue A :=
match q with
| (nil, b) => (rev b, nil)
| q => q
end.
Definition enq {A : Type} (x : A) (q : queue A) : queue A :=
match q with
| (nil, _) => norm (nil, x::[])
| (f, t) => norm (f, x::t)
end.
Definition deq {A : Type} (q : queue A) : queue A :=
match q with
| (nil, _) => (nil, [])
| (cons h t, b) => norm (t, b)
end.
(** This "unit test" checks to make sure your implementation correctly
uses both the front and back list on a simple example. You should
be able to prove it just by changing [Admitted.] to [trivial. Qed.]
If not, you probably have coded up the [enq] function or a helper
incorrectly. In that case, fix it before moving on to the theorems
below. *)
Example test_two_lists : enq 1 (enq 0 empty) = ([0], [1]).
Proof. trivial. Qed.
(**
*** Verification of two-list queues.
Next you need to prove that the equations in the queue specification hold.
The statements of those equations below now include as a precondition
that the RI holds of any input queues.
_Hint:_ in addition to the tactics you used for simple queues, you will
also find [apply...in], [rewrite], and [assumption] to be helpful.
We suggest factoring out helper lemmas whenever you discover that
a hypothesis is difficult to work with in its current form.
*)
Theorem eqn1 : forall (A : Type),
is_empty (@empty A) = true.
Proof.
trivial.
Qed.
Theorem eqn2 : forall (A : Type) (x : A) (q : queue A),
rep_ok q -> is_empty (enq x q) = false.
Proof.
intros A x q evRep.
destruct q as [front back].
destruct front.
trivial.
destruct back.
all: trivial.
Qed.
Theorem eqn3 : forall (A : Type),
front (@empty A) = None.
Proof.
trivial.
Qed.
Theorem eqn4 : forall (A : Type) (x : A) (q : queue A),
rep_ok q -> is_empty q = true -> front (enq x q) = Some x.
Proof.
intros A x q evRep empty_eq_true.
destruct q as [f b].
destruct f.
trivial.
discriminate.
Qed.
Theorem eqn5 : forall (A : Type) (x : A) (q : queue A),
rep_ok q -> is_empty q = false -> front (enq x q) = front q.
Proof.
intros A x q evRep empty_eq_true.
destruct q as [f b].
simpl.
destruct f.
discriminate.
trivial.
Qed.
Theorem eqn6 : forall (A : Type),
deq (@empty A) = @empty A.
Proof.
trivial.
Qed.
Theorem eqn7_helper : forall (A : Type) (x : A) (q: queue A),
rep_ok q -> is_empty q = true -> q = ([], []).
Proof.
intros.
destruct q as [f back].
simpl.
destruct f.
simpl.
rewrite H.
trivial.
trivial.
discriminate.
Qed.
(** Look into how to break this one up *)
Theorem eqn7 : forall (A : Type) (x : A) (q : queue A),
rep_ok q -> is_empty q = true -> deq (enq x q) = empty.
Proof.
intros A x q evRep empty_eq_true.
destruct q as [f b].
destruct f.
destruct b.
simpl.
trivial.
trivial.
discriminate.
Qed.
(**
It turns out that two-list queues actually do not satisfy [eqn8]! To show that,
find a counterexample: values for [x] and [q] that cause [eqn8] to be invalid.
Plug in your values for [x] and [q] below, then prove the three theorems
[counter1], [counter2], and [counter3]. _Hint_: if you choose your values well,
the proofs should be short and easy, requiring only [discriminate] or [trivial].
*)
Module CounterEx.
Definition x : nat := 0.
(* change [0] to a value of your choice *)
Definition q : (list nat * list nat) := ([x], [x]).
(* change [empty] to a value of your choice *)
Theorem counter1 : rep_ok q.
Proof.
discriminate.
Qed.
Theorem counter2 : is_empty q = false.
Proof.
trivial.
Qed.
Theorem counter3 : deq (enq x q) <> enq x (deq q).
Proof.
discriminate.
Qed.
End CounterEx.
(**
Two-list queues do satisfy a relaxed version of [eqn8], though,
where instead of requiring [deq (enq x q)] and [enq x (deq q)]
to be _equal_, we only require them to be _equivalent_ after being
converted to simple queues. The following definition implements
that idea of equivalence:
*)
Definition equiv {A:Type} (q1 q2 : queue A) : Prop :=
match (q1, q2) with
| ((f1,b1),(f2,b2)) => f1 ++ rev b1 = f2 ++ rev b2
end.
(**
Now prove that the following relaxed form of [eqn8] holds. _Hint:_
this is probably the hardest proof in the assignment. Don't hesitate
to manage the complexity of the proof by stating and proving helper lemmas.
We found uses for some additional tactics in this proof:
[contradiction], [destruct (e)], and [unfold]. We also found
a theorem involving [++] from the [List] library to be helpful.
*)
(* Lemma eqn8_equiv' : forall (A : Type) (x : A) (q : queue A),
rep_ok q -> is_empty q = false -> (deq (enq x q)) *)
Lemma front_no_back : forall (A : Type) (x : A) (f : list A),
f <> [] -> equiv (deq (enq x (f, []))) (enq x (deq (f, []))).
Proof.
intros A x f f_not_empty.
destruct f.
contradiction.
simpl.
destruct f.
simpl.
unfold equiv. trivial. simpl.
unfold equiv. simpl. trivial.
Qed.
Lemma elt_cons_front : forall (A : Type) (x : A) (f b: list A),
f <> [] -> is_empty (f, b) = false.
Proof.
intros.
destruct f.
contradiction.
trivial.
Qed.
Lemma enq_nonempty : forall (A : Type) (x : A) (f b : list A),
rep_ok (f,b) -> is_empty (f,b) = false -> enq x (f,b) = (f, x::b).
Proof.
intros A x f b rep_ok is_not_empty.
destruct f.
destruct b.
discriminate.
simpl.
discriminate.
simpl.
trivial.
Qed.
Lemma deq_nonempty : forall (A : Type) (x : A) (f b : list A),
rep_ok (f,b) -> is_empty (f,b) = false -> deq (x::f,b) = (f, b).
Proof.
intros.
destruct f.
discriminate.
trivial.
Qed.
Lemma one_front_back : forall (A : Type) (x a a0 : A) (b : list A),
deq (enq x ([a], a0 :: b)) = (rev (x :: a0 :: b), []).
Proof.
trivial.
Qed.
Lemma some_deq : forall (A : Type) (x a a0 : A) (b : list A),
deq ([a], a0 :: b) = (rev (a0 :: b), []).
Proof.
trivial.
Qed.
Theorem eqn8_equiv : forall (A : Type) (x : A) (q : queue A),
rep_ok q -> is_empty q = false ->
equiv (deq (enq x q)) (enq x (deq q)).
Proof.
intros A x q rep_good is_not_empty.
destruct q as [front back].
destruct front.
destruct back.
discriminate. discriminate.
destruct back.
destruct front0.
unfold equiv.
simpl. trivial.
unfold equiv.
simpl. trivial.
destruct front0.
rewrite one_front_back.
rewrite some_deq.
unfold equiv.
simpl.
destruct (rev back).
simpl. trivial.
simpl.
rewrite app_nil_r.
trivial.
assumption.
simpl.
unfold equiv.
trivial.
Qed.
(**
Finally, verify that [empty] satisfies the RI, and that [enq] and [deq] both
preserve the RI.
*)
Theorem rep_ok_empty : forall (A : Type),
rep_ok (@empty A).
Proof.
intros A.
intros evRep.
trivial.
Qed.
Theorem rep_ok_enq : forall (A : Type) (q : queue A),
rep_ok q -> forall (x : A), rep_ok (enq x q).
Proof.
intros A q rep_good.
intros x.
destruct q as [front back].
destruct front.
all: discriminate.
Qed.
Theorem rep_ok_deq: forall (A : Type) (q : queue A),
rep_ok q -> rep_ok (deq q).
Proof.
intros.
destruct q.
destruct l.
simpl. trivial.
destruct l.
trivial.
simpl.
destruct (rev l0).
trivial.
discriminate.
discriminate.
Qed.
End TwoListQueue.
(********************************************************************)
(** ** Part 3: Logic, and Programs as Proofs *)
(********************************************************************)
Module Logic.
(**
Change each of the following conjectures into a definition. Your
definition should provide a Coq program that is the proof of the
conjecture. For example, given
<<
Conjecture logic0 : forall P : Prop,
P -> P.
>>
You would transform it into
<<
Definition logic0 : forall P : Prop,
P -> P
:=
fun (P : Prop) (p : P) => p.
>>
Please note that if you use tactics to find the programs
you will negatively impact your ability to solve similar problems
on the final exam.
*)
Definition logic1 : forall P Q R S T: Prop,
((P /\ Q) /\ R) -> (S /\ T) -> (Q /\ S)
:= fun (P Q R S T: Prop) (pq_and_r: ((P /\ Q) /\ R)) (s_and_t: (S /\ T)) =>
match (pq_and_r, s_and_t) with
| (conj (conj p q) r, conj s t) => conj q s
end.
Definition logic2 : forall P Q R S : Prop,
(P -> Q) -> (R -> S) -> (P \/ R) -> (Q \/ S)
:= fun (P Q R S: Prop) (p_imp_q: P -> Q) (r_imp_s: R -> S) (p_or_r: P \/ R) =>
match p_or_r with
| or_introl p => or_introl (p_imp_q p)
| or_intror r => or_intror (r_imp_s r)
end.
Definition logic3 : forall P Q : Prop,
(P -> Q) -> (((P /\ Q) -> P) /\ (P -> (P /\ Q)))
:= fun (P Q: Prop) (p_imp_q: P -> Q) =>
conj (fun (p_and_q: P /\ Q) => (match p_and_q with
| conj p q => p
end ))
(fun (p: P) => conj p (p_imp_q p)).
Definition logic4 : forall P Q : Prop,
(P -> Q) -> (~~P -> ~~Q)
:= fun (P Q : Prop) (p_imp_q: P -> Q)
(double_neg_p: (P -> False) -> False) (neg_q: Q -> False) =>
double_neg_p (fun (p: P) => neg_q (p_imp_q p)).
End Logic.
(********************************************************************)
(** ** Part 4: Induction *)
(********************************************************************)
Module Induction.
(** For the proofs in this part of the assignment, in addition
to the tactics already used, we found these to be useful:
[induction] and [ring]. *)
(**
Here is an OCaml function:
<<
let rec sumsq_to n =
if n = 0 then 0
else n*n + sumsq_to (n-1)
>>
Prove that
<<
sumsq_to n = n * (n+1) * (2*n + 1) / 6
>>
by completing the following code.
*)
(** [sumsq_to n] is [0*0 + 1*1 + ... + n*n]. *)
Fixpoint sumsq_to (n:nat) : nat :=
match n with
| 0 => n
| S k => n * n + (sumsq_to k)
end.
Lemma sumsq_helper : forall n : nat,
6 * sumsq_to (S n) = 6 * (S n) * (S n) + 6 * sumsq_to n.
Proof.
intros n. simpl. ring.
Qed.
Theorem sumsq : forall n,
6 * sumsq_to n = n * (n+1) * (2*n+1).
Proof.
intros n.
induction n as [ | k IH].
- trivial.
- rewrite -> sumsq_helper.
rewrite -> IH.
ring.
Qed.
(**
Here is a "backwards" definition of lists, which is why we spell
all the names backwards. Unlike OCaml lists, in which as you
pattern match you encounter the first element of the list,
then the second, etc., with these lists, you encounter
the last element of the list, then the next-to-last, etc.
You may not change this definition.
*)
Inductive tsil (A : Type) : Type :=
| lin : tsil A
| snoc : tsil A -> A -> tsil A.
(** Don't worry about understanding these commands. For those who
are curious: they make it possible to omit the [A] argument
when writing constructors. E.g., to write [lin] instead
of [lin A]. *)
Arguments lin {A}.
Arguments snoc {A} xs x.
(**
For example, the list whose first element is [1], second is [2],
and third is [3] would be written
<<
snoc (snoc (snoc lin 1) 2) 3.
>>
*)
(** [length lst] is the number of elements in [lst].
You may not change this definition. *)
Fixpoint length {A : Type} (lst : tsil A) : nat :=
match lst with
| lin => 0
| snoc xs _ => 1 + length xs
end.
(** [app lst1 lst2] contains all the elements of [lst1]
followed by all the elements of [lst2]. "app" is
short for "append". You may not change this definition. *)
Fixpoint app {A : Type} (lst1 lst2: tsil A) : tsil A :=
match lst2 with
| lin => lst1
| snoc xs x => snoc (app lst1 xs) x
end.
(** Prove the next two theorems. You will need to use induction.
Think carefully about which list to induct on, based on how
[tsil] is defined. *)
Theorem app_assoc : forall (A : Type) (lst1 lst2 lst3 : tsil A),
app lst1 (app lst2 lst3) = app (app lst1 lst2) lst3.
Proof.
intros A lst1 lst2 lst3.
induction lst3 as [ | h IH t].
- simpl. trivial.
- simpl. rewrite <- IH. trivial.
Qed.
Theorem app_length : forall (A : Type) (lst1 lst2 : tsil A),
length (app lst1 lst2) = length lst1 + length lst2.
Proof.
intros A lst1 lst2.
induction lst2 as [ | h IH t].
- simpl. trivial.
- simpl. rewrite -> IH. trivial.
Qed.
End Induction.
(********************************************************************)
(** THE END *)
(********************************************************************)
|
#Oktay Saraçoğlu
#160401083
import numpy as np
def asal(kaca_kadar):
asallar = [2]
if kaca_kadar < 2:
return None
elif kaca_kadar == 2:
return asallar
else:
for i in range(3,kaca_kadar,2):
bolundu = False
# karekökün aşağı yuvarlanma ihtimaline karşı, + 1 ekliyoruz.
limit = (i ** 0.5) + 1
for j in asallar:
if i % j == 0:
bolundu=True
break
if j > limit:
break
if bolundu == False:
asallar.append(i)
return asallar
asallar = asal(600)
asallartxt = open("asallar.txt","w")
for i in range(len(asallar)):
asallar[i] = str(asallar[i])
asallartxt.write(asallar[i]+"\n")
def det(l):
n=len(l)
if (n>2):
i=1
t=0
sum=0
while t<=n-1:
d={}
t1=1
while t1<=n-1:
m=0
d[t1]=[]
while m<=n-1:
if (m==t):
u=0
else:
d[t1].append(l[t1][m])
m+=1
t1+=1
l1=[d[x] for x in d]
sum=sum+i*(l[0][t])*(det(l1))
i=i*(-1)
t+=1
return sum
else:
return (l[0][0]*l[1][1]-l[0][1]*l[1][0])
train_sample_number = len(asallar)
X_train = []
Y_train = []
for i in range(train_sample_number):
X_train.append(i+1)
Y_train.append(float(asallar[i]))
degree = int(input("polinom derecesi : "))
matris = np.full((degree+1,degree+1),0).astype("float")
for i in range(degree+1):
for j in range(degree+1):
sum_x = 0
for k in range(train_sample_number):
sum_x += X_train[k]**(i+j)
matris[i][j] = sum_x
sonuc = []
for i in range(degree+1):
sum = 0
for j in range(train_sample_number):
sum = sum + (Y_train[j]*(X_train[j]**i))
sonuc.append(sum)
array = np.array(sonuc)
array.reshape(-1,1)
delta = det(matris)
dete = []
x = np.full((degree+1,degree+1),0).astype("float")
for i in range(degree+1):
for j in range(degree+1):
for k in range(degree+1):
x[j][k] = matris[j][k]
#print(x)
for j in range(degree+1):
x[j][i] = array[j]
#print(det(x))
dete.append(det(x)/delta)
prediction = float(input("tahmin edilecek değer : "))
sonuc = 0
for i in range(degree+1):
sonuc = sonuc + dete[i]*(prediction**i)
print(dete[i])
#print(sonuc)
delta = 1
degree = 4
point = 160401083% 100
fx = 0
def f(degree,fx,dete,point):
for i in range(degree):
fx = fx + dete[i] * (point ** i)
return fx
central_derivation = (f(degree,fx,dete,(point+delta)) - f(degree,fx,dete,(point-delta)))/2*delta
print("Polinom ile türev : ",central_derivation)
def polinomsuzTurev():
x0 =160401083% 100
h = 1
xprime = (float(asallar[x0 - 1 + h]) - float(asallar[x0 - 1 - h])) / (2 * h)
return xprime
turev2 = polinomsuzTurev()
print("Polinomsuz türev ",turev2)
|
Image(XperimentalFarm.jpg, left, thumbnail, 350, left) The UC Davis Student Experimental Farm focuses on organic and Sustainability sustainable agriculture, including seeding, pest control, irrigation, sales, and marketing. Work hours are from 8am to 12pm Monday thru Friday. All new volunteers are welcomed!
On its 20 acres, researchers and students plant a variety of crops to investigate methods of organic farming. Compost is provided by Project Compost, which composts food wastes from the campus in long aerobic windrows off the side of the road here. Some of the equipment runs on biofuel made at the farm.
A portion of the farm is dedicated to the Market Garden, which sells organicallygrown vegetables to the (Universityaffiliated) public and the Coffee House. Produce from the Market Garden is provided in weekly Community Supported Agriculture CSA baskets for a monthly or quarterly subscription. See the official Web site for more details.
To help out on the farm, contact Mark Van Horn and Raoul Adamchak. Many of those working on the farm are students at the University.
Plucky, the Student Farm cat, has taken a liking to hanging out in front of my apartment in the colleges. So if someone is worried, dont be! Users/ChristyMarsden
20110825 15:14:27 nbsp Just an fyi, I asked about becoming a subscriber and the response I got back was that there is a 1.5 year waiting list. Users/Strategiry
|
from uptrop.fresco_cld_err import process_file, CloudVariableStore, MAX_LAT, MAX_LON, MIN_LAT, MIN_LON, DELTA_LAT, DELTA_LON
import numpy as np
import datetime as dt
# I don't like having these here, but they're stuck until I refactor the last bit of fresco_cld_err
out_lon = np.arange(MIN_LON, MAX_LON, DELTA_LON)
out_lat = np.arange(MIN_LAT, MAX_LAT, DELTA_LAT)
def test_process_file():
X, Y = np.meshgrid(out_lon, out_lat, indexing='ij')
start_date = dt.datetime(year=2019, month=10, day=25)
end_date = dt.datetime(year=2019, month=10, day=26)
test_container = CloudVariableStore(X.shape, start_date, end_date)
fresco_path = "test_data/S5P_OFFL_L2__NO2____20191025T085808_20191025T103937_10527_01_010302_20191031T111532.nc"
dlr_path = "test_data/S5P_OFFL_L2__CLOUD__20191025T085808_20191025T103937_10527_01_010107_20191031T081901.nc"
process_file(dlr_path, fresco_path, test_container)
assert test_container.nobs_dlr != 0
assert test_container.nobs_fresco != 0
|
import week_8.Part_B_H0
import group_theory.quotient_group
/-
# A crash course in H¹(G,M)
We stick to the conventions that `G` is a group (or even
a monoid, we never use inversion) and that `M` is a `G`-module,
that is, an additive abelian group with a `G`-action.
A key concept here is that of a cocycle, or a twisted homomorphism.
These things were later renamed 1-cocycles when people realised that higher
cocycles existed; today whenever I say "cocycle" I mean 1-cocycle).
A cocycle is a function `f : G → M` satisfying the axiom
`∀ (g h : G), f (g * h) = f g + g • f h`. These things
naturally form an abelian group under pointwise addition
and negation, by which I mean "operate on the target":
`(f₁ + f₂) g = f₁ g + f₂ g`.
Let `Z1 G M` denote the abelian group of cocycles.
There is a subgroup `B1 G M` of coboundaries, consisting
of the functions `f` for which there exists `m : M`
such that `f g = g • m - m` (note that it is at this point where we
crucially use the fact that `M` is an abelian group and not just an abelian
monoid). One easily checks that all coboundaries are cocycles, and that
coboundaries are a subgroup (you will be doing this below). The
quotient group `H1 G M`, written `H¹(G,M)` by mathematicians, is the main
definition in this file. The first two theorems we shall prove about it here
are that it is functorial (i.e. a map `φ : M →+[G] N` gives
rise to a map `φ.H1_hom : H1 G M →+ H1 G N`), and exact in the
middle (i.e. if `0 → A → B → C → 0` is a short exact sequence
of `G`-modules then the sequence `H1 G A →+ H1 G B →+ H1 G C`
is exact).
Further work would be to verify "inf-res", otherwise known
as the beginning of the long exact
sequence of terms of low degree in the Hochschild-Serre
spectral sequence for group cohomology (i.e.
`0 → H¹(G/N, Aᴺ) → H¹(G, A) → H¹(N, A)` ) and of course one
could go on to define n-cocycles and n-coboundaries (please
get in touch if you're interested in doing this -- I have
ideas about how to set it all up) and to
construct the Hochschild-Serre spectral sequence itself.
I have no doubt that these kinds of results could be turned
into a research paper.
Let's start with a definition of `H1 G M`. First we need
to define cocycles and coboundaries.
-/
-- 1-cocycles as an additive subgroup of the group `Hom(G,M)`
-- a.k.a. `G → M` of functions from `G` to `M`, with group
-- law induced from `M`.
def Z1_subgroup (G M : Type)
[monoid G] [add_comm_group M] [distrib_mul_action G M] : add_subgroup (G → M) :=
{ carrier := { f : G → M | ∀ (g h : G), f (g * h) = f g + g • f h },
zero_mem' := begin
-- the zero map is a cocycle
sorry
end,
add_mem' := begin
sorry,
end,
neg_mem' := begin
sorry,
end }
-- Just like `H0 G M`, we promote this term to a type
structure Z1 (G M : Type)
[monoid G] [add_comm_group M] [distrib_mul_action G M] : Type :=
(to_fun : G → M)
(is_cocycle : ∀ (g h : G), to_fun (g * h) = to_fun g + g • to_fun h)
-- This is a definition so we need to make an API
namespace Z1
-- let G be a group (or a monoid) and let M be a G-module.
variables {G M : Type}
[monoid G] [add_comm_group M] [distrib_mul_action G M]
-- add a coercion from a cocycle to the function G → M
instance : has_coe_to_fun (Z1 G M) :=
{ F := λ _, G → M,
coe := to_fun }
@[simp] lemma coe_apply (to_fun : G → M)
(is_cocycle : ∀ (g h : G), to_fun (g * h) = to_fun g + g • to_fun h) (g : G) :
({ to_fun := to_fun, is_cocycle := is_cocycle } : Z1 G M) g = to_fun g := rfl
-- add a specification for the coercion
lemma spec (a : Z1 G M) : ∀ (g h : G), a (g * h) = a g + g • a h :=
-- this is the last time we'll see `a.is_cocycle`: we'll
-- use `a.spec` from now on because it applies to `⇑a` and not `a.to_fun`.
a.is_cocycle
-- add an extensionality lemma
@[ext] lemma ext (a b : Z1 G M) (h : ∀ g, a g = b g) : a = b :=
begin
cases a, cases b, simp, ext g, exact h g,
end
-- can you prove addition of two cocycles is a cocycle
def add (a b : Z1 G M) : Z1 G M :=
{ to_fun := λ g, a g + b g,
is_cocycle
:= begin
sorry,
end }
instance : has_add (Z1 G M) := ⟨add⟩
@[simp] lemma coe_add (a b : Z1 G M) (g : G) : (a + b) g = a g + b g := rfl
-- the zero cocycle is a cocycle
def zero : Z1 G M :=
{ to_fun := λ g, 0,
is_cocycle
:= begin
sorry,
end
}
instance : has_zero (Z1 G M) := ⟨zero⟩
@[simp] lemma coe_zero (g : G) : (0 : Z1 G M) g = 0 := rfl
-- negation of a cocycle is a cocycle
def neg (a : Z1 G M) : Z1 G M :=
{ to_fun := λ g, -(a g),
is_cocycle
:= begin
sorry
end
}
instance : has_neg (Z1 G M) := ⟨neg⟩
@[simp] lemma coe_neg (a : Z1 G M) (g : G) : (-a) g = -(a g) := rfl
def sub (a b : Z1 G M) : Z1 G M := a + -b
instance : has_sub (Z1 G M) := ⟨sub⟩
-- make the cocycles into a group
instance : add_comm_group (Z1 G M) :=
begin
refine_struct {
add := (+),
zero := (0 : Z1 G M),
neg := has_neg.neg,
sub := has_sub.sub,
-- ignore this, we have to fill in this proof for technical reasons
sub_eq_add_neg := λ _ _, rfl };
-- we now have five goals. Let's use the semicolon trick to work on
-- all of them at once. I'll show you what happens to the proof
-- of associativity, the others are the same mutatis mutandis
-- (but harder to see)
-- *TODO* could documentstring commutativity and remark that
-- they can see associativity using the cursor.
-- ⊢ ∀ (a b c : Z1 G M), a + b + c = a + (b + c)
intros;
-- ⊢ a + b + c = a + (b + c)
ext;
-- ⊢ ⇑(a + b + c) g = ⇑(a + (b + c)) g
simp;
-- ⊢ ⇑a g + ⇑b g + ⇑c g = ⇑a g + (⇑b g + ⇑c g)
abel
-- general additive abelian group tactic which solves
-- goals which are (absolute) identities in every abelian group.
-- Hypotheses are not looked at though. See Chris Hughes' forthcoming
-- Imperial MSc thesis for a new group theory tactic which is to `abel`
-- what `nlinarith` is to `ring`.
end
end Z1
namespace distrib_mul_action_hom
-- The Z1 construction is functorial in the module `M`. Let's construct
-- the relevant function, showing that if `φ : M →+[G] N` then
-- composition induces an additive group homomorphism `Z1 G M → Z1 G N`.
-- Just like `H0` we first define the auxiliary bare function,
-- and then beef it up to an abelian group homomorphism.
variables {G M N : Type} [monoid G]
[add_comm_group M] [distrib_mul_action G M]
[add_comm_group N] [distrib_mul_action G N]
def Z1_hom_underlying_function (φ : M →+[G] N) (f : Z1 G M) : Z1 G N :=
⟨λ g, φ (f g), begin
-- need to prove that this function obtained by composing the cocycle
-- f with the G-module homomorphism φ is also a cocycle.
sorry
end⟩
@[norm_cast]
lemma Z1_hom_underlying_function_coe_comp (φ : M →+[G] N) (f : Z1 G M) (g : G) :
(Z1_hom_underlying_function φ f g : N) = φ (f g) := rfl
def Z1 (φ : M →+[G] N) : Z1 G M →+ Z1 G N :=
-- to make a term of type `X →+ Y` (a group homomorphism) from a function
-- `f : X → Y` and
-- a proof that it preserves addition we use the following constructor:
add_monoid_hom.mk'
-- We now throw in the bare function
(Z1_hom_underlying_function φ)
-- (or could try direct definition:)
-- (λ f, ⟨λ g, φ (f g), begin
-- -- need to prove that this function obtained by composing the cocycle
-- -- f with the G-module homomorphism φ is also a cocycle.
-- intros g h,
-- rw ←φ.map_smul,
-- rw f.spec,
-- simp,
-- end⟩)
-- and now the proof that it preserves addition
begin
intros e f,
ext g,
simp [φ.Z1_hom_underlying_function_coe_comp],
end
-- it's a functor
variables {P : Type} [add_comm_group P] [distrib_mul_action G P]
def map_comp (φ: M →+[G] N) (ψ : N →+[G] P) (z : _root_.Z1 G M) :
(ψ.Z1) ((φ.Z1) z) = (ψ ∘ᵍ φ).Z1 z :=
begin
-- what do you think?
sorry
end
@[simp] lemma Z1_spec (φ : M →+[G] N) (a : _root_.Z1 G M) (g : G) :
φ.Z1 a g = φ (a g) := rfl
@[simp] lemma Z1_spec' (φ : M →+[G] N) (a : _root_.Z1 G M) (g : G) :
(φ.Z1 a : G → N) = ((φ : M → N) ∘ a) := rfl
end distrib_mul_action_hom
section cochain_map
variables (G M : Type) [monoid G] [add_comm_group M]
[distrib_mul_action G M]
def cochain_map : M →+ Z1 G M :=
{ to_fun := λ m, { to_fun := λ g, g • m - m, is_cocycle := begin
simp [mul_smul, smul_sub],
end},
map_zero' := begin
sorry
end,
map_add' := begin
sorry,
end }
@[simp] lemma cochain_map_apply (m : M) (g : G) :
cochain_map G M m g = g • m - m := rfl
end cochain_map
-- question : do we have cokernels? If A B are abelian groups and
-- `f : A → B` is a group hom, how do I make the type coker f`
-- Lean has inbuilt quotients of additive abelian groups by subgroups
-- so we just take the quotient by the range
@[derive add_comm_group]
def H1 (G M : Type) [monoid G] [add_comm_group M]
[distrib_mul_action G M] : Type :=
quotient_add_group.quotient ((cochain_map G M).range)
--quotient_add_group.quotient (B1 G M)
section quotient_stuff
variables {G M : Type} [monoid G] [add_comm_group M]
[distrib_mul_action G M]
def Z1.quotient : Z1 G M →+ H1 G M :=
quotient_add_group.mk' _
lemma ab_H1.ker_quotient : (Z1.quotient).ker = (cochain_map G M).range :=
quotient_add_group.ker_mk _
end quotient_stuff
namespace H1
variables {G M : Type} [monoid G] [add_comm_group M]
[distrib_mul_action G M]
@[elab_as_eliminator]
def induction_on {p : H1 G M → Prop}
(IH : ∀ z : Z1 G M, p (z.quotient)) (h : H1 G M) : p h :=
quot.induction_on h IH
end H1
/-
We have just defined `H1 G M` as a quotient group, and told Lean
to figure out (or "derive") the obvious abelian group structure
on it, which it did.
If you want to go any further, check out the `ideas` directory.
In there we show that if `φ : M →+[G] N` is a `G`-module
hom then `φ` induces a map `H1 G M → H1 G N`. To prove this we will
need to figure out how to define maps from and to quotient group structures.
Just like last week, this is simply a matter of learning the API for the
definition `quotient_add_group.quotient`.
-/
|
(*! Language | Continuation-passing semantics and weakest precondition calculus !*)
Require Import CompactSemantics.
Require Import Magic.
Section CPS.
Context {pos_t var_t fn_name_t rule_name_t reg_t ext_fn_t: Type}.
Context {reg_t_eq_dec: EqDec reg_t}.
Context {R: reg_t -> type}.
Context {Sigma: ext_fn_t -> ExternalSignature}.
Context {REnv: Env reg_t}.
Notation Log := (Log R REnv).
Notation rule := (rule pos_t var_t fn_name_t R Sigma).
Notation action := (action pos_t var_t fn_name_t R Sigma).
Notation scheduler := (scheduler pos_t rule_name_t).
Definition tcontext (sig: tsig var_t) :=
context (fun k_tau => type_denote (snd k_tau)) sig.
Definition acontext (sig argspec: tsig var_t) :=
context (fun k_tau => action sig (snd k_tau)) argspec.
Definition interp_continuation A sig R := option (Log * R * (tcontext sig)) -> A.
Definition action_continuation A sig tau := interp_continuation A sig (type_denote tau).
Definition rule_continuation A := option Log -> A.
Definition scheduler_continuation A := Log -> A.
Definition cycle_continuation A := REnv.(env_t) R -> A.
(* FIXME what's the right terminology for interpreter? *)
Definition action_interpreter A sig := forall (Gamma: tcontext sig) (action_log: Log), A.
Definition interpreter A := forall (log: Log), A.
(* Definition wp_bind (p: Log * tau * (tcontext sig) -> Prop) p' := *)
(* fun res => *)
(* match res with *)
(* | Some res => p res *)
(* | None => p None *)
(* end *)
(* FIXME monad *)
Section Action.
Context (r: REnv.(env_t) R).
Context (sigma: forall f, Sig_denote (Sigma f)).
Section Args.
Context (interp_action_cps:
forall {sig: tsig var_t} {tau}
(a: action sig tau)
{A} (k: action_continuation A sig tau),
action_interpreter A sig).
Fixpoint interp_args'_cps
{sig: tsig var_t}
{argspec: tsig var_t}
(args: acontext sig argspec)
{A} (k: interp_continuation A sig (tcontext argspec))
: action_interpreter A sig :=
match args in context _ argspec return interp_continuation A sig (tcontext argspec) -> action_interpreter A sig with
| CtxEmpty => fun k Gamma l => k (Some (l, CtxEmpty, Gamma))
| @CtxCons _ _ argspec k_tau arg args =>
fun k =>
interp_args'_cps
args
(fun res =>
match res with
| Some (l, ctx, Gamma) =>
interp_action_cps _ _ arg _
(fun res =>
match res with
| Some (l, v, Gamma) => k (Some (l, CtxCons k_tau v ctx, Gamma))
| None => k None
end) Gamma l
| None => k None
end)
end k.
End Args.
Fixpoint interp_action_cps
{sig tau}
(L: Log)
(a: action sig tau)
{A} (k: action_continuation A sig tau)
: action_interpreter A sig :=
let cps {sig tau} a {A} k := @interp_action_cps sig tau L a A k in
match a in TypedSyntax.action _ _ _ _ _ ts tau return (action_continuation A ts tau -> action_interpreter A ts) with
| Fail tau => fun k Gamma l => k None
| Var m => fun k Gamma l => k (Some (l, cassoc m Gamma, Gamma))
| Const cst => fun k Gamma l => k (Some (l, cst, Gamma))
| Seq r1 r2 =>
fun k =>
cps r1 (fun res =>
match res with
| Some (l, v, Gamma) => cps r2 k Gamma l
| None => k None
end)
| Assign m ex =>
fun k =>
cps ex (fun res =>
match res with
| Some (l, v, Gamma) => k (Some (l, Ob, creplace m v Gamma))
| None => k None
end)
| Bind var ex body =>
fun k =>
cps ex (fun res =>
match res with
| Some (l, v, Gamma) =>
cps body (fun res =>
match res with
| Some (l, v, Gamma) =>
k (Some (l, v, ctl Gamma))
| None =>
k None
end) (CtxCons (var, _) v Gamma) l
| None => k None
end)
| If cond tbranch fbranch =>
fun k =>
cps cond (fun res =>
match res with
| Some (l, v, Gamma) =>
if Bits.single v then cps tbranch k Gamma l
else cps fbranch k Gamma l
| None => k None
end)
| Read P0 idx =>
fun k Gamma l =>
if may_read0 L idx then
k (Some (Environments.update
REnv l idx
(fun rl => {| lread0 := true; lread1 := rl.(lread1);
lwrite0 := rl.(lwrite0); lwrite1 := rl.(lwrite1) |}),
REnv.(getenv) r idx,
Gamma))
else k None
| Read P1 idx =>
fun k Gamma l =>
if may_read1 L idx then
k (Some (Environments.update
REnv l idx
(fun rl => {| lread0 := rl.(lread1); lread1 := true;
lwrite0 := rl.(lwrite0); lwrite1 := rl.(lwrite1) |}),
match (REnv.(getenv) l idx).(lwrite0), (REnv.(getenv) L idx).(lwrite0) with
| Some v, _ => v
| _, Some v => v
| _, _ => REnv.(getenv) r idx
end,
Gamma))
else k None
| Write P0 idx value =>
fun k =>
cps value (fun res =>
match res with
| Some (l, v, Gamma) =>
if may_write0 L l idx then
k (Some (Environments.update
REnv l idx
(fun rl => {| lread0 := rl.(lread1); lread1 := rl.(lread1);
lwrite0 := Some v; lwrite1 := rl.(lwrite1) |}),
Ob, Gamma))
else
k None
| None => k None
end)
| Write P1 idx value =>
fun k =>
cps value (fun res =>
match res with
| Some (l, v, Gamma) =>
if may_write1 L l idx then
k (Some (Environments.update
REnv l idx
(fun rl => {| lread0 := rl.(lread1); lread1 := rl.(lread1);
lwrite0 := rl.(lwrite0); lwrite1 := Some v |}),
Ob, Gamma))
else
k None
| None => k None
end)
| Unop fn arg1 =>
fun k =>
cps arg1 (fun res =>
match res with
| Some (l, v, Gamma) =>
k (Some (l, (PrimSpecs.sigma1 fn) v, Gamma))
| None => k None
end)
| Binop fn arg1 arg2 =>
fun k =>
cps arg1 (fun res =>
match res with
| Some (l, v1, Gamma) =>
cps arg2 (fun res =>
match res with
| Some (l, v2, Gamma) =>
k (Some (l, (PrimSpecs.sigma2 fn) v1 v2, Gamma))
| None => k None
end) Gamma l
| None => k None
end)
| ExternalCall fn arg =>
fun k =>
cps arg (fun res =>
match res with
| Some (l, v, Gamma) =>
k (Some (l, (sigma fn) v, Gamma))
| None => k None
end)
| InternalCall fn args body =>
fun k =>
interp_args'_cps (@cps) args
(fun res =>
match res with
| Some (l, argvals, Gamma) =>
cps body (fun res =>
match res with
| Some (l, v, _) =>
k (Some (l, v, Gamma))
| None => k None
end)
argvals l
| None => k None
end)
| APos pos a => fun k => cps a k
end k.
Definition interp_rule_cps (rl: rule) {A} (k: rule_continuation A) : interpreter A :=
fun L =>
interp_action_cps L rl (fun res =>
match res with
| Some (l, _, _) => k (Some l)
| None => k None
end) CtxEmpty log_empty.
End Action.
Section Scheduler.
Context (r: REnv.(env_t) R).
Context (sigma: forall f, Sig_denote (Sigma f)).
Context (rules: rule_name_t -> rule).
Fixpoint interp_scheduler'_cps
(s: scheduler)
{A} (k: scheduler_continuation A)
{struct s} : interpreter A :=
let interp_try rl s1 s2 : interpreter A :=
fun L =>
interp_rule_cps r sigma (rules rl)
(fun res =>
match res with
| Some l => interp_scheduler'_cps s1 k (log_app l L)
| None => interp_scheduler'_cps s2 k L
end) L in
match s with
| Done => k
| Cons r s => interp_try r s s
| Try r s1 s2 => interp_try r s1 s2
| SPos _ s => interp_scheduler'_cps s k
end.
Definition interp_scheduler_cps
(s: scheduler)
{A} (k: scheduler_continuation A) : A :=
interp_scheduler'_cps s k log_empty.
End Scheduler.
Definition interp_cycle_cps (sigma: forall f, Sig_denote (Sigma f)) (rules: rule_name_t -> rule)
(s: scheduler) (r: REnv.(env_t) R)
{A} (k: _ -> A) :=
interp_scheduler_cps r sigma rules s (fun L => k (commit_update r L)).
Section WP.
Context (r: REnv.(env_t) R).
Context (sigma: forall f, Sig_denote (Sigma f)).
Definition action_precondition := action_interpreter Prop.
Definition action_postcondition := action_continuation Prop.
Definition precondition := interpreter Prop.
Definition rule_postcondition := rule_continuation Prop.
Definition scheduler_postcondition := scheduler_continuation Prop.
Definition cycle_postcondition := cycle_continuation Prop.
Definition wp_action {sig tau} (L: Log) (a: action sig tau) (post: action_postcondition sig tau) : action_precondition sig :=
interp_action_cps r sigma L a post.
Definition wp_rule (rl: rule) (post: rule_postcondition) : precondition :=
interp_rule_cps r sigma rl post.
Definition wp_scheduler (rules: rule_name_t -> rule) (s: scheduler) (post: scheduler_postcondition) : Prop :=
interp_scheduler_cps r sigma rules s post.
Definition wp_cycle (rules: rule_name_t -> rule) (s: scheduler) r (post: cycle_postcondition) : Prop :=
interp_cycle_cps sigma rules s r post.
End WP.
Section Proofs.
Context (r: REnv.(env_t) R).
Context (sigma: forall f, Sig_denote (Sigma f)).
Section Args.
Context (IHa : forall (sig : tsig var_t) (tau : type) (L : Log) (a : action sig tau) (A : Type) (k : option (Log * tau * tcontext sig) -> A)
(Gamma : tcontext sig) (l : Log), interp_action_cps r sigma L a k Gamma l = k (interp_action r sigma Gamma L l a)).
Lemma interp_args'_cps_correct :
forall L {sig} {argspec} args Gamma l {A} (k: interp_continuation A sig (tcontext argspec)),
interp_args'_cps (fun sig tau a A k => interp_action_cps r sigma L a k) args k Gamma l =
k (interp_args r sigma Gamma L l args).
Proof.
induction args; cbn; intros.
- reflexivity.
- rewrite IHargs.
destruct (interp_args r sigma Gamma L l args) as [((?, ?), ?) | ]; cbn; try reflexivity.
rewrite IHa.
destruct (interp_action r sigma _ L _ _) as [((?, ?), ?) | ]; cbn; reflexivity.
Defined.
End Args.
Lemma interp_action_cps_correct:
forall {sig: tsig var_t}
{tau}
(L: Log)
(a: action sig tau)
{A} (k: _ -> A)
(Gamma: tcontext sig)
(l: Log),
interp_action_cps r sigma L a k Gamma l =
k (interp_action r sigma Gamma L l a).
Proof.
fix IHa 4; destruct a; cbn; intros.
all: repeat match goal with
| _ => progress simpl
| [ H: context[_ = _] |- _ ] => rewrite H
| [ |- context[interp_action] ] => destruct interp_action as [((?, ?), ?) | ]
| [ |- context[match ?x with _ => _ end] ] => destruct x
| _ => rewrite interp_args'_cps_correct
| _ => reflexivity || assumption
end.
Qed.
Lemma interp_action_cps_correct_rev:
forall {sig: tsig var_t}
{tau}
(L: Log)
(a: action sig tau)
(Gamma: tcontext sig)
(l: Log),
interp_action r sigma Gamma L l a =
interp_action_cps r sigma L a id Gamma l.
Proof.
intros; rewrite interp_action_cps_correct; reflexivity.
Qed.
Lemma interp_rule_cps_correct:
forall (L: Log)
(a: rule)
{A} (k: _ -> A),
interp_rule_cps r sigma a k L =
k (interp_rule r sigma L a).
Proof.
unfold interp_rule, interp_rule_cps; intros.
rewrite interp_action_cps_correct.
destruct interp_action as [((?, ?), ?) | ]; reflexivity.
Qed.
Lemma interp_rule_cps_correct_rev:
forall (L: Log)
(a: rule),
interp_rule r sigma L a =
interp_rule_cps r sigma a id L.
Proof.
intros; rewrite interp_rule_cps_correct; reflexivity.
Qed.
Lemma interp_scheduler'_cps_correct:
forall (rules: rule_name_t -> rule)
(s: scheduler)
(L: Log)
{A} (k: _ -> A),
interp_scheduler'_cps r sigma rules s k L =
k (interp_scheduler' r sigma rules L s).
Proof.
induction s; cbn; intros.
all: repeat match goal with
| _ => progress simpl
| _ => rewrite interp_rule_cps_correct
| [ H: context[_ = _] |- _ ] => rewrite H
| [ |- context[interp_rule] ] => destruct interp_action as [((?, ?), ?) | ]
| [ |- context[match ?x with _ => _ end] ] => destruct x
| _ => reflexivity
end.
Qed.
Lemma interp_scheduler_cps_correct:
forall (rules: rule_name_t -> rule)
(s: scheduler)
{A} (k: _ -> A),
interp_scheduler_cps r sigma rules s k =
k (interp_scheduler r sigma rules s).
Proof.
intros; apply interp_scheduler'_cps_correct.
Qed.
Lemma interp_cycle_cps_correct:
forall (rules: rule_name_t -> rule)
(s: scheduler)
{A} (k: _ -> A),
interp_cycle_cps sigma rules s r k =
k (interp_cycle sigma rules s r).
Proof.
unfold interp_cycle, interp_cycle_cps; intros; rewrite interp_scheduler_cps_correct.
reflexivity.
Qed.
Lemma interp_cycle_cps_correct_rev:
forall (rules: rule_name_t -> rule)
(s: scheduler),
interp_cycle sigma rules s r =
interp_cycle_cps sigma rules s r id.
Proof.
intros; rewrite interp_cycle_cps_correct; reflexivity.
Qed.
Section WP.
Lemma wp_action_correct:
forall {sig: tsig var_t}
{tau}
(Gamma: tcontext sig)
(L: Log)
(l: Log)
(a: action sig tau)
(post: action_postcondition sig tau),
wp_action r sigma L a post Gamma l <->
post (interp_action r sigma Gamma L l a).
Proof.
intros; unfold wp_action; rewrite interp_action_cps_correct; reflexivity.
Qed.
Lemma wp_rule_correct:
forall (L: Log)
(rl: rule)
(post: rule_postcondition),
wp_rule r sigma rl post L <->
post (interp_rule r sigma L rl).
Proof.
intros; unfold wp_rule; rewrite interp_rule_cps_correct; reflexivity.
Qed.
Lemma wp_scheduler_correct:
forall (rules: rule_name_t -> rule)
(s: scheduler)
(post: scheduler_postcondition),
wp_scheduler r sigma rules s post <->
post (interp_scheduler r sigma rules s).
Proof.
intros; unfold wp_scheduler; rewrite interp_scheduler_cps_correct; reflexivity.
Qed.
Lemma wp_cycle_correct:
forall (rules: rule_name_t -> rule)
(s: scheduler)
(post: cycle_postcondition),
wp_cycle sigma rules s r post <->
post (interp_cycle sigma rules s r).
Proof.
intros; unfold wp_cycle; rewrite interp_cycle_cps_correct; reflexivity.
Qed.
End WP.
End Proofs.
End CPS.
Arguments interp_action_cps
{pos_t var_t fn_name_t reg_t ext_fn_t}
{R Sigma} {REnv} r sigma
{sig tau} L !a / A k.
Arguments interp_rule_cps
{pos_t var_t fn_name_t reg_t ext_fn_t}
{R Sigma} {REnv} r sigma
!rl / {A} k.
Arguments interp_scheduler_cps
{pos_t var_t fn_name_t rule_name_t reg_t ext_fn_t}
{R Sigma} {REnv} r sigma
rules !s / {A} k : assert.
Arguments interp_cycle_cps
{pos_t var_t fn_name_t rule_name_t reg_t ext_fn_t}
{R Sigma} {REnv} sigma
rules !s r / {A} k : assert.
Arguments wp_action
{pos_t var_t fn_name_t reg_t ext_fn_t}
{R Sigma} {REnv} r sigma
{sig tau} L !a post / Gamma action_log : assert.
Arguments wp_rule
{pos_t var_t fn_name_t reg_t ext_fn_t}
{R Sigma} {REnv} r sigma
!rl / post.
Arguments wp_scheduler
{pos_t var_t fn_name_t rule_name_t reg_t ext_fn_t}
{R Sigma} {REnv} r sigma
rules !s / post : assert.
Arguments wp_cycle
{pos_t var_t fn_name_t rule_name_t reg_t ext_fn_t}
{R Sigma} {REnv} sigma
rules !s r / post : assert.
|
State Before: α : Type u_2
β : Type u_1
l : Filter α
k f g g' : α → β
inst✝² : TopologicalSpace β
inst✝¹ : CommSemiring β
inst✝ : ContinuousMul β
hf : SuperpolynomialDecay l k f
c : β
z : ℕ
⊢ Tendsto (fun a => k a ^ z * (fun n => f n * c) a) l (𝓝 0) State After: no goals Tactic: simpa only [← mul_assoc, MulZeroClass.zero_mul] using Tendsto.mul_const c (hf z)
|
The imaginary part of an integer is zero.
|
State Before: α : Type u_1
s✝ t : Set α
a : α
inst✝¹ : Group α
inst✝ : StarSemigroup α
s : Set α
⊢ s⁻¹⋆ = s⋆⁻¹ State After: case h
α : Type u_1
s✝ t : Set α
a : α
inst✝¹ : Group α
inst✝ : StarSemigroup α
s : Set α
x✝ : α
⊢ x✝ ∈ s⁻¹⋆ ↔ x✝ ∈ s⋆⁻¹ Tactic: ext State Before: case h
α : Type u_1
s✝ t : Set α
a : α
inst✝¹ : Group α
inst✝ : StarSemigroup α
s : Set α
x✝ : α
⊢ x✝ ∈ s⁻¹⋆ ↔ x✝ ∈ s⋆⁻¹ State After: no goals Tactic: simp only [mem_star, mem_inv, star_inv]
|
```python
from ngames.evaluation.extensivegames import ExtensiveFormGame, plot_game,\
subgame_perfect_equilibrium, DFS_equilibria_paths
```
# Market game
From S. Fatima, S. Kraus, M. Wooldridge, Principles of Automated Negotiation,
Cambridge University Press, 2014, see Figure 3.3.
```python
m = ExtensiveFormGame(title='Market game')
m.add_players('firm 1', 'firm 2')
m.add_node(1, 'chance', is_root=True)
m.add_node(2, 'firm 1')
m.add_node(3, 'firm 1')
for i in range(4, 8):
m.add_node(i, 'firm 2')
for i in range(8, 16):
m.add_node(i)
m.add_edge(1, 2, label='small')
m.add_edge(1, 3, label='large')
m.add_edge(2, 4, label='L')
m.add_edge(2, 5, label='H')
m.add_edge(3, 6, label='L')
m.add_edge(3, 7, label='H')
m.add_edge(4, 8, label='L')
m.add_edge(4, 9, label='H')
m.add_edge(5, 10, label='L')
m.add_edge(5, 11, label='H')
m.add_edge(6, 12, label='L')
m.add_edge(6, 13, label='H')
m.add_edge(7, 14, label='L')
m.add_edge(7, 15, label='H')
m.set_information_partition('firm 2', {4, 6}, {5, 7})
m.set_information_partition('firm 1', {2, 3})
m.set_uniform_probability_distribution(1)
m.set_utility(8, {'firm 1': 16, 'firm 2': 8})
m.set_utility(9, {'firm 1': 8, 'firm 2': 16})
m.set_utility(10, {'firm 1': 20, 'firm 2': 4})
m.set_utility(11, {'firm 1': 16, 'firm 2': 8})
m.set_utility(12, {'firm 1': 30, 'firm 2': 10})
m.set_utility(13, {'firm 1': 28, 'firm 2': 12})
m.set_utility(14, {'firm 1': 16, 'firm 2': 24})
m.set_utility(15, {'firm 1': 24, 'firm 2': 16})
position_colors = {'firm 1': 'cyan', 'firm 2': 'red'}
my_fig_kwargs = dict(figsize=(12, 12), frameon=False)
my_node_kwargs = dict(font_size=24, node_size=2000, edgecolors='k',
linewidths=3)
my_edge_kwargs = dict(arrowsize=25, width=5)
my_edge_labels_kwargs = dict(font_size=24)
my_patch_kwargs = dict(linewidth=3)
my_legend_kwargs = dict(fontsize=24, loc='upper right', edgecolor='white')
my_utility_label_kwargs = dict(horizontalalignment='center', fontsize=20)
my_info_sets_kwargs = dict(linestyle='--', linewidth=3)
fig = plot_game(m,
position_colors,
fig_kwargs=my_fig_kwargs,
node_kwargs=my_node_kwargs,
edge_kwargs=my_edge_kwargs,
edge_labels_kwargs=my_edge_labels_kwargs,
patch_kwargs=my_patch_kwargs,
legend_kwargs=my_legend_kwargs,
utility_label_kwargs=my_utility_label_kwargs,
utility_label_shift=0.075,
info_sets_kwargs=my_info_sets_kwargs)
```
# Prisoner's Dilemma
Classical one-shot Prioner's Dilemma, but in extensive form.
```python
pd = ExtensiveFormGame(name='Prisoners Dilemma')
pd.add_players('player 1', 'player 2')
pd.add_node(1, 'player 1', is_root=True)
pd.add_node(2, 'player 2')
pd.add_node(3, 'player 2')
for i in range(4, 8):
pd.add_node(i)
pd.add_edge(1, 2, 'cooperate')
pd.add_edge(1, 3, 'defect')
pd.add_edge(2, 4, 'cooperate')
pd.add_edge(2, 5, 'defect')
pd.add_edge(3, 6, 'cooperate')
pd.add_edge(3, 7, 'defect')
pd.set_information_partition('player 2', {2, 3})
pd.set_utility(4, {'player 1': 6, 'player 2': 6})
pd.set_utility(5, {'player 1': 0, 'player 2': 9})
pd.set_utility(6, {'player 1': 9, 'player 2': 0})
pd.set_utility(7, {'player 1': 3, 'player 2': 3})
position_colors = {'player 1': 'aquamarine', 'player 2': 'lightcoral'}
my_fig_kwargs = dict(figsize=(12, 12), tight_layout=True)
my_node_kwargs = dict(font_size=36, node_size=4500, edgecolors='k',
linewidths=3)
my_edge_kwargs = dict(arrowsize=50, width=5)
my_edge_labels_kwargs = dict(font_size=32)
my_patch_kwargs = dict(linewidth=3)
my_legend_kwargs = dict(fontsize=32, loc='upper left', edgecolor='white')
my_utility_label_kwargs = dict(horizontalalignment='center', fontsize=28,
weight='bold')
my_info_sets_kwargs = dict(linestyle='--', linewidth=3)
fig = plot_game(pd,
position_colors,
fig_kwargs=my_fig_kwargs,
node_kwargs=my_node_kwargs,
edge_kwargs=my_edge_kwargs,
edge_labels_kwargs=my_edge_labels_kwargs,
patch_kwargs=my_patch_kwargs,
legend_kwargs=my_legend_kwargs,
utility_label_kwargs=my_utility_label_kwargs,
decimals=0,
utility_label_shift=0.06,
info_sets_kwargs=my_info_sets_kwargs)
```
# Example of information rules
```python
example = ExtensiveFormGame()
example.add_players('position 1', 'position 2')
example.add_node(1, 'position 1', is_root=True)
example.add_node(2, 'position 2')
example.add_node(3, 'position 2')
example.add_edge(1, 2, label='do A')
example.add_edge(1, 3, label='do B')
example.set_information_partition('position 2', {2, 3})
position_colors = {'position 1': 'green', 'position 2': 'cyan'}
my_fig_kwargs['figsize'] = (6, 6)
my_legend_kwargs['loc'] = 'upper left'
my_legend_kwargs['fontsize'] = 20
my_patch_kwargs['linewidth'] = 2
fig = plot_game(example,
position_colors,
utility_label_shift=0.,
fig_kwargs=my_fig_kwargs,
node_kwargs=my_node_kwargs,
edge_kwargs=my_edge_kwargs,
edge_labels_kwargs=my_edge_labels_kwargs,
patch_kwargs=my_patch_kwargs,
legend_kwargs=my_legend_kwargs,
utility_label_kwargs=my_utility_label_kwargs,
info_sets_kwargs=my_info_sets_kwargs)
```
```python
example.set_information_partition('position 2', {2}, {3})
example.is_perfect_information = True
fig = plot_game(example,
position_colors,
utility_label_shift=0.,
fig_kwargs=my_fig_kwargs,
node_kwargs=my_node_kwargs,
edge_kwargs=my_edge_kwargs,
edge_labels_kwargs=my_edge_labels_kwargs,
patch_kwargs=my_patch_kwargs,
legend_kwargs=my_legend_kwargs,
utility_label_kwargs=my_utility_label_kwargs,
info_sets_kwargs=my_info_sets_kwargs)
```
# Ostrom's fishing game
```python
fishing_game = ExtensiveFormGame(title='Fishing game C1')
# add the two positions for the two fishers
fishing_game.add_players('fisher 1', 'fisher 2')
# add the nodes to the graph
fishing_game.add_node(1, player_turn='fisher 1', is_root=True)
fishing_game.add_node(2, player_turn='fisher 2')
fishing_game.add_node(3, player_turn='fisher 2')
fishing_game.add_node(4, player_turn='fisher 1')
fishing_game.add_node(5)
fishing_game.add_node(6)
fishing_game.add_node(7, player_turn='fisher 1')
fishing_game.add_node(8, player_turn='fisher 2')
fishing_game.add_node(9, player_turn='fisher 2')
fishing_game.add_node(10, player_turn='fisher 2')
fishing_game.add_node(11, player_turn='fisher 2')
fishing_game.add_node(12, player_turn='chance')
fishing_game.add_node(13)
fishing_game.add_node(14)
fishing_game.add_node(15, player_turn='chance')
fishing_game.add_node(16, player_turn='chance')
fishing_game.add_node(17)
fishing_game.add_node(18)
fishing_game.add_node(19, player_turn='chance')
for i in range(20, 28):
fishing_game.add_node(i)
# add the edges to the graph
fishing_game.add_edge(1, 2, label='go to spot 1')
fishing_game.add_edge(1, 3, label='go to spot 2')
fishing_game.add_edge(2, 4, label='go to spot 1')
fishing_game.add_edge(2, 5, label='go to spot 2')
fishing_game.add_edge(3, 6, label='go to spot 1')
fishing_game.add_edge(3, 7, label='go to spot 2')
fishing_game.add_edge(4, 8, label='stay')
fishing_game.add_edge(4, 9, label='leave')
fishing_game.add_edge(7, 10, label='stay')
fishing_game.add_edge(7, 11, label='leave')
fishing_game.add_edge(8, 12, label='stay')
fishing_game.add_edge(8, 13, label='leave')
fishing_game.add_edge(9, 14, label='stay')
fishing_game.add_edge(9, 15, label='leave')
fishing_game.add_edge(10, 16, label='stay')
fishing_game.add_edge(10, 17, label='leave')
fishing_game.add_edge(11, 18, label='stay')
fishing_game.add_edge(11, 19, label='leave')
fishing_game.add_edge(12, 20, label='1 wins')
fishing_game.add_edge(12, 21, label='2 wins')
fishing_game.add_edge(15, 22, label='1 wins')
fishing_game.add_edge(15, 23, label='2 wins')
fishing_game.add_edge(16, 24, label='1 wins')
fishing_game.add_edge(16, 25, label='2 wins')
fishing_game.add_edge(19, 26, label='1 wins')
fishing_game.add_edge(19, 27, label='2 wins')
# add imperfect information, equivalent to having players take the actions
# simultaneously
fishing_game.set_information_partition('fisher 2', {2, 3}, {8, 9}, {10, 11})
```
## Rule configuration C1 (default)
See page 85 in E. Ostrom, R. Gardner, J. Walker, Rules, Games, and
Common-Pool Resources, The University of Michigan Press, Ann Arbor, 1994.
https://doi.org/10.3998/mpub.9739.
First, build the default situation as an extensive-form game. Two fishers
competing for two fishing spots, the first spot being better than the other.
The utilities and probability at chance nodes of the game are parametrized
with the following variables:
* $v_i$: economical value of the $i$-th spot. It is assumed that the first
spot is the better one, so $v_1>v_2$.
* $P$: the probability that fisher 1 wins the fight if one happens. It is
assumed that fisher 1 is the stronger one, so $P>0.5$. Then, the probability
that fisher 2 wins a fight is $(1-P)<0.5$.
* $c$: cost of travel between the two spots.
* $d$: damage incurred to the loser of the fight.
$w(j, i)$ denotes the *expected* value for fisher $j$ of having a fight at
spot $i$:
\begin{align}
w(1,i) =& Pv_i+(1-P)(-d)\\
w(2,i) =& (1-P)v_i+P(-d)
\end{align}
Start assigning utilities with made-up values.
```python
# parameters
v1, v2 = 5, 3
P = 0.6
c = 0.5
d = 2
def set_parameters(v1: float, v2: float, P: float, c: float, d: float,
game: ExtensiveFormGame):
w11 = P*v1+(1-P)*(-d)
w12 = P*v2+(1-P)*(-d)
w21 = (1-P)*v1+P*(-d)
w22 = (1-P)*v2+P*(-d)
# set utility parameters and probabilities over outgoing edges at
# chance nodes
game.set_utility(5, {'fisher 1': v1, 'fisher 2': v2})
game.set_utility(6, {'fisher 1': v2, 'fisher 2': v1})
game.set_utility(13, {'fisher 1': v1, 'fisher 2': v2-c})
game.set_utility(14, {'fisher 1': v2-c, 'fisher 2': v1})
game.set_utility(17, {'fisher 1': v2, 'fisher 2': v1-c})
game.set_utility(18, {'fisher 1': v2-c, 'fisher 2': v1})
game.set_probability_distribution(12, {(12, 20): P, (12, 21): (1-P)})
game.set_probability_distribution(15, {(15, 22): P, (15, 23): (1-P)})
game.set_probability_distribution(16, {(16, 24): P, (16, 25): (1-P)})
game.set_probability_distribution(19, {(19, 26): P, (19, 27): (1-P)})
game.set_utility(20, {'fisher 1': v1, 'fisher 2': -d})
game.set_utility(21, {'fisher 1': -d, 'fisher 2': v1})
game.set_utility(22, {'fisher 1': v2-c, 'fisher 2': -c-d})
game.set_utility(23, {'fisher 1': -c-d, 'fisher 2': v2-c})
game.set_utility(24, {'fisher 1': v2, 'fisher 2': -d})
game.set_utility(25, {'fisher 1': -d, 'fisher 2': v2})
game.set_utility(26, {'fisher 1': v1-c, 'fisher 2': -c-d})
game.set_utility(27, {'fisher 1': -c-d, 'fisher 2': v1-c})
return (w11, w12), (w21, w22)
_ = set_parameters(v1, v2, P, c, d, fishing_game)
# default keywords for rendering the figure
my_fig_kwargs = dict(figsize=(45, 24), frameon=False)
my_node_kwargs = dict(font_size=30, node_size=2250, edgecolors='k',
linewidths=2)
my_edge_kwargs = dict(arrowsize=25, width=3)
my_edge_labels_kwargs = dict(font_size=20)
my_patch_kwargs = dict(linewidth=2)
my_legend_kwargs = dict(fontsize=24, loc='upper right', edgecolor='white')
my_utility_label_kwargs = dict(horizontalalignment='center', fontsize=24)
my_info_sets_kwargs = dict(linestyle='--', linewidth=3)
position_colors = {'fisher 1': 'aquamarine', 'fisher 2': 'greenyellow'}
fig = plot_game(fishing_game,
position_colors,
fig_kwargs=my_fig_kwargs,
node_kwargs=my_node_kwargs,
edge_kwargs=my_edge_kwargs,
edge_labels_kwargs=my_edge_labels_kwargs,
patch_kwargs=my_patch_kwargs,
legend_kwargs=my_legend_kwargs,
utility_label_kwargs=my_utility_label_kwargs,
utility_label_shift=0.07,
info_sets_kwargs=my_info_sets_kwargs)
```
Compute the subgame perfect equilibria strategy:
```python
spe = subgame_perfect_equilibrium(fishing_game)
```
Compute the paths of play that arise from following the subgame perfect
equilibria strategy, alongside with the probability of being played. It is
necessary to include probabilities since there are chance nodes:
```python
path_store = []
DFS_equilibria_paths(fishing_game, fishing_game.game_tree.root, spe, [], 1,
path_store)
print("Path -- Probability")
print("-------------------")
for (path, prob) in path_store:
print("{} -- {:.2f}".format(path, prob))
```
Path -- Probability
-------------------
[1, 'go to spot 1', 2, 'go to spot 2', 5] -- 1.00
In order to introduce the later changes to the game in the other rule
configurations, establish that the utility at the terminal nodes can be
computed as:
*Utility* = (*payoff of the outcome*) + (*cost of the path of actions to
get there*)
__Costs assigned to actions__:
| Action | Cost |
|--------------|----------|
| Go to spot 1 | 0 |
| Go to spot 2 | 0 |
| Stay | 0 |
| Leave | -c (c>0) |
__Costs assigned to payoffs__:
| Outcome | Payoff |
|---------|--------|
| Fish at spot 1 | $v_1$ |
| Fish at spot 2 | $v_2$ |
| Looser of fight* | -d (d>0) |
*: in more general terms, a fight can be encompassed under the term
"competition". This will make the transition from C1 to C2 easier.
To reproduce the analysis of the game by Ostrom in an automated way, I use
backward induction. This is not technically correct because the game is
imperfect information, but for the moment the focus is not so much on the
correctness of the solution concept.
The first three cases fulfill $$w(1, 1)>v_2-c$$ and $w(2, 1)>v_2-c$:
* Case 1: $w(1,1)>v_2;\;w(2,1)>v_2$
* Case 2: $w(1,1)>v_2;\;w(2,1)<v_2$
* Case 3: $w(1,1)<v_2;\;w(2,1)<v_2$
The other two cases are:
* Case 4: $w(1,1)>v_2-c;\;w(2,1)<v_2-c$
* Case 5: $w(1,1)<v_2-c;\;w(2,1)<v_2-c$
### Case C1-1
$w(1,1)>v_2;\;w(2,1)>v_2$
As predicted by Ostrom, in the equilibrium both fishers go to spot 1,
stay there and fight.
```python
v1, v2 = 10, 2
P = 0.55
c = 1
d = 2
(w11, w12), (w21, w22) = set_parameters(v1, v2, P, c, d, fishing_game)
print("w(1,1) = {:.1f}".format(w11))
print("w(2,1) = {:.1f}".format(w21))
print("v2 = {:.1f}".format(v2))
spe = subgame_perfect_equilibrium(fishing_game)
path_store = []
DFS_equilibria_paths(fishing_game, fishing_game.game_tree.root, spe, [], 1,
path_store)
print("\nPath -- Probability")
print("-------------------")
for (path, prob) in path_store:
print("{} -- {:.2f}".format(path, prob))
```
w(1,1) = 4.6
w(2,1) = 3.4
v2 = 2.0
Path -- Probability
-------------------
[1, 'go to spot 1', 2, 'go to spot 1', 4, 'stay', 8, 'stay', 12, '1 wins', 20] -- 0.55
[1, 'go to spot 1', 2, 'go to spot 1', 4, 'stay', 8, 'stay', 12, '2 wins', 21] -- 0.45
### Case C1-2
$w(1,1)>v_2;\;w(2,1)<v_2$
As predicted by Ostrom, in the equilibrium the stronger fisher 1 ($P>0.5$)
goes to spot 1, the weaker fisher 2 goes to spot 2.
```python
v1, v2 = 10, 4
P = 0.6
c = 1
d = 2
(w11, w12), (w21, w22) = set_parameters(v1, v2, P, c, d, fishing_game)
print("w(1,1) = {:.1f}".format(w11))
print("w(2,1) = {:.1f}".format(w21))
print("v2 = {:.1f}".format(v2))
spe = subgame_perfect_equilibrium(fishing_game)
path_store = []
DFS_equilibria_paths(fishing_game, fishing_game.game_tree.root, spe, [], 1,
path_store)
print("\nPath -- Probability")
print("-------------------")
for (path, prob) in path_store:
print("{} -- {:.2f}".format(path, prob))
```
### Case C1-3
$w(1,1)<v_2;\;w(2,1)<v_2$
As predicted by Ostrom, again in the equilibrium the stronger fisher 1
($P>0.5$) goes to spot 1, the weaker fisher 2 goes to spot 2.
Ostrom points out that there is another pure strategy equilibrium in which
fisher 1 goes to the worse spot 2, and fisher 2 goes to the better spot 1.
However, that outcome is part of a Nash equilibrium that is not sequentially
rational (?).
```python
v1, v2 = 6, 4
P = 0.6
c = 1
d = 2
(w11, w12), (w21, w22) = set_parameters(v1, v2, P, c, d, fishing_game)
print("w(1,1) = {:.1f}".format(w11))
print("w(2,1) = {:.1f}".format(w21))
print("v2 = {:.1f}".format(v2))
spe = subgame_perfect_equilibrium(fishing_game)
path_store = []
DFS_equilibria_paths(fishing_game, fishing_game.game_tree.root, spe, [], 1,
path_store)
print("\nPath -- Probability")
print("-------------------")
for (path, prob) in path_store:
print("{} -- {:.2f}".format(path, prob))
```
### Case C1-4
$w(1,1)>v_2-c;\;w(2,1)<v_2-c$
As predicted by Ostrom, again in the equilibrium the stronger fisher 1 goes
to spot 1, the weaker fisher 2 goes to spot 2.
```python
v1, v2 = 10, 5
P = 0.6
c = 1
d = 2
(w11, w12), (w21, w22) = set_parameters(v1, v2, P, c, d, fishing_game)
print("w(1,1) = {:.1f}".format(w11))
print("w(2,1) = {:.1f}".format(w21))
print("v2-c = {:.1f}".format(v2-c))
spe = subgame_perfect_equilibrium(fishing_game)
path_store = []
DFS_equilibria_paths(fishing_game, fishing_game.game_tree.root, spe, [], 1,
path_store)
print("\nPath -- Probability")
print("-------------------")
for (path, prob) in path_store:
print("{} -- {:.2f}".format(path, prob))
```
### Case C1-5
$w(1,1)<v_2-c;\;w(2,1)<v_2-c$
As predicted by Ostrom, again in the equilibrium the stronger fisher 1 goes
to spot 1, the weaker fisher 2 goes to spot 2.
```python
v1, v2 = 7, 5
P = 0.6
c = 1
d = 2
(w11, w12), (w21, w22) = set_parameters(v1, v2, P, c, d, fishing_game)
print("w(1,1) = {:.1f}".format(w11))
print("w(2,1) = {:.1f}".format(w21))
print("v2-c = {:.1f}".format(v2-c))
spe = subgame_perfect_equilibrium(fishing_game)
path_store = []
DFS_equilibria_paths(fishing_game, fishing_game.game_tree.root, spe, [], 1,
path_store)
print("\nPath -- Probability")
print("-------------------")
for (path, prob) in path_store:
print("{} -- {:.2f}".format(path, prob))
```
## Rule configuration C2
First fisher in arrival has the right to fish at that spot for the remaining
of the day.
```python
fishing_game_C2 = ExtensiveFormGame(title='Fishing game C2')
# add the two positions for the two fishers
fishing_game_C2.add_players('fisher 1', 'fisher 2')
# add the nodes to the graph
fishing_game_C2.add_node(1, player_turn='fisher 1', is_root=True)
fishing_game_C2.add_node(2, player_turn='fisher 2')
fishing_game_C2.add_node(3, player_turn='fisher 2')
fishing_game_C2.add_node(4, player_turn='chance')
fishing_game_C2.add_node(5)
fishing_game_C2.add_node(6)
fishing_game_C2.add_node(7, player_turn='chance')
fishing_game_C2.add_node(8, player_turn='fisher 2')
fishing_game_C2.add_node(9, player_turn='fisher 1')
fishing_game_C2.add_node(10, player_turn='fisher 2')
fishing_game_C2.add_node(11, player_turn='fisher 1')
for i in range(12, 15+1):
fishing_game_C2.add_node(i)
# add the edges to the graph
fishing_game_C2.add_edge(1, 2, label='go to spot 1')
fishing_game_C2.add_edge(1, 3, label='go to spot 2')
fishing_game_C2.add_edge(2, 4, label='go to spot 1')
fishing_game_C2.add_edge(2, 5, label='go to spot 2')
fishing_game_C2.add_edge(3, 6, label='go to spot 1')
fishing_game_C2.add_edge(3, 7, label='go to spot 2')
fishing_game_C2.add_edge(4, 8, label='1 first')
fishing_game_C2.add_edge(4, 9, label='2 first')
fishing_game_C2.add_edge(7, 10, label='1 first')
fishing_game_C2.add_edge(7, 11, label='2 first')
fishing_game_C2.add_edge(8, 12, label='leave')
fishing_game_C2.add_edge(9, 13, label='leave')
fishing_game_C2.add_edge(10, 14, label='leave')
fishing_game_C2.add_edge(11, 15, label='leave')
# add imperfect information, equivalent to having players take the actions
# simultaneously
fishing_game_C2.set_information_partition('fisher 2', {2, 3}, {8}, {10})
```
The utilities and probability at chance nodes of the game are parametrized
with the following variables:
* $v_i$: economical value of the $i$-th spot. It is assumed that the first
spot is the better one, so $v_1>v_2$.
* $P$: the probability that fisher 1 gets to a spot first. It is assumed
that fisher 1 has better technology than fisher 2, and hence $P>0.5$.
* $c$: cost of travel between the two spots.
$w(j, i)$ denotes the *expected* value for fisher $j$ of spot $i$ if the
other fisher has gone there too:
\begin{align}
w(1,i) =& Pv_i+(1-P)(v_{-i}-c)\\
w(2,i) =& (1-P)v_i+P(v_{-i}-c)
\end{align}
```python
# parameters
v1, v2 = 5, 3
P = 0.6
c = 0.5
def set_parameters_C2(v1: float, v2: float, P: float, c: float,
game: ExtensiveFormGame):
w11 = P*v1+(1-P)*(v2-c)
w12 = P*v2+(1-P)*(v1-c)
w21 = (1-P)*v1+P*(v2-c)
w22 = (1-P)*v2+P*(v1-c)
# set utility parameters and probabilities over outgoing edges at
# chance nodes
game.set_utility(5, {'fisher 1': v1, 'fisher 2': v2})
game.set_utility(6, {'fisher 1': v2, 'fisher 2': v1})
game.set_utility(12, {'fisher 1': v1, 'fisher 2': v2-c})
game.set_utility(13, {'fisher 1': v2-c, 'fisher 2': v1})
game.set_utility(14, {'fisher 1': v2, 'fisher 2': v1-c})
game.set_utility(15, {'fisher 1': v1-c, 'fisher 2': v2})
game.set_probability_distribution(4, {(4, 8): P, (4, 9): (1-P)})
game.set_probability_distribution(7, {(7, 10): P, (7, 11): (1-P)})
return (w11, w12), (w21, w22)
_ = set_parameters_C2(v1, v2, P, c, fishing_game_C2)
# default keywords for rendering the figure
my_fig_kwargs = dict(figsize=(30, 20), frameon=False)
my_node_kwargs = dict(font_size=30, node_size=2250, edgecolors='k',
linewidths=2)
my_edge_kwargs = dict(arrowsize=25, width=3)
my_edge_labels_kwargs = dict(font_size=20)
my_patch_kwargs = dict(linewidth=2)
my_legend_kwargs = dict(fontsize=24, loc='upper right', edgecolor='white')
my_utility_label_kwargs = dict(horizontalalignment='center', fontsize=20)
my_info_sets_kwargs = dict(linestyle='--', linewidth=3)
position_colors = {'fisher 1': 'aquamarine', 'fisher 2': 'greenyellow'}
fig = plot_game(fishing_game_C2,
position_colors,
fig_kwargs=my_fig_kwargs,
node_kwargs=my_node_kwargs,
edge_kwargs=my_edge_kwargs,
edge_labels_kwargs=my_edge_labels_kwargs,
patch_kwargs=my_patch_kwargs,
legend_kwargs=my_legend_kwargs,
utility_label_kwargs=my_utility_label_kwargs,
utility_label_shift=0.06,
info_sets_kwargs=my_info_sets_kwargs)
```
**Changes to go from C1 to C2:**
* If fisher1.location == fisher2.location $\longrightarrow$ engage in a
"competition". In the game tree of C1: "shortcut edge" from node 4 to
node 12.
* Looser of fight from a final to an intermediate outcome (no longer a
terminal node).
* Change in payoff of outcome: $d>0\longrightarrow d=0$. Because fishers are
engaged in a different, non-violent type of competition, it is not costly to
lose the race. (this change might be redundant because being the looser is
now an intermediate instead of a final outcome).
* Additional edges: if fisher $i$ loses the competition $\longrightarrow$
fisher $i$ has to leave.
### Case C2-1
$w(1,1)>v_2;\;w(2,1)>v_2$
As predicted by Ostrom, in the equilibrium both fishers go to spot 1, and
let chance decide who was first.
```python
v1, v2 = 10, 2
P = 0.55
c = 1
(w11, w12), (w21, w22) = set_parameters_C2(v1, v2, P, c, fishing_game_C2)
print("w(1,1) = {:.1f}".format(w11))
print("w(2,1) = {:.1f}".format(w21))
print("v2 = {:.1f}".format(v2))
spe = subgame_perfect_equilibrium(fishing_game_C2)
path_store = []
DFS_equilibria_paths(fishing_game_C2, fishing_game_C2.game_tree.root, spe, [],
1, path_store)
print("\nPath -- Probability")
print("-------------------")
for (path, prob) in path_store:
print("{} -- {:.2f}".format(path, prob))
```
### Case C2-2
$w(1,1)>v_2;\;w(2,1)<v_2$
As predicted by Ostrom, in the equilibrium fisher 1 (the faster) goes to
spot 1, while fisher 2 (the slower) goes to spot 2.
```python
v1, v2 = 10, 5
P = 0.7
c = 3
(w11, w12), (w21, w22) = set_parameters_C2(v1, v2, P, c, fishing_game_C2)
print("w(1,1) = {:.1f}".format(w11))
print("w(2,1) = {:.1f}".format(w21))
print("v2 = {:.1f}".format(v2))
spe = subgame_perfect_equilibrium(fishing_game_C2)
path_store = []
DFS_equilibria_paths(fishing_game_C2, fishing_game_C2.game_tree.root, spe, [],
1, path_store)
print("\nPath -- Probability")
print("-------------------")
for (path, prob) in path_store:
print("{} -- {:.2f}".format(path, prob))
```
### Case C2-3
$w(1,1)<v_2;\;w(2,1)<v_2$
As predicted by Ostrom, in the equilibrium fisher 1 (the faster) goes to
spot 1, while fisher 2 (the slower) goes to spot 2.
As in case C1-3, there is another Nash equilibria in which the most
resourceful fisher 1 goes to the worse spot 2. However, that is not
predicted by backward induction, possibly because that Nash equilibria
is not sequentially rational.
```python
v1, v2 = 10, 8
P = 0.55
c = 3
(w11, w12), (w21, w22) = set_parameters_C2(v1, v2, P, c, fishing_game_C2)
print("w(1,1) = {:.1f}".format(w11))
print("w(2,1) = {:.1f}".format(w21))
print("v2 = {:.1f}".format(v2))
spe = subgame_perfect_equilibrium(fishing_game_C2)
path_store = []
DFS_equilibria_paths(fishing_game_C2, fishing_game_C2.game_tree.root, spe, [],
1, path_store)
print("\nPath -- Probability")
print("-------------------")
for (path, prob) in path_store:
print("{} -- {:.2f}".format(path, prob))
```
## Rule configuration C3
Fisher 1 announces first, and he has the right to go fish wherever he wants.
If fisher 2 goes to the spot taken by fisher 1, he has to leave for the
other spot.
```python
fishing_game_C3 = ExtensiveFormGame(title='Fishing game C3')
# add the two positions for the two fishers
fishing_game_C3.add_players('fisher 1', 'fisher 2')
# add the nodes to the graph
fishing_game_C3.add_node(1, player_turn='fisher 1', is_root=True)
fishing_game_C3.add_node(2, player_turn='fisher 2')
fishing_game_C3.add_node(3, player_turn='fisher 2')
fishing_game_C3.add_node(4, player_turn='fisher 2')
fishing_game_C3.add_node(5)
fishing_game_C3.add_node(6)
fishing_game_C3.add_node(7, player_turn='fisher 2')
fishing_game_C3.add_node(8)
fishing_game_C3.add_node(9)
# add the edges to the graph
fishing_game_C3.add_edge(1, 2, label='go to spot 1')
fishing_game_C3.add_edge(1, 3, label='go to spot 2')
fishing_game_C3.add_edge(2, 4, label='go to spot 1')
fishing_game_C3.add_edge(2, 5, label='go to spot 2')
fishing_game_C3.add_edge(3, 6, label='go to spot 1')
fishing_game_C3.add_edge(3, 7, label='go to spot 2')
fishing_game_C3.add_edge(4, 8, label='leave')
fishing_game_C3.add_edge(7, 9, label='leave')
```
The utilities are parametrized with the following variables:
* $v_i$: economical value of the $i$-th spot. It is assumed that the first
spot is the better one, so $v_1>v_2$.
* $c$: cost of travel between the two spots.
```python
# parameters
v1, v2 = 5, 3
P = 0.6
c = 0.5
fishing_game_C3.set_utility(5, {'fisher 1': v1, 'fisher 2': v2})
fishing_game_C3.set_utility(6, {'fisher 1': v2, 'fisher 2': v1})
fishing_game_C3.set_utility(8, {'fisher 1': v1, 'fisher 2': v2-c})
fishing_game_C3.set_utility(9, {'fisher 1': v2, 'fisher 2': v1-c})
# default keywords for rendering the figure
my_fig_kwargs = dict(figsize=(30, 20))
my_node_kwargs = dict(font_size=30, node_size=2250, edgecolors='k',
linewidths=2)
my_edge_kwargs = dict(arrowsize=25, width=3)
my_edge_labels_kwargs = dict(font_size=20)
my_patch_kwargs = dict(linewidth=2)
my_legend_kwargs = dict(fontsize=24, loc='upper right', edgecolor='white')
my_utility_label_kwargs = dict(horizontalalignment='center', fontsize=20)
my_info_sets_kwargs = dict(linestyle='--', linewidth=3)
position_colors = {'fisher 1': 'aquamarine', 'fisher 2': 'greenyellow'}
fig = plot_game(fishing_game_C3,
position_colors,
fig_kwargs=my_fig_kwargs,
node_kwargs=my_node_kwargs,
edge_kwargs=my_edge_kwargs,
edge_labels_kwargs=my_edge_labels_kwargs,
patch_kwargs=my_patch_kwargs,
legend_kwargs=my_legend_kwargs,
utility_label_kwargs=my_utility_label_kwargs,
utility_label_shift=0.05,
info_sets_kwargs=my_info_sets_kwargs)
```
**Changes to go from C1 to C3:**
* Fisher 1 announces: the information set {2,3} of fisher 2 gets split into
two information sets {2}, {3}
* If fisher$_i$.action == 'go to' fisher$_j$.location $\implies$
fisher$_i$.action $\leftarrow$ 'leave'. In terms of edges in the game tree
from C1: direct edge from 4$\longrightarrow$13 and 7$\longrightarrow$17
```python
spe = subgame_perfect_equilibrium(fishing_game_C3)
path_store = []
DFS_equilibria_paths(fishing_game_C3, fishing_game_C3.game_tree.root, spe, [],
1, path_store)
print("\nPath -- Probability")
print("-------------------")
for (path, prob) in path_store:
print("{} -- {:.2f}".format(path, prob))
```
Path -- Probability
-------------------
[1, 'go to spot 1', 2, 'go to spot 2', 5] -- 1.00
As predicted by Ostrom, in equilibrium the fisher who gets to announce first
(fisher 1) goes to the best spot 1, and the other fish goes to the other
spot. The second fisher will never go to the same spot that the first fisher
went to, because $v_2>v_2-c$.
## Rule configuration C4
This configuration consists of a prearranged rotation of the game in rule
configuration C3. It would consist of alternating between the game in C3 as
presented before, and the same game in C3 but with fisher 1 and fisher
swapped.
# Axelrod's norms game
```python
norms_game = ExtensiveFormGame(title='Axelrod norms game')
norms_game.add_players('i', 'j')
norms_game.add_node(1, player_turn='i', is_root=True)
norms_game.add_node(2, player_turn='chance')
norms_game.add_node(3)
norms_game.add_node(4, player_turn='j')
norms_game.add_node(5)
norms_game.add_node(6)
norms_game.add_node(7)
norms_game.add_edge(1, 2, 'defect')
norms_game.add_edge(1, 3, '~defect')
norms_game.add_edge(2, 4, 'j sees i')
norms_game.add_edge(2, 5, '~j sees i')
norms_game.add_edge(4, 6, 'punish')
norms_game.add_edge(4, 7, '~punish')
T = 3
H = -1
S = 0.6
P = -9
E = -2
norms_game.set_utility(3, {'i': 0, 'j': 0})
norms_game.set_utility(5, {'i': T, 'j': H})
norms_game.set_utility(6, {'i': P, 'j': E})
norms_game.set_utility(7, {'i': T, 'j': H})
norms_game.set_probability_distribution(2, {(2, 4): S, (2, 5): (1-S)})
# default keywords for rendering the figure
my_fig_kwargs = dict(figsize=(15, 15), frameon=False)
my_node_kwargs = dict(font_size=30, node_size=2250, edgecolors='k',
linewidths=2)
my_edge_kwargs = dict(arrowsize=25, width=3)
my_edge_labels_kwargs = dict(font_size=20)
my_patch_kwargs = dict(linewidth=2)
my_legend_kwargs = dict(fontsize=24, loc='upper right', edgecolor='white')
my_utility_label_kwargs = dict(horizontalalignment='center', fontsize=20)
my_info_sets_kwargs = dict(linestyle='--', linewidth=3)
position_colors = {'i': 'aquamarine', 'j': 'greenyellow'}
fig = plot_game(norms_game,
position_colors,
fig_kwargs=my_fig_kwargs,
node_kwargs=my_node_kwargs,
edge_kwargs=my_edge_kwargs,
edge_labels_kwargs=my_edge_labels_kwargs,
patch_kwargs=my_patch_kwargs,
legend_kwargs=my_legend_kwargs,
utility_label_kwargs=my_utility_label_kwargs,
utility_label_shift=0.06,
info_sets_kwargs=my_info_sets_kwargs)
```
**CASE 1:** $E<H$
Theoretical prediction: $i$ will defect but $j$ will not punishes if she
detects $i$.
```python
print("E = {:.1f}".format(E))
print("H = {:.1f}".format(H))
spe = subgame_perfect_equilibrium(norms_game)
path_store = []
DFS_equilibria_paths(norms_game, norms_game.game_tree.root, spe, [], 1,
path_store)
print("\nPath -- Probability")
print("-------------------")
for (path, prob) in path_store:
print("{} -- {:.2f}".format(path, prob))
```
E = -2.0
H = -1.0
Path -- Probability
-------------------
[1, 'defect', 2, 'j sees i', 4, '~punish', 7] -- 0.60
[1, 'defect', 2, '~j sees i', 5] -- 0.40
**CASE 2:** $E>H$
Theoretical prediction: $i$ will not defect
```python
T = 3
H = -2
S = 0.6
P = -9
E = -1
norms_game.set_utility(3, {'i': 0, 'j': 0})
norms_game.set_utility(5, {'i': T, 'j': H})
norms_game.set_utility(6, {'i': P, 'j': E})
norms_game.set_utility(7, {'i': T, 'j': H})
norms_game.set_probability_distribution(2, {(2, 4): S, (2, 5): (1-S)})
print("E = {:.1f}".format(E))
print("H = {:.1f}".format(H))
spe = subgame_perfect_equilibrium(norms_game)
path_store = []
DFS_equilibria_paths(norms_game, norms_game.game_tree.root, spe, [], 1,
path_store)
print("\nPath -- Probability")
print("-------------------")
for (path, prob) in path_store:
print("{} -- {:.2f}".format(path, prob))
```
E = -1.0
H = -2.0
Path -- Probability
-------------------
[1, '~defect', 3] -- 1.00
## Metanorms game
```python
metanorms_game = ExtensiveFormGame(title='Axelrod metanorms game')
metanorms_game.add_players('i', 'j', 'k')
metanorms_game.add_node(1, player_turn='i', is_root=True)
metanorms_game.add_node(2, player_turn='chance')
metanorms_game.add_node(3)
metanorms_game.add_node(4, player_turn='j')
metanorms_game.add_node(5)
metanorms_game.add_node(6)
metanorms_game.add_node(7, player_turn='chance')
metanorms_game.add_node(8, player_turn='k')
metanorms_game.add_node(9)
metanorms_game.add_node(10)
metanorms_game.add_node(11)
metanorms_game.add_edge(1, 2, 'defect')
metanorms_game.add_edge(1, 3, '~defect')
metanorms_game.add_edge(2, 4, 'j sees i')
metanorms_game.add_edge(2, 5, '~j sees i')
metanorms_game.add_edge(4, 6, 'punish i')
metanorms_game.add_edge(4, 7, '~punish i')
metanorms_game.add_edge(7, 8, 'k sees j')
metanorms_game.add_edge(7, 9, '~k sees j')
metanorms_game.add_edge(8, 10, 'punish j')
metanorms_game.add_edge(8, 11, '~punish j')
```
```python
T = 3
H = -1
S = 0.6
P = -9
E = -2
P_prime = P
E_prime = E
metanorms_game.set_utility(3, {'i': 0, 'j': 0, 'k': 0})
metanorms_game.set_utility(5, {'i': T, 'j': H, 'k': H})
metanorms_game.set_utility(6, {'i': P, 'j': E, 'k': 0})
metanorms_game.set_utility(9, {'i': T, 'j': H, 'k': H})
metanorms_game.set_utility(10, {'i': T, 'j': P_prime, 'k': E_prime})
metanorms_game.set_utility(11, {'i': T, 'j': H, 'k': H})
metanorms_game.set_probability_distribution(2, {(2, 4): S, (2, 5): (1-S)})
metanorms_game.set_probability_distribution(7, {(7, 8): S, (7, 9): (1-S)})
# default keywords for rendering the figure
my_fig_kwargs = dict(figsize=(25, 25), frameon=False)
my_node_kwargs = dict(font_size=30, node_size=2250, edgecolors='k',
linewidths=2)
my_edge_kwargs = dict(arrowsize=25, width=3)
my_edge_labels_kwargs = dict(font_size=16)
my_patch_kwargs = dict(linewidth=2)
my_legend_kwargs = dict(fontsize=24, loc='upper right', edgecolor='white')
my_utility_label_kwargs = dict(horizontalalignment='center', fontsize=20)
my_info_sets_kwargs = dict(linestyle='--', linewidth=3)
position_colors = {'i': 'aquamarine', 'j': 'greenyellow', 'k': 'violet'}
fig = plot_game(metanorms_game,
position_colors,
fig_kwargs=my_fig_kwargs,
node_kwargs=my_node_kwargs,
edge_kwargs=my_edge_kwargs,
edge_labels_kwargs=my_edge_labels_kwargs,
patch_kwargs=my_patch_kwargs,
legend_kwargs=my_legend_kwargs,
utility_label_kwargs=my_utility_label_kwargs,
utility_label_shift=0.09,
info_sets_kwargs=my_info_sets_kwargs)
```
```python
spe = subgame_perfect_equilibrium(metanorms_game)
path_store = []
DFS_equilibria_paths(metanorms_game, metanorms_game.game_tree.root, spe, [],
1, path_store)
print("\nPath -- Probability")
print("-------------------")
for (path, prob) in path_store:
print("{} -- {:.2f}".format(path, prob))
```
Path -- Probability
-------------------
[1, 'defect', 2, 'j sees i', 4, '~punish i', 7, 'k sees j', 8, '~punish j', 11] -- 0.36
[1, 'defect', 2, 'j sees i', 4, '~punish i', 7, '~k sees j', 9] -- 0.24
[1, 'defect', 2, '~j sees i', 5] -- 0.40
|
If $f$ is holomorphic on $S - \{ \xi \}$ and $\xi$ is an interior point of $S$, then the following are equivalent: $f$ can be extended to a holomorphic function on $S$. $\lim_{z \to \xi} (z - \xi) f(z) = 0$. $f$ is bounded in a neighborhood of $\xi$.
|
Ask us WHATEVER you need.
We offer professional VIP services in Ibiza Spain. Just tell us your wishes, we will assist your hassle-free dream vacation.
We specialize in reserving the best VIP tables in popular discos and clubs for memorable party experiences. Even all tables are sold out, we will negotiate special prices for you!
|
(************************************************************************)
(* * The Coq Proof Assistant / The Coq Development Team *)
(* v * INRIA, CNRS and contributors - Copyright 1999-2018 *)
(* <O___,, * (see CREDITS file for the list of authors) *)
(* \VV/ **************************************************************)
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(* * (see LICENSE file for the text of the license) *)
(************************************************************************)
(* Evgeny Makarov, INRIA, 2007 *)
(************************************************************************)
Require Import OrderedRing.
Require Import RingMicromega.
Require Import ZArith.
Require Import InitialRing.
Require Import Setoid.
Import OrderedRingSyntax.
Set Implicit Arguments.
Section InitialMorphism.
Variable R : Type.
Variables rO rI : R.
Variables rplus rtimes rminus: R -> R -> R.
Variable ropp : R -> R.
Variables req rle rlt : R -> R -> Prop.
Variable sor : SOR rO rI rplus rtimes rminus ropp req rle rlt.
Notation "0" := rO.
Notation "1" := rI.
Notation "x + y" := (rplus x y).
Notation "x * y " := (rtimes x y).
Notation "x - y " := (rminus x y).
Notation "- x" := (ropp x).
Notation "x == y" := (req x y).
Notation "x ~= y" := (~ req x y).
Notation "x <= y" := (rle x y).
Notation "x < y" := (rlt x y).
Lemma req_refl : forall x, req x x.
Proof.
destruct sor.(SORsetoid) as (Equivalence_Reflexive,_,_).
apply Equivalence_Reflexive.
Qed.
Lemma req_sym : forall x y, req x y -> req y x.
Proof.
destruct sor.(SORsetoid) as (_,Equivalence_Symmetric,_).
apply Equivalence_Symmetric.
Qed.
Lemma req_trans : forall x y z, req x y -> req y z -> req x z.
Proof.
destruct sor.(SORsetoid) as (_,_,Equivalence_Transitive).
apply Equivalence_Transitive.
Qed.
Add Relation R req
reflexivity proved by sor.(SORsetoid).(@Equivalence_Reflexive _ _)
symmetry proved by sor.(SORsetoid).(@Equivalence_Symmetric _ _)
transitivity proved by sor.(SORsetoid).(@Equivalence_Transitive _ _)
as sor_setoid.
Add Morphism rplus with signature req ==> req ==> req as rplus_morph.
Proof.
exact sor.(SORplus_wd).
Qed.
Add Morphism rtimes with signature req ==> req ==> req as rtimes_morph.
Proof.
exact sor.(SORtimes_wd).
Qed.
Add Morphism ropp with signature req ==> req as ropp_morph.
Proof.
exact sor.(SORopp_wd).
Qed.
Add Morphism rle with signature req ==> req ==> iff as rle_morph.
Proof.
exact sor.(SORle_wd).
Qed.
Add Morphism rlt with signature req ==> req ==> iff as rlt_morph.
Proof.
exact sor.(SORlt_wd).
Qed.
Add Morphism rminus with signature req ==> req ==> req as rminus_morph.
Proof.
exact (rminus_morph sor).
Qed.
Ltac le_less := rewrite (Rle_lt_eq sor); left; try assumption.
Ltac le_equal := rewrite (Rle_lt_eq sor); right; try reflexivity; try assumption.
Definition gen_order_phi_Z : Z -> R := gen_phiZ 0 1 rplus rtimes ropp.
Declare Equivalent Keys gen_order_phi_Z gen_phiZ.
Notation phi_pos := (gen_phiPOS 1 rplus rtimes).
Notation phi_pos1 := (gen_phiPOS1 1 rplus rtimes).
Notation "[ x ]" := (gen_order_phi_Z x).
Lemma ring_ops_wd : ring_eq_ext rplus rtimes ropp req.
Proof.
constructor.
exact rplus_morph.
exact rtimes_morph.
exact ropp_morph.
Qed.
Lemma Zring_morph :
ring_morph 0 1 rplus rtimes rminus ropp req
0%Z 1%Z Z.add Z.mul Z.sub Z.opp
Zeq_bool gen_order_phi_Z.
Proof.
exact (gen_phiZ_morph sor.(SORsetoid) ring_ops_wd sor.(SORrt)).
Qed.
Lemma phi_pos1_pos : forall x : positive, 0 < phi_pos1 x.
Proof.
induction x as [x IH | x IH |]; simpl;
try apply (Rplus_pos_pos sor); try apply (Rtimes_pos_pos sor); try apply (Rplus_pos_pos sor);
try apply (Rlt_0_1 sor); assumption.
Qed.
Lemma phi_pos1_succ : forall x : positive, phi_pos1 (Pos.succ x) == 1 + phi_pos1 x.
Proof.
exact (ARgen_phiPOS_Psucc sor.(SORsetoid) ring_ops_wd
(Rth_ARth sor.(SORsetoid) ring_ops_wd sor.(SORrt))).
Qed.
Lemma clt_pos_morph : forall x y : positive, (x < y)%positive -> phi_pos1 x < phi_pos1 y.
Proof.
intros x y H. pattern y; apply Pos.lt_ind with x.
rewrite phi_pos1_succ; apply (Rlt_succ_r sor).
clear y H; intros y _ H. rewrite phi_pos1_succ. now apply (Rlt_lt_succ sor).
assumption.
Qed.
Lemma clt_morph : forall x y : Z, (x < y)%Z -> [x] < [y].
Proof.
intros x y H.
do 2 rewrite (same_genZ sor.(SORsetoid) ring_ops_wd sor.(SORrt));
destruct x; destruct y; simpl in *; try discriminate.
apply phi_pos1_pos.
now apply clt_pos_morph.
apply <- (Ropp_neg_pos sor); apply phi_pos1_pos.
apply (Rlt_trans sor) with 0. apply <- (Ropp_neg_pos sor); apply phi_pos1_pos.
apply phi_pos1_pos.
apply -> (Ropp_lt_mono sor); apply clt_pos_morph.
red. now rewrite Pos.compare_antisym.
Qed.
Lemma Zcleb_morph : forall x y : Z, Z.leb x y = true -> [x] <= [y].
Proof.
unfold Z.leb; intros x y H.
case_eq (x ?= y)%Z; intro H1; rewrite H1 in H.
le_equal. apply Zring_morph.(morph_eq). unfold Zeq_bool; now rewrite H1.
le_less. now apply clt_morph.
discriminate.
Qed.
Lemma Zcneqb_morph : forall x y : Z, Zeq_bool x y = false -> [x] ~= [y].
Proof.
intros x y H. unfold Zeq_bool in H.
case_eq (Z.compare x y); intro H1; rewrite H1 in *; (discriminate || clear H).
apply (Rlt_neq sor). now apply clt_morph.
fold (x > y)%Z in H1. rewrite Z.gt_lt_iff in H1.
apply (Rneq_symm sor). apply (Rlt_neq sor). now apply clt_morph.
Qed.
End InitialMorphism.
|
The circlepath function is periodic with period 1.
|
------------------------------------------------------------------------
-- A tiny library of derived combinators
------------------------------------------------------------------------
module TotalRecognisers.LeftRecursion.Lib (Tok : Set) where
open import Codata.Musical.Notation
open import Data.Bool hiding (_∧_; _≤_)
open import Data.Bool.Properties
open import Function hiding (_∋_)
open import Function.Equality using (_⟨$⟩_)
open import Function.Equivalence using (module Equivalence)
open import Data.List
open import Data.Nat using (ℕ; zero; suc)
open import Data.Product as Prod
open import Relation.Binary
open import Relation.Binary.PropositionalEquality hiding ([_])
open import Relation.Nullary.Decidable
import TotalRecognisers.LeftRecursion
open TotalRecognisers.LeftRecursion Tok
------------------------------------------------------------------------
-- Kleene star
-- The intended semantics of the Kleene star.
infixr 5 _∷_
infix 4 _∈[_]⋆
data _∈[_]⋆ {n} : List Tok → P n → Set where
[] : ∀ {p} → [] ∈[ p ]⋆
_∷_ : ∀ {s₁ s₂ p} → s₁ ∈ p → s₂ ∈[ p ]⋆ → s₁ ++ s₂ ∈[ p ]⋆
module KleeneStar₁ where
infix 15 _⋆ _+
-- This definition requires that the argument recognisers are not
-- nullable.
mutual
_⋆ : P false → P true
p ⋆ = empty ∣ p +
_+ : P false → P false
p + = p · ♯ (p ⋆)
-- The definition of _⋆ above is correct.
⋆-sound : ∀ {s p} → s ∈ p ⋆ → s ∈[ p ]⋆
⋆-sound (∣-left empty) = []
⋆-sound (∣-right (pr₁ · pr₂)) = pr₁ ∷ ⋆-sound pr₂
⋆-complete : ∀ {s p} → s ∈[ p ]⋆ → s ∈ p ⋆
⋆-complete [] = ∣-left empty
⋆-complete (_∷_ {[]} pr₁ pr₂) = ⋆-complete pr₂
⋆-complete (_∷_ {_ ∷ _} pr₁ pr₂) =
∣-right {n₁ = true} (pr₁ · ⋆-complete pr₂)
module KleeneStar₂ where
infix 15 _⋆
-- This definition works for any argument recogniser.
_⋆ : ∀ {n} → P n → P true
_⋆ = KleeneStar₁._⋆ ∘ nonempty
-- The definition of _⋆ above is correct.
⋆-sound : ∀ {s n} {p : P n} → s ∈ p ⋆ → s ∈[ p ]⋆
⋆-sound (∣-left empty) = []
⋆-sound (∣-right (nonempty pr₁ · pr₂)) = pr₁ ∷ ⋆-sound pr₂
⋆-complete : ∀ {s n} {p : P n} → s ∈[ p ]⋆ → s ∈ p ⋆
⋆-complete [] = ∣-left empty
⋆-complete (_∷_ {[]} pr₁ pr₂) = ⋆-complete pr₂
⋆-complete (_∷_ {_ ∷ _} pr₁ pr₂) =
∣-right {n₁ = true} (nonempty pr₁ · ⋆-complete pr₂)
-- Note, however, that for actual parsing the corresponding
-- definition would not be correct. The reason is that p would give
-- a result also when the empty string was accepted, and these
-- results are ignored by the definition above. In the case of
-- actual parsing the result of p ⋆, when p is nullable, should be a
-- stream and not a finite list.
------------------------------------------------------------------------
-- A simplified sequencing operator
infixl 10 _⊙_
_⊙_ : ∀ {n₁ n₂} → P n₁ → P n₂ → P (n₁ ∧ n₂)
_⊙_ {n₁ = n₁} p₁ p₂ = ♯? p₁ · ♯? {b = n₁} p₂
module ⊙ where
complete : ∀ {n₁ n₂ s₁ s₂} {p₁ : P n₁} {p₂ : P n₂} →
s₁ ∈ p₁ → s₂ ∈ p₂ → s₁ ++ s₂ ∈ p₁ ⊙ p₂
complete {n₁} {n₂} s₁∈p₁ s₂∈p₂ = add-♭♯ n₂ s₁∈p₁ · add-♭♯ n₁ s₂∈p₂
infixl 10 _⊙′_
infix 4 _⊙_∋_
data _⊙_∋_ {n₁ n₂} (p₁ : P n₁) (p₂ : P n₂) : List Tok → Set where
_⊙′_ : ∀ {s₁ s₂} (s₁∈p₁ : s₁ ∈ p₁) (s₂∈p₂ : s₂ ∈ p₂) →
p₁ ⊙ p₂ ∋ s₁ ++ s₂
sound : ∀ {n₁} n₂ {s} {p₁ : P n₁} {p₂ : P n₂} →
s ∈ p₁ ⊙ p₂ → p₁ ⊙ p₂ ∋ s
sound {n₁} n₂ (s₁∈p₁ · s₂∈p₂) = drop-♭♯ n₂ s₁∈p₁ ⊙′ drop-♭♯ n₁ s₂∈p₂
------------------------------------------------------------------------
-- A combinator which repeats a recogniser a fixed number of times
⟨_^_⟩-nullable : Bool → ℕ → Bool
⟨ n ^ zero ⟩-nullable = true
⟨ n ^ suc i ⟩-nullable = n ∧ ⟨ n ^ i ⟩-nullable
infixl 15 _^_
_^_ : ∀ {n} → P n → (i : ℕ) → P ⟨ n ^ i ⟩-nullable
p ^ 0 = empty
p ^ suc i = p ⊙ p ^ i
-- Some lemmas relating _^_ to _⋆.
open KleeneStar₂
^≤⋆ : ∀ {n} {p : P n} i → p ^ i ≤ p ⋆
^≤⋆ {n} {p} i s∈ = ⋆-complete $ helper i s∈
where
helper : ∀ i {s} → s ∈ p ^ i → s ∈[ p ]⋆
helper zero empty = []
helper (suc i) (s₁∈p · s₂∈pⁱ) =
drop-♭♯ ⟨ n ^ i ⟩-nullable s₁∈p ∷ helper i (drop-♭♯ n s₂∈pⁱ)
⋆≤^ : ∀ {n} {p : P n} {s} → s ∈ p ⋆ → ∃ λ i → s ∈ p ^ i
⋆≤^ {n} {p} s∈p⋆ = helper (⋆-sound s∈p⋆)
where
helper : ∀ {s} → s ∈[ p ]⋆ → ∃ λ i → s ∈ p ^ i
helper [] = (0 , empty)
helper (s₁∈p ∷ s₂∈p⋆) =
Prod.map suc (λ {i} s₂∈pⁱ → add-♭♯ ⟨ n ^ i ⟩-nullable s₁∈p ·
add-♭♯ n s₂∈pⁱ)
(helper s₂∈p⋆)
------------------------------------------------------------------------
-- A recogniser which only accepts a given token
module Tok (dec : Decidable (_≡_ {A = Tok})) where
tok : Tok → P false
tok t = sat (⌊_⌋ ∘ dec t)
sound : ∀ {s t} → s ∈ tok t → s ≡ [ t ]
sound (sat ok) = cong [_] $ sym $ toWitness ok
complete : ∀ {t} → [ t ] ∈ tok t
complete = sat (fromWitness refl)
------------------------------------------------------------------------
-- A recogniser which accepts the empty string iff the argument is
-- true (and never accepts non-empty strings)
accept-if-true : ∀ b → P b
accept-if-true true = empty
accept-if-true false = fail
module AcceptIfTrue where
sound : ∀ b {s} → s ∈ accept-if-true b → s ≡ [] × T b
sound true empty = (refl , _)
sound false ()
complete : ∀ {b} → T b → [] ∈ accept-if-true b
complete ok with Equivalence.to T-≡ ⟨$⟩ ok
... | refl = empty
|
From Test Require Import tactic.
Section FOFProblem.
Variable Universe : Set.
Variable UniverseElement : Universe.
Variable p_ : Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Prop.
Variable goal_ : Prop.
Variable dom_ : Universe -> Prop.
Variable a9_ : Universe.
Variable a8_ : Universe.
Variable a7_ : Universe.
Variable a63_ : Universe.
Variable a62_ : Universe.
Variable a61_ : Universe.
Variable a60_ : Universe.
Variable a6_ : Universe.
Variable a59_ : Universe.
Variable a58_ : Universe.
Variable a57_ : Universe.
Variable a56_ : Universe.
Variable a55_ : Universe.
Variable a54_ : Universe.
Variable a53_ : Universe.
Variable a52_ : Universe.
Variable a51_ : Universe.
Variable a50_ : Universe.
Variable a5_ : Universe.
Variable a49_ : Universe.
Variable a48_ : Universe.
Variable a47_ : Universe.
Variable a46_ : Universe.
Variable a45_ : Universe.
Variable a44_ : Universe.
Variable a43_ : Universe.
Variable a42_ : Universe.
Variable a41_ : Universe.
Variable a40_ : Universe.
Variable a4_ : Universe.
Variable a39_ : Universe.
Variable a38_ : Universe.
Variable a37_ : Universe.
Variable a36_ : Universe.
Variable a35_ : Universe.
Variable a34_ : Universe.
Variable a33_ : Universe.
Variable a32_ : Universe.
Variable a31_ : Universe.
Variable a30_ : Universe.
Variable a3_ : Universe.
Variable a29_ : Universe.
Variable a28_ : Universe.
Variable a27_ : Universe.
Variable a26_ : Universe.
Variable a25_ : Universe.
Variable a24_ : Universe.
Variable a23_ : Universe.
Variable a22_ : Universe.
Variable a21_ : Universe.
Variable a20_ : Universe.
Variable a2_ : Universe.
Variable a19_ : Universe.
Variable a18_ : Universe.
Variable a17_ : Universe.
Variable a16_ : Universe.
Variable a15_ : Universe.
Variable a14_ : Universe.
Variable a13_ : Universe.
Variable a12_ : Universe.
Variable a11_ : Universe.
Variable a10_ : Universe.
Variable a1_ : Universe.
Variable ax1_1 : (dom_ a1_ /\ (dom_ a2_ /\ (dom_ a3_ /\ (dom_ a4_ /\ (dom_ a5_ /\ (dom_ a6_ /\ (dom_ a7_ /\ (dom_ a8_ /\ (dom_ a9_ /\ (dom_ a10_ /\ (dom_ a11_ /\ (dom_ a12_ /\ (dom_ a13_ /\ (dom_ a14_ /\ (dom_ a15_ /\ (dom_ a16_ /\ (dom_ a17_ /\ (dom_ a18_ /\ (dom_ a19_ /\ (dom_ a20_ /\ (dom_ a21_ /\ (dom_ a22_ /\ (dom_ a23_ /\ (dom_ a24_ /\ (dom_ a25_ /\ (dom_ a26_ /\ (dom_ a27_ /\ (dom_ a28_ /\ (dom_ a29_ /\ (dom_ a30_ /\ (dom_ a31_ /\ (dom_ a32_ /\ (dom_ a33_ /\ (dom_ a34_ /\ (dom_ a35_ /\ (dom_ a36_ /\ (dom_ a37_ /\ (dom_ a38_ /\ (dom_ a39_ /\ (dom_ a40_ /\ (dom_ a41_ /\ (dom_ a42_ /\ (dom_ a43_ /\ (dom_ a44_ /\ (dom_ a45_ /\ (dom_ a46_ /\ (dom_ a47_ /\ (dom_ a48_ /\ (dom_ a49_ /\ (dom_ a50_ /\ (dom_ a51_ /\ (dom_ a52_ /\ (dom_ a53_ /\ (dom_ a54_ /\ (dom_ a55_ /\ (dom_ a56_ /\ (dom_ a57_ /\ (dom_ a58_ /\ (dom_ a59_ /\ (dom_ a60_ /\ (dom_ a61_ /\ (dom_ a62_ /\ dom_ a63_)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))).
Variable ax2_2 : (forall A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11 A12 A13 A14 A15 A16 A17 A18 A19 A20 A21 A22 A23 A24 A25 A26 A27 A28 A29 A30 A31 A32 A33 A34 A35 A36 A37 A38 A39 A40 A41 A42 A43 A44 A45 A46 A47 A48 A49 A50 A51 A52 A53 A54 A55 A56 A57 A58 A59 A60 A61 A62 A63 : Universe, ((dom_ A1 /\ (dom_ A2 /\ (dom_ A3 /\ (dom_ A4 /\ (dom_ A5 /\ (dom_ A6 /\ (dom_ A7 /\ (dom_ A8 /\ (dom_ A9 /\ (dom_ A10 /\ (dom_ A11 /\ (dom_ A12 /\ (dom_ A13 /\ (dom_ A14 /\ (dom_ A15 /\ (dom_ A16 /\ (dom_ A17 /\ (dom_ A18 /\ (dom_ A19 /\ (dom_ A20 /\ (dom_ A21 /\ (dom_ A22 /\ (dom_ A23 /\ (dom_ A24 /\ (dom_ A25 /\ (dom_ A26 /\ (dom_ A27 /\ (dom_ A28 /\ (dom_ A29 /\ (dom_ A30 /\ (dom_ A31 /\ (dom_ A32 /\ (dom_ A33 /\ (dom_ A34 /\ (dom_ A35 /\ (dom_ A36 /\ (dom_ A37 /\ (dom_ A38 /\ (dom_ A39 /\ (dom_ A40 /\ (dom_ A41 /\ (dom_ A42 /\ (dom_ A43 /\ (dom_ A44 /\ (dom_ A45 /\ (dom_ A46 /\ (dom_ A47 /\ (dom_ A48 /\ (dom_ A49 /\ (dom_ A50 /\ (dom_ A51 /\ (dom_ A52 /\ (dom_ A53 /\ (dom_ A54 /\ (dom_ A55 /\ (dom_ A56 /\ (dom_ A57 /\ (dom_ A58 /\ (dom_ A59 /\ (dom_ A60 /\ (dom_ A61 /\ (dom_ A62 /\ dom_ A63)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))) -> p_ A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11 A12 A13 A14 A15 A16 A17 A18 A19 A20 A21 A22 A23 A24 A25 A26 A27 A28 A29 A30 A31 A32 A33 A34 A35 A36 A37 A38 A39 A40 A41 A42 A43 A44 A45 A46 A47 A48 A49 A50 A51 A52 A53 A54 A55 A56 A57 A58 A59 A60 A61 A62 A63)).
Variable ax3_3 : (p_ a63_ a62_ a61_ a60_ a59_ a58_ a57_ a56_ a55_ a54_ a53_ a52_ a51_ a50_ a49_ a48_ a47_ a46_ a45_ a44_ a43_ a42_ a41_ a40_ a39_ a38_ a37_ a36_ a35_ a34_ a33_ a32_ a31_ a30_ a29_ a28_ a27_ a26_ a25_ a24_ a23_ a22_ a21_ a20_ a19_ a18_ a17_ a16_ a15_ a14_ a13_ a12_ a11_ a10_ a9_ a8_ a7_ a6_ a5_ a4_ a3_ a2_ a1_ -> goal_).
Theorem lemma63_4 : goal_.
Proof.
time tac.
Qed.
End FOFProblem.
|
Suppose $f$, $g$, and $h$ are functions defined on a filter $F$ such that $f(x) \neq 0$, $g(x) \neq 0$, and $h(x) \neq 0$ for all $x$ in $F$. Then $h(x)/f(x)$ converges to $h(x)/g(x)$ if and only if $g(x)$ converges to $f(x)$.
|
#include <boost/process.hpp>
#include <iostream>
#include <string>
/*!
\file super_agent.cpp
\author Igor Roshchin
start mongo agent and decorate
*/
using namespace boost::process;
int main() {
return system("./start");
}
|
\subsection{Artistic style transfer for videos}
\label{seq:ruder}
\textit{Artistic style transfer for videos} is a paper written by Manuel Ruder et al. \cite{Ruder:1} And is based on Gatys \cite{Gatys:1} way of implementing style transfer, but introduces a temporal constraint in order to get rid of the randomness that appears when styling each frame individually. \nextline
\subsubsection{Loss function}
The temporal constraint is described in the loss function of the style transfer model. The idea is to penalize the model for deviations between two adjacent frames. So as well as having a content-loss and a style-loss, they introduce a third component for temporal loss:
\begin{equation}
\mathcal{L}_{temporal}(x, \omega, c) = \frac{1}{D}\sum_{k=1} c_k \cdot (x_k - \omega_k)^2
\end{equation}
\nextline This loss component takes three arguments: x, $\omega$ and c. x is the model variable, or more specifically the image we are styling. $\omega$ is the warped previous styled frame. By warped we mean warped using the flow calculated between the current frame and the previous frame. This can be done using a variety of flow calculation algorithms and the article mentions some of these, including DeepFlow and EpicFlow. The c parameter is a mask with the same shape as the styled image, containing integer values 0 or 1. The loss function calculates the squared difference on each pixel (k) of the frame and uses the c-matrix as a weighting for the pixels. For every channel in every pixel where the c-matrix has a value 0 we tell the loss function that this channel in the pixel does not count on the temporal loss. In short, the loss function gives higher loss if the generated image is different from the warped previous stylized frame on every pixel where the c-matrix has value 1. If c has value 0 the difference is not added to the loss.
\subsubsection{Usage of optical flow}
\label{sec:usage_of_optical_flow}
In this implementation the optical flow is used in order to warp previously styled images, detecting disoccluded areas and motion boundaries. These areas are in turn used to create the c-matrix used in the loss function. this is done by giving the disoccluded areas and motion boundaries the value 0 in the c-matrix, and the rest of the image the value 1.\newline\newline To detect the disoccluded areas between two frames, we need the forward flow $(w)$, backward flow$(\hat{w})$, and the forward flow warped to the second image (\~{w}): \newline \begin{equation}\~{w}(x, y) = w( (x, y) + \hat{w}(x, y))\end{equation}. \newline Using these functions the disoccluded areas are calculated using this inequality:\newline
\begin{equation}
|\~{w} + \hat{w}|^2 > 0.01(|\~{w}|^2 + |\hat{w}|^2) + 0.5
\end{equation}
When it comes to detecting motion boundaries this inequality is used:
\begin{equation}
|\nabla\hat{u}|^2 + |\nabla\hat{v}|^2 > 0.01|\hat{w}|^2 + 0.002
\end{equation}
Where $\hat{u}$ and $\hat{v}$ are the two components of the backward flow function output: $\hat{w}(x, y) = (u, v)$
\subsubsection{Long-term temporal loss}
\label{sec:long_term_temporal_loss}
In the first section, the temporal loss is described using only the previous frame, resulting in the total loss-function:
\begin{equation}
\mathcal{L}_{shortterm}(p^{(i)}, a, x) = \alpha \mathcal{L}_{content} + \beta \mathcal{L}_{style} + \gamma \mathcal{L}_{temporal}(x^{(i)}, \omega_{i-1}^i(x^{i-1}, c^{i-1, i}))
\end{equation}
where the temporal loss is the function we described earlier, $x^{(i)}$ is the currently generated frame, $\omega_{i-1}^i(x^{i-1})$ is the previous stylized image warped with the flow from previous frame to current frame, and $c^{i-1, i}$ is the weights of disoccluded areas and motion boundaries between last image and current image. However, the longterm loss function is described like this: \newline
\begin{equation}
\mathcal{L}_{longterm}(p^{(i)}, a, x) = \alpha \mathcal{L}_{content} + \beta \\\mathcal{L}_{style} + \gamma \sum_{j\in J: i-j \leq 1}\mathcal{L}_{temporal}(x^{(i)}, \omega_{i-j}^i(x^{i-j}), c_{long}^{i-j, i}))
\end{equation}
where e.g $J = [1, 2, 4]$. the most important part of this long-term loss function are the $c_{long}$ weights. They are calculated like this:\newline
\begin{equation}
c_{long}^{(i-j, i)} = max(c^{(i-j, i)} - \sum_{k\in J: i - k > i - j} c^{(i-k, i)}, 0)
\end{equation}
Here, max is taken element-wise.\newline
\subsubsection{Multi-pass algorithm}
When generating videos with the new longterm temporal loss, the contrast is less diverse near image boundaries, and is especially noticable in videos with a lot of camera motion, mostly because the flow of information to base each frame on only comes from the first frame. This issue was solved by developing a multi-pass algorithm that initially stylizes every frame individually and then blend frames with non-disoccluded parts of previous frames warped according to the optical flow, and then again run some optimization steps for some iterations with the blend as an initialization.\newline
The initialization of frame i for pass j, when processed in forward direction is created like this:\newline
if i = 1:
\begin{equation}
x'^{(i)(j)} = x^{(i)(j-1)}
\end{equation}
else:
\begin{equation}
x'^{(i)(j)} = \delta c^{i-1, i} \circ \omega_{i-1}^i(x^{(i-1)(j)}) + (\bar{\delta}1 + \delta \bar{c}^{(i-1, i)})\circ x^{(i)(j-1)}
\end{equation}\newline
when processed in backward direction, it's created like this:\newline
if i = $N_{frames}$:\newline
\begin{equation}
x'^{(i)(j)} = x^{(i)(j-1)}
\end{equation}
else:\newline
\begin{equation}
x'^{(i)(j)} = \delta c^{i+1, i} \circ \omega_{i+1}^i(x^{(i+1)(j)}) + (\bar{\delta}1 + \delta \bar{c}^{(i+1, i)})\circ x^{(i)(j-1)}
\end{equation} \newline
In these calculations $\circ$ means element-wise vector multiplication. $\delta$ and $1 -\bar{\delta}$ are the blend factors where 1 is a vector of all ones. $\omega$ is the function for warping an image using the flow between two images. And c is the c-matrix we described in section \ref{sec:usage_of_optical_flow}.
|
.IP \fBadmshot\fR 0.75i
A set of files and scripts that allow for the simple execution of
one\-shot procedures.
.IP \fBarcwtmp\fR
Utility for archiving login history.
.IP \fBbanner\fR
Banner printing utility.
.IP \fBbeuucp\fR
Change the effective group and user ids to
.BR uucp .
.IP \fBbooz\fR
Unpacker for ZOO\-format archives.
.IP \fBcflow\fR
Produces a listing of the program's calling hierarchy based upon
C function calls and declarations.
.IP \fBchess\fR
This program plays a fairly respectable game of chess, although it
is not competetive with state-of-the art commercial programs.
.IP \fBchoose\fR
Randomly selects lines from its input.
Useful for building your own
.BR fortune -like
games.
.IP \fBcmenu\fR
A menu package that lets you execute commands from a menu.
.IP \fBcnews\fR
A distribution of
.B cnews
for COHERENT.
.IP \fBcomb\fR
An alternative to COHERENT's standard
mailer,
.BR /bin/mail .
Features screen-oriented menuing and reply functions.
.IP \fBcrc\fR
Computes encrypted checksums.
Can improve security of your file transfers or your system.
.IP \fBctags\fR
This is the Berkeley version of
.BR ctags ,
ported to COHERENT.
.IP \fBcurses2\fR
Header with additional functions for the COHERENT
.B curses
library.
.IP \fBfinger\fR
Displays information about a user.
.IP \fBfocal\fR
.B focal
language interpreter.
.IP \fBfonts\fR
Computer Modern shareware font collection for
HP LaserJet and compatible printers.
.IP \fBgetppid\fR
A C program that returns your parent process id.
.IP \fBgnews\fR
A nice ``news'' system which includes everything you need
to receive and read news.
.IP \fBGNUgo\fR
This program plays quite a respectable game of
.IR go .
.IP \fBgomoku\fR
An
.IR Othello -style
game played on a 19 by 19 grid.
.IP \fBhd\fR
Similar to COHERENT's command \fBod -c\fP,
but dumps files in a friendlier hexadecimal format.
.IP \fBhotel\fR
A board game of hotel development.
Players take turns placing tiles on the board
and buying stock in the hotels they create.
.IP \fBless\fR
An enhanced version of the traditional Berkeley screen pager
.BR more .
.IP \fBlibndir\fR
Directory-access subroutine library.
.IP \fBmc\fR
A powerful shareware spreadsheet program for COHERENT.
.IP \fBmenubar\fR
Creates a menu window.
Usefel for writing programs that prompt the user for menu choices.
.IP \fBmonth\fR
An appointment calendar.
.IP \fBmtalk\fR
A small, simple multi-user ``chat'' program.
.IP \fBmterm\fR
A basic terminal-services program.
This program utilizes the serial-port handler portions of the
.B kermit
program supplied with COHERENT as the base for a simple terminal package.
.IP \fBmwdl\fR
A simple shell script used to download files from the Mark Williams Company
bulletin board,
.BR mwcbbs .
.IP \fBogre\fR
A game of tank warfare in the 21st Century.
.IP \fBorigami\fR
A powerful folding screen editor that is able to use the same key
bindings as MicroEMACS.
.IP \fBpclist\fR
Yet another screen pager.
.IP \fBps\fR
This archive contains a collection of independent,
self\-documented PostScript programs, including
.BR pscal ,
a useful calendar printing utility.
.IP \fBprolog\fR
A Prolog logic programming language interpreter.
Includes a manual and some tutorial information.
.IP \fBquebbs\fR
This is a Bulletin Board System that was ported to COHERENT.
.IP \fBrcs\fR
A revision control system.
Manages software libraries, stores and retrieves multiple revisions
of text files, and much more.
.IP \fBrn\fR
Larry Wall's popular news reading program.
.IP \fBsc\fR
A greatly modified version of the public domain spreadsheet,
.BR vc .
.IP \fBsdbm\fR
A clone of the Berkeley
.B ndbm
library.
.IP \fBshar\fR
Combines files into shell archive (shar) files.
.IP \fBsokoban\fR
A clone of the popular
.B Boxxle
game.
.IP \fBTASS\fR
A full\-screen, threaded news reader.
.IP \fBtassgn\fR
Allows you to use TASS 3.2 for reading and posting news articles with
the GNEWS package.
.IP \fBtetris\fR
A clone of the popular arcade game Tetris.
.IP \fBtrek73\fR
A computer simulated battle based on the famous
.I "Star Trek"
television series and the game
.IR "Star Fleet Battles" .
.IP \fBumodem\fR
This version of
.B umodem
was modified for COHERENT.
It is based upon
.B umodem
version 4.0 which is also included.
.IP \fBuucp\fR
An
.B awk
script for COHERENT that
lets you to see the cost of your UUCP communications.
.IP \fBvtree\fR
A utility which shows the layout of a directory tree or file system.
.IP \fBwhich\fR
An implementation of the Berkeley
.B which
command.
It searches your path for the first executable file
that matches the command line argument.
.IP \fBwmail\fR
A
.B mailx
clone which is easy to use and one of the best mailers for small systems.
WMAIL needs SMAIL25, included in \*(PN Volume I.
.IP \fBwnews\fR
A small news package which resembles a subset of the original B-News package.
.IP \fBwsh\fR
A shareware window shell for COHERENT.
.IP \fBxcmalt\fR
XCMALT is a massive expansion and modification of XCOMM 2.2,
a UNIX dialout telecommunications program.
.IP \fBxlisp\fR
XLISP is an experimental programming language combining some of the
features of LISP with object\-oriented extensions.
.IP \fBxo\fR
A tic-tac-toe game.
.IP \fBzoo\fR
Contains two programs,
.B zoo
and
.BR fiz .
.B zoo
manipulates archives of files in compressed form.
.B fiz
analyzes damaged
.B zoo
archives for data recovery.
|
1981
|
lemma convex_real_interval [iff]: fixes a b :: "real" shows "convex {a..}" and "convex {..b}" and "convex {a<..}" and "convex {..<b}" and "convex {a..b}" and "convex {a<..b}" and "convex {a..<b}" and "convex {a<..<b}"
|
[STATEMENT]
lemma porder_on_restrictPI':
"\<lbrakk> porder_on A r; B = A \<inter> C \<rbrakk> \<Longrightarrow> porder_on B (r |` C)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>porder_on A r; B = A \<inter> C\<rbrakk> \<Longrightarrow> porder_on B (r |` C)
[PROOF STEP]
by(simp add: porder_on_restrictPI)
|
#ifndef TRADESREQUESTPARAMETERS_HPP
#define TRADESREQUESTPARAMETERS_HPP
#include <QVariant>
#include <QMetaType>
#include <boost/optional.hpp>
#include "basictypes.h"
namespace bitinvest {
namespace core {
namespace bom {
struct TradesParameters
{
TradesParameters():
mSymbol(boost::none),
mFilterSpecifier(boost::none),
mDataSpecifier(boost::none)
{}
TradesParameters(
const Symbol &iSymbol):
mSymbol(iSymbol), mFilterSpecifier(boost::none), mDataSpecifier(boost::none)
{}
TradesParameters(
const Symbol &iSymbol,
const DataSpecifier& iDataSpecifier):
mSymbol(iSymbol), mFilterSpecifier(boost::none), mDataSpecifier(iDataSpecifier)
{}
TradesParameters(
const Symbol &iSymbol,
const FilterSpecifier & iFilterSpecifier):
mSymbol(iSymbol), mFilterSpecifier(iFilterSpecifier), mDataSpecifier(boost::none)
{}
TradesParameters(
const Symbol & iSymbol,
const FilterSpecifier & iFilterSpecifier,
const DataSpecifier & iDataSpecifier):
mSymbol(iSymbol), mFilterSpecifier(iFilterSpecifier), mDataSpecifier(iDataSpecifier)
{}
TradesParameters(const TradesParameters & other):
mSymbol(other.mSymbol), mFilterSpecifier(other.mFilterSpecifier), mDataSpecifier(other.mDataSpecifier)
{}
boost::optional<Symbol> mSymbol;
boost::optional<FilterSpecifier> mFilterSpecifier;
boost::optional<DataSpecifier> mDataSpecifier;
};
}
}
}
Q_DECLARE_METATYPE(bitinvest::core::bom::TradesParameters)
#endif // TRADESREQUESTPARAMETERS_HPP
|
State Before: l : Type ?u.916992
m : Type u_2
n : Type u_1
o : Type ?u.917001
m' : o → Type ?u.917006
n' : o → Type ?u.917011
R : Type ?u.917014
S : Type ?u.917017
α : Type v
β : Type w
γ : Type ?u.917024
inst✝¹ : NonUnitalCommSemiring α
inst✝ : Fintype n
A : Matrix m n α
x : n → α
⊢ vecMul x Aᵀ = mulVec A x State After: case h
l : Type ?u.916992
m : Type u_2
n : Type u_1
o : Type ?u.917001
m' : o → Type ?u.917006
n' : o → Type ?u.917011
R : Type ?u.917014
S : Type ?u.917017
α : Type v
β : Type w
γ : Type ?u.917024
inst✝¹ : NonUnitalCommSemiring α
inst✝ : Fintype n
A : Matrix m n α
x : n → α
x✝ : m
⊢ vecMul x Aᵀ x✝ = mulVec A x x✝ Tactic: ext State Before: case h
l : Type ?u.916992
m : Type u_2
n : Type u_1
o : Type ?u.917001
m' : o → Type ?u.917006
n' : o → Type ?u.917011
R : Type ?u.917014
S : Type ?u.917017
α : Type v
β : Type w
γ : Type ?u.917024
inst✝¹ : NonUnitalCommSemiring α
inst✝ : Fintype n
A : Matrix m n α
x : n → α
x✝ : m
⊢ vecMul x Aᵀ x✝ = mulVec A x x✝ State After: no goals Tactic: apply dotProduct_comm
|
/*
Copyright (C) 2016 Quaternion Risk Management Ltd
All rights reserved.
This file is part of ORE, a free-software/open-source library
for transparent pricing and risk analysis - http://opensourcerisk.org
ORE is free software: you can redistribute it and/or modify it
under the terms of the Modified BSD License. You should have received a
copy of the license along with this program.
The license is also available online at <http://opensourcerisk.org>
This program is distributed on the basis that it will form a useful
contribution to risk analytics and model standardisation, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.
*/
/*! \file ored/utilities/indexparser.cpp
\brief
\ingroup utilities
*/
#include <boost/algorithm/string.hpp>
#include <boost/make_shared.hpp>
#include <map>
#include <ored/configuration/conventions.hpp>
#include <ored/utilities/indexparser.hpp>
#include <ored/utilities/parsers.hpp>
#include <ql/errors.hpp>
#include <ql/indexes/all.hpp>
#include <ql/time/calendars/target.hpp>
#include <ql/time/daycounters/all.hpp>
#include <qle/indexes/bmaindexwrapper.hpp>
#include <qle/indexes/dkcpi.hpp>
#include <qle/indexes/equityindex.hpp>
#include <qle/indexes/fxindex.hpp>
#include <qle/indexes/genericiborindex.hpp>
#include <qle/indexes/ibor/audbbsw.hpp>
#include <qle/indexes/ibor/brlcdi.hpp>
#include <qle/indexes/ibor/chfsaron.hpp>
#include <qle/indexes/ibor/chftois.hpp>
#include <qle/indexes/ibor/clpcamara.hpp>
#include <qle/indexes/ibor/copibr.hpp>
#include <qle/indexes/ibor/corra.hpp>
#include <qle/indexes/ibor/czkpribor.hpp>
#include <qle/indexes/ibor/demlibor.hpp>
#include <qle/indexes/ibor/dkkcibor.hpp>
#include <qle/indexes/ibor/dkkois.hpp>
#include <qle/indexes/ibor/hkdhibor.hpp>
#include <qle/indexes/ibor/hufbubor.hpp>
#include <qle/indexes/ibor/idridrfix.hpp>
#include <qle/indexes/ibor/idrjibor.hpp>
#include <qle/indexes/ibor/ilstelbor.hpp>
#include <qle/indexes/ibor/inrmifor.hpp>
#include <qle/indexes/ibor/krwcd.hpp>
#include <qle/indexes/ibor/krwkoribor.hpp>
#include <qle/indexes/ibor/mxntiie.hpp>
#include <qle/indexes/ibor/myrklibor.hpp>
#include <qle/indexes/ibor/noknibor.hpp>
#include <qle/indexes/ibor/nowa.hpp>
#include <qle/indexes/ibor/nzdbkbm.hpp>
#include <qle/indexes/ibor/plnpolonia.hpp>
#include <qle/indexes/ibor/phpphiref.hpp>
#include <qle/indexes/ibor/plnwibor.hpp>
#include <qle/indexes/ibor/rubmosprime.hpp>
#include <qle/indexes/ibor/saibor.hpp>
#include <qle/indexes/ibor/seksior.hpp>
#include <qle/indexes/ibor/sekstibor.hpp>
#include <qle/indexes/ibor/sgdsibor.hpp>
#include <qle/indexes/ibor/sgdsor.hpp>
#include <qle/indexes/ibor/skkbribor.hpp>
#include <qle/indexes/ibor/thbbibor.hpp>
#include <qle/indexes/ibor/tonar.hpp>
#include <qle/indexes/ibor/twdtaibor.hpp>
#include <qle/indexes/secpi.hpp>
using namespace QuantLib;
using namespace QuantExt;
using namespace std;
using ore::data::Convention;
namespace ore {
namespace data {
// Helper build classes for static map
class IborIndexParser {
public:
virtual ~IborIndexParser() {}
virtual boost::shared_ptr<IborIndex> build(Period p, const Handle<YieldTermStructure>& h) const = 0;
};
template <class T> class IborIndexParserWithPeriod : public IborIndexParser {
public:
boost::shared_ptr<IborIndex> build(Period p, const Handle<YieldTermStructure>& h) const override {
QL_REQUIRE(p != 1 * Days, "must have a period longer than 1D");
return boost::make_shared<T>(p, h);
}
};
// Specialise for MXN-TIIE. If tenor equates to 28 Days, i.e. tenor is 4W or 28D, ensure that the index is created
// with a tenor of 4W under the hood. Things work better this way especially cap floor stripping.
template <> class IborIndexParserWithPeriod<MXNTiie> : public IborIndexParser {
public:
boost::shared_ptr<IborIndex> build(Period p, const Handle<YieldTermStructure>& h) const override {
QL_REQUIRE(p != 1 * Days, "must have a period longer than 1D");
if (p.units() == Days && p.length() == 28) {
return boost::make_shared<MXNTiie>(4 * Weeks, h);
} else {
return boost::make_shared<MXNTiie>(p, h);
}
}
};
template <class T> class IborIndexParserOIS : public IborIndexParser {
public:
boost::shared_ptr<IborIndex> build(Period p, const Handle<YieldTermStructure>& h) const override {
QL_REQUIRE(p == 1 * Days, "must have period 1D");
return boost::make_shared<T>(h);
}
};
template <class T> class IborIndexParserBMA : public IborIndexParser {
public:
boost::shared_ptr<IborIndex> build(Period p, const Handle<YieldTermStructure>& h) const override {
QL_REQUIRE((p.length() == 7 && p.units() == Days) || (p.length() == 1 && p.units() == Weeks),
"BMA indexes are uniquely available with a tenor of 1 week.");
const boost::shared_ptr<BMAIndex> bma = boost::make_shared<BMAIndex>(h);
return boost::make_shared<T>(bma);
}
};
boost::shared_ptr<FxIndex> parseFxIndex(const string& s) {
std::vector<string> tokens;
split(tokens, s, boost::is_any_of("-"));
QL_REQUIRE(tokens.size() == 4, "four tokens required in " << s << ": FX-TAG-CCY1-CCY2");
QL_REQUIRE(tokens[0] == "FX", "expected first token to be FX");
return boost::make_shared<FxIndex>(tokens[0] + "/" + tokens[1], 0, parseCurrency(tokens[2]),
parseCurrency(tokens[3]), NullCalendar());
}
boost::shared_ptr<EquityIndex> parseEquityIndex(const string& s) {
std::vector<string> tokens;
split(tokens, s, boost::is_any_of("-"));
QL_REQUIRE(tokens.size() == 2, "two tokens required in " << s << ": EQ-NAME");
QL_REQUIRE(tokens[0] == "EQ", "expected first token to be EQ");
if (tokens.size() == 2) {
return boost::make_shared<EquityIndex>(tokens[1], NullCalendar(), Currency());
} else {
QL_FAIL("Error parsing equity string " + s);
}
}
bool tryParseIborIndex(const string& s, boost::shared_ptr<IborIndex>& index) {
try {
index = parseIborIndex(s);
} catch (...) {
return false;
}
return true;
}
boost::shared_ptr<IborIndex> parseIborIndex(const string& s, const Handle<YieldTermStructure>& h) {
string dummy;
return parseIborIndex(s, dummy, h);
}
boost::shared_ptr<IborIndex> parseIborIndex(const string& s, string& tenor, const Handle<YieldTermStructure>& h) {
std::vector<string> tokens;
split(tokens, s, boost::is_any_of("-"));
QL_REQUIRE(tokens.size() == 2 || tokens.size() == 3,
"Two or three tokens required in " << s << ": CCY-INDEX or CCY-INDEX-TERM");
Period p;
if (tokens.size() == 3) {
tenor = tokens[2];
p = parsePeriod(tokens[2]);
} else {
tenor = "";
p = 1 * Days;
}
static map<string, boost::shared_ptr<IborIndexParser>> m = {
{"EUR-EONIA", boost::make_shared<IborIndexParserOIS<Eonia>>()},
{"GBP-SONIA", boost::make_shared<IborIndexParserOIS<Sonia>>()},
{"JPY-TONAR", boost::make_shared<IborIndexParserOIS<Tonar>>()},
{"CHF-TOIS", boost::make_shared<IborIndexParserOIS<CHFTois>>()},
{"CHF-SARON", boost::make_shared<IborIndexParserOIS<CHFSaron>>()},
{"USD-FedFunds", boost::make_shared<IborIndexParserOIS<FedFunds>>()},
{"AUD-AONIA", boost::make_shared<IborIndexParserOIS<Aonia>>()},
{"CAD-CORRA", boost::make_shared<IborIndexParserOIS<CORRA>>()},
{"DKK-DKKOIS", boost::make_shared<IborIndexParserOIS<DKKOis>>()},
{"DKK-TNR", boost::make_shared<IborIndexParserOIS<DKKOis>>()},
{"SEK-SIOR", boost::make_shared<IborIndexParserOIS<SEKSior>>()},
{"AUD-BBSW", boost::make_shared<IborIndexParserWithPeriod<AUDbbsw>>()},
{"AUD-LIBOR", boost::make_shared<IborIndexParserWithPeriod<AUDLibor>>()},
{"EUR-EURIBOR", boost::make_shared<IborIndexParserWithPeriod<Euribor>>()},
{"EUR-EURIB", boost::make_shared<IborIndexParserWithPeriod<Euribor>>()},
{"CAD-CDOR", boost::make_shared<IborIndexParserWithPeriod<Cdor>>()},
{"CAD-BA", boost::make_shared<IborIndexParserWithPeriod<Cdor>>()},
{"CZK-PRIBOR", boost::make_shared<IborIndexParserWithPeriod<CZKPribor>>()},
{"EUR-LIBOR", boost::make_shared<IborIndexParserWithPeriod<EURLibor>>()},
{"USD-LIBOR", boost::make_shared<IborIndexParserWithPeriod<USDLibor>>()},
{"GBP-LIBOR", boost::make_shared<IborIndexParserWithPeriod<GBPLibor>>()},
{"JPY-LIBOR", boost::make_shared<IborIndexParserWithPeriod<JPYLibor>>()},
{"JPY-TIBOR", boost::make_shared<IborIndexParserWithPeriod<Tibor>>()},
{"CAD-LIBOR", boost::make_shared<IborIndexParserWithPeriod<CADLibor>>()},
{"CHF-LIBOR", boost::make_shared<IborIndexParserWithPeriod<CHFLibor>>()},
{"SEK-LIBOR", boost::make_shared<IborIndexParserWithPeriod<SEKLibor>>()},
{"SEK-STIBOR", boost::make_shared<IborIndexParserWithPeriod<SEKStibor>>()},
{"NOK-NIBOR", boost::make_shared<IborIndexParserWithPeriod<NOKNibor>>()},
{"HKD-HIBOR", boost::make_shared<IborIndexParserWithPeriod<HKDHibor>>()},
{"SAR-SAIBOR", boost::make_shared<IborIndexParserWithPeriod<SAibor>>()},
{"SGD-SIBOR", boost::make_shared<IborIndexParserWithPeriod<SGDSibor>>()},
{"SGD-SOR", boost::make_shared<IborIndexParserWithPeriod<SGDSor>>()},
{"DKK-CIBOR", boost::make_shared<IborIndexParserWithPeriod<DKKCibor>>()},
{"DKK-LIBOR", boost::make_shared<IborIndexParserWithPeriod<DKKLibor>>()},
{"HUF-BUBOR", boost::make_shared<IborIndexParserWithPeriod<HUFBubor>>()},
{"IDR-IDRFIX", boost::make_shared<IborIndexParserWithPeriod<IDRIdrfix>>()},
{"IDR-JIBOR", boost::make_shared<IborIndexParserWithPeriod<IDRJibor>>()},
{"ILS-TELBOR", boost::make_shared<IborIndexParserWithPeriod<ILSTelbor>>()},
{"INR-MIFOR", boost::make_shared<IborIndexParserWithPeriod<INRMifor>>()},
{"MXN-TIIE", boost::make_shared<IborIndexParserWithPeriod<MXNTiie>>()},
{"PLN-WIBOR", boost::make_shared<IborIndexParserWithPeriod<PLNWibor>>()},
{"SKK-BRIBOR", boost::make_shared<IborIndexParserWithPeriod<SKKBribor>>()},
{"NZD-BKBM", boost::make_shared<IborIndexParserWithPeriod<NZDBKBM>>()},
{"TRY-TRLIBOR", boost::make_shared<IborIndexParserWithPeriod<TRLibor>>()},
{"TWD-TAIBOR", boost::make_shared<IborIndexParserWithPeriod<TWDTaibor>>()},
{"MYR-KLIBOR", boost::make_shared<IborIndexParserWithPeriod<MYRKlibor>>()},
{"KRW-CD", boost::make_shared<IborIndexParserWithPeriod<KRWCd>>()},
{"KRW-KORIBOR", boost::make_shared<IborIndexParserWithPeriod<KRWKoribor>>()},
{"ZAR-JIBAR", boost::make_shared<IborIndexParserWithPeriod<Jibar>>()},
{"RUB-MOSPRIME", boost::make_shared<IborIndexParserWithPeriod<RUBMosprime>>()},
{"USD-SIFMA", boost::make_shared<IborIndexParserBMA<BMAIndexWrapper>>()},
{"THB-BIBOR", boost::make_shared<IborIndexParserWithPeriod<THBBibor>>()},
{"PHP-PHIREF", boost::make_shared<IborIndexParserWithPeriod<PHPPhiref>>()},
{"COP-IBR", boost::make_shared<IborIndexParserOIS<COPIbr>>()},
{"DEM-LIBOR", boost::make_shared<IborIndexParserWithPeriod<DEMLibor>>()},
{"BRL-CDI", boost::make_shared<IborIndexParserOIS<BRLCdi>>()},
{"NOK-NOWA", boost::make_shared<IborIndexParserOIS<Nowa>>()},
{"CLP-CAMARA", boost::make_shared<IborIndexParserOIS<CLPCamara>>()},
{"NZD-OCR", boost::make_shared<IborIndexParserOIS<Nzocr>>()},
{"PLN-POLONIA", boost::make_shared<IborIndexParserOIS<PLNPolonia>>()}};
auto it = m.find(tokens[0] + "-" + tokens[1]);
if (it != m.end()) {
return it->second->build(p, h);
} else if (tokens[1] == "GENERIC") {
// We have a generic index
auto ccy = parseCurrency(tokens[0]);
return boost::make_shared<GenericIborIndex>(p, ccy, h);
} else {
QL_FAIL("parseIborIndex \"" << s << "\" not recognized");
}
}
bool isGenericIndex(const string& indexName) {
return indexName.find("-GENERIC-") != string::npos;
}
bool isInflationIndex(const string& indexName) {
try {
// Currently, only way to have an inflation index is to have a ZeroInflationIndex
parseZeroInflationIndex(indexName);
} catch (...) {
return false;
}
return true;
}
// Swap Index Parser base
class SwapIndexParser {
public:
virtual ~SwapIndexParser() {}
virtual boost::shared_ptr<SwapIndex> build(Period p, const Handle<YieldTermStructure>& f,
const Handle<YieldTermStructure>& d) const = 0;
};
// We build with both a forwarding and discounting curve
template <class T> class SwapIndexParserDualCurve : public SwapIndexParser {
public:
boost::shared_ptr<SwapIndex> build(Period p, const Handle<YieldTermStructure>& f,
const Handle<YieldTermStructure>& d) const override {
return boost::make_shared<T>(p, f, d);
}
};
boost::shared_ptr<SwapIndex> parseSwapIndex(const string& s, const Handle<YieldTermStructure>& f,
const Handle<YieldTermStructure>& d,
boost::shared_ptr<data::IRSwapConvention> convention) {
std::vector<string> tokens;
split(tokens, s, boost::is_any_of("-"));
QL_REQUIRE(tokens.size() == 3, "three tokens required in " << s << ": CCY-CMS-TENOR");
QL_REQUIRE(tokens[0].size() == 3, "invalid currency code in " << s);
QL_REQUIRE(tokens[1] == "CMS", "expected CMS as middle token in " << s);
Period p = parsePeriod(tokens[2]);
string familyName = tokens[0] + "LiborSwapIsdaFix";
Currency ccy = parseCurrency(tokens[0]);
boost::shared_ptr<IborIndex> index =
f.empty() || !convention ? boost::shared_ptr<IborIndex>() : convention->index()->clone(f);
QuantLib::Natural settlementDays = index ? index->fixingDays() : 0;
QuantLib::Calendar calender = convention ? convention->fixedCalendar() : NullCalendar();
Period fixedLegTenor = convention ? Period(convention->fixedFrequency()) : Period(1, Months);
BusinessDayConvention fixedLegConvention = convention ? convention->fixedConvention() : ModifiedFollowing;
DayCounter fixedLegDayCounter = convention ? convention->fixedDayCounter() : ActualActual();
if (d.empty())
return boost::make_shared<SwapIndex>(familyName, p, settlementDays, ccy, calender, fixedLegTenor,
fixedLegConvention, fixedLegDayCounter, index);
else
return boost::make_shared<SwapIndex>(familyName, p, settlementDays, ccy, calender, fixedLegTenor,
fixedLegConvention, fixedLegDayCounter, index, d);
}
// Zero Inflation Index Parser
class ZeroInflationIndexParserBase {
public:
virtual ~ZeroInflationIndexParserBase() {}
virtual boost::shared_ptr<ZeroInflationIndex> build(bool isInterpolated,
const Handle<ZeroInflationTermStructure>& h) const = 0;
};
template <class T> class ZeroInflationIndexParser : public ZeroInflationIndexParserBase {
public:
boost::shared_ptr<ZeroInflationIndex> build(bool isInterpolated,
const Handle<ZeroInflationTermStructure>& h) const override {
return boost::make_shared<T>(isInterpolated, h);
}
};
boost::shared_ptr<ZeroInflationIndex> parseZeroInflationIndex(const string& s, bool isInterpolated,
const Handle<ZeroInflationTermStructure>& h) {
static map<string, boost::shared_ptr<ZeroInflationIndexParserBase>> m = {
{"EUHICP", boost::make_shared<ZeroInflationIndexParser<EUHICP>>()},
{"EU HICP", boost::make_shared<ZeroInflationIndexParser<EUHICP>>()},
{"EUHICPXT", boost::make_shared<ZeroInflationIndexParser<EUHICPXT>>()},
{"EU HICPXT", boost::make_shared<ZeroInflationIndexParser<EUHICPXT>>()},
{"FRHICP", boost::make_shared<ZeroInflationIndexParser<FRHICP>>()},
{"FR HICP", boost::make_shared<ZeroInflationIndexParser<FRHICP>>()},
{"UKRPI", boost::make_shared<ZeroInflationIndexParser<UKRPI>>()},
{"UK RPI", boost::make_shared<ZeroInflationIndexParser<UKRPI>>()},
{"USCPI", boost::make_shared<ZeroInflationIndexParser<USCPI>>()},
{"US CPI", boost::make_shared<ZeroInflationIndexParser<USCPI>>()},
{"ZACPI", boost::make_shared<ZeroInflationIndexParser<ZACPI>>()},
{"ZA CPI", boost::make_shared<ZeroInflationIndexParser<ZACPI>>()},
{"SECPI", boost::make_shared<ZeroInflationIndexParser<SECPI>>()},
{"DKCPI", boost::make_shared<ZeroInflationIndexParser<DKCPI>>()}};
auto it = m.find(s);
if (it != m.end()) {
return it->second->build(isInterpolated, h);
} else {
QL_FAIL("parseZeroInflationIndex: \"" << s << "\" not recognized");
}
}
boost::shared_ptr<Index> parseIndex(const string& s, const data::Conventions& conventions) {
boost::shared_ptr<QuantLib::Index> ret_idx;
try {
ret_idx = parseIborIndex(s);
} catch (...) {
}
if (!ret_idx) {
try {
auto c = boost::dynamic_pointer_cast<SwapIndexConvention>(conventions.get(s));
QL_REQUIRE(c, "no swap index convention");
auto c2 = boost::dynamic_pointer_cast<IRSwapConvention>(conventions.get(c->conventions()));
QL_REQUIRE(c2, "no swap convention");
ret_idx = parseSwapIndex(s, Handle<YieldTermStructure>(), Handle<YieldTermStructure>(), c2);
} catch (...) {
}
}
if (!ret_idx) {
try {
ret_idx = parseZeroInflationIndex(s);
} catch (...) {
}
}
if (!ret_idx) {
try {
ret_idx = parseFxIndex(s);
} catch (...) {
}
}
if (!ret_idx) {
try {
ret_idx = parseEquityIndex(s);
} catch (...) {
}
}
QL_REQUIRE(ret_idx, "parseIndex \"" << s << "\" not recognized");
return ret_idx;
}
bool isOvernightIndex(const string& indexName) {
boost::shared_ptr<IborIndex> index;
if (tryParseIborIndex(indexName, index)) {
auto onIndex = boost::dynamic_pointer_cast<OvernightIndex>(index);
if (onIndex)
return true;
}
return false;
}
} // namespace data
} // namespace ore
|
Formal statement is: lemma finite_imp_null_set_lborel: "finite A \<Longrightarrow> A \<in> null_sets lborel" Informal statement is: If $A$ is a finite set, then $A$ is a null set.
|
If $g$ is eventually nonzero, then $f \in L^1$ if and only if $f g \in L^1$.
|
Require Import UniMath.Foundations.Generalities.uu0.
Require Import UniMath.Foundations.hlevel1.hProp.
Require Import UniMath.Foundations.hlevel2.hSet.
Require Import UniMath.RezkCompletion.precategories.
Require Import UniMath.RezkCompletion.functor_categories.
Require Import SubstSystems.UnicodeNotations.
Require Import UniMath.RezkCompletion.whiskering.
Require Import UniMath.RezkCompletion.Monads.
Require Import UniMath.RezkCompletion.FunctorAlgebras.
Require Import UniMath.RezkCompletion.limits.coproducts.
Require Import SubstSystems.Auxiliary.
Require Import SubstSystems.PointedFunctors.
Require Import SubstSystems.ProductPrecategory.
Require Import SubstSystems.HorizontalComposition.
Require Import SubstSystems.PointedFunctorsComposition.
Require Import SubstSystems.EndofunctorsMonoidal.
Require Import SubstSystems.Signatures.
(* Require Import SubstSystems.FunctorAlgebraViews. *)
Require Import SubstSystems.FunctorsPointwiseCoproduct.
Local Notation "# F" := (functor_on_morphisms F)(at level 3).
Local Notation "F ⟶ G" := (nat_trans F G) (at level 39).
Arguments functor_composite {_ _ _} _ _ .
Arguments nat_trans_comp {_ _ _ _ _} _ _ .
Local Notation "G ∙ F" := (functor_composite F G : [ _ , _ , _ ]) (at level 35).
Local Notation "α ∙∙ β" := (hor_comp β α) (at level 20).
Ltac pathvia b := (apply (@pathscomp0 _ _ b _ )).
Local Notation "α 'ø' Z" := (pre_whisker Z α) (at level 25).
Local Notation "Z ∘ α" := (post_whisker _ _ _ _ α Z) (at level 35).
Local Notation "C ⟦ a , b ⟧" := (precategory_morphisms (C:=C) a b) (at level 50).
Section def_hss.
(** ** Some variables and assumptions *)
(** Assume having a precategory [C] whose hom-types are sets *)
Variable C : precategory.
Variable hs : has_homsets C.
Variable CP : Coproducts C.
Local Notation "'EndC'":= ([C, C, hs]) .
Let hsEndC : has_homsets EndC := functor_category_has_homsets C C hs.
Let CPEndC : Coproducts EndC := Coproducts_functor_precat _ _ CP hs.
Variable H : Signature C hs.
Let θ := theta H.
Let θ_strength1_int := Sig_strength_law1 _ _ H.
Let θ_strength2_int := Sig_strength_law2 _ _ H.
Let Id_H
: functor EndC EndC
:= coproduct_functor _ _ CPEndC
(constant_functor _ _ (functor_identity _ : EndC))
H.
(*
(** [H] is a rank-2 endofunctor on endofunctors *)
Variable H : functor [C, C, hs] [C, C, hs].
*)
(** The forgetful functor from pointed endofunctors to endofunctors *)
Local Notation "'U'" := (functor_ptd_forget C hs).
(** The precategory of pointed endofunctors on [C] *)
Local Notation "'Ptd'" := (precategory_Ptd C hs).
(** The category of endofunctors on [C] *)
Local Notation "'EndC'":= ([C, C, hs]) .
(** The product of two precategories *)
Local Notation "A 'XX' B" := (product_precategory A B) (at level 2).
(** Pre-whiskering defined as morphism part of the functor given by precomposition
with a fixed functor *)
Local Notation "α 'øø' Z" := (# (pre_composition_functor_data _ _ _ hs _ Z) α) (at level 25).
Local Notation "A ⊗ B" := (prodcatpair _ _ A B) (at level 10).
Local Coercion alg_carrier : algebra_ob >-> ob.
(* Local Notation "'τ'" := (tau). *)
(** ** Definition of algebra structure [τ] of a pointed functor *)
(*
Definition AlgStruct (T : Ptd) : UU := pr1 (H(U T)) ⟶ pr1 (U T).
Definition Alg : UU := Σ T : Ptd, AlgStruct T.
Coercion PtdFromAlg (T : Alg) : Ptd := pr1 T.
Definition τ (T : Alg) : pr1 (H (U T)) ⟶ pr1 (U T) := pr2 T.
*)
(* An Id_H algebra is a pointed functor *)
Definition eta_from_alg (T : algebra_ob _ Id_H) : EndC ⟦ functor_identity _, T ⟧.
Proof.
exact (CoproductIn1 _ _ ;; alg_map _ _ T).
Defined.
Definition ptd_from_alg (T : algebra_ob _ Id_H) : Ptd.
Proof.
exists (pr1 T).
exact (eta_from_alg T).
Defined.
Definition tau_from_alg (T : algebra_ob _ Id_H) : EndC ⟦H T, T⟧.
Proof.
exact (CoproductIn2 _ _ ;; alg_map _ _ T).
Defined.
Local Notation "'p' T" := (ptd_from_alg T) (at level 3).
(*
Coercion functor_from_algebra_ob (X : algebra_ob _ Id_H) : functor C C := pr1 X.
*)
Local Notation "` T" := (alg_carrier _ _ T : functor C C) (at level 3).
Local Notation "f ⊕ g" := (CoproductOfArrows _ (CPEndC _ _ ) (CPEndC _ _ ) f g) (at level 40).
(*
Definition bracket (T : algebra_ob _ Id_H) : UU :=
∀ (Z : Ptd) (f : Z ⇒ ptd_from_alg T), iscontr
(Σ h : `T ∙ (U Z) ⇒ T,
alg_map _ _ T øø (U Z) ;; h =
CoproductOfArrows _ (CPEndC _ _ ) (CPEndC _ _ ) (identity (U Z)) (θ (`T ⊗ Z)) ;;
CoproductOfArrows _ (CPEndC _ _ ) (CPEndC _ _ ) (identity (U Z)) (#H h) ;;
CoproductArrow _ (CPEndC _ _ ) (#U f) (tau_from_alg T )).
*)
Definition bracket_property (T : algebra_ob _ Id_H) {Z : Ptd} (f : Z ⇒ ptd_from_alg T)
(h : `T ∙ (U Z) ⇒ T) : UU
:=
alg_map _ _ T øø (U Z) ;; h =
identity (U Z) ⊕ θ (`T ⊗ Z) ;;
identity (U Z) ⊕ #H h ;;
CoproductArrow _ (CPEndC _ _ ) (#U f) (tau_from_alg T).
Definition bracket_at (T : algebra_ob _ Id_H) {Z : Ptd} (f : Z ⇒ ptd_from_alg T): UU :=
iscontr
(Σ h : `T ∙ (U Z) ⇒ T, bracket_property T f h).
Definition bracket (T : algebra_ob _ Id_H) : UU
:= ∀ (Z : Ptd) (f : Z ⇒ ptd_from_alg T), bracket_at T f.
Definition bracket_property_parts (T : algebra_ob _ Id_H) {Z : Ptd} (f : Z ⇒ ptd_from_alg T)
(h : `T ∙ (U Z) ⇒ T) : UU
:=
(#U f = eta_from_alg T øø (U Z) ;; h) ×
(θ (`T ⊗ Z) ;; #H h ;; tau_from_alg T = tau_from_alg T øø (U Z) ;; h).
Definition bracket_parts_at (T : algebra_ob _ Id_H) {Z : Ptd} (f : Z ⇒ ptd_from_alg T) : UU :=
iscontr
(Σ h : `T ∙ (U Z) ⇒ T, bracket_property_parts T f h).
Definition bracket_parts (T : algebra_ob _ Id_H) : UU
:= ∀ (Z : Ptd) (f : Z ⇒ ptd_from_alg T), bracket_parts_at T f.
(* show that for any h of suitable type, the following are equivalent *)
Lemma parts_from_whole (T : algebra_ob _ Id_H) (Z : Ptd) (f : Z ⇒ ptd_from_alg T)
(h : `T ∙ (U Z) ⇒ T) :
bracket_property T f h → bracket_property_parts T f h.
(*
alg_map _ _ T øø (U Z) ;; h =
identity (U Z) ⊕ θ (`T ⊗ Z) ;;
identity (U Z) ⊕ #H h ;;
CoproductArrow _ (CPEndC _ _ ) (#U f) (tau_from_alg T ) →
(#U f = eta_from_alg T øø (U Z) ;; h) ×
(θ (`T ⊗ Z) ;; #H h ;; tau_from_alg T = tau_from_alg T øø (U Z) ;; h ).
*)
Proof.
intro Hyp.
(* assert (Hyp_inst := maponpaths (fun m:EndC⟦_,_⟧ => CoproductIn1 ([C, C] hs)
(CPEndC
((constant_functor ([C, C] hs) ([C, C] hs) (functor_identity C)) T)
(H T));;m) Hyp). *)
split.
+ unfold eta_from_alg.
apply nat_trans_eq; try (exact hs).
intro c.
simpl.
unfold coproduct_nat_trans_in1_data.
assert (Hyp_inst := nat_trans_eq_pointwise _ _ _ _ _ _ Hyp c); clear Hyp.
apply (maponpaths (fun m => CoproductIn1 C (CP _ _);; m)) in Hyp_inst.
match goal with |[ H1 : _ = ?f |- _ = _ ] =>
pathvia (f) end.
* clear Hyp_inst.
rewrite <- assoc.
apply CoproductIn1Commutes_right_in_ctx_dir.
rewrite id_left.
apply CoproductIn1Commutes_right_in_ctx_dir.
rewrite id_left.
apply CoproductIn1Commutes_right_dir.
apply idpath.
* rewrite <- Hyp_inst; clear Hyp_inst.
rewrite <- assoc.
apply idpath.
+ unfold tau_from_alg.
apply nat_trans_eq; try (exact hs).
intro c.
simpl.
unfold coproduct_nat_trans_in2_data.
assert (Hyp_inst := nat_trans_eq_pointwise _ _ _ _ _ _ Hyp c); clear Hyp.
apply (maponpaths (fun m => CoproductIn2 C (CP _ _);; m)) in Hyp_inst.
match goal with |[ H1 : _ = ?f |- _ = _ ] =>
pathvia (f) end.
* clear Hyp_inst.
do 2 rewrite <- assoc.
apply CoproductIn2Commutes_right_in_ctx_dir.
simpl.
rewrite <- assoc.
apply maponpaths.
apply CoproductIn2Commutes_right_in_ctx_dir.
simpl.
rewrite <- assoc.
apply maponpaths.
unfold tau_from_alg.
apply CoproductIn2Commutes_right_dir.
apply idpath.
* rewrite <- Hyp_inst; clear Hyp_inst.
rewrite <- assoc.
apply idpath.
Qed.
Lemma whole_from_parts (T : algebra_ob _ Id_H) (Z : Ptd) (f : Z ⇒ ptd_from_alg T)
(h : `T ∙ (U Z) ⇒ T) :
bracket_property_parts T f h → bracket_property T f h.
(*
(#U f = eta_from_alg T øø (U Z) ;; h) ×
(θ (`T ⊗ Z) ;; #H h ;; tau_from_alg T = tau_from_alg T øø (U Z) ;; h )
→
alg_map _ _ T øø (U Z) ;; h =
identity (U Z) ⊕ θ (`T ⊗ Z) ;;
identity (U Z) ⊕ #H h ;;
CoproductArrow _ (CPEndC _ _ ) (#U f) (tau_from_alg T ).
*)
Proof.
intros [Hyp1 Hyp2].
apply nat_trans_eq; try (exact hs).
intro c.
apply CoproductArrow_eq_cor.
+ clear Hyp2.
assert (Hyp1_inst := nat_trans_eq_pointwise _ _ _ _ _ _ Hyp1 c); clear Hyp1.
rewrite <- assoc.
apply CoproductIn1Commutes_right_in_ctx_dir.
rewrite id_left.
apply CoproductIn1Commutes_right_in_ctx_dir.
rewrite id_left.
apply CoproductIn1Commutes_right_dir.
rewrite Hyp1_inst.
simpl.
apply assoc.
+ clear Hyp1.
assert (Hyp2_inst := nat_trans_eq_pointwise _ _ _ _ _ _ Hyp2 c); clear Hyp2.
rewrite <- assoc.
apply CoproductIn2Commutes_right_in_ctx_dir.
simpl.
rewrite assoc.
eapply pathscomp0.
* eapply pathsinv0.
exact Hyp2_inst.
* clear Hyp2_inst.
simpl.
do 2 rewrite <- assoc.
apply maponpaths.
apply CoproductIn2Commutes_right_in_ctx_dir.
simpl.
rewrite <- assoc.
apply maponpaths.
apply CoproductIn2Commutes_right_dir.
apply idpath.
Qed.
(* show bracket_parts_point is logically equivalent to bracket_point, then
use it to show that bracket_parts is equivalent to bracket using [weqonsecfibers:
∀ (X : UU) (P Q : X → UU),
(∀ x : X, P x ≃ Q x) → (∀ x : X, P x) ≃ (∀ x : X, Q x)] *)
Definition hss : UU := Σ T, bracket T.
Coercion alg_from_hss (T : hss) : algebra_ob _ Id_H := pr1 T.
Definition fbracket (T : hss) {Z : Ptd} (f : Z ⇒ ptd_from_alg T)
: `T ∙ (U Z) ⇒ T
:= pr1 (pr1 (pr2 T Z f)).
(** The bracket operation [fbracket] is unique *)
Definition fbracket_unique_pointwise (T : hss) {Z : Ptd} (f : Z ⇒ ptd_from_alg T)
: ∀ (α : functor_composite (U Z) `T ⟶ `T),
(∀ c : C, pr1 (#U f) c = pr1 (eta_from_alg T) (pr1 (U Z) c) ;; α c) →
(∀ c : C, pr1 (θ (`T ⊗ Z)) c ;; pr1 (#H α) c ;; pr1 (tau_from_alg T) c =
pr1 (tau_from_alg T) (pr1 (U Z) c) ;; α c) → α = fbracket T f.
Proof.
intros α H1 H2.
apply path_to_ctr.
apply whole_from_parts.
split.
- apply nat_trans_eq; try assumption.
- apply nat_trans_eq; assumption.
Qed.
Definition fbracket_unique (T : hss) {Z : Ptd} (f : Z ⇒ ptd_from_alg T)
: ∀ α : functor_composite (U Z)(`T) ⟶ `T,
bracket_property_parts T f α
(*
(#U f = eta_from_alg T øø ((U Z)) ;; α) →
(θ (`T ⊗ Z) ;; #H α ;; tau_from_alg T = tau_from_alg T øø (U Z) ;; α)
*)
→ α = fbracket T f.
Proof.
intros α [H1 H2].
apply path_to_ctr.
apply whole_from_parts.
split; assumption.
Qed.
Definition fbracket_unique_target_pointwise (T : hss) {Z : Ptd} (f : Z ⇒ ptd_from_alg T)
: ∀ α : functor_composite (U Z)(`T) ⟶ `T,
bracket_property_parts T f α
(*
(#U f = eta_from_alg T øø U Z ;; α) →
(θ (`T ⊗ Z) ;; #H α ;; tau_from_alg T = tau_from_alg T øø U Z ;; α)
*)
→ ∀ c, α c = pr1 (fbracket T f) c.
Proof.
intros α H12.
set (t:= fbracket_unique _ _ α H12).
apply (nat_trans_eq_weq _ _ hs _ _ _ _ t).
Qed.
(** Properties of [fbracket] by definition: commutative diagrams *)
Lemma fbracket_η (T : hss) : ∀ {Z : Ptd} (f : Z ⇒ ptd_from_alg T),
#U f = eta_from_alg T øø U Z ;; fbracket T f.
Proof.
intros Z f.
(* assert (H' := parts_from_whole T Z f (fbracket _ f)) . *)
exact (pr1 (parts_from_whole _ _ _ _ (pr2 (pr1 (pr2 T Z f))))).
Qed.
Lemma fbracket_τ (T : hss) : ∀ {Z : Ptd} (f : Z ⇒ ptd_from_alg T),
θ (`T ⊗ Z) ;; #H (fbracket T f) ;; tau_from_alg T
=
tau_from_alg T øø U Z ;; (fbracket T f).
Proof.
intros Z f.
exact (pr2 (parts_from_whole _ _ _ _ (pr2 (pr1 (pr2 T Z f))))).
Qed.
(** [fbracket] is also natural *)
Lemma fbracket_natural (T : hss) {Z Z' : Ptd} (f : Z ⇒ Z') (g : Z' ⇒ ptd_from_alg T)
: post_whisker _ _ _ _ (#U f)(`T) ;; fbracket T g = fbracket T (f ;; g).
Proof.
apply fbracket_unique_pointwise.
- simpl. intro c.
rewrite assoc.
set (H':=nat_trans_ax (eta_from_alg T)).
simpl in H'.
rewrite <- H'; clear H'.
rewrite <- assoc.
apply maponpaths.
set (X:= nat_trans_eq_weq _ _ hs _ _ _ _ (fbracket_η T g)).
simpl in X. exact (X _ ).
- intro c; simpl.
assert (H':=nat_trans_ax (tau_from_alg T)).
simpl in H'.
eapply pathscomp0. Focus 2. apply (!assoc _ _ _ _ _ _ _ _ ).
eapply pathscomp0. Focus 2. apply cancel_postcomposition. apply H'.
clear H'.
set (H':=fbracket_τ T g).
simpl in H'.
assert (X:= nat_trans_eq_pointwise _ _ _ _ _ _ H' c).
simpl in X.
rewrite <- assoc.
rewrite <- assoc.
transitivity ( # (pr1 (H ((`T)))) (pr1 (pr1 f) c) ;;
(pr1 (θ ((`T) ⊗ Z')) c);; pr1 (# H (fbracket T g)) c;; pr1 (tau_from_alg T) c).
Focus 2.
rewrite <- assoc.
rewrite <- assoc.
apply maponpaths.
repeat rewrite assoc.
apply X.
clear X.
set (A:=θ_nat_2_pointwise).
simpl in *.
set (A':= A _ hs H θ (`T) Z Z').
simpl in A'.
set (A2:= A' f).
clearbody A2; clear A'; clear A.
rewrite A2; clear A2.
repeat rewrite <- assoc.
apply maponpaths.
simpl.
repeat rewrite assoc.
apply cancel_postcomposition.
set (A := functor_comp H).
simpl in A.
rewrite A.
apply cancel_postcomposition.
clear A. clear H'.
set (A:=horcomp_id_postwhisker C _ _ hs hs).
rewrite A.
apply idpath.
Qed.
(** As a consequence of naturality, we can compute [fbracket f] from [fbracket identity] *)
Lemma compute_fbracket (T : hss) : ∀ {Z : Ptd} (f : Z ⇒ ptd_from_alg T),
fbracket T f = post_whisker _ _ _ _ (#U f)(`T) ;; fbracket T (identity _ ).
Proof.
intros Z f.
assert (A : f = f ;; identity _ ).
{ rewrite id_right; apply idpath. }
rewrite A.
rewrite <- fbracket_natural.
rewrite id_right.
apply idpath.
Qed.
(** ** Morphisms of heterogeneous substitution systems *)
(** A morphism [f] of pointed functors is an algebra morphism when... *)
(*
Definition isAlgMor {T T' : Alg} (f : T ⇒ T') : UU :=
#H (# U f) ;; τ T' = compose (C:=EndC) (τ T) (#U f).
Lemma isaprop_isAlgMor (T T' : Alg) (f : T ⇒ T') : isaprop (isAlgMor f).
Proof.
apply isaset_nat_trans.
apply hs.
Qed.
*)
(** a little preparation for much later *)
Lemma τ_part_of_alg_mor (T T' : algebra_ob ([C, C] hs) Id_H)
(β : algebra_mor ([C, C] hs) Id_H T T'): #H β ;; tau_from_alg T' = compose (C:=EndC) (tau_from_alg T) β.
Proof.
assert (β_is_alg_mor := pr2 β).
simpl in β_is_alg_mor.
assert (β_is_alg_mor_inst := maponpaths (fun m:EndC⟦_,_⟧ => (CoproductIn2 EndC (CPEndC _ _));; m) β_is_alg_mor); clear β_is_alg_mor.
simpl in β_is_alg_mor_inst.
apply nat_trans_eq; try (exact hs).
intro c.
assert (β_is_alg_mor_inst':= nat_trans_eq_pointwise _ _ _ _ _ _ β_is_alg_mor_inst c); clear β_is_alg_mor_inst.
simpl in β_is_alg_mor_inst'.
rewrite assoc in β_is_alg_mor_inst'.
eapply pathscomp0.
Focus 2.
eapply pathsinv0.
exact β_is_alg_mor_inst'.
clear β_is_alg_mor_inst'.
apply CoproductIn2Commutes_right_in_ctx_dir.
simpl.
rewrite <- assoc.
apply idpath.
Qed.
(** A morphism [β] of pointed functors is a bracket morphism when... *)
Lemma is_ptd_mor_alg_mor (T T' : algebra_ob ([C, C] hs) Id_H)
(β : algebra_mor ([C, C] hs) Id_H T T') :
@is_ptd_mor C (ptd_from_alg T) (ptd_from_alg T') (pr1 β).
Proof.
simpl.
unfold is_ptd_mor. simpl.
intro c.
rewrite <- assoc.
assert (X:=pr2 β).
assert (X':= nat_trans_eq_pointwise _ _ _ _ _ _ X c).
simpl in *.
eapply pathscomp0. apply maponpaths. apply X'.
unfold coproduct_nat_trans_in1_data.
repeat rewrite assoc.
unfold coproduct_nat_trans_data.
eapply pathscomp0.
apply cancel_postcomposition.
apply CoproductIn1Commutes.
simpl.
repeat rewrite <- assoc.
apply id_left.
Qed.
Definition ptd_from_alg_mor {T T' : algebra_ob _ Id_H} (β : algebra_mor _ _ T T')
: ptd_from_alg T ⇒ ptd_from_alg T'.
Proof.
exists (pr1 β).
apply is_ptd_mor_alg_mor.
Defined.
(* show functor laws for [ptd_from_alg] and [ptd_from_alg_mor] *)
Definition ptd_from_alg_functor_data : functor_data (precategory_FunctorAlg _ Id_H hsEndC) Ptd.
Proof.
exists ptd_from_alg.
intros T T' β.
apply ptd_from_alg_mor.
exact β.
Defined.
Lemma is_functor_ptd_from_alg_functor_data : is_functor ptd_from_alg_functor_data.
Proof.
split; simpl; intros.
+ unfold functor_idax.
intro T.
(* match goal with | [ |- ?l = _ ] => let ty:= (type of l) in idtac ty end. *)
apply (invmap (eq_ptd_mor_precat _ hs _ _)).
apply (invmap (eq_ptd_mor _ hs _ _)).
(* match goal with | [ |- ?l = _ ] => let ty:= (type of l) in idtac ty end. *)
apply idpath.
+ unfold functor_compax.
intros T T' T'' β β'.
apply (invmap (eq_ptd_mor_precat _ hs _ _)).
apply (invmap (eq_ptd_mor _ hs _ _)).
apply idpath.
Qed.
Definition ptd_from_alg_functor: functor (precategory_FunctorAlg _ Id_H hsEndC) Ptd :=
tpair _ _ is_functor_ptd_from_alg_functor_data.
Definition isbracketMor {T T' : hss} (β : algebra_mor _ _ T T') : UU :=
∀ (Z : Ptd) (f : Z ⇒ ptd_from_alg T),
fbracket _ f ;; β
=
(β)øø (U Z) ;; fbracket _ (f ;; # ptd_from_alg_functor β ).
Lemma isaprop_isbracketMor (T T':hss) (β : algebra_mor _ _ T T') : isaprop (isbracketMor β).
Proof.
do 2 (apply impred; intro).
apply isaset_nat_trans.
apply hs.
Qed.
(** A morphism of hss is a pointed morphism that is compatible with both
[τ] and [fbracket] *)
Definition ishssMor {T T' : hss} (β : algebra_mor _ _ T T') : UU
:= isbracketMor β.
Definition hssMor (T T' : hss) : UU
:= Σ β : algebra_mor _ _ T T', ishssMor β.
Coercion ptd_mor_from_hssMor (T T' : hss) (β : hssMor T T') : algebra_mor _ _ T T' := pr1 β.
(*
Definition isAlgMor_hssMor {T T' : hss} (β : hssMor T T')
: isAlgMor β := pr1 (pr2 β).
*)
Definition isbracketMor_hssMor {T T' : hss} (β : hssMor T T')
: isbracketMor β := pr2 β.
(** **** Equality of morphisms of hss *)
Section hssMor_equality.
(** Show that equality of hssMor is equality of underlying nat. transformations *)
Variables T T' : hss.
Variables β β' : hssMor T T'.
Definition hssMor_eq1 : β = β' ≃ (pr1 β = pr1 β').
Proof.
apply total2_paths_isaprop_equiv.
intro γ.
apply isaprop_isbracketMor.
Defined.
Definition hssMor_eq : β = β' ≃ (β : EndC ⟦ _ , _ ⟧) = β'.
Proof.
eapply weqcomp.
- apply hssMor_eq1.
- apply total2_paths_isaprop_equiv.
intro.
apply isaset_nat_trans.
apply hs.
Defined.
End hssMor_equality.
Lemma isaset_hssMor (T T' : hss) : isaset (hssMor T T').
Proof.
intros β β'.
apply (isofhlevelweqb _ (hssMor_eq _ _ β β')).
apply isaset_nat_trans.
apply hs.
Qed.
(** ** The precategory of hss *)
(** *** Identity morphism of hss *)
Lemma ishssMor_id (T : hss) : ishssMor (identity (C:=precategory_FunctorAlg _ _ hsEndC ) (pr1 T)).
Proof.
unfold ishssMor.
unfold isbracketMor.
intros Z f.
rewrite id_right.
rewrite functor_id.
rewrite id_right.
apply pathsinv0.
set (H2:=pre_composition_functor _ _ C _ hs (U Z)).
set (H2' := functor_id H2). simpl in H2'.
simpl.
rewrite H2'.
rewrite (id_left EndC).
apply idpath.
Qed.
Definition hssMor_id (T : hss) : hssMor _ _ := tpair _ _ (ishssMor_id T).
(** *** Composition of morphisms of hss *)
Lemma ishssMor_comp {T T' T'' : hss} (β : hssMor T T') (γ : hssMor T' T'')
: ishssMor (compose (C:=precategory_FunctorAlg _ _ hsEndC) (pr1 β) (pr1 γ)).
Proof.
unfold ishssMor.
unfold isbracketMor.
intros Z f.
eapply pathscomp0.
apply assoc.
(* match goal with | [|- ?l = _ ] => assert (Hyp : l = fbracket T f;; pr1 β;; pr1 γ) end. *)
eapply pathscomp0.
apply cancel_postcomposition.
apply isbracketMor_hssMor.
rewrite <- assoc.
eapply pathscomp0.
apply maponpaths.
apply isbracketMor_hssMor.
rewrite assoc.
rewrite functor_comp.
rewrite assoc.
apply cancel_postcomposition.
set (H2:=functor_comp (pre_composition_functor _ _ C _ hs (U Z)) ).
apply pathsinv0.
apply H2.
Qed.
Definition hssMor_comp {T T' T'' : hss} (β : hssMor T T') (γ : hssMor T' T'')
: hssMor T T'' := tpair _ _ (ishssMor_comp β γ).
Definition hss_obmor : precategory_ob_mor.
Proof.
exists hss.
exact hssMor.
Defined.
Definition hss_precategory_data : precategory_data.
Proof.
exists hss_obmor.
split.
- exact hssMor_id.
- exact @hssMor_comp.
Defined.
Lemma is_precategory_hss : is_precategory hss_precategory_data.
Proof.
repeat split; intros.
- apply (invmap (hssMor_eq _ _ _ _ )).
apply (id_left EndC).
- apply (invmap (hssMor_eq _ _ _ _ )).
apply (id_right EndC).
- apply (invmap (hssMor_eq _ _ _ _ )).
apply (assoc EndC).
Qed.
Definition hss_precategory : precategory := tpair _ _ is_precategory_hss.
End def_hss.
Arguments hss {_ _} _ _ .
Arguments hssMor {_ _ _ _ } _ _ .
Arguments fbracket {_ _ _ _ } _ {_} _ .
Arguments fbracket_η {_ _ _ _ } _ {_} _ .
Arguments fbracket_τ {_ _ _ _} _ {_} _ .
Arguments fbracket_unique_target_pointwise {_ _ _ _ } _ {_ _ _} _ _ .
Arguments fbracket_unique {_ _ _ _ } _ {_} _ _ _ .
(* Arguments Alg {_ _} _. *)
Arguments hss_precategory {_ _} _ _ .
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.