Datasets:
AI4M
/

text
stringlengths
0
3.34M
[STATEMENT] lemma n_intersect_num_subset_def: "b1 |\<inter>|\<^sub>n b2 = card {x . x \<subseteq> b1 \<inter> b2 \<and> card x = n}" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (b1 |\<inter>|\<^sub>n b2) = card {x. x \<subseteq> b1 \<inter> b2 \<and> card x = n} [PROOF STEP] using n_intersect_number_def [PROOF STATE] proof (prove) using this: ?b1.0 |\<inter>|\<^sub>?n ?b2.0 \<equiv> card {x \<in> Pow (?b1.0 \<inter> ?b2.0). card x = ?n} goal (1 subgoal): 1. (b1 |\<inter>|\<^sub>n b2) = card {x. x \<subseteq> b1 \<inter> b2 \<and> card x = n} [PROOF STEP] by auto
import os import numpy as np import matplotlib.pyplot as plt from tqdm import tqdm from ..analysis import style, labels def generate_cutflow(basedir, period, samples, num_plots=6, lumi=35.9, year=2016, outpath=os.getcwd()): """ Combine cutflow file for each event process for each job directory and produce general cutflow Args: basedir (str): Path to analysis root folder period (str): Jobs period used in anafile samples (dict): Dictionary mapping each event flavour to jobs directories """ cutflow_filepath = os.path.join(outpath, "cutflow_XX.txt") cutflow_file = open(cutflow_filepath, "w") fig1 = plt.figure(figsize=(25,8)) plot_control = 0 plot_n = 1 NumPlots = num_plots has_tag = False # Remove if CMS join 2016 samples again for datasets in tqdm(samples.keys()): cutflow_file.write("------------------------------------------------------------------------------------"+"\n") cutflow_file.write("Cutflow from " + datasets + ":"+"\n") cutflow_file.write("------------------------------------------------------------------------------------"+"\n") ax = plt.subplot(1,NumPlots,plot_n) plotted = False control = 0 DATA_LUMI = 0 PROC_XSEC = 0 SUM_GEN_WGT = 0 for dataset in samples[datasets]: dataset_year = dataset.split("_files_")[0] dataset_year = dataset_year.split("_")[-1] dataset_tag = dataset.split("_"+dataset_year)[0][-3:] if (dataset_year == period): if( dataset_tag == "APV" ): has_tag = True cutflow = os.path.join(basedir, dataset, "cutflow.txt") cut_name = [] cut_val_i = [] cut_unc_i = [] if os.path.isfile(cutflow): with open(cutflow) as f: for line in f: if line[:10] == "Luminosity" : DATA_LUMI = float(line.split()[1]) if line[:13] == "Cross section" : PROC_XSEC = float(line.split()[2]) if line[:17] == "Sum of genWeights" : SUM_GEN_WGT += float(line.split()[3]) if line[0] == "|" : line_info = line.split() cut_name.append(line_info[0][1:]) cut_val_i.append(float(line_info[1])) cut_unc_i.append(float(line_info[2])**2) if control == 0: cut_val = np.array(cut_val_i) cut_unc = np.array(cut_unc_i) control = 1 else: cut_val = cut_val + np.array(cut_val_i) cut_unc = cut_unc + np.array(cut_unc_i) if control == 1: cut_unc = np.sqrt(cut_unc) if PROC_XSEC == 0: dataScaleWeight = 1 SUM_GEN_WGT = -1 else: dataScaleWeight = (PROC_XSEC/SUM_GEN_WGT) * DATA_LUMI SUM_GEN_WGT = SUM_GEN_WGT*dataScaleWeight cut_val = cut_val*dataScaleWeight cut_unc = cut_unc*dataScaleWeight cutflow_file.write("Data scale weight = " + str(dataScaleWeight)+"\n") cutflow_file.write("------------------------------------------------------------------------------------"+"\n") cutflow_file.write('Cutflow Selected Events Stat. Error Efficiency (%)'+"\n") for i in range(len(cut_name)): cutflow_file.write(cut_name[i].ljust(17) + "%18.6f %16.6f %19.4f" % (cut_val[i], cut_unc[i], (cut_val[i]*100)/SUM_GEN_WGT)+"\n") cutflow_file.write(""+"\n") cutflow_file.write(""+"\n") if datasets == 'Signal_400_100' or datasets == 'Signal_1000_800': for i in range(NumPlots): ax = plt.subplot(1,NumPlots,i+1) plt.plot(cut_val, label=datasets, dashes=[6, 2]) ax = plt.subplot(1,NumPlots,plot_n) elif datasets[:4] != "Data" and datasets[:6] != "Signal": plt.plot(cut_val, label=datasets) plotted = True if plot_control == 7: labels(ax, ylabel="Events", xlabel="Selection") style(ax, lumi=lumi, year=year, ylog=True, xgrid=True, ygrid=True, ylim=[1.e-1,5.e7], legend_ncol=5) plt.xticks(range(len(cut_name)), cut_name, rotation = 25, ha="right") plot_control = 0 plot_n += 1 elif plotted: plot_control += 1 labels(ax, ylabel="Events", xlabel="Selection") style(ax, lumi=lumi, year=year, ylog=True, xgrid=True, ygrid=True, ylim=[1.e-1,5.e7], legend_ncol=5) plt.xticks(range(len(cut_name)), cut_name, rotation = 25, ha="right") plt.subplots_adjust(left=0.055, bottom=0.17, right=0.98, top=0.95, wspace=0.25, hspace=0.0) cutflow_file.close() if( has_tag ): real_cutflow_filepath = os.path.join(outpath, "cutflow_APV_" + period + ".txt") cutflow_plot_path = os.path.join(outpath, "cutflow_APV_" + period + ".png") else: real_cutflow_filepath = os.path.join(outpath, "cutflow_" + period + ".txt") cutflow_plot_path = os.path.join(outpath, "cutflow_" + period + ".png") plt.savefig(cutflow_plot_path) os.system("mv " + cutflow_filepath + " " + real_cutflow_filepath)
############################################################# # R script for building multiple models and their evaluation ############################################################# library(caret) library(pROC) # parallel execution - Windows #library(doParallel); #cl <- makeCluster(4); #4 cores #registerDoParallel(cl) # parallel execution - Linux #library(doMC) #registerDoMC(cores = 4) ##################################### # load the dataset ##################################### #i.i.d assumption #hdd_iid_df <- read.csv("D:\\NUS\\IVLE\\DATA MINING METHODOLOGY AND METHODS\\CA\\DM\\data\\hdd_iid.csv", header=TRUE) # reusing same name only; the below file is in time series format! #EMA hdd_iid_df <- read.csv("D:\\NUS\\IVLE\\DATA MINING METHODOLOGY AND METHODS\\CA\\DM\\data\\ewa_30.csv", header=TRUE) # tsfresh #hdd_iid_df <- read.csv("D:\\NUS\\IVLE\\DATA MINING METHODOLOGY AND METHODS\\CA\\DM\\data\\features_filtered_direct_7days.csv", header=TRUE) # data type fomatting for target hdd_iid_df$failure <- as.factor(hdd_iid_df$failure) ##################################### # split into train and test datasets ##################################### #split = 0.80 split = 0.70 #split = 0.50 trainIndex <- createDataPartition(hdd_iid_df$failure, p=split, list=FALSE) hdd_train <- hdd_iid_df[ trainIndex,] hdd_test <- hdd_iid_df[-trainIndex,] # create copies for preprocessing step using PCA # EMA hdd_train_without_target <- hdd_train[,3:18] hdd_train_with_target <- hdd_train[,c(1,3:18)] # column 1 is the target 'failure' # 3 days #hdd_train_without_target <- hdd_train[,3:855] #hdd_train_with_target <- hdd_train[,c(1,3:855)] # column 1 is the target 'failure' # 7 days #hdd_train_without_target <- hdd_train[,3:1407] #hdd_train_with_target <- hdd_train[,c(1,3:1407)] # column 1 is the target 'failure' # 15 days #hdd_train_without_target <- hdd_train[,3:1966] #hdd_train_with_target <- hdd_train[,c(1,3:1966)] # column 1 is the target 'failure' # 30 days #hdd_train_without_target <- hdd_train[,3:2250] #hdd_train_with_target <- hdd_train[,c(1,3:2250)] # column 1 is the target 'failure' ################################## # cross validation train controls ################################## train_control_kcv <- trainControl(method="cv", number=5, savePredictions = T, preProcOptions=list(thresh = 0.90)) #train_control_loocv <- trainControl(method="LOOCV") ################################## # test data preparation ################################## #x_test <- hdd_test[,3:9] #iid #y_test <- hdd_test[,2] #iid # EMA x_test <- hdd_test[,3:18] # 3 days #x_test <- hdd_test[,3:855] #temporal # 7 days #x_test <- hdd_test[,3:1407] #temporal # 15 days #x_test <- hdd_test[,3:1966] #temporal # 30 days #x_test <- hdd_test[,3:2250] #temporal y_test <- hdd_test[,1] #temporal ################################## # preprocessing steps ################################## # PCA by limiting variance threshold = 90% yields 48 Principal Components preProc <- preProcess(hdd_train_without_target, method = c("center", "scale", "pca"), thresh=0.90) # Applying the processing steps to test and generating the Principal Components for test from the PC coefficients x_test <- predict(preProc, x_test) # this is the final training set with PCs and target. # After cross validation is verified, the model will be trained again using this dataset. hdd_train_final <- predict(preProc, hdd_train_without_target) hdd_train_final$failure <- hdd_train[,1] ################################## # train using decision tree model ################################## # cross validation # k=5 folds #model_rpart <- train(failure~ R10_smart_5_raw + R10_smart_184_raw + R10_smart_187_raw + R10_smart_188_raw + R10_smart_198_raw + R10_smart_183_raw + R10_smart_7_raw, data=hdd_train, trControl=train_control_kcv, method = "rpart") #model_rpart <- train(failure~ R10_smart_5_raw + R10_smart_184_raw + R10_smart_187_raw + R10_smart_188_raw + R10_smart_198_raw + R10_smart_183_raw + R10_smart_7_raw, data=hdd_train, trControl=train_control_loocv, method = "rpart") model_rpart <- train(failure~., data=hdd_train_with_target, trControl=train_control_kcv, method = "rpart", preProcess=c("center", "scale", "pca")) print(model_rpart) roc_rpart<- roc(predictor = as.numeric(model_rpart$pred$pred), response = model_rpart$pred$obs, plot=TRUE, auc=TRUE) # train using the final trainset and make predictions on test data model_rpart <- train(failure~., data=hdd_train_final, method = "rpart") predictions_rpart <- predict(model_rpart, x_test) # summarize results confusionMatrix(data=predictions_rpart, reference=y_test, positive="1") ################################## # train using svm ################################## # cross validation # k=5 folds #model_svmLinear <- train(failure~ R10_smart_5_raw + R10_smart_184_raw + R10_smart_187_raw + R10_smart_188_raw + R10_smart_198_raw + R10_smart_183_raw + R10_smart_7_raw, data=hdd_train, trControl=train_control_kcv, method = "svmLinear") #model_svmLinear <- train(failure~ R10_smart_5_raw + R10_smart_184_raw + R10_smart_187_raw + R10_smart_188_raw + R10_smart_198_raw + R10_smart_183_raw + R10_smart_7_raw, data=hdd_train, trControl=train_control_loocv, method = "svmLinear") model_svmLinear <- train(failure~., data=hdd_train_with_target, trControl=train_control_kcv, method = "svmLinear") print(model_svmLinear) roc_svmLinear<- roc(predictor = as.numeric(model_svmLinear$pred$pred), response = model_svmLinear$pred$obs, plot=TRUE, auc=TRUE) # train using the final trainset and make predictions on test data model_svmLinear <- train(failure~., data=hdd_train_final, method = "svmLinear") predictions_svmLinear <- predict(model_svmLinear, x_test) # summarize results confusionMatrix(data=predictions_svmLinear, reference=y_test, positive="1") ################################## # train using Naive Bayes ################################## # cross validation # k=5 folds #model_nb <- train(failure~ R10_smart_5_raw + R10_smart_184_raw + R10_smart_187_raw + R10_smart_188_raw + R10_smart_198_raw + R10_smart_183_raw + R10_smart_7_raw, data=hdd_train, trControl=train_control_kcv, method = "nb") #model_nb <- train(failure~ R10_smart_5_raw + R10_smart_184_raw + R10_smart_187_raw + R10_smart_188_raw + R10_smart_198_raw + R10_smart_183_raw + R10_smart_7_raw, data=hdd_train, trControl=train_control_loocv, method = "nb") model_nb <- train(failure~., data=hdd_train_with_target, trControl=train_control_kcv, method = "nb") print(model_nb) roc_nb<- roc(predictor = as.numeric(model_nb$pred$pred), response = model_nb$pred$obs, plot=TRUE, auc=TRUE) # train using the final trainset and make predictions on test data model_nb <- train(failure~., data=hdd_train_final, method = "nb") predictions_nb <- predict(model_nb, x_test) # summarize results confusionMatrix(data=predictions_nb, reference=y_test, positive="1") ################################## # train using Random Forest ################################## # cross validation # k=5 folds # number of trees = 51 ntree = 51 #model_rf <- train(failure~ R10_smart_5_raw + R10_smart_184_raw + R10_smart_187_raw + R10_smart_188_raw + R10_smart_198_raw + R10_smart_183_raw + R10_smart_7_raw, data=hdd_train, method="rf", trControl=train_control_kcv, ntree=ntree) #model_rf <- train(failure~ R10_smart_5_raw + R10_smart_184_raw + R10_smart_187_raw + R10_smart_188_raw + R10_smart_198_raw + R10_smart_183_raw + R10_smart_7_raw, data=hdd_train, method="rf", trControl=train_control_loocv, ntree=ntree) model_rf <- train(failure~., data=hdd_train_with_target, method="rf", trControl=train_control_kcv, ntree=ntree) print(model_rf) roc_rf<- roc(predictor = as.numeric(model_rf$pred$pred), response = model_rf$pred$obs, plot=TRUE, auc=TRUE) # train using the final trainset and make predictions on test data model_rf <- train(failure~., data=hdd_train_final, method = "rf") predictions_rf <- predict(model_rf, x_test) # summarize results confusionMatrix(data=predictions_rf, reference=y_test, positive="1") ################################## # train using Logistic Regression ################################## # cross validation # k=5 folds #model_logit <- train(failure~ R10_smart_5_raw + R10_smart_184_raw + R10_smart_187_raw + R10_smart_188_raw + R10_smart_198_raw + R10_smart_183_raw + R10_smart_7_raw, data=hdd_train, method="glm", family="binomial", trControl=train_control_kcv) #model_logit <- train(failure~ R10_smart_5_raw + R10_smart_184_raw + R10_smart_187_raw + R10_smart_188_raw + R10_smart_198_raw + R10_smart_183_raw + R10_smart_7_raw, data=hdd_train, method="glm", family="binomial", trControl=train_control_loocv) model_logit <- train(failure~., data=hdd_train_with_target, method="glm", family="binomial", trControl=train_control_kcv) print(model_logit) roc_logit<- roc(predictor = as.numeric(model_logit$pred$pred), response = model_logit$pred$obs, plot=TRUE, auc=TRUE) # train using the final trainset and make predictions on test data model_logit <- train(failure~., data=hdd_train_final, method="glm", family="binomial") predictions_logit <- predict(model_logit, x_test) # summarize results confusionMatrix(data=predictions_logit, reference=y_test, positive="1") ################################## # train using XGBoost Linear ################################## # cross validation # k=5 folds model_xgb <- train(failure~., data=hdd_train_with_target, method="xgbLinear", trControl=train_control_kcv) print(model_xgb) roc_xgb<- roc(predictor = as.numeric(model_xgb$pred$pred), response = model_xgb$pred$obs, plot=TRUE, auc=TRUE) # train using the final trainset and make predictions on test data model_xgb <- train(failure~., data=hdd_train_final, method="xgbLinear") predictions_xgb <- predict(model_xgb, x_test) # summarize results confusionMatrix(data=predictions_xgb, reference=y_test, positive="1") ########################################################## # Plot ROC with Area Under the Curve for all models ########################################################## plot(roc_rf, col="blue") plot(roc_logit, add=TRUE, col="red") plot(roc_rpart, add=TRUE, col="green") plot(roc_svmLinear, add=TRUE, col="black") plot(roc_nb, add=TRUE, col="orange") plot(roc_xgb, add=TRUE, col="yellow") op <- par(cex = 0.7) legend("bottomright", legend = c("RF", "Logit", "DecisionTree", "SVM-Linear","NaiveBayes", "XGBoost"), col = c("blue", "red", "green", "black","orange", "yellow"), lty = 1) legend("topright", legend = c(paste("RF: ", round(roc_rf$auc, digits = 4), sep=" "),paste("Logit: ", round(roc_logit$auc, digits = 4)),paste("DecisionTree: ", round(roc_rpart$auc, digits = 4)),paste("SVM-Linear: ", round(roc_svmLinear$auc, digits = 4)),paste("NB: ", round(roc_nb$auc, digits = 4)), paste("XGBoost: ", round(roc_xgb$auc, digits = 4)), sep="")) # stop and deregister the parallel execution allocation - Windows #stopCluster(cl) #registerDoSEQ()
\section{Recap} \frame{\tableofcontents[currentsection]} \begin{frame} \frametitle{Basic Load Balancing with Nginx} \begin{center} \includegraphics[scale=0.5]{01-nginx-basic.png} \end{center} \blfootnote{image from \url{https://www.thegeekstuff.com/2017/01/nginx-loadbalancer/}} \end{frame} \begin{frame} \frametitle{Last Exercise Previous Lesson} \begin{center} \includegraphics[scale=0.19]{02-node-connect.png} \end{center} \blfootnote{image from \url{http://engineering.pivotal.io/post/how-to-set-up-an-elixir-cluster-on-amazon-ec2/}} \end{frame}
Wow! This was big news! Shocking! Gilgamesh turns out to be more than fiction or myth, contrary to what academia has been pushing for a century. Gilgamesh was a real person and they found his tomb, just as it was said in the epic, built under the course of the Euphrates River! It only got a little mention in the BBC (in One Minute World News) where Uruk – the origin of eponymous Iraq! NOTE how the BBC says “believed found!” If it was “Lucy’s” bones found over a couple square kilometers, they’d say, “definite proof of humanoid primate!” See, it all depends on what they want you to believe. In this case the find of Gilgamesh tomb ought to be called the find of the decade or of the 21st century, as yet another ancient literary source (2300 BC) turns out to be historical and less “mythological” than widely assumed. Uruk was the first city? Responsible for most first inventions, like writing, law, education, taxes, love songs, ethics, justice, agriculture, medicine, love and family? Wow, that early? But inspite of all these proven first inventions, mainstream historians don’t trust Sumer’s own historical writings and denounce them as fictitious mythology without any core of truth. After all they were the immdiate descendents of stupid cavemen and hunter gatherers! And Euhemerism is ‘a bad bad method of doing history!’ For sure!! Turkish archaeologists claim a historical discovery as they believe they have found pieces of the Trojan Horse. According to a report by newsit.gr, Turkish archaeologists excavating on the site of the historical city of Troy on the hills of Hisarlik, have unearthed a large wooden structure. Historians and archaeologists presume that the pieces are remains of the legendary Trojan Horse. Excavations brought to light dozens of fir planks and beams up to 15 meters long, assembled in a strange form. The wooden assembly was inside the walls of the ancient city of Troy. Fir planks were used for building seafaring ships, archaeologists say. The Trojan Horse is considered to be a mythical structure. Described as a horse in Homer’s Odyssey, historians suggest that the writer was making an analogy for a war machine, or a natural disaster. The structure found fits the description by Homer, Virgil, Augustus and Quintus Smyrnaeus. So, archaeologists tend to believe that the finding is indeed the remains of the subterfuge Greeks used to conquer ancient Troy. Another discovery that supports the archaeologists’ claims is a damaged bronze plate with the inscription “For their return home, the Greeks dedicate this offering to Athena.” Quintus Smyrnaeus refers to the particular plate in his epic poem “Posthomerica” and the plate was also found on the site. The two archaeologists leading the excavation, Boston University professors Christine Morris and Chris Wilson, say that they have a “high level of confidence” that the structure is indeed linked to the legendary horse. They say that all the tests performed up to now have only confirmed their theory.
We purchased too many high end gas grills and need to sell them off now. Our buyers say move'em out at prices below manufacturer minimums so that's what were are doing. Check out our great selection of discount priced DCS, Firemagic, Lynx, Napoleon, OCI, Solaire, Viking grills and appliances. Celebrating 10 years online. Questions? Call us for answers. Free nationwide shipping on DCS gas grills and no sales tax. Authorized online DCS dealer. Witbecks, since 1917. Talk to an expert today. Complete catalog of DCS grills, BBQ accessories, outdoor heaters and refrigeration. Great customer service. Authorized dealer. Full line. Authorized DCS dealer. Also find Bosch, Dacor, GE Monogram, Fisher and Paykel, KitchenAid, Viking and more. Free shipping and no sales tax. Family owned business since 1949. Find, compare and buy products in categories ranging from Grills and Smokers to Kitchen Ranges. Read product reviews and compare prices from thousands of online stores. Browse our DCS store for great savings on all stainless steel DCS grills. Find Deals on Dcs Gas Grill and other Large Appliances at DealTime. Choose from millions of deals. Save time and money every time you shop. Bargain Prices for DCS Gas Grill. Home and Garden Reviews. Cheap Prices for DCS Gas Grill. Home Furnishings Reviews.
[STATEMENT] lemma p2_start: "TAG_sctn False" [PROOF STATE] proof (prove) goal (1 subgoal): 1. TAG_sctn False [PROOF STEP] by simp
/* bclsqr.c $Revision: 273 $ $Date: 2006-09-04 15:59:04 -0700 (Mon, 04 Sep 2006) $ ---------------------------------------------------------------------- This file is part of BCLS (Bound-Constrained Least Squares). Copyright (C) 2006 Michael P. Friedlander, Department of Computer Science, University of British Columbia, Canada. All rights reserved. E-mail: <[email protected]>. BCLS is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. BCLS 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with BCLS; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ---------------------------------------------------------------------- */ /*! \file Interface to LSQR routine. Used to compute a Newton step. */ #include <cblas.h> #include <string.h> #include <stdio.h> #include "bcls.h" #include "bclib.h" #include "bclsqr.h" #include "lsqr.h" /*! \brief Mat-vec routine called by LSQR. LSQR calls this routine, which in turn calls bcls_aprod: This routine is declared "static" so that it won't be confused with the user's own Aprod routine. - If mode = 1, - y(1:m) <- y(1:m) + A(:,ix) * dxFree. - y(m+1:) <- y(m+1:) + damp * dxFree - If mode = 2, - dxFree <- dxFree + A'* y(1:m) + damp y(m+1:). Note that mSubProb is the number of rows in the subproblem. This may or may not be equal to m, which is the number of rows in the original problem. If the subproblem is damped (because the user has either provided a linear term or an explicit damping parameter), then mSubProb = m + nFree. Otherwise, mSubProb = m. \param[in] mode Determines which producte with A is required. \param[in] mSubProb Number of rows in the matrix seen by LSQR. Also: - length of y. \param[in] nFree Number of columns in A(:,ix). Also: - length of ix - length of dxFree. \param[in,out] dxFree Primal variables \param[in,out] y Dual variables. \param[in,out] UsrWrk Transit pointer to the BCLS problem context. */ static void aprod_free_lsqr( const int mode, const int mSubProb, const int nFree, double dxFree[], double y[], void *UsrWrk) { int j; BCLS *ls = (BCLS *)UsrWrk; // Reclaim access to the BCLS workspace. const int m = ls->m; const int preconditioned = ls->Usolve != NULL; const int damped = ls->damp_actual > 0.0; const double damp = ls->damp_actual; int *ix = ls->ix; double *dx = ls->dx; // Used as workspace. double *dy = ls->wrk_u; // ... if (mode == 1) { // Solve U dy = dxFree. U is nFree-by-nFree, and so the // relevant part of dy has length nFree. if (preconditioned) bcls_usolve( ls, BCLS_PRECON_U, nFree, ix, dy, dxFree ); else cblas_dcopy( nFree, dxFree, 1, dy, 1 ); // y2 <- y2 + damp * dy(1:nFree). if (damped) cblas_daxpy( nFree, damp, dy, 1, &y[m], 1 ); // Scatter dy into dx: dx(ix) <- dy(1:nFree). for (j = 0; j < nFree; j++) dx[ ix[j] ] = dy[j]; // dy <- A(:,ix) * dx(ix). bcls_aprod( ls, BCLS_PROD_A, nFree, ix, dx, dy ); // y1 <- y1 + dy. cblas_daxpy( m, 1.0, dy, 1, y, 1 ); } else { // mode == 2 // dx <- A' * y1. bcls_aprod( ls, BCLS_PROD_At, nFree, ix, dx, y ); // Gather dx(ix) into dy: dy(1:nFree) <- dx(ix). for (j = 0; j < nFree; j++) dy[j] = dx[ ix[j] ]; // dy <- dy + damp * y2. if (damped) cblas_daxpy( nFree, damp, &y[m], 1, dy, 1 ); // Solve U' dx = dy. if (preconditioned) bcls_usolve( ls, BCLS_PRECON_Ut, nFree, ix, dy, dx ); else cblas_dcopy( nFree, dy, 1, dx, 1 ); // dxFree <- dxFree + dx. cblas_daxpy( nFree, 1.0, dx, 1, dxFree, 1 ); } return; } /*! \brief Compute a Newton step using LSQR. \see bcls_newton_step_cgls. \param[in,out] ls BCLS problem context. \param[in] m Number of rows in A. \param[in] nFree Number of columns in A(:,ix). Also: - length of ix and dxFree \param[in] ix Index of free variables. \param[in] damp Regularization parameter. \param[in] itnLim Iteration limit on current LSQR call. \param[in] tol LSQR's atol and btol. \param[in,out] dxFree Search direction on free variables. \param[in,out] x Current point. \param[in] c Linear term. \param[in,out] r Residual. Used as RHS for LSQR. \param[out] itns Number of LSQR iterations on current subproblem. \param[out] opt Optimality achieved by LSQR on current subproblem. \return - 0: Required accurace was achieved. - 1: The iteration limit (itnLim) was reached. - 2: A(:,ix) is excessively ill-conditioned. */ int bcls_newton_step_lsqr( BCLS *ls, int m, int nFree, int ix[], double damp, int itnLim, double tol, double dxFree[], double x[], double c[], double r[], int *itns, double *opt ) { int j, k; // Misc. counters. int mpn; // No. of rows in [ N; damp I ]. int unscale_dxFree = 0; const int rescaling_method = 1; const int linear = c != NULL; const int damped = damp > 0.0; const double damp_min = ls->damp_min; const double damp2 = damp * damp; const double zero = 0.0; double damp_actual; double beta1, beta2; // LSQR outputs int istop; // Termination flag. double anorm; // Estimate of Frobenious norm of Abar. double acond; // Estimate of condition no. of Abar. double rnorm; // Estimate of the final value of norm(rbar). double xnorm; // Estimate of the norm of the final solution dx. // Set r(m+1:) <- - 1/beta c + damp^2/beta x, where // beta = max(min_damp, damp). // Note that r is declared length (m+n), so there is always enough // space. The chosen damping parameter is stored in // ls->damp_actual so that it can be used in bcls_aprod_free. if (!damped && !linear) { mpn = m; ls->damp_actual = 0.0; } else { mpn = m + nFree; //-------------------------------------------------------------- // Rescale the RHS. Will need to unscale LSQR's solution later. //-------------------------------------------------------------- if (rescaling_method) { if (linear) { unscale_dxFree = 1; damp_actual = fmax( damp, damp_min ); ls->damp_actual = damp_actual; // r(1:m) = damp_actual * r(1:m) cblas_dscal( m, damp_actual, r, 1 ); // r(m+1:) = - c for (j = 0; j < nFree; j++ ) r[m+j] = - c[ ix[j] ]; // r(m+1:) = - c - damp^2 * x if (damped) for (j = 0; j < nFree; j++) r[m+j] -= damp2 * x[ ix[j] ]; } else { ls->damp_actual = damp; for (j = 0; j < nFree; j++) r[m+j] = - damp * x[ ix[j] ]; } } //-------------------------------------------------------------- // No rescaling. //-------------------------------------------------------------- else { if (damped && linear) { damp_actual = fmax( damp, damp_min ); beta1 = -1.0 / damp_actual; beta2 = -damp * damp / damp_actual; ls->damp_actual = damp_actual; for (j = 0; j < nFree; j++) { k = ix[j]; r[m+j] = beta1 * c[k] + beta2 * x[k]; } } else if ( damped && !linear ) { beta2 = - damp; ls->damp_actual = damp; for (j = 0; j < nFree; j++) r[m+j] = beta2 * x[ ix[j] ]; } else if (!damped && linear ) { beta1 = - 1.0 / damp_min; ls->damp_actual = damp_min; for (j = 0; j < nFree; j++) r[m+j] = beta1 * c[ ix[j] ]; } } } // ----------------------------------------------------------------- // Solve the subproblem with LSQR. // ----------------------------------------------------------------- bcls_timer( &(ls->stopwatch[BCLS_TIMER_LSQR]), BCLS_TIMER_START ); lsqr( mpn, nFree, aprod_free_lsqr, zero, (void *)ls, r, ls->wrk_v, ls->wrk_w, dxFree, NULL, tol, tol, ls->conlim, itnLim, ls->minor_file, &istop, itns, &anorm, &acond, &rnorm, opt, &xnorm ); bcls_timer( &(ls->stopwatch[BCLS_TIMER_LSQR]), BCLS_TIMER_STOP ); // ----------------------------------------------------------------- // Cleanup and exit. First unscale dxFree if needed. // ----------------------------------------------------------------- if (rescaling_method && unscale_dxFree) cblas_dscal( nFree, 1.0/damp_actual, dxFree, 1 ); if (istop <= 3) return 0; else if (istop == 5) return 1; else return 2; }
theory SLTC_More imports SLTC begin subsection \<open>models rules\<close> declare mod_ex_dist [simp] lemma mod_star_trueI: "h\<Turnstile>P \<Longrightarrow> h\<Turnstile>P*true" by (metis assn_times_comm entailsD' entails_true mult.left_neutral) lemma mod_false[simp]: "\<not> h\<Turnstile>false" by (simp add: pure_assn_rule) lemmas mod_pure_star_dist[simp] = mod_pure_star_dist lemma mod_pure_star_dist'[simp]: "h\<Turnstile>\<up>b*P \<longleftrightarrow> h\<Turnstile>P \<and> b" using mod_pure_star_dist by (simp add: mult.commute) lemma mod_starD: "h\<Turnstile>A*B \<Longrightarrow> \<exists>h1 h2. h1\<Turnstile>A \<and> h2\<Turnstile>B" by (metis assn_ext mod_star_convE) subsection \<open>entailment rules\<close> lemmas ent_true[simp] = entails_true declare entails_triv [simp] lemma inst_ex_assn: "A \<Longrightarrow>\<^sub>A B x \<Longrightarrow> A \<Longrightarrow>\<^sub>A (\<exists>\<^sub>Ax. B x)" using entails_ex_post by blast lemma ent_iffI: assumes "A\<Longrightarrow>\<^sub>AB" assumes "B\<Longrightarrow>\<^sub>AA" shows "A=B" apply(rule assn_ext) using assms using entails_def by blast lemma ent_star_mono: "\<lbrakk> P \<Longrightarrow>\<^sub>A P'; Q \<Longrightarrow>\<^sub>A Q'\<rbrakk> \<Longrightarrow> P*Q \<Longrightarrow>\<^sub>A P'*Q'" using entails_trans2 entails_frame by blast lemma merge_true_star_ctx: "true * (true * P) = true * P" by (metis assn_times_assoc top_assn_reduce) lemma ent_true_drop: "P\<Longrightarrow>\<^sub>AQ*true \<Longrightarrow> P*R\<Longrightarrow>\<^sub>AQ*true" "P\<Longrightarrow>\<^sub>AQ \<Longrightarrow> P\<Longrightarrow>\<^sub>AQ*true" apply (metis assn_times_comm ent_star_mono ent_true merge_true_star_ctx) apply (metis assn_one_left ent_star_mono ent_true mult.commute) done lemma ent_true_drop_fst: "R\<Longrightarrow>\<^sub>AQ*true \<Longrightarrow> P*R\<Longrightarrow>\<^sub>AQ*true" apply (metis assn_times_comm ent_star_mono ent_true merge_true_star_ctx) done lemma ent_true_drop_fstf: "R\<Longrightarrow>\<^sub>Atrue*Q \<Longrightarrow> P*R\<Longrightarrow>\<^sub>Atrue*Q" apply (metis ent_star_mono ent_true merge_true_star_ctx) done lemma ent_ex_preI: "(\<And>x. P x \<Longrightarrow>\<^sub>A Q) \<Longrightarrow> \<exists>\<^sub>Ax. P x \<Longrightarrow>\<^sub>A Q" by (meson entails_ex) lemma ent_ex_postI: "Q \<Longrightarrow>\<^sub>A P x \<Longrightarrow> Q \<Longrightarrow>\<^sub>A \<exists>\<^sub>Ax. P x " using entails_ex_post by blast lemma entailsI: assumes "\<And>h. h\<Turnstile>P \<Longrightarrow> h\<Turnstile>Q" shows "P \<Longrightarrow>\<^sub>A Q" using assms unfolding entails_def by auto lemma ent_trans[trans]: "\<lbrakk> P \<Longrightarrow>\<^sub>A Q; Q \<Longrightarrow>\<^sub>AR \<rbrakk> \<Longrightarrow> P \<Longrightarrow>\<^sub>A R" by (auto intro: entailsI dest: entailsD) lemma ent_frame_fwd: assumes R: "P \<Longrightarrow>\<^sub>A R" assumes F: "Ps \<Longrightarrow>\<^sub>A P*F" assumes I: "R*F \<Longrightarrow>\<^sub>A Q" shows "Ps \<Longrightarrow>\<^sub>A Q" using assms by (metis entails_triv ent_star_mono ent_trans) lemma ent_pure_pre_iff[simp]: "(P*\<up>b \<Longrightarrow>\<^sub>A Q) \<longleftrightarrow> (b \<longrightarrow> (P \<Longrightarrow>\<^sub>A Q))" unfolding entails_def by (auto ) lemma ent_pure_pre_iff_sng[simp]: "(\<up>b \<Longrightarrow>\<^sub>A Q) \<longleftrightarrow> (b \<longrightarrow> (emp \<Longrightarrow>\<^sub>A Q))" using ent_pure_pre_iff[where P=emp] by simp lemma ent_pure_post_iff[simp]: "(P \<Longrightarrow>\<^sub>A Q*\<up>b) \<longleftrightarrow> ((\<forall>h. h\<Turnstile>P \<longrightarrow> b) \<and> (P \<Longrightarrow>\<^sub>A Q))" unfolding entails_def by (auto) lemma ent_pure_post_iff_sng[simp]: "(P \<Longrightarrow>\<^sub>A \<up>b) \<longleftrightarrow> ((\<forall>h. h\<Turnstile>P \<longrightarrow> b) \<and> (P \<Longrightarrow>\<^sub>A emp))" using ent_pure_post_iff[where Q=emp] by simp lemma ent_false: "false \<Longrightarrow>\<^sub>A P" by simp lemma ex_assn_cases: "(Q x \<Longrightarrow>\<^sub>A P) \<or> \<not> (\<exists>\<^sub>A y. Q y \<Longrightarrow>\<^sub>A P)" using entails_ex by blast lemma fr_refl': "A \<Longrightarrow>\<^sub>A B \<Longrightarrow> C * A \<Longrightarrow>\<^sub>A C * B" by (blast intro: ent_star_mono entails_triv) subsection \<open>assertion normalization rules\<close> lemmas [simp] = zero_time lemmas merge_true_star[simp] = top_assn_reduce lemma false_absorb[simp]: "false * R = false" by (simp add: assn_ext mod_false') lemma star_false_right[simp]: "P * false = false" using false_absorb by (simp add: assn_times_comm) lemma pure_true[simp]: "\<up>True = emp" by (auto intro: assn_ext simp: one_assn_rule pure_assn_rule) lemma pure_assn_eq_conv[simp]: "\<up>P = \<up>Q \<longleftrightarrow> P=Q" by (metis (full_types) assn_times_comm empty_iff in_range.simps mod_false' mod_pure_star_dist top_assn_rule) lemma ex_distrib_star': "Q * (\<exists>\<^sub>Ax. P x ) = (\<exists>\<^sub>Ax. Q * P x)" proof - have "Q * (\<exists>\<^sub>Ax. P x ) = (\<exists>\<^sub>Ax. P x ) * Q" by (simp add: assn_times_comm) also have "\<dots> = (\<exists>\<^sub>Ax. P x * Q )" unfolding ex_distrib_star by simp also have "\<dots> = (\<exists>\<^sub>Ax. Q * P x )" by (simp add: assn_times_comm) finally show ?thesis . qed lemma ex_false_iff_false[simp]: "(\<exists>\<^sub>A x. false) = false" by (simp add: ent_ex_preI ent_iffI) subsection "for relH" text "Transitivity" lemma relH_trans[trans]: "\<lbrakk>relH as h1 h2; relH as h2 h3\<rbrakk> \<Longrightarrow> relH as h1 h3" unfolding relH_def by auto lemma in_range_subset: "\<lbrakk>as \<subseteq> as'; in_range (h,as')\<rbrakk> \<Longrightarrow> in_range (h,as)" by auto lemma relH_subset: assumes "relH bs h h'" assumes "as \<subseteq> bs" shows "relH as h h'" using assms unfolding relH_def by (auto intro: in_range_subset) subsection "new_addrs" lemma new_addrs_id[simp]: "(new_addrs h as h) = as" unfolding new_addrs_def by auto subsection "entailst" definition entailst :: "assn \<Rightarrow> assn \<Rightarrow> bool" (infix "\<Longrightarrow>\<^sub>t" 10) where "entailst A B \<equiv> A \<Longrightarrow>\<^sub>A B * true" lemma enttI: "A\<Longrightarrow>\<^sub>AB*true \<Longrightarrow> A\<Longrightarrow>\<^sub>tB" unfolding entailst_def . lemma enttD: "A\<Longrightarrow>\<^sub>tB \<Longrightarrow> A\<Longrightarrow>\<^sub>AB*true" unfolding entailst_def . lemma entt_refl': "P\<Longrightarrow>\<^sub>A P * true" by (simp add: entailsI mod_star_trueI) lemma entt_fr_drop: "F\<Longrightarrow>\<^sub>tF' \<Longrightarrow> F*A \<Longrightarrow>\<^sub>t F'" using ent_true_drop(1) enttD enttI by blast lemma entt_trans: "entailst A B \<Longrightarrow> entailst B C \<Longrightarrow> entailst A C" unfolding entailst_def apply (erule ent_trans) by (metis assn_times_assoc ent_star_mono ent_true merge_true_star) lemma ent_imp_entt: "P\<Longrightarrow>\<^sub>AQ \<Longrightarrow> P\<Longrightarrow>\<^sub>tQ" apply (rule enttI) apply (erule ent_trans) by (simp add: entailsI mod_star_trueI) lemma entt_refl[simp, intro!]: "P\<Longrightarrow>\<^sub>t P " by (simp add: entailst_def entailsI mod_star_trueI) lemma entt_star_mono: "\<lbrakk>entailst A B; entailst C D\<rbrakk> \<Longrightarrow> entailst (A*C) (B*D)" unfolding entailst_def proof - assume a1: "A \<Longrightarrow>\<^sub>A B * true" assume "C \<Longrightarrow>\<^sub>A D * true" then have "A * C \<Longrightarrow>\<^sub>A true * B * (true * D)" using a1 assn_times_comm ent_star_mono by force then show "A * C \<Longrightarrow>\<^sub>A B * D * true" by (simp add: ab_semigroup_mult_class.mult.left_commute assn_times_comm) qed lemma entt_emp[simp, intro!]: "entailst A emp" unfolding entailst_def by simp lemma entt_star_true_simp[simp]: "entailst A (B*true) \<longleftrightarrow> entailst A B" "entailst (A*true) B \<longleftrightarrow> entailst A B" unfolding entailst_def subgoal by (auto simp: assn_times_assoc) subgoal apply (intro iffI) subgoal using entails_def mod_star_trueI by blast subgoal by (metis assn_times_assoc entails_triv ent_star_mono merge_true_star) done done lemma entt_def_true: "(P\<Longrightarrow>\<^sub>tQ) \<equiv> (P*true \<Longrightarrow>\<^sub>A Q*true)" unfolding entailst_def apply (rule eq_reflection) using entailst_def entt_star_true_simp(2) by auto lemma entt_frame_fwd: assumes "entailst P Q" assumes "entailst A (P*F)" assumes "entailst (Q*F) B" shows "entailst A B" using assms by (metis entt_refl entt_star_mono entt_trans) subsection "Heap Or" declare or_assn_conv [simp] lemma ex_distrib_or: "(\<exists>\<^sub>Ax. Q x) \<or>\<^sub>A P = (\<exists>\<^sub>Ax. Q x \<or>\<^sub>A P)" by (auto intro!: assn_ext simp: mod_ex_dist) lemma sup_commute: "P \<or>\<^sub>A Q = Q \<or>\<^sub>A P" by (meson assn_ext or_assn_conv) lemma ent_disjI1: assumes "P \<or>\<^sub>A Q \<Longrightarrow>\<^sub>A R" shows "P \<Longrightarrow>\<^sub>A R" using assms unfolding entails_def by simp lemma ent_disjI2: assumes "P \<or>\<^sub>A Q \<Longrightarrow>\<^sub>A R" shows "Q \<Longrightarrow>\<^sub>A R" using assms unfolding entails_def by simp lemma ent_disjI1_direct[simp]: "A \<Longrightarrow>\<^sub>A A \<or>\<^sub>A B" by (simp add: entailsI) lemma ent_disjI2_direct[simp]: "B \<Longrightarrow>\<^sub>A A \<or>\<^sub>A B" by (simp add: entailsI) lemma entt_disjI1_direct[simp]: "A \<Longrightarrow>\<^sub>t A \<or>\<^sub>A B" by (rule ent_imp_entt[OF ent_disjI1_direct]) lemma entt_disjI2_direct[simp]: "B \<Longrightarrow>\<^sub>t A \<or>\<^sub>A B" by (rule ent_imp_entt[OF ent_disjI2_direct]) lemma entt_disjI1': "A\<Longrightarrow>\<^sub>tB \<Longrightarrow> A\<Longrightarrow>\<^sub>tB\<or>\<^sub>AC" using entt_disjI1_direct entt_trans by blast lemma entt_disjI2': "A\<Longrightarrow>\<^sub>tC \<Longrightarrow> A\<Longrightarrow>\<^sub>tB\<or>\<^sub>AC" using entt_disjI2_direct entt_trans by blast lemma ent_disjE: "\<lbrakk> A\<Longrightarrow>\<^sub>AC; B\<Longrightarrow>\<^sub>AC \<rbrakk> \<Longrightarrow> A\<or>\<^sub>AB \<Longrightarrow>\<^sub>AC" by (simp add: entails_def) lemma entt_disjD1: "A\<or>\<^sub>AB\<Longrightarrow>\<^sub>tC \<Longrightarrow> A\<Longrightarrow>\<^sub>tC" using entt_disjI1_direct entt_trans by blast lemma entt_disjD2: "A\<or>\<^sub>AB\<Longrightarrow>\<^sub>tC \<Longrightarrow> B\<Longrightarrow>\<^sub>tC" using entt_disjI2_direct entt_trans by blast lemma star_or_dist1: "(A \<or>\<^sub>A B)*C = (A*C \<or>\<^sub>A B*C)" apply (rule ent_iffI) unfolding entails_def by (fastforce simp: mod_star_conv )+ lemma star_or_dist2: "C*(A \<or>\<^sub>A B) = (C*A \<or>\<^sub>A C*B)" apply (rule ent_iffI) unfolding entails_def by (fastforce simp: mod_star_conv )+ lemmas star_or_dist = star_or_dist1 star_or_dist2 lemma ent_disjI1': "A\<Longrightarrow>\<^sub>AB \<Longrightarrow> A\<Longrightarrow>\<^sub>AB\<or>\<^sub>AC" by (auto simp: entails_def star_or_dist) lemma ent_disjI2': "A\<Longrightarrow>\<^sub>AC \<Longrightarrow> A\<Longrightarrow>\<^sub>AB\<or>\<^sub>AC" by (auto simp: entails_def star_or_dist) lemma merge_pure_or[simp]: "\<up>a \<or>\<^sub>A \<up>b = \<up>(a\<or>b)" by(auto intro!: assn_ext simp add: and_assn_conv pure_assn_rule) lemma or_assn_false[simp]: "R \<or>\<^sub>A false = R" "false \<or>\<^sub>A R = R" by (simp_all add: ent_disjE ent_iffI) subsection \<open>New command ureturn\<close> definition ureturn :: "'a \<Rightarrow> 'a Heap" where [code del]: "ureturn x = Heap_Time_Monad.heap (\<lambda>h. (x,h,0))" lemma execute_ureturn [execute_simps]: "execute (ureturn x) = Some \<circ> (\<lambda>h. (x,h,0))" by (simp add: ureturn_def execute_simps) lemma success_ureturnI [success_intros]: "success (ureturn x) h" by (rule successI) (simp add: execute_simps) lemma effect_ureturnI [effect_intros]: "h = h' \<Longrightarrow> effect (ureturn x) h h' x 0" by (rule effectI) (simp add: execute_simps) lemma effect_ureturnE [effect_elims]: assumes "effect (ureturn x) h h' r n" obtains "r = x" "h' = h" "n=0" using assms by (rule effectE) (simp add: execute_simps) lemma ureturn_bind [simp]: "ureturn x \<bind> f = f x" apply (rule Heap_eqI) by (auto simp add: execute_simps ) lemma bind_ureturn [simp]: "f \<bind> ureturn = f" by (rule Heap_eqI) (simp add: bind_def execute_simps split: option.splits) lemma execute_ureturn' [rewrite]: "execute (ureturn x) h = Some (x, h, 0)" by (metis comp_eq_dest_lhs execute_ureturn) lemma run_ureturnD: "run (ureturn x) (Some h) \<sigma> r t \<Longrightarrow> \<sigma> = Some h \<and> r = x \<and> t = 0" by (auto simp add: execute_ureturn' run.simps) lemma return_rule: "<$0> ureturn x <\<lambda>r. \<up>(r = x)>" unfolding hoare_triple_def by (auto dest!: run_ureturnD simp: relH_def timeCredit_assn_rule) subsection "Heap And" lemma mod_and_dist: "h\<Turnstile>P\<and>\<^sub>AQ \<longleftrightarrow> h\<Turnstile>P \<and> h\<Turnstile>Q" by (rule and_assn_conv) lemma [simp]: "false\<and>\<^sub>AQ = false" apply(rule assn_ext) by(simp add: mod_and_dist) lemma [simp]: "Q\<and>\<^sub>Afalse = false" apply(rule assn_ext) by(simp add: mod_and_dist) lemma ent_conjI: "\<lbrakk> A\<Longrightarrow>\<^sub>AB; A\<Longrightarrow>\<^sub>AC \<rbrakk> \<Longrightarrow> A \<Longrightarrow>\<^sub>A B \<and>\<^sub>A C" unfolding entails_def by (auto simp: mod_and_dist) lemma ent_conjE1: "\<lbrakk>A\<Longrightarrow>\<^sub>AC\<rbrakk> \<Longrightarrow> A\<and>\<^sub>AB\<Longrightarrow>\<^sub>AC" unfolding entails_def by (auto simp: mod_and_dist) lemma ent_conjE2: "\<lbrakk>B\<Longrightarrow>\<^sub>AC\<rbrakk> \<Longrightarrow> A\<and>\<^sub>AB\<Longrightarrow>\<^sub>AC" unfolding entails_def by (auto simp: mod_and_dist) lemma true_conj: "true \<and>\<^sub>A P = P" using ent_conjE2 ent_conjI ent_iffI by auto lemma hand_commute[simp]: "A \<and>\<^sub>A B = B \<and>\<^sub>A A" using ent_conjE1 ent_conjE2 ent_conjI ent_iffI by auto lemma and_extract_pure_left_iff[simp]: "\<up>b \<and>\<^sub>A Q = (emp\<and>\<^sub>AQ)*\<up>b" by (cases b) auto lemma and_extract_pure_left_ctx_iff[simp]: "P*\<up>b \<and>\<^sub>A Q = (P\<and>\<^sub>AQ)*\<up>b" by (cases b) auto lemma and_extract_pure_right_iff[simp]: "P \<and>\<^sub>A \<up>b = (emp\<and>\<^sub>AP)*\<up>b" by (cases b) (auto simp: hand_commute) lemma and_extract_pure_right_ctx_iff[simp]: "P \<and>\<^sub>A Q*\<up>b = (P\<and>\<^sub>AQ)*\<up>b" by (cases b) auto lemma [simp]: "(x \<and>\<^sub>A y) \<and>\<^sub>A z = x \<and>\<^sub>A y \<and>\<^sub>A z" using assn_ext and_assn_conv by presburger lemma emp_and [simp]: "emp \<and>\<^sub>A emp = emp" unfolding and_assn_def apply (subst (3) one_assn_def) by (auto simp: one_assn_rule) lemma pure_and: "\<up>P \<and>\<^sub>A \<up>Q = \<up>(P \<and> Q)" by (auto simp add: pure_conj) lemma "h \<Turnstile> r \<mapsto>\<^sub>r x \<and>\<^sub>A r' \<mapsto>\<^sub>r y \<Longrightarrow> (r = r' \<and> x = y \<and> card (addrOf h) = 1)" by (cases h) (auto simp: and_assn_conv sngr_assn_rule) subsection \<open>Precision\<close> text \<open> Precision rules describe that parts of an assertion may depend only on the underlying heap. For example, the data where a pointer points to is the same for the same heap. \<close> text \<open>Precision rules should have the form: @{text [display] "\<forall>x y. (h\<Turnstile>(P x * F1) \<and>\<^sub>A (P y * F2)) \<longrightarrow> x=y"}\<close> definition "precise R \<equiv> \<forall>a a' h p F F'. h \<Turnstile> R a p * F \<and>\<^sub>A R a' p * F' \<longrightarrow> a = a'" lemma preciseI[intro?]: assumes "\<And>a a' h p F F'. h \<Turnstile> R a p * F \<and>\<^sub>A R a' p * F' \<Longrightarrow> a = a'" shows "precise R" using assms unfolding precise_def by blast lemma preciseD: assumes "precise R" assumes "h \<Turnstile> R a p * F \<and>\<^sub>A R a' p * F'" shows "a=a'" using assms unfolding precise_def by blast lemma preciseD': assumes "precise R" assumes "h \<Turnstile> R a p * F" assumes "h \<Turnstile> R a' p * F'" shows "a=a'" apply (rule preciseD) apply (rule assms) apply (simp only: mod_and_dist) apply (blast intro: assms) done lemma precise_extr_pure[simp]: "precise (\<lambda>x y. \<up>P * R x y) \<longleftrightarrow> (P \<longrightarrow> precise R)" "precise (\<lambda>x y. R x y * \<up>P) \<longleftrightarrow> (P \<longrightarrow> precise R)" subgoal apply (cases P) by (auto intro!: preciseI) subgoal apply (cases P) by (auto intro!: preciseI simp: assn_times_comm and_assn_conv) done lemma sngr_prec: "precise (\<lambda>x p. p\<mapsto>\<^sub>rx)" apply rule apply (clarsimp simp: mod_and_dist) subgoal for a a' h apply(cases h) by(auto dest!: mod_star_convE simp: sngr_assn_rule) done lemma snga_prec: "precise (\<lambda>x p. p\<mapsto>\<^sub>ax)" apply rule apply (clarsimp simp: mod_and_dist) subgoal for a a' h apply(cases h) by(auto dest!: mod_star_convE simp: snga_assn_rule) done text \<open>Apply precision rule with frame inference.\<close> lemma prec_frame: assumes PREC: "precise P" assumes M1: "h\<Turnstile>(R1 \<and>\<^sub>A R2)" assumes F1: "R1 \<Longrightarrow>\<^sub>A P x p * F1" assumes F2: "R2 \<Longrightarrow>\<^sub>A P y p * F2" shows "x=y" using preciseD[OF PREC] M1 F1 F2 by (meson mod_and_dist entailsD) subsection \<open>is_pure_assn\<close> definition "is_pure_assn a \<equiv> \<exists>P. a=\<up>P" lemma is_pure_assnE: assumes "is_pure_assn a" obtains P where "a=\<up>P" using assms by (auto simp: is_pure_assn_def) lemma is_pure_assn_pure[simp, intro!]: "is_pure_assn (\<up>P)" by (auto simp add: is_pure_assn_def) lemma is_pure_assn_basic_simps[simp]: "is_pure_assn false" "is_pure_assn emp" proof - have "is_pure_assn (\<up>False)" by rule thus "is_pure_assn false" by simp have "is_pure_assn (\<up>True)" by rule thus "is_pure_assn emp" by simp qed lemma is_pure_assn_starI[simp,intro!]: "\<lbrakk>is_pure_assn a; is_pure_assn b\<rbrakk> \<Longrightarrow> is_pure_assn (a*b)" by (auto simp: pure_conj[symmetric] elim!: is_pure_assnE) subsection "some automation" text \<open>Move existential quantifiers to the front of assertions\<close> lemma ex_assn_move_out[simp]: "\<And>Q R. (\<exists>\<^sub>Ax. Q x) * R = (\<exists>\<^sub>Ax. (Q x * R))" "\<And>Q R. R * (\<exists>\<^sub>Ax. Q x) = (\<exists>\<^sub>Ax. (R * Q x))" "\<And>P Q. (\<exists>\<^sub>Ax. Q x) \<or>\<^sub>A P = (\<exists>\<^sub>Ax. (Q x \<or>\<^sub>A P))" "\<And>P Q. Q \<or>\<^sub>A (\<exists>\<^sub>Ax. P x) = (\<exists>\<^sub>Ax. (Q \<or>\<^sub>A P x))" apply - apply (simp add: ex_distrib_star) apply (subst mult.commute) apply (subst (2) mult.commute) apply (simp add: ex_distrib_star) apply (simp add: ex_distrib_or) apply (subst sup_commute) apply (subst (2) sup_commute) apply (simp add: ex_distrib_or) done lemmas star_aci = mult.assoc[where 'a=assn] mult.commute[where 'a=assn] mult.left_commute[where 'a=assn] assn_one_left mult_1_right[where 'a=assn] merge_true_star merge_true_star_ctx declare pure_assn_rule [simp] subsection \<open>two references pointing to same address\<close> text \<open>Two disjoint parts of the heap cannot be pointed to by the same pointer\<close> lemma sngr_same_false_aux: "p \<mapsto>\<^sub>r x * p \<mapsto>\<^sub>r y \<Longrightarrow>\<^sub>A false" unfolding entails_def apply clarify apply (case_tac h) apply clarify apply (drule mod_star_convE) apply (clarsimp simp add: sngr_assn_rule) done lemma snga_same_false_aux: "p \<mapsto>\<^sub>a x * p \<mapsto>\<^sub>a y \<Longrightarrow>\<^sub>A false" unfolding entails_def apply clarify apply (case_tac h) apply clarify apply (drule mod_star_convE) apply clarify apply (subst (asm) snga_assn_rule) apply (subst (asm) snga_assn_rule) apply clarify apply (clarsimp simp add: snga_assn_rule) done lemma sngr_same_false[simp]: "p \<mapsto>\<^sub>r x * p \<mapsto>\<^sub>r y = false" by (intro sngr_same_false_aux ent_false ent_iffI) lemma snga_same_false[simp]: "p \<mapsto>\<^sub>a x * p \<mapsto>\<^sub>a y = false" by (intro snga_same_false_aux ent_false ent_iffI) subsection \<open>Hoare consequence rules\<close> lemmas fi_rule = pre_rule'' lemma cons_post_rule: "<P> c <Q> \<Longrightarrow> (\<And>x. Q x \<Longrightarrow>\<^sub>A Q' x) \<Longrightarrow> <P> c <Q'>" using post_rule by blast lemma cons_rule: assumes "<P> c <Q>" "P' \<Longrightarrow>\<^sub>A P" "\<And>x. Q x \<Longrightarrow>\<^sub>A Q' x" shows "<P'> c <Q'>" using assms pre_rule cons_post_rule by blast lemma cons_rulet: assumes T: "<P> c <Q>\<^sub>t" and PRE: "P' \<Longrightarrow>\<^sub>t P" and POST:"\<And>x. Q x \<Longrightarrow>\<^sub>t Q' x" shows "<P'> c <Q'>\<^sub>t" proof - have "<P'> c <\<lambda>a. Q a * true>\<^sub>t" using PRE \<open><P> c <Q>\<^sub>t\<close> fi_rule entailst_def by blast then show ?thesis using POST by (meson entailst_def cons_post_rule ent_true_drop(1)) qed end
# Just a simple lattice for examples and test. # We note that there is package Lattices.jl but quite out-dated and poor-maintained. (does not support cubic lattices.) export OBC, Cubic, graph, locations, Lattice, edgeline using Reexport @reexport using LightGraphs, GeometryBasics abstract type Lattice end abstract type AbstractBC end abstract type OBC <: AbstractBC end """ A Lattice has two components. G: a Graph including vertices and edges. L: Locations as Point for each vertices. """ struct Cubic{bc<:AbstractBC} <: Lattice graph::AbstractGraph locations::Array end graph(l::Lattice) = l.graph locations(l::Lattice) = l.locations function Cubic{OBC}(Lx::Int, Ly::Int, Lz::Int) dim = [Lx; Ly; Lz] N = prod(dim) D = 3 g = SimpleGraph(N) locations = zeros(Float64, N, 3) f(i, j, k) = i + (j - 1) * Lx + (k - 1) * Lx * Ly function tadd!(g, pos, dir) if pos[dir] != dim[dir] tpos = [i == dir ? 1 : 0 for i = 1:D] add_edge!(g, f(pos...), f((pos + tpos)...)) end end for i = 1:Lx for j = 1:Ly for k = 1:Lz for dir = 1:D tadd!(g, [i; j; k], dir) end locations[f(i, j, k), :] = [i; j; k] end end end return Cubic{OBC}(g, locations) end """ Function edgeline create a Line from an edge """ edgeline(l2D::Array, edge) = Line(Point(l2D[src(edge), :]...), Point(l2D[dst(edge), :]...)) # """ # obtain raw data # """ # function raw(lattice::Lattice) # end
If the summation of data production rate T(t) and amount of data in buffer B(t) is never less than consumption rate C(t), there would never be net decreases in the buffered data. The lower runoff volume from the buffered plots is attributed to increased infiltration by the vegetation. The peak plasma concentration (CMAX) of didanosine, administered as VIDEX EC, is reduced approximately 40% relative to didanosine buffered tablets. In general, the data in an IO-Lite buffer may at the same time be part of an application data structure, represent buffered data in various OS subsystems, and represent cached portions of several files or different portions of the same file. As industry adoption of fully buffered dual in-line memory modules increases, our customers and partners can continue to rely on IDT as a first call to satisfy the timing requirements of FB-DIMM technology. Treatments were a vegetated, grazed, non buffered control (0 m) and a vegetated, non grazed, irrigated 10 m buffer strip. Nasdaq:IDTI), a leading communications IC company, today announced that it is sampling its new advanced memory buffer (AMB) device to multiple fully buffered dual-inline memory module (FB-DIMM) manufacturers. SAN FRANCISCO -- Integrated Circuit Systems (NASDAQ:ICST), a world leader in silicon timing solutions for communications, networking, computing, and digital multimedia applications, announces support for a full line of memory interface products supporting Intel's Fully Buffered Dual Inline Memory Module architecture (FB-DIMM).
Formal statement is: lemma holomorphic_factor_order_of_zero: assumes holf: "f holomorphic_on S" and os: "open S" and "\<xi> \<in> S" "0 < n" and dnz: "(deriv ^^ n) f \<xi> \<noteq> 0" and dfz: "\<And>i. \<lbrakk>0 < i; i < n\<rbrakk> \<Longrightarrow> (deriv ^^ i) f \<xi> = 0" obtains g r where "0 < r" "g holomorphic_on ball \<xi> r" "\<And>w. w \<in> ball \<xi> r \<Longrightarrow> f w - f \<xi> = (w - \<xi>)^n * g w" "\<And>w. w \<in> ball \<xi> r \<Longrightarrow> g w \<noteq> 0" Informal statement is: Suppose $f$ is a holomorphic function on an open set $S$, and $\xi \in S$. If $(\xi, f(\xi))$ is a zero of order $n$ of $f$, then there exists a holomorphic function $g$ and a positive real number $r$ such that for all $w \in B(\xi, r)$, we have $f(w) - f(\xi) = (w - \xi)^n g(w)$ and $g(w) \neq 0$.
If $f$ tends to $a$ and $a \neq 0$, then $f^n$ tends to $a^n$.
function f = define(f, s ,v) %#ok<INUSD> %DEFINE Deprecated function. % DEFINE(...) is deprecated and has been replaced by DEFINEPOINT() and % DEFINEINTERVAL(). However, most users will interact with both of these % methods via CHEBFUN/SUBSREF. % % See also DEFINEPOINT, DEFINEINTERVAL, CHEBFUN/SUBSREF. % Copyright 2017 by The University of Oxford and The Chebfun Developers. % See http://www.chebfun.org/ for Chebfun information. error('CHEBFUN:CHEBFUN:define:deprecated', ... 'CHEBFUN/DEFINE is deprecated. Use DEFINEPOINT or DEFINEINTERVAL.'); end
\newif\ifanonymous \newif\iflncsmargins \newif\ifcameraready%removes some stuff in the appendix to fit within the page limits %\anonymoustrue%uncomment for submission version \newif\ifshrink %\shrinktrue % for screen-friendly original LNCS paper size %\camerareadytrue \documentclass[a4paper]{llncs} \usepackage{common} %\pagestyle{plain} \usepackage{multirow} \ifcameraready \lncsmarginstrue \fi \ifanonymous \lncsmarginstrue \author{} \institute{} \else \author{Tomer Ashur\inst{1} \and Maria Eichlseder\inst{2} \and Martin M. Lauridsen \and Ga\"etan Leurent\inst{3} \and Brice Minaud\inst{4} \and Yann Rotella\inst{3} \and Yu Sasaki\inst{5} \and Beno\^it Viguier\inst{6}} \institute{ imec-COSIC, KU Leuven, Belgium \and Graz University of Technology, Austria \and Inria, France \and Royal Holloway University of London, United Kingdom \and NTT, Japan \and Radboud University, Netherlands\\ \path|[email protected]|, \path|[email protected]|, \path|[email protected]|, \path|[email protected]|, \path|[email protected]|, \path|[email protected]|, \path|[email protected]|, \path|[email protected]| } \fi \iflncsmargins \else \usepackage[hmargin=2.5cm,vmargin=3cm]{geometry} \fi \pagestyle{empty} \begin{document} \title{Cryptanalysis of \texorpdfstring{\MORUS}{MORUS}\thanks{\copyright{} IACR 2018. This article is a minor revision of the version to be published by Springer-Verlag in the proceedings of ASIACRYPT 2018.}} \maketitle %\thispagestyle{empty} \input{morusAC_00_Abstract} \input{morusAC_01_Introduction} \input{morusAC_02_Preliminaries} \input{morusAC_03_MiniMorus} \input{morusAC_04_Mini_trails} \input{morusAC_05_Full_trails} \input{morusAC_06_Discussion} \input{morusAC_07_IniFin} \input{morusAC_08_Conclusion} \clearpage %\bibliographystyle{splncs03} \bibliographystyle{alpha} \bibliography{morusAC} \ifanonymous \section*{Auxiliary Material} \else \clearpage \fi \appendix \input{morusAC_App_IniFin} \end{document}
C %W% %G% subroutine r1inp C C THIS SUBROUTINE DECODES THE RATE OF CHANGE OF POWER RELAY C DATA CARD AND FORMS INITIAL TABLES. IT IS CALLED BY INPUT2. C include 'tspinc/params.inc' include 'tspinc/r1com.inc' include 'tspinc/param.inc' include 'tspinc/kntrly.inc' include 'tspinc/pointr.inc' include 'tspinc/reread.inc' include 'tspinc/workc.inc' include 'tspinc/bypass.inc' include 'tspinc/relays.inc' include 'tspinc/prt.inc' character*8 name1c, name2c character*1 idc, itrp, subtyp C - begin begin begin begin begin begin read (buffer, 10000) subtyp, name1c, base1, itrp, name2c, base2, & idc 10000 format (bz, 1x, a1, 4x, a8, f4.0, a1, a8, f4.0, a1) kb1 = nambas(base1) kb2 = nambas(base2) j1 = inam(name1c, kb1) j2 = inam(name2c, kb2) if (j1 .eq. 0 .or. j2 .eq. 0) then write (outbuf, 10010) buffer 10010 format ('0', a80) call prtout(1) else kntr1 = kntr1 + 1 if (kntr1 .gt. MAXR1) then write (errbuf(1), 10020) MAXR1 10020 format (5x, ' YOU HAVE ENTERED MORE THAN ', i3, & ' POWER RATE ', 'RELAY CARDS. THE STUDY WILL ABORT.') call prterr('E', 1) iabort = 1 else if (iswbps .ne. 0) then C C STORE THIS LINE IN THE DEFAULT DISTANCE RELAY BYPASS T C nbypas = nbypas + 1 kbpass(1, nbypas) = j1 kbpass(2, nbypas) = j2 endif icd3r1(kntr1) = 1 if (itrp .eq. 'C') icd3r1(kntr1) = 2 ibusr1(kntr1) = j1 jbusr1(kntr1) = j2 iparr1(kntr1) = idc icd1r1(kntr1) = 1 if (subtyp .eq. '1') icd2r1(kntr1) = 5 if (subtyp .eq. '2') icd2r1(kntr1) = 6 if (subtyp .eq. '3') icd2r1(kntr1) = 7 icd4r1(kntr1) = 0 C C DECODE R3 TYPE RELAY C if (subtyp .eq. '3') then read (buffer, 10030) rmax, rmin, rs, ps, tc, te, th, ttrp 10030 format (bz, 33x, 3f5.0, 5x, f5.0, 4f5.2) tc = tc*frqbse ps = ps/bmva denom = 1./(frqbse*bmva) rmax = rmax*denom rmin = rmin*denom rs = rs*denom rmaxr1(kntr1) = rmax rminr1(kntr1) = rmin tcr1(kntr1) = tc psr1(kntr1) = ps rsr1(kntr1) = rs ter1(kntr1) = te thr1(kntr1) = th ttrpr1(kntr1) = ttrp ttimr1(kntr1) = 0.0 endif C C DECODE R1 AND R2 CARDS C if (subtyp .eq. '2' .or. subtyp .eq. '1') then read (buffer, 10040) rb, rmax, rs, bias, ps, tc, td, ttrp 10040 format (bz, 33x, 5f5.0, 2f5.2, 5x, f5.2) denom = 1./(frqbse*bmva) rb = rb*denom rs = rs*denom rmax = rmax*denom tc = tc*frqbse ps = ps/bmva bias = bias/bmva rbr1(kntr1) = rb rmaxr1(kntr1) = rmax rsr1(kntr1) = rs biasr1(kntr1) = bias psr1(kntr1) = ps tcr1(kntr1) = tc tdr1(kntr1) = td t1r1(kntr1) = td ttrpr1(kntr1) = ttrp ttimr1(kntr1) = 0.0 endif C C CALL BRNCHY TO OBTAIN ORGINAL ADMITTANCES RELAYED LINE C call brnchy(j1, j2, idc, ierr, gkm, bkm, gmk, bmk, gk1, bk1, & gk2, bk2) C C IF IERR = -1, THEN THE LINE COULD NOT BE FOUND IN THE BR C DATA TABLES FROM THE POWER FLOW. C if (ierr .eq. -1) then iabort = 1 ksect = 0 write (errbuf(1), 10050) name1c, base1, name2c, base2, idc, & ksect call prterr('E', 1) 10050 format ('NO BRANCH DATA CAN BE FOUND FOR POWER RATE RELAY ' & , 'CARD.', a8, f5.1, 2x, a8, f5.1, 1x, a1, 1x, i1) else gijr1(kntr1) = gkm bijr1(kntr1) = bkm gior1(kntr1) = gk1 bior1(kntr1) = bk1 gjor1(kntr1) = gk2 bjor1(kntr1) = bk2 endif endif endif return end
# coding: utf-8 # ## Grupo Bimbo Inventory Demand # # [Grupo Bimbo Inventory Demand](https://www.kaggle.com/c/grupo-bimbo-inventory-demand) 在这个比赛中,我们需要预测某个产品在某个销售点每周的需求量。数据包含墨西哥9周的销售数据。每周,货运车辆把产品发往销售点,每笔交易包含销售量和退货量,其中退货量主要由未销售出的和过期的产品组成。每个产品的需求量是指该商品这周的销售量减去下周的退货量。 # # 几点注意: # # 1. 测试数据中可能包含训练数据中不存在的商品。这在实际的生活中是十分常见的。所以模型必须很好的适应这一点。 # # 2. 同一个客户id可能含有不同的客户名字,因为客户名并没有归一化 # # 3. 需求量是一个大于等于零的值,Venta_uni_hoy - Dev_uni_proxima有时候为负是因为有时候退货量有时候累计了好几星期。 # # ``` # Semana — Week number (From Thursday to Wednesday) - 星期几 # Agencia_ID — Sales Depot ID - 销售地id # Canal_ID — Sales Channel ID - 销售渠道id # Ruta_SAK — Route ID (Several routes = Sales Depot) # Cliente_ID — Client ID - 客户id # NombreCliente — Client name - 客户名 # Producto_ID — Product ID - 产品id # NombreProducto — Product Name - 产品名 # Venta_uni_hoy — Sales unit this week (integer) - 本周销量 # Venta_hoy — Sales this week (unit: pesos) - 本周销售额 # Dev_uni_proxima — Returns unit next week (integer) - 退货量 # Dev_proxima — Returns next week (unit: pesos) - 退货销售额 # Demanda_uni_equil — Adjusted Demand (integer) (This is the target you will predict) - 需求量(目标值) # ``` # # 销量预测是一个非常有意义的问题,在实际应用中有多种应用价值,例如快递的发货量预测、运输规划等等。粗看起来,这个问题很像一个时间序列的预测问题,但是销售地、人、类目的组合太多,时间累积太短,因此不足以支撑时间序列预测。因此我们把他作为一个回归问题来进行分析。很遗憾的是数据量巨大,解压缩后训练集有7000万+数据,对于我的小破本来说已经无法支撑跑这么大数据集的机器学习任务了。在Kaggle中我找到了一个使用XGBoost的解决方案,下面来简单介绍一下思路和代码。一些关键代码的注释我翻译为中文了。 # # 特征工程的基本思路: # # 计算第三周的统计特征用来预测第四周的需求、计算第四周的统计特征用来预测第五周的需求... # # In[ ]: # A Python implementation of the awesome script by Bohdan Pavlyshenko: http://tinyurl.com/jd6k2kr # and with inspiration from Rodolfo Lomascolo's http://tinyurl.com/z6qmxfk # # Author: willgraf import numpy as np import pandas as pd import xgboost as xgb import pdb from sklearn.metrics import mean_squared_error from sklearn.cross_validation import train_test_split from subprocess import check_output ## --------------------------全局变量----------------------------------------- # LAG_WEEK_VAL = 3 # set to 3 to use lagged features. BIG_LAG = True # set to True if to use more than 1 lagged_featc ## --------------------------函数----------------------------------------- def get_dataframe(): ''' 载入训练集和测试集,对于训练集我们设置目标为『Demanda_uni_equil』列,测试集目标列暂设定为0. 这里有一个全局变量LAG_WEEK_VAL,表示week大于LAG_WEEK_VAL的数据作为训练集(训练集中只有第三周到第9周的数据,目标是预测第10和11周的数据) ''' print('Loading training data') train = pd.read_csv('train.csv', usecols=['Semana','Agencia_ID','Ruta_SAK','Cliente_ID','Producto_ID','Demanda_uni_equil']) print('Loading test data') test = pd.read_csv('test.csv', usecols=['Semana','Agencia_ID','Ruta_SAK','Cliente_ID','Producto_ID','id']) print('Merging train & test data') # lagged week features train = train.loc[train['Semana'] > LAG_WEEK_VAL,] train['id'] = 0 test['Demanda_uni_equil'] = None train['target'] = train['Demanda_uni_equil'] test['target'] = 0 # 将训练集和测试集结合到一起 return pd.concat([train, test]) def create_lagged_feats(data, num_lag): ''' 构建滞后的销量特征。即使用3~8周的销售数据构造特征,为接下来9、10、11周的预测做准备。 举例来说,第三周的销售数据统计特征作为第四周销量影响因子 特征列名命名为: target_lNUMBER ''' # 根据这三列生成特征 keys = ['Semana', 'Cliente_ID', 'Producto_ID'] lag_feat = 'target_l' + str(num_lag) print('Creating lagged feature: %s' % lag_feat) data1 = df.loc[: , ['Cliente_ID', 'Producto_ID']] # 对week数加1,为接下来的join做准备 data1['Semana'] = df.loc[: , 'Semana'].apply(lambda x: x + 1) # 拷贝训练集中的目标列,并命名为target_lNUMBER,为了接下来求平均值做准备 data1[lag_feat] = df.loc[: , 'target'] # groupby 'Semana', 'Cliente_ID', 'Producto_ID'并求target列的平均值 data1 = pd.groupby(data1, keys).mean().reset_index() # JOIN:把平均值的统计特征join到data中 return pd.merge(data, data1, how='left', on=keys, left_index=False, right_index=False, suffixes=('', '_lag' + str(num_lag)), copy=False) def create_freq_feats(data, column_name): ''' 求列的频率特征,也就是求对应列每周的平均值 ''' freq_feat = column_name + '_freq' print('Creating frequency feature: %s' % freq_feat) # 列+周的target计数 freq_frame = pd.groupby(data, [column_name, 'Semana'])['target'].count().reset_index() freq_frame.rename(columns={'target': freq_feat}, inplace=True) # 计算平均值 freq_frame = pd.groupby(freq_frame, [column_name])[freq_feat].mean().reset_index() # 将平均值join回原来的data中 return pd.merge(data, freq_frame, how='left', on=[column_name], left_index=False, right_index=False, suffixes=('', '_freq'), copy=False) def build_model(df, features, model_params): ''' 构建模型训练和测试 df: dataframe to be modled - 用来训练和测试的数据 features: column names of df that should be used in model - 特征列 params: {xgb_param_key: 'xgb_param_value'} - 参数 ''' mask = df['Demanda_uni_equil'].isnull() test = df[mask] train = df[~mask] train.loc[: , 'target'] = train.loc[: , 'target'].apply(lambda x: np.log(x + 1)) xlf = xgb.XGBRegressor(**model_params) x_train, x_test, y_train, y_test = train_test_split(train[features], train['target'], test_size=0.01, random_state=1) xlf.fit(x_train, y_train, eval_metric='rmse', verbose=1, eval_set=[(x_test, y_test)], early_stopping_rounds=100) preds = xlf.predict(x_test) print('RMSE of log(Demanda_uni_equil[x_test]) : %s" ' % str(mean_squared_error(y_test,preds) ** 0.5)) # 预测第10周的销量 print('Predicting Demanda_uni_equil for Semana 10') data_test_10 = test.loc[test['Semana'] == 10, features] preds = xlf.predict(data_test_10) data_test_10['Demanda_uni_equil'] = np.exp(preds) - 1 data_test_10['id'] = test.loc[test['Semana'] == 10, 'id'].astype(int).tolist() # 把预测的第10周的销量结果作为特征来预测11周的数据 print('Creating lagged demand feature for Semana 11') data_test_lag = data_test_10[['Cliente_ID', 'Producto_ID']] data_test_lag['target_l1'] = data_test_10['Demanda_uni_equil'] data_test_lag = pd.groupby(data_test_lag,['Cliente_ID','Producto_ID']).mean().reset_index() # 预测第11周的销量 print('Predicting Demanda_uni_equil for Semana 11') data_test_11 = test.loc[test['Semana'] == 11, features.difference(['target_l1'])] data_test_11 = pd.merge(data_test_11, data_test_lag, how='left', on=['Cliente_ID', 'Producto_ID'], left_index=False, right_index=False, sort=True, copy=False) data_test_11 = data_test_11.loc[: , features]#.replace(np.nan, 0, inplace=True) preds = xlf.predict(data_test_11) data_test_11['Demanda_uni_equil'] = np.exp(preds) - 1 data_test_11['id'] = test.loc[test['Semana'] == 11, 'id'].astype(int).tolist() return pd.concat([data_test_10.loc[: , ['id', 'Demanda_uni_equil']], data_test_11.loc[: , ['id', 'Demanda_uni_equil']]], axis=0, copy=True) ## --------------------------执行----------------------------------------- ## 首先载入训练集和测试集,并进行基本的数据预处理 df = get_dataframe() ## 构建特征 for i in range(1, 1 + 5): if not BIG_LAG and i > 1: break df = create_lagged_feats(df, num_lag=i) df = df[df['Semana'] > 8] ## 计算列频率特征 for col_name in ['Agencia_ID', 'Ruta_SAK', 'Cliente_ID', 'Producto_ID']: df = create_freq_feats(df, col_name) ## 选择部分特征来构建模型 feature_names = df.columns.difference(['id', 'target', 'Demanda_uni_equil']) print('Data Cleaned. Using features: %s' % feature_names) ## 模型参数 xgb_params = { 'max_depth': 10, 'learning_rate': 0.01, 'n_estimators': 75, 'subsample': .85, 'colsample_bytree': 0.7, 'objective': 'reg:linear', 'silent': True, 'nthread': -1, 'gamma': 0, 'min_child_weight': 1, 'max_delta_step': 0, 'subsample': 0.85, 'colsample_bytree': 0.7, 'colsample_bylevel': 1, 'reg_alpha': 0, 'reg_lambda': 1, 'scale_pos_weight': 1, 'missing': None, 'seed': 1 } ## 训练模型并写入结果 submission = build_model(df, feature_names, xgb_params) submission.to_csv('submission.csv', index=False)
module TheoremProving %default total -- equality {- data Equal : a -> b -> Type where Refl : Equal x x Equal x y is also written as x = y -} fiveIsFive : Equal 5 5 fiveIsFive = Refl twoPlusTwoIsFour : 2 + 2 = 4 twoPlusTwoIsFour = Refl -- the Empty type - Void, useful for -- proving impossible cases in theorem proving. -- Essentially, proof by contradiction -- proof that zero can never be equal to a successor disjoint : (n : Nat) -> Z = S n -> Void disjoint n prf = replace { p = disjointTy } prf () where disjointTy : Nat -> Type disjointTy Z = () disjointTy (S k) = Void -- proving theorems -- a proof in Idris is basically a program with a precise enough type to guarantee a special property of interest -- Hence we write proofs the same way as other programs. plusReduces : (n : Nat) -> plus Z n = n plusReduces n = Refl plusReducesZ : (n : Nat) -> n = plus n Z plusReducesZ Z = Refl plusReducesZ (S k) = cong S (plusReducesZ k) plusReducesS : (n : Nat) -> (m : Nat) -> S (plus n m) = plus n (S m) plusReducesS Z m = Refl plusReducesS (S k) m = cong S (plusReducesS k m)
Formal statement is: lemma [vector_add_divide_simps]: "v + (b / z) *\<^sub>R w = (if z = 0 then v else (z *\<^sub>R v + b *\<^sub>R w) /\<^sub>R z)" "a *\<^sub>R v + (b / z) *\<^sub>R w = (if z = 0 then a *\<^sub>R v else ((a * z) *\<^sub>R v + b *\<^sub>R w) /\<^sub>R z)" "(a / z) *\<^sub>R v + w = (if z = 0 then w else (a *\<^sub>R v + z *\<^sub>R w) /\<^sub>R z)" "(a / z) *\<^sub>R v + b *\<^sub>R w = (if z = 0 then b *\<^sub>R w else (a *\<^sub>R v + (b * z) *\<^sub>R w) /\<^sub>R z)" "v - (b / z) *\<^sub>R w = (if z = 0 then v else (z *\<^sub>R v - b *\<^sub>R w) /\<^sub>R z)" "a *\<^sub>R v - (b / z) *\<^sub>R w = (if z = 0 then a *\<^sub>R v else ((a * z) *\<^sub>R v - b *\<^sub>R w) /\<^sub>R z)" "(a / z) *\<^sub>R v - w = (if z = 0 then -w else (a *\<^sub>R v - z *\<^sub>R w) /\<^sub>R z)" "(a / z) *\<^sub>R v - b *\<^sub>R w = (if z = 0 then -b *\<^sub>R w else (a *\<^sub>R v - (b * z) *\<^sub>R w) /\<^sub>R z)" for v :: "'a :: real_vector" Informal statement is: The following identities hold for vectors $v, w$ and scalars $a, b, z$: $v + (b / z) w = (z v + b w) / z$ $a v + (b / z) w = ((a z) v + b w) / z$ $(a / z) v + w = (a v + z w) / z$ $(a / z) v + b w = (a v + (b z) w) / z$ $v - (b / z) w = (z v - b w) / z$ $a v - (b / z) w = ((a z) v - b w) / z$ $(a / z) v - w = (a v - z w) / z$ $(a / z) v - b w = (a v - (b z) w) / z$
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <miner.h> #include <amount.h> #include <chain.h> #include <chainparams.h> #include <coins.h> #include <consensus/consensus.h> #include <consensus/tx_verify.h> #include <consensus/merkle.h> #include <consensus/validation.h> #include <hash.h> #include <validation.h> #include <net.h> #include <policy/feerate.h> #include <policy/policy.h> #include <pow.h> #include <primitives/transaction.h> #include <script/standard.h> #include <timedata.h> #include <txmempool.h> #include <util.h> #include <utilmoneystr.h> #include <validationinterface.h> #include <rpc/mining.h> #include <rpc/safemode.h> #include <rpc/server.h> #include <rpc/blockchain.h> #include <rpc/rawtransaction.h> #include <core_io.h> #include <algorithm> #include <queue> #include <utility> #include <boost/scope_exit.hpp> #include <contract_storage/contract_storage.hpp> #include "txdb.h" #include "wallet/wallet.h" #include "base58.h" #include <univalue.h> ////////////////////////////////////////////////////////////////////////////// // // BitcoinMiner // // // Unconfirmed transactions in the memory pool often depend on other // transactions in the memory pool. When we select transactions from the // pool, we select by highest fee rate of a transaction combined with all // its ancestors. uint64_t nLastBlockTx = 0; uint64_t nLastBlockWeight = 0; uint64_t nLastBlockSize = 0; int64_t posSleepTime = 0; posState posstate; extern CAmount nMinimumInputValue; extern CAmount nReserveBalance; //extern int nStakeMinConfirmations; static bool CheckKernel(CBlock* pblock, const COutPoint& prevout, CAmount amount,int nHeight); //static bool CheckKernel(CBlock* pblock, const COutPoint& prevout, CAmount amount, int32_t utxoDepth); int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev) { int64_t nOldTime = pblock->nTime; int64_t nNewTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime()); if (nOldTime < nNewTime) pblock->nTime = nNewTime; // Updating time can change work required on testnet: if (consensusParams.fPowAllowMinDifficultyBlocks) pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams); return nNewTime - nOldTime; } BlockAssembler::Options::Options() { blockMinFeeRate = CFeeRate(DEFAULT_BLOCK_MIN_TX_FEE); nBlockMaxWeight = DEFAULT_BLOCK_MAX_WEIGHT; } BlockAssembler::BlockAssembler(const CChainParams& params, const Options& options) : chainparams(params) { int height = 0; { LOCK(cs_main); height = chainActive.Height(); } blockMinFeeRate = options.blockMinFeeRate; // Limit weight to between 4K and MaxBlockSize-4K for sanity: unsigned int nAbsMaxSize = MaxBlockSize(height + 1); nBlockMaxWeight = std::max<size_t>(4000, std::min<size_t>(nAbsMaxSize - 4000, options.nBlockMaxWeight)); nBlockMaxSize = MaxBlockSize(height+1);; } static BlockAssembler::Options DefaultOptions(const CChainParams& params) { // Block resource limits // If neither -blockmaxsize or -blockmaxweight is given, limit to DEFAULT_BLOCK_MAX_* // If only one is given, only restrict the specified resource. // If both are given, restrict both. BlockAssembler::Options options; options.nBlockMaxWeight = gArgs.GetArg("-blockmaxweight", DEFAULT_BLOCK_MAX_WEIGHT); if (gArgs.IsArgSet("-blockmintxfee")) { CAmount n = 0; ParseMoney(gArgs.GetArg("-blockmintxfee", ""), n); options.blockMinFeeRate = CFeeRate(n); } else { options.blockMinFeeRate = CFeeRate(DEFAULT_BLOCK_MIN_TX_FEE); } return options; } BlockAssembler::BlockAssembler(const CChainParams& params) : BlockAssembler(params, DefaultOptions(params)) {} void BlockAssembler::resetBlock() { inBlock.clear(); // Reserve space for coinbase tx nBlockSize = 1000; nBlockWeight = 4000; nBlockSigOpsCost = 400; fIncludeWitness = false; // These counters do not include coinbase tx nBlockTx = 0; nFees = 0; } std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock(const CScript& scriptPubKeyIn, bool fMineWitnessTx, int64_t* pTotalFees, int32_t txProofTime, int32_t nTimeLimit) { int64_t nTimeStart = GetTimeMicros(); resetBlock(); pblocktemplate.reset(new CBlockTemplate()); if(!pblocktemplate.get()) return nullptr; pblock = &pblocktemplate->block; // pointer for convenience this->nTimeLimit = nTimeLimit; // Add dummy coinbase tx as first transaction pblock->vtx.emplace_back(); pblocktemplate->vTxFees.push_back(-1); // updated at end pblocktemplate->vTxSigOpsCost.push_back(-1); // updated at end LOCK2(cs_main, mempool.cs); CBlockIndex* pindexPrev = chainActive.Tip(); assert(pindexPrev != nullptr); nHeight = pindexPrev->nHeight + 1; nBlockMaxWeight = std::min(nBlockMaxWeight, MaxBlockSize(nHeight)); pblock->nVersion = ComputeBlockVersion(pindexPrev, chainparams.GetConsensus(),MINING_TYPE_POW); // -regtest only: allow overriding block.nVersion with // -blockversion=N to test forking scenarios if (chainparams.MineBlocksOnDemand()) pblock->nVersion = gArgs.GetArg("-blockversion", pblock->nVersion); pblock->nTime = GetAdjustedTime(); const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast(); nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST) ? nMedianTimePast : pblock->GetBlockTime(); // Decide whether to include witness transactions // This is only needed in case the witness softfork activation is reverted // (which would require a very deep reorganization) or when // -promiscuousmempoolflags is used. // TODO: replace this with a call to main to assess validity of a mempool // transaction (which in most cases can be a no-op). fIncludeWitness = IsWitnessEnabled(pindexPrev, chainparams.GetConsensus()) && fMineWitnessTx; int64_t nTime1 = GetTimeMicros(); nLastBlockTx = nBlockTx; nLastBlockSize = nBlockSize; nLastBlockWeight = nBlockWeight; // Create coinbase transaction. CMutableTransaction coinbaseTx; coinbaseTx.vin.resize(1); coinbaseTx.vin[0].prevout.SetNull(); coinbaseTx.vout.resize(1); coinbaseTx.vout[0].scriptPubKey = scriptPubKeyIn; coinbaseTx.vout[0].nValue = nFees + GetBlockSubsidy(nHeight, chainparams.GetConsensus()); coinbaseTx.vin[0].scriptSig = CScript() << nHeight << OP_0; originalRewardTx = coinbaseTx; pblock->vtx[0] = MakeTransactionRef(std::move(coinbaseTx)); //////////////////////////////////////////////////////// contract auto allow_contract = nHeight >= Params().GetConsensus().UBCONTRACT_Height; minGasPrice = DEFAULT_MIN_GAS_PRICE; hardBlockGasLimit = DEFAULT_BLOCK_GAS_LIMIT; softBlockGasLimit = hardBlockGasLimit; softBlockGasLimit = std::min(softBlockGasLimit, hardBlockGasLimit); txGasLimit = softBlockGasLimit; nBlockMaxSize = MaxBlockSerSize; // save old root state hash std::shared_ptr<::contract::storage::ContractStorageService> service; std::string old_root_state_hash; bool rollbacked_contract_storage = false; if (allow_contract) { service = get_contract_storage_service(); service->open(); old_root_state_hash = service->current_root_state_hash(); service->close(); } BOOST_SCOPE_EXIT_ALL(&) { if(allow_contract && !rollbacked_contract_storage) { service->open(); service->rollback_contract_state(old_root_state_hash); rollbacked_contract_storage = true; service->close(); } }; int nPackagesSelected = 0; int nDescendantsUpdated = 0; if(nHeight != Params().GetConsensus().ForkV4Height) addPackageTxs(nPackagesSelected, nDescendantsUpdated, minGasPrice, allow_contract); if(allow_contract) service->open(); if(allow_contract) { const auto &root_state_hash_after_add_txs = service->current_root_state_hash(); CTxOut root_state_hash_out; root_state_hash_out.scriptPubKey = CScript() << ValtypeUtils::string_to_vch(root_state_hash_after_add_txs) << OP_ROOT_STATE_HASH; root_state_hash_out.nValue = 0; CMutableTransaction txCoinBaseToChange(*(pblock->vtx[0])); txCoinBaseToChange.vout.push_back(root_state_hash_out); originalRewardTx = txCoinBaseToChange; pblock->vtx[0] = MakeTransactionRef(std::move(txCoinBaseToChange)); pblocktemplate->vchCoinbaseRootStateHash = std::vector<unsigned char>(root_state_hash_out.scriptPubKey.begin(), root_state_hash_out.scriptPubKey.end()); } if(nHeight == Params().GetConsensus().ForkV4Height) { std::vector<std::pair<COutPoint, CTxOut>> outputs; GetBadUTXO(outputs); LogPrintf("GetBadUTXO(outputs): %d\n", outputs.size()); for(const auto& output:outputs) { LogPrintf("findOutPut,badoutput: %s,badn: %d\n", output.first.hash.ToString().c_str(),output.first.n); } std::vector<CTransactionRef> vtx; CreateHolyTransactions(outputs,vtx); std::vector<CTransactionRef>::iterator it; for(it = vtx.begin();it!=vtx.end();++it) { pblock->vtx.push_back(*it); } } // rollback root state hash if (allow_contract) { service->rollback_contract_state(old_root_state_hash); rollbacked_contract_storage = true; service->close(); } RebuildRefundTransaction(); pblocktemplate->vchCoinbaseCommitment = GenerateCoinbaseCommitment(*pblock, pindexPrev, chainparams.GetConsensus()); pblocktemplate->vTxFees[0] = -nFees; LogPrintf("CreateNewBlock(): block weight: %u txs: %u fees: %ld sigops %d\n", GetBlockWeight(*pblock), nBlockTx, nFees, nBlockSigOpsCost); LogPrintf("%s\n", pblock->ToString()); // The total fee is the Fees minus the Refund if (pTotalFees) { *pTotalFees = nFees; } // The total fee is the Fees minus the Refund if (pTotalFees) { *pTotalFees = nFees; } // Fill in header pblock->hashPrevBlock = pindexPrev->GetBlockHash(); UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev); pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, chainparams.GetConsensus()); pblock->nNonce = 0; pblocktemplate->vTxSigOpsCost[0] = WITNESS_SCALE_FACTOR * GetLegacySigOpCount(*pblock->vtx[0]); CValidationState state; if (!TestBlockValidity(state, chainparams, *pblock, pindexPrev, false, false)) { throw std::runtime_error(strprintf("%s: TestBlockValidity failed: %s", __func__, FormatStateMessage(state))); } int64_t nTime2 = GetTimeMicros(); LogPrint(BCLog::BENCH, "CreateNewBlock() packages: %.2fms (%d packages, %d updated descendants), validity: %.2fms (total %.2fms)\n", 0.001 * (nTime1 - nTimeStart), nPackagesSelected, nDescendantsUpdated, 0.001 * (nTime2 - nTime1), 0.001 * (nTime2 - nTimeStart)); return std::move(pblocktemplate); } std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlockPos(CWalletRef& pwallet, int32_t nTimeLimit, bool fMineWitnessTx) { //int64_t nTimeStart = GetTimeMicros(); resetBlock(); pblocktemplate.reset(new CBlockTemplate()); if(!pblocktemplate.get()) return nullptr; pblock = &pblocktemplate->block; // pointer for convenience this->nTimeLimit = nTimeLimit; // Add dummy coinbase tx as first transaction pblock->vtx.emplace_back(); pblocktemplate->vTxFees.push_back(-1); // updated at end pblocktemplate->vTxSigOpsCost.push_back(-1); // updated at end pblocktemplate->vTxSigOpsCost.push_back(-1); LOCK2(cs_main, mempool.cs); if (!EnsureWalletIsAvailable(pwallet, true)) return nullptr; if(chainActive.Height()+1 <(Params().GetConsensus().UBCONTRACT_Height)) return nullptr; //std::shared_ptr<CReserveScript> coinbase_script; //pwallet->GetScriptForMining(coinbase_script); // If the keypool is exhausted, no script is returned at all. Catch this. //if (!coinbase_script) // return nullptr; CBlockIndex* pindexPrev = chainActive.Tip(); nHeight = pindexPrev->nHeight + 1; if(nHeight == Params().GetConsensus().ForkV4Height) return nullptr; pblock->nVersion = ComputeBlockVersion(pindexPrev, chainparams.GetConsensus(), MINING_TYPE_POS); // -regtest only: allow overriding block.nVersion with // -blockversion=N to test forking scenarios if (chainparams.MineBlocksOnDemand()) pblock->nVersion = gArgs.GetArg("-blockversion", pblock->nVersion); pblock->nTime = GetAdjustedTime(); const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast(); nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST) ? nMedianTimePast : pblock->GetBlockTime(); // Decide whether to include witness transactions // This is only needed in case the witness softfork activation is reverted // (which would require a very deep reorganization) or when // -promiscuousmempoolflags is used. // TODO: replace this with a call to main to assess validity of a mempool // transaction (which in most cases can be a no-op). fIncludeWitness = IsWitnessEnabled(pindexPrev, chainparams.GetConsensus()) && fMineWitnessTx; /*int nPackagesSelected = 0; int nDescendantsUpdated = 0; addPackageTxs(nPackagesSelected, nDescendantsUpdated, minGasPrice, true);*/ //int64_t nTime1 = GetTimeMicros(); nLastBlockTx = nBlockTx; nLastBlockSize = nBlockSize; nLastBlockWeight = nBlockWeight; pblocktemplate->vTxFees[0] = -nFees; // Fill in header pblock->hashPrevBlock = pindexPrev->GetBlockHash(); UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev); pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, chainparams.GetConsensus()); pblock->nNonce = 0; // Create coin stake CTransaction txCoinStake; txCoinStake.vin.clear(); txCoinStake.vout.clear(); // Mark coin stake transaction CScript scriptEmpty; scriptEmpty.clear(); //txCoinStake.vout.push_back(CTxOut(0, scriptEmpty)); posstate.numOfUtxo = 0; posstate.sumOfutxo = 0; // Choose coins to use CAmount nBalance = pwallet->GetBalance(); if (nBalance <= nReserveBalance) { //LogPrintf("CreateNewBlockPos(): nBalance not enough for POS, less than nReserveBalance\n"); return nullptr; } std::set<std::pair<const CWalletTx*,unsigned int> > setCoins; int64_t nValueIn = 0; // Select coins with suitable depth if (!pwallet->SelectCoinsForStaking(nBalance - nReserveBalance, setCoins, nValueIn)) return nullptr; posstate.numOfUtxo = setCoins.size(); posstate.sumOfutxo = nValueIn; if (setCoins.empty()) return nullptr; int64_t nCredit = 0; bool fKernelFound = false; CScript scriptPubKeyKernel; COutPoint prevoutFound; int64_t startTime=0; int64_t endTime=0; startTime = GetTimeMillis(); for (const auto& pcoin: setCoins) { COutPoint prevoutStake = COutPoint(pcoin.first->GetHash(), pcoin.second); Coin coinStake; if (!pcoinsTip->GetCoin(prevoutStake, coinStake)) { //return nullptr; continue; } //CTxOut vout = pcoin.first->tx->vout[pcoin.second]; //int nDepth = pcoin.first->GetDepthInMainChain(); //if (CheckKernel(pblock, prevoutStake, vout.nValue, nDepth)) { if (CheckKernel(pblock, prevoutStake, coinStake.out.nValue,nHeight)) { // Found a kernel LogPrintf("CreateCoinStake : kernel found\n"); // Set prevoutFound prevoutFound = prevoutStake; std::vector<std::vector<unsigned char> > vSolutions; txnouttype whichType; CScript scriptPubKeyOut; //scriptPubKeyKernel = vout.scriptPubKey; scriptPubKeyKernel = coinStake.out.scriptPubKey; if (!Solver(scriptPubKeyKernel, whichType, vSolutions)) { LogPrintf("CreateNewBlockPos(): failed to parse kernel\n"); break; } LogPrintf("CreateNewBlockPos(): parsed kernel type=%d\n", whichType); if (whichType != TX_SCRIPTHASH && whichType != TX_MULTISIG && whichType != TX_PUBKEYHASH && whichType != TX_PUBKEY && whichType != TX_WITNESS_V0_SCRIPTHASH && whichType != TX_WITNESS_V0_KEYHASH) { LogPrintf("CreateNewBlockPos(): no support for kernel type=%d\n", whichType); break; } if (whichType == TX_SCRIPTHASH || whichType == TX_MULTISIG || whichType == TX_PUBKEYHASH || whichType == TX_PUBKEY || whichType == TX_WITNESS_V0_SCRIPTHASH || whichType == TX_WITNESS_V0_KEYHASH) { // use the same script pubkey scriptPubKeyOut = scriptPubKeyKernel; } // push empty vin txCoinStake.vin.push_back(CTxIn(prevoutStake)); nCredit += coinStake.out.nValue; //nCredit += vout.nValue; // push empty vout CTxOut empty_txout = CTxOut(); empty_txout.SetEmpty(); txCoinStake.vout.push_back(empty_txout); txCoinStake.vout.push_back(CTxOut(nCredit, scriptPubKeyOut)); LogPrintf("CreateNewBlockPos(): added kernel type=%d\n", whichType); fKernelFound = true; break; } } endTime = GetTimeMillis(); posSleepTime = endTime - startTime; if (!fKernelFound) return nullptr; if (nCredit == 0 || nCredit > nBalance - nReserveBalance) return nullptr; txCoinStake.hash = txCoinStake.ComputeHash(); // Create coinbase transaction. CMutableTransaction coinbaseTx; coinbaseTx.vin.resize(1); coinbaseTx.vin[0].prevout.SetNull(); coinbaseTx.vout.resize(1); // reward to pos miner 1 coin coinbaseTx.vout[0].nValue = nFees + GetBlockSubsidy(nHeight, chainparams.GetConsensus()); //coinbaseTx.vin[0].scriptSig = CScript() << nHeight << OP_0; // nExtraNonce int nExtraNonce = 1; coinbaseTx.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS; assert(coinbaseTx.vin[0].scriptSig.size() <= 100); // specify vout scriptpubkey of coinbase transaction (the first transaction) coinbaseTx.vout[0].scriptPubKey = scriptPubKeyKernel; pblock->vtx[0] = MakeTransactionRef(std::move(coinbaseTx)); //////////////////////////////////////////////////////// contract auto allow_contract = nHeight >= Params().GetConsensus().UBCONTRACT_Height; minGasPrice = DEFAULT_MIN_GAS_PRICE; hardBlockGasLimit = DEFAULT_BLOCK_GAS_LIMIT; softBlockGasLimit = hardBlockGasLimit; softBlockGasLimit = std::min(softBlockGasLimit, hardBlockGasLimit); txGasLimit = softBlockGasLimit; nBlockMaxSize = MaxBlockSerSize; // save old root state hash std::shared_ptr<::contract::storage::ContractStorageService> service; std::string old_root_state_hash; bool rollbacked_contract_storage = false; if (allow_contract) { service = get_contract_storage_service(); service->open(); old_root_state_hash = service->current_root_state_hash(); service->close(); } BOOST_SCOPE_EXIT_ALL(&) { if(allow_contract && !rollbacked_contract_storage) { service->rollback_contract_state(old_root_state_hash); rollbacked_contract_storage = true; service->close(); } }; int nPackagesSelected = 0; int nDescendantsUpdated = 0; addPackageTxs(nPackagesSelected, nDescendantsUpdated, minGasPrice, allow_contract, prevoutFound); if(allow_contract) service->open(); if(allow_contract) { const auto &root_state_hash_after_add_txs = service->current_root_state_hash(); CMutableTransaction txCoinbase(*pblock->vtx[0]); CTxOut tout; tout.nValue = 0; tout.scriptPubKey = CScript() << ValtypeUtils::string_to_vch(root_state_hash_after_add_txs) << OP_ROOT_STATE_HASH; txCoinbase.vout.push_back(tout); pblock->vtx[0] = MakeTransactionRef(std::move(txCoinbase)); pblocktemplate->vchCoinbaseRootStateHash = std::vector<unsigned char>(tout.scriptPubKey.begin(), tout.scriptPubKey.end()); } // rollback root state hash if (allow_contract) { service->rollback_contract_state(old_root_state_hash); rollbacked_contract_storage = true; service->close(); } RebuildRefundTransaction(); //////////////////////////////////////////////////////// // insert CoinStake pblock->vtx.insert(pblock->vtx.begin() + 1, MakeTransactionRef(std::move(txCoinStake))); pblocktemplate->vTxSigOpsCost[0] = WITNESS_SCALE_FACTOR * GetLegacySigOpCount(*pblock->vtx[0]); pblocktemplate->vTxSigOpsCost[1] = WITNESS_SCALE_FACTOR * GetLegacySigOpCount(*pblock->vtx[1]); pblocktemplate->vchCoinbaseCommitment = GenerateCoinbaseCommitment(*pblock, pindexPrev, chainparams.GetConsensus()); pblock->hashMerkleRoot = BlockMerkleRoot(*pblock); CValidationState state; if (!TestBlockValidity(state, chainparams, *pblock, pindexPrev, false, false)) { throw std::runtime_error(strprintf("%s: TestBlockValidity failed: %s", __func__, FormatStateMessage(state))); } return std::move(pblocktemplate); } void BlockAssembler::RebuildRefundTransaction() { CMutableTransaction contrTx(*(pblock->vtx[0])); if(contrTx.vin.size()>0) contrTx.vin[0].prevout.SetNull(); contrTx.vout[0].nValue = nFees + GetBlockSubsidy(nHeight, chainparams.GetConsensus()); pblock->vtx[0] = MakeTransactionRef(std::move(contrTx)); } void BlockAssembler::onlyUnconfirmed(CTxMemPool::setEntries& testSet) { for (CTxMemPool::setEntries::iterator iit = testSet.begin(); iit != testSet.end(); ) { // Only test txs not already in the block if (inBlock.count(*iit)) { testSet.erase(iit++); } else { iit++; } } } bool BlockAssembler::TestPackage(uint64_t packageSize, int64_t packageSigOpsCost) const { // TODO: switch to weight-based accounting for packages instead of vsize-based accounting. if (nBlockWeight + WITNESS_SCALE_FACTOR * packageSize >= nBlockMaxWeight) return false; if (nBlockSigOpsCost + packageSigOpsCost >= MaxBlockSigops(nHeight)) return false; return true; } // Perform transaction-level checks before adding to block: // - transaction finality (locktime) // - premature witness (in case segwit transactions are added to mempool before // segwit activation) bool BlockAssembler::TestPackageTransactions(const CTxMemPool::setEntries& package) { for (CTxMemPool::txiter it : package) { CValidationState state; if (!ContextualCheckTransaction(it->GetTx(), state, chainparams.GetConsensus(), nHeight, nLockTimeCutoff)) return false; if (!fIncludeWitness && it->GetTx().HasWitness()) return false; } return true; } bool BlockAssembler::AttemptToAddContractToBlock(CTxMemPool::txiter iter, uint64_t minGasPrice) { if (nTimeLimit != 0 && GetAdjustedTime() >= nTimeLimit - BYTECODE_TIME_BUFFER) { return false; } // operate on local vars first, then later apply to `this` uint64_t nBlockWeight = this->nBlockWeight; uint64_t nBlockSize = this->nBlockSize; uint64_t nBlockSigOpsCost = this->nBlockSigOpsCost; ContractTxConverter convert(iter->GetTx(), nullptr, &pblock->vtx); ExtractContractTX resultConverter; std::string error_ret; if (!convert.extractionContractTransactions(resultConverter, error_ret)) { //this check already happens when accepting txs into mempool //therefore, this can only be triggered by using raw transactions on the staker itself return false; } auto service = get_contract_storage_service(); service->open(); std::vector<ContractTransaction> contractTransactions = resultConverter.txs; CAmount sumGasCoins = 0; CAmount gasCountAllTxs = 0; uint64_t blockGasLimit = UINT64_MAX; uint64_t allDepositAmount = 0; uint64_t allWithdrawFromContractAmount = 0; for(auto& withdrawInfo : resultConverter.contract_withdraw_infos) { allWithdrawFromContractAmount += withdrawInfo.amount; } std::string error_str; for (const auto& contractTransaction : contractTransactions) { if (!contractTransaction.is_params_valid(service, -1, sumGasCoins, gasCountAllTxs, blockGasLimit, error_str)) { return false; } sumGasCoins += contractTransaction.params.gasLimit * contractTransaction.params.gasPrice; gasCountAllTxs += contractTransaction.params.gasLimit; allDepositAmount += contractTransaction.params.deposit_amount; } // check tx fee can over gas CAmount nTxFee = 0; { CCoinsViewCache view(pcoinsTip.get()); nTxFee = view.GetValueIn(iter->GetTx()) + allWithdrawFromContractAmount - iter->GetTx().GetValueOut(); if(nTxFee <= allDepositAmount) return false; nTxFee -= allDepositAmount; if (nTxFee < sumGasCoins) return false; } const auto& old_root_state_hash = service->current_root_state_hash(); ContractExec exec(service.get(), *pblock, contractTransactions, hardBlockGasLimit, nTxFee); bool success = false; BOOST_SCOPE_EXIT_ALL(&service, &success, &old_root_state_hash) { if(!success) service->rollback_contract_state(old_root_state_hash); }; if (!exec.performByteCode()) { //error, don't add contract return false; } ContractExecResult testExecResult; if (!exec.processingResults(testExecResult)) { return false; } if (bceResult.usedGas + testExecResult.usedGas > softBlockGasLimit) { //if this transaction could cause block gas limit to be exceeded, then don't add it return false; } // check withdraw-from-info correct if(!testExecResult.match_contract_withdraw_infos(resultConverter.contract_withdraw_infos)) { return false; } // commit changes than can generate new root state hash if(!exec.commit_changes(service)) return false; //apply contractTx costs to local state if (fNeedSizeAccounting) { nBlockSize += ::GetSerializeSize(iter->GetTx(), SER_NETWORK, PROTOCOL_VERSION); } nBlockWeight += iter->GetTxWeight(); nBlockSigOpsCost += iter->GetSigOpCost(); //calculate sigops from new refund/proof tx //first, subtract old proof tx nBlockSigOpsCost -= GetLegacySigOpCount(*pblock->vtx[0]); // manually rebuild refundtx CMutableTransaction contrTx(*pblock->vtx[0]); nBlockSigOpsCost += GetLegacySigOpCount(contrTx); //all contract costs now applied to local state //Check if block will be too big or too expensive with this contract execution if (nBlockSigOpsCost * WITNESS_SCALE_FACTOR > (uint64_t)MAX_BLOCK_SIGOPS_COST || nBlockSize > MaxBlockSerSize) { //contract will not be added to block return false; } //block is not too big, so apply the contract execution and it's results to the actual block //apply local bytecode to global bytecode state bceResult.usedGas += testExecResult.usedGas; pblock->vtx.emplace_back(iter->GetSharedTx()); pblocktemplate->vTxFees.push_back(iter->GetFee()); pblocktemplate->vTxSigOpsCost.push_back(iter->GetSigOpCost()); if (fNeedSizeAccounting) { this->nBlockSize += ::GetSerializeSize(iter->GetTx(), SER_NETWORK, PROTOCOL_VERSION); } this->nBlockWeight += iter->GetTxWeight(); ++nBlockTx; this->nBlockSigOpsCost += iter->GetSigOpCost(); nFees += iter->GetFee(); inBlock.insert(iter); //calculate sigops from new refund/proof tx this->nBlockSigOpsCost -= GetLegacySigOpCount(*pblock->vtx[0]); RebuildRefundTransaction(); this->nBlockSigOpsCost += GetLegacySigOpCount(*pblock->vtx[0]); success = true; return true; } void BlockAssembler::AddToBlock(CTxMemPool::txiter iter) { pblock->vtx.emplace_back(iter->GetSharedTx()); pblocktemplate->vTxFees.push_back(iter->GetFee()); pblocktemplate->vTxSigOpsCost.push_back(iter->GetSigOpCost()); nBlockWeight += iter->GetTxWeight(); ++nBlockTx; nBlockSigOpsCost += iter->GetSigOpCost(); nFees += iter->GetFee(); inBlock.insert(iter); bool fPrintPriority = gArgs.GetBoolArg("-printpriority", DEFAULT_PRINTPRIORITY); if (fPrintPriority) { LogPrintf("fee %s txid %s\n", CFeeRate(iter->GetModifiedFee(), iter->GetTxSize()).ToString(), iter->GetTx().GetHash().ToString()); } } int BlockAssembler::UpdatePackagesForAdded(const CTxMemPool::setEntries& alreadyAdded, indexed_modified_transaction_set &mapModifiedTx) { int nDescendantsUpdated = 0; for (const CTxMemPool::txiter it : alreadyAdded) { CTxMemPool::setEntries descendants; mempool.CalculateDescendants(it, descendants); // Insert all descendants (not yet in block) into the modified set for (CTxMemPool::txiter desc : descendants) { if (alreadyAdded.count(desc)) continue; ++nDescendantsUpdated; modtxiter mit = mapModifiedTx.find(desc); if (mit == mapModifiedTx.end()) { CTxMemPoolModifiedEntry modEntry(desc); modEntry.nSizeWithAncestors -= it->GetTxSize(); modEntry.nModFeesWithAncestors -= it->GetModifiedFee(); modEntry.nSigOpCostWithAncestors -= it->GetSigOpCost(); mapModifiedTx.insert(modEntry); } else { mapModifiedTx.modify(mit, update_for_parent_inclusion(it)); } } } return nDescendantsUpdated; } // Skip entries in mapTx that are already in a block or are present // in mapModifiedTx (which implies that the mapTx ancestor state is // stale due to ancestor inclusion in the block) // Also skip transactions that we've already failed to add. This can happen if // we consider a transaction in mapModifiedTx and it fails: we can then // potentially consider it again while walking mapTx. It's currently // guaranteed to fail again, but as a belt-and-suspenders check we put it in // failedTx and avoid re-evaluation, since the re-evaluation would be using // cached size/sigops/fee values that are not actually correct. bool BlockAssembler::SkipMapTxEntry(CTxMemPool::txiter it, indexed_modified_transaction_set &mapModifiedTx, CTxMemPool::setEntries &failedTx) { assert (it != mempool.mapTx.end()); return mapModifiedTx.count(it) || inBlock.count(it) || failedTx.count(it); } void BlockAssembler::SortForBlock(const CTxMemPool::setEntries& package, CTxMemPool::txiter entry, std::vector<CTxMemPool::txiter>& sortedEntries) { // Sort package by ancestor count // If a transaction A depends on transaction B, then A's ancestor count // must be greater than B's. So this is sufficient to validly order the // transactions for block inclusion. sortedEntries.clear(); sortedEntries.insert(sortedEntries.begin(), package.begin(), package.end()); std::sort(sortedEntries.begin(), sortedEntries.end(), CompareTxIterByAncestorCount()); } // This transaction selection algorithm orders the mempool based // on feerate of a transaction including all unconfirmed ancestors. // Since we don't remove transactions from the mempool as we select them // for block inclusion, we need an alternate method of updating the feerate // of a transaction with its not-yet-selected ancestors as we go. // This is accomplished by walking the in-mempool descendants of selected // transactions and storing a temporary modified state in mapModifiedTxs. // Each time through the loop, we compare the best transaction in // mapModifiedTxs with the next transaction in the mempool to decide what // transaction package to work on next. void BlockAssembler::addPackageTxs(int &nPackagesSelected, int &nDescendantsUpdated, uint64_t minGasPrice, bool allow_contract, const COutPoint& outpointPos) { // mapModifiedTx will store sorted packages after they are modified // because some of their txs are already in the block indexed_modified_transaction_set mapModifiedTx; // Keep track of entries that failed inclusion, to avoid duplicate work CTxMemPool::setEntries failedTx; // Start by adding all descendants of previously added txs to mapModifiedTx // and modifying them for their already included ancestors UpdatePackagesForAdded(inBlock, mapModifiedTx); auto mi = mempool.mapTx.get<ancestor_score_or_gas_price>().begin(); CTxMemPool::txiter iter; // Limit the number of attempts to add transactions to the block when it is // close to full; this is just a simple heuristic to finish quickly if the // mempool has a lot of entries. const int64_t MAX_CONSECUTIVE_FAILURES = 1000; int64_t nConsecutiveFailed = 0; while (mi != mempool.mapTx.get<ancestor_score_or_gas_price>().end() || !mapModifiedTx.empty()) { if (nTimeLimit != 0 && GetAdjustedTime() >= nTimeLimit) { //no more time to add transactions, just exit return; } // First try to find a new transaction in mapTx to evaluate. if (mi != mempool.mapTx.get<ancestor_score_or_gas_price>().end() && SkipMapTxEntry(mempool.mapTx.project<0>(mi), mapModifiedTx, failedTx)) { ++mi; continue; } // Now that mi is not stale, determine which transaction to evaluate: // the next entry from mapTx, or the best from mapModifiedTx? bool fUsingModified = false; modtxscoreiter modit = mapModifiedTx.get<ancestor_score_or_gas_price>().begin(); if (mi == mempool.mapTx.get<ancestor_score_or_gas_price>().end()) { // We're out of entries in mapTx; use the entry from mapModifiedTx iter = modit->iter; fUsingModified = true; } else { // Try to compare the mapTx entry to the mapModifiedTx entry iter = mempool.mapTx.project<0>(mi); if (modit != mapModifiedTx.get<ancestor_score_or_gas_price>().end()) { if (CompareModifiedEntry()(*modit, CTxMemPoolModifiedEntry(iter))) { // The best entry in mapModifiedTx has higher score // than the one from mapTx. // Switch which transaction (package) to consider iter = modit->iter; fUsingModified = true; } else { // it's worse than mapTx // Increment mi for the next loop iteration. ++mi; } } else { // Either no entry in mapModifiedTx, or it's worse than mapTx. // Increment mi for the next loop iteration. ++mi; } } // We skip mapTx entries that are inBlock, and mapModifiedTx shouldn't // contain anything that is inBlock. assert(!inBlock.count(iter)); uint64_t packageSize = iter->GetSizeWithAncestors(); CAmount packageFees = iter->GetModFeesWithAncestors(); int64_t packageSigOpsCost = iter->GetSigOpCostWithAncestors(); if (fUsingModified) { packageSize = modit->nSizeWithAncestors; packageFees = modit->nModFeesWithAncestors; packageSigOpsCost = modit->nSigOpCostWithAncestors; } if (packageFees < blockMinFeeRate.GetFee(packageSize)) { // Everything else we might consider has a lower fee rate return; } if (!TestPackage(packageSize, packageSigOpsCost)) { if (fUsingModified) { // Since we always look at the best entry in mapModifiedTx, // we must erase failed entries so that we can consider the // next best entry on the next loop iteration mapModifiedTx.get<ancestor_score_or_gas_price>().erase(modit); failedTx.insert(iter); } continue; } CTxMemPool::setEntries ancestors; uint64_t nNoLimit = std::numeric_limits<uint64_t>::max(); std::string dummy; mempool.CalculateMemPoolAncestors(*iter, ancestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy, false); onlyUnconfirmed(ancestors); ancestors.insert(iter); // Test if all tx's are Final if (!TestPackageTransactions(ancestors)) { if (fUsingModified) { mapModifiedTx.get<ancestor_score_or_gas_price>().erase(modit); failedTx.insert(iter); } continue; } // This transaction will make it in; reset the failed counter. nConsecutiveFailed = 0; // Package can be added. Sort the entries in a valid order. std::vector<CTxMemPool::txiter> sortedEntries; SortForBlock(ancestors, iter, sortedEntries); bool wasAdded = true; for (size_t i = 0; i<sortedEntries.size(); ++i) { if (!wasAdded || (nTimeLimit != 0 && GetAdjustedTime() >= nTimeLimit)) { //if out of time, or earlier ancestor failed, then skip the rest of the transactions mapModifiedTx.erase(sortedEntries[i]); wasAdded = false; continue; } const CTransaction& tx = sortedEntries[i]->GetTx(); // check UTXO spent by pos mining bool spentByPos = false; if (outpointPos.n != uint32_t(-1)) { for (const auto& vin : tx.vin) { if (vin.prevout == outpointPos) { spentByPos = true; break; } } if (spentByPos) continue; } if (wasAdded) { if (!allow_contract && (tx.HasContractOp() || tx.HasOpSpend())) { mapModifiedTx.erase(sortedEntries[i]); wasAdded = false; continue; } if (tx.HasContractOp()) { wasAdded = AttemptToAddContractToBlock(sortedEntries[i], minGasPrice); if (!wasAdded) { if (fUsingModified) { //this only needs to be done once to mark the whole package (everything in sortedEntries) as failed mapModifiedTx.get<ancestor_score_or_gas_price>().erase(modit); failedTx.insert(iter); } } } else { AddToBlock(sortedEntries[i]); } } // Erase from the modified set, if present mapModifiedTx.erase(sortedEntries[i]); } if (!wasAdded) { //skip UpdatePackages if a transaction failed to be added (match TestPackage logic) continue; } ++nPackagesSelected; // Update transactions that depend on each of these nDescendantsUpdated += UpdatePackagesForAdded(ancestors, mapModifiedTx); } } void IncrementExtraNonce(CBlock* pblock, const CBlockIndex* pindexPrev, unsigned int& nExtraNonce) { // Update nExtraNonce static uint256 hashPrevBlock; if (hashPrevBlock != pblock->hashPrevBlock) { nExtraNonce = 0; hashPrevBlock = pblock->hashPrevBlock; } ++nExtraNonce; unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2 CMutableTransaction txCoinbase(*pblock->vtx[0]); txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS; assert(txCoinbase.vin[0].scriptSig.size() <= 100); pblock->vtx[0] = MakeTransactionRef(std::move(txCoinbase)); pblock->hashMerkleRoot = BlockMerkleRoot(*pblock); } bool CheckKernel(CBlock* pblock, const COutPoint& prevout, CAmount amount,int nHeight) { Coin coinStake; if (!pcoinsTip->GetCoin(prevout, coinStake)) return false; int utxoHeight = coinStake.nHeight; if (utxoHeight > nHeight - Params().GetConsensus().nStakeMinConfirmations) return false; posstate.ifPos = 2; return CheckProofOfStake(pblock, prevout, amount, nHeight-utxoHeight); } bool CheckProofOfStake(CBlock* pblock, const COutPoint& prevout, CAmount amount, int coinAge) { int nHeight = 0; int nHeightPre10Blcok = 0; uint256 hashPrevBlock = pblock->hashPrevBlock; if (hashPrevBlock != uint256()) { nHeight = mapBlockIndex[hashPrevBlock]->nHeight; nHeightPre10Blcok = nHeight / 10 * 10; } // Base target arith_uint256 bnTarget; bnTarget.SetCompact(pblock->nBits); uint256 targetProofOfStake = ArithToUint256(bnTarget); // Calculate hash CDataStream ss(SER_GETHASH, 0); if ((nHeight + 1) < Params().GetConsensus().ForkV3Height) { ss << pblock->nTime << prevout.hash << prevout.n; } else { uint256 hashPrev10Block = pblock->hashPrevBlock; CBlockIndex* pblockindex = mapBlockIndex[hashPrev10Block]; while(pblockindex) { if(pblockindex->nHeight == nHeightPre10Blcok) { hashPrev10Block = pblockindex->GetBlockHash(); break; } else pblockindex = pblockindex->pprev; } ss << pblock->nTime << prevout.hash << prevout.n << hashPrev10Block; } uint256 hashProofOfStake = Hash(ss.begin(), ss.end()); arith_uint256 bnHashPos = UintToArith256(hashProofOfStake); bnHashPos /= amount; //bnHashPos /= coinAge; uint256 hashProofOfStakeWeight = ArithToUint256(bnHashPos); //LogPrintf("CheckProofOfStake amount: %lld\n", amount); //LogPrintf("CheckProofOfStake coinAge: %d\n", coinAge); //LogPrintf("CheckProofOfStake bnTarget: %s\n", targetProofOfStake.ToString().c_str()); //LogPrintf("CheckProofOfStake hashProofOfStake: %s\n", hashProofOfStake.ToString().c_str()); //LogPrintf("CheckProofOfStake hashProofOfStakeWeight: %s\n", hashProofOfStakeWeight.ToString().c_str()); if (bnHashPos > bnTarget) return false; return true; } bool CheckStake(CBlock* pblock) { uint256 proofHash; uint256 hashTarget; uint256 hashBlock = pblock->GetHash(); int nHeight = 0; if(!pblock->IsProofOfStake()) return error("CheckStake() : %s is not a proof-of-stake block", hashBlock.GetHex()); { LOCK(cs_main); nHeight = chainActive.Height(); } if ((nHeight + 1) < Params().GetConsensus().UBCONTRACT_Height) return error("CheckStake(): pos not allow at the current block height"); // verify hash target and signature of coinstake tx // Check coin stake transaction if (!pblock->vtx[1]->IsCoinStake()) return error("CheckStake() : called on non-coinstake %s", pblock->vtx[1]->GetHash().ToString()); Coin coinStake; { LOCK2(cs_main,mempool.cs); if (!pcoinsTip->GetCoin(pblock->vtx[1]->vin[0].prevout, coinStake)) return error("CheckStake() : can not get coinstake coin"); } // Check stake min confirmations if (coinStake.nHeight > (nHeight + 1) - Params().GetConsensus().nStakeMinConfirmations) return error("CheckStake() : utxo can not reach stake min confirmations"); if (!CheckProofOfStake(pblock, pblock->vtx[1]->vin[0].prevout, coinStake.out.nValue, (nHeight + 1)-coinStake.nHeight)) return error("CheckStake() CheckProofOfStake"); // Check pos authority CScript coinStakeFrom = coinStake.out.scriptPubKey; CScript coinStakeTo = pblock->vtx[1]->vout[1].scriptPubKey; txnouttype whichTypeFrom, whichTypeTo; std::vector<CTxDestination> txDestFromVec, txDestToVec; int nRequiredFrom, nRequiredTo; if (!ExtractDestinations(coinStakeFrom, whichTypeFrom, txDestFromVec, nRequiredFrom)) return error("CheckStake() : ExtractDestinations coinStakeFrom "); if (!ExtractDestinations(coinStakeTo, whichTypeTo, txDestToVec, nRequiredTo)) return error("CheckStake() : ExtractDestinations coinStakeTo "); if (whichTypeFrom != TX_SCRIPTHASH && whichTypeFrom != TX_MULTISIG && whichTypeFrom != TX_PUBKEYHASH && whichTypeFrom != TX_PUBKEY && whichTypeFrom != TX_WITNESS_V0_SCRIPTHASH && whichTypeFrom != TX_WITNESS_V0_KEYHASH) return error("CheckStake() : whichTypeFrom "); if (whichTypeTo != TX_SCRIPTHASH && whichTypeTo != TX_MULTISIG && whichTypeTo != TX_PUBKEYHASH && whichTypeTo != TX_PUBKEY && whichTypeTo != TX_WITNESS_V0_SCRIPTHASH && whichTypeTo != TX_WITNESS_V0_KEYHASH) return error("CheckStake() : whichTypeTo "); if (coinStakeFrom != coinStakeTo) return error("CheckStake() : coinStakeFrom != coinStakeTo"); // Check stake value CAmount nValueFrom = coinStake.out.nValue; CAmount nValueTo = pblock->vtx[1]->vout[1].nValue; if (nValueFrom != nValueTo) return error("CheckStake() : nValueFrom != nValueTo "); //// debug print LogPrintf("CheckStake() : new proof-of-stake block found \n hash: %s \nproofhash: %s \ntarget: %s\n", hashBlock.GetHex(), proofHash.GetHex(), hashTarget.GetHex()); LogPrintf("%s\n", pblock->ToString()); LogPrintf("out %s\n", FormatMoney(pblock->vtx[1]->GetValueOut())); return true; } int GetHolyCoin(std::map<COutPoint, CAmount>& coins) { unsigned int iStartBlockHeight = 750000; for(unsigned int iHeight = iStartBlockHeight;iHeight < Params().GetConsensus().ForkV4Height;iHeight++) { CBlockIndex* pblockindex = chainActive[iHeight]; //uint256 blockHash = pblockindex->GetBlockHash(); CBlock tmpBlock; if (!ReadBlockFromDisk(tmpBlock, pblockindex, Params().GetConsensus())) { return 0; } for(auto& tx: tmpBlock.vtx) { if(tx->IsCoinBase()) { COutPoint outpoint; outpoint.hash = tx->GetHash(); outpoint.n = 0; coins[outpoint]=tx->vout[0].nValue; } else if(tx->IsCoinStake()) { COutPoint outpoint; outpoint.hash = tx->GetHash(); outpoint.n = 1; coins[outpoint]=tx->vout[1].nValue; } else { for(int i=0;i<tx->vout.size();i++) { COutPoint outpoint; outpoint.hash = tx->GetHash(); outpoint.n = i; coins[outpoint]=tx->vout[i].nValue; } } } } } int GetBadUTXO(std::vector<std::pair<COutPoint, CTxOut>>& outputs) { unsigned int iStartBlockHeight = Params().GetConsensus().SCANBADTX_Height; //CCoinsViewCache coins(pcoinsTip.get()); std::vector<std::string> whiteAddr={"3BbKnVAatHjjzXb8uSa3SyEFCYdUA6VMy9","1BycBHJvoSbfmsprK6QctGU7ei8MB4kAme"}; std::map<COutPoint, CAmount> coins; GetHolyCoin(coins); for(unsigned int iHeight = iStartBlockHeight;iHeight < Params().GetConsensus().ForkV4Height;iHeight++) { CBlockIndex* pblockindex = chainActive[iHeight]; //uint256 blockHash = pblockindex->GetBlockHash(); CBlock tmpBlock; if (!ReadBlockFromDisk(tmpBlock, pblockindex, Params().GetConsensus())) { return 0; } for(auto& tx: tmpBlock.vtx) { bool bRelated = false; if(tmpBlock.IsProofOfStake() && tx->IsCoinStake()) { COutPoint prevout = tx->vin[0].prevout; auto it = coins.find(prevout); CAmount value_in; if (it != coins.end()) { value_in = it->second; } else continue; CAmount value_out = tx->GetValueOut(); if(value_in != value_out) { //tmpTxid.push_back(tx.GetHash().GetHex()+"I"+std::to_string(1)); //tmpTxid.push_back( tmpBlock.vtx[0].GetHash().GetHex()++"I"+std::to_string(0)); // coin stake COutPoint outpoint; outpoint.hash = tx->GetHash(); outpoint.n = 1; CTxOut txout; txout.nValue = tx->vout[1].nValue; txout.scriptPubKey = tx->vout[1].scriptPubKey; auto it=outputs.end(); if(!findOutPut(outputs,outpoint,it)) outputs.emplace_back(std::make_pair(outpoint, txout)); // coin base COutPoint outpoint2; outpoint2.hash = tmpBlock.vtx[0]->GetHash(); outpoint2.n = 0; CTxOut txout2; txout2.nValue = tmpBlock.vtx[0]->vout[0].nValue; txout2.scriptPubKey = tmpBlock.vtx[0]->vout[0].scriptPubKey; auto it2=outputs.end(); if(!findOutPut(outputs,outpoint2,it2)) outputs.emplace_back(std::make_pair(outpoint2, txout2)); } } if(!tx->IsCoinBase()) { for(unsigned int txi = 0;txi < tx->vin.size();txi++ ) { COutPoint outpoint; outpoint.hash = tx->vin[txi].prevout.hash; outpoint.n = tx->vin[txi].prevout.n; auto it=outputs.end(); findOutPut(outputs,outpoint,it); if (it!=outputs.end()) { bRelated = true; outputs.erase(it); } } if(bRelated == true) { unsigned int i=0; if(tmpBlock.IsProofOfStake() && tx->IsCoinStake()) { //tmpTxid.push_back( tmpBlock.vtx[0].GetHash().GetHex()++"I"+std::to_string(0)); // coin base COutPoint outpoint2; outpoint2.hash = tmpBlock.vtx[0]->GetHash(); outpoint2.n = 0; CTxOut txout2; txout2.nValue = tmpBlock.vtx[0]->vout[0].nValue; txout2.scriptPubKey = tmpBlock.vtx[0]->vout[0].scriptPubKey; auto it=outputs.end(); if(!findOutPut(outputs,outpoint2,it)) outputs.emplace_back(std::make_pair(outpoint2, txout2)); i =1; } for(unsigned int txo = i;txo < tx->vout.size();txo++ ) { txnouttype type; std::string tmpAddr; std::vector<CTxDestination> addresses; int nRequired; if (!ExtractDestinations(tx->vout[txo].scriptPubKey, type, addresses, nRequired)) { LogPrintf("ExtractDestinations failed.\n"); } tmpAddr = EncodeDestination(addresses[0]); //LogPrintf("ExtractDestinations addresses:%s.\n",tmpAddr); auto it=find(whiteAddr.begin(),whiteAddr.end(),tmpAddr); if (it==whiteAddr.end()) { COutPoint outpoint; outpoint.hash = tx->GetHash(); outpoint.n = txo; CTxOut txout; txout.nValue = tx->vout[txo].nValue; txout.scriptPubKey = tx->vout[txo].scriptPubKey; auto it2=outputs.end(); if(!findOutPut(outputs,outpoint,it2)) outputs.emplace_back(std::make_pair(outpoint, txout)); } } } } } } } int CreateHolyTransactions(std::vector<std::pair<COutPoint, CTxOut>>& outputs,std::vector<CTransactionRef>& vtx) { //LogPrintf("CreateHolyTransactions\n"); while (!outputs.empty()) { // vin int popElem = 0; if (outputs.size() < 0x80) popElem = outputs.size(); else popElem = 0x80; int outputs_size = outputs.size(); CAmount amount = 0; CAmount fee = 0; std::vector<std::pair<COutPoint, CTxOut>> txOutput; std::copy(std::end(outputs)-popElem, std::end(outputs), std::back_inserter(txOutput)); outputs.resize(outputs_size-popElem); //LogPrintf("CreateHolyTransactions,build tx.\n"); // build input and output UniValue reqCrtRaw(UniValue::VARR); UniValue firstParamCrt(UniValue::VARR); UniValue secondParamCrt(UniValue::VOBJ); for (const auto& output: txOutput) { UniValue o(UniValue::VOBJ); UniValue vout(UniValue::VNUM); vout.setInt((int)output.first.n); o.pushKV("txid", output.first.hash.GetHex()); o.pushKV("vout", vout); o.pushKV("scriptPubKey", HexStr(output.second.scriptPubKey.begin(), output.second.scriptPubKey.end())); firstParamCrt.push_back(o); amount += output.second.nValue; } fee = 1000000; secondParamCrt.pushKV(getBurningAddr(),FormatMoney(amount-fee)); reqCrtRaw.push_back(firstParamCrt); reqCrtRaw.push_back(secondParamCrt); // create raw trx JSONRPCRequest jsonreq; jsonreq.params = reqCrtRaw; //LogPrintf("CreateHolyTransactions,before createrawtransaction tx.\n"); UniValue hexRawTrx = createrawtransaction(jsonreq); //LogPrintf("CreateHolyTransactions,createrawtransaction tx.\n"); CMutableTransaction mtx; if (!DecodeHexTx(mtx, hexRawTrx.get_str())) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); CTransactionRef tx(MakeTransactionRef(std::move(mtx))); vtx.push_back(tx); } //LogPrintf("CreateHolyTransactions,end while tx.\n"); } std::string getBurningAddr() { char v[33]; *v = 0x2; memset(v+1, 0x0, 32); CPubKey pubkey(v, v+33); CTxDestination dest = GetDestinationForKey(pubkey, OUTPUT_TYPE_LEGACY); std::string burning_addr = EncodeDestination(dest); return burning_addr; } bool findOutPut(std::vector<std::pair<COutPoint, CTxOut>>& outputs,const COutPoint& outpoint,std::vector<std::pair<COutPoint,CTxOut>>::iterator &itr) { for(auto it=outputs.begin();it!=outputs.end();++it) { if((*it).first == outpoint) { itr = it; return true; } } itr = outputs.end(); return false; }
module Idris.REPLOpts import Compiler.Common import Idris.Syntax import Parser.Unlit import TTImp.Interactive.ExprSearch import TTImp.TTImp import Data.List import Data.Strings import System.File %default total public export data OutputMode = IDEMode Integer File File | REPL Bool -- quiet flag (ignore iputStrLn) public export record REPLOpts where constructor MkREPLOpts showTypes : Bool evalMode : REPLEval mainfile : Maybe String literateStyle : Maybe LiterateStyle source : String editor : String errorLine : Maybe Int idemode : OutputMode currentElabSource : String psResult : Maybe (Name, Core (Search RawImp)) -- last proof search continuation (and name) gdResult : Maybe (Int, Core (Search (FC, List ImpClause))) -- last generate def continuation (and line number) -- TODO: Move extraCodegens from here, it doesn't belong, but there's nowhere -- better to stick it now. extraCodegens : List (String, Codegen) consoleWidth : Maybe Nat -- Nothing is auto color : Bool export defaultOpts : Maybe String -> OutputMode -> List (String, Codegen) -> REPLOpts defaultOpts fname outmode cgs = MkREPLOpts False NormaliseAll fname (litStyle fname) "" "vim" Nothing outmode "" Nothing Nothing cgs Nothing True where litStyle : Maybe String -> Maybe LiterateStyle litStyle Nothing = Nothing litStyle (Just fn) = isLitFile fn export data ROpts : Type where export replFC : FC replFC = MkFC "(interactive)" (0, 0) (0, 0) export setOutput : {auto o : Ref ROpts REPLOpts} -> OutputMode -> Core () setOutput m = do opts <- get ROpts put ROpts (record { idemode = m } opts) export getOutput : {auto o : Ref ROpts REPLOpts} -> Core OutputMode getOutput = do opts <- get ROpts pure (idemode opts) export setMainFile : {auto o : Ref ROpts REPLOpts} -> Maybe String -> Core () setMainFile src = do opts <- get ROpts put ROpts (record { mainfile = src, literateStyle = litStyle src } opts) where litStyle : Maybe String -> Maybe LiterateStyle litStyle Nothing = Nothing litStyle (Just fn) = isLitFile fn export resetProofState : {auto o : Ref ROpts REPLOpts} -> Core () resetProofState = do opts <- get ROpts put ROpts (record { psResult = Nothing, gdResult = Nothing } opts) export setSource : {auto o : Ref ROpts REPLOpts} -> String -> Core () setSource src = do opts <- get ROpts put ROpts (record { source = src } opts) export getSource : {auto o : Ref ROpts REPLOpts} -> Core String getSource = do opts <- get ROpts pure (source opts) export getSourceLine : {auto o : Ref ROpts REPLOpts} -> Int -> Core (Maybe String) getSourceLine l = do src <- getSource pure $ findLine (integerToNat (cast (l-1))) (lines src) where findLine : Nat -> List String -> Maybe String findLine Z (l :: ls) = Just l findLine (S k) (l :: ls) = findLine k ls findLine _ [] = Nothing export getLitStyle : {auto o : Ref ROpts REPLOpts} -> Core (Maybe LiterateStyle) getLitStyle = do opts <- get ROpts pure (literateStyle opts) export setCurrentElabSource : {auto o : Ref ROpts REPLOpts} -> String -> Core () setCurrentElabSource src = do opts <- get ROpts put ROpts (record { currentElabSource = src } opts) export getCurrentElabSource : {auto o : Ref ROpts REPLOpts} -> Core String getCurrentElabSource = do opts <- get ROpts pure (currentElabSource opts) addCodegen : {auto o : Ref ROpts REPLOpts} -> String -> Codegen -> Core () addCodegen s cg = do opts <- get ROpts put ROpts (record { extraCodegens $= ((s,cg)::) } opts) export getCodegen : {auto o : Ref ROpts REPLOpts} -> String -> Core (Maybe Codegen) getCodegen s = do opts <- get ROpts pure $ lookup s (extraCodegens opts) export getConsoleWidth : {auto o : Ref ROpts REPLOpts} -> Core (Maybe Nat) getConsoleWidth = do opts <- get ROpts pure $ opts.consoleWidth export setConsoleWidth : {auto o : Ref ROpts REPLOpts} -> Maybe Nat -> Core () setConsoleWidth n = do opts <- get ROpts put ROpts (record { consoleWidth = n } opts) export getColor : {auto o : Ref ROpts REPLOpts} -> Core Bool getColor = do opts <- get ROpts pure $ opts.color export setColor : {auto o : Ref ROpts REPLOpts} -> Bool -> Core () setColor b = do opts <- get ROpts put ROpts (record { color = b } opts)
(* Property from Case-Analysis for Rippling and Inductive Proof, Moa Johansson, Lucas Dixon and Alan Bundy, ITP 2010. This Isabelle theory is produced using the TIP tool offered at the following website: https://github.com/tip-org/tools This file was originally provided as part of TIP benchmark at the following website: https://github.com/tip-org/benchmarks Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly to make it compatible with Isabelle2017.*) theory TIP_prop_54 imports "../../Test_Base" begin datatype Nat = Z | S "Nat" fun t22 :: "Nat => Nat => Nat" where "t22 (Z) y = y" | "t22 (S z) y = S (t22 z y)" fun t2 :: "Nat => Nat => Nat" where "t2 (Z) y = Z" | "t2 (S z) (Z) = S z" | "t2 (S z) (S x2) = t2 z x2" theorem property0 : "((t2 (t22 m n) n) = m)" oops end
/* Copyright (c) 2014, Kai Klindworth All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef BLAS_WRAPPER_H #define BLAS_WRAPPER_H #include <cblas.h> namespace blas { inline void gemm(double* Y, const double* A, bool transposeA, int rowsA, int colsA, const double* B, bool transposeB, int rowsB, int colsB, double alpha = 1.0, double beta = 0.0) { cblas_dgemm(CblasRowMajor, transposeA ? CblasTrans : CblasNoTrans, transposeB ? CblasTrans : CblasNoTrans, transposeA ? colsA : rowsA, transposeB ? rowsB : colsB, transposeB ? colsB : rowsB, alpha, A, colsA, B, colsB, beta, Y, transposeB ? rowsB : colsB); } inline void gemm(float* Y, const float* A, bool transposeA, int rowsA, int colsA, const float* B, bool transposeB, int rowsB, int colsB, float alpha = 1.0f, float beta = 0.0f) { cblas_sgemm(CblasRowMajor, transposeA ? CblasTrans : CblasNoTrans, transposeB ? CblasTrans : CblasNoTrans, transposeA ? colsA : rowsA, transposeB ? rowsB : colsB, transposeB ? colsB : rowsB, alpha, A, colsA, B, colsB, beta, Y, transposeB ? rowsB : colsB); } inline void gemv(double* Y, const double* A, bool transposeA, int rowsA, int colsA, const double* x, double alpha = 1.0, double beta = 0.0) { cblas_dgemv(CblasRowMajor, transposeA ? CblasTrans : CblasNoTrans, rowsA, colsA, alpha, A, colsA, x, 1, beta, Y, 1); } inline void gemv(float* Y, const float* A, bool transposeA, int rowsA, int colsA, const float* x, float alpha = 1.0, float beta = 0.0) { cblas_sgemv(CblasRowMajor, transposeA ? CblasTrans : CblasNoTrans, rowsA, colsA, alpha, A, colsA, x, 1, beta, Y, 1); } inline void ger(double* Y, const double * A, int rowsA, const double* X, int rowsX, double alpha = 1.0) { cblas_dger(CblasRowMajor, rowsA, rowsX, alpha, A, 1, X, 1, Y, rowsX); } inline void ger(float* Y, const float * A, int rowsA, const float* X, int rowsX, float alpha = 1.0) { cblas_sger(CblasRowMajor, rowsA, rowsX, alpha, A, 1, X, 1, Y, rowsX); } inline double norm2(double* X, int n, int stride = 1) { return cblas_dnrm2(n, X, stride); } inline float norm2(float* X, int n, int stride = 1) { return cblas_snrm2(n, X, stride); } inline void scale(float alpha, float* X, int n, int stride = 1) { return cblas_sscal(n, alpha, X, stride); } inline void scale(double alpha, double* X, int n, int stride = 1) { return cblas_dscal(n, alpha, X, stride); } } #endif
(* This Isabelle theory is produced using the TIP tool offered at the following website: https://github.com/tip-org/tools This file was originally provided as part of TIP benchmark at the following website: https://github.com/tip-org/benchmarks Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly to make it compatible with Isabelle2017.*) theory TIP_sort_nat_SSortIsSort imports "../../Test_Base" begin datatype 'a list = nil2 | cons2 "'a" "'a list" datatype Nat = Z | S "Nat" fun le :: "Nat => Nat => bool" where "le (Z) y = True" | "le (S z) (Z) = False" | "le (S z) (S x2) = le z x2" fun ssortminimum1 :: "Nat => Nat list => Nat" where "ssortminimum1 x (nil2) = x" | "ssortminimum1 x (cons2 y1 ys1) = (if le y1 x then ssortminimum1 y1 ys1 else ssortminimum1 x ys1)" fun insert :: "Nat => Nat list => Nat list" where "insert x (nil2) = cons2 x (nil2)" | "insert x (cons2 z xs) = (if le x z then cons2 x (cons2 z xs) else cons2 z (insert x xs))" fun isort :: "Nat list => Nat list" where "isort (nil2) = nil2" | "isort (cons2 y xs) = insert y (isort xs)" fun deleteBy :: "('a => ('a => bool)) => 'a => 'a list => 'a list" where "deleteBy x y (nil2) = nil2" | "deleteBy x y (cons2 y2 ys) = (if (x y) y2 then ys else cons2 y2 (deleteBy x y ys))" (*fun did not finish the proof*) function ssort :: "Nat list => Nat list" where "ssort (nil2) = nil2" | "ssort (cons2 y ys) = (let m :: Nat = ssortminimum1 y ys in cons2 m (ssort (deleteBy (% (z :: Nat) => % (x2 :: Nat) => (z = x2)) m (cons2 y ys))))" by pat_completeness auto theorem property0 : "((ssort xs) = (isort xs))" oops end
(* -> Section 5.1 in paper -> Union Types + Null + Intersection Types -> Nominal types -> Parametric Polymorphism *) Require Import TLC.LibLN. Require Import Program.Equality. Require Import Coq.Lists.ListSet. From Coq Require Export Lists.List. Export ListNotations. Require Import syntax. (** definitions *) (* defns value *) Inductive value : exp -> Prop := (* defn value *) | val_int : forall i5, value (e_lit i5) | val_abs : forall e, lc_exp (e_abs e) -> value (e_abs e) | val_null : value e_null | val_tabs : forall T e, lc_exp (e_tabs T e) -> value (e_tabs T e) | val_new : forall P, value (e_new P). (* defns FindType *) Inductive findtype : exp -> typ -> Prop := (* defn findtype *) | findtype_int : forall i5, findtype (e_lit i5) t_int | findtype_arrow : forall (e:exp), lc_exp (e_abs e) -> findtype (e_abs e) (t_arrow t_top t_bot) | findtype_null : findtype e_null t_unit | findtype_tabs : forall T e, findtype (e_tabs T e) (t_all t_bot t_bot) | find_type_new : forall P, findtype (e_new P) (t_prim P). #[export] Hint Constructors value findtype : core. (****** Counting Free Variables ******) (** Computing free type variables in a type *) Fixpoint fv_tt (T : typ) {struct T} : vars := match T with | t_top => \{} | t_int => \{} | t_bot => \{} | t_arrow T1 T2 => (fv_tt T1) \u (fv_tt T2) | t_union T1 T2 => (fv_tt T1) \u (fv_tt T2) | t_and T1 T2 => (fv_tt T1) \u (fv_tt T2) | t_unit => \{} | t_bvar J => \{} | t_fvar X => \{X} | t_all T1 T2 => (fv_tt T1) \u (fv_tt T2) | t_prim i => \{} end. (** Computing free type variables in a term *) Fixpoint fv_te (e : exp) {struct e} : vars := match e with | e_bvar i => \{} | e_fvar x => \{} | e_lit i => \{} | e_abs e => fv_te e | e_app e1 e2 => (fv_te e1) \u (fv_te e2) | e_typeof e A e1 B e2 => (fv_te e) \u (fv_tt A) \u (fv_te e1) \u (fv_tt B) \u (fv_te e2) | e_null => \{} | e_tabs V e1 => (fv_tt V) \u (fv_te e1) | e_tapp e1 V => (fv_te e1) \u (fv_tt V) | e_new i => \{} end. (** Computing free term variables in a type *) Fixpoint fv_ee (e : exp) {struct e} : vars := match e with | e_bvar i => \{} | e_fvar x => \{x} | e_lit i => \{} | e_abs e => (fv_ee e) | e_app e1 e2 => (fv_ee e1) \u (fv_ee e2) | e_typeof e A e1 B e2 => (fv_ee e) \u (fv_ee e1) \u (fv_ee e2) | e_null => \{} | e_tabs V e1 => (fv_ee e1) | e_tapp e1 V => (fv_ee e1) | e_new i => \{} end. (***** Substitution Functions ******) (** Substitution for free type variables in types. *) Fixpoint subst_tt (Z : var) (U : typ) (T : typ) {struct T} : typ := match T with | t_top => t_top | t_int => t_int | t_bot => t_bot | t_arrow T1 T2 => t_arrow (subst_tt Z U T1) (subst_tt Z U T2) | t_union T1 T2 => t_union (subst_tt Z U T1) (subst_tt Z U T2) | t_and T1 T2 => t_and (subst_tt Z U T1) (subst_tt Z U T2) | t_unit => t_unit | t_bvar J => t_bvar J | t_fvar X => If (X = Z) then U else (t_fvar X) | t_all T1 T2 => t_all (subst_tt Z U T1) (subst_tt Z U T2) | t_prim i => t_prim i end. (** Substitution for free type variables in terms. *) Fixpoint subst_te (Z : var) (U : typ) (e : exp) {struct e} : exp := match e with | e_bvar i => e_bvar i | e_fvar x => e_fvar x | e_lit i => e_lit i | e_abs e => e_abs (subst_te Z U e) | e_app e1 e2 => e_app (subst_te Z U e1) (subst_te Z U e2) | e_typeof e A e1 B e2 => e_typeof (subst_te Z U e) (subst_tt Z U A) (subst_te Z U e1) (subst_tt Z U B) (subst_te Z U e2) | e_null => e_null | e_tabs V e1 => e_tabs (subst_tt Z U V) (subst_te Z U e1) | e_tapp e1 V => e_tapp (subst_te Z U e1) (subst_tt Z U V) | e_new i => e_new i end. (** Substitution for free term variables in terms. *) Fixpoint subst_ee (z : var) (u : exp) (e : exp) {struct e} : exp := match e with | e_bvar i => e_bvar i | e_fvar x => If (x = z) then u else e_fvar x | e_lit i => e_lit i | e_abs e => e_abs (subst_ee z u e) | e_app e1 e2 => e_app (subst_ee z u e1) (subst_ee z u e2) | e_typeof e A e1 B e2 => e_typeof (subst_ee z u e) A (subst_ee z u e1) B (subst_ee z u e2) | e_null => e_null | e_tabs V e1 => e_tabs V (subst_ee z u e1) | e_tapp e1 V => e_tapp (subst_ee z u e1) V | e_new i => e_new i end. (* defns Typing *) Reserved Notation "PG ; G |= e : A" (at level 80, e at next level, A at next level). Inductive typing (PG:envp) : env -> exp -> typ -> Prop := (* defn typing *) | typ_lit : forall (G:env) i5, okt PG G -> okenvp PG -> typing PG G (e_lit i5) t_int | typ_null : forall G, okt PG G -> okenvp PG -> typing PG G e_null t_unit | typ_var : forall (G:env) (x:var) (A:typ), okt PG G -> okenvp PG -> binds x (bind_typ A) G -> typing PG G (e_fvar x) A | typ_app : forall (G:env) (e1 e2:exp) (B A:typ), typing PG G e1 (t_arrow A B) -> typing PG G e2 A -> typing PG G (e_app e1 e2) B | typ_sub : forall (G:env) (e:exp) (A B:typ), typing PG G e B -> sub PG G B A -> typing PG G e A | typ_abs : forall (L:vars) (G:env) (e:exp) (A B:typ), okt PG G -> okenvp PG -> ( forall x , x \notin L -> typing PG (G & x ~: A) (open_ee e (e_fvar x)) B) -> typing PG G (e_abs e) (t_arrow A B) | typ_typeof : forall (L:vars) (G:env) (e:exp) (A:typ) (e1:exp) (B:typ) (e2:exp) (C:typ), typing PG G e (t_union A B) -> ( forall x ,x \notin L -> typing PG (G & x ~: A ) (open_ee e1 (e_fvar x) ) C) -> ( forall x ,x \notin L -> typing PG (G & x ~: B ) (open_ee e2 (e_fvar x) ) C) -> (PG ; G |= A *a B) -> typing PG G (e_typeof e A e1 B e2) C | typ_inter : forall G e A B, typing PG G e A -> typing PG G e B -> typing PG G e (t_and A B) | typ_tabs : forall L G e A B, okt PG G -> okenvp PG -> (forall X, X \notin L -> typing PG (G & X ~*: A) (e open_te_var X) (B open_tt_var X)) -> typing PG G (e_tabs A e) (t_all A B) | typ_tapp : forall G e A B C, typing PG G e (t_all B C) -> PG ; G |= A *a B -> groundtype A -> typing PG G (e_tapp e A) (open_tt C A) where "PG ; G |= e : A" := (typing PG G e A). (* defns Reduction *) Reserved Notation "PG ; G |= e --> e'" (at level 80, e at next level, e' at next level). Inductive step (PG:envp) (G:env) : exp -> exp -> Prop := (* defn step *) | step_appl : forall (e1 e2 e1':exp), lc_exp e2 -> step PG G e1 e1' -> step PG G (e_app e1 e2) (e_app e1' e2) | step_appr : forall (v e e':exp), value v -> step PG G e e' -> step PG G (e_app v e) (e_app v e') | step_beta : forall (e:exp) (v:exp), lc_exp (e_abs e) -> value v -> step PG G (e_app (e_abs e) v) (open_ee e v) | step_typeof : forall (e:exp) (A:typ) (e1:exp) (B:typ) (e2 e':exp), lc_exp (e_typeof e A e1 B e2) -> step PG G e e' -> step PG G (e_typeof e A e1 B e2) (e_typeof e' A e1 B e2) | step_typeofl : forall (v:exp) (A:typ) (e1:exp) (B:typ) (e2:exp) (C:typ), lc_exp (e_typeof v A e1 B e2) -> value v -> findtype v C -> sub PG G C A -> step PG G (e_typeof v A e1 B e2) (open_ee e1 v) | step_typeofr : forall (v:exp) (A:typ) (e1:exp) (B:typ) (e2:exp) (C:typ), lc_exp (e_typeof v A e1 B e2) -> value v -> findtype v C -> sub PG G C B -> step PG G (e_typeof v A e1 B e2) (open_ee e2 v ) | step_tapp : forall e e' A, type A -> step PG G e e' -> step PG G (e_tapp e A) (e_tapp e' A) | step_tabs : forall A e B, lc_exp (e_tabs A e) -> type B -> step PG G (e_tapp (e_tabs A e) B) (open_te e B) where "PG ; G |= e --> e'" := (step PG G e e') : env_scope. #[export] Hint Constructors typing step : core. (** Gathering free names already used in the proofs **) Ltac gather_vars := let A := gather_vars_with (fun x : vars => x) in let B := gather_vars_with (fun x : var => \{x}) in let C := gather_vars_with (fun x : exp => fv_ee x) in let D := gather_vars_with (fun x : exp => fv_te x) in let E := gather_vars_with (fun x : typ => fv_tt x) in let F := gather_vars_with (fun x : env => dom x) in constr:(A \u B \u C \u D \u E \u F). (** "pick_fresh x" tactic create a fresh variable with name x *) Ltac pick_fresh x := let L := gather_vars in (pick_fresh_gen L x). (** "apply_fresh T as x" is used to apply inductive rule which use an universal quantification over a cofinite set *) Tactic Notation "apply_fresh" constr(T) "as" ident(x) := apply_fresh_base T gather_vars x. Tactic Notation "apply_fresh" "*" constr(T) "as" ident(x) := apply_fresh T as x; autos*. (** These tactics help applying a lemma which conclusion mentions an environment (E & F) in the particular case when F is empty *) Ltac get_env := match goal with | |- sub _ ?E _ _ => E | |- typing _ ?E _ _ => E end. Tactic Notation "apply_empty_bis" tactic(get_env) constr(lemma) := let E := get_env in rewrite <- (concat_empty_r E); eapply lemma; try rewrite concat_empty_r. Tactic Notation "apply_empty" constr(F) := apply_empty_bis (get_env) F. Tactic Notation "apply_empty" "*" constr(F) := apply_empty F; autos*. (** Tactic to undo when Coq does too much simplification *) Definition subst_tb (Z : var) (P : typ) (b : bind) : bind := match b with | bind_disj T => bind_disj (subst_tt Z P T) | bind_typ T => bind_typ (subst_tt Z P T) end. Ltac unsimpl_map_bind := match goal with |- context [ ?B (subst_tt ?Z ?P ?U) ] => unsimpl ((subst_tb Z P) (B U)) end. Tactic Notation "unsimpl_map_bind" "*" := unsimpl_map_bind; autos*. (* ********************************************************************** *) (** * Properties of Substitutions *) (* ********************************************************************** *) (** ** Properties of type substitution in types *) Lemma open_tt_rec_type_aux : forall T j V i U, i <> j -> open_tt_rec j V T = open_tt_rec i U (open_tt_rec j V T) -> T = open_tt_rec i U T. Proof with congruence || eauto. induction T; intros j V i U Neq H; simpl in *; inversion H; f_equal... case_nat... case_nat... Qed. (** Opening a locally closed term is the identity. This lemma depends on the immediately preceding lemma. *) Lemma open_tt_rec_type : forall T U k, type T -> T = open_tt_rec k U T. Proof with auto. intros T U k Htyp. revert k. induction Htyp; intros k; simpl; f_equal... unfold open_tt in *. pick_fresh X. apply (open_tt_rec_type_aux T2 0 (t_fvar X))... Qed. (** Substitution for a fresh name is identity. *) Lemma subst_tt_fresh : forall Z U T, Z \notin fv_tt T -> subst_tt Z U T = T. Proof. induction T; simpl; intros; f_equal*. case_var*. Qed. (** Substitution commutes with opening under certain conditions. This lemma depends on the fact that opening a locally closed term is the identity. *) Lemma subst_tt_open_tt_rec : forall T1 T2 X P k, type P -> subst_tt X P (open_tt_rec k T2 T1) = open_tt_rec k (subst_tt X P T2) (subst_tt X P T1). Proof with auto. intros T1 T2 X P k WP. revert k. induction T1; intros k; simpl; f_equal... case_nat; subst... case_var; subst... apply open_tt_rec_type... Qed. (** Substitution distributes on the open operation. *) Lemma subst_tt_open_tt : forall T1 T2 X P, type P -> subst_tt X P (open_tt T1 T2) = open_tt (subst_tt X P T1) (subst_tt X P T2). Proof. unfold open_tt. intros. apply subst_tt_open_tt_rec; auto. Qed. (** Substitution and open_var for distinct names commute. *) Lemma subst_tt_open_tt_var : forall X Y U T, Y <> X -> type U -> (subst_tt X U T) open_tt_var Y = subst_tt X U (T open_tt_var Y). Proof. introv Neq Wu. rewrite* subst_tt_open_tt. simpl. case_var*. Qed. Lemma subst_tt_intro_rec : forall X T2 U k, X \notin fv_tt T2 -> open_tt_rec k U T2 = subst_tt X U (open_tt_rec k (t_fvar X) T2). Proof with congruence || auto. induction T2; intros U k Fr; simpl in *; f_equal... case_nat... simpl. case_var... case_var... Qed. (** Opening up a body t with a type u is the same as opening up the abstraction with a fresh name x and then substituting u for x. *) Lemma subst_tt_intro : forall X T2 U, X \notin fv_tt T2 -> type U -> open_tt T2 U = subst_tt X U (T2 open_tt_var X). Proof. introv Fr Wu. rewrite* subst_tt_open_tt. rewrite* subst_tt_fresh. simpl. case_var*. Qed. (* ********************************************************************** *) (** ** Properties of type substitution in terms *) Lemma open_te_rec_expr_aux : forall e j u i P , open_ee_rec j u e = open_te_rec i P (open_ee_rec j u e) -> e = open_te_rec i P e. Proof with congruence || eauto. induction e; intros j u i P H; simpl in *; inversion H; f_equal... Qed. Lemma open_te_rec_type_aux : forall e j Q i P, i <> j -> open_te_rec j Q e = open_te_rec i P (open_te_rec j Q e) -> e = open_te_rec i P e. Proof. induction e; intros j Q i P Neq Heq; simpl in *; inversion Heq; f_equal; eauto using open_tt_rec_type_aux. Qed. Lemma open_te_rec_expr : forall e U k, lc_exp e -> e = open_te_rec k U e. Proof. intros e U k WF. revert k. induction WF; intros k; simpl; f_equal; auto using open_tt_rec_type; try solve [ unfold open_ee in *; pick_fresh x; eapply open_te_rec_expr_aux with (j := 0) (u := e_fvar x); auto | unfold open_te in *; pick_fresh X; eapply open_te_rec_type_aux with (j := 0) (Q := t_fvar X); auto ]. Qed. (** Substitution for a fresh name is identity. *) Lemma subst_te_fresh : forall X U e, X \notin fv_te e -> subst_te X U e = e. Proof. induction e; simpl; intros; f_equal*; apply* subst_tt_fresh. Qed. Lemma subst_te_open_te_rec : forall e T X U k, type U -> subst_te X U (open_te_rec k T e) = open_te_rec k (subst_tt X U T) (subst_te X U e). Proof. intros e T X U k WU. revert k. induction e; intros k; simpl; f_equal; auto using subst_tt_open_tt_rec. Qed. (** Substitution distributes on the open operation. *) Lemma subst_te_open_te : forall e T X U, type U -> subst_te X U (open_te e T) = open_te (subst_te X U e) (subst_tt X U T). Proof. intros. unfold open_te. generalize 0. induction e; intros; simpls; f_equal*; apply* subst_tt_open_tt_rec. Qed. (** Substitution and open_var for distinct names commute. *) Lemma subst_te_open_te_var : forall X Y U e, Y <> X -> type U -> (subst_te X U e) open_te_var Y = subst_te X U (e open_te_var Y). Proof. introv Neq Wu. rewrite* subst_te_open_te. simpl. case_var*. Qed. Lemma subst_te_intro_rec : forall X e U k, X \notin fv_te e -> open_te_rec k U e = subst_te X U (open_te_rec k (t_fvar X) e). Proof. induction e; intros U k Fr; simpl in *; f_equal; auto using subst_tt_intro_rec. Qed. (** Opening up a body t with a type u is the same as opening up the abstraction with a fresh name x and then substituting u for x. *) Lemma subst_te_intro : forall X U e, X \notin fv_te e -> type U -> open_te e U = subst_te X U (e open_te_var X). Proof. introv Fr Wu. rewrite* subst_te_open_te. rewrite* subst_te_fresh. simpl. case_var*. Qed. (* ********************************************************************** *) (** ** Properties of term substitution in terms *) Lemma open_ee_rec_term_core : forall e j v u i, i <> j -> open_ee_rec j v e = open_ee_rec i u (open_ee_rec j v e) -> e = open_ee_rec i u e. Proof. induction e; introv Neq H; simpl in *; inversion H; f_equal*. case_nat*. case_nat*. Qed. Lemma open_ee_rec_type_aux : forall e j V u i, open_te_rec j V e = open_ee_rec i u (open_te_rec j V e) -> e = open_ee_rec i u e. Proof. induction e; intros j V u i H; simpl; inversion H; f_equal; eauto. Qed. Lemma open_ee_rec_term : forall u e, lc_exp e -> forall k, e = open_ee_rec k u e. Proof. induction 1; intros; simpl; f_equal*. unfolds open_ee_rec. pick_fresh x. apply* (@open_ee_rec_term_core e 0 (e_fvar x)). unfolds open_ee. pick_fresh x. apply* (@open_ee_rec_term_core e1 0 (e_fvar x)). unfolds open_ee. pick_fresh x. apply* (@open_ee_rec_term_core e2 0 (e_fvar x)). unfolds open_te. pick_fresh X. apply* (@open_ee_rec_type_aux e1 0 (t_fvar X)). Qed. (** Substitution for a fresh name is identity. *) Lemma subst_ee_fresh : forall x u e, x \notin fv_ee e -> subst_ee x u e = e. Proof. induction e; simpl; intros; f_equal*. case_var*. Qed. (** Substitution distributes on the open operation. *) Lemma subst_ee_open_ee : forall t1 t2 u x, lc_exp u -> subst_ee x u (open_ee t1 t2) = open_ee (subst_ee x u t1) (subst_ee x u t2). Proof. intros. unfold open_ee. generalize 0. induction t1; intros; simpls; f_equal*. case_nat*. case_var*. rewrite* <- open_ee_rec_term. Qed. (** Substitution and open_var for distinct names commute. *) Lemma subst_ee_open_ee_var : forall x y u e, y <> x -> lc_exp u -> (subst_ee x u e) open_ee_var y = subst_ee x u (e open_ee_var y). Proof. introv Neq Wu. rewrite* subst_ee_open_ee. simpl. case_var*. Qed. (** Opening up a body t with a type u is the same as opening up the abstraction with a fresh name x and then substituting u for x. *) Lemma subst_ee_intro : forall x u e, x \notin fv_ee e -> lc_exp u -> open_ee e u = subst_ee x u (e open_ee_var x). Proof. introv Fr Wu. rewrite* subst_ee_open_ee. rewrite* subst_ee_fresh. simpl. case_var*. Qed. (** Interactions between type substitutions in terms and opening with term variables in terms. *) Lemma subst_te_open_ee_var : forall Z P x e, (subst_te Z P e) open_ee_var x = subst_te Z P (e open_ee_var x). Proof. introv. unfold open_ee. generalize 0. induction e; intros; simpl; f_equal*. case_nat*. Qed. (** Interactions between term substitutions in terms and opening with type variables in terms. *) Lemma subst_ee_open_te_var : forall z u e X, lc_exp u -> (subst_ee z u e) open_te_var X = subst_ee z u (e open_te_var X). Proof. introv. unfold open_te. generalize 0. induction e; intros; simpl; f_equal*. case_var*. symmetry. apply* open_te_rec_expr. Qed. (** Substitutions preserve local closure. *) Lemma subst_tt_type : forall T Z P, type T -> type P -> type (subst_tt Z P T). Proof. induction 1; intros; simpl; auto. case_var*. apply_fresh* type_all as X. rewrite* subst_tt_open_tt_var. Qed. Lemma subst_te_term : forall e Z P, lc_exp e -> type P -> lc_exp (subst_te Z P e). Proof. puts: subst_tt_type. induction 1; intros; simpl; auto. apply_fresh* lc_e_abs as x. rewrite* subst_te_open_ee_var. apply_fresh* lc_e_typeof as x. rewrite* subst_te_open_ee_var. rewrite* subst_te_open_ee_var. apply_fresh* lc_e_tabs as X. rewrite* subst_te_open_te_var. Qed. Lemma subst_ee_term : forall e1 Z e2, lc_exp e1 -> lc_exp e2 -> lc_exp (subst_ee Z e2 e1). Proof. induction 1; intros; simpl; auto. case_var*. - apply_fresh* lc_e_abs as y. rewrite* subst_ee_open_ee_var. - apply_fresh* lc_e_typeof as y. rewrite* subst_ee_open_ee_var. rewrite* subst_ee_open_ee_var. - apply_fresh* lc_e_tabs as X. rewrite* subst_ee_open_te_var. Qed. #[export] Hint Resolve subst_ee_term subst_te_term subst_tt_type : core. (* ********************************************************************** *) (** * Relations between well-formed environment and types well-formed in environments *) Lemma ok_from_okt : forall PG E, okt PG E -> ok E. Proof. induction 1. auto. auto. auto. Qed. #[export] Hint Extern 1 (ok _) => apply (ok_from_okt _ _) : core. (** Through weakening *) Lemma wft_weaken : forall PG G T E F, wft PG (E & G) T -> ok (E & F & G) -> wft PG (E & F & G) T. Proof. intros. gen_eq : (E & G) as K. gen E F G. induction H; intros; subst; eauto. (* case: var *) apply (@wft_var PG U). apply* binds_weaken. (* case: all *) pick_fresh Y. apply wft_all with (L:=(((((L \u fv_tt T1) \u fv_tt T2) \u dom E0) \u dom G) \u dom F)); auto. intros. apply_ih_bind* H2. (* apply_fresh* wft_all as Y. apply_ih_bind* H1. *) Qed. Lemma wft_weaken_right : forall PG T E F, wft PG E T -> ok (E & F) -> wft PG (E & F) T. Proof. intros. assert (E & F & empty = E & F). rewrite~ concat_empty_r. rewrite <- H1 in *. assert (E = E & empty). rewrite~ concat_empty_r. rewrite H2 in H. apply~ wft_weaken. Qed. Lemma append_empty_right : forall (E : env), E = E & empty. Proof. intros. rewrite~ concat_empty_r. Qed. (** Extraction from a disjointness assumption in a well-formed environments *) Lemma wft_from_env_has_sub : forall PG x U E, okt PG E -> binds x (bind_disj U) E -> wft PG E U. Proof. unfold binds. introv OK. induction OK; introv B. - rewrite get_empty in B. inverts B. - rewrite get_push in B. case_var. forwards* : IHOK B. apply* wft_weaken_right. apply ok_from_okt in OK; auto. - rewrite get_push in B. case_var. inverts B. apply* wft_weaken_right. apply ok_from_okt in OK; auto. forwards* : IHOK B. apply* wft_weaken_right. apply ok_from_okt in OK; auto. Qed. (** Extraction from a typing assumption in a well-formed environments *) Lemma wft_from_env_has_typ : forall PG x U E, okt PG E -> binds x (bind_typ U) E -> wft PG E U. Proof. unfold binds. introv OK. induction OK; introv B. - rewrite get_empty in B. inverts B. - rewrite get_push in B. case_var. inverts B. apply* wft_weaken_right. apply ok_from_okt in OK; auto. forwards* : IHOK B. apply* wft_weaken_right. apply ok_from_okt in OK; auto. - rewrite get_push in B. case_var. apply* wft_weaken_right. apply ok_from_okt in OK; auto. Qed. (** Automation *) (* ********************************************************************** *) (** ** Properties of well-formedness of an environment *) (** If a type is well-formed in an environment then it is locally closed. *) Lemma type_from_wft : forall PG E T, wft PG E T -> type T. Proof. induction 1; eauto. Qed. (** Through narrowing *) Lemma wft_narrow : forall PG V F U T E X, wft PG (E & X ~*: V & F) T -> okt PG (E & X ~*: U & F) -> wft PG (E & X ~*: U & F) T. Proof. intros. gen_eq : (E & X ~*: V & F) as K. gen E F. induction H; intros; subst; eauto. binds_cases H. eapply wft_var. apply* binds_concat_left_ok. apply ok_from_okt in H0; auto. apply (@wft_var PG U). apply* binds_middle_eq. eapply wft_var. apply* binds_concat_right. pick_fresh Y. apply wft_all with (L:=(((((((L \u \{ X}) \u fv_tt V) \u fv_tt U) \u fv_tt T1) \u fv_tt T2) \u dom E0) \u dom F)); auto. intros. apply_ih_bind* H2. Qed. (** Through strengthening *) Lemma wft_strengthen : forall PG E F x U T, wft PG (E & x ~: U & F) T -> wft PG (E & F) T. Proof. intros. gen_eq : (E & x ~: U & F) as G. gen F. induction H; intros F EQ; subst; auto. apply* (@wft_var PG U0). binds_cases H; try discriminate; autos*. pick_fresh Y. apply wft_all with (L:=((((((L \u \{ x}) \u fv_tt U) \u fv_tt T1) \u fv_tt T2) \u dom E) \u dom F)); auto. intros. apply_ih_bind* H2. Qed. (** Through type substitution *) (** Inversion lemma *) Lemma okt_push_inv : forall PG E x T, okt PG (E & x ~: T) -> okt PG E /\ x # E /\ wft PG E T. Proof. introv O. inverts O. false* empty_push_inv. lets (?&M&?): (eq_push_inv H). inverts M. subst. autos. lets (?&M&?): (eq_push_inv H). inverts M. Qed. Lemma okt_push_inv_tt : forall PG E X T, okt PG (E & X ~*: T) -> okt PG E /\ X # E /\ wft PG E T /\ groundtype T. Proof. introv O. inverts O. false* empty_push_inv. lets (?&M&?): (eq_push_inv H). inverts M. lets (?&M&?): (eq_push_inv H). inverts M. subst. autos. Qed. #[export] Hint Resolve wft_weaken_right : core. #[export] Hint Immediate wft_from_env_has_sub wft_from_env_has_typ : core. #[export] Hint Resolve okt_push_inv okt_push_inv_tt : core. (** Through narrowing *) Lemma okt_narrow : forall PG V E F U X, okt PG (E & X ~*: V & F) -> wft PG E U -> groundtype U -> okt PG (E & X ~*: U & F). Proof. induction F using env_ind; intros. rewrite <- append_empty_right in *. apply okt_push_inv_tt in H. destructs H. apply* okt_disj. destruct v. rewrite concat_assoc in *. apply okt_push_inv_tt in H. destructs H. apply* okt_disj. apply* wft_narrow. rewrite concat_assoc in *. apply okt_push_inv in H. destructs H. apply* okt_typ. apply* wft_narrow. Qed. (** Through strengthening *) Lemma okt_strengthen : forall PG x T (E F : env), okt PG (E & x ~: T & F) -> okt PG (E & F). Proof. introv O. induction F using env_ind. rewrite concat_empty_r in *. apply okt_push_inv in O. destruct~ O. rewrite concat_assoc in *. destruct v. apply okt_push_inv_tt in O. destructs O. apply okt_disj; auto. apply wft_strengthen in H1; auto. apply okt_push_inv in O. destructs O. apply okt_typ; auto. apply wft_strengthen in H1; auto. Qed. Lemma okt_concat_inv : forall PG E F x V, okt PG (E & (x ~: V) & F) -> okt PG E /\ x # E /\ wft PG E V. Proof. intros PG E F. gen PG E. induction F using env_ind; introv; rew_env_concat; auto; introv ok. destruct v. apply okt_push_inv_tt in ok. destruct ok. forwards*: IHF H. apply okt_push_inv in ok. destruct ok. forwards*: IHF H. Qed. Lemma okt_concat_inv_tt : forall PG E F X V, okt PG (E & (X ~*: V) & F) -> okt PG E /\ X # E /\ X # F /\ wft PG E V /\ groundtype V. Proof. intros PG E F. gen PG E. induction F using env_ind; introv; rew_env_concat; auto; introv ok. apply okt_push_inv_tt in ok. split*. destruct v. apply okt_push_inv_tt in ok. destruct ok. forwards*: IHF H. apply okt_push_inv in ok. destruct ok. forwards*: IHF H. Qed. (** Automation *) #[export] Hint Immediate okt_strengthen : core. (* ********************************************************************** *) (** ** Regularity of relations *) (** The subtyping relation is restricted to well-formed objects. *) Lemma sub_regular : forall PG E S T, sub PG E S T -> okenvp PG /\ wft PG E S /\ wft PG E T /\ okt PG E. Proof. induction 1; autos*. (*all case*) split*. splits. - pick_fresh Y. apply wft_all with (L:=(((((L \u fv_tt S1) \u fv_tt S2) \u fv_tt T1) \u fv_tt T2) \u dom G)); auto. destructs~ IHsub. intros. destructs~ (H2 X). rewrite (append_empty_right (G & X ~*: S1)). eapply wft_narrow with (V:=T1). rewrite~ <- append_empty_right. rewrite~ <- append_empty_right. apply* okt_disj. - pick_fresh Y. apply wft_all with (L:=(((((L \u fv_tt S1) \u fv_tt S2) \u fv_tt T1) \u fv_tt T2) \u dom G)); auto. destructs~ IHsub. forwards* (_&_&_&ok): H2 Y. apply okt_push_inv_tt in ok. destructs~ ok. intros. destruct~ (H2 X). rewrite (append_empty_right (G & X ~*: T1)). destructs H5. rewrite~ concat_empty_r. - destructs IHsub; auto. Qed. Require Import TLC.LibEnv. Lemma notin_fv_tt_open : forall Y X T, X \notin fv_tt (T open_tt_var Y) -> X \notin fv_tt T. Proof. intros Y X T. unfold open_tt. generalize 0. induction T; simpl; intros k Fr; eauto. apply notin_union in Fr. destruct~ Fr. notin_simpl; eauto. apply notin_union in Fr. destruct~ Fr. notin_simpl; eauto. apply notin_union in Fr. destruct~ Fr. notin_simpl; eauto. apply notin_union in Fr. destruct~ Fr. notin_simpl; eauto. Qed. #[export] Hint Constructors groundtype : core. (**************************************************************) (** Substitution in a ground type returns ground type *) Lemma subst_groundtype : forall T, groundtype T -> forall P, type P -> forall Z, groundtype (subst_tt Z P T). Proof. induction 1; intros; simpl; eauto; try solve [inverts* H]. Qed. Lemma wft_subst_tb : forall PG F Q E Z P T, wft PG (E & Z ~*: Q & F) T -> wft PG E P -> ok (E & map (subst_tb Z P) F) -> wft PG (E & map (subst_tb Z P) F) (subst_tt Z P T). Proof. introv WT WP. gen_eq : (E & Z ~*: Q & F) as G. gen F. induction WT; intros F EQ Ok; subst; simpl subst_tt; auto. case_var*. binds_cases H. apply* wft_var. apply (@wft_var PG (subst_tt Z P U)). unsimpl_map_bind*. pick_fresh Y. apply wft_all with (L:=(((((((L \u \{ Z}) \u fv_tt Q) \u fv_tt P) \u fv_tt T1) \u fv_tt T2) \u dom E) \u dom F)); intros; auto. forwards*: type_from_wft WP. forwards*: subst_groundtype T1 P Z. unsimpl ((subst_tb Z P) (bind_disj T1)). puts : type_from_wft. rewrite* subst_tt_open_tt_var. apply_ih_map_bind* H1. Qed. (** Through type reduction *) Lemma wft_open : forall PG E U T1 T2, ok E -> wft PG E (t_all T1 T2) -> wft PG E U -> wft PG E (open_tt T2 U). Proof. introv Ok WA WU. inversions WA. pick_fresh X. puts : type_from_wft. rewrite* (@subst_tt_intro X). forwards* K: (@wft_subst_tb PG empty T1 E X U (T2 open_tt_var X)). forwards* : H4 X. rewrite~ concat_empty_r. rewrite map_empty. rewrite~ concat_empty_r. rewrite map_empty in K. rewrite~ concat_empty_r in K. Qed. Lemma typing_regular : forall PG E e T, typing PG E e T -> okenvp PG /\ okt PG E /\ lc_exp e /\ wft PG E T. Proof. induction 1; try splits*. - (*case arrow*) destructs IHtyping1. inverts* H4. - (*case subsumption*) apply sub_regular in H0. destructs~ H0. (* - pick_fresh y. specializes H0 y. destructs~ H0. apply okt_push_inv in H0. destruct H0. auto. *) - (*case abs*) apply lc_e_abs with (L:=L). intros. specializes H2 x. destructs~ H2. - (*case abs*) pick_fresh x. forwards* : H2 x. destructs H3. apply okt_push_inv in H4. destructs H4. rewrite (append_empty_right ((G & x ~: A))) in H6. apply wft_strengthen in H6. rewrite~ <- append_empty_right in H6. - (*case typeof*) apply lc_e_typeof with (L:=L); intros. destructs~ IHtyping. destructs~ IHtyping. inverts H8. apply type_from_wft with (PG:=PG) (E:=G); auto. destructs~ IHtyping. inverts H8. apply type_from_wft with (PG:=PG) (E:=G); auto. forwards* (?&?&?): H1 x. forwards* (?&?): H3 x. - (*case tabs*) pick_fresh x. forwards*(?&?&?&?): H1 x. rewrite (@append_empty_right (G & x ~: A)) in H8. apply wft_strengthen in H8. rewrite~ <- append_empty_right in H8. (* - pick_fresh X. specializes H0 X. destructs~ H0. apply okt_push_inv_tt in H0. destruct H0. auto. *) - apply_fresh lc_e_tabs as X. pick_fresh X. forwards* (?&?&?&?): H2 X. apply okt_push_inv_tt in H4. destructs H4. apply type_from_wft in H8; auto. forwards* : H2 X. - pick_fresh Y. apply wft_all with (L:=(((((L \u fv_ee e) \u fv_te e) \u fv_tt A) \u fv_tt B) \u dom G)); auto. forwards*(?&?&?&?): H2 Y. apply okt_push_inv_tt in H4. destructs~ H4. forwards*(_&okt&_): H2 Y. apply okt_push_inv_tt in okt. destructs~ okt. intros. forwards*(?&?&?&?): H2 X. - apply lc_e_tapp. destructs~ IHtyping. apply disj_regular in H0. destructs H0. apply type_from_wft in H3; auto. - destructs~ IHtyping. forwards* (okp&_&WFA&_): disj_regular H0. apply ok_from_okt in H3. forwards*: wft_open H3 H5 WFA. Qed. (** The value relation is restricted to well-formed objects. *) Lemma value_regular : forall t, value t -> lc_exp t. Proof. induction 1; autos*. Qed. #[export] Hint Immediate value_regular : core. (** The reduction relation is restricted to well-formed objects. *) Lemma step_regular : forall PG E t t', step PG E t t' -> lc_exp t /\ lc_exp t'. Proof. induction 1; split*. - inverts H. pick_fresh y. rewrite* (@subst_ee_intro y). - inverts H. destructs IHstep. apply_fresh* lc_e_typeof as y. - inverts H. pick_fresh y. rewrite* (@subst_ee_intro y). - inverts H. pick_fresh y. rewrite* (@subst_ee_intro y). - inverts H. pick_fresh Y. rewrite* (@subst_te_intro Y). Qed. (** Automation *) #[export] Hint Extern 1 (okt ?PG ?E) => match goal with | H: sub _ _ _ _ |- _ => apply (proj31 (sub_regular H)) | H: typing _ _ _ _ |- _ => apply (proj31 (typing_regular H)) end : core. #[export] Hint Extern 1 (wft ?PG ?E ?T) => match goal with | H: typing PG E _ T |- _ => apply (proj33 (typing_regular H)) | H: sub PG E T _ |- _ => apply (proj32 (sub_regular H)) | H: sub PG E _ T |- _ => apply (proj33 (sub_regular H)) end : core. #[export] Hint Extern 1 (type ?T) => let go PG E := apply (@type_from_wft PG E); auto in match goal with | H: typing _ ?E _ T |- _ => go E | H: sub _ ?E T _ |- _ => go E | H: sub _ ?E _ T |- _ => go E end : core. #[export] Hint Extern 1 (lc_exp ?e) => match goal with | H: typing _ _ ?e _ |- _ => apply (proj32 (typing_regular H)) | H: step _ _ ?e _ |- _ => apply (proj1 (step_regular H)) | H: step _ _ _ ?e |- _ => apply (proj2 (step_regular H)) end : core. (**********************************) (***** Subtyping Properties *****) (**********************************) (*********** Subtyping Reflexivity **********) Lemma sub_refl : forall (PG:envp) (G : syntax.env) (A:typ), okt PG G -> okenvp PG -> wft PG G A -> sub PG G A A. Proof. introv OK OKP WF. induction WF; eauto. apply* s_ora. apply* s_anda. pick_fresh Y. apply s_all with (L:=(((L \u fv_tt T1) \u fv_tt T2) \u dom E)); auto. Defined. #[export] Hint Resolve sub_refl : core. #[export] Hint Resolve wft_narrow : core. Lemma sub_narrowing_aux : forall PG Q F E Z P S T, sub PG (E & Z ~*: P & F) S T -> sub PG E P Q -> okt PG (E & Z ~*: Q & F) -> sub PG (E & Z ~*: Q & F) S T. Proof. introv SsubT PsubQ Ok. gen_eq : (E & Z ~*: P & F) as G. gen F P Q. forwards*: sub_regular SsubT. destructs H. induction SsubT; introv SsubQ EQ Ok; subst; try (forwards*: sub_regular SsubQ). - (*case arrow*) forwards*: sub_regular SsubT1. forwards*: sub_regular SsubT2. - (*case A1 | A2 <: A*) forwards*: sub_regular SsubT1. forwards*: sub_regular SsubT2. - (*case A <: A1*) forwards*: sub_regular SsubT. - (*case A <: A2*) forwards*: sub_regular SsubT. - (*case A <: A1 & A2*) forwards*: sub_regular SsubT1. forwards*: sub_regular SsubT2. - (*case A1 <: A*) forwards*: sub_regular SsubT. - (*case A2 <: A*) forwards*: sub_regular SsubT. - (*case All*) apply s_all with (L:=L). forwards*: sub_regular SsubT. inverts* H0. intros. forwards*: H4 X. apply sub_regular in H8. destructs H8. forwards*: H5 X (F & X ~*: T1) P Q. rewrite~ concat_assoc. apply okt_push_inv_tt in H11. destructs H11. apply* okt_disj. rewrite~ concat_assoc. rewrite~ concat_assoc in H12. Qed. (*********************************************** Supertypes properties for subtyping transitivity ************************************************) Lemma getsubtypes_inversion_temp12 : forall (PG : envp), forall (n1 i : nat) (A B:typ), set_In n1 (get_all_subtypes ((i , A) :: PG) B) -> ((n1 = i) /\ (issupertype ((i, A) :: PG) (t_prim i) B = true) ) \/ set_In n1 (get_all_subtypes PG B). Proof. destruct PG; intros. - simpl in H. destruct (eq_dec B A). destruct (eq_dec_nat i i); simpl in H. destruct H. left. split. auto. subst. simpl. destruct (eq_dec A A). destruct (eq_dec_nat n1 n1); simpl. auto. contradiction. contradiction. inverts H. contradiction. destruct (eq_dec_nat i i); simpl in H. inverts H. inverts H. - destruct p as [j C]. simpl. simpl in H. destruct (eq_dec B C). destruct (eq_dec B A). destruct (eq_dec_nat i i). simpl in H. destruct H; auto. contradiction. destruct (eq_dec_nat j j). destruct (eq_dec_nat i j). simpl in H. simpl. destruct (eq_dec A (t_prim j)). destruct (eq_dec_nat i i); simpl in *. destruct H; auto. contradiction. destruct (eq_dec_nat i i); simpl in *. subst. destruct (issupertype PG A C). simpl in H. destruct H; auto. simpl in H. destruct H; auto. contradiction. destruct ((eq_dec_nat i i)); simpl in H. destruct (eq_dec A (t_prim j)); simpl in *. destruct H; auto. subst. destruct (issupertype PG A C); simpl in *. destruct H; auto. destruct H; auto. contradiction. contradiction. destruct (eq_dec B A). destruct (eq_dec_nat i i); simpl in *. destruct ((eq_dec_nat j j)); simpl in *. destruct H; auto. contradiction. contradiction. destruct (eq_dec_nat i i); simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec A (t_prim j)); simpl in *. destruct (issupertype PG C B); simpl in *. destruct H; auto. auto. destruct (issupertype PG A B); simpl in *. destruct H; auto. destruct (issupertype PG C B); simpl in *. destruct H; auto. auto. contradiction. contradiction. Qed. Lemma nats_to_types_iff : forall i l, set_In i l <-> set_In (t_prim i) (nats_to_types l). Proof. split. - gen i. induction l; intros. inverts H. simpl. simpl in H. destruct H. auto. auto. - gen i. induction l; intros. inverts H. simpl in H. simpl. destruct H. inverts H. auto. forwards*: IHl H. Qed. Lemma subpertypes_inversion : forall PG, forall i n, issupertype PG (t_prim i) (t_prim n) = true -> set_In i (get_all_subtypes PG (t_prim n)). Proof. induction PG; introv EQ. - inverts EQ. - destruct a as [j A]. destruct A; simpl in *. + (*case top*) destruct (eq_dec_nat i j); simpl in *. destruct (eq_dec_nat j j); simpl. destruct (issupertype PG t_top (t_prim n)); simpl in *. auto. inverts EQ. contradiction. destruct (eq_dec_nat j j); simpl. destruct (issupertype PG t_top (t_prim n)); simpl. forwards*: IHPG EQ. forwards*: IHPG EQ. contradiction. + (*case int*) destruct (eq_dec_nat i j); simpl in *. destruct (eq_dec_nat j j); simpl. destruct (issupertype PG t_int (t_prim n)); simpl in *. auto. inverts EQ. contradiction. destruct (eq_dec_nat j j); simpl. destruct (issupertype PG t_int (t_prim n)); simpl. forwards*: IHPG EQ. forwards*: IHPG EQ. contradiction. + (*case bot*) destruct (eq_dec_nat i j); simpl in *. destruct (eq_dec_nat j j); simpl. destruct (issupertype PG t_bot (t_prim n)); simpl in *. auto. inverts EQ. contradiction. destruct (eq_dec_nat j j); simpl. destruct (issupertype PG t_bot (t_prim n)); simpl. forwards*: IHPG EQ. forwards*: IHPG EQ. contradiction. + (*case arrow*) destruct (eq_dec_nat i j); simpl in *. destruct (eq_dec_nat j j); simpl. destruct (issupertype PG (t_arrow A1 A2) (t_prim n)); simpl in *. auto. inverts EQ. contradiction. destruct (eq_dec_nat j j); simpl. destruct (issupertype PG (t_arrow A1 A2) (t_prim n)); simpl. forwards*: IHPG EQ. forwards*: IHPG EQ. contradiction. + (*case union*) destruct (eq_dec_nat i j); simpl in *. destruct (eq_dec_nat j j); simpl. destruct (issupertype PG (t_union A1 A2) (t_prim n)); simpl in *. auto. inverts EQ. contradiction. destruct (eq_dec_nat j j); simpl. destruct (issupertype PG (t_union A1 A2) (t_prim n)); simpl. forwards*: IHPG EQ. forwards*: IHPG EQ. contradiction. + (*case intersection*) destruct (eq_dec_nat i j); simpl in *. destruct (eq_dec_nat j j); simpl. destruct (issupertype PG (t_and A1 A2) (t_prim n)); simpl in *. auto. inverts EQ. contradiction. destruct (eq_dec_nat j j); simpl. destruct (issupertype PG (t_and A1 A2) (t_prim n)); simpl. forwards*: IHPG EQ. forwards*: IHPG EQ. contradiction. + (*case unit*) destruct (eq_dec_nat i j); simpl in *. destruct (eq_dec_nat j j); simpl. destruct (issupertype PG t_unit (t_prim n)); simpl in *. auto. inverts EQ. contradiction. destruct (eq_dec_nat j j); simpl. destruct (issupertype PG t_unit (t_prim n)); simpl. forwards*: IHPG EQ. forwards*: IHPG EQ. contradiction. + (*case bvar*) destruct (eq_dec_nat i j); simpl in *. destruct (eq_dec_nat j j); simpl. destruct (issupertype PG (t_bvar n0) (t_prim n)); simpl in *. auto. inverts EQ. contradiction. destruct (eq_dec_nat j j); simpl. destruct (issupertype PG (t_bvar n0) (t_prim n)); simpl. forwards*: IHPG EQ. forwards*: IHPG EQ. contradiction. + (*case fvar*) destruct (eq_dec_nat i j); simpl in *. destruct (eq_dec_nat j j); simpl. destruct (issupertype PG (t_fvar v) (t_prim n)); simpl in *. auto. inverts EQ. contradiction. destruct (eq_dec_nat j j); simpl. destruct (issupertype PG (t_fvar v) (t_prim n)); simpl. forwards*: IHPG EQ. forwards*: IHPG EQ. contradiction. + (*case all*) destruct (eq_dec_nat i j); simpl in *. destruct (eq_dec_nat j j); simpl. destruct (issupertype PG (t_all A1 A2) (t_prim n)); simpl in *. auto. inverts EQ. contradiction. destruct (eq_dec_nat j j); simpl. destruct (issupertype PG (t_all A1 A2) (t_prim n)); simpl. forwards*: IHPG EQ. forwards*: IHPG EQ. contradiction. + (* case P *) destruct (eq_dec_nat n n0); simpl in *. destruct (eq_dec_nat i j); simpl in *. destruct (eq_dec_nat j j); simpl. auto. contradiction. destruct (eq_dec_nat j j); simpl. forwards*: IHPG EQ. contradiction. destruct (eq_dec_nat i j); simpl in *. destruct (eq_dec_nat j j); simpl. destruct (issupertype PG (t_prim n0) (t_prim n)); simpl. auto. inverts EQ. contradiction. destruct (eq_dec_nat j j); simpl. destruct (issupertype PG (t_prim n0) (t_prim n)); simpl. forwards*: IHPG EQ. forwards*: IHPG EQ. contradiction. Defined. Lemma issupertype_inverse : forall PG i A n, issupertype ((i, A) :: PG) (t_prim i) (t_prim n) = true -> A = (t_prim n) \/ issupertype PG A (t_prim n) = true. Proof. destruct PG; intros. - destruct A; simpl in *; try solve [destruct (eq_dec_nat i i); simpl in *; inverts H]. destruct (eq_dec_nat n n0); simpl in *. destruct (eq_dec_nat i i); simpl in *. auto. contradiction. destruct (eq_dec_nat i i); simpl in *. inverts H. contradiction. - destruct p as [j C]. destruct A; (*all cases except P*) destruct C; simpl in *; try solve [ destruct (eq_dec_nat i j); simpl in *; destruct (eq_dec_nat i i); simpl in *; auto; contradiction; destruct (eq_dec_nat i i); simpl in *; auto; contradiction]. + (*case A = top, C = P*) destruct (eq_dec_nat i j); simpl in *. destruct (eq_dec_nat n0 j); simpl in *. destruct (eq_dec_nat n n0); simpl in *. subst. auto. destruct (eq_dec_nat i i); simpl in *. subst. auto. contradiction. destruct (eq_dec_nat n n0); simpl in *. subst. auto. destruct (eq_dec_nat i i); simpl in *. auto. contradiction. destruct (eq_dec_nat n0 j); simpl in *. destruct (eq_dec_nat n n0); simpl in *. subst. auto. destruct (eq_dec_nat i i); simpl in *. subst. auto. contradiction. destruct (eq_dec_nat n n0); simpl in *. subst. auto. destruct (eq_dec_nat i i); simpl in *. auto. contradiction. + (*case A = int, C = P*) destruct (eq_dec_nat i j); simpl in *. destruct (eq_dec_nat n0 j); simpl in *. destruct (eq_dec_nat n n0); simpl in *. subst. auto. destruct (eq_dec_nat i i); simpl in *. subst. auto. contradiction. destruct (eq_dec_nat n n0); simpl in *. subst. auto. destruct (eq_dec_nat i i); simpl in *. auto. contradiction. destruct (eq_dec_nat n0 j); simpl in *. destruct (eq_dec_nat n n0); simpl in *. subst. auto. destruct (eq_dec_nat i i); simpl in *. subst. auto. contradiction. destruct (eq_dec_nat n n0); simpl in *. subst. auto. destruct (eq_dec_nat i i); simpl in *. auto. contradiction. + (*case A = bot, C = P*) destruct (eq_dec_nat i j); simpl in *. destruct (eq_dec_nat n0 j); simpl in *. destruct (eq_dec_nat n n0); simpl in *. subst. auto. destruct (eq_dec_nat i i); simpl in *. subst. auto. contradiction. destruct (eq_dec_nat n n0); simpl in *. subst. auto. destruct (eq_dec_nat i i); simpl in *. auto. contradiction. destruct (eq_dec_nat n0 j); simpl in *. destruct (eq_dec_nat n n0); simpl in *. subst. auto. destruct (eq_dec_nat i i); simpl in *. subst. auto. contradiction. destruct (eq_dec_nat n n0); simpl in *. subst. auto. destruct (eq_dec_nat i i); simpl in *. auto. contradiction. + (*case A = arrow, C = P*) destruct (eq_dec_nat i j); simpl in *. destruct (eq_dec_nat n0 j); simpl in *. destruct (eq_dec_nat n n0); simpl in *. subst. auto. destruct (eq_dec_nat i i); simpl in *. subst. auto. contradiction. destruct (eq_dec_nat n n0); simpl in *. subst. auto. destruct (eq_dec_nat i i); simpl in *. auto. contradiction. destruct (eq_dec_nat n0 j); simpl in *. destruct (eq_dec_nat n n0); simpl in *. subst. auto. destruct (eq_dec_nat i i); simpl in *. subst. auto. contradiction. destruct (eq_dec_nat n n0); simpl in *. subst. auto. destruct (eq_dec_nat i i); simpl in *. auto. contradiction. + (*case A = union, C = P*) destruct (eq_dec_nat i j); simpl in *. destruct (eq_dec_nat n0 j); simpl in *. destruct (eq_dec_nat n n0); simpl in *. subst. auto. destruct (eq_dec_nat i i); simpl in *. subst. auto. contradiction. destruct (eq_dec_nat n n0); simpl in *. subst. auto. destruct (eq_dec_nat i i); simpl in *. auto. contradiction. destruct (eq_dec_nat n0 j); simpl in *. destruct (eq_dec_nat n n0); simpl in *. subst. auto. destruct (eq_dec_nat i i); simpl in *. subst. auto. contradiction. destruct (eq_dec_nat n n0); simpl in *. subst. auto. destruct (eq_dec_nat i i); simpl in *. auto. contradiction. + (*case A = intersection, C = P*) destruct (eq_dec_nat i j); simpl in *. destruct (eq_dec_nat n0 j); simpl in *. destruct (eq_dec_nat n n0); simpl in *. subst. auto. destruct (eq_dec_nat i i); simpl in *. subst. auto. contradiction. destruct (eq_dec_nat n n0); simpl in *. subst. auto. destruct (eq_dec_nat i i); simpl in *. auto. contradiction. destruct (eq_dec_nat n0 j); simpl in *. destruct (eq_dec_nat n n0); simpl in *. subst. auto. destruct (eq_dec_nat i i); simpl in *. subst. auto. contradiction. destruct (eq_dec_nat n n0); simpl in *. subst. auto. destruct (eq_dec_nat i i); simpl in *. auto. contradiction. + (*case A = unit, C = P*) destruct (eq_dec_nat i j); simpl in *. destruct (eq_dec_nat n0 j); simpl in *. destruct (eq_dec_nat n n0); simpl in *. subst. auto. destruct (eq_dec_nat i i); simpl in *. subst. auto. contradiction. destruct (eq_dec_nat n n0); simpl in *. subst. auto. destruct (eq_dec_nat i i); simpl in *. auto. contradiction. destruct (eq_dec_nat n0 j); simpl in *. destruct (eq_dec_nat n n0); simpl in *. subst. auto. destruct (eq_dec_nat i i); simpl in *. subst. auto. contradiction. destruct (eq_dec_nat n n0); simpl in *. subst. auto. destruct (eq_dec_nat i i); simpl in *. auto. contradiction. + (*case A = (t_bvar n1), C = P*) destruct (eq_dec_nat i j); simpl in *. destruct (eq_dec_nat n0 j); simpl in *. destruct (eq_dec_nat n n0); simpl in *. subst. auto. destruct (eq_dec_nat i i); simpl in *. subst. auto. contradiction. destruct (eq_dec_nat n n0); simpl in *. subst. auto. destruct (eq_dec_nat i i); simpl in *. auto. contradiction. destruct (eq_dec_nat n0 j); simpl in *. destruct (eq_dec_nat n n0); simpl in *. subst. auto. destruct (eq_dec_nat i i); simpl in *. subst. auto. contradiction. destruct (eq_dec_nat n n0); simpl in *. subst. auto. destruct (eq_dec_nat i i); simpl in *. auto. contradiction. + (*case A = (t_fvar v), C = P*) destruct (eq_dec_nat i j); simpl in *. destruct (eq_dec_nat n0 j); simpl in *. destruct (eq_dec_nat n n0); simpl in *. subst. auto. destruct (eq_dec_nat i i); simpl in *. subst. auto. contradiction. destruct (eq_dec_nat n n0); simpl in *. subst. auto. destruct (eq_dec_nat i i); simpl in *. auto. contradiction. destruct (eq_dec_nat n0 j); simpl in *. destruct (eq_dec_nat n n0); simpl in *. subst. auto. destruct (eq_dec_nat i i); simpl in *. subst. auto. contradiction. destruct (eq_dec_nat n n0); simpl in *. subst. auto. destruct (eq_dec_nat i i); simpl in *. auto. contradiction. + (*case A = (t_all C1 C2), C = P*) destruct (eq_dec_nat i j); simpl in *. destruct (eq_dec_nat n0 j); simpl in *. destruct (eq_dec_nat n n0); simpl in *. subst. auto. destruct (eq_dec_nat i i); simpl in *. subst. auto. contradiction. destruct (eq_dec_nat n n0); simpl in *. subst. auto. destruct (eq_dec_nat i i); simpl in *. auto. contradiction. destruct (eq_dec_nat n0 j); simpl in *. destruct (eq_dec_nat n n0); simpl in *. subst. auto. destruct (eq_dec_nat i i); simpl in *. subst. auto. contradiction. destruct (eq_dec_nat n n0); simpl in *. subst. auto. destruct (eq_dec_nat i i); simpl in *. auto. contradiction. + (*case A = P, C = P*) destruct (eq_dec_nat n n1); simpl in *. destruct (eq_dec_nat i j); simpl in *. destruct (eq_dec_nat n0 j); simpl in *. destruct (eq_dec_nat n n0); simpl in *. subst. auto. auto. destruct (eq_dec_nat n n0); simpl in *. subst. auto. destruct (eq_dec_nat i i); simpl in *. auto. contradiction. destruct (eq_dec_nat n0 j); simpl in *. destruct (eq_dec_nat n n0); simpl in *. auto. auto. destruct (eq_dec_nat n n0); simpl in *. subst. auto. destruct (eq_dec_nat i i); simpl in *. auto. contradiction. destruct (eq_dec_nat i j); simpl in *. destruct (eq_dec_nat n0 j); simpl in *. destruct (eq_dec_nat n n0); simpl in *. subst. auto. auto. destruct (eq_dec_nat n n0); simpl in *. subst. auto. destruct (eq_dec_nat i i); simpl in *. auto. contradiction. destruct (eq_dec_nat n0 j); simpl in *. destruct (eq_dec_nat n n0); simpl in *. auto. auto. destruct (eq_dec_nat n n0); simpl in *. subst. auto. destruct (eq_dec_nat i i); simpl in *. auto. contradiction. destruct (eq_dec_nat n0 j); simpl in *. destruct (eq_dec_nat n n0); simpl in *. subst. auto. auto. destruct (eq_dec_nat n n0); simpl in *. subst. auto. destruct (eq_dec_nat i i); simpl in *. auto. contradiction. destruct (eq_dec_nat n0 j); simpl in *. destruct (eq_dec_nat n n0); simpl in *. auto. auto. destruct (eq_dec_nat n n0); simpl in *. subst. auto. destruct (eq_dec_nat i i); simpl in *. auto. contradiction. Defined. Lemma issupertype_top_p : forall PG n, issupertype PG (t_top) (t_prim n) = false. Proof. induction PG; intros. - simpl. auto. - destruct a as [i C]. simpl. destruct (eq_dec t_top (t_prim i)). inverts e. auto. Defined. Lemma issupertype_int_p : forall PG n, issupertype PG (t_int) (t_prim n) = false. Proof. induction PG; intros. - simpl. auto. - destruct a as [i C]. simpl. destruct (eq_dec t_int (t_prim i)). inverts e. apply IHPG. Defined. Lemma issupertype_bot_p : forall PG n, issupertype PG (t_bot) (t_prim n) = false. Proof. induction PG; intros. - simpl. auto. - destruct a as [i C]. simpl. destruct (eq_dec t_bot (t_prim i)). inverts e. apply IHPG. Defined. Lemma issupertype_unit_p : forall PG n, issupertype PG (t_unit) (t_prim n) = false. Proof. induction PG; intros. - simpl. auto. - destruct a as [i C]. simpl. destruct (eq_dec t_unit (t_prim i)). inverts e. apply IHPG. Defined. Lemma issupertype_arrow_p : forall PG A B n, issupertype PG (t_arrow A B) (t_prim n) = false. Proof. induction PG; intros. - simpl. auto. - destruct a as [i C]. simpl. destruct (eq_dec (t_arrow A B) (t_prim i)). inverts e. apply IHPG. Defined. Lemma issupertype_union_p : forall PG A B n, issupertype PG (t_union A B) (t_prim n) = false. Proof. induction PG; intros. - simpl. auto. - destruct a as [i C]. simpl. destruct (eq_dec (t_union A B) (t_prim i)). inverts e. apply IHPG. Defined. Lemma issupertype_inter_p : forall PG A B n, issupertype PG (t_and A B) (t_prim n) = false. Proof. induction PG; intros. - simpl. auto. - destruct a as [i C]. simpl. destruct (eq_dec (t_and A B) (t_prim i)). inverts e. apply IHPG. Defined. Lemma issupertype_bvar_p : forall PG j n, issupertype PG (t_bvar j) (t_prim n) = false. Proof. induction PG; intros. - simpl. auto. - destruct a as [i C]. simpl. destruct (eq_dec (t_bvar j) (t_prim i)). inverts e. apply IHPG. Defined. Lemma issupertype_fvar_p : forall PG v n, issupertype PG (t_fvar v) (t_prim n) = false. Proof. induction PG; intros. - simpl. auto. - destruct a as [i C]. simpl. destruct (eq_dec (t_fvar v) (t_prim i)). inverts e. apply IHPG. Defined. Lemma issupertype_all_p : forall PG A B n, issupertype PG (t_all A B) (t_prim n) = false. Proof. induction PG; intros. - simpl. auto. - destruct a as [i C]. simpl. destruct (eq_dec (t_all A B) (t_prim i)). inverts e. apply IHPG. Defined. Lemma issupertype_weakening : forall PG n1 n2, issupertype PG (t_prim n1) (t_prim n2) = true -> forall i A, ~ set_In i (domain_envp PG) -> issupertype ((i, A) :: PG) (t_prim n1) (t_prim n2) = true. Proof. introv EQ NOTIN. destruct A; try (simpl; destruct (eq_dec_nat n1 i); subst; simpl; auto); try solve [apply subpertypes_inversion in EQ; apply allsubtypes_in_to_domain_nat in EQ; contradiction]. Qed. Lemma get_all_subtypes_issupertype : forall PG, okenvp PG -> forall n1 n2, set_In n1 (get_all_subtypes PG (t_prim n2)) -> issupertype PG (t_prim n1) (t_prim n2) = true. Proof. introv OK. induction OK; intros. - simpl in H. inverts H. - destruct A. + simpl in *. destruct (eq_dec_nat i i); simpl in *. rewrite issupertype_top_p in H1. destruct (eq_dec_nat n1 i); simpl. subst. apply allsubtypes_in_to_domain_nat in H1. contradiction. apply IHOK in H1. auto. contradiction. + simpl in *. destruct (eq_dec_nat i i); simpl in *. rewrite issupertype_int_p in H1. destruct (eq_dec_nat n1 i); simpl. subst. apply allsubtypes_in_to_domain_nat in H1. contradiction. apply IHOK in H1. auto. contradiction. + simpl in *. destruct (eq_dec_nat i i); simpl in *. rewrite issupertype_bot_p in H1. destruct (eq_dec_nat n1 i); simpl. subst. apply allsubtypes_in_to_domain_nat in H1. contradiction. apply IHOK in H1. auto. contradiction. + simpl in *. destruct (eq_dec_nat i i); simpl in *. rewrite issupertype_arrow_p in H1. destruct (eq_dec_nat n1 i); simpl. subst. apply allsubtypes_in_to_domain_nat in H1. contradiction. apply IHOK in H1. auto. contradiction. + simpl in *. destruct (eq_dec_nat i i); simpl in *. rewrite issupertype_union_p in H1. destruct (eq_dec_nat n1 i); simpl. subst. apply allsubtypes_in_to_domain_nat in H1. contradiction. apply IHOK in H1. auto. contradiction. + simpl in *. destruct (eq_dec_nat i i); simpl in *. rewrite issupertype_inter_p in H1. destruct (eq_dec_nat n1 i); simpl. subst. apply allsubtypes_in_to_domain_nat in H1. contradiction. apply IHOK in H1. auto. contradiction. + simpl in *. destruct (eq_dec_nat i i); simpl in *. rewrite issupertype_unit_p in H1. destruct (eq_dec_nat n1 i); simpl. subst. apply allsubtypes_in_to_domain_nat in H1. contradiction. apply IHOK in H1. auto. contradiction. + (*case bvar*) simpl in *. destruct (eq_dec_nat i i); simpl in *. rewrite issupertype_bvar_p in H1. destruct (eq_dec_nat n1 i); simpl. subst. apply allsubtypes_in_to_domain_nat in H1. contradiction. apply IHOK in H1. auto. contradiction. + (*case fvar*) simpl in *. destruct (eq_dec_nat i i); simpl in *. rewrite issupertype_fvar_p in H1. destruct (eq_dec_nat n1 i); simpl. subst. apply allsubtypes_in_to_domain_nat in H1. contradiction. apply IHOK in H1. auto. contradiction. + (*case all*) simpl in *. destruct (eq_dec_nat i i); simpl in *. rewrite issupertype_all_p in H1. destruct (eq_dec_nat n1 i); simpl. subst. apply allsubtypes_in_to_domain_nat in H1. contradiction. apply IHOK in H1. auto. contradiction. + (*case P*) apply getsubtypes_inversion_temp12 in H1; auto. destruct H1. destruct H1. subst. auto. apply IHOK in H1. forwards: issupertype_weakening H1 (t_prim n) H0. auto. Qed. Lemma allsubtypes_in_to_domain_nat : forall PG A, forall i, set_In i (get_all_subtypes PG A) -> set_In i (domain_envp PG). Proof. induction PG; introv IN1. - inverts IN1. - destruct a as [C D]. simpl in *. destruct (eq_dec_nat C C). destruct (eq_dec A D). + simpl in IN1. destruct IN1. * auto. * specialize (IHPG A i). forwards: IHPG H. auto. + simpl in IN1. destruct (issupertype PG D A). simpl in IN1. destruct IN1. auto. apply IHPG in H; auto. apply IHPG in IN1; auto. + contradiction. Qed. Lemma n_in_semi_trans : forall PG, okenvp PG -> forall n1 n2, set_In n1 (get_all_subtypes PG (t_prim n2)) -> forall i, set_In i (get_all_subtypes ((i, t_prim n1) :: PG) (t_prim n2)). Proof. intros. simpl. destruct (eq_dec_nat n2 n1); simpl. destruct (eq_dec_nat i i); simpl. auto. contradiction. destruct (eq_dec_nat i i); simpl. apply get_all_subtypes_issupertype in H0; auto. rewrite H0. simpl. auto. contradiction. Defined. Lemma demorgan2 : forall P Q, ~ (P \/ Q) -> ~P /\ ~Q. Proof. unfold not in *; intros. splits; intros. apply H; auto. apply H; auto. Qed. Lemma not_in_domain_issupertype_false : forall PG, okenvp PG -> forall i, ~ set_In i (domain_envp PG) -> forall A, issupertype PG A (t_prim i) = false. Proof. introv OK. induction OK; intros. - simpl. auto. - simpl in H1. apply demorgan2 in H1. destruct H1. destruct A; simpl; destruct (eq_dec A0 (t_prim i)); simpl; (*all cases except P*) try solve [ forwards*: IHOK H2 t_top; forwards*: IHOK H2]. (*case P*) destruct (eq_dec_nat i0 n); simpl. subst. inverts H. contradiction. forwards*: IHOK H2 (t_prim n). Defined. Lemma not_in_domain_subtypes_empty : forall PG, okenvp PG -> forall i, ~ set_In i (domain_envp PG) -> (get_all_subtypes PG (t_prim i)) = []. Proof. introv OK. induction OK; intros. - simpl. auto. - simpl in H1. apply demorgan2 in H1. destruct H1. destruct A; simpl; destruct (eq_dec_nat i i); simpl; try solve [contradiction]. + forwards* FALSE: not_in_domain_issupertype_false OK t_top; rewrite* FALSE. + forwards* FALSE: not_in_domain_issupertype_false OK t_int; rewrite* FALSE. + forwards* FALSE: not_in_domain_issupertype_false OK t_bot; rewrite* FALSE. + forwards* FALSE: not_in_domain_issupertype_false OK (t_arrow A1 A2); rewrite* FALSE. + forwards* FALSE: not_in_domain_issupertype_false OK (t_union A1 A2); rewrite* FALSE. + forwards* FALSE: not_in_domain_issupertype_false OK (t_and A1 A2); rewrite* FALSE. + forwards* FALSE: not_in_domain_issupertype_false OK t_unit; rewrite* FALSE. + forwards* FALSE: not_in_domain_issupertype_false OK (t_bvar n); rewrite* FALSE. + forwards* FALSE: not_in_domain_issupertype_false OK (t_fvar v); rewrite* FALSE. + forwards* FALSE: not_in_domain_issupertype_false OK (t_all A1 A2); rewrite* FALSE. + (*case P*) destruct (eq_dec_nat i0 n); simpl. subst. inverts H. contradiction. forwards FALSE: not_in_domain_issupertype_false OK H2 (t_prim n). rewrite FALSE. auto. Defined. Lemma set_in_weakening : forall PG n1 n2, set_In n1 (get_all_subtypes PG (t_prim n2)) -> forall i A, set_In n1 (get_all_subtypes ((i, A) :: PG) (t_prim n2)). Proof. destruct PG; intros. - simpl in H. inverts H. - destruct p as [j C]. destruct A. + (*case A = top*) destruct C. * (*case top top*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_top (t_prim n2)). simpl. simpl in H. auto. auto. contradiction. contradiction. * (*case top int*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_top (t_prim n2)). destruct (issupertype PG t_int (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG t_int (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case top bot*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_top (t_prim n2)). destruct (issupertype PG t_bot (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG t_bot (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case top arrow*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_top (t_prim n2)). destruct (issupertype PG (t_arrow C1 C2) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_arrow C1 C2) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case top union*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_top (t_prim n2)). destruct (issupertype PG (t_union C1 C2) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_union C1 C2) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case top intersection*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_top (t_prim n2)). destruct (issupertype PG (t_and C1 C2) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_and C1 C2) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case top unit*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_top (t_prim n2)). destruct (issupertype PG t_unit (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG t_unit (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case top bvar*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_top (t_prim n2)). destruct (issupertype PG (t_bvar n) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_bvar n) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case top fvar*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_top (t_prim n2)). destruct (issupertype PG (t_fvar v) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_fvar v) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case top all*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_top (t_prim n2)). destruct (issupertype PG (t_all C1 C2) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_all C1 C2) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case top P*) simpl in *. destruct (eq_dec_nat n2 n); simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_top (t_prim n2)). simpl. auto. simpl. auto. contradiction. contradiction. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i j); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG t_top (t_prim n2)). destruct (issupertype PG (t_prim n) (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG (t_prim n) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG t_top (t_prim n2)). destruct (issupertype PG (t_prim n) (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG (t_prim n) (t_prim n2)); simpl in *. auto. auto. contradiction. contradiction. + (*case A = int*) destruct C. * (*case int top*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_int (t_prim n2)). destruct (issupertype PG t_top (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG t_top (t_prim n2)); simpl in *. auto. auto. contradiction. contradiction. * (*case int int*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_int (t_prim n2)); simpl in *. auto. auto. contradiction. contradiction. * (*case int bot*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_int (t_prim n2)). destruct (issupertype PG t_bot (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG t_bot (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case int arrow*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_int (t_prim n2)). destruct (issupertype PG (t_arrow C1 C2) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_arrow C1 C2) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case int union*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_int (t_prim n2)). destruct (issupertype PG (t_union C1 C2) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_union C1 C2) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case int intersection*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_int (t_prim n2)). destruct (issupertype PG (t_and C1 C2) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_and C1 C2) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case int unit*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_int (t_prim n2)). destruct (issupertype PG t_unit (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG t_unit (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case int bvar*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_int (t_prim n2)). destruct (issupertype PG (t_bvar n) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_bvar n) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case int fvar*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_int (t_prim n2)). destruct (issupertype PG (t_fvar v) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_fvar v) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case int all*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_int (t_prim n2)). destruct (issupertype PG (t_all C1 C2) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_all C1 C2) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case int P*) simpl in *. destruct (eq_dec_nat n2 n); simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_int (t_prim n2)). simpl. auto. simpl. auto. contradiction. contradiction. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i j); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG t_int (t_prim n2)). destruct (issupertype PG (t_prim n) (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG (t_prim n) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG t_int (t_prim n2)). destruct (issupertype PG (t_prim n) (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG (t_prim n) (t_prim n2)); simpl in *. auto. auto. contradiction. contradiction. + (*case A = bot*) destruct C. * (*case bot top*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_bot (t_prim n2)). destruct (issupertype PG t_top (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG t_top (t_prim n2)); simpl in *. auto. auto. contradiction. contradiction. * (*case bot int*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_int (t_prim n2)); simpl in *. destruct (issupertype PG t_bot (t_prim n2)); simpl. auto. auto. destruct (issupertype PG t_bot (t_prim n2)); simpl. auto. auto. contradiction. contradiction. * (*case bot bot*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_bot (t_prim n2)); simpl in *. auto. auto. contradiction. contradiction. * (*case bot arrow*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_bot (t_prim n2)). destruct (issupertype PG (t_arrow C1 C2) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_arrow C1 C2) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case bot union*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_bot (t_prim n2)). destruct (issupertype PG (t_union C1 C2) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_union C1 C2) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case bot intersection*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_bot (t_prim n2)). destruct (issupertype PG (t_and C1 C2) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_and C1 C2) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case bot unit*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_bot (t_prim n2)). destruct (issupertype PG t_unit (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG t_unit (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case bot bvar*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_bot (t_prim n2)). destruct (issupertype PG (t_bvar n) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_bvar n) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case bot fvar*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_bot (t_prim n2)). destruct (issupertype PG (t_fvar v) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_fvar v) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case bot all*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_bot (t_prim n2)). destruct (issupertype PG (t_all C1 C2) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_all C1 C2) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case bot P*) simpl in *. destruct (eq_dec_nat n2 n); simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_bot (t_prim n2)). simpl. auto. simpl. auto. contradiction. contradiction. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i j); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG t_bot (t_prim n2)). destruct (issupertype PG (t_prim n) (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG (t_prim n) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG t_bot (t_prim n2)). destruct (issupertype PG (t_prim n) (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG (t_prim n) (t_prim n2)); simpl in *. auto. auto. contradiction. contradiction. + (*case A = arrow*) destruct C. * (*case arrow top*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_arrow A1 A2) (t_prim n2)). destruct (issupertype PG t_top (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG t_top (t_prim n2)); simpl in *. auto. auto. contradiction. contradiction. * (*case arrow int*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_arrow A1 A2) (t_prim n2)); simpl in *. destruct (issupertype PG t_bot (t_prim n2)); simpl. auto. auto. destruct (issupertype PG t_bot (t_prim n2)); simpl. auto. auto. contradiction. contradiction. * (*case arrow bot*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_bot (t_prim n2)); simpl in *. destruct (issupertype PG (t_arrow A1 A2) (t_prim n2)); simpl. auto. auto. destruct (issupertype PG (t_arrow A1 A2) (t_prim n2)); simpl. auto. auto. contradiction. contradiction. * (*case arrow arrow*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_arrow C1 C2) (t_prim n2)); simpl in *. destruct (issupertype PG (t_arrow A1 A2) (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG (t_arrow A1 A2) (t_prim n2)); simpl. auto. auto. contradiction. contradiction. * (*case arrow union*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_arrow A1 A2) (t_prim n2)). destruct (issupertype PG (t_union C1 C2) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_union C1 C2) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case arrow intersection*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_arrow A1 A2) (t_prim n2)). destruct (issupertype PG (t_and C1 C2) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_and C1 C2) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case arrow unit*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_arrow A1 A2) (t_prim n2)). destruct (issupertype PG t_unit (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG t_unit (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case arrow bvar*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_arrow A1 A2) (t_prim n2)). destruct (issupertype PG (t_bvar n) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_bvar n) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case arrow fvar*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_arrow A1 A2) (t_prim n2)). destruct (issupertype PG (t_fvar v) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_fvar v) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case arrow all*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_arrow A1 A2) (t_prim n2)). destruct (issupertype PG (t_all C1 C2) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_all C1 C2) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case arrow P*) simpl in *. destruct (eq_dec_nat n2 n); simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_arrow A1 A2) (t_prim n2)). simpl. auto. simpl. auto. contradiction. contradiction. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i j); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_arrow A1 A2) (t_prim n2)). destruct (issupertype PG (t_prim n) (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG (t_prim n) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_arrow A1 A2) (t_prim n2)). destruct (issupertype PG (t_prim n) (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG (t_prim n) (t_prim n2)); simpl in *. auto. auto. contradiction. contradiction. + (*case A = union*) destruct C. * (*case union top*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_union A1 A2) (t_prim n2)). destruct (issupertype PG t_top (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG t_top (t_prim n2)); simpl in *. auto. auto. contradiction. contradiction. * (*case union int*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_union A1 A2) (t_prim n2)); simpl in *. destruct (issupertype PG t_bot (t_prim n2)); simpl. auto. auto. destruct (issupertype PG t_bot (t_prim n2)); simpl. auto. auto. contradiction. contradiction. * (*case union bot*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_bot (t_prim n2)); simpl in *. destruct (issupertype PG (t_union A1 A2) (t_prim n2)); simpl. auto. auto. destruct (issupertype PG (t_union A1 A2) (t_prim n2)); simpl. auto. auto. contradiction. contradiction. * (*case union arrow*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_arrow C1 C2) (t_prim n2)); simpl in *. destruct (issupertype PG (t_union A1 A2) (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG (t_union A1 A2) (t_prim n2)); simpl. auto. auto. contradiction. contradiction. * (*case union union*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_union A1 A2) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case union intersection*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_union A1 A2) (t_prim n2)). destruct (issupertype PG (t_and C1 C2) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_and C1 C2) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case union unit*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_union A1 A2) (t_prim n2)). destruct (issupertype PG t_unit (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG t_unit (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case union bvar*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_union A1 A2) (t_prim n2)). destruct (issupertype PG (t_bvar n) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_bvar n) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case union fvar*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_union A1 A2) (t_prim n2)). destruct (issupertype PG (t_fvar v) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_fvar v) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case union all*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_union A1 A2) (t_prim n2)). destruct (issupertype PG (t_all C1 C2) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_all C1 C2) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case union P*) simpl in *. destruct (eq_dec_nat n2 n); simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_union A1 A2) (t_prim n2)). simpl. auto. simpl. auto. contradiction. contradiction. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i j); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_union A1 A2) (t_prim n2)). destruct (issupertype PG (t_prim n) (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG (t_prim n) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_union A1 A2) (t_prim n2)). destruct (issupertype PG (t_prim n) (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG (t_prim n) (t_prim n2)); simpl in *. auto. auto. contradiction. contradiction. + (*case A = intersection*) destruct C. * (*case intersection top*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_and A1 A2) (t_prim n2)). destruct (issupertype PG t_top (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG t_top (t_prim n2)); simpl in *. auto. auto. contradiction. contradiction. * (*case intersection int*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_and A1 A2) (t_prim n2)); simpl in *. destruct (issupertype PG t_bot (t_prim n2)); simpl. auto. auto. destruct (issupertype PG t_bot (t_prim n2)); simpl. auto. auto. contradiction. contradiction. * (*case intersection bot*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_bot (t_prim n2)); simpl in *. destruct (issupertype PG (t_and A1 A2) (t_prim n2)); simpl. auto. auto. destruct (issupertype PG (t_and A1 A2) (t_prim n2)); simpl. auto. auto. contradiction. contradiction. * (*case intersection arrow*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_arrow C1 C2) (t_prim n2)); simpl in *. destruct (issupertype PG (t_and A1 A2) (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG (t_and A1 A2) (t_prim n2)); simpl. auto. auto. contradiction. contradiction. * (*case intersection union*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_and A1 A2) (t_prim n2)). destruct (issupertype PG (t_union C1 C2) (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG (t_union C1 C2) (t_prim n2)); simpl in *. auto. auto. contradiction. contradiction. * (*case intersection intersection*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_and C1 C2) (t_prim n2)); simpl in *. destruct (issupertype PG (t_and A1 A2) (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG (t_and A1 A2) (t_prim n2)); simpl in *. auto. auto. contradiction. contradiction. * (*case intersection unit*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_and A1 A2) (t_prim n2)). destruct (issupertype PG t_unit (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG t_unit (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case intersection bvar*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_and A1 A2) (t_prim n2)). destruct (issupertype PG (t_bvar n) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_bvar n) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case intersection fvar*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_and A1 A2) (t_prim n2)). destruct (issupertype PG (t_fvar v) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_fvar v) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case intersection all*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_and A1 A2) (t_prim n2)). destruct (issupertype PG (t_all C1 C2) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_all C1 C2) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case intersection P*) simpl in *. destruct (eq_dec_nat n2 n); simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_and A1 A2) (t_prim n2)). simpl. auto. simpl. auto. contradiction. contradiction. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i j); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_and A1 A2) (t_prim n2)). destruct (issupertype PG (t_prim n) (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG (t_prim n) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_and A1 A2) (t_prim n2)). destruct (issupertype PG (t_prim n) (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG (t_prim n) (t_prim n2)); simpl in *. auto. auto. contradiction. contradiction. + (*case A = unit*) destruct C. * (*case unit top*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_unit (t_prim n2)). destruct (issupertype PG t_top (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG t_top (t_prim n2)); simpl in *. auto. auto. contradiction. contradiction. * (*case unit int*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_int (t_prim n2)); simpl in *. destruct (issupertype PG t_unit (t_prim n2)); simpl. auto. auto. destruct (issupertype PG t_unit (t_prim n2)); simpl. auto. auto. contradiction. contradiction. * (*case unit bot*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_unit (t_prim n2)). destruct (issupertype PG t_bot (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG t_bot (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case unit arrow*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_unit (t_prim n2)). destruct (issupertype PG (t_arrow C1 C2) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_arrow C1 C2) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case unit union*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_unit (t_prim n2)). destruct (issupertype PG (t_union C1 C2) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_union C1 C2) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case unit intersection*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_unit (t_prim n2)). destruct (issupertype PG (t_and C1 C2) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_and C1 C2) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case unit unit*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_unit (t_prim n2)); simpl in *. auto. auto. contradiction. contradiction. * (*case unit bvar*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_unit (t_prim n2)). destruct (issupertype PG (t_bvar n) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_bvar n) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case unit fvar*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_unit (t_prim n2)). destruct (issupertype PG (t_fvar v) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_fvar v) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case unit all*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_unit (t_prim n2)). destruct (issupertype PG (t_all C1 C2) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_all C1 C2) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case unit P*) simpl in *. destruct (eq_dec_nat n2 n); simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_unit (t_prim n2)). simpl. auto. simpl. auto. contradiction. contradiction. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i j); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG t_unit (t_prim n2)). destruct (issupertype PG (t_prim n) (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG (t_prim n) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG t_unit (t_prim n2)). destruct (issupertype PG (t_prim n) (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG (t_prim n) (t_prim n2)); simpl in *. auto. auto. contradiction. contradiction. + (*case A = Tbvar*) destruct C. * (*case unit top*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_bvar n) (t_prim n2)). destruct (issupertype PG t_top (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG t_top (t_prim n2)); simpl in *. auto. auto. contradiction. contradiction. * (*case Tbvar int*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_int (t_prim n2)); simpl in *. destruct (issupertype PG (t_bvar n) (t_prim n2)); simpl. auto. auto. destruct (issupertype PG (t_bvar n) (t_prim n2)); simpl. auto. auto. contradiction. contradiction. * (*case Tbvar bot*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_bvar n) (t_prim n2)). destruct (issupertype PG t_bot (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG t_bot (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case Tbvar arrow*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_bvar n) (t_prim n2)). destruct (issupertype PG (t_arrow C1 C2) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_arrow C1 C2) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case Tbvar union*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_bvar n) (t_prim n2)). destruct (issupertype PG (t_union C1 C2) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_union C1 C2) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case Tbvar intersection*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_bvar n) (t_prim n2)). destruct (issupertype PG (t_and C1 C2) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_and C1 C2) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case Tbvar unit*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_bvar n) (t_prim n2)); simpl in *. destruct (issupertype PG t_unit (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG t_unit (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case Tbvar bvar*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_bvar n) (t_prim n2)). simpl. auto. auto. contradiction. contradiction. * (*case Tbvar fvar*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_bvar n) (t_prim n2)). destruct (issupertype PG (t_fvar v) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_fvar v) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case Tbvar all*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_bvar n) (t_prim n2)). destruct (issupertype PG (t_all C1 C2) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_all C1 C2) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case Tbvar P*) simpl in *. destruct (eq_dec_nat n2 n); simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_bvar n) (t_prim n2)). simpl. auto. simpl. auto. contradiction. contradiction. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i j); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_bvar n) (t_prim n2)). destruct (issupertype PG (t_prim n) (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG (t_prim n) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_bvar n) (t_prim n2)). destruct (issupertype PG (t_prim n) (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG (t_prim n) (t_prim n2)); simpl in *. auto. auto. contradiction. contradiction. + (*case A = TFvar*) destruct C. * (*case TFvar top*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_fvar v) (t_prim n2)). destruct (issupertype PG t_top (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG t_top (t_prim n2)); simpl in *. auto. auto. contradiction. contradiction. * (*case Tfvar int*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_fvar v) (t_prim n2)); simpl in *. destruct (issupertype PG t_int (t_prim n2)); simpl. auto. auto. destruct (issupertype PG t_int (t_prim n2)); simpl. auto. auto. contradiction. contradiction. * (*case Tfvar bot*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_fvar v) (t_prim n2)). destruct (issupertype PG t_bot (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG t_bot (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case Tfvar arrow*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_fvar v) (t_prim n2)). destruct (issupertype PG (t_arrow C1 C2) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_arrow C1 C2) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case Tfvar union*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_fvar v) (t_prim n2)). destruct (issupertype PG (t_union C1 C2) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_union C1 C2) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case Tfvar intersection*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_fvar v) (t_prim n2)). destruct (issupertype PG (t_and C1 C2) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_and C1 C2) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case Tfvar unit*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_fvar v) (t_prim n2)); simpl in *. destruct (issupertype PG t_unit (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG t_unit (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case Tfvar bvar*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_fvar v) (t_prim n2)); simpl in *. destruct (issupertype PG (t_bvar n) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_bvar n) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case Tfvar fvar*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_fvar v) (t_prim n2)); simpl in *. auto. auto. contradiction. contradiction. * (*case Tfvar all*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_fvar v) (t_prim n2)). destruct (issupertype PG (t_all C1 C2) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_all C1 C2) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case Tfvar P*) simpl in *. destruct (eq_dec_nat n2 n); simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_fvar v) (t_prim n2)). simpl. auto. simpl. auto. contradiction. contradiction. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i j); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_fvar v) (t_prim n2)). destruct (issupertype PG (t_prim n) (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG (t_prim n) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_fvar v) (t_prim n2)). destruct (issupertype PG (t_prim n) (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG (t_prim n) (t_prim n2)); simpl in *. auto. auto. contradiction. contradiction. + (*case A = All*) destruct C. * (*case All top*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_all A1 A2) (t_prim n2)). destruct (issupertype PG t_top (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG t_top (t_prim n2)); simpl in *. auto. auto. contradiction. contradiction. * (*case All int*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG t_int (t_prim n2)); simpl in *. destruct (issupertype PG (t_all A1 A2) (t_prim n2)); simpl. auto. auto. destruct (issupertype PG (t_all A1 A2) (t_prim n2)); simpl. auto. auto. contradiction. contradiction. * (*case All bot*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_all A1 A2) (t_prim n2)). destruct (issupertype PG t_bot (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG t_bot (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case All arrow*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_all A1 A2) (t_prim n2)). destruct (issupertype PG (t_arrow C1 C2) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_arrow C1 C2) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case All union*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_all A1 A2) (t_prim n2)). destruct (issupertype PG (t_union C1 C2) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_union C1 C2) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case All intersection*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_all A1 A2) (t_prim n2)). destruct (issupertype PG (t_and C1 C2) (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG (t_and C1 C2) (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case All unit*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_all A1 A2) (t_prim n2)); simpl in *. destruct (issupertype PG t_unit (t_prim n2)). simpl in H. simpl. auto. simpl. auto. destruct (issupertype PG t_unit (t_prim n2)). simpl in *. auto. auto. contradiction. contradiction. * (*case All bvar*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_all A1 A2) (t_prim n2)); simpl in *. auto. auto. contradiction. contradiction. * (*case All fvar*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_all A1 A2) (t_prim n2)); simpl in *. auto. auto. contradiction. contradiction. * (*case All all*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_all A1 A2) (t_prim n2)); simpl in *. auto. auto. contradiction. contradiction. * (*case All P*) simpl in *. destruct (eq_dec_nat n2 n); simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i i); simpl in *. destruct (issupertype PG (t_all A1 A2) (t_prim n2)). simpl. auto. simpl. auto. contradiction. contradiction. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i j); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_all A1 A2) (t_prim n2)). destruct (issupertype PG (t_prim n) (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG (t_prim n) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_all A1 A2) (t_prim n2)). destruct (issupertype PG (t_prim n) (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG (t_prim n) (t_prim n2)); simpl in *. auto. auto. contradiction. contradiction. + (*case A = P*) destruct C. * (*case P top*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i j); simpl. destruct (eq_dec_nat n j); simpl. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG t_top (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG t_top (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG t_top (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_prim n) (t_prim n2)). destruct (issupertype PG t_top (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG t_top (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat n j); simpl. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG t_top (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG t_top (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG t_top (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_prim n) (t_prim n2)). destruct (issupertype PG t_top (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG t_top (t_prim n2)); simpl in *. auto. auto. contradiction. contradiction. * (*case P int*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i j); simpl. destruct (eq_dec_nat n j); simpl. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG t_int (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG t_int (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG t_int (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_prim n) (t_prim n2)). destruct (issupertype PG t_int (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG t_int (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat n j); simpl. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG t_int (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG t_int (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG t_int (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_prim n) (t_prim n2)). destruct (issupertype PG t_int (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG t_int (t_prim n2)); simpl in *. auto. auto. contradiction. contradiction. * (*case P bot*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i j); simpl. destruct (eq_dec_nat n j); simpl. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG t_bot (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG t_bot (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG t_bot (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_prim n) (t_prim n2)). destruct (issupertype PG t_bot (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG t_bot (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat n j); simpl. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG t_bot (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG t_bot (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG t_bot (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_prim n) (t_prim n2)). destruct (issupertype PG t_bot (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG t_bot (t_prim n2)); simpl in *. auto. auto. contradiction. contradiction. * (*case P arrow*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i j); simpl. destruct (eq_dec_nat n j); simpl. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_arrow C1 C2) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_arrow C1 C2) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_arrow C1 C2) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_prim n) (t_prim n2)). destruct (issupertype PG (t_arrow C1 C2) (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG (t_arrow C1 C2) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat n j); simpl. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_arrow C1 C2) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_arrow C1 C2) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_arrow C1 C2) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_prim n) (t_prim n2)). destruct (issupertype PG (t_arrow C1 C2) (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG (t_arrow C1 C2) (t_prim n2)); simpl in *. auto. auto. contradiction. contradiction. * (*case P union*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i j); simpl. destruct (eq_dec_nat n j); simpl. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_union C1 C2) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_union C1 C2) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_union C1 C2) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_prim n) (t_prim n2)). destruct (issupertype PG (t_union C1 C2) (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG (t_union C1 C2) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat n j); simpl. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_union C1 C2) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_union C1 C2) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_union C1 C2) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_prim n) (t_prim n2)). destruct (issupertype PG (t_union C1 C2) (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG (t_union C1 C2) (t_prim n2)); simpl in *. auto. auto. contradiction. contradiction. * (*case P intersection*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i j); simpl. destruct (eq_dec_nat n j); simpl. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_and C1 C2) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_and C1 C2) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_and C1 C2) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_prim n) (t_prim n2)). destruct (issupertype PG (t_and C1 C2) (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG (t_and C1 C2) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat n j); simpl. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_and C1 C2) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_and C1 C2) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_and C1 C2) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_prim n) (t_prim n2)). destruct (issupertype PG (t_and C1 C2) (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG (t_and C1 C2) (t_prim n2)); simpl in *. auto. auto. contradiction. contradiction. * (*case P unit*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i j); simpl. destruct (eq_dec_nat n j); simpl. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG t_unit (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG t_unit (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG t_unit (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_prim n) (t_prim n2)). destruct (issupertype PG t_unit (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG t_unit (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat n j); simpl. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG t_unit (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG t_unit (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG t_unit (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_prim n) (t_prim n2)). destruct (issupertype PG t_unit (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG t_unit (t_prim n2)); simpl in *. auto. auto. contradiction. contradiction. * (*case P Tbvar*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i j); simpl. destruct (eq_dec_nat n j); simpl. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_bvar n0) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_bvar n0) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_bvar n0) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_prim n) (t_prim n2)). destruct (issupertype PG (t_bvar n0) (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG (t_bvar n0) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat n j); simpl. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_bvar n0) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_bvar n0) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_bvar n0) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_prim n) (t_prim n2)). destruct (issupertype PG (t_bvar n0) (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG (t_bvar n0) (t_prim n2)); simpl in *. auto. auto. contradiction. contradiction. * (*case P Tfvar*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i j); simpl. destruct (eq_dec_nat n j); simpl. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_fvar v) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_fvar v) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_fvar v) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_prim n) (t_prim n2)). destruct (issupertype PG (t_fvar v) (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG (t_fvar v) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat n j); simpl. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_fvar v) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_fvar v) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_fvar v) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_prim n) (t_prim n2)). destruct (issupertype PG (t_fvar v) (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG (t_fvar v) (t_prim n2)); simpl in *. auto. auto. contradiction. contradiction. * (*case P All*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat i j); simpl. destruct (eq_dec_nat n j); simpl. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_all C1 C2) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_all C1 C2) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_all C1 C2) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_prim n) (t_prim n2)). destruct (issupertype PG (t_all C1 C2) (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG (t_all C1 C2) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat n j); simpl. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_all C1 C2) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_all C1 C2) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_all C1 C2) (t_prim n2)); simpl in *. auto. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_prim n) (t_prim n2)). destruct (issupertype PG (t_all C1 C2) (t_prim n2)); simpl in *. auto. auto. destruct (issupertype PG (t_all C1 C2) (t_prim n2)); simpl in *. auto. auto. contradiction. contradiction. * (*case P P*) simpl in *. destruct (eq_dec_nat j j); simpl in *. destruct (eq_dec_nat n2 n0); simpl in *. destruct (eq_dec_nat i j); simpl. destruct (eq_dec_nat n j); simpl. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. auto. contradiction. destruct (eq_dec_nat i i); simpl. auto. contradiction. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. auto. contradiction. (*repeatition started in reverse*) destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_prim n) (t_prim n2)); simpl. auto. auto. contradiction. destruct (eq_dec_nat n j); simpl. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. auto. contradiction. destruct (eq_dec_nat i i); simpl. auto. contradiction. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_prim n) (t_prim n2)); simpl. auto. auto. contradiction. (*repeatition from (eq_dec_nat i j) *) destruct (eq_dec_nat i j); simpl. destruct (eq_dec_nat n j); simpl. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_prim n0) (t_prim n2)); simpl. auto. auto. contradiction. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_prim n) (t_prim n2)); simpl. auto. auto. contradiction. destruct (eq_dec_nat n j); simpl. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_prim n0) (t_prim n2)); simpl. auto. auto. contradiction. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_prim n) (t_prim n2)); simpl. auto. auto. contradiction. (**** repeatition from (eq_dec_nat n2 n0) *****) destruct (eq_dec_nat n2 n0); simpl in *. destruct (eq_dec_nat i j); simpl. destruct (eq_dec_nat n j); simpl. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. auto. contradiction. destruct (eq_dec_nat i i); simpl. auto. contradiction. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. auto. contradiction. (*repeatition started in reverse*) destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_prim n) (t_prim n2)); simpl. auto. auto. contradiction. destruct (eq_dec_nat n j); simpl. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. auto. contradiction. destruct (eq_dec_nat i i); simpl. auto. contradiction. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_prim n) (t_prim n2)); simpl. auto. auto. contradiction. (*repeatition from (eq_dec_nat i j) *) destruct (eq_dec_nat i j); simpl. destruct (eq_dec_nat n j); simpl. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_prim n0) (t_prim n2)); simpl. auto. auto. contradiction. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_prim n) (t_prim n2)); simpl. auto. auto. contradiction. destruct (eq_dec_nat n j); simpl. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_prim n0) (t_prim n2)); simpl. auto. auto. contradiction. destruct (eq_dec_nat n2 n); simpl. destruct (eq_dec_nat i i); simpl. auto. contradiction. destruct (eq_dec_nat i i); simpl. destruct (issupertype PG (t_prim n) (t_prim n2)); simpl. auto. auto. contradiction. Defined. Lemma p_in_sub_nat62 : forall PG, okenvp PG -> forall n1 n2, set_In n1 (get_all_subtypes PG (t_prim n2)) -> forall n3, set_In n2 (get_all_subtypes PG (t_prim n3)) -> set_In n1 (get_all_subtypes PG (t_prim n3)). Proof. introv OK. inductions OK; intros. - inverts H0. - apply getsubtypes_inversion_temp12 in H1. destruct H1. destruct H1. apply getsubtypes_inversion_temp12 in H2. destruct H2. destruct H2. subst. apply subpertypes_inversion; auto. subst. forwards*: issupertype_inverse H3. destruct H1. subst. apply n_in_semi_trans; auto. simpl in *. destruct A. rewrite issupertype_top_p in H1. inverts H1. rewrite issupertype_int_p in H1. inverts H1. rewrite issupertype_bot_p in H1. inverts H1. rewrite issupertype_arrow_p in H1. inverts H1. rewrite issupertype_union_p in H1. inverts H1. rewrite issupertype_inter_p in H1. inverts H1. rewrite issupertype_unit_p in H1. inverts H1. rewrite issupertype_bvar_p in H1. inverts H1. rewrite issupertype_fvar_p in H1. inverts H1. rewrite issupertype_all_p in H1. inverts H1. forwards*: subpertypes_inversion H1. forwards*: IHOK H4 H2. apply n_in_semi_trans; auto. apply getsubtypes_inversion_temp12 in H2. destruct H2. destruct H2. subst. apply not_in_domain_subtypes_empty in H0; auto. rewrite H0 in H1. inverts H1. forwards*: IHOK H1 H2. apply set_in_weakening. auto. Defined. Lemma p_in_sub : forall PG n1 n2, okenvp PG -> set_In (t_prim n1) (nats_to_types (get_all_subtypes PG (t_prim n2))) -> forall n3, set_In (t_prim n2) (nats_to_types (get_all_subtypes PG (t_prim n3))) -> set_In (t_prim n1) (nats_to_types (get_all_subtypes PG (t_prim n3))). Proof. intros. apply nats_to_types_iff. apply nats_to_types_iff in H0. apply nats_to_types_iff in H1. eapply p_in_sub_nat62 with (n2:=n2); auto. Qed. (* ********************************************************************** *) (** Subtyping Transitivity *) Lemma sub_transitivity : forall B PG G A C, sub PG G A B -> sub PG G B C -> sub PG G A C. Proof. intros B PG G A C ASubB BSubC. assert (W : (type B)). forwards*: sub_regular ASubB. destructs H. forwards*: type_from_wft H1. generalize dependent C. generalize dependent A. generalize dependent G. generalize dependent PG. remember B as B' in |- *. generalize dependent B'. induction W; intros B' EQ PG G A ASubB. 1:{ (* Case Top *) intros; inductions ASubB; eauto; try discriminate. inductions BSubC; eauto. forwards*: sub_regular BSubC. } 1:{ (* Case Int *) intros; inductions ASubB; eauto; try discriminate. forwards*: sub_regular BSubC. } 1:{ (* Case Bot *) intros; inductions ASubB; eauto; try discriminate. forwards*: sub_regular BSubC. } 1:{ (* Case Arrow *) intros; inductions ASubB; eauto; try discriminate. inductions BSubC; eauto. forwards*: sub_regular ASubB1. forwards*: sub_regular ASubB2. forwards*: sub_regular BSubC. } 1:{ (* Case Union *) intros; inductions ASubB; eauto; try discriminate. inductions BSubC; eauto. forwards*: sub_regular ASubB. inverts EQ. apply sub_or in BSubC. destruct BSubC. forwards*: IHW2 T2 A C. forwards*: sub_regular BSubC. } 1:{ (* Case And *) intros; inductions ASubB; eauto; try discriminate. inductions BSubC; eauto. forwards*: sub_regular ASubB1. forwards*: sub_regular BSubC. } 1:{ (* Case TVar *) intros; inductions ASubB; eauto; try discriminate. forwards*: sub_regular BSubC. } 1:{ (* Case Disjoint Quantification *) intros; inductions ASubB; eauto; try discriminate. forwards*: sub_regular BSubC. inductions BSubC; eauto. (* All <: Top *) assert (sub PG G (t_all S1 S2) (t_all T1 T2)). pick_fresh Y. apply s_all with (L:=((((((L \u L0) \u fv_tt T1) \u fv_tt T2) \u fv_tt S1) \u fv_tt S2) \u dom G)); auto. forwards*: sub_regular H7. (* All <: All *) clear H4 IHBSubC. pick_fresh Y. apply s_all with (L:=(((((((((L \u L0) \u L1) \u fv_tt T1) \u fv_tt T2) \u fv_tt S1) \u fv_tt S2) \u fv_tt T4) \u fv_tt T5) \u dom G)); autos*. intros. lapply (H0 X); [ intros K | auto ]. apply (K (T2 open_tt_var X)); auto. rewrite (append_empty_right (G & X ~*: T4)). eapply sub_narrowing_aux; eauto. assert (NOTIN : X \notin L0) by auto. forwards: H2 X NOTIN. rewrite~ <- append_empty_right. forwards* TEMP1: H6 X. forwards* (_&_&_&TEMP2): sub_regular TEMP1. apply okt_push_inv_tt in TEMP2. destructs TEMP2. rewrite~ <- append_empty_right. } 1:{ (* Case Unit *) intros; inductions ASubB; eauto; try discriminate. forwards*: sub_regular BSubC. } 1:{ intros; inductions BSubC; eauto; try discriminate. (*case bot <: C*) forwards*: sub_regular ASubB. (*case P <: C *) forwards*: sub_regular ASubB. inductions ASubB; eauto. forwards*: IHASubB1. split*. split*. destructs H4. inverts* H5. forwards*: IHASubB2. split*. split*. destructs H4. inverts* H6. forwards*: IHASubB. split*. split*. destructs H5. inverts* H6. forwards*: IHASubB. split*. split*. destructs H5. inverts* H6. forwards*: p_in_sub H3 H8. } Defined. (* ********************************************************************** *) (** Subtyping Weakening *) Lemma sub_weakening : forall PG E F G S T, sub PG (E & G) S T -> okt PG (E & F & G) -> sub PG (E & F & G) S T. Proof. introv Typ. gen_eq : (E & G) as H. gen G. induction Typ; introv EQ Ok; subst; eauto. - apply wft_weaken with (F:=F) in H1; auto. apply ok_from_okt in Ok; auto. - apply wft_weaken with (F:=F) in H; auto. apply ok_from_okt in Ok; auto. - apply wft_weaken with (F:=F) in H; auto. apply ok_from_okt in Ok; auto. - apply wft_weaken with (F:=F) in H; auto. apply ok_from_okt in Ok; auto. - apply wft_weaken with (F:=F) in H; auto. apply ok_from_okt in Ok; auto. - apply wft_weaken with (F:=F) in H1; auto. apply ok_from_okt in Ok; auto. - apply wft_weaken with (F:=F) in H1; auto. apply ok_from_okt in Ok; auto. - pick_fresh Y. apply s_all with (L:=( ((((((L \u fv_tt S1) \u fv_tt S2) \u fv_tt T1) \u fv_tt T2) \u dom E) \u dom F) \u dom G0)); auto. intros. forwards* : H1 X (G0 & X ~*: T1). rewrite~ concat_assoc. apply sub_regular in Typ. destructs Typ. forwards*: ok_from_okt Ok. forwards* : wft_weaken H5. forwards*: H0 Y. forwards*(_&_&_&TEMP1): sub_regular H9. apply okt_push_inv_tt in TEMP1. destructs TEMP1. rewrite~ concat_assoc. rewrite~ concat_assoc in H3. - apply wft_weaken with (F:=F) in H1; auto. apply ok_from_okt in Ok; auto. - apply wft_weaken with (F:=F) in H1; auto. apply wft_weaken with (F:=F) in H2; auto. apply ok_from_okt in Ok; auto. apply ok_from_okt in Ok; auto. Qed. (********************************************) (** OSubs Unique **) Lemma osubs_unique : forall PG E A l1, OSubtypes PG E A l1 -> forall l2, OSubtypes PG E A l2 -> l1 = l2. Proof. introv osubs1. induction osubs1; introv osubs2; eauto; try solve [inverts* osubs2]. inverts osubs2. forwards*: IHosubs1_1 H1. forwards*: IHosubs1_2 H3. subst. auto. inverts osubs2. forwards*: IHosubs1_1 H1. forwards*: IHosubs1_2 H3. subst. auto. inverts osubs2. apply binds_get in H. apply binds_get in H1. rewrite H in H1. inverts H1. forwards*: IHosubs1 H2. subst. auto. Qed. (********************************************) (** Disjointness Weakening **) Lemma osubs_strength : forall PG E G S l x T, OSubtypes PG (E & x ~: T & G) S l -> ok (E & G) -> OSubtypes PG (E & G) S l. Proof. introv OSubs ok. induction OSubs; eauto. apply osubs_fvar with (T:=T0); auto. rewrite <- (concat_empty_r). binds_cases H. apply* binds_weaken. rewrite~ concat_empty_r. rewrite <- (concat_empty_r). apply* binds_weaken. rewrite~ concat_empty_r. rewrite~ concat_empty_r. Qed. Lemma osubs_weaken : forall F PG E G S l, OSubtypes PG (E & G) S l -> okt PG (E & F & G) -> OSubtypes PG (E & F & G) S l. Proof. intros. induction H; auto; intros. apply osubs_fvar with (T:=T); auto. apply* binds_weaken. apply ok_from_okt in H0; auto. Qed. Lemma osubs_exists_strengthen : forall PG E G F S l, OSubtypes PG (E & F & G) S l -> okt PG (E & F & G) -> wft PG (E & F & G ) S -> wft PG (E & G) S -> okt PG (E & G) -> exists l1, OSubtypes PG (E & G) S l1. Proof. introv OSubs ok WFT1 WFT2 ok'. induction OSubs; eauto. inverts WFT1. inverts WFT2. - (*case union*) destruct~ IHOSubs1 as [l3 osubsa]. destruct~ IHOSubs2 as [l4 osubsb]. exists* (l3 `union` l4). - (*case intersection*) inverts WFT1. inverts WFT2. destruct~ IHOSubs1 as [l3 osubsa]. destruct~ IHOSubs2 as [l4 osubsb]. exists* (l3 `inter` l4). - (*case TVar*) destruct~ IHOSubs as [l3 H3]. forwards*: wft_from_env_has_sub ok H. inverts WFT2. apply ok_from_okt in ok. lets H2': H2. apply binds_weaken with (F:=F) in H2'; auto. apply binds_get in H. apply binds_get in H2'. rewrite H in H2'. inverts H2'. forwards*: wft_from_env_has_sub H2. exists* ((all_ord PG) `dif` l3). apply* osubs_fvar. inverts WFT2. apply ok_from_okt in ok. lets H2': H2. apply binds_weaken with (F:=F) in H2'; auto. apply binds_get in H. apply binds_get in H2'. rewrite H in H2'. inverts H2'. auto. Qed. Lemma osubs_weaken_empty : forall PG E G F S, OSubtypes PG (E & G) S [] -> okt PG (E & F & G) -> OSubtypes PG (E & F & G) S []. Proof. introv OSubs ok. gen F. induction OSubs; eauto. intros. apply* osubs_fvar. apply binds_weaken with (F:=F) in H; auto. apply* ok_from_okt. Qed. Lemma disj_weakening : forall F PG E G S T, PG; (E & G) |= S *a T -> okt PG (E & F & G) -> PG; (E & F & G) |= S *a T. Proof. introv Disj Ok. forwards* (OKP&OK&WFS&WFT): disj_regular Disj. unfold DisjAlgo. splits; autos*. apply* wft_weaken. apply ok_from_okt in Ok; auto. apply* wft_weaken. apply ok_from_okt in Ok; auto. intros l3 l4 Subs. unfold DisjAlgo in Disj. destructs Disj. destruct Subs as [sub1 sub2]. forwards*: osubs_exists_strengthen sub1. apply* wft_weaken. apply* ok_from_okt. forwards*: osubs_exists_strengthen sub2. apply* wft_weaken. apply* ok_from_okt. destruct H4 as [l1 subs3]. destruct H5 as [l2 subs4]. (* this is proveable with some more thinking *) forwards*: H3 l1 l2. assert (OSubtypes PG (E & G) (t_and S T) (l1 `inter` l2)) by auto. rewrite H4 in H5. forwards*: osubs_weaken_empty (t_and S T). assert (OSubtypes PG (E & F & G) (t_and S T) (l3 `inter` l4)) by auto. forwards*: osubs_unique H6 H7. Qed. (* ********************************************************************** *) (** Typing Weakening *) Lemma typing_weakening : forall PG E F G e T, typing PG (E & G) e T -> okt PG (E & F & G) -> typing PG (E & F & G) e T. Proof. introv Typ. gen F. inductions Typ; introv Ok. - apply* typ_lit. - apply* typ_null. - apply* typ_var. apply* binds_weaken. apply ok_from_okt in Ok; auto. - apply* typ_app. - apply* typ_sub. apply* sub_weakening. - pick_fresh y. apply typ_abs with (L:=((((((L \u fv_ee e) \u fv_te e) \u fv_tt A) \u fv_tt B) \u dom E) \u dom G) \u dom F); auto. intros. forwards~: (H1 x). apply_ih_bind (H2 x); eauto. apply* okt_typ. apply* wft_weaken. apply typing_regular in H4. destructs~ H4. apply okt_push_inv in H5. destructs~ H5. apply ok_from_okt in Ok; auto. - pick_fresh y. apply typ_typeof with (L:=(((((((L \u fv_ee e) \u fv_te e) \u fv_tt A) \u fv_tt B) \u dom E) \u dom G) \u dom F)); intros; autos*. + forwards* : H x. apply_ih_bind (H0 x); eauto. apply okt_typ; auto. apply* wft_weaken. forwards* (?&?&?&?): typing_regular Typ. inverts* H9. apply ok_from_okt in Ok; auto. + forwards* : H1 x. apply_ih_bind (H2 x); eauto. apply okt_typ; auto. apply* wft_weaken. forwards* (?&?&?&?): typing_regular Typ. inverts* H9. apply ok_from_okt in Ok; auto. + (* TODO: need some work here *) apply* disj_weakening. - apply* typ_inter. - pick_fresh Y. apply typ_tabs with (L:=(((((((L \u fv_ee e) \u fv_te e) \u fv_tt A) \u fv_tt B) \u dom E) \u dom G) \u dom F)); auto; intros. apply_ih_bind (H2 X); eauto. apply okt_disj; auto. apply* wft_weaken. forwards* : H1 Y. forwards* (?&?&?): typing_regular H4. apply* (@okt_push_inv_tt PG (E & G) Y A). apply ok_from_okt in Ok; auto. forwards*: H1 Y. forwards* (_&TEMP1&_): typing_regular H4. apply okt_push_inv_tt in TEMP1. destructs~ TEMP1. - eapply typ_tapp; eauto. (* TODO: need some work here *) apply* disj_weakening. Qed. (* ********************************************************************** *) (** Subtyping Strengthening *) Lemma sub_strengthening : forall PG x U E F S T, sub PG (E & x ~: U & F) S T -> sub PG (E & F) S T. Proof. intros PG x U E F S T SsubT. gen_eq : (E & x ~: U & F) as G. gen F. induction SsubT; introv EQ; subst; autos*; try solve [apply wft_strengthen in H1; apply okt_strengthen in H0; auto]; try solve [apply wft_strengthen in H; auto]; try solve [apply okt_strengthen in H; auto]. (* case: all *) pick_fresh Y. apply s_all with (L:=((((((((L \u \{ x}) \u fv_tt U) \u fv_tt S1) \u fv_tt S2) \u fv_tt T1) \u fv_tt T2) \u dom E) \u dom F)); auto; intros. apply_ih_bind* H1. apply wft_strengthen in H2; apply wft_strengthen in H1; apply okt_strengthen in H0; auto. Qed. (** Ground Types Properties *) Lemma exists_osubtypes_ground : forall PG E A, groundtype A -> exists l, OSubtypes PG E A l. Proof. introv GT. inductions GT; try solve [exists*]. destruct~ IHGT1 as [l1]. destruct~ IHGT2 as [l2]. exists*. destruct~ IHGT1 as [l1]. destruct~ IHGT2 as [l2]. exists*. Qed. Lemma groundtype_osubs_env_unique : forall PG A, groundtype A -> forall E1 l1, OSubtypes PG E1 A l1 -> forall E2 l2, OSubtypes PG E2 A l2 -> l1 = l2. Proof. induction 1; introv osub1 osub2; try solve [inverts osub1; inverts osub2; auto]. inverts osub1. inverts osub2. forwards* EQ1: IHgroundtype1 H3 H4. forwards* EQ2: IHgroundtype2 H5 H7. subst. auto. inverts osub1. inverts osub2. forwards* EQ1: IHgroundtype1 H3 H4. forwards* EQ2: IHgroundtype2 H5 H7. subst. auto. Qed. (**********************************************************) (**** subset definition and properties *) Definition subset (l1 l2 : list typ) := forall (t : typ), set_In t l1 -> set_In t l2. Lemma subset_refl : forall l, subset l l. Proof. unfold subset. introv IN. auto. Qed. Lemma subset_empty_empty : forall l, subset l [] -> l = []. Proof. unfold subset. intros. destruct l. - auto. - false. apply (H t). simpl. left*. Qed. Lemma empty_subset : forall l, subset [] l. Proof. unfold subset. intros. inverts H. Qed. Lemma subset_trans : forall t l1 l2, set_In t l1 -> subset l1 l2 -> set_In t l2. Proof. unfold subset. intros. forwards*: H0 H. Qed. Lemma subset_union_elim : forall l1 l2 l, subset l1 l -> subset l2 l -> subset (l1 `union` l2) l. Proof. unfold subset; introv IN1 IN2 IN3. apply set_union_elim in IN3. destruct IN3; auto. Qed. Lemma subset_union_introl : forall l1 l2 l, subset l l1 -> subset l (l1 `union` l2). Proof. unfold subset; introv IN1 IN2. apply set_union_intro; auto. Qed. Lemma subset_union_intror : forall l1 l2 l, subset l l2 -> subset l (l1 `union` l2). Proof. unfold subset; introv IN1 IN2. apply set_union_intro; auto. Qed. Lemma subset_inter_eliml : forall l1 l2 l, subset l1 l -> subset (l1 `inter` l2) l. Proof. unfold subset; introv IN1 IN2. apply set_inter_elim in IN2. destruct IN2; auto. Qed. Lemma subset_inter_elimr : forall l1 l2 l, subset l2 l -> subset (l1 `inter` l2) l. Proof. unfold subset; introv IN1 IN2. apply set_inter_elim in IN2. destruct IN2; auto. Qed. Lemma subset_inter_elim_inv : forall l1 l2 l, subset l l1 -> subset l l2 -> subset l (l1 `inter` l2). Proof. unfold subset; introv IN1 IN2 IN3. apply set_inter_intro; auto. Qed. Lemma subset_diff : forall l l1 l2, subset l2 l1 -> subset (l `dif` l1) (l `dif` l2). Proof. unfold subset; intros. apply set_diff_iff in H0. destruct H0. apply* set_diff_intro. unfold not. intros. apply (H t) in H2. contradiction. Qed. Lemma groundtype_subtype_subset : forall PG E P, groundtype P -> forall Q, groundtype Q -> sub PG E P Q -> forall l1 E2, OSubtypes PG E2 P l1 -> forall l2 E3, OSubtypes PG E3 Q l2 -> subset l1 l2. Proof. introv GP GQ Sub osub1 osub2. gen Q l2. induction osub1; intros. - (*case top*) induction osub2; try solve [inverts Sub]. apply subset_refl. unfold subset; introv IN. inverts GQ. inverts Sub. forwards*: IHosub2_1 H6. apply (subset_trans t (all_ord PG) l1 IN) in H. apply* set_union_intro. forwards*: IHosub2_2 H6. apply (subset_trans t (all_ord PG) l2 IN) in H. apply* set_union_intro. inverts GQ. inverts Sub. unfold subset; introv IN. forwards*: IHosub2_1 H5. forwards*: IHosub2_2 H6. apply (subset_trans t (all_ord PG) l1 IN) in H. apply (subset_trans t (all_ord PG) l2 IN) in H0. apply* set_inter_intro. - (*case bot*) apply empty_subset. - (*case int*) unfold subset; intros. inductions Sub; inverts osub2. unfold all_ord. simpl in H2. destruct H2. subst. simpl. auto. inverts H2. auto. inverts GQ. forwards*: IHSub H3. apply set_union_intro. left*. inverts GQ. forwards*: IHSub H5. apply set_union_intro. right*. inverts GQ. forwards*: IHSub1 H2. forwards*: IHSub2 H4. apply* set_inter_intro. - (*case arroq*) unfold subset; intros. inductions Sub; inverts osub2. unfold all_ord. simpl in H2. destruct H2. subst. simpl. auto. inverts H2. auto. inverts GQ. forwards*: IHSub H3. apply set_union_intro. left*. inverts GQ. forwards*: IHSub H5. apply set_union_intro. right*. inverts GQ. forwards*: IHSub1 H2. forwards*: IHSub2 H4. apply* set_inter_intro. - (*case union*) apply sub_or in Sub. destruct Sub. inverts GP. forwards*: IHosub1_1 H osub2. forwards*: IHosub1_2 H0 osub2. apply* (subset_union_elim l1 l2 l0). - (*case and*) induction osub2. (*case and top*) inverts GP. inverts Sub. inverts H3. forwards*: IHosub1_1 t_top. apply* subset_inter_eliml. forwards*: IHosub1_1 H6. apply* subset_inter_eliml. forwards*: IHosub1_2 H6. apply* subset_inter_elimr. (*case and bot*) inverts GP. inverts Sub. forwards*: IHosub1_1 H6. apply* subset_inter_eliml. forwards*: IHosub1_2 H6. apply* subset_inter_elimr. (*case and int*) inverts GP. inverts Sub. forwards*: IHosub1_1 H6. apply* subset_inter_eliml. forwards*: IHosub1_2 H6. apply* subset_inter_elimr. (*case and arrow*) inverts GP. inverts Sub. forwards*: IHosub1_1 H6. apply* subset_inter_eliml. forwards*: IHosub1_2 H6. apply* subset_inter_elimr. (*and or*) inverts GP. inverts GQ. inverts Sub. forwards*: IHosub2_1 H8. apply* subset_union_introl. forwards*: IHosub2_2 H8. apply* subset_union_intror. forwards*: IHosub1_1 H8. apply* subset_inter_eliml. forwards*: IHosub1_2 H8. apply* subset_inter_elimr. (*and and*) apply sub_and in Sub. destruct Sub. inverts GQ. forwards*: IHosub2_1 H. forwards*: IHosub2_2 H0. apply* subset_inter_elim_inv. (*and unit*) inverts GP. inverts Sub. forwards*: IHosub1_1 H6. apply* subset_inter_eliml. forwards*: IHosub1_2 H6. apply* subset_inter_elimr. (*and fvar*) inverts GQ. (*and all*) inverts GP. inverts Sub. forwards*: IHosub1_1 H6. apply* subset_inter_eliml. forwards*: IHosub1_2 H6. apply* subset_inter_elimr. (*and prim*) inverts GP. inverts Sub. forwards*: IHosub1_1 H6. apply* subset_inter_eliml. forwards*: IHosub1_2 H6. apply* subset_inter_elimr. - (*case unit*) unfold subset; intros. inductions Sub; inverts osub2. unfold all_ord. simpl in H2. destruct H2. subst. simpl. auto. inverts H2. auto. inverts GQ. forwards*: IHSub H3. apply set_union_intro. left*. inverts GQ. forwards*: IHSub H5. apply set_union_intro. right*. inverts GQ. forwards*: IHSub1 H2. forwards*: IHSub2 H4. apply* set_inter_intro. - (*case TVar*) inverts GP. - (*case All*) inverts GP. unfold subset; introv IN. induction osub2; try solve [inverts Sub]. simpl in IN. destruct IN. subst. simpl. auto. inverts H. inverts GQ. inverts Sub. forwards*: IHosub2_1 H7. apply* set_union_intro. forwards*: IHosub2_2 H7. apply* set_union_intro. inverts GQ. apply sub_and in Sub. destruct Sub. forwards*: IHosub2_1 H. forwards*: IHosub2_2 H1. apply* set_inter_intro. auto. - (*case prim*) unfold subset; simpl; introv IN. induction osub2; try solve [inverts Sub]. unfold all_ord. simpl. destruct IN. subst. right. right. right. right. auto. forwards* (Ok&WFP&_): sub_regular Sub. inverts WFP. apply* i_in_nat_to_types. right. right. right. right. apply* allsubtypes_in_to_domain. inverts GQ. inverts Sub. forwards*: IHosub2_1 H6. apply* set_union_intro. forwards*: IHosub2_2 H6. apply* set_union_intro. inverts GQ. inverts Sub. forwards*: IHosub2_1 H5. forwards*: IHosub2_2 H6. apply* set_inter_intro. simpl. inverts Sub. destruct IN. subst~. right*. destruct IN. subst. right*. forwards* (i1&EQ): prim_type_in_nats_to_types H. subst. right. apply * p_in_sub. Qed. (* Narrowing of OSubs *) Lemma osubs_narrowing_tvar : forall PG Q F E Z P X l1, OSubtypes PG (E & Z ~*: P & F) (t_fvar X) l1 -> okt PG (E & Z ~*: P & F) -> sub PG E P Q -> groundtype P -> groundtype Q -> forall l2, OSubtypes PG (E & Z ~*: Q & F) (t_fvar X) l2 -> subset l2 l1. Proof. introv osub1 Ok sub1 GP GQ osub2. gen Q l2. inductions osub1; auto; intros; try solve [inverts subtvar]. - (*case TVar*) inverts osub2. forwards* TEMP1: sub_regular sub1. forwards* Ok1: okt_narrow Q Ok. forwards* GT: okt_binds_ground Ok H. forwards* GT0: okt_binds_ground Ok1 H1. binds_cases H. binds_cases H1. apply binds_get in B0. apply binds_get in B1. rewrite B0 in B1. inverts B1. forwards* EQ1: groundtype_osubs_env_unique osub1 H2. rewrite EQ1. (* reflexivity *) apply subset_refl. apply okt_concat_inv_tt in Ok1. destructs Ok1. unfold "#" in H0. (* contradiction of H0 and B0 *) apply binds_get in B0. apply get_some_inv in B0. contradiction. (* contradiction of Fr and B1 *) apply binds_get in B1. apply get_some_inv in B1. contradiction. binds_cases H1. apply okt_concat_inv_tt in Ok1. destructs Ok1. (* contradiction of H0 and B0 *) apply binds_get in B0. apply get_some_inv in B0. contradiction. inverts EQ. inverts EQ0. (* True - H3 and osub1 - l <= l1 *) lets TEMP2: groundtype_subtype_subset PG E P GP Q. forwards* TEMP3: TEMP2 GQ sub1. forwards* TEMP4: TEMP3 osub1 H2. apply* subset_diff. (* contradiction of Fr and B0 *) apply binds_get in B0. apply get_some_inv in B0. contradiction. binds_cases H1. (* contradiction of B0 and Fr *) apply binds_get in B0. apply get_some_inv in B0. contradiction. (* contradiction of B0 and Fr *) apply binds_get in B0. apply get_some_inv in B0. contradiction. apply binds_get in B0. apply binds_get in B1. rewrite B1 in B0. inverts B0. forwards* EQ1: groundtype_osubs_env_unique osub1 H2. rewrite EQ1. (* reflexivity *) apply subset_refl. Qed. Lemma osubs_narrowing_empty : forall PG Q F E Z P S l1, OSubtypes PG (E & Z ~*: P & F) S l1 -> okt PG (E & Z ~*: P & F) -> sub PG E P Q -> groundtype P -> groundtype Q -> forall l2, OSubtypes PG (E & Z ~*: Q & F) S l2 -> subset l2 l1. Proof. introv osub1 Ok sub1 GP GQ osub2. gen Q l2. induction osub1; auto; intros; try solve [inverts osub2; apply subset_refl]. 1 :{ (*case union*) inverts osub2. forwards*: IHosub1_1 sub1 H1. forwards*: IHosub1_2 sub1 H3. apply subset_union_elim. apply* subset_union_introl. apply* subset_union_intror . } 1 : { (*case and*) inverts osub2. forwards*: IHosub1_1 sub1 H1. forwards*: IHosub1_2 sub1 H3. apply subset_inter_elim_inv. apply* subset_inter_eliml. apply* subset_inter_elimr. } 1 : { (* TVar *) forwards*: okt_binds_ground H. assert (osubfvar : OSubtypes PG (E & Z ~*: P & F) (t_fvar X) (all_ord PG `dif` l)). eauto. forwards*: osubs_narrowing_tvar osubfvar osub2. } Qed. (* Disjointness Narrowing *) (* Lemma 26 *) Lemma disj_narrowing : forall PG Q F E Z P S T, PG; (E & Z ~*: P & F) |= S *a T -> sub PG E P Q -> groundtype Q -> PG; (E & Z ~*: Q & F) |= S *a T. Proof. unfold DisjAlgo. intros. destructs H. forwards*(_&WFP&WFQ&ok): sub_regular H0. forwards*: okt_narrow H2 WFQ. splits; auto. apply wft_narrow with (V:=P); auto. apply wft_narrow with (V:=P); auto. introv osubs. destruct osubs as [osub1 osub2]. forwards* (l3&osub3): exists_osubtypes H2 H3. forwards* (l4&osub4): exists_osubtypes H2 H4. forwards*: H5 l3 l4. assert (OSubtypes PG (E & Z ~*: P & F) (t_and S T) (l3 `inter` l4)) by auto. rewrite H7 in H8. forwards*: osubs_narrowing_empty H8 H0. forwards*: okt_concat_inv_tt H2. apply subset_empty_empty in H9. auto. Qed. (********************************************) (** Typing Narrowing **) Lemma typing_narrowing : forall PG Q E F X P e T, sub PG E P Q -> typing PG (E & X ~*: P & F) e T -> groundtype Q -> typing PG (E & X ~*: Q & F) e T. Proof. introv PsubQ Typ GQ. gen_eq : (E & X ~*: P & F) as E'. gen F. forwards*: sub_regular PsubQ. destructs H. induction Typ; introv EQ; subst; auto. - apply* typ_lit. apply* okt_narrow. - apply* typ_null. apply* okt_narrow. - binds_cases H5. apply* typ_var. apply* okt_narrow. apply* typ_var. apply* okt_narrow. - apply* typ_app. - apply* typ_sub. forwards*: sub_narrowing_aux H3 PsubQ. forwards* (_&_&_&TEMP1): sub_regular H3. apply* okt_narrow. - pick_fresh y. apply typ_abs with (L:=(((((((((L \u \{ X}) \u fv_ee e) \u fv_te e) \u fv_tt Q) \u fv_tt P) \u fv_tt A) \u fv_tt B) \u dom E) \u dom F)); intros; auto. apply* okt_narrow. apply_ih_bind* H6. - pick_fresh y. apply typ_typeof with (L:=((((((((((((((L \u \{ X}) \u fv_ee e) \u fv_ee e1) \u fv_ee e2) \u fv_te e) \u fv_te e1) \u fv_te e2) \u fv_tt Q) \u fv_tt P) \u fv_tt A) \u fv_tt B) \u fv_tt C) \u dom E) \u dom F)) ; intros; auto. apply_ih_bind* H4. apply_ih_bind* H6. (* TODO: need some work here *) apply* disj_narrowing. - pick_fresh Y. apply typ_tabs with (L:=(((((((((L \u \{ X}) \u fv_ee e) \u fv_te e) \u fv_tt Q) \u fv_tt P) \u fv_tt A) \u fv_tt B) \u dom E) \u dom F)); intros; auto. apply* okt_narrow. apply_ih_bind* H6. - apply* typ_tapp. (* TODO: need some work here *) apply* disj_narrowing. Qed. (** Disjointness Strengthening *) Lemma disj_strengthening : forall PG x U E F S T, PG; (E & x ~: U & F) |= S *a T -> PG; (E & F) |= S *a T. Proof. unfold DisjAlgo. intros PG x U E F S T SsubT. destructs SsubT. splits; autos*. apply wft_strengthen in H1; auto. apply wft_strengthen in H2; auto. intros. destruct H4 as [OSub1 OSub2]. apply H3. split. apply* osubs_weaken. apply* osubs_weaken. Qed. (* Preservation through term substitution *) Lemma typing_through_subst_ee : forall PG E F x T e u U, typing PG (E & x ~: U & F) e T -> typing PG E u U -> typing PG (E & F) (subst_ee x u e) T. Proof. introv TypT TypU. lets TypT': TypT. inductions TypT; simpl. (*case int*) - apply* typ_lit. - (*case null*) apply* typ_null. (*case var*) - case_var. + binds_get H1. apply ok_from_okt in H; auto. lets M: (typing_weakening PG E F empty u U). do 2 rewrite concat_empty_r in M. apply* M. + binds_cases H1; apply* typ_var. (*case app*) - eapply typ_app; eauto. (*case sub*) - forwards* : IHTypT E F TypU TypT. eapply typ_sub; eauto. apply sub_strengthening in H; auto. (*case abs*) - pick_fresh y. apply typ_abs with (L:=((((((((((L \u \{ x}) \u fv_ee u) \u fv_ee e) \u fv_te u) \u fv_te e) \u fv_tt U) \u fv_tt A) \u fv_tt B) \u dom E) \u dom F)); intros; autos*. assert (x0 \notin L) by auto. specialize (H2 x0 H4 E (F & x0 ~: A)). rewrite* subst_ee_open_ee_var. lets : H2 x U. forwards* : H5. rewrite~ concat_assoc. rewrite~ concat_assoc. rewrite~ <- concat_assoc. apply typing_regular in TypU. destructs~ TypU. (*case typeof*) - pick_fresh y. apply typ_typeof with (L:=(((((((((((((((L \u \{ x}) \u fv_ee u) \u fv_ee e) \u fv_ee e1) \u fv_ee e2) \u fv_te u) \u fv_te e) \u fv_te e1) \u fv_te e2) \u fv_tt U) \u fv_tt A) \u fv_tt B) \u fv_tt C) \u dom E) \u dom F)); intros; eauto. + rewrite* subst_ee_open_ee_var. forwards*: H x0. forwards*: H0 x0 E (F & x0 ~: A) x. rewrite~ concat_assoc. rewrite~ concat_assoc. rewrite~ <- concat_assoc. apply typing_regular in TypU. destructs~ TypU. + rewrite* subst_ee_open_ee_var. forwards*: H1 x0. forwards*: H2 x0 E (F & x0 ~: B) x. rewrite~ concat_assoc. rewrite~ concat_assoc. rewrite~ <- concat_assoc. apply typing_regular in TypU. destructs~ TypU. + (* need work here *) apply disj_strengthening in H3; auto. - apply* typ_inter. - pick_fresh Y. apply typ_tabs with (L:=((((((((((L \u \{ x}) \u fv_ee u) \u fv_ee e) \u fv_te u) \u fv_te e) \u fv_tt U) \u fv_tt A) \u fv_tt B) \u dom E) \u dom F)); intros; autos*. assert (X \notin L) by auto. specialize (H1 X H4). rewrite* subst_ee_open_te_var. lets : H2 X H4 E (F & X ~*: A) x. lets : H5 U. forwards*: H6. rewrite~ concat_assoc. rewrite~ concat_assoc. rewrite~ <- concat_assoc. apply typing_regular in TypU. destructs~ TypU. - eapply typ_tapp; eauto. (* need work here *) apply disj_strengthening in H; auto. Qed. Lemma okt_subst_tb : forall PG Q Z P E F, okt PG (E & Z ~*: Q & F) -> wft PG E P -> okt PG (E & map (subst_tb Z P) F). Proof. induction F using env_ind; intros Ok WP. - (*case F = empty*) rewrite concat_empty_r in Ok. rewrite map_empty. rewrite concat_empty_r. apply okt_push_inv_tt in Ok. destructs~ Ok. - (*case F = x ~ v*) rewrite concat_assoc in Ok. (* destruc ~ to ~:* and ~: *) destruct v. apply okt_push_inv_tt in Ok. destructs Ok. forwards*: IHF. rewrite map_concat. rewrite map_single. simpl. forwards*: okt_disj PG (E & (map (subst_tb Z P) F)) x (subst_tt Z P t). apply ok_from_okt in H3. forwards*: wft_subst_tb H1 H3. apply type_from_wft in WP. forwards*: subst_groundtype H2 WP. rewrite~ concat_assoc. apply okt_push_inv in Ok. destructs Ok. forwards*: IHF. rewrite map_concat. rewrite map_single. simpl. forwards*: okt_typ PG (E & (map (subst_tb Z P) F)) x (subst_tt Z P t). apply ok_from_okt in H2. forwards*: wft_subst_tb H1 H2. rewrite~ concat_assoc. Qed. (* ********************************************************************** *) (** Type substitution in Types Preserves Subtyping *) Lemma sub_through_subst_tt : forall PG Q E F Z S T P, sub PG (E & Z ~*: Q & F) S T -> PG; E |= P *a Q -> okt PG ((E & map (subst_tb Z P) F)) -> sub PG (E & map (subst_tb Z P) F) (subst_tt Z P S) (subst_tt Z P T). Proof. introv SsubT PsubQ ok. gen_eq : (E & Z ~*: Q & F) as G. gen F. induction SsubT; introv okt EQ; subst; simpl subst_tt; eauto. - (*case top*) forwards*: ok_from_okt okt. forwards*: disj_regular PsubQ. destructs H3. forwards*: wft_subst_tb H1 H2. - (*case A <: A1 | A2*) forwards* Sub: IHSsubT. forwards* OK: ok_from_okt okt. forwards* (okp&okte&WFP&WFQ): disj_regular PsubQ. forwards*: wft_subst_tb H OK. - (*case A <: A1 | A2*) forwards* Sub: IHSsubT. forwards* OK: ok_from_okt okt. forwards* (okp&okte&WFP&WFQ): disj_regular PsubQ. forwards*: wft_subst_tb H OK. - (*case A1 & A2 <: A*) forwards* Sub: IHSsubT. forwards* OK: ok_from_okt okt. forwards* (okp&okte&WFP&WFQ): disj_regular PsubQ. forwards*: wft_subst_tb H OK. - (*case A1 & A2 <: A*) forwards* Sub: IHSsubT. forwards* OK: ok_from_okt okt. forwards* (okp&okte&WFP&WFQ): disj_regular PsubQ. forwards*: wft_subst_tb H OK. - (*case bot <: A*) forwards* OK: ok_from_okt okt. forwards* (okp&okte&WFP&WFQ): disj_regular PsubQ. forwards*: wft_subst_tb H1 OK. - (*case fvar*) case_var. forwards*: disj_regular PsubQ. apply* sub_refl. apply* wft_weaken_right. apply ok_from_okt in okt. auto. forwards* OK: ok_from_okt okt. forwards*: disj_regular PsubQ. apply* sub_refl. forwards*: wft_subst_tb H1 OK. rewrite~ (subst_tt_fresh Z P (t_fvar X)) in H3. simpl. auto. - (*case all*) forwards* Sub: IHSsubT. forwards* OK: ok_from_okt okt. forwards* (okp&okte&WFP&WFQ): disj_regular PsubQ. pick_fresh Y. apply s_all with (L:=( ((((((((L \u \{ Z}) \u fv_tt Q) \u fv_tt P) \u fv_tt S1) \u fv_tt S2) \u fv_tt T1) \u fv_tt T2) \u dom E) \u dom F)); auto; intros. apply type_from_wft in WFP. apply* subst_groundtype. forwards*: H1 X (F & X ~*: T1). rewrite map_concat. rewrite map_single. simpl. rewrite concat_assoc. apply* okt_disj. forwards* (_&_&WFT1&_): sub_regular SsubT. forwards*: wft_subst_tb WFT1 WFP OK. apply type_from_wft in WFP. assert (NOTIN: X \notin L) by auto. specialize (H0 X). apply H0 in NOTIN. forwards* (_&_&_&TEMP1): sub_regular NOTIN. apply okt_push_inv_tt in TEMP1. destructs TEMP1. apply* subst_groundtype. rewrite~ concat_assoc. rewrite map_concat in H3. rewrite map_single in H3. unsimpl_map_bind. rewrite~ (subst_tt_open_tt_var). rewrite~ (subst_tt_open_tt_var). rewrite~ concat_assoc in H3. apply type_from_wft in WFP; auto. apply type_from_wft in WFP; auto. - (*case Prim*) forwards* OK: ok_from_okt okt. forwards* (okp&okte&WFP&WFQ): disj_regular PsubQ. apply* sub_refl. forwards*: wft_subst_tb H1 OK. - (*case Prim*) forwards* OK: ok_from_okt okt. forwards* (okp&okte&WFP&WFQ): disj_regular PsubQ. apply* s_p_sub. forwards*: wft_subst_tb H1 OK. forwards*: wft_subst_tb H2 OK. Qed. (************************************************************************ *) (** Preservation by Type Substitution of Types in Terms *) Lemma notin_fv_wf : forall PG E X T, wft PG E T -> X # E -> X \notin fv_tt T. Proof. induction 1; intros Fr; simpl; eauto. rewrite notin_singleton. intro. subst. apply Fr. apply binds_get in H. apply get_none in Fr. rewrite H in Fr. inverts Fr. notin_simpl; auto. pick_fresh Y. forwards*: H1 Y. apply* (@notin_fv_tt_open Y). Qed. (************************************************************************ *) (** ** Type substitution preserves typing *) Lemma map_subst_tb_id : forall PG G Z P, okt PG G -> Z \notin dom G -> G = map (subst_tb Z P) G. Proof with auto. intros PG G Z P H. induction H; simpl; intros Fr. rewrite~ map_empty. forwards*: IHokt. rewrite map_concat. rewrite map_single. simpl. rewrite (subst_tt_fresh Z P T); eauto. rewrite H2 at 1; auto. forwards*: notin_fv_wf Z H0. forwards*: IHokt. rewrite map_concat. rewrite map_single. simpl. rewrite (subst_tt_fresh Z P T); eauto. rewrite H3 at 1; auto. forwards*: notin_fv_wf Z H0. Qed. (********************************************) (** Substitution Preserves Disjointness **) Lemma osubs_gtype_subst_unique : forall PG E1 T l1, groundtype T -> OSubtypes PG E1 T l1 -> forall E2 Z P l2, OSubtypes PG E2 (subst_tt Z P T) l2 -> l1 = l2. Proof. introv GT osub1. induction osub1; introv osub2; simpl in *; try solve [inverts GT]; try solve [inverts osub2; auto]. - (*case union*) inverts GT. inverts osub2. forwards* EQ1: IHosub1_1 H3. forwards* EQ2: IHosub1_2 H5. subst. auto. - (*case and*) inverts GT. inverts osub2. forwards* EQ1: IHosub1_1 H3. forwards* EQ2: IHosub1_2 H5. subst. auto. Qed. Lemma osubs_subst_disj_tvar : forall PG Q F E Z P X l1, OSubtypes PG (E & Z ~*: Q & F) (t_fvar X) l1 -> okt PG (E & Z ~*: Q & F) -> DisjAlgo PG E P Q -> groundtype P -> groundtype Q -> okt PG (E & map (subst_tb Z P) F) -> forall l2, OSubtypes PG (E & map (subst_tb Z P) F) (t_fvar X) l2 -> subset l2 l1. Proof. introv osub1 Ok sub1 GP GQ Ok1 osub2. gen P l2. inductions osub1; auto; intros; try solve [inverts subtvar]. - (*case TVar*) inverts osub2. forwards* TEMP1: disj_regular sub1. forwards* GT: okt_binds_ground Ok H. forwards* GT0: okt_binds_ground Ok1 H1. binds_cases H. binds_cases H1. apply binds_get in B0. apply binds_get in B. rewrite B0 in B. inverts B. forwards* EQ1: groundtype_osubs_env_unique osub1 H2. rewrite EQ1. (* reflexivity *) apply subset_refl. (* contradiction of Fr and B1 *) apply binds_get in B1. apply get_some_inv in B1. rewrite dom_map in B1. contradiction. binds_cases H1. apply binds_get in B. apply get_some_inv in B. apply okt_concat_inv_tt in Ok. destructs Ok. contradiction. apply binds_get in B0. apply get_some_inv in B0. rewrite dom_map in B0. contradiction. binds_cases H1. unfold "#" in Fr. rewrite dom_map in Fr. apply binds_get in B0. apply get_some_inv in B0. contradiction. apply binds_map with (f:=(subst_tb Z P)) in B0. apply binds_get in B1. apply binds_get in B0. rewrite B0 in B1. inverts B1. forwards* EQ: osubs_gtype_subst_unique osub1 H2. subst. apply subset_refl. Qed. Lemma inter_no_common_l : forall (l1 l2 : list typ), (l1 `inter` l2) = [] -> forall t, set_In t l1 -> ~ (set_In t l2). Proof. unfold not. intros. forwards*: set_inter_intro eq_dec H0 H1. rewrite H in H2. inverts H2. Qed. Lemma inter_no_common_r : forall (l1 l2 : list typ), (l1 `inter` l2) = [] -> forall t, set_In t l2 -> ~ (set_In t l1). Proof. unfold not. intros. forwards*: set_inter_intro eq_dec H1 H0. rewrite H in H2. inverts H2. Qed. Lemma osub_in_all_ord : forall PG E P l, groundtype P -> OSubtypes PG E P l -> wft PG E P -> forall t, set_In t l -> set_In t (all_ord PG). Proof. introv GP osub WFP. induction osub; introv IN. (*case top*) auto. (*case bot*) inverts IN. (*case int*) simpl in IN. simpl. destruct IN as [IN | IN]. subst. auto. inverts IN. (*case arrow*) simpl in IN. simpl. destruct IN as [IN | IN]. subst. auto. inverts IN. (*case union*) inverts GP. inverts WFP. apply set_union_elim in IN. destruct IN as [IN | IN]; auto. (*case and*) inverts GP. inverts WFP. apply set_inter_elim1 in IN; auto. (*case unit*) simpl in IN. simpl. destruct IN as [IN | IN]. subst. auto. inverts IN. (*case Tfvar*) inverts GP. (*case all*) simpl in IN. simpl. destruct IN as [IN | IN]. subst. auto. inverts IN. (*case P*) inverts WFP. simpl. right. right. right. right. simpl in IN. destruct IN as [IN | IN]. subst. apply* i_in_nat_to_types. apply allsubtypes_in_to_domain in IN. auto. Qed. Lemma osub_disjoint_types_subset : forall P, groundtype P -> forall PG E1 l1, OSubtypes PG E1 P l1 -> wft PG E1 P -> forall E2 Q l2, groundtype Q -> OSubtypes PG E2 Q l2 -> forall E3, OSubtypes PG E3 (t_and P Q) [] -> subset l1 ((all_ord PG) `dif` l2). Proof. introv GP osub1 WFP GQ osub2 Disj. unfold subset. introv IN. apply set_diff_intro. forwards*: osub_in_all_ord osub1. unfold not. introv TEMP. inverts Disj. forwards*: groundtype_osubs_env_unique osub1 H2. subst. forwards*: groundtype_osubs_env_unique osub2 H3. subst. forwards*: inter_no_common_l H1 IN. Qed. Lemma osubtypes_subst_disj_empty : forall PG Q F E Z P S l1, OSubtypes PG (E & Z ~*: Q & F) S l1 -> okt PG (E & Z ~*: Q & F) -> DisjAlgo PG E P Q -> groundtype P -> groundtype Q -> wft PG (E & map (subst_tb Z P) F) P -> forall l2, OSubtypes PG (E & map (subst_tb Z P) F) (subst_tt Z P S) l2 -> subset l2 l1. Proof. introv osub1 Ok sub1 GP GQ WFMP osub2. gen P l2. induction osub1; auto; intros; try solve [inverts osub2; apply subset_refl]. 1 :{ (*case union*) inverts osub2. forwards*: IHosub1_1 sub1 H1. forwards*: IHosub1_2 sub1 H3. apply subset_union_elim. apply* subset_union_introl. apply* subset_union_intror . } 1 : { (*case and*) inverts osub2. forwards*: IHosub1_1 sub1 H1. forwards*: IHosub1_2 sub1 H3. apply subset_inter_elim_inv. apply* subset_inter_eliml. apply* subset_inter_elimr. } 1 : { (* TVar *) forwards*: okt_binds_ground H. assert (osubfvar : OSubtypes PG (E & Z ~*: Q & F) (t_fvar X) (all_ord PG `dif` l)). eauto. unfold subst_tt in osub2. case_var. apply binds_middle_eq_inv in H. inverts H. unfold DisjAlgo in sub1. destruct sub1 as [okp [ok1 [WFP [WFQ Disj1]]]]. forwards* (l5&osubp): exists_osubtypes ok1 WFP. forwards* (l6&osubq): exists_osubtypes ok1 WFQ. forwards* DisjPQ: Disj1 l5 l6. assert (OSUBSPQ: OSubtypes PG E (t_and P Q) (l5 `inter` l6)) by auto. rewrite DisjPQ in OSUBSPQ. forwards*: osub_disjoint_types_subset osub2 osub1 OSUBSPQ. apply* ok_from_okt. forwards*: osubs_subst_disj_tvar osub2. apply* okt_subst_tb. forwards*: disj_regular sub1. } Qed. (* Disjointness Substitution *) (* Lemma 25 *) Lemma disj_subst : forall PG Q E F Z A B P, PG; (E & Z ~*: Q & F) |= A *a B -> PG; E |= P *a Q -> groundtype P -> okt PG (E & map (subst_tb Z P) F) -> PG; (E & map (subst_tb Z P) F) |= (subst_tt Z P A) *a (subst_tt Z P B). Proof. introv Disj1 Disj2 GP ok. unfold DisjAlgo in Disj1. destruct Disj1 as [okp [ok1 [WFA [WFB Disj1]]]]. forwards* (_&ok2&WFP&WFQ&_): Disj2. forwards* ok': ok_from_okt ok. splits; auto. forwards*: wft_subst_tb WFA WFP. forwards*: wft_subst_tb WFB WFP. introv OSubs. destruct OSubs as [OSub1 OSub2]. forwards* (l3&osuba): exists_osubtypes ok1 WFA. forwards* (l4&osubb): exists_osubtypes ok1 WFB. forwards* DisjAB: Disj1 l3 l4. assert (DisjAB': OSubtypes PG (E & Z ~*: Q & F) (t_and A B) (l3 `inter` l4)) by auto. rewrite DisjAB in DisjAB'. (* rewrite DisjPQ in DisjPQ'. *) assert (DisjABsubst: OSubtypes PG (E & map (subst_tb Z P) F) (t_and (subst_tt Z P A) (subst_tt Z P B)) (l1 `inter` l2)) by auto. forwards*: osubtypes_subst_disj_empty DisjAB' ok1 Disj2 DisjABsubst. forwards*: okt_concat_inv_tt ok1. apply subset_empty_empty in H. auto. Qed. (* type substitution preserves typing *) Lemma typing_through_subst_te : forall PG Q E F Z e T P, typing PG (E & Z ~*: Q & F) e T -> groundtype P -> PG; E |= P *a Q -> okt PG (E & map (subst_tb Z P) F) -> typing PG (E & map (subst_tb Z P) F) (subst_te Z P e) (subst_tt Z P T). Proof. introv Typ GP Disj Ok. gen_eq : (E & Z ~*: Q & F) as G. gen F. induction Typ; introv Ok EQ; subst; simpls subst_tt; simpls subst_te. - apply* typ_lit. - apply* typ_null. - apply* typ_var. binds_cases H1. + apply okt_concat_inv_tt in H. destruct H as [oke [znote [znotf _]]]. forwards*: wft_from_env_has_typ B0. forwards*: notin_fv_wf H. forwards*: subst_tt_fresh P H1. rewrite H2. apply* binds_concat_left. + apply* binds_concat_right. unsimpl_map_bind. apply* binds_map. - eapply typ_app; eauto. - forwards*: IHTyp F. lets TEMP: sub_through_subst_tt. specialize (TEMP PG Q E F Z B A P H Disj Ok). (apply typ_sub with (B:=(subst_tt Z P B))); auto. - pick_fresh y. apply typ_abs with (L:=(((((((((L \u \{ Z}) \u fv_ee e) \u fv_te e) \u fv_tt Q) \u fv_tt P) \u fv_tt A) \u fv_tt B) \u dom E) \u dom F)); auto. intros. forwards*: H2 x (F & x ~: A). (*repeatition*) rewrite map_concat. rewrite map_single. simpl. rewrite concat_assoc. apply* okt_typ. assert (NOTIN: x \notin L) by auto. apply (H1 x) in NOTIN. forwards* TEMP: NOTIN. apply typing_regular in TEMP. destruct TEMP as [okp [okt [LC _]]]. apply okt_push_inv in okt. destruct okt as [okt [_ WFA ]]. forwards*(_&_&WFP&_): disj_regular Disj. apply ok_from_okt in Ok. forwards*: wft_subst_tb WFA WFP. (*repeatition end*) rewrite~ concat_assoc. rewrite map_concat in H4. rewrite map_single in H4. unsimpl_map_bind. rewrite (subst_te_open_ee_var). rewrite~ concat_assoc in H4. - pick_fresh y. apply typ_typeof with (L:=((((((((((((((L \u \{ Z}) \u fv_ee e) \u fv_ee e1) \u fv_ee e2) \u fv_te e) \u fv_te e1) \u fv_te e2) \u fv_tt Q) \u fv_tt P) \u fv_tt A) \u fv_tt B) \u fv_tt C) \u dom E) \u dom F)); auto; intros. forwards* : H0 x (F & x ~: A). (*repeatition*) rewrite map_concat. rewrite map_single. simpl. rewrite concat_assoc. apply* okt_typ. assert (NOTIN: x \notin L) by auto. apply (H x) in NOTIN. forwards* TEMP: NOTIN. apply typing_regular in TEMP. destruct TEMP as [okp [okt [LC _]]]. apply okt_push_inv in okt. destruct okt as [okt [_ WFA ]]. forwards*(_&_&WFP&_): disj_regular Disj. apply ok_from_okt in Ok. forwards*: wft_subst_tb WFA WFP. (*repeatition end*) rewrite~ concat_assoc. rewrite map_concat in H5. rewrite map_single in H5. unsimpl_map_bind. rewrite concat_assoc in H5. rewrite~ subst_te_open_ee_var. forwards*: H2 x (F & x ~: B). (*repeatition*) rewrite map_concat. rewrite map_single. simpl. rewrite concat_assoc. apply* okt_typ. assert (NOTIN: x \notin L) by auto. apply (H1 x) in NOTIN. forwards* TEMP: NOTIN. apply typing_regular in TEMP. destruct TEMP as [okp [okt [LC _]]]. apply okt_push_inv in okt. destruct okt as [okt [_ WFA ]]. forwards*(_&_&WFP&_): disj_regular Disj. apply ok_from_okt in Ok. forwards*: wft_subst_tb WFA WFP. (*repeatition end*) rewrite~ concat_assoc. rewrite map_concat in H5. rewrite map_single in H5. unsimpl_map_bind. rewrite concat_assoc in H5. rewrite~ subst_te_open_ee_var. (* lemma that substitution preserves disjointness *) forwards*: disj_subst H3 Disj. - apply* typ_inter. - pick_fresh Y. apply typ_tabs with (L:=(((((((((L \u \{ Z}) \u fv_ee e) \u fv_te e) \u fv_tt Q) \u fv_tt P) \u fv_tt A) \u fv_tt B) \u dom E) \u dom F)); auto. intros. forwards*: H1 X. forwards*: H2 X (F & X ~*: A). (*repeatition*) rewrite map_concat. rewrite map_single. simpl. rewrite concat_assoc. apply* okt_disj. assert (NOTIN: X \notin L) by auto. apply (H1 X) in NOTIN. forwards* TEMP: NOTIN. apply typing_regular in TEMP. destruct TEMP as [okp [okt [LC _]]]. apply okt_push_inv_tt in okt. destruct okt as [okt [_ WFA ]]. forwards*(_&_&WFP&_): disj_regular Disj. apply ok_from_okt in Ok. forwards*: wft_subst_tb WFA WFP. forwards* (_&TEMP1&_): typing_regular H4. apply okt_push_inv_tt in TEMP1. destructs TEMP1. forwards* (_&TEMP1&WFP&_): disj_regular Disj. apply type_from_wft in WFP. apply* subst_groundtype. (*repeatition end*) rewrite~ concat_assoc. forwards*: disj_regular Disj. rewrite map_concat in H5. rewrite map_single in H5. unsimpl_map_bind. rewrite~ subst_te_open_te_var. rewrite~ concat_assoc in H5. rewrite~ subst_tt_open_tt_var. forwards*(_&_&WFP&_): disj_regular. apply type_from_wft in WFP; auto. forwards*(_&_&WFP&_): disj_regular. apply type_from_wft in WFP; auto. - rewrite subst_tt_open_tt. apply* typ_tapp. (* lemma that substitution preserves disjointness *) forwards*: disj_subst H Disj. apply* subst_groundtype. apply disj_regular in Disj. destructs Disj. apply type_from_wft in H3; auto. apply disj_regular in Disj. destructs Disj. apply type_from_wft in H3; auto. Qed. (* ********************************************************************** *) (** Typing inversion lemmas *) Lemma inv_int : forall PG E A i5, typing PG E (e_lit i5) A -> typing PG E (e_lit i5) t_int /\ sub PG E t_int A. Proof. introv Typ. inductions Typ. (*case typ_int*) - split*. (*case typ_sub*) - specialize (IHTyp i5). forwards* : IHTyp. destruct H0. split*. eapply sub_transitivity; eauto. - forwards* : IHTyp1. destruct H. forwards* : IHTyp2. Qed. Lemma abs_typ_arrow_sub : forall PG G e A, typing PG G (e_abs e) A -> exists A1 B1, sub PG G (t_arrow A1 B1) A. Proof. introv Typ. inductions Typ. - forwards* : IHTyp. destruct H0 as [x1[x2 H3]]. exists x1 x2. eapply sub_transitivity; eauto. - exists* A B. pick_fresh x. forwards* : H1 x. apply typing_regular in H3. destructs H3. apply okt_push_inv in H4. destructs~ H4. rewrite (@append_empty_right (G & x ~: A)) in H6. apply wft_strengthen in H6. rewrite~ <- (@append_empty_right G) in H6. - forwards* : IHTyp1. forwards* : IHTyp2. destruct H as [x1 [x2 H3]]. destruct H0 as [x3 [x4 H4]]. exists t_top t_bot. apply s_anda. forwards* : sub_regular H3. destructs H. apply typing_regular in Typ1. destructs~ Typ1. inverts H0. assert (sub PG G (t_arrow t_top t_bot) (t_arrow x1 x2)); eauto. eapply sub_transitivity; eauto. forwards* : sub_regular H4. destructs H. apply typing_regular in Typ2. destructs Typ2. inverts H0. assert (sub PG G (t_arrow t_top t_bot) (t_arrow x3 x4)); eauto. eapply sub_transitivity; eauto. Qed. Lemma abs_typ_all_sub : forall PG G e A B, typing PG G (e_tabs A e) B -> exists A1 B1, sub PG G (t_all A1 B1) B. Proof. introv Typ. inductions Typ. - forwards* : IHTyp. destruct H0 as [x1[x2 H3]]. exists x1 x2. eapply sub_transitivity; eauto. - forwards~ : IHTyp1. forwards~ : IHTyp2. destruct H as [x1 [x2 H3]]. destruct H0 as [x3 [x4 H4]]. exists t_bot t_bot. apply s_anda. + forwards* (?&?&?&?): sub_regular H3. inverts H0. assert (sub PG G (t_all t_bot t_bot) (t_all x1 x2)); auto. pick_fresh Y. apply s_all with (L:=((((((((((L \u fv_ee e) \u fv_te e) \u fv_tt A) \u fv_tt A0) \u fv_tt B) \u fv_tt x1) \u fv_tt x2) \u fv_tt x3) \u fv_tt x4) \u dom G)); intros; auto. eapply sub_transitivity; eauto. + forwards* (?&?&?&?): sub_regular H4. inverts H0. assert (sub PG G (t_all t_bot t_bot) (t_all x3 x4)). pick_fresh Y. apply s_all with (L:=((((((((((L \u fv_ee e) \u fv_te e) \u fv_tt A) \u fv_tt A0) \u fv_tt B) \u fv_tt x1) \u fv_tt x2) \u fv_tt x3) \u fv_tt x4) \u dom G)); intros; auto. eapply sub_transitivity; eauto. - exists t_bot t_bot. pick_fresh Y. apply s_all with (L:=(((((L \u fv_ee e) \u fv_te e) \u fv_tt A) \u fv_tt B) \u dom G)); intros; auto. forwards* : H1 Y. forwards* (?&?&?&?) : typing_regular H3. apply okt_push_inv_tt in H5. destructs~ H5. forwards* : H1 X. forwards* (?&?&?&?) : typing_regular H4. Qed. Lemma inv_and_arrow : forall PG G e A1 A2 B1 B2, typing PG G (e_abs e) (t_and A1 A2) -> sub PG G (t_and A1 A2) (t_arrow B1 B2) -> sub PG G A1 (t_arrow B1 B2) \/ sub PG G A2 (t_arrow B1 B2). Proof. introv Typ Sub. inverts Sub; eauto. Qed. Lemma inv_and_all : forall PG G e A1 A2 B1 B2 A, typing PG G (e_tabs A e) (t_and A1 A2) -> sub PG G (t_and A1 A2) (t_all B1 B2) -> sub PG G A1 (t_all B1 B2) \/ sub PG G A2 (t_all B1 B2). Proof. introv Typ Sub. inverts Sub; eauto. Qed. Lemma inv_abs_sub : forall PG G e A B1 B2, typing PG G (e_abs e) A -> sub PG G A (t_arrow B1 B2) -> exists C1 C2, (exists L, forall x , x \notin L -> typing PG (G & x ~: C1) (e open_ee_var x) C2) /\ sub PG G (t_arrow C1 C2) (t_arrow B1 B2). Proof. introv Typ Sub. inductions Typ; eauto. - assert (HS: sub PG G B (t_arrow B1 B2)) by applys sub_transitivity H Sub. forwards* (?&?&?&?): IHTyp HS. - forwards* [HS|HS]: inv_and_arrow Sub. Qed. Lemma inv_all_sub : forall PG G e A B B1 B2, typing PG G (e_tabs A e) B -> sub PG G B (t_all B1 B2) -> exists C1 C2, (exists L, forall X , X \notin L -> typing PG (G & X ~*: B1) (e open_te_var X) (C2 open_tt_var X)) /\ sub PG G (t_all C1 C2) (t_all B1 B2). Proof. introv Typ Sub. inductions Typ; eauto. - assert (HS: sub PG G B (t_all B1 B2)) by applys sub_transitivity H Sub. forwards* (?&?&?&?): IHTyp HS. - forwards* : inv_and_all Sub. - exists* A B. split*. exists L. intros. inverts Sub. forwards*: H1 X. rewrite (append_empty_right (G & X ~*: B1)). apply typing_narrowing with (P:=A); auto. rewrite~ concat_empty_r. pick_fresh Y. forwards*: H11 Y. forwards* (_&_&_&TEMP1): sub_regular H5. apply okt_push_inv_tt in TEMP1. destructs~ TEMP1. Qed. Lemma inv_arrow : forall PG G e A1 A2, typing PG G (e_abs e) (t_arrow A1 A2) -> exists B1 B2, (exists L, forall x , x \notin L -> typing PG (G & x ~: B1) (e open_ee_var x) B2) /\ sub PG G (t_arrow B1 B2) (t_arrow A1 A2). Proof. introv Typ. inverts Typ. - forwards* : inv_abs_sub H. - exists A1 A2. split*. pick_fresh x. forwards* : H5 x. forwards* (?&?&?&?): typing_regular H. apply okt_push_inv in H1. destructs H1. rewrite (@append_empty_right (G & x ~: A1)) in H6. apply wft_strengthen in H6. rewrite~ <- (@append_empty_right G) in H6. Qed. Lemma inv_all : forall PG G e A A1 A2, typing PG G (e_tabs A e) (t_all A1 A2) -> exists B1 B2, (exists L, forall X , X \notin L -> typing PG (G & X ~*: A1) (e open_te_var X) (B2 open_tt_var X)) /\ sub PG G (t_all B1 B2) (t_all A1 A2). Proof. introv Typ. inverts Typ. - forwards* : inv_all_sub H. - exists A1 A2. split*. pick_fresh Y. apply s_all with (L:=(((((L \u fv_ee e) \u fv_te e) \u fv_tt A1) \u fv_tt A2) \u dom G)); intros; auto. forwards* : H6 Y. forwards*(?&?&?&?): typing_regular H. apply okt_push_inv_tt in H1. destructs~ H1. forwards* : H6 Y. apply typing_regular in H. destructs H. apply okt_push_inv_tt in H0. destructs~ H0. forwards* : H6 X. apply typing_regular in H0. destructs H0. apply okt_push_inv_tt in H1. destructs H1. apply* sub_refl. Qed. Lemma inv_abs_union : forall PG G e A A1 A2, typing PG G (e_abs e) A -> sub PG G A (t_union A1 A2) -> typing PG G (e_abs e) A1 \/ typing PG G (e_abs e) A2. Proof. introv Typ Sub. inductions Typ; eauto. - eapply sub_transitivity in Sub; eauto. - inverts* Sub. - inverts* Sub. Qed. Lemma inv_all_union : forall PG G e A B A1 A2, typing PG G (e_tabs A e) B -> sub PG G B (t_union A1 A2) -> typing PG G (e_tabs A e) A1 \/ typing PG G (e_tabs A e) A2. Proof. introv Typ Sub. inductions Typ; eauto. - eapply sub_transitivity in Sub; eauto. - inverts* Sub. - inverts* Sub. Qed. Lemma inv_null : forall PG E A, typing PG E e_null A -> typing PG E e_null t_unit /\ sub PG E t_unit A. Proof. introv Typ. inductions Typ. (*case typ_int*) - split*. (*case typ_sub*) - forwards* : IHTyp. destruct H0. split*. eapply sub_transitivity; eauto. - forwards* : IHTyp1. Qed. Lemma inv_P : forall PG E P A, typing PG E (e_new P) A -> typing PG E (e_new P) (t_prim P) /\ sub PG E (t_prim P) A. Proof. introv Typ. inductions Typ. (*case typ_int*) - forwards*: IHTyp. destruct H0. split*. eapply sub_transitivity; eauto. (*case typ_sub*) - forwards*: IHTyp1. forwards*: IHTyp2. Qed. Lemma check_or_typ : forall PG E e A B, value e -> typing PG E e (t_union A B) -> typing PG E e A \/ typing PG E e B. Proof. introv Val Typ. inverts Val. (*subsumption again*) - apply inv_int in Typ. destruct Typ. inverts* H0. - inverts Typ. eapply inv_abs_union in H0; eauto. - apply inv_null in Typ. destruct Typ. inverts* H0. - inverts Typ. eapply inv_all_union in H0; eauto. - apply inv_P in Typ. destruct Typ. inverts* H0. Qed. (********************************************************) (** A value cannot check against disjoint types **) Lemma val_check_disjoint_types : forall PG E v A B, PG; E |= A *a B -> value v -> typing PG E v A -> typing PG E v B -> False. Proof. introv Disj Val Typ1 Typ2. unfold DisjAlgo in Disj. forwards*(OKP&OK&LC&WFA): typing_regular Typ1. forwards*(_&_&_&WFB): typing_regular Typ2. forwards* (l1&EX1): exists_osubtypes A WFA. forwards* (l2&EX2): exists_osubtypes B WFB. assert (OSSubs: OSubtypes PG E A l1 /\ OSubtypes PG E B l2) by auto. destruct Disj as [_ [_ [ _ [_ Disj]]]]. specialize (Disj l1 l2). apply Disj in OSSubs. clear Disj. inverts Val. - apply inv_int in Typ1. destruct Typ1. apply inv_int in Typ2. destruct Typ2. assert (SUB : sub PG E t_int (t_and A B)) by auto. forwards*: ord_sub_findsubtypes_not_empty SUB. - apply abs_typ_arrow_sub in Typ1. destruct Typ1 as [A1 [B1]]. assert (sub PG E (t_arrow t_top t_bot) (t_arrow A1 B1)). forwards* (?&?&?&?): sub_regular H0. inverts* H2. apply abs_typ_arrow_sub in Typ2. destruct Typ2 as [A2 [B2]]. assert (sub PG E (t_arrow t_top t_bot) (t_arrow A2 B2)). forwards* (?&?&?&?): sub_regular H2. inverts* H4. eapply sub_transitivity with (A:=(t_arrow t_top t_bot)) (B:=(t_arrow A1 B1)) (C:=A) in H1; auto. eapply sub_transitivity with (A:=(t_arrow t_top t_bot)) (B:=(t_arrow A2 B2)) (C:=B) in H3; auto. assert (SUB : sub PG E (t_arrow t_top t_bot) (t_and A B)) by auto. forwards*: ord_sub_findsubtypes_not_empty SUB. - apply inv_null in Typ1. destruct Typ1. apply inv_null in Typ2. destruct Typ2. assert (SUB : sub PG E t_unit (t_and A B)) by auto. forwards*: ord_sub_findsubtypes_not_empty SUB. - apply abs_typ_all_sub in Typ1. destruct Typ1 as [A1 [B1]]. forwards* (?&?&?&?): sub_regular H0. inverts H2. assert (sub PG E (t_all t_bot t_bot) (t_all A1 B1)). pick_fresh Y. apply s_all with (L:=((((((((L \u fv_ee e) \u fv_te e) \u fv_tt A) \u fv_tt B) \u fv_tt T) \u fv_tt A1) \u fv_tt B1) \u dom E)); intros; auto. apply abs_typ_all_sub in Typ2. destruct Typ2 as [A2 [B2]]. forwards* (?&?&?&?): sub_regular H5. inverts H8. assert (sub PG E (t_all t_bot t_bot) (t_all A2 B2)). pick_fresh Y. apply s_all with (L:=(((((((((((L \u L0) \u fv_ee e) \u fv_te e) \u fv_tt A) \u fv_tt B) \u fv_tt T) \u fv_tt A2) \u fv_tt B2) \u fv_tt A1) \u fv_tt B1) \u dom E)); intros; auto. eapply sub_transitivity with (A:=(t_all t_bot t_bot)) (B:=(t_all A1 B1)) (C:=A) in H0; auto. eapply sub_transitivity with (A:=(t_all t_bot t_bot)) (B:=(t_all A2 B2)) (C:=B) in H5; auto. assert (SUB : sub PG E (t_all t_bot t_bot) (t_and A B)) by auto. forwards*: ord_sub_findsubtypes_not_empty SUB. - apply inv_P in Typ1. destruct Typ1. apply inv_P in Typ2. destruct Typ2. assert (SUB : sub PG E (t_prim P) (t_and A B)) by auto. forwards*: ord_sub_findsubtypes_not_empty SUB. Qed. (*******************************************************) (** findtype gives least type of an expressions **) Lemma check_find_type : forall PG E e A B, typing PG E e A -> findtype e B -> sub PG E B A. Proof. introv Typ Find. inductions Find. - apply inv_int in Typ. destruct~ Typ. - apply abs_typ_arrow_sub in Typ. destruct Typ as [A1 [B1]]. forwards* (?&?&?&?): sub_regular H0. inverts H2. assert (sub PG E (t_arrow t_top t_bot) (t_arrow A1 B1)) by auto. eapply sub_transitivity; eauto. - apply inv_null in Typ. destruct~ Typ. - apply abs_typ_all_sub in Typ. destruct Typ as [A1 [B1]]. forwards* (?&?&?&?): sub_regular H. inverts H1. assert (sub PG E (t_all t_bot t_bot) (t_all A1 B1)). pick_fresh Y. apply s_all with (L:=(((((((L \u fv_ee e) \u fv_te e) \u fv_tt A) \u fv_tt T) \u fv_tt A1) \u fv_tt B1) \u dom E)); intros; auto. eapply sub_transitivity; eauto. - apply inv_P in Typ. destruct~ Typ. Qed. (**************************************************************) (** An ordinary type cannot be subtype of disjoint types **) Lemma sub_ord_disjoint_types : forall PG E A B, PG; E |= A *a B -> forall C, Ord C -> sub PG E C A -> sub PG E C B -> False. Proof. introv Disj Ord SubA SubB. unfold DisjAlgo in Disj. forwards*(OKP&WFC&WFA&OK): sub_regular SubA. forwards*(_&_&WFB&_): sub_regular SubB. forwards* (l1&EX1): exists_osubtypes A WFA. forwards* (l2&EX2): exists_osubtypes B WFB. assert (OSSubs: OSubtypes PG E A l1 /\ OSubtypes PG E B l2) by auto. destruct Disj as [_ [_ [ _ [_ Disj]]]]. specialize (Disj l1 l2). apply Disj in OSSubs. clear Disj. assert (Sub: sub PG E C (t_and A B)) by auto. forwards*: ord_sub_findsubtypes_not_empty Ord Sub. Qed. (********************************************) (** Values have ordinary types **) Lemma findtype_ord_type : forall v A, findtype v A -> Ord A. Proof. introv Find. inverts* Find. Qed. (**************************************) (**** Type Preservation Theorem *****) (**************************************) Lemma preservation : forall PG E e e' T, typing PG E e T -> step PG E e e' -> typing PG E e' T. Proof. introv Typ. gen e'. induction Typ; introv Red; try solve [ inverts* Red ]. - (* app *) inverts* Red. (* beta *) forwards* : inv_arrow Typ1. destruct H as [A1[B1 [H H']]]. destruct H as [L]. pick_fresh x. assert (x \notin L) by auto. lets: H x H0. assert (G & x ~: A1 = G & x ~: A1 & empty). rewrite* concat_empty_r. rewrite H4 in H2. assert (G = G & empty). rewrite* concat_empty_r. rewrite H5. lets: typing_through_subst_ee. inverts H'. forwards* : H6 H2. rewrite* (@subst_ee_intro x). apply typ_sub with (B:=B1). auto. rewrite concat_empty_r. auto. - (* typeof *) inverts* Red. + (* value checks against disjoint types *) lets temp: check_or_typ G e A B H11. lets DisjOr: temp Typ. destruct DisjOr. * (*true goal*) pick_fresh y. assert (y \notin L) by auto. forwards* : H H5. assert (G & y ~: A = G & y ~: A & empty). rewrite* concat_empty_r. rewrite H7 in H6. assert (G = G & empty). rewrite* concat_empty_r. rewrite H8. forwards* : typing_through_subst_ee. rewrite* (@subst_ee_intro y). * (*false goal, value e checks against disjoint types A and B*) lets temp1: check_find_type G e B C0 H4. lets SubB: temp1 H12. inverts H12; forwards*: sub_ord_disjoint_types H3 H13 SubB. + (* value checks against disjoint types *) lets temp: check_or_typ G e A B H11. lets DisjOr: temp Typ. destruct DisjOr. * (*false goal, value e checks against disjoint types A and B*) lets temp1: check_find_type G e A C0 H4. lets SubA: temp1 H12. inverts H12; forwards*: sub_ord_disjoint_types H3 SubA H13. * (*true goal*) pick_fresh y. assert (y \notin L) by auto. forwards* : H1 H5. assert (G & y ~: B = G & y ~: B & empty). rewrite* concat_empty_r. rewrite H7 in H6. assert (G = G & empty). rewrite* concat_empty_r. rewrite H8. forwards* : typing_through_subst_ee. rewrite* (@subst_ee_intro y). - forwards* : IHTyp1. - (* case tapp *) inverts* Red. clear IHTyp. forwards* : inv_all Typ. destruct H1 as [A1[B1 [H' H'']]]. destruct H' as [L]. inverts H''. pick_fresh X. forwards*: H1 X. forwards*: H11 X. rewrite* (@subst_te_intro X). rewrite* (@subst_tt_intro X). rewrite (append_empty_right G). rewrite <- (map_empty ((subst_tb X A))). apply* (typing_through_subst_te PG B). rewrite* concat_empty_r. rewrite* map_empty. rewrite concat_empty_r. forwards*: sub_regular H9. Qed. (*********************************) (****** Progress Theorem *******) (*********************************) Lemma progress : forall PG e T, typing PG empty e T -> (value e) \/ (exists e', step PG empty e e'). Proof. introv Typ. gen_eq E: (@empty typ). lets Typ': Typ. inductions Typ; intros EQ; subst. (*case int*) - left*. (*case null*) - left*. (*case var*) - apply binds_empty_inv in H1. inversion H1. (*case typ-app*) - right. forwards* : IHTyp1. destruct H. + forwards* : IHTyp2. destruct H0. * inverts* H. (*i infers arrow*) apply inv_int in Typ1. destruct Typ1. inverts H1. apply inv_null in Typ1. destruct Typ1. inverts H1. apply abs_typ_all_sub in Typ1. destruct Typ1 as [A1 [B1]]. inverts H. apply inv_P in Typ1. destruct Typ1. inverts H1. (*case step-appl*) * destruct H0. exists* (e_app e1 x). (*case step-appr*) + destruct H. exists (e_app x e2). apply* step_appl. forwards* : typing_regular Typ2. (*case typ-sub*) - forwards* : IHTyp. (*case typ-abs*) - left. forwards* : typing_regular Typ'. (*case typ-typeof*) - right. forwards* : IHTyp. destruct H4. + apply check_or_typ in Typ; auto. destruct Typ. (*case typeofl*) * destruct H4. { (*case e = int*) apply inv_int in H5. destruct H5. exists (open_ee e1 (e_lit i5)). pick_fresh y. assert (y \notin L) by auto. lets: H y H6. eapply step_typeofl with (C:=t_int); eauto. forwards* : typing_regular Typ'. } { (*case e = \x.e*) apply abs_typ_arrow_sub in H5. destruct H5 as [A1 [B1]]. forwards* : sub_regular H5. destructs H6. inverts H7. assert (sub PG empty (t_arrow t_top t_bot) (t_arrow A1 B1)) by auto. eapply sub_transitivity in H5; eauto. exists (open_ee e1 (e_abs e)). pick_fresh y. forwards*: H y. eapply step_typeofl with (C:=(t_arrow t_top t_bot)); eauto. forwards* : typing_regular Typ'. } { (*case e = null*) apply inv_null in H5. destruct H5. exists (open_ee e1 e_null). pick_fresh y. assert (y \notin L) by auto. lets: H y H6. eapply step_typeofl with (C:=t_unit); eauto. forwards* : typing_regular Typ'. } { (* case e = e A *) apply abs_typ_all_sub in H5. destruct H5 as [A1 [B1]]. forwards*(?&?&?&?): sub_regular H5. inverts H7. assert (sub PG empty (t_all t_bot t_bot) (t_all A1 B1)). pick_fresh Y. apply s_all with (L:=(((((((((((((L \u L0) \u fv_ee e1) \u fv_ee e2) \u fv_ee e) \u fv_te e1) \u fv_te e2) \u fv_te e) \u fv_tt A) \u fv_tt B) \u fv_tt C) \u fv_tt T) \u fv_tt A1) \u fv_tt B1)); auto. eapply sub_transitivity in H5; eauto. exists (open_ee e1 (e_tabs T e)). pick_fresh y. forwards*: H y. eapply step_typeofl with (C:=(t_all t_bot t_bot)); eauto. forwards* : typing_regular Typ'. } { (* case e = e_new *) apply inv_P in H5. destruct H5. exists (open_ee e1 (e_new P)). pick_fresh y. assert (y \notin L) by auto. lets: H y H6. eapply step_typeofl with (C:=(t_prim P)); eauto. forwards* : typing_regular Typ'. } * (*case typeofr*) destruct H4. apply inv_int in H5. destruct H5. { (*case e = int*) exists (open_ee e2 (e_lit i5)). pick_fresh y. assert (y \notin L) by auto. lets: H1 y H6. eapply step_typeofr with (C:=t_int); eauto. forwards* : typing_regular Typ'. } { (*case e = \x.e*) apply abs_typ_arrow_sub in H5. destruct H5 as [A1 [B1]]. forwards* : sub_regular H5. destructs H6. inverts H7. assert (sub PG empty (t_arrow t_top t_bot) (t_arrow A1 B1)) by auto. eapply sub_transitivity in H5; eauto. exists (open_ee e2 (e_abs e)). pick_fresh y. forwards*: H1 y. eapply step_typeofr with (C:=(t_arrow t_top t_bot)); eauto. forwards* : typing_regular Typ'. } { (*case e = null*) apply inv_null in H5. destruct H5. exists (open_ee e2 e_null). pick_fresh y. forwards*: H y. eapply step_typeofr with (C:=t_unit); eauto. forwards* : typing_regular Typ'. } { (* case e = e A *) apply abs_typ_all_sub in H5. destruct H5 as [A1 [B1]]. forwards*(?&?&?&?): sub_regular H5. inverts H7. assert (sub PG empty (t_all t_bot t_bot) (t_all A1 B1)). pick_fresh Y. apply s_all with (L:=((((((((((((L \u L0) \u fv_ee e1) \u fv_ee e2) \u fv_ee e) \u fv_te e1) \u fv_te e2) \u fv_te e) \u fv_tt A) \u fv_tt B) \u fv_tt C) \u fv_tt T) \u fv_tt A1) \u fv_tt B1); auto. eapply sub_transitivity in H5; eauto. exists (open_ee e2 (e_tabs T e)). pick_fresh y. forwards*: H y. eapply step_typeofr with (C:=(t_all t_bot t_bot)); eauto. forwards* : typing_regular Typ'. } { (* case e = e_new *) apply inv_P in H5. destruct H5. exists (open_ee e2 (e_new P)). pick_fresh y. forwards*: H y. eapply step_typeofr with (C:=(t_prim P)); eauto. forwards* : typing_regular Typ'. } + (*case typeof*) destruct H4. exists (e_typeof x A e1 B e2). apply step_typeof; auto. forwards* : typing_regular Typ'. - forwards* : IHTyp1. - left. apply* val_tabs. forwards* : typing_regular Typ'. - (*case typ-app*) right. forwards* : IHTyp. destruct H1. + inverts* H1. (*i infers arrow*) apply inv_int in Typ. destruct Typ. inverts H2. apply abs_typ_arrow_sub in Typ. destruct Typ as [A1 [B1]]. inverts H1. apply inv_null in Typ. destruct Typ. inverts H2. exists ((open_te e0 A)). apply* step_tabs. apply typing_regular in Typ'. destructs~ Typ'. inverts~ H4. apply inv_P in Typ. destruct Typ. inverts H2. (*case step-appl*) + destruct H1. exists* (e_tapp x A). apply* step_tapp. apply typing_regular in Typ'. destructs Typ'. inverts~ H4. Qed. (****************************************************) (** More typing inversion properties *) Lemma inv_app : forall PG E e1 e2 A, typing PG E (e_app e1 e2) A -> exists A1 B1, typing PG E e1 (t_arrow A1 B1) /\ typing PG E e2 A1. Proof. introv Typ. inductions Typ. - exists* A B. - specialize (IHTyp e1 e2). forwards* : IHTyp. - forwards* : IHTyp1. Qed. Lemma inv_typeof : forall PG E e e1 e2 A B C, typing PG E (e_typeof e A e1 B e2) C -> exists D, typing PG E e D /\ PG; E |= A *a B. Proof. introv Typ. inductions Typ. - specialize (IHTyp e e1 e2 A B). forwards* : IHTyp. - exists* (t_union A B). - forwards* : IHTyp1. Qed. Lemma inv_tapp : forall PG E e A B, typing PG E (e_tapp e A) B -> exists A1 A2, typing PG E e (t_all A1 A2). Proof. introv Typ. inductions Typ. - forwards* : IHTyp. - forwards* : IHTyp1. - exists* B C. Qed. (********************************************) (** Value is normal form **) Lemma value_not_step : forall PG E v e', value v -> step PG E v e' -> False. Proof. intros. inverts H; try solve [inverts H0]. Qed. (********************************************) (** findtype uniqueness **) Lemma findtype_unique : forall v A B, findtype v A -> findtype v B -> A = B. Proof. introv TypA TypB. inverts TypA; inverts* TypB. Qed. (*********************************) (***** Determinism Theorem *****) (*********************************) Lemma determinism : forall PG E e e1 e2 A, typing PG E e A -> step PG E e e1 -> step PG E e e2 -> e1 = e2. Proof. introv Typ He1. gen e2 A. induction He1; introv Typ He2. (*case step-appl*) - inverts* He2. + apply inv_app in Typ. destruct Typ as [A1 [B1]]. destruct H0. forwards* : IHHe1. rewrite* H3. + inverts* H2; inverts He1. + inverts* He1. (*case step-appr*) - inverts* He2. + inverts* H; inverts* H4. + apply inv_app in Typ. destruct Typ as [A1 [B1]]. destruct H0. forwards* : IHHe1 H1. rewrite* H3. + inverts H4; inverts He1. (*case step-beta*) - inverts* He2. + inverts* H5. + inverts H0; inverts H5. (*case step-typeof*) - inverts* He2. + apply inv_typeof in Typ. destruct Typ as [D]. destruct H0. forwards* : IHHe1. rewrite* H2. + inverts H8; inverts He1. + inverts H8; inverts He1. (*case step-typeofl*) - inverts* He2. + apply value_not_step in H10; eauto. inverts H10. + apply inv_typeof in Typ. destruct Typ as [D]. destruct H3 as [H3 Disj]. forwards*: findtype_unique H1 H11. subst. forwards*: findtype_ord_type H1. forwards*: sub_ord_disjoint_types Disj H2 H12. (*case step-typeofr*) - inverts* He2. + inverts H0; inverts H10. + apply inv_typeof in Typ. destruct Typ as [D]. destruct H3 as [H3 Disj]. forwards*: findtype_unique H1 H11. subst. forwards*: findtype_ord_type H1. forwards*: sub_ord_disjoint_types Disj H12 H2. (*case step-tapp*) - inverts He2. + apply inv_tapp in Typ. destruct Typ as [A1 [A2]]. forwards* : IHHe1 H0. rewrite~ H1. + inverts He1. - inverts* He2. inverts H5. Qed.
\section{Hypothesis testing}
/- Copyright (c) 2022 Jujian Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jujian Zhang, Junyan Xu ! This file was ported from Lean 3 source module topology.sheaves.skyscraper ! leanprover-community/mathlib commit 70fd9563a21e7b963887c9360bd29b2393e6225a ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathbin.Topology.Sheaves.Punit import Mathbin.Topology.Sheaves.Stalks import Mathbin.Topology.Sheaves.Functors /-! # Skyscraper (pre)sheaves A skyscraper (pre)sheaf `𝓕 : (pre)sheaf C X` is the (pre)sheaf with value `A` at point `p₀` that is supported only at open sets contain `p₀`, i.e. `𝓕(U) = A` if `p₀ ∈ U` and `𝓕(U) = *` if `p₀ ∉ U` where `*` is a terminal object of `C`. In terms of stalks, `𝓕` is supported at all specializations of `p₀`, i.e. if `p₀ ⤳ x` then `𝓕ₓ ≅ A` and if `¬ p₀ ⤳ x` then `𝓕ₓ ≅ *`. ## Main definitions * `skyscraper_presheaf`: `skyscraper_presheaf p₀ A` is the skyscraper presheaf at point `p₀` with value `A`. * `skyscraper_sheaf`: the skyscraper presheaf satisfies the sheaf condition. ## Main statements * `skyscraper_presheaf_stalk_of_specializes`: if `y ∈ closure {p₀}` then the stalk of `skyscraper_presheaf p₀ A` at `y` is `A`. * `skyscraper_presheaf_stalk_of_not_specializes`: if `y ∉ closure {p₀}` then the stalk of `skyscraper_presheaf p₀ A` at `y` is `*` the terminal object. TODO: generalize universe level when calculating stalks, after generalizing universe level of stalk. -/ noncomputable section open TopologicalSpace TopCat CategoryTheory CategoryTheory.Limits Opposite universe u v w variable {X : TopCat.{u}} (p₀ : X) [∀ U : Opens X, Decidable (p₀ ∈ U)] section variable {C : Type v} [Category.{w} C] [HasTerminal C] (A : C) /-- A skyscraper presheaf is a presheaf supported at a single point: if `p₀ ∈ X` is a specified point, then the skyscraper presheaf `𝓕` with value `A` is defined by `U ↦ A` if `p₀ ∈ U` and `U ↦ *` if `p₀ ∉ A` where `*` is some terminal object. -/ @[simps] def skyscraperPresheaf : Presheaf C X where obj U := if p₀ ∈ unop U then A else terminal C map U V i := if h : p₀ ∈ unop V then eqToHom <| by erw [if_pos h, if_pos (le_of_hom i.unop h)] else ((if_neg h).symm.rec terminalIsTerminal).from _ map_id' U := (em (p₀ ∈ U.unop)).elim (fun h => dif_pos h) fun h => ((if_neg h).symm.rec terminalIsTerminal).hom_ext _ _ map_comp' U V W iVU iWV := by by_cases hW : p₀ ∈ unop W · have hV : p₀ ∈ unop V := le_of_hom iWV.unop hW simp only [dif_pos hW, dif_pos hV, eq_to_hom_trans] · rw [dif_neg hW] apply ((if_neg hW).symm.rec terminal_is_terminal).hom_ext #align skyscraper_presheaf skyscraperPresheaf theorem skyscraperPresheaf_eq_pushforward [hd : ∀ U : Opens (TopCat.of PUnit.{u + 1}), Decidable (PUnit.unit ∈ U)] : skyscraperPresheaf p₀ A = ContinuousMap.const (TopCat.of PUnit) p₀ _* skyscraperPresheaf PUnit.unit A := by convert_to@skyscraperPresheaf X p₀ (fun U => hd <| (opens.map <| ContinuousMap.const _ p₀).obj U) C _ _ A = _ <;> first |congr |rfl #align skyscraper_presheaf_eq_pushforward skyscraperPresheaf_eq_pushforward /-- Taking skyscraper presheaf at a point is functorial: `c ↦ skyscraper p₀ c` defines a functor by sending every `f : a ⟶ b` to the natural transformation `α` defined as: `α(U) = f : a ⟶ b` if `p₀ ∈ U` and the unique morphism to a terminal object in `C` if `p₀ ∉ U`. -/ @[simps] def SkyscraperPresheafFunctor.map' {a b : C} (f : a ⟶ b) : skyscraperPresheaf p₀ a ⟶ skyscraperPresheaf p₀ b where app U := if h : p₀ ∈ U.unop then eqToHom (if_pos h) ≫ f ≫ eqToHom (if_pos h).symm else ((if_neg h).symm.rec terminalIsTerminal).from _ naturality' U V i := by simp only [skyscraperPresheaf_map]; by_cases hV : p₀ ∈ V.unop · have hU : p₀ ∈ U.unop := le_of_hom i.unop hV split_ifs simpa only [eq_to_hom_trans_assoc, category.assoc, eq_to_hom_trans] · apply ((if_neg hV).symm.rec terminal_is_terminal).hom_ext #align skyscraper_presheaf_functor.map' SkyscraperPresheafFunctor.map' theorem SkyscraperPresheafFunctor.map'_id {a : C} : SkyscraperPresheafFunctor.map' p₀ (𝟙 a) = 𝟙 _ := by ext1; ext1; simp only [SkyscraperPresheafFunctor.map'_app, nat_trans.id_app]; split_ifs · simp only [category.id_comp, category.comp_id, eq_to_hom_trans, eq_to_hom_refl] · apply ((if_neg h).symm.rec terminal_is_terminal).hom_ext #align skyscraper_presheaf_functor.map'_id SkyscraperPresheafFunctor.map'_id theorem SkyscraperPresheafFunctor.map'_comp {a b c : C} (f : a ⟶ b) (g : b ⟶ c) : SkyscraperPresheafFunctor.map' p₀ (f ≫ g) = SkyscraperPresheafFunctor.map' p₀ f ≫ SkyscraperPresheafFunctor.map' p₀ g := by ext1; ext1; simp only [SkyscraperPresheafFunctor.map'_app, nat_trans.comp_app]; split_ifs · simp only [category.assoc, eq_to_hom_trans_assoc, eq_to_hom_refl, category.id_comp] · apply ((if_neg h).symm.rec terminal_is_terminal).hom_ext #align skyscraper_presheaf_functor.map'_comp SkyscraperPresheafFunctor.map'_comp /-- Taking skyscraper presheaf at a point is functorial: `c ↦ skyscraper p₀ c` defines a functor by sending every `f : a ⟶ b` to the natural transformation `α` defined as: `α(U) = f : a ⟶ b` if `p₀ ∈ U` and the unique morphism to a terminal object in `C` if `p₀ ∉ U`. -/ @[simps] def skyscraperPresheafFunctor : C ⥤ Presheaf C X where obj := skyscraperPresheaf p₀ map _ _ := SkyscraperPresheafFunctor.map' p₀ map_id' _ := SkyscraperPresheafFunctor.map'_id p₀ map_comp' _ _ _ := SkyscraperPresheafFunctor.map'_comp p₀ #align skyscraper_presheaf_functor skyscraperPresheafFunctor end section -- In this section, we calculate the stalks for skyscraper presheaves. -- We need to restrict universe level. variable {C : Type v} [Category.{u} C] (A : C) [HasTerminal C] /-- The cocone at `A` for the stalk functor of `skyscraper_presheaf p₀ A` when `y ∈ closure {p₀}` -/ @[simps] def skyscraperPresheafCoconeOfSpecializes {y : X} (h : p₀ ⤳ y) : Cocone ((OpenNhds.inclusion y).op ⋙ skyscraperPresheaf p₀ A) where pt := A ι := { app := fun U => eqToHom <| if_pos <| h.mem_open U.unop.1.2 U.unop.2 naturality' := fun U V inc => by change dite _ _ _ ≫ _ = _; rw [dif_pos] · erw [category.comp_id, eq_to_hom_trans] rfl · exact h.mem_open V.unop.1.2 V.unop.2 } #align skyscraper_presheaf_cocone_of_specializes skyscraperPresheafCoconeOfSpecializes /-- The cocone at `A` for the stalk functor of `skyscraper_presheaf p₀ A` when `y ∈ closure {p₀}` is a colimit -/ noncomputable def skyscraperPresheafCoconeIsColimitOfSpecializes {y : X} (h : p₀ ⤳ y) : IsColimit (skyscraperPresheafCoconeOfSpecializes p₀ A h) where desc c := eqToHom (if_pos trivial).symm ≫ c.ι.app (op ⊤) fac c U := by rw [← c.w (hom_of_le <| (le_top : unop U ≤ _)).op] change _ ≫ _ ≫ dite _ _ _ ≫ _ = _ rw [dif_pos] · simpa only [skyscraperPresheafCoconeOfSpecializes_ι_app, eq_to_hom_trans_assoc, eq_to_hom_refl, category.id_comp] · exact h.mem_open U.unop.1.2 U.unop.2 uniq c f h := by rw [← h, skyscraperPresheafCoconeOfSpecializes_ι_app, eq_to_hom_trans_assoc, eq_to_hom_refl, category.id_comp] #align skyscraper_presheaf_cocone_is_colimit_of_specializes skyscraperPresheafCoconeIsColimitOfSpecializes /-- If `y ∈ closure {p₀}`, then the stalk of `skyscraper_presheaf p₀ A` at `y` is `A`. -/ noncomputable def skyscraperPresheafStalkOfSpecializes [HasColimits C] {y : X} (h : p₀ ⤳ y) : (skyscraperPresheaf p₀ A).stalk y ≅ A := colimit.isoColimitCocone ⟨_, skyscraperPresheafCoconeIsColimitOfSpecializes p₀ A h⟩ #align skyscraper_presheaf_stalk_of_specializes skyscraperPresheafStalkOfSpecializes /-- The cocone at `*` for the stalk functor of `skyscraper_presheaf p₀ A` when `y ∉ closure {p₀}` -/ @[simps] def skyscraperPresheafCocone (y : X) : Cocone ((OpenNhds.inclusion y).op ⋙ skyscraperPresheaf p₀ A) where pt := terminal C ι := { app := fun U => terminal.from _ naturality' := fun U V inc => terminalIsTerminal.hom_ext _ _ } #align skyscraper_presheaf_cocone skyscraperPresheafCocone /-- The cocone at `*` for the stalk functor of `skyscraper_presheaf p₀ A` when `y ∉ closure {p₀}` is a colimit -/ noncomputable def skyscraperPresheafCoconeIsColimitOfNotSpecializes {y : X} (h : ¬p₀ ⤳ y) : IsColimit (skyscraperPresheafCocone p₀ A y) := let h1 : ∃ U : OpenNhds y, p₀ ∉ U.1 := let ⟨U, ho, h₀, hy⟩ := not_specializes_iff_exists_open.mp h ⟨⟨⟨U, ho⟩, h₀⟩, hy⟩ { desc := fun c => eqToHom (if_neg h1.choose_spec).symm ≫ c.ι.app (op h1.some) fac := fun c U => by change _ = c.ι.app (op U.unop) simp only [← c.w (hom_of_le <| @inf_le_left _ _ h1.some U.unop).op, ← c.w (hom_of_le <| @inf_le_right _ _ h1.some U.unop).op, ← category.assoc] congr 1 refine' ((if_neg _).symm.rec terminal_is_terminal).hom_ext _ _ exact fun h => h1.some_spec h.1 uniq := fun c f H => by rw [← category.id_comp f, ← H, ← category.assoc] congr 1; apply terminal_is_terminal.hom_ext } #align skyscraper_presheaf_cocone_is_colimit_of_not_specializes skyscraperPresheafCoconeIsColimitOfNotSpecializes /-- If `y ∉ closure {p₀}`, then the stalk of `skyscraper_presheaf p₀ A` at `y` is isomorphic to a terminal object. -/ noncomputable def skyscraperPresheafStalkOfNotSpecializes [HasColimits C] {y : X} (h : ¬p₀ ⤳ y) : (skyscraperPresheaf p₀ A).stalk y ≅ terminal C := colimit.isoColimitCocone ⟨_, skyscraperPresheafCoconeIsColimitOfNotSpecializes _ A h⟩ #align skyscraper_presheaf_stalk_of_not_specializes skyscraperPresheafStalkOfNotSpecializes /-- If `y ∉ closure {p₀}`, then the stalk of `skyscraper_presheaf p₀ A` at `y` is a terminal object -/ def skyscraperPresheafStalkOfNotSpecializesIsTerminal [HasColimits C] {y : X} (h : ¬p₀ ⤳ y) : IsTerminal ((skyscraperPresheaf p₀ A).stalk y) := IsTerminal.ofIso terminalIsTerminal <| (skyscraperPresheafStalkOfNotSpecializes _ _ h).symm #align skyscraper_presheaf_stalk_of_not_specializes_is_terminal skyscraperPresheafStalkOfNotSpecializesIsTerminal theorem skyscraperPresheaf_isSheaf : (skyscraperPresheaf p₀ A).IsSheaf := by classical exact (presheaf.is_sheaf_iso_iff (eq_to_iso <| skyscraperPresheaf_eq_pushforward p₀ A)).mpr (sheaf.pushforward_sheaf_of_sheaf _ (presheaf.is_sheaf_on_punit_of_is_terminal _ (by dsimp rw [if_neg] exact terminal_is_terminal exact Set.not_mem_empty PUnit.unit))) #align skyscraper_presheaf_is_sheaf skyscraperPresheaf_isSheaf /-- The skyscraper presheaf supported at `p₀` with value `A` is the sheaf that assigns `A` to all opens `U` that contain `p₀` and assigns `*` otherwise. -/ def skyscraperSheaf : Sheaf C X := ⟨skyscraperPresheaf p₀ A, skyscraperPresheaf_isSheaf _ _⟩ #align skyscraper_sheaf skyscraperSheaf /-- Taking skyscraper sheaf at a point is functorial: `c ↦ skyscraper p₀ c` defines a functor by sending every `f : a ⟶ b` to the natural transformation `α` defined as: `α(U) = f : a ⟶ b` if `p₀ ∈ U` and the unique morphism to a terminal object in `C` if `p₀ ∉ U`. -/ def skyscraperSheafFunctor : C ⥤ Sheaf C X where obj c := skyscraperSheaf p₀ c map a b f := Sheaf.Hom.mk <| (skyscraperPresheafFunctor p₀).map f map_id' c := Sheaf.Hom.ext _ _ <| (skyscraperPresheafFunctor p₀).map_id _ map_comp' _ _ _ f g := Sheaf.Hom.ext _ _ <| (skyscraperPresheafFunctor p₀).map_comp _ _ #align skyscraper_sheaf_functor skyscraperSheafFunctor namespace StalkSkyscraperPresheafAdjunctionAuxs variable [HasColimits C] /-- If `f : 𝓕.stalk p₀ ⟶ c`, then a natural transformation `𝓕 ⟶ skyscraper_presheaf p₀ c` can be defined by: `𝓕.germ p₀ ≫ f : 𝓕(U) ⟶ c` if `p₀ ∈ U` and the unique morphism to a terminal object if `p₀ ∉ U`. -/ @[simps] def toSkyscraperPresheaf {𝓕 : Presheaf C X} {c : C} (f : 𝓕.stalk p₀ ⟶ c) : 𝓕 ⟶ skyscraperPresheaf p₀ c where app U := if h : p₀ ∈ U.unop then 𝓕.germ ⟨p₀, h⟩ ≫ f ≫ eqToHom (if_pos h).symm else ((if_neg h).symm.rec terminalIsTerminal).from _ naturality' U V inc := by dsimp; by_cases hV : p₀ ∈ V.unop · have hU : p₀ ∈ U.unop := le_of_hom inc.unop hV split_ifs erw [← category.assoc, 𝓕.germ_res inc.unop, category.assoc, category.assoc, eq_to_hom_trans] rfl · split_ifs apply ((if_neg hV).symm.rec terminal_is_terminal).hom_ext #align stalk_skyscraper_presheaf_adjunction_auxs.to_skyscraper_presheaf StalkSkyscraperPresheafAdjunctionAuxs.toSkyscraperPresheaf /-- If `f : 𝓕 ⟶ skyscraper_presheaf p₀ c` is a natural transformation, then there is a morphism `𝓕.stalk p₀ ⟶ c` defined as the morphism from colimit to cocone at `c`. -/ def fromStalk {𝓕 : Presheaf C X} {c : C} (f : 𝓕 ⟶ skyscraperPresheaf p₀ c) : 𝓕.stalk p₀ ⟶ c := let χ : Cocone ((OpenNhds.inclusion p₀).op ⋙ 𝓕) := Cocone.mk c <| { app := fun U => f.app (op U.unop.1) ≫ eqToHom (if_pos U.unop.2) naturality' := fun U V inc => by dsimp; erw [category.comp_id, ← category.assoc, comp_eq_to_hom_iff, category.assoc, eq_to_hom_trans, f.naturality, skyscraperPresheaf_map] have hV : p₀ ∈ (open_nhds.inclusion p₀).obj V.unop := V.unop.2; split_ifs simpa only [comp_eq_to_hom_iff, category.assoc, eq_to_hom_trans, eq_to_hom_refl, category.comp_id] } colimit.desc _ χ #align stalk_skyscraper_presheaf_adjunction_auxs.from_stalk StalkSkyscraperPresheafAdjunctionAuxs.fromStalk theorem to_skyscraper_fromStalk {𝓕 : Presheaf C X} {c : C} (f : 𝓕 ⟶ skyscraperPresheaf p₀ c) : toSkyscraperPresheaf p₀ (fromStalk _ f) = f := NatTrans.ext _ _ <| funext fun U => (em (p₀ ∈ U.unop)).elim (fun h => by dsimp split_ifs erw [← category.assoc, colimit.ι_desc, category.assoc, eq_to_hom_trans, eq_to_hom_refl, category.comp_id] rfl) fun h => by dsimp split_ifs apply ((if_neg h).symm.rec terminal_is_terminal).hom_ext #align stalk_skyscraper_presheaf_adjunction_auxs.to_skyscraper_from_stalk StalkSkyscraperPresheafAdjunctionAuxs.to_skyscraper_fromStalk theorem fromStalk_to_skyscraper {𝓕 : Presheaf C X} {c : C} (f : 𝓕.stalk p₀ ⟶ c) : fromStalk p₀ (toSkyscraperPresheaf _ f) = f := colimit.hom_ext fun U => by erw [colimit.ι_desc] dsimp rw [dif_pos U.unop.2] rw [category.assoc, category.assoc, eq_to_hom_trans, eq_to_hom_refl, category.comp_id, presheaf.germ] congr 3 apply_fun Opposite.unop using unop_injective rw [unop_op] ext rfl #align stalk_skyscraper_presheaf_adjunction_auxs.from_stalk_to_skyscraper StalkSkyscraperPresheafAdjunctionAuxs.fromStalk_to_skyscraper /-- The unit in `presheaf.stalk ⊣ skyscraper_presheaf_functor` -/ @[simps] protected def unit : 𝟭 (Presheaf C X) ⟶ Presheaf.stalkFunctor C p₀ ⋙ skyscraperPresheafFunctor p₀ where app 𝓕 := toSkyscraperPresheaf _ <| 𝟙 _ naturality' 𝓕 𝓖 f := by ext U; dsimp; split_ifs · simp only [category.id_comp, ← category.assoc] rw [comp_eq_to_hom_iff] simp only [category.assoc, eq_to_hom_trans, eq_to_hom_refl, category.comp_id] erw [colimit.ι_map] rfl · apply ((if_neg h).symm.rec terminal_is_terminal).hom_ext #align stalk_skyscraper_presheaf_adjunction_auxs.unit StalkSkyscraperPresheafAdjunctionAuxs.unit /-- The counit in `presheaf.stalk ⊣ skyscraper_presheaf_functor` -/ @[simps] protected def counit : skyscraperPresheafFunctor p₀ ⋙ (Presheaf.stalkFunctor C p₀ : Presheaf C X ⥤ C) ⟶ 𝟭 C where app c := (skyscraperPresheafStalkOfSpecializes p₀ c specializes_rfl).Hom naturality' x y f := colimit.hom_ext fun U => by erw [← category.assoc, colimit.ι_map, colimit.iso_colimit_cocone_ι_hom_assoc, skyscraperPresheafCoconeOfSpecializes_ι_app, category.assoc, colimit.ι_desc, whiskering_left_obj_map, whisker_left_app, SkyscraperPresheafFunctor.map'_app, dif_pos U.unop.2, skyscraperPresheafCoconeOfSpecializes_ι_app, comp_eq_to_hom_iff, category.assoc, eq_to_hom_comp_iff, ← category.assoc, eq_to_hom_trans, eq_to_hom_refl, category.id_comp, comp_eq_to_hom_iff, category.assoc, eq_to_hom_trans, eq_to_hom_refl, category.comp_id, CategoryTheory.Functor.id_map] #align stalk_skyscraper_presheaf_adjunction_auxs.counit StalkSkyscraperPresheafAdjunctionAuxs.counit end StalkSkyscraperPresheafAdjunctionAuxs section open StalkSkyscraperPresheafAdjunctionAuxs /-- `skyscraper_presheaf_functor` is the right adjoint of `presheaf.stalk_functor` -/ def skyscraperPresheafStalkAdjunction [HasColimits C] : (Presheaf.stalkFunctor C p₀ : Presheaf C X ⥤ C) ⊣ skyscraperPresheafFunctor p₀ where homEquiv c 𝓕 := { toFun := toSkyscraperPresheaf _ invFun := fromStalk _ left_inv := fromStalk_to_skyscraper _ right_inv := to_skyscraper_fromStalk _ } Unit := StalkSkyscraperPresheafAdjunctionAuxs.unit _ counit := StalkSkyscraperPresheafAdjunctionAuxs.counit _ homEquiv_unit 𝓕 c α := by ext U; simp only [Equiv.coe_fn_mk, to_skyscraper_presheaf_app, nat_trans.comp_app, SkyscraperPresheafFunctor.map'_app, skyscraperPresheafFunctor_map, unit_app] split_ifs · erw [category.id_comp, ← category.assoc, comp_eq_to_hom_iff, category.assoc, category.assoc, category.assoc, category.assoc, eq_to_hom_trans, eq_to_hom_refl, category.comp_id, ← category.assoc _ _ α, eq_to_hom_trans, eq_to_hom_refl, category.id_comp] · apply ((if_neg h).symm.rec terminal_is_terminal).hom_ext homEquiv_counit 𝓕 c α := by ext U; simp only [Equiv.coe_fn_symm_mk, counit_app] erw [colimit.ι_desc, ← category.assoc, colimit.ι_map, whisker_left_app, category.assoc, colimit.ι_desc] rfl #align skyscraper_presheaf_stalk_adjunction skyscraperPresheafStalkAdjunction instance [HasColimits C] : IsRightAdjoint (skyscraperPresheafFunctor p₀ : C ⥤ Presheaf C X) := ⟨_, skyscraperPresheafStalkAdjunction _⟩ instance [HasColimits C] : IsLeftAdjoint (Presheaf.stalkFunctor C p₀) := ⟨_, skyscraperPresheafStalkAdjunction _⟩ /-- Taking stalks of a sheaf is the left adjoint functor to `skyscraper_sheaf_functor` -/ def stalkSkyscraperSheafAdjunction [HasColimits C] : Sheaf.forget C X ⋙ Presheaf.stalkFunctor _ p₀ ⊣ skyscraperSheafFunctor p₀ where homEquiv 𝓕 c := ⟨fun f => ⟨toSkyscraperPresheaf p₀ f⟩, fun g => fromStalk p₀ g.1, fromStalk_to_skyscraper p₀, fun g => by ext1 apply to_skyscraper_from_stalk⟩ Unit := { app := fun 𝓕 => ⟨(StalkSkyscraperPresheafAdjunctionAuxs.unit p₀).app 𝓕.1⟩ naturality' := fun 𝓐 𝓑 ⟨f⟩ => by ext1 apply (StalkSkyscraperPresheafAdjunctionAuxs.unit p₀).naturality } counit := StalkSkyscraperPresheafAdjunctionAuxs.counit p₀ homEquiv_unit 𝓐 c f := by ext1 exact (skyscraperPresheafStalkAdjunction p₀).homEquiv_unit homEquiv_counit 𝓐 c f := (skyscraperPresheafStalkAdjunction p₀).homEquiv_counit #align stalk_skyscraper_sheaf_adjunction stalkSkyscraperSheafAdjunction instance [HasColimits C] : IsRightAdjoint (skyscraperSheafFunctor p₀ : C ⥤ Sheaf C X) := ⟨_, stalkSkyscraperSheafAdjunction _⟩ end end
{-# LANGUAGE OverloadedStrings #-} module Data.Outputable.Instances where import Control.Applicative (ZipList) import Data.Char (isAlphaNum) import Data.Complex (Complex) import Data.Functor.Identity (Identity) import Data.Int (Int16, Int32, Int64, Int8) import Data.List.NonEmpty (NonEmpty) import qualified Data.Map as Map import Data.Monoid (All, Any, Dual, First, Last, Product, Sum) import Data.Outputable.Class import qualified Data.Semigroup as S (First, Last, Max, Min, Option, WrappedMonoid) import Data.Text (Text, unpack) import qualified Data.Text.Lazy as TL (Text, unpack) import Data.Version (Version) import Data.Void (Void) import Data.Word (Word16, Word32, Word64, Word8) import GHC.Generics import Numeric.Natural (Natural) import System.Exit (ExitCode) import Text.PrettyPrint.HughesPJClass viaPretty :: Pretty a => Int -> a -> Doc viaPretty _ = pPrint viaPrettyNum :: (Ord a, Num a, Pretty a) => Int -> a -> Doc viaPrettyNum n x | n /= 0 && x < 0 = parens $ pPrint x | otherwise = pPrint x viaShow _ x = text $ show x viaShowNum n x | n /= 0 && x < 0 = parens $ viaShow n x | otherwise = viaShow n x instance Outputable Double where pprPrec = viaPrettyNum instance Outputable Float where pprPrec = viaPrettyNum instance Outputable Int where pprPrec = viaPrettyNum instance Outputable Int8 where pprPrec = viaShowNum instance Outputable Int16 where pprPrec = viaShowNum instance Outputable Int32 where pprPrec = viaShowNum instance Outputable Int64 where pprPrec = viaShowNum instance Outputable Integer where pprPrec = viaPrettyNum instance Outputable Natural where pprPrec = viaShow instance Outputable Word where pprPrec = viaShow instance Outputable Word8 where pprPrec = viaShow instance Outputable Word16 where pprPrec = viaShow instance Outputable Word32 where pprPrec = viaShow instance Outputable Word64 where pprPrec = viaShow instance Outputable TL.Text where pprPrec n x = doubleQuotes $ text $ TL.unpack x instance Outputable Text where pprPrec n x = doubleQuotes $ text $ unpack x instance Outputable a => Outputable [a] where pprPrec _ = pprList instance Outputable Char where pprPrec _ x = quotes $ char x pprList = pPrint instance Outputable Bool instance Outputable Ordering instance Outputable () instance Outputable DecidedStrictness instance Outputable SourceStrictness instance Outputable SourceUnpackedness instance Outputable Associativity instance Outputable Fixity instance Outputable Any instance Outputable All instance Outputable ExitCode instance Outputable Version instance Outputable Void instance Outputable a => Outputable (Maybe a) instance Outputable p => Outputable (Par1 p) instance Outputable a => Outputable (NonEmpty a) instance Outputable a => Outputable (Product a) instance Outputable a => Outputable (Sum a) instance Outputable a => Outputable (Dual a) instance Outputable a => Outputable (Last a) instance Outputable a => Outputable (First a) instance Outputable a => Outputable (Identity a) instance Outputable a => Outputable (ZipList a) instance Outputable a => Outputable (S.Option a) instance Outputable m => Outputable (S.WrappedMonoid m) instance Outputable a => Outputable (S.Last a) instance Outputable a => Outputable (S.First a) instance Outputable a => Outputable (S.Max a) instance Outputable a => Outputable (S.Min a) instance Outputable a => Outputable (Complex a) instance (Outputable a, Outputable b) => Outputable (Either a b) instance (Outputable a, Outputable b) => Outputable (a, b) where pprPrec _ (a, b) = parens $ fsep $ punctuate comma [ppr a, ppr b] instance (Outputable a, Outputable b, Outputable c) => Outputable (a, b, c) where pprPrec _ (a, b, c) = parens $ fsep $ punctuate comma [ppr a, ppr b, ppr c] instance (Outputable a, Outputable b, Outputable c, Outputable d) => Outputable (a, b, c, d) where pprPrec _ (a, b, c, d) = parens $ fsep $ punctuate comma [ppr a, ppr b, ppr c, ppr d] instance (Outputable a, Outputable b, Outputable c, Outputable d, Outputable e) => Outputable (a, b, c, d, e) where pprPrec _ (a, b, c, d, e) = parens $ fsep $ punctuate comma [ppr a, ppr b, ppr c, ppr d, ppr e] instance (Outputable k, Outputable v) => Outputable (Map.Map k v) where pprPrec _ m = "fromList" <+> ppr (Map.toList m)
= Tactics : More Basic Tactics This chapter introduces several additional proof strategies and tactics that allow us to begin proving more interesting properties of functional programs. We will see: - how to use auxiliary lemmas in both "forward-style" and "backward-style" proofs; - how to reason about data constructors (in particular, how to use the fact that they are injective and disjoint); - how to strengthen an induction hypothesis (and when such strengthening is required); and - more details on how to reason by case analysis. > module Tactics > > import Basics > import Induction > import Pruviloj > > %access public export > > %default total > > %language ElabReflection > == The \idr{exact} Tactic We often encounter situations where the goal to be proved is _exactly_ the same as some hypothesis in the context or some previously proved lemma. > silly1 : (n, m, o, p : Nat) -> (n = m) -> [n,o] = [n,p] -> [n,o] = [m,p] Here, we could prove this with rewrites: > silly1 n m o p eq1 eq2 = rewrite eq2 in > rewrite eq1 in Refl or the dependent pattern matching: ```idris silly1 n n o o Refl Refl = Refl ``` \todo[inline]{Write more about dependent pattern matching techinque. Maybe move to an earlier chapter?} as we have done several times before. We can achieve the same effect by a series of tactic applications, using \idr{exact} instead of the \idr{rewrite}+\idr{Refl} combination: \todo[inline]{Explain \idr{intros} (move text from `Basics`?), \idr{Var} and \idr{rewriteWith}. Explain the "backwards" order.} \todo[inline]{\idr{| _ => fail []} is needed for totality} > silly1' : (n, m, o, p : Nat) -> (n = m) -> [n,o] = [n,p] -> [n,o] = [m,p] > silly1' = %runElab silly1_tac > where > silly1_tac : Elab () > silly1_tac = do > [n,m,o,p,eq1,eq2] <- intros > | _ => fail [] > rewriteWith $ Var eq1 > exact $ Var eq2 (This tactic is called `apply` in Coq.) \todo[inline]{The following doesn't seem to hold in Idris, you have to manually apply things with \idr{RApp} for \idr{exact} to work. Maybe there's another tactic?} The \idr{exact} tactic also works with _conditional_ hypotheses and lemmas: if the statement being applied is an implication, then the premises of this implication will be added to the list of subgoals needing to be proved. > silly2 : (n, m, o, p : Nat) -> (n = m) -> > ((q, r : Nat) -> q = r -> [q,o] = [r,p]) -> > [n,o] = [m,p] > silly2 = %runElab silly2_tac > where > silly2_tac : Elab () > silly2_tac = do > [n,m,o,p,eq1,eq2] <- intros > | _ => fail [] > exact $ (((Var eq2) `RApp` (Var n)) `RApp` (Var m)) `RApp` (Var eq1) You may find it instructive to experiment with this proof and see if there is a way to complete it using just \idr{rewrite} instead of \idr{exact}. \todo[inline]{Edit} Typically, when we use \idr{exact h}, the statement \idr{h} will begin with a `(...)` that binds some _universal variables_. When Idris matches the current goal against the conclusion of \idr{h}, it will try to find appropriate values for these variables. For example, when we do \idr{exact $ Var eq2} in the following proof, the universal variable \idr{q} in \idr{eq2} gets instantiated with \idr{n} and \idr{r} gets instantiated with \idr{m}. > silly2a : (n, m : Nat) -> (n,n) = (m,m) -> > ((q, r : Nat) -> (q,q) = (r,r) -> [q] = [r]) -> > [n] = [m] > silly2a = %runElab silly2a_tac > where > silly2a_tac : Elab () > silly2a_tac = do > [n,m,eq1,eq2] <- intros > | _ => fail [] > exact $ (((Var eq2) `RApp` (Var n)) `RApp` (Var m)) `RApp` (Var eq1) ==== Exercise: 2 stars, optional (silly_ex) Complete the following proof without using `simpl`. > silly_ex : ((n : Nat) -> evenb n = True -> oddb (S n) = True) > -> evenb 3 = True -> oddb 4 = True > silly_ex = ?remove_me -- %runElab silly_ex_tac > where > silly_ex_tac : Elab () > silly_ex_tac = ?silly_ex_tac_rhs $\square$ To use the \idr{exact} tactic, the (conclusion of the) fact being applied must match the goal exactly -- for example, \idr{exact} will not work if the left and right sides of the equality are swapped. > silly3_firsttry : (n : Nat) -> True = n == 5 -> > (S (S n)) == 7 = True > silly3_firsttry = %runElab silly3_firsttry_tac > where > silly3_firsttry_tac : Elab () > silly3_firsttry_tac = do > [_,h] <- intros > | _ => fail [] Here we cannot use \idr{exact} directly, but we can use the \idr{symmetry} tactic, which switches the left and right sides of an equality in the goal. > symmetry > exact $ Var h ==== Exercise: 3 stars (apply_exercise1) (_Hint_: You can use \idr{exact} with previously defined lemmas, not just hypotheses in the context. Remember that `:search` is your friend.) > rev : (l : List x) -> List x > rev [] = [] > rev (h::t) = (rev t) ++ [h] > rev_exercise1 : (l, l' : List Nat) -> l = rev l' -> l' = rev l > rev_exercise1 = ?remove_me1 -- %runElab rev_exercise1_tac > where > rev_exercise1_tac : Elab () > rev_exercise1_tac = ?rev_exercise1_tac_rhs $\square$ ==== Exercise: 1 star, optional (apply_rewrite) Briefly explain the difference between the tactics \idr{exact} and \idr{rewriteWith}. What are the situations where both can usefully be applied? > -- FILL IN HERE $\square$ == The \idr{apply} Tactic The following silly example uses two rewrites in a row to get from `[a,b]` to `[e,f]`. > trans_eq_example : (a, b, c, d, e, f : Nat) -> > [a,b] = [c,d] -> [c,d] = [e,f] -> [a,b] = [e,f] > trans_eq_example a b c d e f eq1 eq2 = rewrite eq1 in > rewrite eq2 in Refl Note that this can also be proven with dependent pattern matching: ```idris trans_eq_example a b a b a b Refl Refl = Refl ``` Since this is a common pattern, we might like to pull it out as a lemma recording, once and for all, the fact that equality is transitive. > trans_eq : (n, m, o : x) -> n = m -> m = o -> n = o > trans_eq n n n Refl Refl = Refl (This lemma already exists in Idris' stdlib under the name of \idr{trans}.) Now, we should be able to use \idr{trans_eq} to prove the above example. However, to do this we need a slight refinement of the \idr{exact} tactic. > trans_eq_example' : (a, b, c, d, e, f : Nat) -> > [a,b] = [c,d] -> [c,d] = [e,f] -> [a,b] = [e,f] > trans_eq_example' = %runElab trans_eq_example_tac > where > trans_eq_example_tac : Elab () > trans_eq_example_tac = do > [a,b,c,d,e,f,eq1,eq2] <- intros > | _ => fail [] \todo[inline]{Edit: Idris apparently can figure things out itself via \idr{solve}. Explain the quotation syntax.} If we simply tell Idris \idr{apply (Var `{trans_eq}) ..} at this point, it can tell (by matching the goal against the conclusion of the lemma) that it should instantiate \idr{x} with \idr{[Nat]}, \idr{n} with \idr{[a,b]}, and \idr{o} with \idr{[e,f]}. However, the matching process doesn't determine an instantiation for \idr{m}: we have to supply one explicitly by adding with (m:=[c,d]) to the invocation of \idr{apply}. > [_,_,_,_,_,_] <- apply (Var `{trans_eq}) > [True, True, True, True, False, False] > | _ => fail [] > solve > exact $ Var eq1 > exact $ Var eq2 ==== Exercise: 3 stars, optional (apply_with_exercise) > trans_eq_exercise : (n, m, o, p : Nat) -> > m = (minusTwo o) -> > (n + p) = m -> > (n + p) = (minusTwo o) > trans_eq_exercise = ?remove_me2 -- %runElab trans_eq_exercise_tac > where > trans_eq_exercise_tac : Elab () > trans_eq_exercise_tac = ?trans_eq_exercise_rhs $\square$ == The \idr{inversion} Tactic Recall the definition of natural numbers: ```idris data Nat : Type where Z : Nat S : Nat -> Nat ``` It is obvious from this definition that every number has one of two forms: either it is the constructor \idr{Z} or it is built by applying the constructor \idr{S} to another number. But there is more here than meets the eye: implicit in the definition (and in our informal understanding of how datatype declarations work in other programming languages) are two more facts: - The constructor \idr{S} is _injective_. That is, if \idr{S n = S m}, it must be the case that \idr{n = m}. - The constructors \idr{Z} and \idr{S} are _disjoint_. That is, \idr{Z} is not equal to \idr{S n} for any \idr{n}. Similar principles apply to all inductively defined types: all constructors are injective, and the values built from distinct constructors are never equal. For lists, the \idr{(::)} constructor is injective and \idr{Nil} is different from every non-empty list. For booleans, \idr{True} and \idr{False} are different. (Since neither \idr{True} nor \idr{False} take any arguments, their injectivity is not interesting.) And so on. Idris provides a tactic called \idr{injective} that allows us to exploit these principles in proofs. To see how to use it, let's show explicitly that the \idr{S} constructor is injective: > S_injective : (n, m : Nat) -> S n = S m -> n = m > S_injective = %runElab S_injective_tac > where > covering > S_injective_tac : Elab () > S_injective_tac = do > [n, m, h] <- intros > | _ => fail [] By writing \idr{injective (Var h) res} at this point, we are asking Idris to generate all equations that it can infer from \idr{h} as additional hypotheses, replacing variables in the goal as it goes. In the present example, this amounts to adding a new hypothesis \idr{h1 : n = m} and replacing \idr{n} by \idr{m} in the goal. \todo[inline]{Explain \idr{gensym}, \idr{unproduct} and \idr{hypothesis}} > res <- gensym "sInj" > injective (Var h) res > unproduct (Var res) > hypothesis Here's a more interesting example that shows how multiple equations can be derived at once. \todo[inline]{Works quite fast in Elab shell but hangs the compiler} > -- inversion_ex1 : (n, m, o : Nat) -> [n, m] = [o, o] -> [n] = [m] > -- inversion_ex1 = %runElab inversion_ex1_tac > -- where > -- inversion_ex1_tac : Elab () > -- inversion_ex1_tac = do > -- [n, m, o, eq] <- intros > -- | _ => fail [] > -- eqinj <- gensym "eqinj" > -- injective (Var eq) eqinj > -- > -- eqinj2 <- gensym "eqinj2" -- manual destructuring > -- both (Var eqinj) !(gensym "natnat") eqinj2 > -- neqo <- gensym "neqo" > -- eqinj3 <- gensym "eqinj3" > -- both (Var eqinj2) no eqinj3 > -- meqos <- gensym "meqos" > -- both (Var eqinj3) mos !(gensym "uu") > -- > -- oeqn <- gensym "oeqn" > -- symmetryAs (Var neqo) oeqn > -- symmetry > -- rewriteWith $ Var oeqn > -- exact $ Var meqos > -- solve Note that we need to pass the parameter \idr{eqinj} which will be bound to equations that \idr{injective} generates. \todo[inline]{Remove when a release with https://github.com/idris-lang/Idris-dev/pull/3925 happens} ==== Exercise: 1 star (inversion_ex3) > inversion_ex3 : (x, y, z : a) -> (l, j : List a) -> > x :: y :: l = z :: j -> > y :: l = x :: j -> > x = y > inversion_ex3 = ?remove_me3 -- %runElab inversion_ex3_tac > where > inversion_ex3_tac : Elab () > inversion_ex3_tac = ?inversion_ex3_tac_rhs $\square$ \todo[inline]{Edit} When used on a hypothesis involving an equality between _different_ constructors (e.g., \idr{S n = Z}), \idr{injective} solves the goal immediately. Consider the following proof: > beq_nat_0_l : Z == n = True -> n = Z We can proceed by case analysis on n. The first case is trivial. > beq_nat_0_l {n=Z} _ = Refl However, the second one doesn't look so simple: assuming \idr{0 == S n' = True}, we must show \idr{S n' = 0}, but the latter clearly contradictory! The way forward lies in the assumption. After simplifying the goal state, we see that \idr{0 == S n' = True} has become \idr{False = True}: \todo[inline]{How to show impossible cases from Elab?} > beq_nat_0_l {n=(S _)} prf = absurd prf If we use \idr{absurd} on this hypothesis, Idris allows us to safely infer any conclusion from it, in this case our goal of \idr{n = 0}. This is an instance of a logical principle known as the principle of explosion, which asserts that a contradictory hypothesis entails anything, even false things! > inversion_ex4 : (n : Nat) -> S n = Z -> 2 + 2 = 5 > -- we need "sym" because Prelude.Nat only disproves "Z = S n" for us > inversion_ex4 n prf = absurd $ sym prf In simple cases like this, we could've also solved this with matching on \idr{prf}: ```idris inversion_ex4 _ Refl impossible ``` > inversion_ex5 : (n, m : Nat) -> False = True -> [n] = [m] > inversion_ex5 n m prf = absurd prf Again, here we can also write ```idris inversion_ex5 _ _ Refl impossible ``` If you find the principle of explosion confusing, remember that these proofs are not actually showing that the conclusion of the statement holds. Rather, they are arguing that, if the nonsensical situation described by the premise did somehow arise, then the nonsensical conclusion would follow. We'll explore the principle of explosion of more detail in the next chapter. ==== Exercise: 1 star (inversion_ex6) > inversion_ex6 : (x, y, z : a) -> (l, j : List a) -> > x :: y :: l = [] -> > y :: l = z :: j -> > x = z > inversion_ex6 x y z l j prf prf1 = ?inversion_ex6_rhs $\square$ To summarize this discussion, suppose \idr{h} is a hypothesis in the context or a previously proven lemma of the form \idr{c a1 a2 ... an = d b1 b2 ... bm} \todo[inline]{Edit, especially the \idr{disjoint} part} for some constructors \idr{c} and \idr{d} and arguments \idr{a1 ... an} and \idr{b1 ... bm}. Then \idr{injective h} and \idr{disjoint h} have the following effects: - If \idr{c} and \idr{d} are the same constructor, then, by the injectivity of this constructor, we know that \idr{a1 = b1}, \idr{a2 = b2}, etc. The \idr{injective h} adds these facts to the context and tries to use them to rewrite the goal. - If \idr{c} and \idr{d} are different constructors, then the hypothesis \idr{h} is contradictory, and the current goal doesn't have to be considered at all. In this case, \idr{disjoint h} marks the current goal as completed and pops it off the goal stack. The injectivity of constructors allows us to reason that \idr{(n, m : Nat) -> S n = S m -> n = m}. The converse of this implication is an instance of a more general fact about both constructors and functions, which we will find useful in a few places below: > f_equal : (f : a -> b) -> (x, y : a) -> x = y -> f x = f y > f_equal f x x Refl = Refl (This is called \idr{cong} in Idris' stdlib.) == Using Tactics on Hypotheses \todo[inline]{Edit, Idris runs \idr{compute} on hypotheses automatically} By default, most tactics work on the goal formula and leave the context unchanged. However, most tactics also have a variant that performs a similar operation on a statement in the context. For example, the tactic \idr{compute} in H performs simplification in the hypothesis named \idr{h} in the context. > S_inj : (n, m : Nat) -> (b : Bool) -> > S n == S m = b -> n == m = b > S_inj = %runElab S_inj_tac > where > S_inj_tac : Elab () > S_inj_tac = do > [n, m, b, eq] <- intros > | _ => fail [] > exact $ Var eq \todo[inline]{Edit} Similarly, \idr{applyIn l h} matches some conditional statement \idr{l} (of the form \idr{l1 -> l2}, say) against a hypothesis \idr{h} in the context. However, unlike ordinary \idr{exact} (which rewrites a goal matching \idr{l2} into a subgoal \idr{l1}), \idr{applyIn l h n} matches \idr{h} against \idr{l1} and, if successful, binds the result \idr{l2} to \idr{n}. In other words, \idr{applyIn l h} gives us a form of "forward reasoning": from \idr{l1 -> l2} and a hypothesis matching \idr{l1}, it produces a hypothesis matching \idr{l2}. By contrast, \idr{exact l} is "backward reasoning": it says that if we know \idr{l1->l2} and we are trying to prove \idr{l2}, it suffices to prove \idr{l1}. Here is a variant of a proof from above, using forward reasoning throughout instead of backward reasoning. > silly3' : (n, m : Nat) -> (n == 5 = True -> m == 7 = True) -> > True = n == 5 -> True = m == 7 > silly3' = %runElab silly3_tac > where > silly3_tac : Elab () > silly3_tac = do > [n,m,eq,h] <- intros > | _ => fail [] > hsym <- symmetryAs (Var h) "hsym" > happ <- applyAs (Var eq) (Var hsym) "happ" > happsym <- symmetryAs (Var happ) "happsym" > exact $ Var happsym Forward reasoning starts from what is _given_ (premises, previously proven theorems) and iteratively draws conclusions from them until the goal is reached. Backward reasoning starts from the _goal_, and iteratively reasons about what would imply the goal, until premises or previously proven theorems are reached. If you've seen informal proofs before (for example, in a math or computer science class), they probably used forward reasoning. In general, idiomatic use of Idris elab scripts tends to favor backward reasoning, but in some situations the forward style can be easier to think about. ==== Exercise: 3 stars, recommended (plus_n_n_injective) Practice using "in" variants in this exercise. (Hint: use \idr{plus_n_Sm}.) > plus_n_n_injective : n + n = m + m -> n = m > plus_n_n_injective = ?plus_n_n_injective_rhs $\square$ == Varying the Induction Hypothesis Sometimes it is important to control the exact form of the induction hypothesis when carrying out inductive proofs in Idris elab script. In particular, we need to be careful about which of the assumptions we move (using \idr{intros}) from the goal to the context before invoking the \idr{induction} tactic. For example, suppose we want to show that the \idr{double} function is injective -- i.e., that it maps different arguments to different results: > double_injective : double n = double m -> n = m > double_injective {n=Z} {m=Z} _ = Refl > double_injective {n=Z} {m=(S _)} Refl impossible > double_injective {n=(S _)} {m=Z} Refl impossible > double_injective {n=(S n')} {m=(S m')} eq = > let eqss = succInjective _ _ $ succInjective _ _ eq > in rewrite double_injective {n=n'} {m=m'} eqss in Refl \todo[inline]{Edit the rest of the section to use \idr{induction}?} The way we _start_ this proof is a bit delicate: if we begin with intros n. induction n. all is well. But if we begin it with intros n m. induction n. we get stuck in the middle of the inductive case... Theorem double_injective_FAILED : ∀n m, double n = double m -> n = m. Proof. intros n m. induction n as [| n']. - (* n = Z *) simpl. intros eq. destruct m as [| m']. + (* m = Z *) reflexivity. + (* m = S m' *) inversion eq. - (* n = S n' *) intros eq. destruct m as [| m']. + (* m = Z *) inversion eq. + (* m = S m' *) apply f_equal. At this point, the induction hypothesis, IHn', does not give us n' = m' -- there is an extra S in the way -- so the goal is not provable. Abort. What went wrong? The problem is that, at the point we invoke the induction hypothesis, we have already introduced m into the context -- intuitively, we have told Coq, "Let's consider some particular n and m..." and we now have to prove that, if double n = double m for these particular n and m, then n = m. The next tactic, induction n says to Coq: We are going to show the goal by induction on n. That is, we are going to prove, for all n, that the proposition - P n = "if double n = double m, then n = m" holds, by showing - P Z (i.e., "if double Z = double m then Z = m") and - P n -> P (S n) (i.e., "if double n = double m then n = m" implies "if double (S n) = double m then S n = m"). If we look closely at the second statement, it is saying something rather strange: it says that, for a particular m, if we know - "if double n = double m then n = m" then we can prove - "if double (S n) = double m then S n = m". To see why this is strange, let's think of a particular m -- say, 5. The statement is then saying that, if we know - Q = "if double n = 10 then n = 5" then we can prove - R = "if double (S n) = 10 then S n = 5". But knowing Q doesn't give us any help at all with proving R! (If we tried to prove R from Q, we would start with something like "Suppose double (S n) = 10..." but then we'd be stuck: knowing that double (S n) is 10 tells us nothing about whether double n is 10, so Q is useless.) Trying to carry out this proof by induction on n when m is already in the context doesn't work because we are then trying to prove a relation involving every n but just a single m. The successful proof of double_injective leaves m in the goal statement at the point where the induction tactic is invoked on n: Theorem double_injective : ∀n m, double n = double m -> n = m. Proof. intros n. induction n as [| n']. - (* n = Z *) simpl. intros m eq. destruct m as [| m']. + (* m = Z *) reflexivity. + (* m = S m' *) inversion eq. - (* n = S n' *) simpl. Notice that both the goal and the induction hypothesis are different this time: the goal asks us to prove something more general (i.e., to prove the statement for every m), but the IH is correspondingly more flexible, allowing us to choose any m we like when we apply the IH. intros m eq. Now we've chosen a particular m and introduced the assumption that double n = double m. Since we are doing a case analysis on n, we also need a case analysis on m to keep the two "in sync." destruct m as [| m']. + (* m = Z *) simpl. The 0 case is trivial: inversion eq. + (* m = S m' *) apply f_equal. At this point, since we are in the second branch of the destruct m, the m' mentioned in the context is the predecessor of the m we started out talking about. Since we are also in the S branch of the induction, this is perfect: if we instantiate the generic m in the IH with the current m' (this instantiation is performed automatically by the apply in the next step), then IHn' gives us exactly what we need to finish the proof. apply IHn'. inversion eq. reflexivity. Qed. What you should take away from all this is that we need to be careful about using induction to try to prove something too specific: To prove a property of n and m by induction on n, it is sometimes important to leave m generic. The following exercise requires the same pattern. ==== Exercise: 2 stars (beq_nat_true) \ \todo[inline]{We explicitly write out implicits as having type \idr{Nat} since \idr{(==)} is polymorphic} > beq_nat_true : {n, m : Nat} -> n == m = True -> n = m > beq_nat_true prf = ?beq_nat_true_rhs $\square$ ==== Exercise: 2 stars, advanced (beq_nat_true_informal) Give a careful informal proof of \idr{beq_nat_true}, being as explicit as possible about quantifiers. > -- FILL IN HERE $\square$ \todo[inline]{What to do with the rest of this?} The strategy of doing fewer intros before an induction to obtain a more general IH doesn't always work by itself; sometimes some rearrangement of quantified variables is needed. Suppose, for example, that we wanted to prove double_injective by induction on m instead of n. Theorem double_injective_take2_FAILED : ∀n m, double n = double m -> n = m. Proof. intros n m. induction m as [| m']. - (* m = Z *) simpl. intros eq. destruct n as [| n']. + (* n = Z *) reflexivity. + (* n = S n' *) inversion eq. - (* m = S m' *) intros eq. destruct n as [| n']. + (* n = Z *) inversion eq. + (* n = S n' *) apply f_equal. (* Stuck again here, just like before. *) Abort. The problem is that, to do induction on m, we must first introduce n. (If we simply say induction m without introducing anything first, Coq will automatically introduce n for us!) What can we do about this? One possibility is to rewrite the statement of the lemma so that m is quantified before n. This works, but it's not nice: We don't want to have to twist the statements of lemmas to fit the needs of a particular strategy for proving them! Rather we want to state them in the clearest and most natural way. What we can do instead is to first introduce all the quantified variables and then re-generalize one or more of them, selectively taking variables out of the context and putting them back at the beginning of the goal. The generalize dependent tactic does this. Theorem double_injective_take2 : ∀n m, double n = double m -> n = m. Proof. intros n m. (* n and m are both in the context *) generalize dependent n. (* Now n is back in the goal and we can do induction on m and get a sufficiently general IH. *) induction m as [| m']. - (* m = Z *) simpl. intros n eq. destruct n as [| n']. + (* n = Z *) reflexivity. + (* n = S n' *) inversion eq. - (* m = S m' *) intros n eq. destruct n as [| n']. + (* n = Z *) inversion eq. + (* n = S n' *) apply f_equal. apply IHm'. inversion eq. reflexivity. Qed. Let's look at an informal proof of this theorem. Note that the proposition we prove by induction leaves n quantified, corresponding to the use of generalize dependent in our formal proof. _Theorem_: For any nats n and m, if double n = double m, then n = m. _Proof_: Let m be a Nat. We prove by induction on m that, for any n, if double n = double m then n = m. - First, suppose m = 0, and suppose n is a number such that double n = double m. We must show that n = 0. Since m = 0, by the definition of double we have double n = 0. There are two cases to consider for n. If n = 0 we are done, since m = 0 = n, as required. Otherwise, if n = S n' for some n', we derive a contradiction: by the definition of double, we can calculate double n = S (S (double n')), but this contradicts the assumption that double n = 0. - Second, suppose m = S m' and that n is again a number such that double n = double m. We must show that n = S m', with the induction hypothesis that for every number s, if double s = double m' then s = m'. By the fact that m = S m' and the definition of double, we have double n = S (S (double m')). There are two cases to consider for n. If n = 0, then by definition double n = 0, a contradiction. Thus, we may assume that n = S n' for some n', and again by the definition of double we have S (S (double n')) = S (S (double m')), which implies by inversion that double n' = double m'. Instantiating the induction hypothesis with n' thus allows us to conclude that n' = m', and it follows immediately that S n' = S m'. Since S n' = n and S m' = m, this is just what we wanted to show. $\square$ Before we close this section and move on to some exercises, let's digress briefly and use \idr{beq_nat_true} to prove a similar property of identifiers that we'll need in later chapters: > data Id : Type where > MkId : Nat -> Id > beq_id : (x1, x2 : Id) -> Bool > beq_id (MkId n1) (MkId n2) = n1 == n2 > beq_id_true : beq_id x y = True -> x = y > beq_id_true {x=MkId x'} {y=MkId y'} prf = > rewrite beq_nat_true {n=x'} {m=y'} prf in Refl === Exercise: 3 stars, recommended (gen_dep_practice) Prove this by induction on \idr{l}. > data Option : (x : Type) -> Type where > Some : x -> Option x > None : Option x > nth_error : (l : List x) -> (n : Nat) -> Option x > nth_error [] n = None > nth_error (a::l') n = if n == 0 > then Some a > else nth_error l' (Nat.pred n) > nth_error_after_last: (n : Nat) -> (l : List x) -> > length l = n -> nth_error l n = None $\square$ == Unfolding Definitions \todo[inline]{Edit} It sometimes happens that we need to manually unfold a definition so that we can manipulate its right-hand side. For example, if we define... > square : Nat -> Nat > square n = n * n ... and try to prove a simple fact about square... > square_mult : (n, m : Nat) -> square (n * m) = square n * square m > square_mult n m = rewrite multAssociative (n*m) n m in > rewrite multCommutative (n*m) n in > rewrite multAssociative (n*n) m m in > rewrite multAssociative n n m in Refl ... we succeed because Idris unfolds everything for us automatically. \todo[inline]{Remove the next part?} ... we get stuck: simpl doesn't simplify anything at this point, and since we haven't proved any other facts about square, there is nothing we can apply or rewrite with. To make progress, we can manually unfold the definition of square: unfold square. Now we have plenty to work with: both sides of the equality are expressions involving multiplication, and we have lots of facts about multiplication at our disposal. In particular, we know that it is commutative and associative, and from these facts it is not hard to finish the proof. rewrite mult_assoc. assert (H : n * m * n = n * n * m). { rewrite mult_comm. apply mult_assoc. } rewrite H. rewrite mult_assoc. reflexivity. Qed. At this point, a deeper discussion of unfolding and simplification is in order. You may already have observed that \idr{Refl} will often unfold the definitions of functions automatically when this allows them to make progress. For example, if we define \idr{foo m} to be the constant \idr{5}... > foo : Nat -> Nat > foo x = 5 then \idr{Refl} in the following proof will unfold \idr{foo m} to \idr{(\x => 5) m} and then further simplify this expression to just \idr{5}. > silly_fact_1 : foo m + 1 = foo (m + 1) + 1 > silly_fact_1 = Refl However, this automatic unfolding is rather conservative. For example, if we define a slightly more complicated function involving a pattern match... > bar : Nat -> Nat > bar Z = 5 > bar (S _) = 5 ...then the analogous proof will get stuck: ```idris silly_fact_2_FAILED : bar m + 1 = bar (m + 1) + 1 silly_fact_2_FAILED = Refl ``` The reason that \idr{Refl} doesn't make progress here is that it notices that, after tentatively unfolding \idr{bar m}, it is left with a match whose scrutinee, \idr{m}, is a variable, so the match cannot be simplified further. (It is not smart enough to notice that the two branches of the match are identical.) So it gives up on unfolding \idr{bar m} and leaves it alone. Similarly, tentatively unfolding \idr{bar (m+1)} leaves a match whose scrutinee is a function application (that, itself, cannot be simplified, even after unfolding the definition of \idr{+}), so \idr{Refl} leaves it alone. At this point, there are two ways to make progress. One is to match on implicit parameter \idr{m} to break the proof into two cases, each focusing on a more concrete choice of \idr{m} (\idr{Z} vs \idr{S _}). In each case, the match inside of \idr{bar} can now make progress, and the proof is easy to complete. > silly_fact_2 : bar m + 1 = bar (m + 1) + 1 > silly_fact_2 {m=Z} = Refl > silly_fact_2 {m=(S _)} = Refl \todo[inline]{Edit} This approach works, but it depends on our recognizing that the match hidden inside bar is what was preventing us from making progress. A more straightforward way to make progress is to explicitly tell Idris to unfold bar. \todo[inline]{Can we destruct in Elab script? Maybe with \idr{deriveElim}?} Fact silly_fact_2' : ∀m, bar m + 1 = bar (m + 1) + 1. Proof. intros m. unfold bar. Now it is apparent that we are stuck on the match expressions on both sides of the =, and we can use destruct to finish the proof without thinking too hard. destruct m. - reflexivity. - reflexivity. Qed. == Using \idr{destruct} on Compound Expressions \todo[inline]{Edit. Explain \idr{with}} We have seen many examples where destruct is used to perform case analysis of the value of some variable. But sometimes we need to reason by cases on the result of some _expression_. We can also do this with destruct. Here are some examples: > sillyfun : Nat -> Bool > sillyfun n = if n == 3 > then False > else if n == 5 > then False > else False > sillyfun_false : (n : Nat) -> sillyfun n = False > sillyfun_false n with (n == 3) > sillyfun_false n | True = Refl > sillyfun_false n | False with (n == 5) > sillyfun_false n | False | True = Refl > sillyfun_false n | False | False = Refl After unfolding \idr{sillyfun} in the above proof, we find that we are stuck on \idr{if (n == 3) then ... else ...}. But either \idr{n} is equal to \idr{3} or it isn't, so we can use \idr{with (n == 3)} to let us reason about the two cases. \todo[inline]{Edit} In general, the destruct tactic can be used to perform case analysis of the results of arbitrary computations. If e is an expression whose type is some inductively defined type T, then, for each constructor c of T, destruct e generates a subgoal in which all occurrences of e (in the goal and in the context) are replaced by c. ==== Exercise: 3 stars, optional (combine_split) > combine_split : (l : List (x,y)) -> (l1 : List x) -> (l2 : List y) -> > unzip l = (l1, l2) -> zip l1 l2 = l > combine_split l l1 l2 prf = ?combine_split_rhs $\square$ However, destructing compound expressions requires a bit of care, as such destructs can sometimes erase information we need to complete a proof. For example, suppose we define a function \idr{sillyfun1} like this: > sillyfun1 : Nat -> Bool > sillyfun1 n = if n == 3 > then True > else if n == 5 > then True > else False Now suppose that we want to convince Idris of the (rather obvious) fact that \idr{sillyfun1 n} yields \idr{True} only when \idr{n} is odd. By analogy with the proofs we did with \idr{sillyfun} above, it is natural to start the proof like this: > sillyfun1_odd : (n : Nat) -> sillyfun1 n = True -> oddb n = True > sillyfun1_odd n prf with (n == 3) proof eq3 > sillyfun1_odd n Refl | True = > rewrite beq_nat_true (sym eq3) {n} {m=3} in Refl > sillyfun1_odd n prf | False with (n == 5) proof eq5 > sillyfun1_odd n Refl | False | True = > rewrite beq_nat_true (sym eq5) {n} {m=5} in Refl > sillyfun1_odd n prf | False | False = absurd prf \todo[inline]{Edit the following, since \idr{with} works fine here as well} We get stuck at this point because the context does not contain enough information to prove the goal! The problem is that the substitution performed by destruct is too brutal -- it threw away every occurrence of n == 3, but we need to keep some memory of this expression and how it was destructed, because we need to be able to reason that, since n == 3 = True in this branch of the case analysis, it must be that n = 3, from which it follows that n is odd. What we would really like is to substitute away all existing occurences of n == 3, but at the same time add an equation to the context that records which case we are in. The eqn: qualifier allows us to introduce such an equation, giving it a name that we choose. Theorem sillyfun1_odd : ∀(n : Nat), sillyfun1 n = True -> oddb n = True. Proof. intros n eq. unfold sillyfun1 in eq. destruct (beq_nat n 3) eqn:Heqe3. (* Now we have the same state as at the point where we got stuck above, except that the context contains an extra equality assumption, which is exactly what we need to make progress. *) - (* e3 = True *) apply beq_nat_true in Heqe3. rewrite -> Heqe3. reflexivity. - (* e3 = False *) (* When we come to the second equality test in the body of the function we are reasoning about, we can use eqn: again in the same way, allow us to finish the proof. *) destruct (beq_nat n 5) eqn:Heqe5. + (* e5 = True *) apply beq_nat_true in Heqe5. rewrite -> Heqe5. reflexivity. + (* e5 = False *) inversion eq. Qed. ==== Exercise: 2 stars (destruct_eqn_practice) > bool_fn_applied_thrice : (f : Bool -> Bool) -> (b : Bool) -> f (f (f b)) = f b > bool_fn_applied_thrice f b = ?bool_fn_applied_thrice_rhs $\square$ == Review We've now seen many of Idris's most fundamental tactics. We'll introduce a few more in the coming chapters, and later on we'll see some more powerful automation tactics that make Idris help us with low-level details. But basically we've got what we need to get work done. Here are the ones we've seen: \todo[inline]{Edit} - \idr{intros}: move hypotheses/variables from goal to context - \idr{reflexivity}: finish the proof (when the goal looks like \idr{e = e}) - \idr{exact}: prove goal using a hypothesis, lemma, or constructor - \idr{apply... in H}: apply a hypothesis, lemma, or constructor to a hypothesis in the context (forward reasoning) - \idr{apply... with...}: explicitly specify values for variables that cannot be determined by pattern matching - \idr{compute}: simplify computations in the goal - \idr{simpl in H}: ... or a hypothesis - \idr{rewriteWith}: use an equality hypothesis (or lemma) to rewrite the goal - \idr{rewrite ... in H}: ... or a hypothesis - \idr{symmetry}: changes a goal of the form \idr{t=u} into \idr{u=t} - \idr{symmetryAs h}: changes a hypothesis of the form \idr{t=u} into \idr{u=t} - \idr{unfold}: replace a defined constant by its right-hand side in the goal - \idr{unfold... in H}: ... or a hypothesis - \idr{destruct... as...}: case analysis on values of inductively defined types - \idr{destruct... eqn:...}: specify the name of an equation to be added to the context, recording the result of the case analysis - \idr{induction... as...}: induction on values of inductively defined types - \idr{injective}: reason by injectivity of constructors - \idr{disjoint}: reason by distinctness of constructors - \idr{assert (H: e)} (or \idr{assert (e) as H}): introduce a "local lemma" \idr{e} and call it \idr{H} - \idr{generalize dependent x}: move the variable \idr{x} (and anything else that depends on it) from the context back to an explicit hypothesis in the goal formula == Additional Exercises ==== Exercise: 3 stars (beq_nat_sym) > beq_nat_sym : (n, m : Nat) -> n == m = m == n > beq_nat_sym n m = ?beq_nat_sym_rhs $\square$ ==== Exercise: 3 stars, advancedM? (beq_nat_sym_informal) Give an informal proof of this lemma that corresponds to your formal proof above: Theorem: For any \idr{Nat}s \idr{n}, idr{m}, \idr{n == m = m == n} Proof: > --FILL IN HERE $\square$ ==== Exercise: 3 stars, optional (beq_nat_trans) > beq_nat_trans : {n, m, p : Nat} -> n == m = True -> m == p = True -> > n == p = True > beq_nat_trans prf prf1 = ?beq_nat_trans_rhs $\square$ ==== Exercise: 3 stars, advanced (split_combine) We proved, in an exercise above, that for all lists of pairs, \idr{zip} is the inverse of \idr{unzip}. How would you formalize the statement that \idr{unzip} is the inverse of \idr{zip}? When is this property true? Complete the definition of \idr{split_combine} below with a property that states that \idr{unzip} is the inverse of \idr{zip}. Then, prove that the property holds. (Be sure to leave your induction hypothesis general by not doing \idr{intros} on more things than necessary. Hint: what property do you need of \idr{l1} and \idr{l2} for \idr{unzip (zip l1 l2) = (l1,l2)} to be true?) > split_combine : ?split_combine $\square$ ==== Exercise: 3 stars, advanced (filter_exercise) This one is a bit challenging. Pay attention to the form of your induction hypothesis. > filter_exercise : (test : a -> Bool) -> (x : a) -> (l, lf : List a) -> > filter test l = x :: lf -> > test x = True > filter_exercise test x l lf prf = ?filter_exercise_rhs $\square$ ==== Exercise: 4 stars, advanced, recommended (forall_exists_challenge) Define two recursive functions, \idr{forallb} and \idr{existsb}. The first checks whether every element in a list satisfies a given predicate: \idr{forallb oddb [1,3,5,7,9] = True} \idr{forallb not [False,False] = True} \idr{forallb evenb [0,2,4,5] = False} \idr{forallb (== 5) [] = True} The second checks whether there exists an element in the list that satisfies a given predicate: \idr{existsb (== 5) [0,2,3,6] = False} \idr{existsb ((&&) True) [True,True,False] = True} \idr{existsb oddb [1,0,0,0,0,3] = True} \idr{existsb evenb [] = False} Next, define a _nonrecursive_ version of \idr{existsb} -- call it \idr{existsb'} -- using \idr{forallb} and \idr{not}. Finally, prove a theorem \idr{existsb_existsb'} stating that \idr{existsb'} and \idr{existsb} have the same behavior. > -- FILL IN HERE $\square$
#include "sv/dsol/hessian.h" #include <Eigen/Cholesky> // LLT and LDLT #include <Eigen/LU> // inverse #include "sv/util/logging.h" #include "sv/util/tbb.h" namespace sv::dsol { using Vector2d = Eigen::Vector2d; using Vector3i = Eigen::Vector3i; using LltLowerInplace = Eigen::LLT<MatrixXdRef, Eigen::Lower>; using LdltLowerInplace = Eigen::LDLT<MatrixXdRef, Eigen::Lower>; namespace { constexpr int dp = Dim::kPose; constexpr int df = Dim::kFrame; constexpr int dd = Dim::kPoint; constexpr int da = Dim::kAffine; } // namespace /// ============================================================================ void PatchHessian::AddI(const Vector2d& It, double r, double w) noexcept { const auto wr = w * r; ItI.noalias() += (It * w) * It.transpose(); Itr.noalias() += It * wr; r2 += r * r; wr2 += r * wr; } void PatchHessian::SetI(const Matrix2Kd& It, const ArrayKd& r, const ArrayKd& w) noexcept { const ArrayKd wr = w * r; ItI.noalias() = It * w.matrix().asDiagonal() * It.transpose(); Itr.noalias() = It * wr.matrix(); r2 = (r * r).sum(); wr2 = (wr * r).sum(); } /// ============================================================================ void PatchHessian1::AddA(const Vector2d& It, const Vector2d& At, double r, double w) noexcept { ItA.noalias() += (It * w) * At.transpose(); AtA.noalias() += (At * w) * At.transpose(); Atr.noalias() += At * (w * r); } void PatchHessian1::SetA(const Matrix2Kd& It, const Matrix2Kd& At, const ArrayKd& r, const ArrayKd& w) noexcept { const MatrixK2d wA = w.matrix().asDiagonal() * At.transpose(); ItA.noalias() = It * wA; AtA.noalias() = At * wA; Atr.noalias() = At * (w * r).matrix(); } /// ============================================================================ void PatchHessian2::AddA(const Vector2d& It, const Vector2d& A0t, const Vector2d& A1t, double r, double w) noexcept { const Vector2d Itw = It * w; ItA0.noalias() += Itw * A0t.transpose(); ItA1.noalias() += Itw * A1t.transpose(); A0tA0.noalias() += (A0t * w) * A0t.transpose(); A0tA1.noalias() += (A0t * w) * A1t.transpose(); A1tA1.noalias() += (A1t * w) * A1t.transpose(); const auto wr = w * r; A0tr.noalias() += A0t * wr; A1tr.noalias() += A1t * wr; } void PatchHessian2::SetA(const Matrix2Kd& It, const Matrix2Kd& A0t, const Matrix2Kd& A1t, const ArrayKd& r, const ArrayKd& w) noexcept { const MatrixK2d wA0 = w.matrix().asDiagonal() * A0t.transpose(); const MatrixK2d wA1 = w.matrix().asDiagonal() * A1t.transpose(); ItA0.noalias() = It * wA0; ItA1.noalias() = It * wA1; A0tA0.noalias() = A0t * wA0; A0tA1.noalias() = A0t * wA1; A1tA1.noalias() = A1t * wA1; const ArrayKd wr = w * r; A0tr.noalias() = A0t * wr.matrix(); A1tr.noalias() = A1t * wr.matrix(); } /// ============================================================================ FrameHessian1& FrameHessian1::operator+=(const FrameHessian1& rhs) noexcept { if (rhs.n > 0) { H += rhs.H; b += rhs.b; n += rhs.n; c += rhs.c; } return *this; } void FrameHessian1::AddPatchHess(const PatchHessian1& ph, const Matrix26d& G, int affine_offset) noexcept { // [Gt*(It*I)*G, Gt*(It*A)] | [Gt*(It*r)] // [ (At*I)*G, (At*A)] | [ (At*r)] ++n; // FrameHessian1 is 10x10, where the variable is ordered as follows // [pose, aff0, aff1] // Add pose block, which is always top-left 6x6 // Gt * ItI * G H.topLeftCorner<dp, dp>().noalias() += G.transpose() * ph.ItI * G; // Gt * It * r b.head<dp>().noalias() -= G.transpose() * ph.Itr; // cost c += ph.r2; if (affine_offset < 0) return; // Depends on which camera, the affine parameters would be different // Therefore we use affine_offset to indicate where should we put the // corresponding Hessian block. affine_index is pose_dim + affine_offset, left // is pose_dim, right is pose_dim + affine_dim const int ia = dp + affine_offset; // 6(L) or 8(R) // https://eigen.tuxfamily.org/dox/classEigen_1_1LLT.html // Performance: for best performance, it is recommended to use a column-major // storage format with the Lower triangular part (the default), or, // equivalently, a row-major storage format with the Upper triangular part. // Otherwise, you might get a 20% slowdown for the full factorization step, // and rank-updates can be up to 3 times slower. // AtI * G H.block<da, dp>(ia, 0).noalias() += ph.ItA.transpose() * G; // AtA H.block<da, da>(ia, ia) += ph.AtA; // Atr b.segment<da>(ia) -= ph.Atr; } /// ============================================================================ FrameHessian2::FrameHessian2(int fi, int fj) : i_{fi}, j_{fj} { CHECK_GE(fi, 0); CHECK_GE(fj, 0); CHECK_NE(fi, fj); } std::string FrameHessian2::Repr() const { return fmt::format("FrameHessian2(i={}, j={}, n={}, c={:.4e})", i_, j_, n, c); } FrameHessian2& FrameHessian2::operator+=(const FrameHessian2& rhs) { CHECK_GE(i_, 0); CHECK_GE(j_, 0); CHECK_EQ(i_, rhs.i_); CHECK_EQ(j_, rhs.j_); if (rhs.n > 0) { Hii += rhs.Hii; Hij += rhs.Hij; Hjj += rhs.Hjj; bi += rhs.bi; bj += rhs.bj; c += rhs.c; n += rhs.n; } return *this; } void FrameHessian2::AddPatchHess(const PatchHessian2& ph, const Matrix26d& G0, const Matrix26d& G1, int affine_offset) noexcept { ++n; // --------------------------------------------------------------------------- // JtJ | -Jtr // --------------------------------------------------------------------------- // [Hii, , Hij ] | [bi] // [ , Hjj ] | [bj] // --------------------------------------------------------------------------- // [[G0t*ItI*G0, G0t*ItA0], [G0t*ItI*G1, G0t*ItA1]] | [G0t*Itr] // [[ A0tI*G0, A0tA0)], [ A0tI*G1, A0tA1]] | [ A0t*r] // [G1t*ItI*G1, G1t*ItA1]] | [G1t*Itr] // [ A1tI*G1, A1t*A1]] | [ A1t*r] // --------------------------------------------------------------------------- // Note that we don't strictly enforce i < j, so it is possible when i > j, we // have a lower triangular form. This is taken care of in // FullBlockHessian.Add() // Pose block // G0t * ItI * G0 Hii.topLeftCorner<dp, dp>().noalias() += G0.transpose() * ph.ItI * G0; // G0t * ItI * G1 Hij.topLeftCorner<dp, dp>().noalias() += G0.transpose() * ph.ItI * G1; // G1t * ItI * G1 Hjj.topLeftCorner<dp, dp>().noalias() += G1.transpose() * ph.ItI * G1; // G0t * Itr bi.head<dp>().noalias() -= G0.transpose() * ph.Itr; // G1t * Itr bj.head<dp>().noalias() -= G1.transpose() * ph.Itr; // cost c += ph.r2; if (affine_offset < 0) return; // since we only project points from left image, ia0 should always be 0 // ia1 depends on which image we project into, 0 for left, 2 for right const int ia0 = dp; const int ia1 = dp + affine_offset; // We only fill the upper-triangular part for now and make it symmetric later // before solving // G0t * ItA0 Hii.block<dp, da>(0, ia0).noalias() += G0.transpose() * ph.ItA0; // A0t * A0 Hii.block<da, da>(ia0, ia0) += ph.A0tA0; // This is already an off-diagonal block so we need it to be full // G0t * It * A1 Hij.block<dp, da>(0, ia1).noalias() += G0.transpose() * ph.ItA1; // A0t * I * G1 Hij.block<da, dp>(ia0, 0).noalias() += ph.ItA0.transpose() * G1; // A0t * A1 Hij.block<da, da>(ia0, ia1) += ph.A0tA1; // G1t * ItA1 Hjj.block<dp, da>(ia1, 0).noalias() += G1.transpose() * ph.ItA1; // A1t * A1 Hjj.block<da, da>(ia1, ia1) += ph.A1tA1; // A0t * r bi.segment<da>(ia0) -= ph.A0tr; // A1t * r bj.segment<da>(ia1) -= ph.A1tr; } /// ============================================================================ void FrameHessianX::ResetData() noexcept { Reset(); if (!data_.empty()) { storage().setZero(); } } int FrameHessianX::MapFrames(int nframes) { const int dim = nframes * Dim::kFrame; const int size = dim * dim + dim; ResizeData(size); auto* ptr = data_ptr(); new (&Hpp) MatrixXdMap(ptr, dim, dim); ptr += Hpp.size(); new (&bp) VectorXdMap(ptr, dim); ptr += bp.size(); CHECK_EQ(ptr - data_ptr(), size); return size; } void FrameHessianX::Scale(double s) noexcept { if (s == 1.0) return; Hpp.array() *= s; bp.array() *= s; } void FrameHessianX::AddDiag(int ind, int size, double val) { CHECK_GE(ind, 0); CHECK_LE(ind + size, Hpp.rows()) << fmt::format("ind: {}, size: {}, H: {}", ind, size, Hpp.rows()); Hpp.diagonal().segment(ind, size).array() += val; } void FrameHessianX::FixGauge(double lambda, bool fix_scale) { CHECK_GE(num_frames(), 1); AddDiag(0, df, lambda); if (fix_scale) { // Fix the translation parameter of the second frame // Ideally one only need to fix one direction of translation CHECK_GE(num_frames(), 2); AddDiag(df + 3, 3, lambda); } } /// ============================================================================ void SchurFrameHessian::AddPriorHess(const PriorFrameHessian& prior) { CHECK(prior.Ok()); CHECK_GE(num_frames(), prior.num_frames()); const auto m = prior.dim_frames(); Hpp.topLeftCorner(m, m) += prior.Hpp; bp.head(m) += prior.bp; n += prior.n; } void SchurFrameHessian::Solve(VectorXdRef xp, VectorXdRef yp) { CHECK(Ok()); CHECK(!empty()); CHECK_EQ(xp.size(), dim_frames()); // s is a copy const auto s = (Hpp.diagonal().array().abs() + 10).sqrt().inverse().matrix().eval(); const auto S = s.asDiagonal(); // Use inplace decomposition // https://eigen.tuxfamily.org/dox/group__InplaceDecomposition.html // For 4 frames, inplace solve is roughly 10x faster than normal solve (1us vs // 10us). // Because we add both a large and small value to the diagonal, we use ldlt to // ensure stability of the decomposition LdltLowerInplace solver(Hpp); xp = solver.solve(bp); yp = S.inverse() * xp; // Inplace decomp modifies storage, so we reset n n = 0; } void SchurFrameHessian::MargFrame(PriorFrameHessian& prior, int fid) { CHECK(Ok()); CHECK_GE(fid, 0); CHECK_LT(fid, num_frames()); CHECK_EQ(num_frames(), prior.num_frames() + 1); // First rotate the block that needs to be marginalized to top left. It is // possible to also rotate it to bottom right, but it is highly likely that // the oldest frame will be marginalized, so move it to top left will take // fewer operations (noop if its already there). Therefore, the subsequent // frame marginalization operation will be different from the point // marginalization one. StableRotateBlockTopLeft(Hpp, bp, fid, df); // Now we can marginalize the top left block of Hsc on to the rest MargTopLeftBlock(Hpp, bp, prior.Hpp, prior.bp, df); // Record how many points are marginalized prior.n = n; } /// ============================================================================ int FramePointHessian::CalcDataSize(int frame_dim, int point_dim) noexcept { // Hpp + Hpm + Hmm + bp + bm + xp + xm return frame_dim * frame_dim + // Hpp frame_dim * point_dim + // Hpm point_dim + // Hmm frame_dim + // bp point_dim + // bm frame_dim + // xp point_dim; // xm } std::string FramePointHessian::Repr() const { return fmt::format( "FullBlockHessian(nframes={}, npoints={}, dframes={}, dpoints={}, " "num={}, costs={:.4e}, size={}, capacity={}, usage={:.2f}%)", num_frames(), num_points(), dim_frames(), dim_points(), num_costs(), cost(), size(), capacity(), (100.0 * size()) / capacity()); } auto FramePointHessian::XpAt(int i) const noexcept -> Eigen::Map<const Vector10d> { CHECK_GE(i, 0); CHECK_LT(i, num_frames()); return Eigen::Map<const Vector10d>(xp.data() + i * df); } auto FramePointHessian::XpAt(int i) noexcept -> Eigen::Map<Vector10d> { CHECK_GE(i, 0); CHECK_LT(i, num_frames()); return Eigen::Map<Vector10d>(xp.data() + i * df); } int FramePointHessian::MapFull(int nframes, int npoints) { const int frame_dim = nframes * Dim::kFrame; const int point_dim = npoints * Dim::kPoint; const int size = CalcDataSize(frame_dim, point_dim); ResizeData(size); // https://eigen.tuxfamily.org/dox // group__TutorialMapClass.html#TutorialMapPlacementNew auto* ptr = data_ptr(); new (&Hpp) MatrixXdMap(ptr, frame_dim, frame_dim); ptr += Hpp.size(); new (&Hpm) MatrixXdMap(ptr, frame_dim, point_dim); ptr += Hpm.size(); new (&Hmm) VectorXdMap(ptr, point_dim); new (&Hmm_inv) VectorXdMap(ptr, point_dim); ptr += Hmm.size(); new (&bp) VectorXdMap(ptr, frame_dim); ptr += bp.size(); new (&bm) VectorXdMap(ptr, point_dim); ptr += bm.size(); new (&xp) VectorXdMap(ptr, frame_dim); ptr += xp.size(); new (&xm) VectorXdMap(ptr, point_dim); ptr += xm.size(); CHECK_EQ(ptr - data_ptr(), size); return size; } void FramePointHessian::ReserveFull(int nframes, int npoints) { CHECK_GT(nframes, 0); CHECK_GT(npoints, 0); const int frame_dim = nframes * Dim::kFrame; const int point_dim = npoints * Dim::kPoint; const auto size = CalcDataSize(frame_dim, point_dim); ReserveData(size); } void FramePointHessian::ResetFull(double Hpp_diag) noexcept { ready_ = false; ResetData(); if (Hpp_diag > 0) { Hpp.diagonal().setConstant(Hpp_diag); } } void FramePointHessian::AddFrameHess(const FrameHessian2& fh) { if (!fh.Ok()) return; const int ii = fh.ii(); const int jj = fh.jj(); CHECK_GE(ii, 0); CHECK_GE(jj, 0); CHECK_LT(ii, dim_frames()); CHECK_LT(jj, dim_frames()); CHECK_NE(ii, jj); // Add each sub block in pose hessian (only upper triangular block) Hpp.block<df, df>(ii, ii) += fh.Hii; Hpp.block<df, df>(jj, jj) += fh.Hjj; if (ii < jj) { Hpp.block<df, df>(ii, jj) += fh.Hij; } else { Hpp.block<df, df>(jj, ii).noalias() += fh.Hij.transpose(); } bp.segment<df>(ii) += fh.bi; bp.segment<df>(jj) += fh.bj; c += fh.c; n += fh.n; } void FramePointHessian::AddPatchHess(const PatchHessian2& ph, const Matrix26d& G0, const Matrix26d& G1, const Vector2d& Gd, const Vector3i& ijh, int affine_offset) noexcept { const int if0 = ijh[0]; // start index of frame 0 const int if1 = ijh[1]; // start index of frame 1 const int hid = ijh[2]; // index of depth point // G0t * ItI * Gd Hpm.block<dp, dd>(if0, hid).noalias() += G0.transpose() * ph.ItI * Gd; // G1t * ItI * Gd Hpm.block<dp, dd>(if1, hid).noalias() += G1.transpose() * ph.ItI * Gd; // Gdt * ItI * Gd Hmm[hid] += Gd.transpose() * ph.ItI * Gd; // Gdt * Itr bm[hid] -= Gd.transpose() * ph.Itr; if (affine_offset < 0) return; const int ia0 = if0 + dp; // aff_offset = 0, since it's always left const int ia1 = if1 + dp + affine_offset; // A0t * I * Gd Hpm.block<da, dd>(ia0, hid).noalias() += ph.ItA0.transpose() * Gd; // A1t * I * Gd Hpm.block<da, dd>(ia1, hid).noalias() += ph.ItA1.transpose() * Gd; } void FramePointHessian::Solve() { CHECK(ready_); // Back-substitute xp to get xm xm = Hmm_inv.asDiagonal() * (bm - Hpm.transpose() * xp); } void FramePointHessian::Prepare() { CHECK(!ready_); SafeCwiseInverse(Hmm); // Hmm_inv FillLowerTriangular(Hpp); ready_ = true; } int FramePointHessian::MargPointsAll(SchurFrameHessian& schur, int gsize) const { CHECK(Ok()); CHECK(ready_); // Hsc = Hpp - Hpm * Hmm^-1 * Hmp // bsc = bp - Hpm * Hmm^-1 * bm // Also update n for schur to store number of points marginalized const auto n_marged = MargPointsToFrames(Hpp, Hpm, Hmm_inv, bp, bm, schur.Hpp, schur.bp, gsize); schur.n = n_marged; return n_marged; } int FramePointHessian::MargPointsRange(SchurFrameHessian& schur, const cv::Range& range, int gsize) { CHECK(Ok()) << Repr(); CHECK_GE(range.start, 0); CHECK_LT(range.end, dim_points()); CHECK_GT(range.size(), 0); const int i = range.start; const int m = range.end - range.start; // m stores the number of points being marginalized, which might be different // from n, as some points might be considered outlier and have no // contribution. Also m is allowed to be 0 since the MargPointsToFramesLower // function can handle this case. // Manually prepare for marginalization FillLowerTriangular(Hpp); SafeCwiseInverse(Hmm.segment(i, m)); const auto n_marged = MargPointsToFrames(Hpp, Hpm.middleCols(i, m), Hmm_inv.segment(i, m), bp, bm.segment(i, m), schur.Hpp, schur.bp, gsize); schur.n = n_marged; return n_marged; } int MargPointsToFrames(const MatrixXdCRef& Hpp, const MatrixXdCRef& Hpm, const VectorXdCRef& Hmm_inv, const VectorXdCRef& bp, const VectorXdCRef& bm, MatrixXdRef Hsc, VectorXdRef bsc, int gsize) { // https://www.robots.ox.ac.uk/~gsibley/Personal/Papers/gsibley-springer2007.pdf // [ Hpp Hpm ] [ xp ] = [ bp ] // [ Hpm Hmm ] [ xm ] = [ bm ] // Hsc = Hpp - Hpm * Hmm^-1 * Hmp // bsc = bp - Hpm * Hmm^-1 * bm // Pre-condition // 1. Hpp is square/symmetric and matches Hpm and bp // 2. Hsc is square and matches Hpp and bsc const auto dim_frames = bp.size(); const auto dim_points = bm.size(); CHECK_GT(dim_frames, 0); CHECK_EQ(Hpp.rows(), dim_frames); CHECK_EQ(Hpp.cols(), dim_frames); CHECK_EQ(Hpm.rows(), dim_frames); CHECK_EQ(Hpm.cols(), dim_points); CHECK_EQ(Hmm_inv.size(), dim_points); CHECK_EQ(Hpp, Hpp.transpose()) << "\n" << Hpp; CHECK_EQ(Hsc.rows(), dim_frames); CHECK_EQ(Hsc.cols(), dim_frames); CHECK_EQ(bsc.size(), dim_frames); // Writing efficient matrix product expressions // https://eigen.tuxfamily.org/dox/TopicWritingEfficientProductExpression.html // m1.noalias() = m4 + m2 * m3; // Should be // m1 = m4; // m1.noalias() += m2 * m3; // Simple benchmark shows no huge difference though, probably because Hpp is // much smaller compared to Hpm. However, doing this allows us to nicely // handle the case where no points are to be marginalized Hsc = Hpp; bsc = bp; // If no points to marg, then just set Hsc to Hpp and return if (dim_points == 0) return 0; if (gsize <= 0) { // Single thread Hsc.noalias() -= Hpm * Hmm_inv.asDiagonal() * Hpm.transpose(); } else { // Parallel // First compute Hpm * Hmm^-1 * Hpm^T, only fill lower triangular part // Hsc is column major, thus we fill each column per thread // for each column in lower triangular part we compute // Hsc[i:,i] -= Hpm[i:,:] * (Hmm_inv * Hpm[i,:]) ParallelFor({0, static_cast<int>(dim_frames), gsize}, [&](int i) { const auto r = dim_frames - i; Hsc.col(i).tail(r).noalias() -= Hpm.bottomRows(r) * (Hmm_inv.asDiagonal() * Hpm.row(i).transpose()); }); } // Make sure Hsc is symmetric FillUpperTriangular(Hsc); bsc.noalias() -= Hpm * (Hmm_inv.asDiagonal() * bm); // Post-condition // 1. Hsc shape doesn't change CHECK_EQ(Hsc.rows(), dim_frames); CHECK_EQ(Hsc.cols(), dim_frames); CHECK_EQ(bsc.size(), dim_frames); return static_cast<int>((bm.array() != 0).count()); } int PointHessian::MapPoints(int npoints) { const int dim = npoints * Dim::kPoint; const int size = dim * 3; data_.resize(size); auto* ptr = data_.data(); new (&H) VectorXdMap(ptr, dim); ptr += H.size(); new (&b) VectorXdMap(ptr, dim); ptr += b.size(); new (&x) VectorXdMap(ptr, dim); ptr += x.size(); CHECK_EQ(ptr - data_.data(), size); return size; } } // namespace sv::dsol
// // Revision.hpp // PretendToWork // // Created by tqtifnypmb on 14/12/2017. // Copyright © 2017 tqtifnypmb. All rights reserved. // #pragma once #include "../rope/Range.h" #include "../types.h" #include <gsl/gsl> #include <vector> #include <string> namespace brick { class Rope; class Revision { public: enum class Operation { insert, erase, }; Revision(size_t authorId, size_t revId, Operation op, const Range& range); Revision(size_t authorId, size_t revId, Operation op, const Range& range, const detail::CodePointList& text); Revision(const Revision&) = default; Revision() = default; void apply(gsl::not_null<Rope*> rope) const; bool canApply(gsl::not_null<const Rope*> rope) const; size_t authorId() const { return authorId_; } bool prior(const Revision& rev) const { return authorId() <= rev.authorId(); } size_t revId() const { return revId_; } const Range& range() const { return range_; } Range& range() { return range_; } int affectLength() const { if (op() == Operation::insert) { return static_cast<int>(cplist().size()); } else { return range().length; } } Operation op() const { return op_; } bool valid() const { return !range_.empty() && range_.location >= 0; } void setInvalid() { range_.length = 0; } const detail::CodePointList& cplist() const { return cplist_; } private: size_t authorId_; // revId_ only identify individual revision // newer revision doesn't have to have greater revId_ size_t revId_; detail::CodePointList cplist_; Operation op_; Range range_; }; } // namespace brick
<a href="https://colab.research.google.com/github/StevenMElliott/AB-Demo/blob/master/Copy_of_Linear_Algebra_Assignment.ipynb" target="_parent"></a> # Part 1 - Scalars and Vectors For the questions below it is not sufficient to simply provide answer to the questions, but you must solve the problems and show your work using python (the NumPy library will help a lot!) Translate the vectors and matrices into their appropriate python representations and use numpy or functions that you write yourself to demonstrate the result or property. ``` import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np ``` ## 1.1 Create a two-dimensional vector and plot it on a graph ``` v1 = [300,250] plt.arrow(0,0, 300, 250, head_width=10, head_length=10, color='r'); plt.title('Red Vector') plt.axis([0, 350, 0, 300]); #([-x, x, -y, y]) limits of the graph - BRACKETS ``` ## 1.2 Create a three-dimensional vecor and plot it on a graph ``` vectors = np.array( [[0,0,0,-1,-0,1]]) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') for vector in vectors: v = np.array([vector[3],vector[4],vector[5]]) vlength=np.linalg.norm(v) ax.quiver(vector[0], vector[1], vector[2], vector[3], vector[4], vector[5], pivot='tail',length=vlength,arrow_length_ratio=0.3/vlength) ax.set_xlim([-3,3]) ax.set_ylim([-3,3]) ax.set_zlim([0,3]); ``` ## 1.3 Scale the vectors you created in 1.1 by $5$, $\pi$, and $-e$ and plot all four vectors (original + 3 scaled vectors) on a graph. What do you notice about these vectors? ``` from math import e, pi ``` ``` v1 = [300, 250] v2 =[(300*5), (250*5)] v3 = [(300*pi), (250*pi)] v4 = [(300*-e), (250*-e)] ``` ``` #the vectors and scalers v1 = [300, 250] v2 =[(300*5), (250*5)] v3 = [(300*pi), (250*pi)] v4 = [(300*-e), (250*-e)] #plot the vectors original = plt.arrow(0,0, v1[0], v1[1], head_width=100 , head_length=100, color='r'); scaled_by_5 = plt.arrow(0,0, v2[0], v2[1], head_width=100 , head_length=100, color='b'); scaled_by_pi = plt.arrow(0,0, v3[0], v3[1], head_width=100 , head_length=100, color='y'); scaled_by_neg_e = plt.arrow(0,0, v4[0], v4[1], head_width=100 , head_length=100, color='black'); #reference lings and limits plt.grid() plt.axhline(y=0, alpha=.5) plt.axvline(x=0, alpha=.5) plt.axis([-1600, 1600, -1600, 1600]); ``` These vectors are colinear ## 1.4 Graph vectors $\vec{a}$ and $\vec{b}$ and plot them on a graph \begin{align} \vec{a} = \begin{bmatrix} 5 \\ 7 \end{bmatrix} \qquad \vec{b} = \begin{bmatrix} 3 \\4 \end{bmatrix} \end{align} ``` a = np.array([5,7]) b = np.array([3,4]) plt.arrow(0,0, a[0], a[1], head_width=.2, head_length=.2, color='r'); plt.arrow(0,0, b[0], b[1], head_width=.2, head_length=.2, color='b'); plt.axis([0,8,0,8]); ``` ## 1.5 find $\vec{a} - \vec{b}$ and plot the result on the same graph as $\vec{a}$ and $\vec{b}$. Is there a relationship between vectors $\vec{a} \thinspace, \vec{b} \thinspace \text{and} \thinspace \vec{a-b}$ ``` a = np.array([5,7]) b = np.array([3,4]) difference = a-b plt.arrow(0,0, a[0], a[1], head_width=.2, head_length=.2, color='r'); plt.arrow(0,0, b[0], b[1], head_width=.2, head_length=.2, color='b'); plt.arrow(0,0, difference[0], difference[1], head_width=.2, head_length=.2, color='k'); print('The result is:',difference) plt.axis([0,8,0,8]);c = a-b ``` The relationship is taking the values from the first and subtracting the values of the 2nd. The 3rd vector is equal to (2, 3) ## 1.6 Find $c \cdot d$ \begin{align} \vec{c} = \begin{bmatrix}7 & 22 & 4 & 16\end{bmatrix} \qquad \vec{d} = \begin{bmatrix}12 & 6 & 2 & 9\end{bmatrix} \end{align} ``` ``` ## 1.7 Find $e \times f$ \begin{align} \vec{e} = \begin{bmatrix} 5 \\ 7 \\ 2 \end{bmatrix} \qquad \vec{f} = \begin{bmatrix} 3 \\4 \\ 6 \end{bmatrix} \end{align} ``` ``` ## 1.8 Find $||g||$ and then find $||h||$. Which is longer? \begin{align} \vec{e} = \begin{bmatrix} 1 \\ 1 \\ 1 \\ 8 \end{bmatrix} \qquad \vec{f} = \begin{bmatrix} 3 \\3 \\ 3 \\ 3 \end{bmatrix} \end{align} ``` ``` ## 1.9 Show that the following vectors are orthogonal (perpendicular to each other): \begin{align} \vec{g} = \begin{bmatrix} 1 \\ 0 \\ -1 \end{bmatrix} \qquad \vec{h} = \begin{bmatrix} 1 \\ \sqrt{2} \\ 1 \end{bmatrix} \end{align} ``` ``` # Part 2 - Matrices ## 2.1 What are the dimensions of the following matrices? Which of the following can be multiplied together? See if you can find all of the different legal combinations. \begin{align} A = \begin{bmatrix} 1 & 2 \\ 3 & 4 \\ 5 & 6 \end{bmatrix} \qquad B = \begin{bmatrix} 2 & 4 & 6 \\ \end{bmatrix} \qquad C = \begin{bmatrix} 9 & 6 & 3 \\ 4 & 7 & 11 \end{bmatrix} \qquad D = \begin{bmatrix} 1 & 0 & 0 \\ 0 & 1 & 0 \\ 0 & 0 & 1 \end{bmatrix} \qquad E = \begin{bmatrix} 1 & 3 \\ 5 & 7 \end{bmatrix} \end{align} ``` ``` ## 2.2 Find the following products: CD, AE, and BA. What are the dimensions of the resulting matrices? How does that relate to the dimensions of their factor matrices? ``` ``` ## 2.3 Find $F^{T}$. How are the numbers along the main diagonal (top left to bottom right) of the original matrix and its transpose related? What are the dimensions of $F$? What are the dimensions of $F^{T}$? \begin{align} F = \begin{bmatrix} 20 & 19 & 18 & 17 \\ 16 & 15 & 14 & 13 \\ 12 & 11 & 10 & 9 \\ 8 & 7 & 6 & 5 \\ 4 & 3 & 2 & 1 \end{bmatrix} \end{align} ``` ``` # Part 3 - Square Matrices ## 3.1 Find $IG$ (be sure to show your work) 😃 \begin{align} G= \begin{bmatrix} 12 & 11 \\ 7 & 10 \end{bmatrix} \end{align} ``` ``` ## 3.2 Find $|H|$ and then find $|J|$. \begin{align} H= \begin{bmatrix} 12 & 11 \\ 7 & 10 \end{bmatrix} \qquad J= \begin{bmatrix} 0 & 1 & 2 \\ 7 & 10 & 4 \\ 3 & 2 & 0 \end{bmatrix} \end{align} ``` ``` ## 3.3 Find H^{-1} and then find J^{-1} ``` ``` ## 3.4 Find $HH^{-1}$ and then find $G^{-1}G$. Is $HH^{-1} == G^{-1}G$? Why or Why not? # Stretch Goals: A reminder that these challenges are optional. If you finish your work quickly we welcome you to work on them. If there are other activities that you feel like will help your understanding of the above topics more, feel free to work on that. Topics from the Stretch Goals sections will never end up on Sprint Challenges. You don't have to do these in order, you don't have to do all of them. - Write a function that can calculate the dot product of any two vectors of equal length that are passed to it. - Write a function that can calculate the norm of any vector - Prove to yourself again that the vectors in 1.9 are orthogonal by graphing them. - Research how to plot a 3d graph with animations so that you can make the graph rotate (this will be easier in a local notebook than in google colab) - Create and plot a matrix on a 2d graph. - Create and plot a matrix on a 3d graph. - Plot two vectors that are not collinear on a 2d graph. Calculate the determinant of the 2x2 matrix that these vectors form. How does this determinant relate to the graphical interpretation of the vectors?
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Bhavik Mehta -/ import category_theory.limits.has_limits import category_theory.discrete_category /-! # Categorical (co)products > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines (co)products as special cases of (co)limits. A product is the categorical generalization of the object `Π i, f i` where `f : ι → C`. It is a limit cone over the diagram formed by `f`, implemented by converting `f` into a functor `discrete ι ⥤ C`. A coproduct is the dual concept. ## Main definitions * a `fan` is a cone over a discrete category * `fan.mk` constructs a fan from an indexed collection of maps * a `pi` is a `limit (discrete.functor f)` Each of these has a dual. ## Implementation notes As with the other special shapes in the limits library, all the definitions here are given as `abbreviation`s of the general statements for limits, so all the `simp` lemmas and theorems about general limits can be used. -/ noncomputable theory universes w v v₂ u u₂ open category_theory namespace category_theory.limits variables {β : Type w} variables {C : Type u} [category.{v} C] -- We don't need an analogue of `pair` (for binary products), `parallel_pair` (for equalizers), -- or `(co)span`, since we already have `discrete.functor`. local attribute [tidy] tactic.discrete_cases /-- A fan over `f : β → C` consists of a collection of maps from an object `P` to every `f b`. -/ abbreviation fan (f : β → C) := cone (discrete.functor f) /-- A cofan over `f : β → C` consists of a collection of maps from every `f b` to an object `P`. -/ abbreviation cofan (f : β → C) := cocone (discrete.functor f) /-- A fan over `f : β → C` consists of a collection of maps from an object `P` to every `f b`. -/ @[simps] def fan.mk {f : β → C} (P : C) (p : Π b, P ⟶ f b) : fan f := { X := P, π := { app := λ X, p X.as } } /-- A cofan over `f : β → C` consists of a collection of maps from every `f b` to an object `P`. -/ @[simps] def cofan.mk {f : β → C} (P : C) (p : Π b, f b ⟶ P) : cofan f := { X := P, ι := { app := λ X, p X.as } } -- FIXME dualize as needed below (and rename?) /-- Get the `j`th map in the fan -/ def fan.proj {f : β → C} (p : fan f) (j : β) : p.X ⟶ f j := p.π.app (discrete.mk j) @[simp] lemma fan_mk_proj {f : β → C} (P : C) (p : Π b, P ⟶ f b) (j : β) : (fan.mk P p).proj j = p j := rfl /-- An abbreviation for `has_limit (discrete.functor f)`. -/ abbreviation has_product (f : β → C) := has_limit (discrete.functor f) /-- An abbreviation for `has_colimit (discrete.functor f)`. -/ abbreviation has_coproduct (f : β → C) := has_colimit (discrete.functor f) /-- Make a fan `f` into a limit fan by providing `lift`, `fac`, and `uniq` -- just a convenience lemma to avoid having to go through `discrete` -/ @[simps] def mk_fan_limit {f : β → C} (t : fan f) (lift : Π s : fan f, s.X ⟶ t.X) (fac : ∀ (s : fan f) (j : β), lift s ≫ (t.proj j) = s.proj j) (uniq : ∀ (s : fan f) (m : s.X ⟶ t.X) (w : ∀ j : β, m ≫ t.proj j = s.proj j), m = lift s) : is_limit t := { lift := lift, fac' := λ s j, by convert fac s j.as; simp, uniq' := λ s m w, uniq s m (λ j, w (discrete.mk j)), } section variables (C) /-- An abbreviation for `has_limits_of_shape (discrete f)`. -/ abbreviation has_products_of_shape (β : Type v) := has_limits_of_shape.{v} (discrete β) /-- An abbreviation for `has_colimits_of_shape (discrete f)`. -/ abbreviation has_coproducts_of_shape (β : Type v) := has_colimits_of_shape.{v} (discrete β) end /-- `pi_obj f` computes the product of a family of elements `f`. (It is defined as an abbreviation for `limit (discrete.functor f)`, so for most facts about `pi_obj f`, you will just use general facts about limits.) -/ abbreviation pi_obj (f : β → C) [has_product f] := limit (discrete.functor f) /-- `sigma_obj f` computes the coproduct of a family of elements `f`. (It is defined as an abbreviation for `colimit (discrete.functor f)`, so for most facts about `sigma_obj f`, you will just use general facts about colimits.) -/ abbreviation sigma_obj (f : β → C) [has_coproduct f] := colimit (discrete.functor f) notation `∏ ` f:20 := pi_obj f notation `∐ ` f:20 := sigma_obj f /-- The `b`-th projection from the pi object over `f` has the form `∏ f ⟶ f b`. -/ abbreviation pi.π (f : β → C) [has_product f] (b : β) : ∏ f ⟶ f b := limit.π (discrete.functor f) (discrete.mk b) /-- The `b`-th inclusion into the sigma object over `f` has the form `f b ⟶ ∐ f`. -/ abbreviation sigma.ι (f : β → C) [has_coproduct f] (b : β) : f b ⟶ ∐ f := colimit.ι (discrete.functor f) (discrete.mk b) /-- The fan constructed of the projections from the product is limiting. -/ def product_is_product (f : β → C) [has_product f] : is_limit (fan.mk _ (pi.π f)) := is_limit.of_iso_limit (limit.is_limit (discrete.functor f)) (cones.ext (iso.refl _) (by tidy)) /-- The cofan constructed of the inclusions from the coproduct is colimiting. -/ def coproduct_is_coproduct (f : β → C) [has_coproduct f] : is_colimit (cofan.mk _ (sigma.ι f)) := is_colimit.of_iso_colimit (colimit.is_colimit (discrete.functor f)) (cocones.ext (iso.refl _) (by tidy)) /-- A collection of morphisms `P ⟶ f b` induces a morphism `P ⟶ ∏ f`. -/ abbreviation pi.lift {f : β → C} [has_product f] {P : C} (p : Π b, P ⟶ f b) : P ⟶ ∏ f := limit.lift _ (fan.mk P p) /-- A collection of morphisms `f b ⟶ P` induces a morphism `∐ f ⟶ P`. -/ abbreviation sigma.desc {f : β → C} [has_coproduct f] {P : C} (p : Π b, f b ⟶ P) : ∐ f ⟶ P := colimit.desc _ (cofan.mk P p) /-- Construct a morphism between categorical products (indexed by the same type) from a family of morphisms between the factors. -/ abbreviation pi.map {f g : β → C} [has_product f] [has_product g] (p : Π b, f b ⟶ g b) : ∏ f ⟶ ∏ g := lim_map (discrete.nat_trans (λ X, p X.as)) instance pi.map_mono {f g : β → C} [has_product f] [has_product g] (p : Π b, f b ⟶ g b) [Π i, mono (p i)] : mono $ pi.map p := @@limits.lim_map_mono _ _ _ _ _ (by { dsimp, apply_instance }) /-- Construct an isomorphism between categorical products (indexed by the same type) from a family of isomorphisms between the factors. -/ abbreviation pi.map_iso {f g : β → C} [has_products_of_shape β C] (p : Π b, f b ≅ g b) : ∏ f ≅ ∏ g := lim.map_iso (discrete.nat_iso (λ X, p X.as)) /-- Construct a morphism between categorical coproducts (indexed by the same type) from a family of morphisms between the factors. -/ abbreviation sigma.map {f g : β → C} [has_coproduct f] [has_coproduct g] (p : Π b, f b ⟶ g b) : ∐ f ⟶ ∐ g := colim_map (discrete.nat_trans (λ X, p X.as)) instance sigma.map_epi {f g : β → C} [has_coproduct f] [has_coproduct g] (p : Π b, f b ⟶ g b) [Π i, epi (p i)] : epi $ sigma.map p := @@limits.colim_map_epi _ _ _ _ _ (by { dsimp, apply_instance }) /-- Construct an isomorphism between categorical coproducts (indexed by the same type) from a family of isomorphisms between the factors. -/ abbreviation sigma.map_iso {f g : β → C} [has_coproducts_of_shape β C] (p : Π b, f b ≅ g b) : ∐ f ≅ ∐ g := colim.map_iso (discrete.nat_iso (λ X, p X.as)) section comparison variables {D : Type u₂} [category.{v₂} D] (G : C ⥤ D) variables (f : β → C) /-- The comparison morphism for the product of `f`. This is an iso iff `G` preserves the product of `f`, see `preserves_product.of_iso_comparison`. -/ def pi_comparison [has_product f] [has_product (λ b, G.obj (f b))] : G.obj (∏ f) ⟶ ∏ (λ b, G.obj (f b)) := pi.lift (λ b, G.map (pi.π f b)) @[simp, reassoc] lemma pi_comparison_comp_π [has_product f] [has_product (λ b, G.obj (f b))] (b : β) : pi_comparison G f ≫ pi.π _ b = G.map (pi.π f b) := limit.lift_π _ (discrete.mk b) @[simp, reassoc] lemma map_lift_pi_comparison [has_product f] [has_product (λ b, G.obj (f b))] (P : C) (g : Π j, P ⟶ f j) : G.map (pi.lift g) ≫ pi_comparison G f = pi.lift (λ j, G.map (g j)) := by { ext, discrete_cases, simp [← G.map_comp] } /-- The comparison morphism for the coproduct of `f`. This is an iso iff `G` preserves the coproduct of `f`, see `preserves_coproduct.of_iso_comparison`. -/ def sigma_comparison [has_coproduct f] [has_coproduct (λ b, G.obj (f b))] : ∐ (λ b, G.obj (f b)) ⟶ G.obj (∐ f) := sigma.desc (λ b, G.map (sigma.ι f b)) @[simp, reassoc] lemma ι_comp_sigma_comparison [has_coproduct f] [has_coproduct (λ b, G.obj (f b))] (b : β) : sigma.ι _ b ≫ sigma_comparison G f = G.map (sigma.ι f b) := colimit.ι_desc _ (discrete.mk b) @[simp, reassoc] lemma sigma_comparison_map_desc [has_coproduct f] [has_coproduct (λ b, G.obj (f b))] (P : C) (g : Π j, f j ⟶ P) : sigma_comparison G f ≫ G.map (sigma.desc g) = sigma.desc (λ j, G.map (g j)) := by { ext, discrete_cases, simp [← G.map_comp] } end comparison variables (C) /-- An abbreviation for `Π J, has_limits_of_shape (discrete J) C` -/ abbreviation has_products := Π (J : Type w), has_limits_of_shape (discrete J) C /-- An abbreviation for `Π J, has_colimits_of_shape (discrete J) C` -/ abbreviation has_coproducts := Π (J : Type w), has_colimits_of_shape (discrete J) C variable {C} lemma has_smallest_products_of_has_products [has_products.{w} C] : has_products.{0} C := λ J, has_limits_of_shape_of_equivalence (discrete.equivalence equiv.ulift : discrete (ulift.{w} J) ≌ _) lemma has_smallest_coproducts_of_has_coproducts [has_coproducts.{w} C] : has_coproducts.{0} C := λ J, has_colimits_of_shape_of_equivalence (discrete.equivalence equiv.ulift : discrete (ulift.{w} J) ≌ _) lemma has_products_of_limit_fans (lf : ∀ {J : Type w} (f : J → C), fan f) (lf_is_limit : ∀ {J : Type w} (f : J → C), is_limit (lf f)) : has_products.{w} C := λ (J : Type w), { has_limit := λ F, has_limit.mk ⟨(cones.postcompose discrete.nat_iso_functor.inv).obj (lf (λ j, F.obj ⟨j⟩)), (is_limit.postcompose_inv_equiv _ _).symm (lf_is_limit _)⟩ } /-! (Co)products over a type with a unique term. -/ section unique variables {C} [unique β] (f : β → C) /-- The limit cone for the product over an index type with exactly one term. -/ @[simps] def limit_cone_of_unique : limit_cone (discrete.functor f) := { cone := { X := f default, π := { app := λ j, eq_to_hom (by { dsimp, congr, }), }, }, is_limit := { lift := λ s, s.π.app default, fac' := λ s j, begin have w := (s.π.naturality (eq_to_hom (unique.default_eq _))).symm, dsimp at w, simpa [eq_to_hom_map] using w, end, uniq' := λ s m w, begin specialize w default, dsimp at w, simpa using w, end, }, } @[priority 100] instance has_product_unique : has_product f := has_limit.mk (limit_cone_of_unique f) /-- A product over a index type with exactly one term is just the object over that term. -/ @[simps] def product_unique_iso : ∏ f ≅ f default := is_limit.cone_point_unique_up_to_iso (limit.is_limit _) (limit_cone_of_unique f).is_limit /-- The colimit cocone for the coproduct over an index type with exactly one term. -/ @[simps] def colimit_cocone_of_unique : colimit_cocone (discrete.functor f) := { cocone := { X := f default, ι := { app := λ j, eq_to_hom (by { discrete_cases, dsimp, congr, }), }, }, is_colimit := { desc := λ s, s.ι.app default, fac' := λ s j, begin have w := (s.ι.naturality (eq_to_hom (unique.eq_default _))), dsimp at w, simpa [eq_to_hom_map] using w, end, uniq' := λ s m w, begin specialize w default, dsimp at w, simpa using w, end, }, } @[priority 100] instance has_coproduct_unique : has_coproduct f := has_colimit.mk (colimit_cocone_of_unique f) /-- A coproduct over a index type with exactly one term is just the object over that term. -/ @[simps] def coproduct_unique_iso : ∐ f ≅ f default := is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit _) (colimit_cocone_of_unique f).is_colimit end unique section reindex variables {C} {γ : Type v} (ε : β ≃ γ) (f : γ → C) section variables [has_product f] [has_product (f ∘ ε)] /-- Reindex a categorical product via an equivalence of the index types. -/ def pi.reindex : pi_obj (f ∘ ε) ≅ pi_obj f := has_limit.iso_of_equivalence (discrete.equivalence ε) (discrete.nat_iso (λ i, iso.refl _)) @[simp, reassoc] lemma pi.reindex_hom_π (b : β) : (pi.reindex ε f).hom ≫ pi.π f (ε b) = pi.π (f ∘ ε) b := begin dsimp [pi.reindex], simp only [has_limit.iso_of_equivalence_hom_π, discrete.nat_iso_inv_app, equivalence.equivalence_mk'_counit, discrete.equivalence_counit_iso, discrete.nat_iso_hom_app, eq_to_iso.hom, eq_to_hom_map], dsimp, simpa [eq_to_hom_map] using limit.w (discrete.functor (f ∘ ε)) (discrete.eq_to_hom' (ε.symm_apply_apply b)), end @[simp, reassoc] lemma pi.reindex_inv_π (b : β) : (pi.reindex ε f).inv ≫ pi.π (f ∘ ε) b = pi.π f (ε b) := by simp [iso.inv_comp_eq] end section variables [has_coproduct f] [has_coproduct (f ∘ ε)] /-- Reindex a categorical coproduct via an equivalence of the index types. -/ def sigma.reindex : sigma_obj (f ∘ ε) ≅ sigma_obj f := has_colimit.iso_of_equivalence (discrete.equivalence ε) (discrete.nat_iso (λ i, iso.refl _)) @[simp, reassoc] lemma sigma.ι_reindex_hom (b : β) : sigma.ι (f ∘ ε) b ≫ (sigma.reindex ε f).hom = sigma.ι f (ε b) := begin dsimp [sigma.reindex], simp only [has_colimit.iso_of_equivalence_hom_π, equivalence.equivalence_mk'_unit, discrete.equivalence_unit_iso, discrete.nat_iso_hom_app, eq_to_iso.hom, eq_to_hom_map, discrete.nat_iso_inv_app], dsimp, simp [eq_to_hom_map, ←colimit.w (discrete.functor f) (discrete.eq_to_hom' (ε.apply_symm_apply (ε b)))], end @[simp, reassoc] lemma sigma.ι_reindex_inv (b : β) : sigma.ι f (ε b) ≫ (sigma.reindex ε f).inv = sigma.ι (f ∘ ε) b := by simp [iso.comp_inv_eq] end end reindex end category_theory.limits
\section{Compactness} Recall that a continuous, real-valued function on a closed bounded interval is bounded and attains its bound. The question is, for which topological space $X$ is it true that every continuous real functions is bounded. \begin{example} 1. For finite $X$, every function $X\to\mathbb R$ is bounded.\\ 2. If for all continuous $f:X\to\mathbb R,\exists n\in\mathbb N,\exists A_1,A_2,\ldots,A_n\subset X$ such that $X=\bigcup_iA_i$ and $f$ is bounded on each $A_i$, then $f$ is bounded on $X$. \end{example} Note that given continuous $f:X\to\mathbb R$, for $x\in X$, $U_x=f^{-1}((f(x)-1,f(x)+1))$ is open and $f$ is bounded there. So if there is some finite subset of $\{U_x:x\in X\}$ that still covers $X$, then $f$ must be bounded. \begin{definition} An open cover of a topological space $X$ is a family of open sets $\mathscr U=\{U_i\}_{i\in I}$ in $X$ such that $X=\bigcup_{i\in I}U_i$.\\ A subcover of $\mathscr U$ is a subset $\mathscr V\subset \mathscr U$ that is also an open cover of $X$. $\mathscr V$ is called a finite subcover if it is finite.\\ $X$ is compact if every open cover of $X$ has a finite subcover. \end{definition} \begin{theorem} If $X\neq\varnothing$ is compact and $f:X\to\mathbb R$ is continuous, then $f$ is bounded and attains its bound. \end{theorem} \begin{proof} By continuity of $f$ and compactness of $X$, there is a finite subset of $\{f^{-1}((f(x)-1,f(x)+1)):x\in X\}$ that covers $X$, which means that $f$ is bounded on any set in a finite family, so $f$ is bounded in the union of that family, which is $X$. To show that $f$ attains its bound, let $m=\{f(x):x\in X\}$ which exists since $X\neq\varnothing$ and $f$ is bounded. Suppose that there is not an $x$ with $f(x)=m$, so for any $x\in X,f(x)>m$ so $\exists m_x$ such that $f(x)>m_x>m$. Let $U_x=f^{-1}((m_x,\infty))$ which is open and contains $x$, and $\inf_{U_x}f\ge m_x>x$. Note that the family of all $U_x$ is an open cover of $X$, so there is a finite subcover $\{U_x\}_{x\in F}$, so $\forall y\in X,f(y)\ge \min_{x\in F}m_x>m$, contradiction. \end{proof} Note that for a subspace $Y\subset X$, $Y$ is compact iff whenever $\mathscr U$ is a family of open set in $X$ whose union contains $Y$, there is a finite subset $\mathscr V\subset \mathscr U$ such that the union of elements in $\mathscr V$ contains $Y$. \begin{theorem}\label{01compact} $[0,1]$ is compact. \end{theorem} \begin{proof} Let $\mathscr U$ be a set of open sets in $\mathbb R$ thar contains $[0,1]$, assume that there does not exist finite subcover that contains $[0,1]$, then if $0\le a<b\le 1$ and $[a,b]$ cannot be covered by any finite $\mathscr V\subset\mathscr U$, then let $C=(a+b)/2$, then one of $[a,c],[c,b]$ cannot be covered by finite $\mathscr V\subset\mathscr U$.\\ Therefore, inductively we can find intervals $I_n=[a_n,b_n]$ such that $$I_0=[0,1],I_{n+1}\subset I_n,|b_n-a_n|=1/2^n$$ thus $a_n\to x,b_n=a_n+(b_n-a_n)\to x$ for some $x\in [0,1]$. Now there is $U\subset \mathscr U$ such that $x\in U$, but then there is some $\epsilon$ with $(x-\epsilon,x+\epsilon)\subset U$, therefore for sufficiently large $n$, $I_n\subset U$, which is a contradiction. \end{proof} \begin{proposition}\label{compact_haus_closed} Let $X$ be a topological space and $Y\subset X$ a subspace, then\\ 1. If $X$ is compact and $Y$ is closed in $X$, then $Y$ is compact.\\ 2. If $X$ is Hausdorff and $Y$ is compact, then $Y$ is closed. \end{proposition} \begin{proof} 1. Let $\mathscr U$ covers $Y$, then $\mathscr U\cup \{X\setminus Y\}$ is an open cover of $X$. Since $X$ is compact, there is a finite subcover $\mathscr V\subset \mathscr U\cup \{X\setminus Y\}$ that covers $X$, hence $\mathscr V\setminus\{X\setminus Y\}\subset \mathscr U$ is finite and covers $Y$.\\ 2. We want to show that its complement is open. Indeed, for any $x\in X\setminus Y$, and for any $y\in Y$, there are disjoint $U_y,V_y$ such that $x\in U_y,y\in V_y$, then $\{V_y\}_{y\in Y}$ is an open cover of $Y$, thus there is some finite set $F\subset Y$ such that $Y\subset\bigcup_{y\in F}V_y$, so $U=\cap_{y\in F}U_y$ is open, and by definition it is disjoint from $Y$, hence $x\in U\subset X\setminus Y$, which shows that $X\setminus Y$ is open. \end{proof} \begin{proposition} If $X$ is compact and $f:X\to Y$ is continuous, then $f(X)$ is compact. \end{proposition} \begin{proof} For any open $\{U_i\}_{i\in I}$ that covers $f(X)$, $\{f^{-1}(U_i)\}_{i\in I}$ is an open cover of $X$, therefore there is some finite $F\subset I$ such that $\{f^{-1}(U_i)\}_{i\in F}$ covers $X$, hence $\{U_i\}_{i\in F}$ covers $f(X)$. \end{proof} \begin{remark} 1. Compactness is a topological property.\\ 2. Let $f:X\to Y$ and $A\subset X$. Suppose $A$ is compact, then $f(A)$ is compact. \end{remark} \begin{example} For $a<b$, $[a,b]=f([0,1])$ where $f(x)=(b-a)x+a$ which is continuous, thus every closed bounded interval is compact. \end{example} \begin{corollary} If $X$ is compact and $R$ is an equivalence relation on $X$, then $X/R$ is compact. \end{corollary} \begin{proof} The quotient map is continuous and surjective. \end{proof} \begin{theorem}[Topological Inverse Function Theorem] If $f:X\to Y$ is a continuous bijection and $X$ is compact and $Y$ is Hausdorff, then $f$ is a homeomorphism. \end{theorem} \begin{proof} It suffices to check that $f$ is an open map, which, since $f$ is a bijection, is equivalent to say that $f$ is a closed map.\\ Fix any closed $V\subset X$, then $V$ is compact since $X$ is compact, thus $f(V)$ is compact since $f$ is continuous, therefore $f(V)$ is closed since $Y$ is hausfdorff. The result follows. \end{proof} \begin{example} Consider $f:\mathbb R\to S^1$ by $f(t)=e^{2\pi it}$ induces a continuous bijection $\tilde{f}:\mathbb R/\mathbb Z\to S^1$. Now $\mathbb R/\mathbb Z=q([0,1])$ (where $q$ is the quotient map) is compact and $S^1$ is Hausdorff since it is a metric space, therefore $\tilde{f}$ is a homeomorphism. \end{example} \begin{theorem}[Tychonorff's Theorem on Finite Products \footnote{It works for arbitrary products, but that case is much much harder} ]\label{tycho_finite} Finite products of compact spaces are compact. \end{theorem} \begin{proof} It suffices to show for $2$.\\ Assume $X,Y$ are compact. Fix $x\in X$, $\exists W_y\in\mathscr U$ with $x,y\in W_y$, so there is some $U_y$ open in $X$ and $V_y$ open in $Y$ such that $(x,y)\in U_y\times V_y\subset W_y$, so there is a finite $F_Y\subset Y$ with $\bigcup_{y\in F_Y}V_y=Y$. Let $T_x=\bigcup_{y\in F_Y}U_y$ is open and contains $x$ and note that $T_x\times Y\subset \bigcup_{y\in F_Y}W_y$. But then $\{T_x\}_{x\in X}$ covers $X$, so there is a finite $F_X\subset X$ such that $\{T_x\}_{x\in F_X}$ covers $X$, hence $$X\times Y\subset \bigcup_{x\in F_X}T_x\times Y=\bigcup_{x\in F_X}\bigcup_{y\in F_Y}W_y$$ The last term is the required finite subcover. \end{proof} \begin{theorem}[Heine-Borel Theorem] A subset $K\subset\mathbb R^n$ if and only if it is closed and bounded. \end{theorem} \begin{proof} If $K$ is compact, note that $f:\mathbb R^n\to\mathbb R$ by $x\mapsto \|x\|$, thus it is bounded. $K$ is also closed by Proposition \ref{compact_haus_closed}.\\ Conversely, if $K$ is closed and bounded, there is some $M>0$ such that $K\subset [-M,M]^n$ which is compact by Theorem \ref{01compact} and \ref{tycho_finite}. Since $K$ is closed in $[-M,M]^n$, it is compact by Proposition \ref{compact_haus_closed}. \end{proof} \begin{definition} Given an open set $U\subset\mathbb R^n$, a sequence of functions $f_k:U\to\mathbb R$ converges locally uniformly on $U$ to some function $f:U\to\mathbb R$ if $\forall x\in U, \exists r>0, D_r(x)\subset U$ and $f_k\to f$ uniformly on $D_r(x)$. \end{definition} Thus this happens if and only if $f_n\to f$ uniformly on any compact subset of $U$. \begin{definition} A topological space $X$ is called sequentially compact if and only if every sequence in $X$ has a convergent subsequence. \end{definition} \begin{example} Any closed bounded subset of $\mathbb R^n$ is sequentially compact by Bolzano-Weierstrass. \end{example} \begin{definition} Fix a metric space $(M,d)$. For $\epsilon>0$ and $F\subset M$. We say $F$ is an $\epsilon$-net for $M$ if $\forall x\in M,\exists y\in F,d(x,y)\le \epsilon$. That is, $$M=\bigcup_{y\in F} B_\epsilon(y)$$ We say $M$ is totally bounded if for any $\epsilon>0$, there is a finite $\epsilon$-net for $M$. \end{definition} Note that any compact space is totally bounded, but the converse is not true by taking $[0,1)$, but the only thing missing here is completeness. \begin{theorem} The followings are equivalent:\\ (1) $M$ is compact.\\ (2) $M$ is sequentially compact.\\ (3) $M$ is totally bounded and complete. \end{theorem} \begin{proof} $1\implies 2$: Let $(x_n)$ be a sequence in $M$, so for $n\in\mathbb N$, let $A_n=\{x_k:k>n\}$. We shall show that $\bigcap_{n\in\mathbb N}\bar{A}$ is nonempty. Assume not, then $$\bigcup_{n\in\mathbb N}M\setminus\bar{A}=M$$ But $M$ is compact and all $M\setminus\bar{A}$ are closed, there is finite subcover, hence there is some $N\in\mathbb N$ such that $\bigcup_{n\le N}M\setminus\bar{A}=M$. Also $A_m\supset A_n,\forall m\le n$, so we have the complement of the closure of $A_{N}$ would be $M$, so that closure is empty, contradiction.\\ So we can fix $x\in \bigcap_{n\in\mathbb N}\bar{A}$. It is then trivial to construct a subsequence of $x_n$ that converges to $x$.\\ $2\implies 3$: $M$ is complete since a Cauchy sequence with convergent subsequence is convergent. To see it is totally bounded, assume it is not, then there is some $\epsilon>0$ such that every $\epsilon$-net is infinite. Pick $x_1\in M$, then if we have already picked $x_1,\ldots,x_n$, we can pick $x_{n+1}\notin \bigcup_{k=1}^nB_\epsilon(x_k)$, which we can do since $M$ has no finite $\epsilon$-net. But this $(x_n)$ does not have any Cauchy subsequence, so it has no converging subsequence.\\ $3\implies 1$: Assume $M$ is not compact, so there is an open cover $\mathscr U$ without any finite subcover. We say $A\subset M$ is ``bad'' if there is no finite subcover of $A$ in $\mathscr U$. So $M$ is bad but $\varnothing$ is not. Note if $A=\bigcup_{i=1}^nB_i$ is bad, then there is some $i$ such that $B_i$ is bad.\\ Next, we want to show that if $A$ is bad and $\epsilon>0$, then $\exists B\subset A$ such that $B$ is bad and $\operatorname{diam}B=\sup_{x,y\in B}d(x,y)<\epsilon$. Indeed, since $M$ is bounded, we have a finite $\epsilon/2$-net $F$, that is, $$\bigcup_{x\in F}B_{\epsilon/2}(x)=M\implies \bigcup_{x\in F}(B_{\epsilon/2}(x)\cap A)=A$$ But this would mean that there is some $x\in F$ such that $B_{\epsilon/2}(x)\cap A$ is bad, and by triangle inequality its diameter is less than $\epsilon$. Using this we can construct a sequence $M\supset A_1\supset A_2\supset\cdots$ such that $A_n$ is bad for any $n$ and $\operatorname{diam}A<1/n$. So we can pick $x_n\in A_n$, then $x_n$ is Cauchy, thus it tends to a limit $x\in M$ by completeness, so there is some $U\in\mathscr U$ such that $x\in U$, so $\exists r>0$ such that $D_r(x)\subset U$, which provides a finite subcover for $A_n$ where $n$ is large enough. \end{proof} \begin{remark} We have a new proof of Bolzano-Weierstrass now! We can also have a new proof of Theorem \ref{tycho_finite} for metric spaces.\\ However, the equivalence of sequentially compactness and compactness fails in both directions in general topological spaces. \end{remark}
theory equational_clausal_logic (* N. Peltier - http://membres-lig.imag.fr/peltier/ *) imports Main terms "HOL-Library.Multiset" begin section \<open>Equational Clausal Logic\<close> text \<open>The syntax and semantics of clausal equational logic are defined as usual. Interpretations are congruences on binary trees.\<close> subsection \<open>Syntax\<close> text \<open>We first define the syntax of equational clauses.\<close> datatype 'a equation = Eq "'a trm" "'a trm" fun lhs where "lhs (Comb t1 t2) = t1" | "lhs (Var x) = (Var x)" | "lhs (Const x) = (Const x)" fun rhs where "rhs (Comb t1 t2) = t2" | "rhs (Var x) = (Var x)" | "rhs (Const x) = (Const x)" datatype 'a literal = Pos "'a equation" | Neg "'a equation" fun atom :: "'a literal \<Rightarrow> 'a equation" where "(atom (Pos x)) = x" | "(atom (Neg x)) = x" datatype sign = pos | neg fun get_sign :: "'a literal \<Rightarrow> sign" where "(get_sign (Pos x)) = pos" | "(get_sign (Neg x)) = neg" fun positive_literal :: "'a literal \<Rightarrow> bool" where "(positive_literal (Pos x)) = True" | "(positive_literal (Neg x)) = False" fun negative_literal :: "'a literal \<Rightarrow> bool" where "(negative_literal (Pos x)) = False" | "(negative_literal (Neg x)) = True" fun mk_lit :: "sign \<Rightarrow> 'a equation \<Rightarrow> 'a literal" where "(mk_lit pos x) = (Pos x)" | "(mk_lit neg x) = (Neg x)" definition decompose_equation where "decompose_equation e t s = (e = (Eq t s) \<or> (e = (Eq s t)))" definition decompose_literal where "decompose_literal L t s p = (\<exists>e. ((p = pos \<and> (L = (Pos e)) \<and> decompose_equation e t s) \<or> (p = neg \<and> (L = (Neg e)) \<and> decompose_equation e t s)))" fun subterms_of_eq where "subterms_of_eq (Eq t s) = (subterms_of t \<union> subterms_of s)" fun vars_of_eq where "vars_of_eq (Eq t s) = (vars_of t \<union> vars_of s)" lemma decompose_equation_vars: assumes "decompose_equation e t s" shows "vars_of t \<subseteq> vars_of_eq e" by (metis assms decompose_equation_def sup.cobounded1 sup_commute vars_of_eq.simps) fun subterms_of_lit where "subterms_of_lit (Pos e) = (subterms_of_eq e)" | "subterms_of_lit (Neg e) = (subterms_of_eq e)" fun vars_of_lit where "vars_of_lit (Pos e) = (vars_of_eq e)" | "vars_of_lit (Neg e) = (vars_of_eq e)" fun vars_of_cl where "vars_of_cl C = { x. \<exists>L. x \<in> (vars_of_lit L) \<and> L \<in> C }" fun subterms_of_cl where "subterms_of_cl C = { x. \<exists>L. x \<in> (subterms_of_lit L) \<and> L \<in> C }" text \<open>Note that clauses are defined as sets and not as multisets (identical literals are always merged).\<close> type_synonym 'a clause = "'a literal set" fun ground_clause :: "'a clause \<Rightarrow> bool" where "(ground_clause C) = ((vars_of_cl C) = {})" fun subst_equation :: "'a equation \<Rightarrow> 'a subst \<Rightarrow> 'a equation" where "(subst_equation (Eq u v) s) = (Eq (subst u s) (subst v s))" fun subst_lit :: "'a literal \<Rightarrow> 'a subst \<Rightarrow> 'a literal" where "(subst_lit (Pos e) s) = (Pos (subst_equation e s))" | "(subst_lit (Neg e) s) = (Neg (subst_equation e s))" fun subst_cl :: "'a clause \<Rightarrow> 'a subst \<Rightarrow> 'a clause" where "(subst_cl C s) = { L. (\<exists>L'. (L' \<in> C) \<and> (L = (subst_lit L' s))) }" text \<open>We establish some properties of the functions returning the set of variables occurring in an object.\<close> lemma decompose_literal_vars: assumes "decompose_literal L t s p" shows "vars_of t \<subseteq> vars_of_lit L" by (metis assms decompose_equation_vars decompose_literal_def vars_of_lit.simps(1) vars_of_lit.simps(2)) lemma vars_of_cl_lem: assumes "L \<in> C" shows "vars_of_lit L \<subseteq> vars_of_cl C" using assms by auto lemma set_of_variables_is_finite_eq: shows "finite (vars_of_eq e)" proof - obtain t and s where "e = Eq t s" using equation.exhaust by auto then have "vars_of_eq e = (vars_of t) \<union> (vars_of s)" by auto from this show ?thesis by auto qed lemma set_of_variables_is_finite_lit: shows "finite (vars_of_lit l)" proof - obtain e where "l = Pos e \<or> l = Neg e" using literal.exhaust by auto then have "vars_of_lit l = (vars_of_eq e)" by auto from this show ?thesis using set_of_variables_is_finite_eq by auto qed lemma set_of_variables_is_finite_cl: assumes "finite C" shows "finite (vars_of_cl C)" proof - let ?S = "{ x. \<exists>l. x = vars_of_lit l \<and> l \<in> C }" have "vars_of_cl C = \<Union> ?S" by auto from assms have "finite ?S" by auto { fix x have "x \<in> ?S \<Longrightarrow> finite x" using set_of_variables_is_finite_lit by auto } from this and \<open>finite ?S\<close> have "finite (\<Union> ?S)" using finite_Union by auto from this and \<open>vars_of_cl C = \<Union> ?S\<close> show ?thesis by auto qed lemma subterm_lit_vars : assumes "u \<in> subterms_of_lit L" shows "vars_of u \<subseteq> vars_of_lit L" proof - obtain e where def_e: "L = (Pos e) \<or> L = (Neg e)" and "vars_of_lit L = vars_of_eq e" by (metis negative_literal.elims(2) negative_literal.elims(3) vars_of_lit.simps(1) vars_of_lit.simps(2)) obtain t and s where def_ts: "e = (Eq t s) \<or> e = (Eq s t)" and "vars_of_eq e = vars_of t \<union> vars_of s" by (metis equation.exhaust vars_of_eq.simps) from this and \<open>vars_of_lit L = vars_of_eq e\<close> have "vars_of_lit L = vars_of t \<union> vars_of s" by auto from assms(1) and def_e def_ts have "u \<in> subterms_of t \<union> subterms_of s" by auto from this have "vars_of u \<subseteq> vars_of t \<union> vars_of s" by (meson UnE sup.coboundedI1 sup.coboundedI2 vars_subterms_of) from this and \<open>vars_of_lit L = vars_of t \<union> vars_of s\<close> show ?thesis by auto qed lemma subterm_vars : assumes "u \<in> subterms_of_cl C" shows "vars_of u \<subseteq> vars_of_cl C" proof - from assms(1) obtain L where "u \<in> subterms_of_lit L" and "L \<in> C" by auto from \<open>u \<in> subterms_of_lit L\<close> have "vars_of u \<subseteq> vars_of_lit L" using subterm_lit_vars by auto from \<open>L \<in> C\<close> have "vars_of_lit L \<subseteq> vars_of_cl C" using vars_of_cl.simps by auto from this and \<open>vars_of u \<subseteq> vars_of_lit L\<close> show ?thesis by auto qed text \<open>We establish some basic properties of substitutions.\<close> lemma subterm_cl_subst: assumes "x \<in> (subterms_of_cl C)" shows "(subst x \<sigma>) \<in> (subterms_of_cl (subst_cl C \<sigma>))" proof - from assms(1) obtain L where "L \<in> C" and "x \<in> subterms_of_lit L" by auto from \<open>L \<in> C\<close> have "(subst_lit L \<sigma>) \<in> (subst_cl C \<sigma>)" by auto obtain e where "L = (Pos e) \<or> L = (Neg e)" using literal.exhaust by auto then show ?thesis proof assume "L = (Pos e)" from this and \<open>x \<in> subterms_of_lit L\<close> have "x \<in> subterms_of_eq e" by auto from \<open>L = (Pos e)\<close> have "(subst_lit L \<sigma>) = (Pos (subst_equation e \<sigma>))" by auto obtain t s where "e = (Eq t s)" using equation.exhaust by auto from this have "(subst_equation e \<sigma>) = (Eq (subst t \<sigma>) (subst s \<sigma>))" by auto from \<open>x \<in> subterms_of_eq e\<close> and \<open>e = (Eq t s)\<close> have "x \<in> subterms_of t \<or> x \<in> subterms_of s" by auto then show ?thesis proof assume "x \<in> subterms_of t" then have "occurs_in x t" by auto then obtain p where "subterm t p x" unfolding occurs_in_def by blast from this have "subterm (subst t \<sigma>) p (subst x \<sigma>)" using substs_preserve_subterms by auto from this have "occurs_in (subst x \<sigma>) (subst t \<sigma>)" unfolding occurs_in_def by auto then have "(subst x \<sigma>) \<in> subterms_of (subst t \<sigma>)" by auto then have "(subst x \<sigma>) \<in> subterms_of_eq (Eq (subst t \<sigma>) (subst s \<sigma>))" by auto from this and \<open>L = (Pos e)\<close> and \<open>e = Eq t s\<close> have "(subst x \<sigma>) \<in> (subterms_of_lit (subst_lit L \<sigma>))" by auto from this and \<open>(subst_lit L \<sigma>) \<in> (subst_cl C \<sigma>)\<close> show "(subst x \<sigma>) \<in> subterms_of_cl (subst_cl C \<sigma>)" by auto next assume "x \<in> subterms_of s" then have "occurs_in x s" by auto then obtain p where "subterm s p x" unfolding occurs_in_def by blast from this have "subterm (subst s \<sigma>) p (subst x \<sigma>)" using substs_preserve_subterms by auto from this have "occurs_in (subst x \<sigma>) (subst s \<sigma>)" unfolding occurs_in_def by auto then have "(subst x \<sigma>) \<in> subterms_of (subst s \<sigma>)" by auto then have "(subst x \<sigma>) \<in> subterms_of_eq (Eq (subst t \<sigma>) (subst s \<sigma>))" by auto from this and \<open>L = (Pos e)\<close> and \<open>e = Eq t s\<close> have "(subst x \<sigma>) \<in> (subterms_of_lit (subst_lit L \<sigma>))" by auto from this and \<open>(subst_lit L \<sigma>) \<in> (subst_cl C \<sigma>)\<close> show "(subst x \<sigma>) \<in> subterms_of_cl (subst_cl C \<sigma>)" by auto qed next assume "L = (Neg e)" from this and \<open>x \<in> subterms_of_lit L\<close> have "x \<in> subterms_of_eq e" by auto from \<open>L = (Neg e)\<close> have "(subst_lit L \<sigma>) = (Neg (subst_equation e \<sigma>))" by auto obtain t s where "e = (Eq t s)" using equation.exhaust by auto from this have "(subst_equation e \<sigma>) = (Eq (subst t \<sigma>) (subst s \<sigma>))" by auto from \<open>x \<in> subterms_of_eq e\<close> and \<open>e = (Eq t s)\<close> have "x \<in> subterms_of t \<or> x \<in> subterms_of s" by auto then show ?thesis proof assume "x \<in> subterms_of t" then have "occurs_in x t" by auto then obtain p where "subterm t p x" unfolding occurs_in_def by blast from this have "subterm (subst t \<sigma>) p (subst x \<sigma>)" using substs_preserve_subterms by auto from this have "occurs_in (subst x \<sigma>) (subst t \<sigma>)" unfolding occurs_in_def by auto then have "(subst x \<sigma>) \<in> subterms_of (subst t \<sigma>)" by auto then have "(subst x \<sigma>) \<in> subterms_of_eq (Eq (subst t \<sigma>) (subst s \<sigma>))" by auto from this and \<open>L = (Neg e)\<close> and \<open>e = Eq t s\<close> have "(subst x \<sigma>) \<in> (subterms_of_lit (subst_lit L \<sigma>))" by auto from this and \<open>(subst_lit L \<sigma>) \<in> (subst_cl C \<sigma>)\<close> show "(subst x \<sigma>) \<in> subterms_of_cl (subst_cl C \<sigma>)" by auto next assume "x \<in> subterms_of s" then have "occurs_in x s" by auto then obtain p where "subterm s p x" unfolding occurs_in_def by blast from this have "subterm (subst s \<sigma>) p (subst x \<sigma>)" using substs_preserve_subterms by auto from this have "occurs_in (subst x \<sigma>) (subst s \<sigma>)" unfolding occurs_in_def by auto then have "(subst x \<sigma>) \<in> subterms_of (subst s \<sigma>)" by auto then have "(subst x \<sigma>) \<in> subterms_of_eq (Eq (subst t \<sigma>) (subst s \<sigma>))" by auto from this and \<open>L = (Neg e)\<close> and \<open>e = Eq t s\<close> have "(subst x \<sigma>) \<in> (subterms_of_lit (subst_lit L \<sigma>))" by auto from this and \<open>(subst_lit L \<sigma>) \<in> (subst_cl C \<sigma>)\<close> show "(subst x \<sigma>) \<in> subterms_of_cl (subst_cl C \<sigma>)" by auto qed qed qed lemma ground_substs_yield_ground_clause: assumes "ground_on (vars_of_cl C) \<sigma>" shows "ground_clause (subst_cl C \<sigma>)" proof (rule ccontr) let ?D = "(subst_cl C \<sigma>)" let ?V = "(vars_of_cl C)" assume "\<not>(ground_clause ?D)" then obtain x where "x \<in> (vars_of_cl ?D)" by auto then obtain l where "l \<in> C" and "x \<in> (vars_of_lit (subst_lit l \<sigma>))" by auto from \<open>l \<in> C\<close> have "vars_of_lit l \<subseteq> vars_of_cl C" by auto obtain e where "l = Pos e \<or> l = Neg e" using literal.exhaust by auto then have "vars_of_lit l = vars_of_eq e" by auto let ?l' = "(subst_lit l \<sigma>)" let ?e' = "(subst_equation e \<sigma>)" obtain t and s where "e = Eq t s" using equation.exhaust by auto then have "vars_of_eq e = vars_of t \<union> vars_of s" by auto let ?t' = "(subst t \<sigma>)" let ?s' = "(subst s \<sigma>)" from \<open>e = Eq t s\<close> have "?e' = (Eq ?t' ?s')" by auto from \<open>l = Pos e \<or> l = Neg e\<close> have "?l' = Pos ?e' \<or> ?l' = Neg ?e'" by auto from \<open>l \<in> C\<close> have "?l' \<in> ?D" by auto from \<open>?l' = Pos ?e' \<or> ?l' = Neg ?e'\<close> and \<open>x \<in> (vars_of_lit ?l')\<close> have "x \<in> (vars_of_eq ?e')" by auto from this and \<open>?e' = (Eq ?t' ?s')\<close> have "x \<in> (vars_of ?t' \<union> vars_of ?s')" by auto then have i:"\<not>(ground_term ?t') \<or> \<not>(ground_term ?s')" unfolding ground_term_def by auto from \<open>vars_of_eq e = vars_of t \<union> vars_of s\<close> and \<open>vars_of_lit l = vars_of_eq e\<close> and \<open>vars_of_lit l \<subseteq> ?V\<close> have "vars_of t \<subseteq> ?V" and "vars_of s \<subseteq> ?V" by auto from \<open>vars_of t \<subseteq> ?V\<close> and \<open>ground_on ?V \<sigma>\<close> have "ground_on (vars_of t) \<sigma>" unfolding ground_on_def by auto then have ii:"ground_term ?t'" using ground_instance by auto from \<open>vars_of s \<subseteq> ?V\<close> and \<open>ground_on ?V \<sigma>\<close> have "ground_on (vars_of s) \<sigma>" unfolding ground_on_def by auto then have iii:"ground_term ?s'" using ground_instance by auto from i and ii and iii show False by auto qed lemma ground_clauses_and_ground_substs: assumes "ground_clause (subst_cl C \<sigma>)" shows "ground_on (vars_of_cl C) \<sigma>" proof (rule ccontr) assume "\<not>ground_on (vars_of_cl C) \<sigma>" from this obtain x where "x \<in> vars_of_cl C" and "\<not> ground_term (subst (Var x) \<sigma>)" unfolding ground_on_def by auto from \<open>\<not> ground_term (subst (Var x) \<sigma>)\<close> obtain y where "y \<in> vars_of (subst (Var x) \<sigma>)" unfolding ground_term_def by auto from \<open>x \<in> vars_of_cl C\<close> obtain L where "L \<in> C" and "x \<in> vars_of_lit L" by auto from \<open>x \<in> vars_of_lit L\<close> obtain e where "L = Pos e \<or> L = Neg e" and "x \<in> vars_of_eq e" by (metis vars_of_lit.elims) from \<open>x \<in> vars_of_eq e\<close> obtain t s where "e = (Eq t s)" and "x \<in> vars_of t \<union> vars_of s" by (metis vars_of_eq.elims) from this have "x \<in> vars_of t \<or> x \<in> vars_of s" by auto then have "y \<in> vars_of_eq (subst_equation e \<sigma>)" proof assume "x \<in> vars_of t" have i: "vars_of (subst t \<sigma>) = \<Union>{V. \<exists>x. x \<in> vars_of t \<and> V = vars_of (subst (Var x) \<sigma>) }" using vars_of_instances [of t \<sigma>] by meson from \<open>x \<in> vars_of t\<close> i have "vars_of (subst (Var x) \<sigma>) \<subseteq> vars_of (subst t \<sigma>)" by auto from this and \<open>y \<in> vars_of (subst (Var x) \<sigma>)\<close> \<open>e = (Eq t s)\<close> show ?thesis by auto next assume "x \<in> vars_of s" have i: "vars_of (subst s \<sigma>) = \<Union>{V. \<exists>x. x \<in> vars_of s \<and> V = vars_of (subst (Var x) \<sigma>) }" using vars_of_instances [of s \<sigma>] by meson from \<open>x \<in> vars_of s\<close> i have "vars_of (subst (Var x) \<sigma>) \<subseteq> vars_of (subst s \<sigma>)" by auto from this and \<open>y \<in> vars_of (subst (Var x) \<sigma>)\<close> \<open>e = (Eq t s)\<close> show ?thesis by auto qed from this and \<open>L = Pos e \<or> L = Neg e\<close> have "y \<in> vars_of_lit (subst_lit L \<sigma>)" by auto from this and \<open>L \<in> C\<close> have "y \<in> vars_of_cl (subst_cl C \<sigma>)" by auto from this and assms(1) show False by auto qed lemma ground_instance_exists: assumes "finite C" shows "\<exists>\<sigma>. (ground_clause (subst_cl C \<sigma>))" proof - let ?V = "(vars_of_cl C)" from assms have "finite ?V" using set_of_variables_is_finite_cl by auto from this obtain \<sigma> where "ground_on ?V \<sigma>" using ground_subst_exists by blast let ?D = "(subst_cl C \<sigma>)" from \<open>ground_on ?V \<sigma>\<close> have "(ground_clause ?D)" using ground_substs_yield_ground_clause [of C \<sigma>] by auto then show ?thesis by auto qed lemma composition_of_substs : shows "(subst (subst t \<sigma>) \<eta>) = (subst t (comp \<sigma> \<eta>))" by simp lemma composition_of_substs_eq : shows "(subst_equation (subst_equation e \<sigma>) \<eta>) = (subst_equation e (comp \<sigma> \<eta>))" by (metis subst_equation.simps composition_of_substs vars_of_eq.elims) lemma composition_of_substs_lit : shows "(subst_lit (subst_lit l \<sigma>) \<eta>) = (subst_lit l (comp \<sigma> \<eta>))" by (metis subst_lit.simps(1) subst_lit.simps(2) composition_of_substs_eq positive_literal.cases) lemma composition_of_substs_cl : shows "(subst_cl (subst_cl C \<sigma>) \<eta>) = (subst_cl C (comp \<sigma> \<eta>))" proof - let ?f = "(\<lambda>x. (subst_lit (subst_lit x \<sigma>) \<eta>))" let ?f' = "(\<lambda>x. (subst_lit x (comp \<sigma> \<eta>)))" have "\<forall>l. (?f l) = (?f' l)" using composition_of_substs_lit by auto then show ?thesis by auto qed lemma substs_preserve_ground_lit : assumes "ground_clause C" assumes "y \<in> C" shows "subst_lit y \<sigma> = y" proof - obtain t and s where "y = Pos (Eq t s) \<or> y = Neg (Eq t s)" by (metis subst_equation.elims get_sign.elims) from this have "vars_of t \<subseteq> vars_of_lit y" by auto from this and \<open>y \<in> C\<close> have "vars_of t \<subseteq> vars_of_cl C" by auto from this and assms(1) have "ground_term t" unfolding ground_term_def by auto then have "subst t \<sigma> = t" using substs_preserve_ground_terms by auto from \<open>y = Pos (Eq t s) \<or> y = Neg (Eq t s)\<close> have "vars_of s \<subseteq> vars_of_lit y" by auto from this and \<open>y \<in> C\<close> have "vars_of s \<subseteq> vars_of_cl C" by auto from this and assms(1) have "ground_term s" unfolding ground_term_def by auto then have "subst s \<sigma> = s" using substs_preserve_ground_terms by auto from \<open>subst s \<sigma> = s\<close> and \<open>subst t \<sigma> = t\<close> and \<open>y = Pos (Eq t s) \<or> y = Neg (Eq t s)\<close> show "subst_lit y \<sigma> = y" by auto qed lemma substs_preserve_ground_clause : assumes "ground_clause C" shows "subst_cl C \<sigma> = C" proof show "subst_cl C \<sigma> \<subseteq> C" proof fix x assume "x \<in> subst_cl C \<sigma>" then obtain y where "y \<in> C" and "x = subst_lit y \<sigma>" by auto from assms(1) and \<open>y \<in> C\<close> and \<open>x = subst_lit y \<sigma>\<close> have "x = y" using substs_preserve_ground_lit by auto from this and \<open>y \<in> C\<close> show "x \<in> C" by auto qed next show "C \<subseteq> subst_cl C \<sigma>" proof fix x assume "x \<in> C" then have "subst_lit x \<sigma> \<in> subst_cl C \<sigma>" by auto from assms(1) and \<open>x \<in> C\<close> have "x = subst_lit x \<sigma>" using substs_preserve_ground_lit [of C x] by auto from this and \<open>x \<in> C\<close> show "x \<in> subst_cl C \<sigma>" by auto qed qed lemma substs_preserve_finiteness : assumes "finite C" shows "finite (subst_cl C \<sigma>)" proof - from assms(1) show ?thesis using Finite_Set.finite_imageI by auto qed text \<open>We prove that two equal substitutions yield the same objects.\<close> lemma subst_eq_eq : assumes "subst_eq \<sigma> \<eta>" shows "subst_equation e \<sigma> = subst_equation e \<eta>" proof - obtain t and s where "e = Eq t s" using equation.exhaust by auto from assms(1) have "subst s \<sigma> = subst s \<eta>" by auto from assms(1) have "subst t \<sigma> = subst t \<eta>" by auto from \<open>subst s \<sigma> = subst s \<eta>\<close> \<open>subst t \<sigma> = subst t \<eta>\<close> and \<open>e = Eq t s\<close> show ?thesis by auto qed lemma subst_eq_cl: assumes "subst_eq \<sigma> \<eta>" shows "subst_cl C \<sigma> = subst_cl C \<eta>" proof (rule ccontr) assume "subst_cl C \<sigma> \<noteq> subst_cl C \<eta>" then obtain L where "L \<in> C" and "subst_lit L \<sigma> \<noteq> subst_lit L \<eta>" by force from assms(1) and \<open>subst_lit L \<sigma> \<noteq> subst_lit L \<eta>\<close> show False using subst_eq_lit by auto qed lemma coincide_on_eq : assumes "coincide_on \<sigma> \<eta> (vars_of_eq e)" shows "subst_equation e \<sigma> = subst_equation e \<eta>" proof - obtain t and s where "e = Eq t s" using equation.exhaust by auto then have "vars_of t \<subseteq> vars_of_eq e" by simp from this and \<open>coincide_on \<sigma> \<eta> (vars_of_eq e)\<close> have "coincide_on \<sigma> \<eta> (vars_of t)" unfolding coincide_on_def by auto from this have "subst t \<sigma> = subst t \<eta>" using coincide_on_term by auto from \<open>e = Eq t s\<close> have "vars_of s \<subseteq> vars_of_eq e" by simp from this and \<open>coincide_on \<sigma> \<eta> (vars_of_eq e)\<close> have "coincide_on \<sigma> \<eta> (vars_of s)" unfolding coincide_on_def by auto from this have "subst s \<sigma> = subst s \<eta>" using coincide_on_term by auto from \<open>subst t \<sigma> = subst t \<eta>\<close> and \<open>subst s \<sigma> = subst s \<eta>\<close> and \<open>e = Eq t s\<close> show ?thesis by auto qed lemma coincide_on_lit : assumes "coincide_on \<sigma> \<eta> (vars_of_lit l)" shows "subst_lit l \<sigma> = subst_lit l \<eta>" proof - obtain e where "l = Pos e \<or> l = Neg e" using literal.exhaust by auto then have "vars_of_eq e \<subseteq> vars_of_lit l" by auto from this and \<open>coincide_on \<sigma> \<eta> (vars_of_lit l)\<close> have "coincide_on \<sigma> \<eta> (vars_of_eq e)" unfolding coincide_on_def by auto from this have "subst_equation e \<sigma> = subst_equation e \<eta>" using coincide_on_eq by auto from this and \<open>l = Pos e \<or> l = Neg e\<close> show ?thesis by auto qed lemma coincide_on_cl : assumes "coincide_on \<sigma> \<eta> (vars_of_cl C)" shows "subst_cl C \<sigma> = subst_cl C \<eta>" proof (rule ccontr) assume "subst_cl C \<sigma> \<noteq> subst_cl C \<eta>" then obtain L where "L \<in> C" and "subst_lit L \<sigma> \<noteq> subst_lit L \<eta>" by force from \<open>L \<in> C\<close> have "vars_of_lit L \<subseteq> vars_of_cl C" by auto from this and assms have "coincide_on \<sigma> \<eta> (vars_of_lit L)" unfolding coincide_on_def by auto from this and \<open>subst_lit L \<sigma> \<noteq> subst_lit L \<eta>\<close> show False using coincide_on_lit by auto qed subsection \<open>Semantics\<close> text \<open>Interpretations are congruences on the set of terms.\<close> definition fo_interpretation :: "'a binary_relation_on_trms \<Rightarrow> bool" where "(fo_interpretation x) = (congruence x)" fun validate_ground_eq :: "'a binary_relation_on_trms \<Rightarrow> 'a equation \<Rightarrow> bool" where "(validate_ground_eq I (Eq t s) = (I t s))" fun validate_ground_lit :: "'a binary_relation_on_trms \<Rightarrow> 'a literal \<Rightarrow> bool" where "validate_ground_lit I (Pos E) = (validate_ground_eq I E)" | "validate_ground_lit I (Neg E) = (\<not>(validate_ground_eq I E))" fun validate_ground_clause :: "'a binary_relation_on_trms \<Rightarrow> 'a clause \<Rightarrow> bool" where "validate_ground_clause I C = (\<exists>L.(L \<in> C) \<and> (validate_ground_lit I L))" fun validate_clause :: "'a binary_relation_on_trms \<Rightarrow> 'a clause \<Rightarrow> bool" where "validate_clause I C = (\<forall>s. (ground_clause (subst_cl C s)) \<longrightarrow> (validate_ground_clause I (subst_cl C s)))" fun validate_clause_set :: "'a binary_relation_on_trms \<Rightarrow> 'a clause set \<Rightarrow> bool" where "validate_clause_set I S = (\<forall>C. (C \<in> S \<longrightarrow> (validate_clause I C)))" definition clause_entails_clause :: "'a clause \<Rightarrow> 'a clause \<Rightarrow> bool" where "clause_entails_clause C D = (\<forall>I. (fo_interpretation I \<longrightarrow> validate_clause I C \<longrightarrow> validate_clause I D))" definition set_entails_clause :: "'a clause set \<Rightarrow> 'a clause \<Rightarrow> bool" where "set_entails_clause S C = (\<forall>I. (fo_interpretation I \<longrightarrow> validate_clause_set I S \<longrightarrow> validate_clause I C))" definition satisfiable_clause_set :: "'a clause set \<Rightarrow> bool" where "(satisfiable_clause_set S) = (\<exists>I. (fo_interpretation I) \<and> (validate_clause_set I S))" text \<open>We state basic properties of the entailment relation.\<close> lemma set_entails_clause_member: assumes "C \<in> S" shows "set_entails_clause S C" proof (rule ccontr) assume "\<not> ?thesis" from this obtain I where "fo_interpretation I" "validate_clause_set I S" "\<not> validate_clause I C" unfolding set_entails_clause_def by auto from \<open>validate_clause_set I S\<close> and assms(1) \<open>\<not> validate_clause I C\<close> show False by auto qed lemma instances_are_entailed : assumes "validate_clause I C" shows "validate_clause I (subst_cl C \<sigma>)" proof (rule ccontr) assume "\<not>validate_clause I (subst_cl C \<sigma>)" then obtain \<eta> where "\<not>validate_ground_clause I (subst_cl (subst_cl C \<sigma>) \<eta>)" and "ground_clause (subst_cl (subst_cl C \<sigma>) \<eta>)" by auto then have i: "\<not>validate_ground_clause I (subst_cl C (comp \<sigma> \<eta>))" using composition_of_substs_cl by metis from \<open>ground_clause (subst_cl (subst_cl C \<sigma>) \<eta>)\<close> have ii: "ground_clause (subst_cl C (comp \<sigma> \<eta>))" using composition_of_substs_cl by metis from i and ii have "\<not>validate_clause I C" by auto from \<open>\<not>validate_clause I C\<close> and \<open>validate_clause I C\<close> show False by blast qed text \<open>We prove that two equivalent substitutions yield equivalent objects.\<close> lemma equivalent_on_eq : assumes "equivalent_on \<sigma> \<eta> (vars_of_eq e) I" assumes "fo_interpretation I" shows "(validate_ground_eq I (subst_equation e \<sigma>)) = (validate_ground_eq I (subst_equation e \<eta>))" proof - obtain t and s where "e = Eq t s" using equation.exhaust by auto then have "vars_of t \<subseteq> vars_of_eq e" by simp from this and assms(1) have "equivalent_on \<sigma> \<eta> (vars_of t) I" unfolding equivalent_on_def by auto from this assms(2) have "I (subst t \<sigma>) (subst t \<eta>)" using equivalent_on_term unfolding fo_interpretation_def by auto from \<open>e = Eq t s\<close> have "vars_of s \<subseteq> vars_of_eq e" by simp from this and \<open>equivalent_on \<sigma> \<eta> (vars_of_eq e) I\<close> have "equivalent_on \<sigma> \<eta> (vars_of s) I" unfolding equivalent_on_def by auto from this assms(2) have "I (subst s \<sigma>) (subst s \<eta>)" using equivalent_on_term unfolding fo_interpretation_def by auto from assms(2) \<open>I (subst t \<sigma>) (subst t \<eta>)\<close> and \<open>I (subst s \<sigma>) (subst s \<eta>)\<close> and \<open>e = Eq t s\<close> show ?thesis unfolding fo_interpretation_def congruence_def equivalence_relation_def transitive_def symmetric_def reflexive_def by (metis (full_types) subst_equation.simps validate_ground_eq.simps) qed lemma equivalent_on_lit : assumes "equivalent_on \<sigma> \<eta> (vars_of_lit l) I" assumes "fo_interpretation I" shows "(validate_ground_lit I (subst_lit l \<sigma>)) = (validate_ground_lit I (subst_lit l \<eta>))" proof - obtain e where "l = Pos e \<or> l = Neg e" using literal.exhaust by auto then have "vars_of_eq e \<subseteq> vars_of_lit l" by auto from this and \<open>equivalent_on \<sigma> \<eta> (vars_of_lit l) I\<close> have "equivalent_on \<sigma> \<eta> (vars_of_eq e) I" unfolding equivalent_on_def by auto from this assms(2) have "(validate_ground_eq I (subst_equation e \<sigma>)) = (validate_ground_eq I (subst_equation e \<eta>))" using equivalent_on_eq by auto from this and \<open>l = Pos e \<or> l = Neg e\<close> show ?thesis by auto qed lemma equivalent_on_cl : assumes "equivalent_on \<sigma> \<eta> (vars_of_cl C) I" assumes "fo_interpretation I" shows "(validate_ground_clause I (subst_cl C \<sigma>)) = (validate_ground_clause I (subst_cl C \<eta>))" proof (rule ccontr) assume "(validate_ground_clause I (subst_cl C \<sigma>)) \<noteq> (validate_ground_clause I (subst_cl C \<eta>))" then obtain L where "L \<in> C" and "(validate_ground_lit I (subst_lit L \<sigma>)) \<noteq> (validate_ground_lit I (subst_lit L \<eta>))" by force from \<open>L \<in> C\<close> have "vars_of_lit L \<subseteq> vars_of_cl C" by auto from this and assms have "equivalent_on \<sigma> \<eta> (vars_of_lit L) I" unfolding equivalent_on_def by auto from this assms(2) and \<open>(validate_ground_lit I (subst_lit L \<sigma>)) \<noteq> (validate_ground_lit I (subst_lit L \<eta>))\<close> show False using equivalent_on_lit by metis qed end
Another important asset are the Storm 's narrow dimensions , which allow it to traverse the narrow alleyways common to the <unk> of many Middle Eastern cities , places that armoured Humvees can only enter with great difficulty and minimal manoeuvrability , if at all . Full @-@ height rear doors which allow for the quick deployment of fully equipped troops into combat are touted as another advantage over similar vehicles .
{-# OPTIONS --without-K --safe #-} module Categories.Category.Lift where open import Level open import Categories.Category open import Categories.Functor using (Functor) liftC : ∀ {o ℓ e} o′ ℓ′ e′ → Category o ℓ e → Category (o ⊔ o′) (ℓ ⊔ ℓ′) (e ⊔ e′) liftC o′ ℓ′ e′ C = record { Obj = Lift o′ Obj ; _⇒_ = λ X Y → Lift ℓ′ (lower X ⇒ lower Y) ; _≈_ = λ f g → Lift e′ (lower f ≈ lower g) ; id = lift id ; _∘_ = λ f g → lift (lower f ∘ lower g) ; assoc = lift assoc ; sym-assoc = lift sym-assoc ; identityˡ = lift identityˡ ; identityʳ = lift identityʳ ; identity² = lift identity² ; equiv = record { refl = lift Equiv.refl ; sym = λ eq → lift (Equiv.sym (lower eq)) ; trans = λ eq eq′ → lift (Equiv.trans (lower eq) (lower eq′)) } ; ∘-resp-≈ = λ eq eq′ → lift (∘-resp-≈ (lower eq) (lower eq′)) } where open Category C liftF : ∀ {o ℓ e} o′ ℓ′ e′ (C : Category o ℓ e) → Functor C (liftC o′ ℓ′ e′ C) liftF o′ ℓ′ e′ C = record { F₀ = lift ; F₁ = lift ; identity = lift refl ; homomorphism = lift refl ; F-resp-≈ = lift } where open Category C open Equiv unliftF : ∀ {o ℓ e} o′ ℓ′ e′ (C : Category o ℓ e) → Functor (liftC o′ ℓ′ e′ C) C unliftF o′ ℓ′ e′ C = record { F₀ = lower ; F₁ = lower ; identity = refl ; homomorphism = refl ; F-resp-≈ = lower } where open Category C open Equiv
{-# OPTIONS --type-in-type #-} open import Agda.Primitive using (Setω) -- No panic should be triggered data A : Setω where record B' : Set where field theA : A data B : Set where b : A → B data C : Set where c : Setω → C data C' : Setω where c : Setω → C' record C'' : Setω where field theSet : Setω thefield : theSet
(**************************************************************************) (* This is part of ATBR, it is distributed under the terms of the *) (* GNU Lesser General Public License version 3 *) (* (see file LICENSE for more details) *) (* *) (* Copyright 2009-2011: Thomas Braibant, Damien Pous. *) (**************************************************************************) (** Functors and homomorphisms between algebraic structures *) Require Import Common. Require Import Classes. Require Import SemiLattice. Require Import KleeneAlgebra. Set Implicit Arguments. Unset Strict Implicit. Record functor (G1 G2: Graph) := { fT: @T G1 -> @T G2; fX:> forall A B, X A B -> X (fT A) (fT B) }. Section Defs. Context {G1: Graph} {G2: Graph}. Class graph_functor (F: functor G1 G2) := { functor_compat: forall A B, Proper (equal A B ==> equal _ _) (F A B) }. Definition faithful (F: functor G1 G2) := forall A B x y, F A B x == F A B y -> x == y. Definition full (F: functor G1 G2) := forall A B y, exists x, F A B x == y. Class monoid_functor {Mo1: Monoid_Ops G1} {Mo2: Monoid_Ops G2} (F: functor G1 G2) := { monoid_graph_functor :> graph_functor F; functor_dot : forall A B C x y, F A C (x*y) == F A B x * F B C y; functor_one : forall A, F A A 1 == 1 }. Class semilattice_functor {SLo1: SemiLattice_Ops G1} {SL2: SemiLattice_Ops G2} (F: functor G1 G2) := { semilattice_graph_functor :> graph_functor F; functor_plus : forall A B x y, F A B (x+y) == F A B x + F A B y; functor_zero : forall A B, F A B 0 == 0 }. Section SLfunct. Context {SLo1} {SL1: @SemiLattice G1 SLo1} {SLo2} {SL2: @SemiLattice G2 SLo2} {F: functor G1 G2} {HF: semilattice_functor F}. Lemma functor_incr: forall A B, Proper ((leq A B) ==> (leq _ _)) (F A B). Proof. intros. intros x y H. unfold leq. rewrite <- functor_plus. apply functor_compat. trivial. Qed. Lemma functor_sum: forall A B i k f, F A B (sum i k f) == sum i k (fun i => F A B (f i)). Proof. intros. revert i; induction k; intro i. apply functor_zero. simpl. rewrite functor_plus. apply plus_compat; auto. Qed. End SLfunct. Context {Mo1: Monoid_Ops G1} {Mo2: Monoid_Ops G2} {SLo1: SemiLattice_Ops G1} {SLo2: SemiLattice_Ops G2} {Ko1: Star_Op G1} {Ko2: Star_Op G2}. Class semiring_functor (F: functor G1 G2) := { semiring_monoid_functor :> monoid_functor F; semiring_semilattice_functor :> semilattice_functor F }. Lemma functor_star_leq {KA1: KleeneAlgebra G1} {KA2: KleeneAlgebra G2} {F: functor G1 G2} {HF: semiring_functor F}: forall A a, (F A A a)# <== F A A (a#). Proof. intros. apply star_destruct_left_one. rewrite <- functor_one. rewrite <- functor_dot. rewrite <- functor_plus. apply functor_incr. rewrite star_make_right. reflexivity. Qed. Class kleene_functor (F: functor G1 G2) := { kleene_semiring :> semiring_functor F; functor_star: forall A a, F A A (a#) == (F A A a) # }. End Defs.
! { dg-do compile } ! { dg-options "-fcoarray=single" } ! ! PR fortran/18918 ! ! Was failing before as the "x%a()[]" was ! regarded as coindexed subroutine test2() type t integer, allocatable :: a(:)[:] end type t type(t), SAVE :: x allocate(x%a(1)[*]) end subroutine test2 module m integer, allocatable :: a(:)[:] end module m ! Was failing as "a" was allocatable but ! as->cotype was not AS_DEFERERED. use m end
[STATEMENT] lemma gbinomial_minus': "(a + of_nat b) gchoose b = (- 1) ^ b * (- (a + 1) gchoose b)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. a + of_nat b gchoose b = (- (1::'a)) ^ b * (- (a + (1::'a)) gchoose b) [PROOF STEP] by (subst gbinomial_minus) (simp add: power_mult_distrib [symmetric])
library(tictoc) tic() #119.4 sec elapsed require( gdxrrw ) require( tidyverse ) require(ggplot2) library(gridExtra) library(broom) require( rgdal ) library(rgeos) gams_path = 'C:/GAMS/win64/24.9' # Local location of indus ix model - MAKE SURE TO ADD TO SYSTEM ENVIRONMENT VARIABLES setwd(indus_ix_path) # Basin analyzed basin = 'Indus' # basin.spdf = readOGR( paste( "P:/is-wel/indus/message_indus", 'input', sep = '/' ), paste( basin, 'bcu', sep = '_' ), verbose = FALSE ) if (!exists('shiny_mode')) shiny_mode = F if (shiny_mode){} else { dir.create(file.path(indus_ix_path,paste0('plots_',sc)),showWarnings = F ) setwd(paste0(indus_ix_path,'/plots_',sc)) } #endif # Basin analyzed basin = 'Indus' # Get the relevant data from the gdx output files scname = c(baseline,sc) scen_chk = sapply( scname, function( sss ){ paste( 'MSGoutput_', sss, '.gdx', sep = '' ) } ) upath = paste( indus_ix_path, '/model/output/', sep='') # Import results from gdx gams_path = 'C:/GAMS/win64/24.9' igdx( gams_path ) res.list = lapply( scen_chk, function(fpath){ # 65.97 sec elapsed vars = c( 'demand_fixed','CAP_NEW', 'CAP','historical_new_capacity', 'ACT', 'input', 'output', 'inv_cost', 'fix_cost', 'var_cost','EMISS', 'STORAGE','STORAGE_CHG', 'bound_storage_up','bound_storage_lo','PRICE_COMMODITY','PRICE_EMISSION') gdx_res = lapply( vars, function( vv ){ tmp = rgdx( paste( upath, fpath, sep = '' ), list( name = vv, form = "sparse" ) ) names(tmp$uels) = tmp$domains rs = data.frame( tmp$val ) names(rs) = c( unlist( tmp$domains ), 'value' ) rs[ , which( names(rs) != 'value' ) ] = do.call( cbind, lapply( names( rs )[ which( names(rs) != 'value' ) ], function( cc ){ sapply( unlist( rs[ , cc ] ) , function(ii){ return( tmp$uels[[ cc ]][ ii ] ) } ) } ) ) return(rs) } ) names(gdx_res) = vars return(gdx_res) } ) names( res.list ) = scen_chk print('Variables loaded from gdxs') shiny_vars = c( 'demand_fixed', 'CAP_NEW', 'CAP', 'ACT', 'input', 'output', 'inv_cost', 'EMISS','STORAGE','STORAGE_CHG' ) for (vari in shiny_vars){ assign(paste0(vari,'.shiny'),bind_rows( lapply( scen_chk, function( sc ){ tmp.df = res.list[[ sc ]][[ paste0(vari) ]] tmp.df$scenario = paste0(sc) return(tmp.df) } ) ) ) } EMISS.shiny = EMISS.shiny %>% rename(type = emission) %>% mutate(type_tec) ##### COSTS ##### cost_by_technology.df = bind_rows( lapply( scen_chk, function( sc ){ cap.df = res.list[[ sc ]][[ 'CAP' ]] cap_new.df = res.list[[ sc ]][[ 'CAP_NEW' ]] act.df = res.list[[ sc ]][[ 'ACT' ]] inv.df = res.list[[ sc ]][[ 'inv_cost' ]] fix.df = res.list[[ sc ]][[ 'fix_cost' ]] var.df = res.list[[ sc ]][[ 'var_cost' ]] ic.df = merge( cap_new.df, inv.df, by = c( 'node', 'tec', 'year_all' ) , all.x = TRUE ) %>% mutate( invc = value.x * value.y ) %>% group_by( node, tec, year_all ) %>% summarise( invc = sum(invc) ) %>% dplyr::select( node, tec, year_all, invc ) ic.df[ is.na( ic.df ) ] = 0 fc.df = merge( cap.df, fix.df, by = c( 'node', 'tec', 'vintage', 'year_all' ) , all.x = TRUE ) %>% mutate( fixc = value.x * value.y ) %>% group_by( node, tec, year_all ) %>% summarise( fixc = sum(fixc) ) %>% ungroup() %>% data.frame() %>% dplyr::select( node, tec, year_all, fixc ) fc.df[ is.na( fc.df ) ] = 0 vc.df = merge( act.df, var.df, by = c( 'node', 'tec', 'vintage', 'year_all', 'mode', 'time' ) , all.x = TRUE ) %>% mutate( varc = value.x * value.y ) %>% group_by( node, tec, year_all ) %>% summarise( varc = sum(varc) ) %>% ungroup() %>% data.frame() %>% dplyr::select( node, tec, year_all, varc ) vc.df[ is.na( vc.df ) ] = 0 tc.df = merge( merge( ic.df, fc.df, by = c( 'node', 'tec', 'year_all' ) ), vc.df, by = c( 'node', 'tec', 'year_all' ) ) %>% mutate( tot = invc + fixc + varc ) %>% # rename( inv = value.x, fix = value.y, var = value ) %>% mutate( invc = round( invc, digits = 2 ), fixc = round( fixc, digits = 2 ), varc = round( varc, digits = 2 ), value = round( tot, digits = 2 ) ) %>% mutate( units = 'million_USD' ) %>% dplyr::select( node, tec, year_all, units, invc, fixc, varc, value ) btc.df = tc.df %>% group_by( tec, year_all ) %>% summarise( invc = sum(invc), fixc = sum(fixc), varc = sum(varc), value = sum(value) ) %>% ungroup() %>% mutate( node = basin ) %>% mutate( units = 'million_USD' ) %>% dplyr::select( node, tec, year_all, units, invc, fixc, varc, value ) res = rbind( tc.df, btc.df ) res$scenario = sc res = res[ which( res$value > 0 ), ] return(res) } ) ) tec = unique(c(res.list[[ scen_chk[1] ]]$output$tec,res.list[[ scen_chk[1] ]]$input$tec,res.list[[ scen_chk[2] ]]$output$tec,res.list[[ scen_chk[2] ]]$input$tec) ) tech_type.df = rbind( data.frame( type = 'fossil_energy', tec = tec[ grepl( 'coal|oil|gas|igcc', tec ) ] ), data.frame( type = 'renewables', tec = tec[ grepl( 'solar|wind|geothermal', tec ) ] ), data.frame( type = 'hydro', tec = tec[ grepl( 'hydro_river|hydro_canal|hydro_old', tec ) ] ), data.frame( type = 'nuclear & ccs', tec = tec[ grepl( 'nuclear|ccs', tec ) ] ), data.frame( type = 'electricity grid', tec = tec[ grepl( 'trs_|electricity_distribution|electricity_short_strg', tec ) ] ), data.frame( type = 'water distribution', tec = tec[ grepl( 'diversion|distribution|wastewater_collection|desal|canal', tec ) & !grepl( 'electricity|irrigation|hydro', tec )] ), data.frame( type = 'wastewater treatment', tec = tec[ grepl( 'wastewater_treatment|wastewater_recycling', tec ) ] ), data.frame( type = 'land use', tec = tec[ grepl( 'crop', tec ) ] ), data.frame( type = 'rural generation', tec = tec[ grepl( 'agri|ethanol|genset|solid_biom', tec ) ] ), data.frame( type = 'irrigation', tec = tec[ grepl( 'irr_|irrigation', tec ) ] ) ) import_routes = (tech_type.df %>% filter(!gsub('.*_','',tec) %in% as.character(seq(1,15,1) ),type == 'electricity grid',grepl('trs_',tec)))$tec tech_type.df = tech_type.df %>% mutate(type = if_else(tec %in% import_routes,'electricity import',as.character(type)) ) #graphic settings ------------------ cost_col = c('electricity import' = '#d9d9d9', 'fossil_energy' = '#787878', "renewables" = "#ffffb3", 'hydro' = "#80b1d3", 'nuclear & ccs' = "#fccde5", 'rural generation' = "#549149", 'electricity grid' = "#fb8072", "water distribution" = "#bebada", 'wastewater treatment' = "#b3de69", 'land use' = "#fdb462", 'irrigation' = "#8dd3c7" ) #value refers tot eh total cost_by_technology.df = cost_by_technology.df %>% left_join(tech_type.df) %>% mutate(country = if_else(node != 'Indus', gsub('_.*','',node), node)) cost_by_technology.shiny = cost_by_technology.df %>% select(node,year_all,scenario,type,value) %>% group_by(node,year_all,scenario,type) %>% summarise(value = sum(value)*1e-3) %>% ungroup() %>% mutate(unit = 'Billion USD') type.shiny = as.character(unique(cost_by_technology.shiny$type)) if (shiny_mode){} else { # country averages do not consider 0 values for years with no investment ina specific sector, # therefore overal average is slightly higher than the Indus one df_cost0 = cost_by_technology.df %>% filter( year_all %in% c(2020,2030,2040,2050) ) %>% group_by( year_all, country, type, scenario ) %>% summarise( investment = sum( invc ), operational = sum(varc + fixc) ) %>% ungroup() zero_cost_matrix = crossing(year_all = unique(df_cost0$year_all), country = unique(df_cost0$country), type = unique(df_cost0$type), scenario = unique(df_cost0$scenario)) %>% mutate(investment2 = 0, operational2 = 0) df_cost = cost_by_technology.df %>% filter( year_all %in% c(2020,2030,2040,2050) ) %>% group_by( year_all, country, type, scenario ) %>% summarise( investment = sum( invc ), operational = sum(varc + fixc) ) %>% ungroup() %>% right_join(zero_cost_matrix) %>% mutate(investment = if_else(!is.na(investment), investment, investment2), operational = if_else(!is.na(operational), operational, operational2)) %>% group_by( country, type, scenario ) %>% summarise( investment = mean( investment ),operational = mean( operational ) ) %>% gather('cost','value',investment,operational) %>% # mutate(value = 1e-3 * value ) %>% mutate(scenario = gsub('_',' ', gsub('.*MSGoutput_','',gsub('\\.gdx.*','',scenario) ) ) ) %>% group_by(country,type,scenario,cost) %>% summarise(value = sum(value)) %>% ungroup() pdf( 'indus_invest.pdf', width = 6, height = 6 ) v1 = ggplot(df_cost %>% filter(!country %in% c('AFG','Indus','CHN') ),aes(x = scenario,y = value,fill = type))+ geom_bar( stat = "identity", position = "stack", color = 'grey40',size = 0.1) + facet_wrap(country~cost)+ylab('Billion USD per year')+ scale_fill_manual(values = cost_col)+ theme_bw()+ theme(axis.title.x = element_blank(), axis.text.x = element_text(angle = 45)) plot(v1) v2 = ggplot(df_cost %>% filter(country %in% c('Indus') ),aes(x = scenario,y = value,fill = type))+ geom_bar( stat = "identity", position = "stack", color = 'grey40',size = 0.1) + facet_wrap(country~cost)+ylab('Billion USD per year')+ scale_fill_manual(values = cost_col)+ theme_bw()+ theme(axis.title.x = element_blank(), axis.text.x = element_text(angle = 45)) plot(v2) # difference compared to baseline # df_cost_base = df_cost %>% filter(scenario == scname[1]) %>% # rename(valueB = value) %>% select(-scenario) # # df_cost2 = df_cost %>% filter(scenario != scname[1]) %>% # left_join(df_cost_base) %>% # mutate(valueB = if_else(is.na(valueB),0,valueB)) %>% # mutate(diff = round((value - valueB),3) ) # # V3 = ggplot(df_cost2 %>% filter(!country %in% c('AFG','CHN')),aes(x = type, y = value, fill = type,alpha = cost))+ # geom_bar( stat = "identity", position = "stack", color = 'grey40',size = 0.1) + # facet_wrap(country~scenario)+ylab('Billion USD per year')+ # scale_fill_manual(values = cost_col)+ # scale_alpha_discrete(range=c(0.4, 1))+ # theme_bw()+ theme(axis.title.x = element_blank(), # axis.text.x = element_text(angle = 30)) # plot(V3) # # df_cost3 = df_cost2 %>% group_by(country,scenario,cost) %>% # summarise(value = sum(value), valueB = sum(valueB)) %>% ungroup() %>% # mutate(diff = round((value - valueB),3) ) # # V4 = ggplot(df_cost3 %>% filter(!country %in% c('AFG','CHN')),aes(x = country, y = value, fill = cost))+ # geom_bar( stat = "identity", position = "stack", color = 'grey40',size = 0.1) + # facet_wrap(~scenario)+ylab('Billion USD per year')+ # theme_bw()+ theme(axis.title.x = element_blank() ) # plot(V4) # dev.off() } #### Nexus interactions #### energy_for_water.df = bind_rows( lapply( scen_chk, function( sc ){ merge( data.frame( res.list[[ sc ]]$input ) %>% filter( commodity == 'electricity', !( tec %in% tec[ grepl( 'electricity|trs_', tec ) ] ) ), data.frame( res.list[[ sc ]]$ACT ), by = c( 'node', 'tec', 'vintage', 'year_all', 'mode', 'time' ) ) %>% mutate( value = value.x * value.x ) %>% select( node, tec,year_all, value ) %>% group_by( node,tec, year_all ) %>% summarise( sum( value ) ) %>% data.frame() %>% mutate( scenario = sc ) %>% rename( value = sum.value.) %>% select( node,tec, scenario, year_all, value ) } ) ) energy_for_water.shiny = energy_for_water.df %>% mutate(value = (value * 30 *24* 1e-6), #conversion from MWmonth to TWh unit = 'TWh') # irrigation_gw_diversion and so on are to be consider en for water or for irrigation/land use? # maybe en for water would be just for urban and rural water management. energy_for_irrigation.df = bind_rows( lapply( scen_chk, function( sc ){ merge( data.frame( res.list[[ sc ]]$input ) %>% filter( commodity %in% c('energy','electricity'), level %in% c('agriculture_final','irrigation_final') ), data.frame( res.list[[ sc ]]$ACT ), by = c( 'node', 'tec', 'vintage', 'year_all', 'mode', 'time' ) ) %>% mutate( value = value.x * value.y ) %>% select( node, year_all, value ) %>% group_by( node, year_all ) %>% summarise( sum( value ) ) %>% data.frame() %>% mutate( scenario = sc ) %>% rename( value = sum.value.) %>% select( node, scenario, year_all, value ) } ) ) water_for_energy.df = bind_rows( lapply( scen_chk, function( sc ){ merge( data.frame( res.list[[ sc ]]$input ) %>% filter( commodity == 'freshwater', tec %in% unique( data.frame( res.list[[ sc ]]$output ) %>% filter( commodity == 'electricity', level == 'energy_secondary' ) %>% select( tec ) %>% unlist() ) ), data.frame( res.list[[ sc ]]$ACT ), by = c( 'node', 'tec', 'vintage', 'year_all', 'mode', 'time' ) ) %>% mutate( value = value.x * value.y ) %>% select( node, year_all, value ) %>% group_by( year_all, node ) %>% summarise( value = sum( value ) ) %>% data.frame() %>% mutate( scenario = sc ) %>% select( node, scenario, year_all, value ) } ) ) water_for_energy.shiny = water_for_energy.df %>% mutate(value = (value * 30 * 1e-3), #conversion from MCM/day x month to km3 unit = 'km3') water_for_irrigation.df = bind_rows( lapply( scen_chk, function( sc ){ merge( data.frame( res.list[[ sc ]]$input ) %>% filter( commodity == 'freshwater', tec %in% tec[ grepl('irrigation_', tec ) ] ), data.frame( res.list[[ sc ]]$ACT ), by = c( 'node', 'tec', 'vintage', 'year_all', 'mode', 'time' ) ) %>% mutate( value = value.x * value.y ) %>% select( node, year_all, value ) %>% group_by( year_all, node ) %>% summarise( sum( value ) ) %>% data.frame() %>% mutate( scenario = sc ) %>% rename( value = sum.value.) %>% select( node, scenario, year_all, value ) } ) ) water_for_irrigation.shiny = water_for_irrigation.df %>% mutate(value = (value * 30 * 1e-3), #conversion from MCM/day x month to km3 unit = 'km3') biomass_for_energy.df = bind_rows( lapply( scen_chk, function( sc ){ merge( data.frame( res.list[[ sc ]]$input ) %>% filter( commodity == 'biomass' ), data.frame( res.list[[ sc ]]$ACT ), by = c( 'node', 'tec', 'vintage', 'year_all', 'mode', 'time' ) ) %>% mutate( value = value.x * value.y ) %>% select( node, year_all, value ) %>% group_by( node, year_all ) %>% summarise( sum( value ) ) %>% data.frame() %>% mutate( scenario = sc ) %>% rename( value = sum.value.) %>% select( node, scenario, year_all, value ) } ) ) biomass_for_energy.shiny = biomass_for_energy.df if (shiny_mode){} else { pdf( 'indus_nexus.pdf', width = 7, height = 3.5 ) p1 = layout( matrix( c(1,2,3), 1,3, byrow=TRUE ), widths=c(0.2,0.2,0.2), heights=c(0.7) ) par(mar=c(3,6,2,0.5), oma = c(2,2,2,2)) colc = c('gray10','gray40','gray70','gray90') barplot( 1e-3 * as.matrix( cbind( energy_for_water.df %>% filter( scenario == scen_chk[1], year_all %in% c(2020,2030,2040,2050) ) %>% group_by(scenario,year_all) %>% summarise(value = sum(value)) %>% ungroup() %>% select( value ) %>% unlist(), energy_for_water.df %>% filter( scenario == scen_chk[2], year_all %in% c(2020,2030,2040,2050) ) %>% group_by(scenario,year_all) %>% summarise(value = sum(value)) %>% ungroup() %>% select( value ) %>% unlist() ) ), beside = TRUE, names.arg = scname, ylim = c(0,1.2*max((energy_for_water.df %>% group_by(scenario,year_all) %>% summarise(value = sum(value)))$value)*1e-3), ylab = 'GWh', col = colc, main = 'Energy for Water' ) abline(h=0) box() legend( 'topleft', legend = c(2020,2030,2040,2050), fill = colc, bty='n' ) barplot( 1 * as.matrix( cbind( water_for_energy.df %>% filter( scenario == scen_chk[1], year_all %in% c(2020,2030,2040,2050) ) %>% group_by(scenario,year_all) %>% summarise(value = sum(value)) %>% ungroup() %>% select( value ) %>% unlist(), water_for_energy.df %>% filter( scenario == scen_chk[2], year_all %in% c(2020,2030,2040,2050) ) %>% group_by(scenario,year_all) %>% summarise(value = sum(value)) %>% ungroup() %>% select( value ) %>% unlist() ) ), beside = TRUE, names.arg = scname, col = colc, ylab = 'Mm3/year', ylim = c(0,1.2*max((water_for_energy.df %>% group_by(scenario,year_all) %>% filter(year_all <= 2050 )%>% summarise(value = sum(value)))$value)), main = 'Water for Energy' ) abline(h=0) box() legend( 'topleft', legend = c(2020,2030,2040,2050), fill = colc, bty='n' ) barplot( 1 * as.matrix( cbind( water_for_irrigation.df %>% filter( scenario == scen_chk[1], year_all %in% c(2020,2030,2040,2050) ) %>% group_by(scenario,year_all) %>% summarise(value = sum(value)) %>% ungroup() %>% select( value ) %>% unlist(), water_for_irrigation.df %>% filter( scenario == scen_chk[2], year_all %in% c(2020,2030,2040,2050) ) %>% group_by(scenario,year_all) %>% summarise(value = sum(value)) %>% ungroup() %>% select( value ) %>% unlist() ) ), beside = TRUE, col = colc, names.arg = scname, ylab = 'Mm3/year', ylim = c( 0,1.5*max((water_for_irrigation.df %>% group_by(scenario,year_all) %>% summarise(value = sum(value)))$value*1) ), main = 'Water for Irrigation' ) abline(h=0) box() legend( 'topleft', legend = c(2020,2030,2040,2050), fill = colc, bty='n' ) dev.off() # a = crossing(orig = c('Water','Energy','Land'), # to = c('Water','Energy','Land'), # min = 0) %>% filter(orig != to) # ## round plot # tmp = rbind(energy_for_water.df %>% select(-tec) %>% mutate(orig = 'Energy', to = 'Water') %>% # mutate(value = value * 1e-3) %>% mutate(unit = 'GWh'), # energy_for_irrigation.df %>% mutate(orig = 'Energy', to = 'Land') %>% # mutate(value = value * 1e-3) %>% mutate(unit = 'GWh'), # water_for_energy.df %>% mutate(orig = 'Water', to = 'Energy') %>% # mutate(value = value ) %>% mutate(unit = 'MCM'), # water_for_irrigation.shiny %>% mutate(orig = 'Water', to = 'Land') %>% # mutate(value = value ) %>% mutate(unit = 'MCM'), # biomass_for_energy.df %>% mutate(orig = 'Land', to = 'Energy') %>% # mutate(value = value ) %>% mutate(unit = 'kt') ) %>% # group_by(scenario,year_all, orig, to) %>% # dplyr::summarise(value = sum(value)) %>% ungroup() %>% # group_by(scenario, orig, to) %>% # dplyr::summarise(value = mean(value)) %>% ungroup() %>% # right_join(a) %>% mutate(scenario = if_else(is.na(value),sc,scenario)) %>% ## hardcoded # mutate(value = if_else(is.na(value),min,value)) %>% select(-min) # # # plot using chordDiagram # require("circlize") # make_nexus_diagram <- function(tmp,sc){ # m = tmp %>% filter(scenario == sc) %>% # tidyr::spread(to,value) %>% dplyr::select(Energy,Land,Water) %>% as.matrix() # dimnames(m) <- list(orig = c('Energy [GWh]','Land [kt]','Water [MCM]'), dest = c('Energy [GWh]','Land [kt]','Water [MCM]')) # m[is.na(m)] = 0 # # df1 = data.frame(order = c(1:3), # r = c(220,50,0), # g = c(0,140,150), # b = c(0,40,230), # region = c('Energy [GWh]','Land [kt]','Water [MCM]')) %>% # mutate(col = rgb(r, g, b, max=255), max = rowSums(m) ) # # #plot # circos.clear() # #par(mar = rep(0, 4), cex=0.9) # #change degree and add gap,trak margin esternal and up to flows # circos.par(canvas.ylim=c(-1.8,1.8),track.margin = c(0.01, -0.05),start.degree = 105, gap.degree = min(80,max(50,sum(df1$max))) ) # chordDiagram(x = m, # directional = 1, # direction.type = c("diffHeight", "arrows"), # link.arr.type = "big.arrow", # order = df1$region, # grid.col = df1$col, annotationTrack = "grid", # transparency = 0.25, annotationTrackHeight = c(0.1, 0.1), # diffHeight = -0.24) # # #add in labels and axis # circos.trackPlotRegion(track.index = 1, panel.fun = function(x, y) { # xlim = get.cell.meta.data("xlim") # xlim[2] = (df1 %>% filter(region == get.cell.meta.data("sector.index")))$max # sector.index = get.cell.meta.data("sector.index") # circos.text(mean(get.cell.meta.data("xlim")), 2.8, sector.index, facing = "bending") # circos.axis(labels.cex=0.5,"top", major.at = seq(0, ceiling(max(xlim)/500)*500 , 500), # minor.ticks=1, labels.away.percentage = 0.2, labels.niceFacing = F ) # }, bg.border = NA) # circos.clear() # title(main = list(paste0(sc), cex = 1, # col = "black", font = 1),line = -3 ) # # } # # pdf( 'nexus_flows.pdf', width = 8, height = 6 ) # for (i in seq_along(scen_chk) ) # { # # par(mar = c(0.2,0.2,0.2,0.2)) # make_nexus_diagram(tmp,scen_chk[i]) # } # dev.off() # # } #### STORAGE #### storage.df = bind_rows( lapply( scen_chk, function( sc ){ data.frame( res.list[[ sc ]]$STORAGE ) %>% # mutate(node = gsub('_.*','',node) ) %>% # group_by(node,year_all,time) %>% # summarise(value = sum(value)) %>% ungroup() %>% filter(year_all<= 2050) %>% mutate( scenario = sc ) %>% mutate(month = as.numeric(time) ) %>% select( node, scenario, year_all, month, value ) } ) ) if (shiny_mode){} else { pdf( 'storage.pdf', width = 7, height = 6 ) for (i in seq_along(scen_chk) ) { par(mfrow = c(i,1)) storage.dfi = storage.df %>% filter(scenario == scen_chk[i]) VAR1 = ggplot(storage.dfi,aes(month,value,colour = year_all)) + geom_line()+ facet_wrap(~node)+ theme_bw()+ ggtitle(paste0('scenario: ',scname[i])) plot(VAR1) } dev.off() } # INSTALLED CAPACITY load historical_capacity.df = bind_rows( lapply( scen_chk, function( sc ){ data.frame( res.list[[ sc ]]$historical_new_capacity ) %>% # group_by( node, year_all ) %>% summarise(value = sum( value ) ) %>% mutate( scenario = sc ) } ) ) capacity.df = bind_rows( lapply( scen_chk, function( sc ){ data.frame( res.list[[ sc ]]$CAP ) %>% filter(year_all <= 2050) %>% mutate( scenario = sc ) } ) ) new_capacity.df = bind_rows( lapply( scen_chk, function( sc ){ data.frame( res.list[[ sc ]]$CAP_NEW ) %>% filter(year_all <= 2050) %>% mutate( scenario = sc ) } ) ) #### COMMODITIES #### # TO DO, fix color when plotting multiple graphs # electricity generation #unit is in MW per month, MWmonth, when summing to yearly values we have MWyear = 8.760 GWh energy_prod_by_source.df = bind_rows( lapply( scen_chk, function( sc ){ merge( data.frame( res.list[[ sc ]]$output ) %>% filter( commodity == 'electricity' & level == 'energy_secondary' | commodity == 'electricity' & level == 'irrigation_final' & tec != 'electricity_distribution_irrigation') %>% filter(!grepl('trs_',tec)), data.frame( res.list[[ sc ]]$ACT ), by = c( 'node', 'tec', 'vintage', 'year_all', 'mode', 'time' ) ) %>% filter(year_all <= 2050) %>% mutate( value = value.x * value.y ) %>% select( node, tec, year_all, time, value ) %>% # group_by( node, year_all ) %>% summarise(value = sum( value ) ) %>% mutate( scenario = sc ) } ) ) transmission_flow.df = bind_rows( lapply( scen_chk, function( sc ){ merge( rbind(data.frame( res.list[[ sc ]]$output ) %>% filter( grepl('trs',tec) ), data.frame( res.list[[ sc ]]$input ) %>% filter( tec == 'trs_PAK_4|PAK' ) ), data.frame( res.list[[ sc ]]$ACT ), by = c( 'node', 'tec', 'vintage', 'year_all', 'mode', 'time' ) ) %>% filter(year_all <= 2050) %>% mutate( value = value.x * value.y ) %>% dplyr::select( node, tec, year_all, mode, time, value ) %>% # group_by( node, year_all ) %>% summarise(value = sum( value ) ) %>% mutate( scenario = sc ) } ) ) %>% dplyr::rename(node_in = node) %>% mutate(node_out = gsub('.*\\|','',tec)) elec_imp_exp = transmission_flow.df %>% mutate(node = node_in) %>% mutate(value = if_else(mode == 1,-value,value)) %>% bind_rows(transmission_flow.df %>% mutate(node = node_out) %>% mutate(value = if_else(mode == 1,value,-value)) ) %>% dplyr::select( node, tec, year_all, time,scenario, value ) %>% mutate(type = 'imp_exp') natioal_inp_exp = elec_imp_exp %>% filter(node %in% c('AFG','CHN','IND','PAK')) %>% mutate(value = -value) %>% rename(country = node) # tec = unique(res.list[[ scen_chk[1] ]]$output$tec) tech_type_enes.df = rbind( data.frame( type = 'coal', tec = tec[ grepl( 'coal', tec ) ] ), data.frame( type = 'nuclear_ccs', tec = tec[ grepl( 'nuclear|igcc', tec ) ] ), data.frame( type = 'gas', tec = tec[ grepl( 'gas', tec ) ] ), data.frame( type = 'hydro', tec = tec[ grepl( 'hydro', tec ) ] ), data.frame( type = 'oil', tec = tec[ grepl( 'oil', tec ) ] ), data.frame( type = 'wind', tec = tec[ grepl( 'wind', tec ) ] ), data.frame( type = 'solar', tec = tec[ grepl( 'solar', tec ) ] ), data.frame( type = 'geothermal', tec = tec[ grepl( 'geothermal', tec ) ] ), data.frame( type = 'rural gen.', tec = c('ethanol_genset','irri_diesel_genset','agri_pv') )) #graphic settings ------------------ en_source_col = c('imp_exp' = '#dcdcdc', "wind" = "#4DAF4A", 'solar' = "#FFFF33", 'rural gen.' = "#A65628", 'hydro' = "#377EB8", "geothermal" = "#984EA3", 'gas' = "#FF7F00", 'nuclear_ccs' = "#F781BF", 'coal' = "#E41A1C", 'oil' = '#0a0a0a' ) en_source_order = as.data.frame(en_source_col) %>% mutate(type = row.names(.)) theme_common = theme(legend.background = element_rect(fill="white", size=0.1, linetype="solid", colour ="black")) #----------------------------- energy_prod_by_source.df = energy_prod_by_source.df %>% left_join(tech_type_enes.df) %>% mutate(value = (value * 30 *24* 1e-6), #conversion from MWmonth to TWh unit = 'TWh') energy_prod_by_source.shiny = energy_prod_by_source.df %>% select(-tec) %>% bind_rows(elec_imp_exp %>% filter(!node %in% c('AFG','CHN','IND','PAK')) %>% mutate(value = (value * 30 *24* 1e-6), #conversion from MWmonth to TWh unit = 'TWh') ) %>% group_by_("node" , "year_all", "time" , "scenario", "type",'unit' ) %>% summarise(value = sum(value)) %>% ungroup() type.shiny = unique(c(type.shiny,as.character( unique(energy_prod_by_source.shiny$type)) )) # ENERGY FINAL final_energy_by_use.df = bind_rows( lapply( scen_chk, function( sc ){ merge( data.frame( res.list[[ sc ]]$input ) %>% filter( commodity == 'electricity' & level == 'urban_final' | commodity == 'electricity' & level == 'irrigation_final' | commodity == 'electricity' & level == 'rural_final'| commodity == 'electricity' & level == 'industry_final'| commodity == 'electricity' & grepl('diversion',tec)), data.frame( res.list[[ sc ]]$ACT ), by = c( 'node', 'tec', 'vintage', 'year_all', 'mode', 'time' ) ) %>% filter(year_all <= 2050) %>% mutate( value = value.x * value.y ) %>% select( node, tec, commodity,level,year_all, time, value ) %>% # group_by( node, year_all ) %>% summarise(value = sum( value ) ) %>% mutate( scenario = sc ) } ) ) tech_type_ene.df = rbind( data.frame( type = 'water distr', tec = tec[ grepl( 'diversion|seawater|distribution', tec ) ] ), data.frame( type = 'canal', tec = tec[ grepl( 'canal', tec ) ] ), data.frame( type = 'water treat', tec = tec[ grepl( 'wastewater', tec ) ] ), data.frame( type = 'smart irr', tec = tec[ grepl( 'irr_smart', tec ) ] ), data.frame( type = 'drip irr', tec = tec[ grepl( 'irr_drip', tec ) ] ), data.frame( type = 'sprinkler irr', tec = tec[ grepl( 'irr_sprinkler', tec ) ] )) #graphic settings ------------------ en_final_col = c( "industry demand" = "#FF7F00", "rural demand" = "#4DAF4A", 'urban demand' = "#A65628", 'sprinkler irr' = "#F781BF", 'smart irr' = "#FFFF33", "drip irr" = "#984EA3", 'water distr' = "#377EB8", 'canal' = "#E41A1C", 'water treat' = "#75cbf4" ) en_final_order = as.data.frame(en_final_col) %>% mutate(type = row.names(.)) #----------------------------- final_energy_by_use.df = final_energy_by_use.df %>% left_join(tech_type_ene.df) %>% mutate(type = if_else(is.na(type),'other',as.character(type)) ) %>% mutate(value = (value * 30 *24* 1e-6), #conversion from MWmonth to TWh unit = 'TWh') elec_demand = demand_fixed.shiny %>% filter(year_all>2015 & year_all <2060 & commodity == 'electricity') %>% mutate(type = gsub('_final',' demand',level)) %>% mutate(value = (value * 30 *24* 1e-6), #conversion from MWmonth to TWh unit = 'TWh') final_energy_by_use.shiny = final_energy_by_use.df %>% select(node,scenario,time,type,level,year_all,value,unit) %>% bind_rows(elec_demand %>% select(node,scenario,type,level,year_all,value,unit) ) %>% select(-level) %>% group_by_("node" , "year_all", "time" , "scenario", "type" ,'unit') %>% summarise(value = sum(value)) %>% ungroup() type.shiny = unique(c(type.shiny,as.character( unique(final_energy_by_use.shiny$type)) )) # %>% group_by(level,year_all,scenario) %>% # summarise(inp = sum(value) ) %>% ungroup() # # final_energy_by_out.df = bind_rows( lapply( scen_chk, function( sc ){ # # merge( data.frame( res.list[[ sc ]]$output ) %>% # filter( commodity == 'electricity' & level == 'urban_final' | # commodity == 'electricity' & level == 'irrigation_final' | # commodity == 'electricity' & level == 'rural_final' ), # data.frame( res.list[[ sc ]]$ACT ), # by = c( 'node', 'tec', 'vintage', 'year_all', 'mode', 'time' ) ) %>% # filter(year_all <= 2050) %>% # mutate( value = value.x * value.y ) %>% # select( node, tec, commodity,level,year_all, time, value ) %>% # # group_by( node, year_all ) %>% summarise(value = sum( value ) ) %>% # mutate( scenario = sc ) # # } ) ) # # sum(final_energy_by_out.df$value)-sum(final_energy_by_use.df$value) - sum(elec_demand$value) ene_historical_capacity.df = historical_capacity.df %>% left_join(tech_type_enes.df) %>% filter(!is.na(type)) %>% select(node,type,tec,year_all,scenario,value) ene_capacity.df = capacity.df %>% left_join(tech_type_enes.df) %>% filter(!is.na(type)) %>% select(node,tec,type,year_all,scenario,value) %>% bind_rows(ene_historical_capacity.df %>% filter(year_all < 2020) %>% #not clear why some values are assigned to 2020, also for nuclear, coal and gas group_by(node,tec,type,scenario) %>% summarise(value = sum(value)) %>% ungroup() %>% mutate(year_all = '2015') %>% select(node,tec,type,year_all,scenario,value)) %>% # bind_rows(ene_historical_capacity.df %>% filter(year_all == 2020) %>% # group_by(node,type,year_all,scenario) %>% # summarise(value = sum(value)) %>% ungroup() %>% # select(node,type,year_all,scenario,value)) %>% group_by(node,tec,type,year_all,scenario) %>% summarise(value = sum(value)) %>% ungroup() new_ene_capacity.df = new_capacity.df %>% left_join(tech_type_enes.df) %>% filter(!is.na(type)) %>% select(node,type,tec,year_all,scenario,value) %>% bind_rows(ene_historical_capacity.df %>% filter(year_all <2020)) new_ene_capacity_plot = new_ene_capacity.df %>% mutate(year = as.numeric(year_all)) %>% select(node,type,tec,year,scenario,value) %>% mutate(country = gsub('_.*','',node)) %>% group_by(country,type,year,scenario) %>% summarise(value = sum(value)) ggplot(new_ene_capacity_plot %>% filter(scenario == scen_chk[2], country != 'CHN'),aes(x = year,y = value,fill = type))+ geom_bar( stat = "identity", position = "stack") + facet_wrap(~country)+ scale_fill_manual(name = 'technology',values = en_source_col)+ theme_bw()+ ggtitle(paste0('Power plants new installed capacity. Scenario: ',scname[2])) # IN SCENARIO WITH SDGS, ELECTRICITY DISTRIBUTION OUTPUTS IN IRRIGATION FINAL IS # HIGHER THAN THE REQUIREMENTS OF IRRIGATION TECHNOLOGIES, 1800 TWh # IS THE ENERGY GOING SOMEWHERE ELSE OR IS IT DUE TO INEQUALITY IN COMMODITY BALANCE? WHY HAPPENS ONLY IN THAT CASE? if (shiny_mode){} else { en_mix_plot = energy_prod_by_source.df %>% mutate(country = gsub('_.*','',node)) %>% group_by(country,type,year_all,scenario) %>% bind_rows(natioal_inp_exp %>% mutate(value = (value * 30 *24* 1e-6) )) %>% # conversion only for imports summarise(value = sum(value)) %>% ungroup() %>% mutate(year = as.numeric( year_all) ) %>% filter(country != 'CHN') en_mix_plot_month = energy_prod_by_source.df %>% mutate(country = gsub('_.*','',node)) %>% group_by(country,time,type,year_all,scenario) %>% bind_rows(natioal_inp_exp %>% mutate(value = (value * 30 *24* 1e-6) )) %>% # conversion only for imports summarise(value = sum(value)) %>% ungroup() %>% mutate(year = as.numeric( year_all), month = as.numeric(time)) %>% filter(country != 'CHN') final_en_plot = final_energy_by_use.df %>% select(node,type,level,year_all,scenario,value) %>% bind_rows(elec_demand %>% select(node,type,level,year_all,scenario,value) ) %>% mutate(country = gsub('_.*','',node)) %>% group_by(country,type,year_all,scenario) %>% summarise(value = sum(value)) %>% ungroup() %>% mutate(year = as.numeric( year_all) ) %>% filter(country != 'CHN') ene_capacity_plot = ene_capacity.df %>% mutate(year = as.numeric(year_all)) %>% select(node,type,year,scenario,value) %>% mutate(country = gsub('_.*','',node)) %>% filter(country != 'CHN') plist = list() plist1 = list() plist2 = list() pdf( 'energy_mix.pdf', width = 7, height = 6 ) maxy = max((ene_capacity_plot %>% group_by(country,year,scenario) %>% summarise(value = sum(value)) %>% ungroup())$value) maxy1 = max((en_mix_plot %>% filter(value > 0)%>% group_by(country,year,scenario) %>% summarise(value = sum(value)) %>% ungroup())$value) min1 = min((en_mix_plot %>% filter(value < 0) %>% group_by(country,year,scenario) %>% summarise(value = sum(value)) %>% ungroup())$value) maxy2 = max((final_en_plot %>% group_by(country,year,scenario) %>% summarise(value = sum(value)) %>% ungroup())$value) for (i in seq_along(scen_chk) ) { plist[[i]] = ggplot(ene_capacity_plot %>% filter(scenario == scen_chk[i]),aes(x = year,y = value,fill = type))+ geom_bar( stat = "identity", position = "stack") + geom_vline(xintercept = 2017.5,linetype = 'longdash',color = 'grey40')+ facet_wrap(~country)+ylim(0,maxy)+ scale_fill_manual(name = 'technology',values = en_source_col)+ theme_bw()+ ggtitle(paste0('Power -plant installed capacity. Scenario: ',scname[i])) par(mfrow = c(i,1)) plist1[[i]] = ggplot(en_mix_plot %>% filter(scenario == scen_chk[i]), aes(x = year,y = value,fill = factor(type , levels = en_source_order$type)))+ geom_bar( stat = "identity", position = "stack") + facet_wrap(~country)+ylim(min1,maxy1)+ylab('TWh')+ scale_fill_manual(name = 'technology',values = en_source_col)+ theme_bw()+ ggtitle(paste0('Electricity supply. Scenario: ',scname[i]))+ theme_common plist2[[i]] = ggplot(final_en_plot %>% filter(scenario == scen_chk[i]), aes(x = year,y = value,fill = factor(type , levels = en_final_order$type)))+ geom_bar( stat = "identity", position = "stack") + facet_wrap(~country)+ylim(0,maxy2)+ylab('TWh')+ scale_fill_manual(name = 'end use',values = en_final_col)+ theme_bw()+ ggtitle(paste0('Electricity use. Scenario: ',scname[i]))+ theme_common } grid.arrange(grobs=plist) grid.arrange(grobs=plist1) maxy = max((en_mix_plot_month %>% filter(value > 0) %>% group_by(country,month,year,scenario,time) %>% summarise(value = sum(value)) %>% ungroup())$value)*1.05 miny = min((en_mix_plot_month)$value) for (i in seq_along(scen_chk) ) { par(mfrow = c(i,1)) VAR2 = ggplot(en_mix_plot_month %>% filter(scenario == scen_chk[i]), aes(x = month,y = value,fill = factor(type , levels = en_source_order$type)))+ geom_bar( stat = "identity", position = "stack") + facet_wrap(country~year)+ylim(miny,maxy)+ylab('TWh')+ scale_fill_manual(name = 'technology',values = en_source_col)+ scale_x_continuous(breaks = c(1,3,6,9,12))+ theme_bw()+ ggtitle(paste0('Electrcity supply. Scenario: ',scname[i])) plot(VAR2) } grid.arrange(grobs=plist2) dev.off() } # CROP AREA and WATER area_by_crop.df = bind_rows( lapply( scen_chk, function( sc ){ merge( data.frame( res.list[[ sc ]]$output ) %>% filter( commodity == 'crop_land', level == 'area' , tec != 'fallow_crop' ), data.frame( res.list[[ sc ]]$ACT ), by = c( 'node', 'tec', 'vintage', 'year_all', 'mode', 'time' ) ) %>% filter(year_all <= 2050) %>% mutate( value = value.x * value.y ) %>% select( node, tec, year_all, time, value ) %>% # group_by( node, year_all ) %>% summarise(value = sum( value ) ) %>% mutate( scenario = sc ) } ) ) tech_type_crop.df = rbind( data.frame( type = 'fallow_crop', tec = tec[ grepl( 'fallow_crop', tec ) ] ), data.frame( type = 'cotton', tec = tec[ grepl( 'cotton', tec ) ] ), data.frame( type = 'fodder', tec = tec[ grepl( 'fodder', tec ) ] ), data.frame( type = 'fruit', tec = tec[ grepl( 'fruit', tec ) ] ), data.frame( type = 'pulses', tec = tec[ grepl( 'pulses', tec ) ] ), data.frame( type = 'maize', tec = tec[ grepl( 'maize', tec ) ] ), data.frame( type = 'rice', tec = tec[ grepl( 'rice', tec ) ] ), data.frame( type = 'sugarcane', tec = tec[ grepl( 'sugarcane', tec ) ] ), data.frame( type = 'vegetables', tec = tec[ grepl( 'vegetables', tec ) ] ), data.frame( type = 'wheat', tec = tec[ grepl( 'wheat', tec ) ] ) ) #graphic settings ------------------ crop_col = c('cotton' = "#1b9e77", "fodder" = "#d95f02", 'fruit' = '#b1b1b1', 'pulses' = "#7570b3", 'maize' = "#25bad9", 'rice' = "#e7298a", 'sugarcane' = "#66a61e", 'vegetables' = '#005ad1', 'wheat' = '#e6ab02' ) crop_order = as.data.frame(crop_col) %>% mutate(type = row.names(.)) #----------------------------- area_by_crop.df = area_by_crop.df %>% left_join(tech_type_crop.df) %>% mutate(method = if_else(grepl('rainfed_',tec),'rainfed','irrigated')) #the method dimension does not go in the shiny display, it does not match with plot generalization area_by_crop.shiny = area_by_crop.df %>% select(-tec) %>% group_by_("node" , "year_all", "time" , "scenario", "type" ) %>% summarise(value = sum(value)) %>% ungroup() type.shiny = unique(c(type.shiny,as.character( unique(area_by_crop.shiny$type)) )) crop_capacity.df = capacity.df %>% filter(grepl('crop_|irr_|rainfed',tec)) %>% group_by(node,tec,year_all,scenario) %>% summarise(value = sum(value)) %>% ungroup() %>% bind_rows(historical_capacity.df %>% filter(year_all < 2020, grepl('crop_|irr_|rainfed',tec)) ) # first only plot total land for crop crop_capacity_plot1 = crop_capacity.df %>% filter(grepl('crop_',tec) ) %>% left_join(tech_type_crop.df) %>% mutate(country = gsub('_.*','',node)) %>% group_by(country,type,year_all,scenario) %>% summarise(value = sum(value)) %>% ungroup() ggplot(crop_capacity_plot1 %>% filter(scenario == scen_chk[2]), aes(x = year_all,y = value,fill = factor(type , levels = crop_order$type)))+ geom_bar( stat = "identity", position = "stack") + facet_wrap(~country)+ylab('Mha')+ scale_fill_manual(name = 'crop',values = crop_col)+ theme_bw()+ ggtitle(paste0('crop area. Scenario: ')) new_capacity.df %>% filter(grepl('irr_',tec) ) %>% left_join(tech_type_crop.df) %>% mutate(country = gsub('_.*','',node)) %>% mutate(method = if_else(grepl('rainfed_',tec),'rainfed','irrigated')) %>% group_by(country,type,method,year_all,scenario) %>% summarise(value = sum(value)) %>% ungroup() %>% filter(scenario == scen_chk[2]) %>% ggplot(. ,aes(x = year_all,y = value,fill = factor(type , levels = crop_order$type)))+ geom_bar( stat = "identity", position = "stack") + facet_wrap(~country)+ylab('Mha')+ scale_fill_manual(name = 'crop',values = crop_col)+ theme_bw()+ ggtitle(paste0('crop area. Scenario: ')) if (shiny_mode){} else { crop_area_plot_year = area_by_crop.df %>% mutate(country = gsub('_.*','',node)) %>% group_by(country,method,type,year_all,scenario) %>% summarise(value = sum(value)) %>% ungroup() %>% mutate(year = as.numeric( year_all) ) %>% filter(country != 'CHN') crop_area_plot_month = area_by_crop.df %>% mutate(country = gsub('_.*','',node)) %>% group_by(country,time,method,type,year_all,scenario) %>% summarise(value = sum(value)) %>% ungroup() %>% mutate(year = as.numeric( year_all) ) %>% mutate(month = as.numeric(time)) %>% filter(country != 'CHN') # irrigation and rainfed capacity crop_capacity_plot2 = crop_capacity.df %>% filter(grepl('irr_|rainfed',tec) ) %>% left_join(tech_type_crop.df) %>% mutate(country = gsub('_.*','',node), year = as.numeric(year_all)) %>% mutate(method = if_else(grepl('rainfed_',tec),'rainfed','irrigated')) %>% group_by(country,type,method,year,scenario) %>% summarise(value = sum(value)) %>% ungroup() %>% filter(country != 'CHN') plist = list() pdf( 'crop_land.pdf', onefile = TRUE) maxy = max((crop_capacity_plot2 %>% group_by(country,year,scenario) %>% summarise(value = sum(value)) %>% ungroup())$value) for (i in seq_along(scen_chk) ) { plist[[i]] = ggplot(crop_capacity_plot2 %>% filter(scenario == scen_chk[i]), aes(x = year,y = value,fill = factor(type , levels = crop_order$type),alpha = method))+ geom_bar( stat = "identity", position = "stack") + geom_vline(xintercept = 2017.5,linetype = 'longdash',color = 'grey40')+ facet_wrap(~country)+ylim(0,maxy)+ylab('Mha')+ scale_fill_manual(name = 'crop',values = crop_col)+ scale_alpha_manual(values = c(irrigated = 1,rainfed = 0.5))+ scale_x_continuous(breaks = c(2015,2020,2030,2040,2050))+ theme_bw()+ ggtitle(paste0('crop installed capacity. Scenario: ',scname[i])) } grid.arrange(grobs=plist) maxy = max((crop_area_plot_year %>% group_by(country,year,scenario) %>% summarise(value = sum(value)) %>% ungroup())$value) for (i in seq_along(scen_chk) ) { plist[[i]] = ggplot(crop_area_plot_year %>% filter(scenario == scen_chk[i]), aes(x = year,y = value,fill = factor(type , levels = crop_order$type),alpha = method))+ geom_bar( stat = "identity", position = "stack") + facet_wrap(~country)+ylim(0,maxy)+ylab('Mha')+ scale_fill_manual(name = 'crop',values = crop_col)+ scale_alpha_manual(values = c(irrigated = 1,rainfed = 0.5))+ theme_bw()+ ggtitle(paste0('crop area. Scenario: ',scname[i])) } grid.arrange(grobs=plist) maxy = max((crop_area_plot_month %>% group_by(country,year,scenario,time) %>% summarise(value = sum(value)) %>% ungroup())$value) for (i in seq_along(scen_chk) ) { par(mfrow = c(i,1)) VAR2 = ggplot(crop_area_plot_month %>% filter(scenario == scen_chk[i]), aes(x = month,y = value,fill = factor(type , levels = crop_order$type),alpha = method))+ geom_bar( stat = "identity", position = "stack") + facet_wrap(country~year)+ylim(0,maxy)+ylab('Mha')+ scale_fill_manual(name = 'crop',values = crop_col)+ scale_alpha_manual(values = c(irrigated = 1,rainfed = 0.5))+ scale_x_continuous(breaks = c(1,3,6,9,12))+ theme_bw()+ ggtitle(paste0('crop area. Scenario: ',scname[i])) plot(VAR2) } dev.off() } # WATER CONSUMPTION BY SOURCE # groundwater: for the model it is always freshwater.aquifer. however fossil gw = # water from freshwater.aquier - water carried by renew_gw_extract # indeed, renew_gw_extract moves water from renew_gw.aquifer to freshwater_aquifer surface_water.df = bind_rows( lapply( scen_chk, function( sc ){ merge( data.frame( res.list[[ sc ]]$input ) %>% filter( tec == 'sw_extract' | commodity %in% c('wastewater') & level %in% c('urban_secondary','rural_secondary','industry_secondary') ) %>% filter( tec != "environmental_flow") , data.frame( res.list[[ sc ]]$ACT ), by = c( 'node', 'tec', 'vintage', 'year_all', 'mode', 'time' ) ) %>% filter(year_all <= 2050) %>% mutate( value = value.x * value.y ) %>% select( node,commodity,level, tec, year_all, time, value ) %>% # group_by( node, year_all ) %>% summarise(value = sum( value ) ) %>% mutate( scenario = sc ) } ) ) desal_and_gw.df = bind_rows( lapply( scen_chk, function( sc ){ merge( data.frame( res.list[[ sc ]]$output ) %>% filter(grepl( 'seawater', tec ) | grepl( 'gw_extract', tec ) ) , data.frame( res.list[[ sc ]]$ACT ), by = c( 'node', 'tec', 'vintage', 'year_all', 'mode', 'time' ) ) %>% filter(year_all <= 2050) %>% mutate( value = value.x * value.y ) %>% select( node,commodity,level, tec, year_all, time, value ) %>% # group_by( node, year_all ) %>% summarise(value = sum( value ) ) %>% mutate( scenario = sc ) } ) ) tech_type_waterS.df = rbind( data.frame( type = 'fossil gw', tec = "gw_extract"), data.frame( type = 'renewable gw', tec = 'renew_gw_extract' ), data.frame( type = 'surface water', tec = tec[ grepl( 'sw_extract', tec ) ] ), data.frame( type = 'seawater', tec = tec[ grepl( 'seawater', tec ) ] ), data.frame( type = 'wastewater', tec = tec[ grepl( 'wastewater', tec ) ] )) #graphic settings ------------------ water_source_col = c( "fossil gw" = "#a6cee3", "renewable gw" = "#33a02c", 'surface water' = "#1f78b4", 'seawater' = "#b2df8a", 'wastewater' = "#fb9a99", 'other' = '#dcdcdc' ) # in km3/month, if summed is km3/year water_by_source.df = surface_water.df %>% bind_rows(desal_and_gw.df) %>% left_join(tech_type_waterS.df) %>% mutate(type = if_else(is.na(type),'other',as.character(type)) ) %>% left_join( ., data.frame( time = as.character(seq(1:12)), days = c(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) ) ) %>% mutate(value = value * days / 1e3) %>% #conversion from MCM/day x month to km3/month select(-days) water_by_source.shiny = water_by_source.df %>% select(-commodity,-level,-tec) %>% group_by_("node" , "year_all", "time" , "scenario", "type" ) %>% summarise(value = sum(value)) %>% ungroup() %>% # mutate(value = (value * 30 * 1e-3), #conversion from MCM/day x month to km3 mutate( unit = 'km3') type.shiny = unique(c(type.shiny,as.character( unique(water_by_source.shiny$type)) )) # Water final final_water_by_use.df = bind_rows( lapply( scen_chk, function( sc ){ merge( data.frame( res.list[[ sc ]]$input ) %>% filter( commodity == 'freshwater' & level == 'energy_secondary' | commodity == 'freshwater' & level == 'irrigation_final'), data.frame( res.list[[ sc ]]$ACT ), by = c( 'node', 'tec', 'vintage', 'year_all', 'mode', 'time' ) ) %>% filter(year_all <= 2050) %>% mutate( value = value.x * value.y ) %>% select( node, tec, commodity,level,year_all, time, value ) %>% # group_by( node, year_all ) %>% summarise(value = sum( value ) ) %>% mutate( scenario = sc ) } ) ) tech_type_water.df = rbind( data.frame( type = 'power plants', tec = tec[ grepl( 'coal_|gas_|oil_|nuclear_|geothermal_', tec ) ] ), data.frame( type = 'flood irr', tec = tec[ grepl( 'irr_flood', tec ) ] ), data.frame( type = 'flood CL', tec = tec[ grepl( 'irr_canal_lining_flood', tec ) ] ), data.frame( type = 'smart drip', tec = tec[ grepl( 'irr_drip_smart', tec ) ] ), data.frame( type = 'drip irr', tec = tec[ grepl( 'irr_drip', tec ) & !grepl( 'smart', tec ) ] ) , data.frame( type = 'sprinkler irr', tec = tec[ grepl( 'irr_sprinkler', tec ) & !grepl( 'smart', tec ) ] ), data.frame( type = 'smart sprinkler', tec = tec[ grepl( 'irr_sprinkler_smart', tec ) ] ) ) #graphic settings ------------------ water_final_col = c( "power plants" = "#33a02c", "flood irr" = "#1f78b4", "flood CL" = "#984ea3", 'smart drip' = "#984ea3", 'drip irr' = "#49bfe3", 'sprinkler irr' = "#fdbf6f", 'smart sprinkler' = '#fdda4e', 'industry demand' = '#b2df8a', 'rural demand' = '#fb9a99', 'urban demand' = '#e31a1c', 'other' = '#dcdcdc' ) final_water_by_use0.df = final_water_by_use.df %>% left_join(tech_type_water.df) %>% mutate(type = if_else(is.na(type),'other',as.character(type)) ) water_for_crops.shiny = final_water_by_use.df %>% filter(level == 'irrigation_final') %>% mutate(type = gsub('.*\\_', '', tec)) %>% select(-tec,-commodity,-level) %>% group_by_("node" , "year_all", "time" , "scenario", "type" ) %>% summarise(value = sum(value)) %>% ungroup() %>% mutate(value = (value * 30 * 1e-3), #conversion from MCM/day x month to km3 unit = 'km3') water_demand = demand_fixed.shiny %>% filter(year_all>2015 & year_all <2060 & commodity == 'freshwater' & !level %in% c('inflow','river_in') ) %>% mutate(type = gsub('_final',' demand',level)) final_water_by_use.df = final_water_by_use0.df %>% select(node,scenario,time,type,level,year_all,value) %>% bind_rows(water_demand %>% select(node,scenario,time,type,level,year_all,value) ) %>% left_join( ., data.frame( time = as.character(seq(1:12)), days = c(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) ) ) %>% mutate(value = value * days / 1e3) %>% #conversion from MCM/day x month to km3/month select(-days) final_water_by_use.shiny = final_water_by_use.df %>% select(-level) %>% group_by_("node" , "year_all", "time" , "scenario", "type" ) %>% summarise(value = sum(value)) %>% ungroup() %>% # mutate(value = (value * 30 * 1e-3), #conversion from MCM/day x month to km3 mutate( unit = 'km3') type.shiny = unique(c(type.shiny,as.character( unique(water_for_crops.shiny$type)) , as.character( unique(final_water_by_use.shiny$type)) )) ## calculation of capacity and plot history with results wat_historical_capacity.df = historical_capacity.df %>% filter(year_all < 2020, grepl('sw_diversion|gw_diversion',tec)) %>% group_by(node,tec,year_all,scenario) %>% summarise(value = sum(value)) %>% ungroup() wat_capacity.df = capacity.df %>% filter(grepl('sw_diversion|gw_diversion',tec)) %>% group_by(node,tec,year_all,scenario) %>% summarise(value = sum(value)) %>% ungroup() %>% bind_rows( wat_historical_capacity.df ) ## example of map plot with groundwater groundwater_extr.df = water_by_source.df %>% filter(type %in% c('fossil gw','renewable gw')) %>% group_by(node,year_all,time,scenario) %>% summarise(value = sum(value)) %>% ungroup() #sum fossil and renewable groundwater extractions # example of map that should be integrated in the loop basin.spdf2 = basin.spdf names(basin.spdf2)[1] = 'node' basin.spdf2 <- basin.spdf2[ 'node'] # Let's add a unique ID column to our data. basin.spdf2@data$id <- row.names(basin.spdf2@data) #basin.tidy have the shapefiles coordinate basin.tidy <- broom::tidy(basin.spdf2) basin.tidy <<- dplyr::left_join(basin.tidy, basin.spdf2@data, by='id') theme_map <<- # theme_minimal() + theme( text = element_text(family = "Ubuntu Regular", color = "#22211d"), axis.line = element_blank(), axis.text.x = element_blank(), axis.text.y = element_blank(), axis.ticks = element_blank(), axis.title.x = element_blank(), axis.title.y = element_blank(), # panel.grid.minor = element_line(color = "#ebebe5", size = 0.2), panel.grid.major = element_line(color = "#ebebe5", size = 0.2), panel.grid.minor = element_blank(), plot.background = element_rect(fill = "#f5f5f2", color = NA), panel.background = element_rect(fill = "#f5f5f2", color = NA), legend.background = element_rect(fill = "#f5f5f2", color = NA), panel.border = element_blank() ) # example, we plot all scenarios, all years, average through months gw_plot_data = groundwater_extr.df %>% group_by(node,year_all,scenario) %>% summarise(value = mean(value)) %>% ungroup() #basin.tidy2 has the value data basin.tidy2 <- dplyr::left_join(basin.tidy, gw_plot_data, by='node') %>% filter(!is.na(value)) ggplot() + geom_polygon(data = basin.tidy, aes(long,lat, group=group),color='black',fill = "#f5f5f2",size = 0.1) + geom_polygon(data = basin.tidy2, aes(long,lat, group=group,fill=value),alpha=0.8,color='black',size = 0.1) + coord_map("azequalarea") + # facet_wrap(as.formula(paste("~", input$grouping)))+ facet_wrap(year_all~scenario)+ scale_fill_gradient(low = "#56B1F7", high = "#132B43")+ theme_map # PLOT WATER SUPPLY AND FINAL USE if (shiny_mode){} else { wat_capacity_plot.df = wat_capacity.df %>% mutate(country = gsub('_.*','',node), year = as.numeric(year_all)) %>% group_by(country,tec,year,scenario) %>% summarise(value = sum(value)) %>% ungroup() %>% mutate(source = if_else(grepl('_sw_',tec),'surface','groundwater'), tec = gsub('gw_|sw_','',tec)) %>% filter(country != 'CHN') water_by_source_plot_year = water_by_source.df %>% mutate(country = gsub('_.*','',node)) %>% group_by(country,type,year_all,scenario) %>% summarise(value = sum(value)) %>% ungroup() %>% mutate(year = as.numeric( year_all) ) %>% filter(country != 'CHN') water_by_source_plot_month = water_by_source.df %>% mutate(country = gsub('_.*','',node)) %>% group_by(country,time,type,year_all,scenario) %>% summarise(value = sum(value)) %>% ungroup() %>% mutate(year = as.numeric( year_all) ) %>% mutate(month = as.numeric(time)) %>% filter(country != 'CHN') final_water_plot = final_water_by_use.df %>% mutate(country = gsub('_.*','',node)) %>% group_by(country,type,year_all,scenario) %>% summarise(value = sum(value)) %>% ungroup() %>% mutate(year = as.numeric( year_all) ) %>% filter(country != 'CHN') crop_water_use_plot_yr = final_water_by_use0.df %>% select(-type) %>% filter(level == 'irrigation_final') %>% mutate(type = gsub('.*\\_', '', tec)) %>% mutate(country = gsub('_.*','',node)) %>% left_join( ., data.frame( time = as.character(seq(1:12)), days = c(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) ) ) %>% mutate(value = value * days / 1e3) %>% #conversion from MCM/day x month to km3/month select(-days) %>% group_by(country,type,year_all,scenario) %>% summarise(value = sum(value)) %>% ungroup() %>% mutate(year = as.numeric( year_all) ) %>% filter(country != 'CHN') crop_water_use_plot_mth = final_water_by_use0.df %>% select(-type) %>% filter(level == 'irrigation_final') %>% mutate(type = gsub('.*\\_', '', tec)) %>% mutate(country = gsub('_.*','',node)) %>% left_join( ., data.frame( time = as.character(seq(1:12)), days = c(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) ) ) %>% mutate(value = value * days / 1e3) %>% #conversion from MCM/day x month to km3/month select(-days) %>% group_by(country,type,time,year_all,scenario) %>% summarise(value = sum(value)) %>% ungroup() %>% mutate(year = as.numeric( year_all) ) %>% mutate(month = as.numeric(time)) %>% filter(country != 'CHN') plist = list() plist1 = list() plist2 = list() plist3 = list() pdf( 'water_supply_and_final_use.pdf', onefile = TRUE) maxy1 = max((water_by_source_plot_year %>% group_by(country,year,scenario) %>% summarise(value = sum(value)) %>% ungroup())$value)*1.05 maxy2 = max((final_water_plot %>% group_by(country,year,scenario) %>% summarise(value = sum(value)) %>% ungroup())$value)*1.05 maxy3 = max((crop_water_use_plot_yr %>% group_by(country,year,scenario) %>% summarise(value = sum(value)) %>% ungroup())$value)*1.05 for (i in seq_along(scen_chk) ) { plist[[i]] = ggplot(wat_capacity_plot.df %>% filter(scenario == scen_chk[i]), aes(x = year, y = value, fill = tec, alpha = source))+ geom_bar( stat = "identity", position = "stack") + geom_vline(xintercept = 2017.5,linetype = 'longdash',color = 'grey40')+ facet_wrap(~country)+ggtitle(paste0('water tec capacity. Scenario: ',scname[i]))+ scale_color_brewer(type = 'qual',palette = 2)+ scale_alpha_manual(values = c(surface = 1,groundwater = 0.5))+ theme_bw() plist1[[i]]= ggplot(water_by_source_plot_year %>% filter(scenario == scen_chk[i]),aes(x = year,y = value,fill = type))+ geom_bar( stat = "identity", position = "stack") + facet_wrap(~country)+ylim(0,maxy1)+ylab('km3')+ scale_fill_manual(name = 'type',values = water_source_col)+ theme_bw()+ ggtitle(paste0('water sources. Scenario: ',scname[i]))+ theme(axis.title.x = element_blank()) plist2[[i]]= ggplot(final_water_plot %>% filter(scenario == scen_chk[i]),aes(x = year_all,y = value,fill = type))+ geom_bar( stat = "identity", position = "stack") + facet_wrap(~country)+ylim(0,maxy2)+ylab('km3')+ scale_fill_manual(name = 'type',values = water_final_col)+ theme_bw()+ ggtitle(paste0('water final use. Scenario: ',scname[i]))+ theme(axis.title.x = element_blank()) plist3[[i]]= ggplot(crop_water_use_plot_yr %>% filter(scenario == scen_chk[i]), aes(x = year_all,y = value,fill = factor(type , levels = crop_order$type)))+ geom_bar( stat = "identity", position = "stack") + facet_wrap(~country)+ylim(0,maxy3)+ylab('km3')+ scale_fill_manual(name = 'technology',values = crop_col)+ theme_bw()+ ggtitle(paste0('Crops water use. Scenario: ',scname[i]))+ theme(axis.title.x = element_blank()) } grid.arrange(grobs=plist) grid.arrange(grobs=plist1) maxy = max((water_by_source_plot_month %>% group_by(country,year,scenario,time) %>% summarise(value = sum(value)) %>% ungroup())$value) for (i in seq_along(scen_chk) ) { par(mfrow = c(i,1)) VAR2 = ggplot(water_by_source_plot_month %>% filter(scenario == scen_chk[i]),aes(x = month,y = value,fill = type))+ geom_bar( stat = "identity", position = "stack") + facet_wrap(country~year)+ylim(0,maxy)+ylab('km3')+ scale_fill_manual(name = 'type',values = water_source_col)+ theme_bw()+ ggtitle(paste0('water sources. Scenario: ',scname[i]))+ theme(axis.title.x = element_blank()) plot(VAR2) } grid.arrange(grobs=plist2) grid.arrange(grobs=plist3) maxy = max((crop_water_use_plot_mth %>% group_by(country,year,scenario,time) %>% summarise(value = sum(value)) %>% ungroup())$value) for (i in seq_along(scen_chk) ) { par(mfrow = c(i,1)) VAR2 = ggplot(crop_water_use_plot_mth %>% filter(scenario == scen_chk[i]), aes(x = month,y = value,fill = factor(type , levels = crop_order$type)))+ geom_bar( stat = "identity", position = "stack") + facet_wrap(country~year)+ylim(0,maxy)+ylab('km3')+ scale_fill_manual(name = 'technology',values = crop_col)+ theme_bw()+ ggtitle(paste0('Crops water use. Scenario: ',scname[i]))+ theme(axis.title.x = element_blank()) plot(VAR2) } dev.off() } ## FLOW RESULTS: WATER STREAMS AND ELECTRICITY TRANSMISSION # river flow: # get basin shape and simplify them + get centroids # extra_basin.spdf = readOGR( paste( "P:/is-wel/indus/message_indus", 'input', sep = '/' ), paste0( 'indus_extra_basin_rip_countries'), verbose = FALSE ) # extra_basin.spdf = gSimplify(extra_basin.spdf,0.05) sbasin.spdf = gSimplify(basin.spdf,0.03) node_data = basin.spdf@data %>% mutate(DOWN = if_else(is.na(DOWN),'SINK',as.character(DOWN) )) %>% dplyr::select(PID,OUTX,OUTY,DOWN) node_poly = broom::tidy(sbasin.spdf) %>% mutate(group = if_else(group == 4.2,4.1,as.numeric(as.character(group))) ) extra_node_poly = broom::tidy(extra_basin.spdf) %>% mutate(group = as.numeric(as.character(group)) ) %>% filter(group %in% c(0.1,1.1,1.2,2.1,3.1,3.3)) %>% mutate(country = if_else(group <= 1,'AFG', if_else(group > 1 & group <= 2,'PAK', if_else(group > 2 & group <= 3,'IND','CHN'))) ) map_node_group = data.frame(node = node_data$PID, group = unique(node_poly$group)) node_poly = node_poly %>% left_join(map_node_group) %>% mutate(country = gsub('_.*','',node)) node_centroids = gCentroid(basin.spdf,byid=T, id = basin.spdf$PID) coord_sink = node_data %>% filter(PID == 'PAK_4') %>% dplyr::select(OUTX,OUTY) centroid_ext_node = data.frame(x = c(67, 81.3, 78, 66.7), y = c(35, 33, 29.5, 26), node = c('AFG','CHN','IND','PAK'), stringsAsFactors = F) cent_tidy = as.data.frame(node_centroids@coords) %>% mutate(node = row.names(.)) %>% bind_rows(data.frame(x = coord_sink$OUTX, y = coord_sink$OUTY, node = 'SINK', stringsAsFactors = F)) %>% bind_rows(centroid_ext_node) river_flow.df = bind_rows( lapply( scen_chk, function( sc ){ merge( data.frame( res.list[[ sc ]]$input ) %>% filter( grepl('river',tec) , tec != 'hydro_river', commodity == 'freshwater'), data.frame( res.list[[ sc ]]$ACT ), by = c( 'node', 'tec', 'vintage', 'year_all', 'mode', 'time' ) ) %>% filter(year_all <= 2050) %>% mutate( value = value.x * value.y ) %>% dplyr::select( node, tec, year_all, time, value ) %>% # group_by( node, year_all ) %>% summarise(value = sum( value ) ) %>% mutate( scenario = sc ) } ) ) %>% dplyr::rename(node_in = node) %>% mutate(node_out = gsub('.*\\|','',tec)) # INPUT OF RIVER = OUTPUT ENV FLOW + RETURN FLOWS FORM POWER PLANTS env_flow.df = bind_rows( lapply( scen_chk, function( sc ){ merge( data.frame( res.list[[ sc ]]$output ) %>% filter( tec == 'environmental_flow', commodity == 'freshwater'), data.frame( res.list[[ sc ]]$ACT ), by = c( 'node', 'tec', 'vintage', 'year_all', 'mode', 'time' ) ) %>% filter(year_all <= 2050) %>% mutate( value = value.x * value.y ) %>% dplyr::select( node, tec, year_all, time, value ) %>% # group_by( node, year_all ) %>% summarise(value = sum( value ) ) %>% mutate( scenario = sc ) } ) ) %>% dplyr::rename(node_in = node) %>% left_join(node_data , by = c("node_in" = "PID")) %>% dplyr::rename(node_out= DOWN) %>% dplyr::select(-OUTX,-OUTY) env_flow.coord = env_flow.df %>% left_join(cent_tidy %>% dplyr::rename(x.in = x, y.in = y), by = c("node_in" = "node")) %>% left_join(cent_tidy %>% dplyr::rename(x.out = x, y.out = y), by = c("node_out" = "node")) %>% dplyr::select(tec,scenario,year_all,time,value,node_in,node_out,x.in,y.in,x.out,y.out) river_flow.coord = river_flow.df %>% left_join(cent_tidy %>% dplyr::rename(x.in = x, y.in = y), by = c("node_in" = "node")) %>% left_join(cent_tidy %>% dplyr::rename(x.out = x, y.out = y), by = c("node_out" = "node")) %>% dplyr::select(tec,scenario,year_all,time,value,node_in,node_out,x.in,y.in,x.out,y.out) river_flow.shiny = river_flow.df %>% select(-tec,-node_out) %>% rename(node = node_in) %>% mutate(unit = 'MCM/day') # highlight annual transfer for most important sections: boerders and outlet river_section = data.frame(node_in = c('AFG_2','IND_1','IND_2','IND_3','IND_4','PAK_8','PAK_4'), section = c('Kabul','Jhelam','Chenab','Ravi','Stulej','Upper Indus','Outflow'), stringsAsFactors = F) annual_flows.df = river_flow.df %>% filter(node_in %in% river_section$node_in) %>% left_join(river_section) %>% mutate(time = as.numeric(time)) %>% left_join( ., data.frame( time = seq(1:12), days = c(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) ) ) %>% mutate(value = value * days *1e-3) %>% # km^3/month, becomes yearly when summarizing group_by(section,year_all,scenario) %>% summarise(value = sum(value)) %>% ungroup() %>% mutate(units = 'km^3 per year') ## Canals canal_flow.df = bind_rows( lapply( scen_chk, function( sc ){ merge( data.frame( res.list[[ sc ]]$output ) %>% filter( grepl('canal',tec), tec != 'hydro_canal' ), data.frame( res.list[[ sc ]]$ACT ), by = c( 'node', 'tec', 'vintage', 'year_all', 'mode', 'time' ) ) %>% filter(year_all <= 2050) %>% mutate( value = value.x * value.y ) %>% dplyr::select( node, tec, year_all, time, value ) %>% # group_by( node, year_all ) %>% summarise(value = sum( value ) ) %>% mutate( scenario = sc ) } ) ) %>% dplyr::rename(node_in = node) %>% mutate(node_out = gsub('.*\\|','',tec)) %>% mutate(type = gsub('_.*','',tec)) %>% filter(!grepl('irr_',tec)) canal_flow.coord = canal_flow.df %>% left_join(cent_tidy %>% dplyr::rename(x.in = x, y.in = y), by = c("node_in" = "node")) %>% left_join(cent_tidy %>% dplyr::rename(x.out = x, y.out = y), by = c("node_out" = "node")) %>% dplyr::select(tec,type,scenario,year_all,time,value,node_in,node_out,x.in,y.in,x.out,y.out) canal_flow.shiny = canal_flow.coord ## Transmission lines trans_flow.coord = transmission_flow.df %>% filter(mode == 1) %>% bind_rows(transmission_flow.df %>% filter(mode == 2) %>% rename(node_out = node_in, node_in = node_out) %>% dplyr::select( node_in, tec, year_all, mode, time, value,scenario ,node_out )) %>% left_join(cent_tidy %>% dplyr::rename(x.in = x, y.in = y), by = c("node_in" = "node")) %>% left_join(cent_tidy %>% dplyr::rename(x.out = x, y.out = y), by = c("node_out" = "node")) %>% dplyr::select(tec,scenario,mode,year_all,time,value,node_in,node_out,x.in,y.in,x.out,y.out) %>% mutate(value = value *30*24*1e-6, unit = 'TWh') trans_flow.shiny = trans_flow.coord # PLOTTING if (shiny_mode){} else { ocean_poly = data.frame(long = c(65,65,71,71), lat = c(26,20,20,26), order = c(1,2,3,4), hole = FALSE , piece = 1, group = 0.1, id = 0 ) #trip out ocean with other countries, does't work well #no transparency of filling, yes very light colors theme_map_flow = theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank()) country_colors <- c(AFG = "#A2A7D2", CHN = "#F4AA91", IND ="#FAD4A1", PAK = "#C0DDAE") river_plot = river_flow.coord %>% group_by_("tec","scenario","year_all" ,"node_in", "node_out","x.in","y.in","x.out","y.out") %>% summarise(value = sum(value)) canal_plot = canal_flow.coord %>% group_by_("tec",'type' ,"scenario","year_all" ,"node_in", "node_out","x.in","y.in","x.out","y.out") %>% summarise(value = sum(value)) trans_plot = trans_flow.coord %>% group_by_("tec" ,"scenario","mode","year_all" ,"node_in", "node_out","x.in","y.in","x.out","y.out") %>% summarise(value = sum(value)) pdf( 'water_electricity_flow_maps.pdf', onefile = TRUE) # river flows max_size = max(river_plot$value) for (i in seq_along(scen_chk) ) { par(mfrow = c(i,1)) VAR1 = ggplot()+ geom_polygon(data = ocean_poly,aes(long,lat,group = group),colour = 'lightblue',fill = 'lightblue')+ geom_polygon(data = extra_node_poly,aes(long,lat,group = group,fill = country),colour = 'grey50')+ # write country name. make country color, geom_polygon(data = node_poly,aes(long,lat,group = group,fill = country),colour = 'grey50',size = 0.5)+ geom_curve(data = river_plot %>% filter(scenario == scen_chk[i]),aes(x = x.in,y = y.in,xend = x.out, yend = y.out,size = value), color = 'deepskyblue3', lineend = c('butt'),curvature = -0.1 )+ # geom_curve(data = test_env_flow,aes(x = x.in,y = y.in,xend = x.out, yend = y.out,size = value),color = 'darkorchid', # arrow = arrow(length = unit(test_plot$value * 0.0002, "npc"),type = 'open'), # lineend = c('butt'), linejoin = c('round'),curvature = -0.2 )+ facet_wrap(~year_all)+ ggtitle(paste0('Annual river flows. Scenario: ',scen_chk[i]) )+ coord_cartesian(xlim = c(66,82), ylim = c(24,37), expand = TRUE, default = FALSE, clip = "on")+ scale_size(name = 'MCM',range = c(0.8, 2),limits = c(0,max_size))+ scale_fill_manual(values=country_colors)+ theme_bw() + theme_map_flow plot(VAR1) } # canal flows max_size = max(canal_plot$value) for (i in seq_along(scen_chk) ) { par(mfrow = c(i,1)) VAR1 = ggplot()+ geom_polygon(data = ocean_poly,aes(long,lat,group = group),colour = 'lightblue',fill = 'lightblue')+ geom_polygon(data = extra_node_poly,aes(long,lat,group = group,fill = country),colour = 'grey50', size = 0.5)+ # write country name. make country color, geom_polygon(data = node_poly,aes(long,lat,group = group,fill = country),colour = 'grey50', size = 0.5)+ geom_curve(data = canal_plot %>% filter(scenario == scen_chk[i]),aes(x = x.in,y = y.in,xend = x.out, yend = y.out,size = value,colour = type), arrow = arrow(length = unit( 0.02, "npc"),type = 'open'),curvature = -0.2, lineend = c('butt') )+ facet_wrap(~year_all)+ ggtitle(paste0('Annual canal flows. Scenario: ',scen_chk[i]) )+ # geom_curve(data = canal_test_plot %>% filter(grepl('lined',tec)),aes(x = x.in,y = y.in,xend = x.out, yend = y.out,size = value), # color = 'deepskyblue4', arrow = arrow(length = unit( 0.02, "npc"),type = 'open'), # lineend = c('butt'), linejoin = c('round'),curvature = 0.1 )+ coord_cartesian(xlim = c(66,82), ylim = c(24,37), expand = TRUE, default = FALSE, clip = "on")+ scale_size(name = 'MCM',range = c(0.3, 2),limits = c(0,max_size))+ scale_fill_manual(values=country_colors)+ scale_color_manual(values = c(conv = 'brown3',lined = 'deepskyblue4'))+ theme_bw()+theme_map_flow plot(VAR1) } # electricity transmission plot max_size = max(trans_plot$value) for (i in seq_along(scen_chk) ) { par(mfrow = c(i,1)) VAR1 = ggplot()+ geom_polygon(data = ocean_poly,aes(long,lat,group = group),colour = 'lightblue',fill = 'lightblue')+ geom_polygon(data = extra_node_poly,aes(long,lat,group = group,fill = country),colour = 'grey50',size = 0.1)+ # write country name. make country color, geom_polygon(data = node_poly,aes(long,lat,group = group,fill = country),colour = 'grey50',size = 0.1)+ geom_point(data = cent_tidy,aes(x,y))+ geom_curve(data = trans_plot%>% filter(scenario == scen_chk[i], mode == 1),aes(x = x.in,y = y.in,xend = x.out, yend = y.out,size = value), color = 'brown2', arrow = arrow(length = unit( 0.02, "npc"),type = 'open'), lineend = c('butt'), linejoin = c('round'),curvature = -0.3 )+ geom_curve(data = trans_plot %>% filter(scenario == scen_chk[i],mode == 2),aes(x = x.in,y = y.in,xend = x.out, yend = y.out,size = value),color = 'brown2', arrow = arrow(length = unit( 0.02, "npc"),type = 'open'), lineend = c('butt'), linejoin = c('round'),curvature = 0.1 )+ coord_cartesian(xlim = c(66,82), ylim = c(24,37), expand = TRUE, default = FALSE, clip = "on")+ facet_wrap(~year_all)+ ggtitle(paste0('Annual electricity transmission flows. Scenario: ',scen_chk[i]) )+ scale_size(name = 'TWh',range = c(0.3, 2),limits = c(0,max_size))+ scale_fill_manual(values=country_colors)+ theme_bw()+theme_map_flow plot(VAR1) } dev.off() } ## CALCULATE RESULTING YIELD PER NODE/CROP # in Mha area_by_crop.calc = area_by_crop.df %>% group_by(node,year_all,time,scenario,type) %>% summarise(value = sum(value)) area_crop_2020 = area_by_crop.calc %>% filter(year_all == 2020 ) %>% ungroup() %>% group_by_("node" , "scenario", "type" ) %>% summarise(value = sum(value)) %>% ungroup() #in kton crop_production.df = bind_rows( lapply( scen_chk, function( sc ){ merge( data.frame( res.list[[ sc ]]$output ) %>% filter( grepl( '_yield',commodity), level == 'raw' ), data.frame( res.list[[ sc ]]$ACT ), by = c( 'node', 'tec', 'vintage', 'year_all', 'mode', 'time' ) ) %>% filter(year_all <= 2050) %>% mutate( value = value.x * value.y ) %>% select( node, tec, year_all, time, value ) %>% # group_by( node, year_all ) %>% summarise(value = sum( value ) ) %>% mutate( scenario = sc ) } ) ) crop_production.df = crop_production.df %>% left_join(tech_type_crop.df) crop_production.calc = crop_production.df %>% group_by(node,year_all,time,scenario,type) %>% summarise(value = sum(value)) %>% left_join(area_by_crop.calc, by = c("node", "year_all", "time", "scenario", "type")) %>% mutate(value = value.x/value.y/1000) %>% ungroup() crop_prod_avg = crop_production.calc %>% group_by(node,scenario,type) %>% summarise(value = mean(value)) prod_crop_2020 = crop_production.calc %>% filter(year_all == 2020 ) %>% ungroup() %>% group_by_("node" , "scenario", "type" ) %>% summarise(value = sum(value)) %>% ungroup() %>% left_join(area_crop_2020, by = c('node','scenario','type')) %>% mutate(value = value.x/value.y/1000) %>% ungroup() ## COMMODITY COSTS/PRICES #### commodity_price.df = bind_rows( lapply( scen_chk, function( sc ){ data.frame( res.list[[ sc ]]$PRICE_COMMODITY ) %>% mutate( scenario = sc , country = gsub('_.*','',node) , year_all = as.numeric(year_all) ) %>% # sometime time is 'year' therefore I do not transofr in numeric here filter(year_all <= 2050) } ) ) country_colors <- c(AFG = "chartreuse4", CHN = "pink", IND ="red", PAK = "blue") # Land sector agriculture_land_cost.df = commodity_price.df %>% filter(commodity == 'crop_land') %>% mutate(unit = 'USD/ha') %>% group_by(scenario,country,year_all,unit) %>% summarise(value = -mean(value)) crop_product_prices.df = commodity_price.df %>% filter(level == 'raw', value >= 0) %>% mutate(unit = 'USD/ton', commodity = gsub('_yield','',commodity), value = value*1000) %>% #from M$/kton = k$/ton -> $/ton) group_by(scenario,country,commodity,year_all,time,unit) %>% summarise(value = mean(value)) # Electricity at final level final_elec_cost.df = commodity_price.df %>% filter(commodity == 'electricity' & grepl('_final',level), value >= 0) %>% mutate(value = (value *1e3 /30 / 24), # ACT is in MWmonth -> *30 d/m * 24 h/d -> MWh unit = 'USD/kWh', time = as.numeric(time)) %>% group_by(scenario,country,year_all,time,unit) %>% summarise(value = mean(value)) biofuel_cost.df = commodity_price.df %>% filter(commodity == 'biomass' , value >= 0) %>% mutate(value = (value *1000), # from M$/kton = k$/ton -> $/ton) unit = 'USD/ton', time = as.numeric(time)) %>% group_by(scenario,country,level,year_all,time,unit) %>% summarise(value = mean(value)) %>% ungroup() biofuel_cost_plot= ggplot(biofuel_cost.df,aes(x = time,y = value,color = country))+ geom_line(size = 0.8)+theme_bw()+ facet_wrap(level~year_all,nrow = 2)+ scale_color_manual(values=country_colors)+ ylab('USD/ton') + xlab('month') + ggtitle('bio-fuel costs')+ scale_x_continuous(breaks = c(1,3,6,9,12)) # doubts on these biomass costs, it's lower than the variable cost, # maybe due to the residue price, which is soimetime negative? # surface freshwater, groundwater and wastewater costs # groundwater pumping is now free? or included in the gw_diversion tecchnologies? # if so, we cannot distinguish, if goes into the freshwater final cost final_water_cost.df = commodity_price.df %>% filter(commodity %in% c('wastewater','freshwater') & grepl('_final',level), value >= 0) %>% mutate(value = (value /30), # from M CM/day to monthly amount? I am not sure unit = 'USD/m^3 (per month)', time = as.numeric(time)) %>% group_by(scenario,country,commodity,year_all,time,unit) %>% summarise(value = mean(value)) %>% ungroup() if (shiny_mode){} else { pdf( 'commodity_costs.pdf', onefile = TRUE) max_size = max(agriculture_land_cost.df$value) max_size2 = max(crop_product_prices.df$value) for (i in seq_along(scen_chk) ) { # par(mfrow = c(i,1)) land_cost_plot = ggplot(agriculture_land_cost.df %>% filter(scenario == scen_chk[i]),aes(x = year_all,y = value,color = country))+ geom_line()+theme_bw()+ scale_color_manual(values=country_colors)+ylim(c(0,max_size))+ ylab(unique(agriculture_land_cost.df$unit))+ ggtitle(paste0('Land costs. Scenario: ',scen_chk[i])) crop_cost_plot = ggplot(crop_product_prices.df %>% filter(scenario == scen_chk[i]),aes(x = year_all,y = value,color = country))+ geom_line(size = 0.8)+theme_bw()+ facet_wrap(~commodity)+ scale_color_manual(values=country_colors)+ylim(c(0,max_size2))+ ylab('USD/ton')+ ggtitle(paste0('products costs. Scenario: ',scen_chk[i])) two_land_plot = grid.arrange(land_cost_plot,crop_cost_plot, heights = c(0.4,0.6)) } max_size = max(final_elec_cost.df$value) for (i in seq_along(scen_chk) ) { elec_cost_plot = ggplot(final_elec_cost.df %>% filter(scenario == scen_chk[i]),aes(x = time,y = value,color = country))+ geom_line(size = 0.8)+theme_bw()+ facet_wrap(~year_all)+ scale_color_manual(values=country_colors)+ylim(c(0,max_size))+ ylab('USD/kWh') + xlab('month') + ggtitle(paste0('electricity costs. Scenario: ',scen_chk[i]))+ scale_x_continuous(breaks = c(1,3,6,9,12)) plot(elec_cost_plot) } max_size = max(final_water_cost.df$value) max_size1 = max((final_water_cost.df %>% group_by(scenario,commodity,year_all,time,unit) %>% summarise(value = mean(value)) )$value) for (i in seq_along(scen_chk) ) { # par(mfrow = c(i,1)) water_cost_plot = ggplot(final_water_cost.df %>% filter(scenario == scen_chk[i]),aes(x = time,y = value,color = country))+ geom_line(size = 0.8)+theme_bw()+ facet_wrap(commodity~year_all,ncol = 4)+ scale_color_manual(values=country_colors)+ylim(c(0,max_size))+ ylab('USD/m^3') + xlab('month') + ggtitle(paste0('water costs. Scenario: ',scen_chk[i]))+ scale_x_continuous(breaks = c(1,3,6,9,12)) avg_indus_water_cost_plot = ggplot(final_water_cost.df %>% group_by(scenario,commodity,year_all,time,unit) %>% summarise(value = mean(value)) %>% filter(scenario == scen_chk[i]) ,aes(x = time,y = value,color = as.factor(year_all) ))+ geom_line(size = 0.8)+theme_bw()+ facet_wrap(~commodity)+ylim(c(0,max_size))+ ylab('USD/m^3') + xlab('month') + ggtitle(paste0('water costs for whole region. Scenario: ',scen_chk[i]))+ scale_x_continuous(breaks = c(1,3,6,9,12)) two_wat_plot = grid.arrange(water_cost_plot,avg_indus_water_cost_plot, heights = c(0.7,0.3)) } dev.off() } toc()
\subsection{Analytic geometry in the plane}\label{subsec:analytic_geometry_in_the_plane} \begin{remark}\label{rem:analytic_geometry} Analytic geometry is a XVII-century branch of mathematics that studies geometric figures using coordinate \hyperref[rem:coordinate_systems]{systems}. The term \enquote{analytic geometry} may refer to a modern subbranch of algebraic geometry, however we refrain from using \enquote{analytic geometry} in that sense. Historically, most of these definitions were given either for the Euclidean \hyperref[def:euclidean_plane]{plane} or for the three-dimensional Euclidean space. Most of the definitions from \fullref{subsec:vector_space_geometry} are generalizations of concepts from analytic geometry. We will state definitions in the language of linear algebra and refrain from using synthetic (axiomatic) geometry. When working in the plane (resp. three-dimensional space), we will assume that we have fixed an \hyperref[def:orthonormal_system]{orthonormal} coordinate \hyperref[def:euclidean_plane_coordinate_system]{system} \( Oxy \) (resp. \( Oxyz \)), which allows us to visualize geometric figures. \end{remark} \begin{definition}\label{def:plane_line_equations} \hyperref[def:geometric_line]{Lines} in \( \BbbR^2 \) are, so ubiquitous that they can be represented by a lot of standard \hyperref[ex:equations]{equations}. \begin{thmenum} \thmitem{def:plane_line_equations/vector_parametric} When regarding a line as a parametric curve as in \fullref{def:geometric_line/parametric}, the \hyperref[def:first_order_syntax/formula]{formula} \begin{equation}\label{def:plane_line_equations/parametric_equation} l(t) = tx + a \end{equation} is called a \term{vector parametric equation}. \thmitem{def:plane_line_equations/scalar_parametric} Given \fullref{def:plane_line_equations/parametric_equation}, the \term{scalar parametric equations} of the line are \begin{equation}\label{def:plane_line_equations/scalar_parametric_equations} \begin{cases} & l_1(t) = t x_1 + a_1 \\ & l_2(t) = t x_2 + a_2. \end{cases} \end{equation} \thmitem{def:plane_line_equations/general} When regarding a line as an algebraic curve as in \fullref{def:geometric_line/algebraic}, the equation \begin{equation}\label{def:plane_line_equations/general_equation} p(x, y) \coloneqq Ax + By + C = 0 \end{equation} is called the \term{general equation} or simply \term{equation} of a line in a plane. Either \( A \) or \( B \) must be nonzero, so that \( \deg(p) = 1 \). Note that multiple general equations can have the same locus (e.g. the entire polynomial ideal \( \braket{p} \)). \thmitem{def:plane_line_equations/normal} If \( A^2 + B^2 = 1 \), we call \fullref{def:plane_line_equations/general_equation} a \term{normal equation}. This leaves us with only two representatives of \( \braket{p} \). \thmitem{def:plane_line_equations/cartesian} Given \( k, m \in \BbbR \) and \( k \neq 0 \), we define the \term{Cartesian equation} of a line: \begin{equation}\label{def:plane_line_equations/cartesian_equation} y = kx + m. \end{equation} We call \( k \) the \term{slope} of the line. This is a special case of \fullref{def:plane_line_equations/general} with \( A = -k \), \( B = -1 \) and \( C = m \). Unlike the general equation, the Cartesian equation of a line is unique. Conversely, if \( B \neq 0 \) in \fullref{def:plane_line_equations/general_equation}, we can define \( k = -\tfrac A B \) and \( m = -\tfrac C B \) to form a Cartesian equation. \thmitem{def:plane_line_equations/intercept} Given nonzero \( a, b \in \BbbR \), we define the \term{intercept equation} of a line: \begin{equation}\label{def:plane_line_equations/intercept_equation} \frac x a + \frac y b = 1, \end{equation} This is a special case of \fullref{def:plane_line_equations/general} with \( A = \frac 1 a \), \( B = \frac 1 b \) and \( C = -1 \). The intercept equation of a line is also unique. If \( A, B, C \neq 0 \) in \fullref{def:plane_line_equations/general}, we can define an \term{intercept equation} as \( a = -\tfrac C A \) and \( b = -\tfrac C B \)). \end{thmenum} \end{definition} \begin{figure} \begin{minipage}[b]{0.40\textwidth} \centering \text{\todo{Add diagram}}\iffalse\begin{mplibcode} input metapost/plotting; u := 1.5cm; beginfig(1); path l, x_axis, y_axis; x_axis = (-1, 0) scaled u -- (1, 0) scaled u; y_axis = (0, -1) scaled u -- (0, 1) scaled u; l = (-1 / 2, -1) * u -- (1, 3 / 4) * u; drawarrow x_axis; label.bot("$x$", point 0.9 of x_axis); drawarrow y_axis; label.lft("$y$", point 0.9 of y_axis); draw l; label.bot("$y = kx + m$", startpoint of l); endfig; \end{mplibcode}\fi \caption{A \hyperref[def:geometric_line]{line} in \( \BbbR^2 \) defined using its \hyperref[def:plane_line_equations/cartesian]{Cartesian equation}.}\label{def:plane_line_equations/cartesian_equation_drawing} \end{minipage} \hspace{0.05\textwidth} \begin{minipage}[b]{0.40\textwidth} \centering \text{\todo{Add diagram}}\iffalse\begin{mplibcode} input metapost/plotting; u := 1.5cm; beginfig(1) drawarrow (-1 / 2, 0) scaled u -- (2, 0) scaled u; drawarrow (0, -1 / 2) scaled u -- (0, 2) scaled u; z0 = (1 / 2, 1 / 6) scaled u; z1 = (2, 11 / 12) scaled u; z2 = (1, 13 / 6) scaled u; draw z0 -- (x0, max(y1, y2)) dashed withdots; drawarrow z0 -- z1; draw (x0, y1) -- z1 dashed evenly; label.top("$x_1$", midpoint of ((x0, y1) -- z1)); drawarrow z0 -- z2; draw (x0, y2) -- z2 dashed evenly; label.bot("$x_2$", midpoint of ((x0, y2) -- z2)); endfig; \end{mplibcode}\fi \caption{An \hyperref[def:angle/acute]{acute angle} with its measurement segments dashed.}\label{def:angle/figure} \end{minipage} \end{figure} \begin{definition}\label{def:angle} A \term{directed angle} is a tuple of two closed \hyperref[def:geometric_ray]{rays} with a common vertex. It is a closed cone. Given two rays \( r_1, r_2 \) with a common vertex, we denote their corresponding directed angle by \( \sphericalangle(r_1, r_2) \). Suppose that \( r_1 \) and \( r_2 \) have scalar parametric equations \begin{equation*} r_i: t \mapsto \begin{cases} tx_i + a_i \\ ty_i + b_i, \end{cases} i = 1, 2. \end{equation*} We write The condition of the rays having a common vertex is equivalent to \( a_1 = a_2 \) and \( b_1 = b_2 \). If not specified otherwise, we assume that \( a_1 = a_2 = b_1 = b_2 = 0 \). The \term{measure in radians} of a directed angle, often called the angle itself, is defined as the number (see \fullref{def:geometric_trigonometric_functions}) \begin{equation*} \alpha \coloneqq \rem(\arctantwo(y_2, x_2) - \arctantwo(y_1, x_1), 2\pi). \end{equation*} We can classify angles based on their measure as \begin{thmenum} \thmitem{def:angle/zero} \term{zero} if \( \alpha = 0 \), \thmitem{def:angle/acute} \term{acute} if \( \alpha \in (0, \tfrac \pi 2) \), \thmitem{def:angle/right} \term{right} if \( \alpha = \tfrac \pi 2 \), \thmitem{def:angle/obtuse} \term{obtuse} if \( \alpha \in (\tfrac \pi 2, \pi) \), \thmitem{def:angle/straight} \term{straight} if \( \alpha = \pi \), in which case the angle is actually a line, \thmitem{def:angle/reflex} \term{reflex} if \( \alpha > \pi \). \end{thmenum} We often do not care about the order of the two rays and speak of an \term{undirected angle}. In this case, the measure of the undirected angle is the smaller of the measures of the two oriented angles. Thus, we cannot speak of straight and reflex undirected angles. \end{definition} \begin{definition}\label{def:triangle} \begin{figure} \centering \text{\todo{Add diagram}}\iffalse\begin{mplibcode} input metapost/plotting; beginfig(1) pair A, B, C; path alpha, beta, gamma; A := origin; B := (3, 0) scaled u; C := (2, 2) scaled u; draw A -- B -- C -- cycle; alpha = fullcircle scaled (u / 2) shifted A cutbefore (A -- B) cutafter (A -- C); draw alpha; label.urt("$\alpha$", point 0.4 of alpha); beta = fullcircle scaled (u / 2) shifted B cutbefore (B -- C) cutafter (B -- A); draw beta; label.ulft("$\beta$", point 1.4 of beta); gamma = fullcircle scaled (u / 4) shifted C cutbefore (A -- C) cutafter (B -- C); draw gamma; label.bot("$\gamma$", point 0.6 of gamma); fill dot shifted A; fill dot shifted B; fill dot shifted C; label.llft("$A$", A); label.lrt("$B$", B); label.top("$C$", C); label.rt("$a$", midpoint of (B -- C)); label.ulft("$b$", midpoint of (A -- C)); label.bot("$c$", midpoint of (A -- B)); endfig; \end{mplibcode}\fi \caption{An \hyperref[def:triangle/acute]{acute triangle}.}\label{def:triangle/figure} \end{figure} A \term{triangle} is a triple \( (A, B, C) \) of \hyperref[def:point]{points}, no two of which are \hyperref[def:collinear_complanar]{collinear} (see \fullref{def:simplex/triangle} for a more general definition). The three points are called the \term{vertices} of the triangle. Define the associated \hyperref[def:convex_set/line_segment]{line segments}, called the \term{sides} of the triangle, and its (undirected) \hyperref[def:angle]{angles} as \begin{balign*} a \coloneqq [B, C], & & \alpha \coloneqq \sphericalangle(b, c), \\ b \coloneqq [A, C], & & \beta \coloneqq \sphericalangle(a, c), \\ c \coloneqq [A, B], & & \gamma \coloneqq \sphericalangle(a, b). \end{balign*} Note that we defined the angles using segments rather than rays, but this is immaterial because each to each segment \( [p, q] \) there corresponds exactly one closed ray \( t \mapsto p + t q \). We can classify triangles based on their sides as \begin{thmenum} \thmitem{def:triangle/isosceles} \term{isosceles} if at least two of its sides have equal length \thmitem{def:triangle/equilateral} \term{equilateral} if all of its sides have equal length \end{thmenum} or based on their angles as \begin{thmenum} \thmitem{def:triangle/acute} \term{acute} if all of its angles are \hyperref[def:angle/acute]{acute}. \thmitem{def:triangle/right} \term{right} if at least one of the angles is \hyperref[def:angle/straight]{straight}. \thmitem{def:triangle/obtuse} \term{obtuse} if at least one of its angles is \hyperref[def:angle/obtuse]{obtuse}. \end{thmenum} \end{definition} \begin{definition}\label{def:quadratic_plane_curve} The \term{quadratic plane curves} are algebraic \hyperref[def:hypersurface/algebraic]{curves} given by a bivariate polynomial of degree \( 2 \). The \term{general equation} of a quadratic plane curve is \begin{equation}\label{def:quadratic_plane_curve/general_equation} c(x, y) \coloneqq A x^2 + B xy + C y^2 + Dx + Ey + F = 0. \end{equation} Multiple equation can correspond to the same curve. Not all general equations, however, define algebraic curves. We will not concern ourselves with the details. See \fullref{ex:affine_varieties} for a proof that the unit circle is an algebraic curve. It turns out that the algebraic curves given \fullref{def:quadratic_plane_curve/general_equation} are precisely the ones listed here, collectively known as \term{conic sections}. We give only canonical forms of the equations; any linear transformation of the corresponding loci is described by another general equation. \begin{figure} \begin{minipage}{0.3\textwidth} \centering \text{\todo{Add diagram}}\iffalse\begin{mplibcode} input metapost/plotting; u := 1.25cm; vardef scaled_sin(expr x) = 5 / 6 * sin(x) enddef; beginfig(1) fill dot shifted (u, 0); drawarrow (-pi / 2, 0) scaled u -- (pi / 2, 0) scaled u; drawarrow (0, -pi / 2) scaled u -- (0, pi / 2) scaled u; drawarrow path_of_curve(cos, scaled_sin, -1 / 4 * pi, 3 / 4 * pi, 0.01, u); drawarrow path_of_curve(cos, scaled_sin, 3 / 4 * pi, 7 / 4 * pi, 0.01, u); endfig; \end{mplibcode}\fi \end{minipage} \hspace{0.02\textwidth} \begin{minipage}{0.3\textwidth} \centering \text{\todo{Add diagram}}\iffalse\begin{mplibcode} input metapost/plotting; u := 1.25cm; vardef minus_cosh(expr x) = -cosh(x) enddef; beginfig(1) drawarrow (-pi / 2, 0) scaled u -- (pi / 2, 0) scaled u; drawarrow (0, -pi / 2) scaled u -- (0, pi / 2) scaled u; drawarrow path_of_curve(cosh, sinh, -pi / 3, 0, 0.01, u); drawarrow path_of_curve(cosh, sinh, 0, pi / 3, 0.01, u); drawarrow path_of_curve(minus_cosh, sinh, -pi / 3, 0, 0.01, u); drawarrow path_of_curve(minus_cosh, sinh, 0, pi / 3, 0.01, u); endfig; \end{mplibcode}\fi \end{minipage} \hspace{0.02\textwidth} \begin{minipage}{0.3\textwidth} \centering \text{\todo{Add diagram}}\iffalse\begin{mplibcode} input metapost/plotting; u := 1.25cm; beginfig(1) fill dot; drawarrow (-pi / 2, 0) scaled u -- (pi / 2, 0) scaled u; drawarrow (0, -pi / 2) scaled u -- (0, pi / 2) scaled u; vardef y_upper(expr x) = sqrt(x) enddef; vardef y_lower(expr x) = -sqrt(x) enddef; drawarrow path_of_plot(y_upper, 0, pi / 3, 0.01, u); drawarrow path_of_plot(y_lower, 0, pi / 3, 0.01, u); endfig; \end{mplibcode}\fi \end{minipage} \caption{An \hyperref[def:quadratic_plane_curve/ellipse]{ellipse}, \hyperref[def:quadratic_plane_curve/hyperbola]{hyperbola} and \hyperref[def:quadratic_plane_curve/parabola]{parabola} defined via their parametric equations. The starting point is highlighted and the direction of the parametric curves is shown.}\label{def:quadratic_plane_curve/figure} \end{figure} \begin{thmenum} \thmitem{def:quadratic_plane_curve/ellipse} An \term{ellipse} is a quadratic curve whose canonical equation has the form \begin{equation}\label{def:quadratic_plane_curve/ellipse/canonical_equation} c(x, y) \coloneqq \frac {x^2} {a^2} + \frac {y^2} {b^2} - 1 = 0, \end{equation} where \( a, b > 0 \). If \( a = b \), we say that the ellipse is a \term{circle} and we call \( a \) the circle's \term{radius}. The \term{unit circle} is defined by \( a = b = 1 \). Circles generalize to \hyperref[def:metric_space/sphere]{spheres} in metric spaces. \Fullref{def:pi} and \fullref{def:geometric_trigonometric_functions} logically belong here, but are extracted separately for brevity. We are often interested in defining ellipses via \term{scalar parametric equations} using \hyperref[def:trigonometric_functions]{trigonometric functions} as follows: \begin{equation}\label{def:quadratic_plane_curve/ellipse/parametric_equations} \begin{cases} x = a \cos(t) \\ y = b \sin(t), \end{cases} \end{equation} where \( t \in [0, 2\pi) \). We will now demonstrate that \fullref{def:quadratic_plane_curve/ellipse/canonical_equation} and \fullref{def:quadratic_plane_curve/ellipse/parametric_equations} describe the same curve. First, suppose that the pair \( (x_0, y_0) \) satisfies \fullref{def:quadratic_plane_curve/ellipse/canonical_equation}. It follows from \fullref{thm:arctantwo} that \( t_0 \coloneqq \arctantwo\left(\tfrac {y_0} b, \tfrac {x_0} a \right) \) is a, solution to the \hyperref[def:quadratic_plane_curve/ellipse/parametric_equations]{parametric equations}. Conversely, if \( x_0 = a \cos(t_0) \) and \( y_0 = b \sin(t_0) \) for some \( t_0 \in [0, 2\pi) \), by \fullref{thm:trigonometric_identities/pythagorean_identity} it follows that the pair \( (x_0, y_0) \) is a root of \fullref{def:quadratic_plane_curve/ellipse/canonical_equation} and, by \fullref{thm:arctantwo}, \( t_0 \) can be restored given \( \cos(t_0) \) and \( \sin(t_0) \). Therefore, every point of the parametric equation \fullref{def:quadratic_plane_curve/ellipse/parametric_equations} corresponds uniquely to a, solution of the canonical equation \fullref{def:quadratic_plane_curve/ellipse/canonical_equation} and vice versa, which makes the two approaches to defining ellipses equivalent. \thmitem{def:quadratic_plane_curve/hyperbola} A \term{hyperbola} is a quadratic curve whose canonical equation has the form \begin{equation}\label{def:quadratic_plane_curve/hyperbola/canonical_equation} c(x, y) \coloneqq \frac {x^2} {a^2} - \frac {y^2} {b^2} - 1 = 0, \end{equation} where \( a, b > 0 \). Similarly to ellipses, we are can define hyperbolas via \term{scalar parametric equations} using \hyperref[def:hyperbolic_trigonometric_functions]{hyperbolic trigonometric functions} as follows: \begin{equation}\label{def:quadratic_plane_curve/hyperbola/parametric_equations} \begin{cases} x = a \cosh(t) \\ y = b \sinh(t), \end{cases} \end{equation} where \( t \in \BbbR \). This only defines the \term{right part} of the hyperbola. The left part is defined by replacing \( a \) with \( -a \). \thmitem{def:quadratic_plane_curve/parabola} A \term{parabola} is a quadratic curve whose canonical equation has the form \begin{equation}\label{def:quadratic_plane_curve/parabola/canonical_equation} c(x, y) \coloneqq y^2 - 2px = 0, \end{equation} where \( p \neq 0 \). Unlike ellipses and hyperbolas, we do not define parametric equations. Instead, we define \( y \) as a function of \( x \) separately for the lower half-plane and upper half-plane: \begin{equation}\label{def:quadratic_plane_curve/parabola/cartesian_equation} y(x) = \pm \sqrt{2px}. \end{equation} \end{thmenum} Ellipses, hyperbolas and parabolas are collectively called \term{conic sections}. \end{definition} \begin{definition}\label{def:pi} \begin{figure} \centering \text{\todo{Add diagram}}\iffalse\begin{mplibcode} input metapost/plotting; beginfig(1) drawarrow (-pi / 2, 0) scaled u -- (pi / 2, 0) scaled u; drawarrow (0, -1 / 2) scaled u -- (0, pi / 2) scaled u; vardef y(expr x) = sqrt(1 - x ** 2) enddef; drawarrow path_of_plot(y, -1, 1, 0.01, u); endfig; \end{mplibcode}\fi \caption{\( \gph(y^+) \) as a parametric curve in \fullref{def:pi}.}\label{fig:def:pi/upper_half_circle} \end{figure} The definition of a circle of unit radius as the zero-locus of the polynomial \( x^2 + y^2 - 1 \) allows us to, solve a chicken-and-egg problem regarding the definitions of the number \( \pi \). It is conventional to define it as the ratio of a circle's circumference to its diameter. For a unit circle, this diameter is \( 2 \). It will be simpler for us, however, to define \( \pi \) as the radius of a half-circle's circumference since we can represent \( y \) as a function of \( x \) in the upper \hyperref[def:half_space]{half-plane} (see \ref{fig:def:pi/upper_half_circle}). Define the parametric curve \begin{balign*} & y^+: [-1, 1] \to [0, 1] \\ & y^+(x) \coloneqq \sqrt{1 - x^2}. \end{balign*} We use \fullref{thm:length_of_function_graph} to find the length of the graph \( \gph(y^+(x)) \). The derivative of \( y^+(x) \) is \begin{equation*} D_x[y^+(x)] = \frac{-2x}{2 \sqrt{1 - x^2}} = - \frac x {\sqrt{1 - x^2}} dx. \end{equation*} The length of the curve \( \gph(y^+) \) is thus \begin{equation*} \len(\gph(y^+)) = \int_{-1}^1 \sqrt{1 + \frac{x^2}{1 - x^2}} dx = \int_{-1}^1 \frac 1 {\sqrt{1 - x^2}} dx. \end{equation*} This justifies the definition \begin{equation}\label{def:pi/weierstrass_integral} \pi \coloneqq \int_{-1}^1 \frac 1 {\sqrt{1 - x^2}} dx. \end{equation} See \fullref{thm:trigonometric_function_basic_roots} for a proof of how this relates to the trigonometric functions and \fullref{thm:def:exponential_function/properties/eulers_identity} as a consequence. \end{definition} \begin{definition}\label{def:geometric_trigonometric_functions} After defining the \hyperref[def:trigonometric_functions]{trigonometric functions} \( \cos(z) \) and \( \sin(z) \) analytically via power series, we will define their geometric counterparts \( \cos_G(z) \) and \( \sin_G(z) \) and show the connection between them. The actual geometric definition relies on formalisms that are far beyond our interest (see the notes in \fullref{def:euclidean_plane}). Fix a point \( (x_0, y_0) \) on the unit circle (that is, \( x_0^2 + y_0^2 = 1 \)) and define the points \begin{equation}\label{def:geometric_trigonometric_functions/vertices} \begin{array}{l} A \coloneqq (x_0, y_0), \\ B \coloneqq (0, 0), \\ C \coloneqq (x_0, 0). \end{array} \end{equation} Consider the \hyperref[def:triangle]{triangle} formed by these vertices. \Cref{fig:def:geometric_trigonometric_functions/triangle} illustrates the situation. \begin{figure} \begin{minipage}[b]{0.4\textwidth} \centering \text{\todo{Add diagram}}\iffalse\begin{mplibcode} input metapost/plotting; u := 3.5cm; beginfig(1) pair A, B, C; path alpha, beta; t := 1; A := origin; B := (cos(t), sin(t)) scaled u; C := (cos(t), 0) scaled u; draw A -- B -- C -- cycle; alpha = fullcircle scaled (u / 4) shifted A cutbefore (A -- C) cutafter (A -- B); draw alpha; label.urt("$\alpha$", midpoint of alpha); label.lft("$\begin{rcases} \sin_G(\alpha) = \tfrac {\len b} {\len c} \\ \cos_G(\alpha) = \tfrac {\len a} {\len c} \end{rcases}$", A); beta = fullcircle scaled (u / 4) shifted B cutbefore (B -- A) cutafter (B -- C); draw beta; label.llft("$\beta$", point 0.7 of beta); label.lft("$\begin{rcases} \sin_G(\beta) = \tfrac {\len a} {\len c} \\ \cos_G(\beta) = \tfrac {\len b} {\len c} \end{rcases}$", B - (0.05, 0) * u); fill dot shifted A; fill dot shifted B; fill dot shifted C; label.bot("$A$", A); label.top("$B$", B); label.lrt("$C$", C); label.rt("$a$", midpoint of (B -- C)); label.bot("$b$", midpoint of (A -- C)); label.ulft("$c$", midpoint of (A -- B)); endfig; \end{mplibcode}\fi \end{minipage} \hspace{0.05\textwidth} \begin{minipage}[b]{0.4\textwidth} \centering \text{\todo{Add diagram}}\iffalse\begin{mplibcode} input metapost/plotting; u := 3.5cm; beginfig(1) pair A, B, C; path alpha, beta; t := 1; A := origin; B := (cos(t), sin(t)) scaled u; C := (cos(t), 0) scaled u; drawarrow (-sin(pi/16), 0) scaled u -- (5/4, 0) scaled u; drawarrow (0, -sin(pi/16)) scaled u -- (0, 5/4) scaled u; draw path_of_curve(cos, sin, -pi/16, 9/16 * pi, 0.01, u); draw A -- B -- C -- cycle; alpha = fullcircle scaled (u / 4) shifted A cutbefore (A -- C) cutafter (A -- B); draw alpha; label.urt("$\alpha$", midpoint of alpha); beta = fullcircle scaled (u / 4) shifted B cutbefore (B -- A) cutafter (B -- C); draw beta; label.llft("$\beta$", point 0.7 of beta); fill dot shifted A; fill dot shifted B; fill dot shifted C; label.llft("$(0, 0)$", A); label.urt("$(x_0, y_0)$", B); label.lrt("$(x_0, 0)$", C); label.rt("$a$", midpoint of (B -- C)); label.bot("$b$", midpoint of (A -- C)); label.ulft("$c$", midpoint of (A -- B)); endfig; \end{mplibcode}\fi \end{minipage} \caption{An \enquote{abstract} right triangle in the \hyperref[def:euclidean_plane]{Euclidean plane} with legends for geometric sines and cosines and the same triangle in \( \BbbR^2 \) connecting the origin to a point \( (x_0, y_0) \) on the unit circle.}\label{fig:def:geometric_trigonometric_functions/triangle} \end{figure} The original \enquote{geometric definition} of \( \sin_G \) and \( \cos_G \) regards them as functions of an angle rather than numeric functions. \( \sin_G \) and \( \cos_G \) are only defined for two of the angles in a right triangle. The geometric definition is \begin{balign*} \sin_G(\alpha) \coloneqq \frac{\len(b)} {\len(c)}, & & \cos_G(\alpha) \coloneqq \frac{\len(a)} {\len(c)}, \\ \sin_G(\beta) \coloneqq \frac{\len(b)} {\len(c)}, & & \cos_G(\beta) \coloneqq \frac{\len(a)} {\len(c)}. \end{balign*} In our case, \( \len(a) = y_0 \), \( \len(b) = x_0 \) and \( \len(c) = 1 \). Furthermore, \( \sin_G(\beta) \) nor \( \cos_G( \beta) \) are immaterial to our subsequent arguments and we only introduced them for the sake of having a full definition. Therefore, we conclude that \begin{balign*} \sin_G(\alpha) = x_0, & & \cos_G(\alpha) = y_0. \end{balign*} To see that \( \sin_G \) and \( \cos_G \) are somewhat analogous to \( \sin \) and \( \cos \), notice that by \fullref{thm:arctantwo}, there exists a unique \( t_0 \coloneqq \arctantwo(y_0, x_0) \) such that \begin{balign*} \sin(t_0) = x_0, & & \cos(t_0) = y_0. \end{balign*} Therefore, our \hyperref[def:trigonometric_functions]{analytic definition} of the trigonometric functions as numeric functions correspond to the classical geometric definition in the special case where we consider the angle near the origin in the triangle formed by the vertices \fullref{def:geometric_trigonometric_functions/vertices}. This motivates \enquote{measuring} angles using the obtained correspondence. This unit of measurement is called a \term{radian}. We say that the angle \( \alpha \) is \( t_0 \) \term{radians}. Outside of mathematics, it is more conventional to use \term{degrees}, which are obtained from radians by scaling with \( \tfrac {180} {\pi} \). That is, \( \alpha \) is \( \tfrac {180} {\pi} t_0 \) degrees. \end{definition}
module Text.Token %default total ||| For a type `kind`, specify a way of converting the recognised ||| string into a value. ||| ||| ```idris example ||| data SimpleKind = SKString | SKInt | SKComma ||| ||| TokenKind SimpleKind where ||| TokType SKString = String ||| TokType SKInt = Int ||| TokType SKComma = () ||| ||| tokValue SKString x = x ||| tokValue SKInt x = cast x ||| tokValue SKComma x = () ||| ``` public export interface TokenKind (k : Type) where ||| The type that a token of this kind converts to. TokType : k -> Type ||| Convert a recognised string into a value. The type is determined ||| by the kind of token. tokValue : (kind : k) -> String -> TokType kind ||| A token of a particular kind and the text that was recognised. public export record Token k where constructor Tok kind : k text : String ||| Get the value of a `Token k`. The resulting type depends upon ||| the kind of token. public export value : TokenKind k => (t : Token k) -> TokType (kind t) value (Tok k x) = tokValue k x
""" Zip file support """ #***************************************************************************** # Copyright (C) 2016 Volker Braun <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # http://www.gnu.org/licenses/ #***************************************************************************** from __future__ import print_function import zipfile from sage_bootstrap.uncompress.filter_os_files import filter_os_files class SageZipFile(zipfile.ZipFile): """ Wrapper for zipfile.ZipFile to provide better API fidelity with SageTarFile insofar as it's used by this script. """ @classmethod def can_read(cls, filename): """ Given an archive filename, returns True if this class can read and process the archive format of that file. """ return zipfile.is_zipfile(filename) @property def names(self): """ List of filenames in the archive. Filters out names of OS-related files that shouldn't be in the archive (.DS_Store, etc.) """ return filter_os_files(self.namelist()) def extractbytes(self, member): """ Return the contents of the specified archive member as bytes. If the member does not exist, returns None. """ if member in self.namelist(): return self.read(member)
From Coq Require Import String NArith ZArith DecimalString HexString. From Vyper Require Import Config FSet. From Vyper.L10 Require AST Base ToString. Section AST. Context {C: VyperConfig}. Inductive small_stmt := Pass | Const (dst: N) (val: uint256) | Copy (dst src: N) | StorageGet (dst: N) (name: string) | StoragePut (name: string) (src: N) | UnOp (op: L10.AST.unop) (dst src: N) | PowConstBase (dst: N) (base: uint256) (exp: N) | PowConstExp (dst base: N) (exp: uint256) | BinOp (op: L10.AST.binop) (dst src1 src2: N) (Ok: op <> L10.AST.Pow) | PrivateCall (dst: N) (name: string) (args_offset args_count: N) | BuiltinCall (dst: N) (name: string) (args_offset args_count: N) | Abort (ab: L10.Base.abort) | Return (src: N) | Raise (src: N). Inductive stmt := SmallStmt (s: small_stmt) | IfElseStmt (cond_src: N) (yes: stmt) (no: stmt) | Loop (var: N) (count: uint256) (body: stmt) | Semicolon (a b: stmt). Inductive decl := StorageVarDecl (name: string) | FunDecl (name: string) (args_count: N) (body: stmt). (**************************** format ******************************) Local Open Scope string_scope. Definition string_of_small_stmt (ss: small_stmt) := match ss with | Pass => "pass" | Const dst val => "var" ++ NilZero.string_of_uint (N.to_uint dst) ++ " = " ++ HexString.of_Z (Z_of_uint256 val) | Copy dst src => "var" ++ NilZero.string_of_uint (N.to_uint dst) ++ " = var" ++ NilZero.string_of_uint (N.to_uint src) | StorageGet dst name => "var" ++ NilZero.string_of_uint (N.to_uint dst) ++ " = storage_get(" ++ name ++ ")" | StoragePut name src => "storage_put(" ++ name ++ ", var" ++ NilZero.string_of_uint (N.to_uint src) ++ ")" | UnOp op dst src => "var" ++ NilZero.string_of_uint (N.to_uint dst) ++ " = " ++ L10.ToString.string_of_unop op ++ " var" ++ NilZero.string_of_uint (N.to_uint src) | PowConstBase dst base exp => "var" ++ NilZero.string_of_uint (N.to_uint dst) ++ " = " ++ NilZero.string_of_int (Z.to_int (Z_of_uint256 base)) ++ " ** var" ++ NilZero.string_of_uint (N.to_uint exp) | PowConstExp dst base exp => "var" ++ NilZero.string_of_uint (N.to_uint dst) ++ " = var" ++ NilZero.string_of_uint (N.to_uint base) ++ " ** " ++ NilZero.string_of_int (Z.to_int (Z_of_uint256 exp)) | BinOp op dst src1 src2 _ => "var" ++ NilZero.string_of_uint (N.to_uint dst) ++ " = var" ++ NilZero.string_of_uint (N.to_uint src1) ++ " " ++ L10.ToString.string_of_binop op ++ " var" ++ NilZero.string_of_uint (N.to_uint src2) | PrivateCall dst name args_offset args_count => "var" ++ NilZero.string_of_uint (N.to_uint dst) ++ " = " ++ name ++ "/" ++ NilZero.string_of_uint (N.to_uint args_count) ++ "(var" ++ NilZero.string_of_uint (N.to_uint args_offset) ++ ", ...)" | BuiltinCall dst name args_offset args_count => "var" ++ NilZero.string_of_uint (N.to_uint dst) ++ " = $" ++ name ++ "/" ++ NilZero.string_of_uint (N.to_uint args_count) ++ "(var" ++ NilZero.string_of_uint (N.to_uint args_offset) ++ ", ...)" | Abort a => "abort " ++ L10.Base.string_of_abort a | Return n => "return var" ++ NilZero.string_of_uint (N.to_uint n) | Raise n => "raise var" ++ NilZero.string_of_uint (N.to_uint n) end. Fixpoint lines_of_stmt (s: stmt) : list string := match s with | SmallStmt ss => string_of_small_stmt ss :: nil | IfElseStmt cond yes no => ("if var" ++ NilZero.string_of_uint (N.to_uint cond) ++ ":") :: L10.ToString.add_indent (lines_of_stmt yes) ++ "else:" :: L10.ToString.add_indent (lines_of_stmt no) | Loop var count body => ("for var" ++ NilZero.string_of_uint (N.to_uint var) ++ " in count(" ++ HexString.of_Z (Z_of_uint256 count) ++ "):") :: L10.ToString.add_indent (lines_of_stmt body) | Semicolon a b => lines_of_stmt a ++ lines_of_stmt b end. Definition lines_of_decl (d: decl) : list string := (match d with | StorageVarDecl name => ("var " ++ name)%string :: nil | FunDecl name args body => ("def " ++ name ++ "/" ++ NilZero.string_of_uint (N.to_uint args) ++ ":")%string :: L10.ToString.add_indent (lines_of_stmt body) end)%list. Definition string_of_decl (d: decl) := let newline := " " in newline ++ List.fold_right (fun x tail => x ++ newline ++ tail) "" (lines_of_decl d). Definition string_of_decls {C: VyperConfig} (l: list decl) := List.fold_right append "" (List.map string_of_decl l). End AST.
If $a \in S$, $b,c \in S$, and $S$ is starlike with respect to $a$, then the convex hull of $a,b,c$ is contained in $S$.
using Dates struct Transaction sender::String recipient::String amount::Int end struct Block index::Int timestamp::Dates.DateTime transaction::Array{Transaction} proof::Int previous_hash::String end mutable struct blockchain chain::Array{Block} current_transaction::Array{Transaction} end
(* Title: The pi-calculus Author/Maintainer: Jesper Bengtson (jebe.dk), 2012 *) theory Weak_Late_Bisim_Subst_SC imports Weak_Late_Bisim_Subst Strong_Late_Bisim_Subst_SC begin (******** Structural Congruence **********) (******** The \<nu>-operator *****************) lemma resComm: fixes P :: pi shows "<\<nu>a><\<nu>b>P \<approx>\<^sup>s <\<nu>b><\<nu>a>P" proof - have "<\<nu>a><\<nu>b>P \<sim>\<^sup>s <\<nu>b><\<nu>a>P" by(rule Strong_Late_Bisim_Subst_SC.resComm) thus ?thesis by(rule strongBisimWeakBisim) qed (******** Match *********) lemma matchId: fixes a :: name and P :: pi shows "[a\<frown>a]P \<approx>\<^sup>s P" proof - have "[a\<frown>a]P \<sim>\<^sup>s P" by(rule Strong_Late_Bisim_Subst_SC.matchId) thus ?thesis by(rule strongBisimWeakBisim) qed (******** Mismatch *********) shows "[a\<noteq>a]P \<approx>\<^sup>s \<zero>" proof - have "[a\<noteq>a]P \<sim>\<^sup>s \<zero>" by(rule Strong_Late_Bisim_Subst_SC.mismatchNil) thus ?thesis by(rule strongBisimWeakBisim) qed (******** The +-operator *********) lemma sumSym: fixes P :: pi and Q :: pi shows "P \<oplus> Q \<approx>\<^sup>s Q \<oplus> P" proof - have "P \<oplus> Q \<sim>\<^sup>s Q \<oplus> P" by(rule Strong_Late_Bisim_Subst_SC.sumSym) thus ?thesis by(rule strongBisimWeakBisim) qed (******** The |-operator *********) lemma parZero: fixes P :: pi shows "P \<parallel> \<zero> \<approx>\<^sup>s P" proof - have "P \<parallel> \<zero> \<sim>\<^sup>s P" by(rule Strong_Late_Bisim_Subst_SC.parZero) thus ?thesis by(rule strongBisimWeakBisim) qed lemma parSym: fixes P :: pi and Q :: pi shows "P \<parallel> Q \<approx>\<^sup>s Q \<parallel> P" proof - have "P \<parallel> Q \<sim>\<^sup>s Q \<parallel> P" by(rule Strong_Late_Bisim_Subst_SC.parSym) thus ?thesis by(rule strongBisimWeakBisim) qed assumes "x \<sharp> P" shows "<\<nu>x>(P \<parallel> Q) \<approx>\<^sup>s P \<parallel> <\<nu>x>Q" proof - from `x \<sharp> P` have "<\<nu>x>(P \<parallel> Q) \<sim>\<^sup>s P \<parallel> <\<nu>x>Q" by(rule Strong_Late_Bisim_Subst_SC.scopeExtPar) thus ?thesis by(rule strongBisimWeakBisim) qed lemma scopeExtPar': fixes P :: pi and Q :: pi and x :: name assumes "x \<sharp> Q" shows "<\<nu>x>(P \<parallel> Q) \<approx>\<^sup>s (<\<nu>x>P) \<parallel> Q" proof - from `x \<sharp> Q` have "<\<nu>x>(P \<parallel> Q) \<sim>\<^sup>s (<\<nu>x>P) \<parallel> Q" by(rule Strong_Late_Bisim_Subst_SC.scopeExtPar') thus ?thesis by(rule strongBisimWeakBisim) qed shows "(P \<parallel> Q) \<parallel> R \<approx>\<^sup>s P \<parallel> (Q \<parallel> R)" proof - have "(P \<parallel> Q) \<parallel> R \<sim>\<^sup>s P \<parallel> (Q \<parallel> R)" by(rule Strong_Late_Bisim_Subst_SC.parAssoc) thus ?thesis by(rule strongBisimWeakBisim) qed lemma freshRes: fixes P :: pi and a :: name assumes "a \<sharp> P" shows "<\<nu>a>P \<approx>\<^sup>s P" using assms proof - from `a \<sharp> P` have "<\<nu>a>P \<sim>\<^sup>s P" by(rule Strong_Late_Bisim_Subst_SC.scopeFresh) thus ?thesis by(rule strongBisimWeakBisim) qed lemma scopeExtSum: fixes P :: pi and Q :: pi and x :: name assumes "x \<sharp> P" shows "<\<nu>x>(P \<oplus> Q) \<approx>\<^sup>s P \<oplus> <\<nu>x>Q" proof - from `x \<sharp> P` have "<\<nu>x>(P \<oplus> Q) \<sim>\<^sup>s P \<oplus> <\<nu>x>Q" by(rule Strong_Late_Bisim_Subst_SC.scopeExtSum) thus ?thesis by(rule strongBisimWeakBisim) qed lemma bangSC: fixes P shows "!P \<approx>\<^sup>s P \<parallel> !P" proof - have "!P \<sim>\<^sup>s P \<parallel> !P" by(rule Strong_Late_Bisim_Subst_SC.bangSC) thus ?thesis by(rule strongBisimWeakBisim) qed end
Today I have a post for you on making lovely homemade bubble wands. We used the new and improved Artterro bubble wand kit, sent to us for review (and which also contains materials and instructions for making some fun garden art!), but if you’re feeling crafty and resourceful you could make bubble wands without a kit. If you’re a craft store junkie (who, me?) with more time than money or just like working things out, then go the DIY route. But even hard-core DIYers like me enjoy a good kit now and again. The Artterro Eco Art Kits are my kind of art kit. They contain beautiful, high quality materials, are accompanied by inspirational idea-filled brochures, and are made and packaged with the Earth in mind. But the real kicker for me is that while they are KITS, they are still wonderfully open-ended. There is no right or wrong way to create bubble wands or garden art or any other art or craft in the Artterro kits (and we’ve tried just about all of their art kits at this point). We were excited to try out Artterro’s bubble wand kit, partly because who doesn’t love a bubble wand? And an even more sustainable focus. Among other changes, the packaging is now made from 100% recycled cardboard. Maia, Daphne, and I got to work on making bubble wands with the kit. Each kit has two painted wooden dowels so can officially be used to make 2 bubble wands. However, if you have a few sticks or dowels around, you could easily make several more with the amount of wire and glass beads included. Maia and I poked wire through the holes at the tops of the wooden dowels, bent it into our desired bubble wand shapes, then looped it back down and wrapped it around the dowels to secure it. Maia made a simple heart-shaped bubble wand (above). Daphne and I collaborated to make a flower-shaped bubble wand. The bubble wand kit says it’s for ages 8 and up, but Daphne, at 4, was able to participate at her own level. I did the wire bending and cutting on our wand and she did the bead stringing (one of her favorite activities). Here’s our finished flower bubble wand. The kit doubles as a garden art kit, with thicker wire and bigger beads and marbles for the garden art. But then decided they were too awesome as silly dress up glasses. So she created a spiral for the garden instead. The beads are meant to be attached by wrapping the thinner wire around them, but Maia had a bit of trouble with that, and decided to use scotch tape instead. Have you made homemade bubble wands? Or garden art? P.S. Tomorrow I’ll share photos from our afternoon of bubble blowing with our new homemade bubble wands! If you’d like to try out this or other art kits, check out the new and improved arts and crafts kits in the Artterro shop or read on for an Artterro art kit giveaway. To enter the giveaway for a chance to win both Artterro’s Deluxe Bubble Wand Kit as well as their Needle Felting Kit, leave a comment to this post by Friday, April 25th at 11:59 pm EST. After you leave your comment, make sure to tell the Rafflecopter widget that you commented and would like to enter the giveaway! Giveaway open to readers in the US. This Artterro Eco Art Kit was sent to us for free to try out and review, by Artterro, an Artful Parent sponsor. All opinions expressed are my own. I love Artterro kits, and the idea of a bubble wand-making kit is too fabulous. My kiddos are obsessed with bubbles and would be over the moon if we made our own bubble wands! I have been making bubble wands since I was a little girl I make my own glass beads also. I use vynal covered close line wire .it comes in different shiney colors . Have lots of fun sell lots .I put up a tea cart a bowl of water or bucket on the ground. A wand to use and God bless you and yours .if you’re interested in calling me for more tips call 443-296-7699 ..ask for hummer take me over the moon with you please and lots of ♡ . What beautiful bubble wands! I never would have thought to add beads! These are fun and I love the idea of garden art, I’ll have to try this with my kiddos. Thank you! I need a bubble recipe…looking forward to to tomorrows post! My kids go through bubbles like crazy. I just learned needle felting. It’s such fun! Oh so fun! Nothing is better than bubble making :) Thanks for the giveaway!! The perfect time of year for garden art. Ours is mostly dirt right now and needs some cheer. Looks like a fun project for several different age groups and abilities! Looks like some very cool crafts, fun for everyone! We would be absolutely thrille to win those kits. Trying to save up for one now. Thank you for this chance to win them. I had to hop over and check out the other Arttero kits available – these are just too cool! Thank you for the great opportunity to win one! Love Artterro! And I love the bubble wand idea! My kids are bubble-makers all summer long, so I know they’d love this craft. What great kits! They leave a lot of room for kids own creativity. Thanks for review and giveaway! This bubble wand kit looks like great fun! We love both bubbles and beads! My niece will love this. She will have so much fun. I love the idea of making your own Bubble Wands. More fun in the garden with a creative bubble wand! We would love this! These would be so great camping! We’d love to make some! We would LOVE this! My 7 year old is always begging for more arts and crafts. What a fun project!!! Bubbles are in high demand at my house!! looks like a lot of fun. my son would be in heaven making his own bubble wand! thanks for the chance! Well, I love these kits, I teach a textile class and girls just love these kind of projects! Those are really cool. My child loves bubbles! Looks like tons of fun, my boys would love it! We haven’t tried the Artterro kits yet, but they look fantastic! And my daughter loves both blowing bubbles and making things, so I’m sure she’d love the bubble wand kit. We were just outside with bubbles yesterday….great outdoor activity for all ages! We have been looking for garden art ideas… Love this! This looks like a lot of fun! Thanks for posting about it! Those kits look wonderful. Haven’t seen them around here. Both my daughters love bubbles (9 and 4) so this would be awesome to win! I love these ideas can’t wait to make some with my son. Love this idea! Hope I win the kits! The kits do look wonderful. Love the bubble kit. Maybe it could be used to make some magic!! That bubble wand kit looks so fun! Love this company and the fact that it is made in the USA! Very cool! I’d love to win! Thanks! I was not familiar with Artterro kits until I read this post. But I love the idea of the bubble wands, and as a needlefelter myself, I can’t wait to check out the needlefelting and whatever other kits they have. I love the sustainable focus. Thanks for posting! That’s really amazing. Thanks ! Love from France. Very inspiring! Great kit ideas! We love bubbles so this just makes it even more fun! Looks like so much fun and good for motor coordination too. I never thought of this! I would love a kit to help me get started, and hopefully after that we could use leftover bits that I have collected. Their kits gave always looked fantastic. I’d love to try. What a neat kit! My little artist would love it! This would make my daughters very happy!! I’d not heard of this company before. Thanks for the introduction! I’ll have to check out more of their merchandise and ideas. :-D My daughter LOVES blowing bubbles. I believe she was at it for about 3 hours the other day! I’m always looking for some sort of organized project for my son, which I why I like kits like these. We have a clear goal, and everyone right at our fingertips. I’m so grateful for people more creative than I am! What fun!!! Thanks for such great ideas! Wow! There are so many possibilities with these. We’d really like to try! SOOOOO FUN!!!!!!!! Thanks for the chance to win! What a great craft! My boys LOVE bubbles and they will love this, thanks for sharing! We’ve been working on some bubble projects recently, and that kit looks amazing! What a great project for this perfect spring weather! My boys are helping set up a garden and these decorations and bubble wands would be a perfect addition to our outside play time! I have always wanted to try these kits and my girls love bubbles. Thank you! I’d love to win one of these for my kiddos! We love doing arts and crafts together. Too cute! My kids would love this. Great kit…..my 4 year old would love them……may be we will have a bubble party with her friends. Oh, what fun! Who doesn’t love blowing bubbles. I can’t wait to see your pics. These kits look amazing!!!!! Would love to win these for my daughter!!! Thank you for all the wonderful ideas!!!!! Love these kits! Thanks for the giveaway! Love this! I’ve never seen a kit like this, and I think my toddler and I would have fun making some garden art together. Thanks! Great idea! I would love it for my daughters. Looks like a lot of fun!! Thanks. Oh how fun! My kiddos will love this. Looks like a great kit and my daughter loves bubbles! Wow, those look wonderful! I have been wanting to try their kits…..crossing my fingers! I would LOVE some garden art to make with my kids! The bubble wand kit looks so awesome! Love this idea, and the kit looks wonderful! Can’t wait to try. My little one NEEDS art. She isn’t happy without it. We would love these crafty kits! Looking forward to making our own bubble wands-the Arterra kits would be great additions to our craft area. The bubble ward kit looks so fun! The kits look like fun. I think my son would really have fun with this! This looks like so much fun! I think my daughter would enjoy this. This is right uo my alley! The bubble wand kit looks like so much fun! They have some very nice kits. My kids love these kits. They would like canvas book kit. Love it!! So fun. Thank you! This would be a fun activity! Thanks for the opportunity! If it’s even remotely nice outside, my girls want to blow bubbles. The cheap, plastic wands that break after one use are the only ones I can find around here so thank you for the tutorial & info about these amazing kits! Ooooo….bubbles. What great warm weather activity. The bubble kit is just perfect for Spring! Yay for spring weather! We loooove bubbles and this is such a fun idea. This looks like a cute activity for the kids! Looks so fun! Thanks for sharing. How fun! I never knew this type of kit existed. My almost 5 year old would love creating her own bubble wand!
= = = Retail and hospitality = = =
function cv2tifs(y,f) %CV2TIFS Decodes a TIFS2CV compressed image sequence. % Y = CV2TIFS(Y,F) decodes compressed sequence Y (a structure % generated by TIFS2CV) and creates a multiframe TIFF file F. % % See also TIFS2CV. % % Copyright 2002-2020 Gatesmark % % This function, and other functions in the DIPUM Toolbox, are based % on the theoretical and practical foundations established in the % book Digital Image Processing Using MATLAB, 3rd ed., Gatesmark % Press, 2020. % % Book website: http://www.imageprocessingplace.com % License: https://github.com/dipum/dipum-toolbox/blob/master/LICENSE.txt % Get the number of frames, block size, and reconstruction quality. fcnt = double(y.frames); m = double(y.blksz); q = double(y.quality); % Reconstruct the first image in the sequence and store. if q == 0 r = double(huff2mat(y.video(1))); else r = double(jpeg2im(y.video(1))); end imwrite(uint8(r),f,'Compression','none','WriteMode','overwrite'); % Get the frame size and motion vectors. fsz = size(r); mvsz = [fsz/m 2 fcnt]; mv = int16(huff2mat(y.motion)); mv = reshape(mv,mvsz); % For frames except the first, get a motion conpensated prediction % residual and add to the proper reference subimages. for i = 2:fcnt if q == 0 pe = double(huff2mat(y.video(i))); else pe = double(jpeg2im(y.video(i)) - 255); end peC = im2col(pe,[m m],'distinct'); for col = 1:size(peC,2) u = 1 + mod(m * (col - 1),fsz(1)); v = 1 + m * floor((col - 1) * m / fsz(1)); rx = u - mv(1 + floor((u - 1)/m), 1 + floor((v - 1)/m), ... 1, i); ry = v - mv(1 + floor((u - 1)/m), 1 + floor((v - 1)/m), ... 2, i); subimage = r(rx:rx + m - 1,ry:ry + m - 1); peC(:,col) = subimage(:) - peC(:,col); end r = col2im(double(uint16(peC)),[m m],fsz,'distinct'); imwrite(uint8(r),f,'Compression','none', ... 'WriteMode','append'); end
(* Title: HOL/Auth/n_g2kAbsAfter_lemma_inv__78_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__78_on_rules imports n_g2kAbsAfter_lemma_on_inv__78 begin section{*All lemmas on causal relation between inv__78*} lemma lemma_inv__78_on_rules: assumes b1: "r \<in> rules N" and b2: "(f=inv__78 )" 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__78) 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__78) 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__78) 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__78) 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__78) 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__78) 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__78) 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__78) 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__78) 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__78) 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__78) 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__78) 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__78) 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__78) 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__78) 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__78) 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__78) 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__78) 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__78) 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__78) 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__78) 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__78) 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__78) 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__78) 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__78) 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__78) 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__78) 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__78) done } ultimately show "invHoldForRule s f r (invariants N)" by satx qed end
\documentclass[journal, letterpaper]{IEEEtran} %\documentclass{scrartcl} \usepackage[ngerman,english]{babel} %\usepackage[latin1]{inputenc} \usepackage[utf8]{inputenc} \usepackage[T1]{fontenc} \usepackage{amsmath} \usepackage{amsthm} \usepackage{amsfonts} \usepackage{tikz} \usepackage{verbatim} \usepackage{subcaption} \usepackage{algorithm} \usepackage{algorithmic} \usepackage[pdftex]{hyperref} \renewcommand{\algorithmicrequire}{\textbf{Input:}} \renewcommand{\algorithmiccomment}[1]{\ \ // #1} % C-like // Comments \hyphenation{render} % No clubs and widows allowed \clubpenalty10000 \widowpenalty10000 \displaywidowpenalty=10000 \begin{document} %\title{Simulating elastic spheres without external forces} %\subtitle{Project 1 for class CS6491 Computer Graphics} \title{Cube with Spheres \\ {\large Project 1 for class CS6491 Computer Graphics}} %\author{Sebastian Weiss} \author{Sebastian Weiss, Can Erdogan \\ \today} %\date{\today} \maketitle \begin{tikzpicture}[remember picture,overlay] \node[anchor=north east,inner sep=0pt] at (current page.north east) {\includegraphics[scale=1.5]{pic}}; \end{tikzpicture} \section{Objective} In this project, we want to simulate the physically correct motion of a large number of completely elastic spheres flying around in a cube. \section{Input} The input consists of the following data: the initial positions and velocities of $n$ spheres and the half side length of the surrounding cube $s$. We assume that the spheres all have the same radius $r$, the same finite mass, are constantly moving (i.e. no external forces like gravity are applied), that all collisions are completely elastic and at least one velocity is not zero. Furthermore, the spheres do not overlap with each other or the surrounding cube, but they can touch. The surrounding cube is assumed to be of infinite mass, centered at the origin of the coordinate system and aligned to the coordinate axes. \section{Overview} The expected bottleneck of the simulation is the physics calculation. We therefore present a framework for calculating the next collision events in parallel. The computation process, called the physics thread, does not check for collisions in discrete time steps, it instead computes the exact time until the next collision happens. The collision events are buffered and sent to the render thread. This thread then retrieves the collision events and draws the state of the simulation in discrete frames. \section{Implementation} In the following section, we present the steps needed to implement the simulation. \subsection{Datastructures} The sphere $i$, indexed from $0$ to $n-1$, consists of the following data: the initial position $A_i$ and velocity $V_i$ and the start time $t_i$, set to zero at the start of the simulation. The state of the simulation consists of the following data: the current time $t_\text{global}$, initialized with 0, and an array of all spheres $S$. A collision event $e$ contains the time of collision $t_e$ and an array with the indices of the modified spheres and their new positions and velocities at this time. It is written as $(t_e, \{(i, A_i, V_i) | \forall \text{ changed } i\})$. \subsection{Collision computations} This section provides the basic functions needed to compute the collision times and new velocities. \subsubsection{Sphere-Sphere collision}\label{SSC} Given: the spheres $i$ and $j$, and the sphere radius $r$. A collision at time $t$ happens if $\left|(A_i + tV_i)(A_j+tV_j)\right|=2r$ is valid. Expansion leads to the following formula: \begin{equation*} t^2\underbrace{\left|V_i-V_j\right|^2}_{=:a} + t\cdot\underbrace{2((A_iA_j) \bullet (V_j-V_i))}_{=:b} + \underbrace{\left|A_iA_j\right|^2 - 4r^2}_{=:c} = 0 \label{eq:SSC} \end{equation*} This equation is then solved with $t_{1,2}=\frac{-b \pm \sqrt{b^2-4ac}}{2a}$. W.l.o.g. $t_1<t_2$. The following cases have to be distinguished: \begin{itemize} \item $a=0$: the velocities of the spheres are equal, they either always intersect, always touch or always fly in parallel. So no collision is detected. \item $b^2-4ac < 0$: no collision detected, the spheres pass each other. \item $b^2-4ac = 0$: the spheres touch exactly once, no force is applied to the spheres. \item $b^2-4ac > 0$: the equation has two solutions, $t_1$ indicates the start of the intersection and $t_2$ the end. Only collisions with $t_1\geq 0$ are valid collisions and $t_1$ is the resulting collision time. \end{itemize} \subsubsection{Sphere-Sphere velocity change}\label{SSV} Given: the spheres $i$ and $j$, and the time of collision $t$. Output: the new velocities $V'_i$ and $V'_j$ after collision. Let $N:=(A_i+tV_i)(A_j+tV_j)$. The following formula computes the new velocities: \begin{equation*} V'_i=V_j \angle N - V_i \angle N + V_i \ , \ V'_j=V_i \angle N - V_j \angle N + V_j \label{eq:SSV} \end{equation*} \subsubsection{Sphere-Cube collision}\label{SCC} Given: the sphere $i$, the radius $r$ and the half side length $s$ of the surrounding cube. The sphere collides at time $t_{x1}$ with the lower face of the cube in x-direction, and at $t_{x2}$ with the upper face, similar $t_{y1}$ to $t_{z2}$. They are computed according to the following formula: \begin{equation*} t_{c1}=\frac{-s+r-A_i.c}{V_i.c} \ , \ t_{c2}=\frac{s-r-A_i.c}{V_i.c} \ \forall c\in \{x,y,z\} \label{eq:SCC} \end{equation*} \subsubsection{Sphere-Cube velocity change}\label{SCV} Since the surrounding cube is aligned to the coordinate axes, the change in velocity becomes trivial. If a sphere hits one of the two cube faces in x-direction, the x-component of the velocity is negated, and similar with the y- and z-direction. \subsection{Multithreading and synchronization} There exists two threads that run in parallel: the render thread and the physics thread, forming a producer-consumer pattern. The physics thread sends collision events to the render thread over a queue (e.g. a java.util.concurrent.BlockingQueue). We recommend to cap the capacity of the queue to limit the count of events that are precomputed. \subsection{Render thread} The render thread stores the current state of the simulation, the current time and the next collision event $e$. The pseudocode Alg.\ref{alg1} sketches the actions executed every frame: \begin{algorithm} \caption{render frame} \label{alg1} \begin{algorithmic} \STATE $t_\text{global}$ += time per frame. \REPEAT \IF{$e$ is null} \STATE poll the next event from the queue, wait if necessary. \ENDIF \IF{$t_e \leq t_{global}$} \STATE copy the modified spheres from the event into the current state, including position and velocity. \STATE set the time of the modified spheres to $t_e$. \STATE set $e$ to null. \ENDIF \UNTIL{$e$ not null \AND $t_e > t_\text{global}$} \STATE draw each sphere at the position $A_i + (t_\text{global}-t_i)V_i$. \end{algorithmic} \end{algorithm} \subsection{Physics thread 1} The pseudocode Alg.\ref{alg2} sketches the basic work of the physics thread. The physics thread works on its own copy of the initial state. \begin{algorithm} \caption{physics thread - $O(n^2)$} \label{alg2} \begin{algorithmic} \REQUIRE the initial set of spheres $S$ and the queue used for communication \STATE $t_\text{global}=0$ \COMMENT{start time} \LOOP \STATE $i=\text{null}$, $j=\text{null}$. \STATE $\Delta t = \infty$. \FORALL{$\{i',j'\} \in \binom{\{0,...,n-1\}}{2}$} \STATE Check if the collision of sphere $i'$ and $j'$ is sooner than $\Delta t$ (see \ref{SSC}). Store that time in $\Delta t$ and the colliding spheres in $i$ and $j$. \ENDFOR \FORALL{$i' \in \{0,...,n-1\}$} \STATE Check if the collision of sphere $i'$ with the surrounding cube is sooner than $\Delta t$ (see \ref{SCC}). Modify $\Delta t$, $i$, and decode the cube face in $j$. \ENDFOR \STATE Move all spheres $\Delta t$ time steps. \STATE Add $\Delta t$ to $t_\text{global}$. \IF{$j$ indicates a sphere} \STATE Modify $V_i$, $V_j$ according to \ref{SSV}. \STATE Add event $(t_\text{global}, \{(i, A_i, V_i), (j, A_j, V_j)\})$ to the queue. \ELSE[$j$ indicates a cube face] \STATE Modify $V_i$ according to \ref{SCV}. \STATE Add event $(t_\text{global}, \{(i, A_i, V_i)\})$ to the queue, wait if necessary. \ENDIF \ENDLOOP \end{algorithmic} \end{algorithm} Since we assume that at least one velocity is not the null vector, at least one collision is always found. \subsection{Improvement to linear time} The algorithm as described above needs $O(n^2)$ time ($n$ is the number of spheres) per loop iteration. This can be improved to linear time by the following idea: It is not needed to recompute all $\binom{n}{2}$ pairs after one collision. First, for every sphere, the next collision is stored, including the time and collision partner (sphere or cube face). This requires one complete collision check in $O(n^2)$ at the beginning. After a collision, only the modified spheres are then checked for collisions with the other spheres and the bounding box, and the stored collision for these spheres are updated. This operation runs in $O(n)$. The other sphere-sphere pairs remain unaffected. To find the next collision, one must iterate through all the stored collisions in the spheres, so again a time of $O(n)$. \begin{figure}[ht!] \centering %\includegraphics[width=0.7\linewidth]{invalidatePartners.png} \begin{tikzpicture}[scale=0.75] \tikzstyle{node1}=[circle,draw,color=black,minimum size=30,inner sep=0pt] \tikzstyle{node2}=[circle,draw,color=red,minimum size=30,inner sep=0pt] \tikzstyle{node3}=[circle,draw,dashed,color=black,minimum size=30,inner sep=0pt] \tikzstyle{node4}=[circle,draw,dashed,color=red,minimum size=30,inner sep=0pt] \tikzstyle{edge}=[thin,dashed,->] \node[node1] (A1) at (0,0) {A}; \node[node1] (B1) at (-4,6) {B}; \node[node2] (C1) at (-3,3) {C}; \node[node3] (A2) at (3.15,6.3) {A}; \draw[edge] (A1) -- (A2); \node[node3] (B2) at (2.4,7.45) {B}; \draw[edge] (B1) -- (B2); \node[node4] (A3) at (3.15*0.4,6.3*0.4) {A}; \node[node4] (C3) at (0.0,3.2) {C}; \draw[edge,red] (A1) -- (A3); \draw[edge,red] (C1) -- (C3); \end{tikzpicture} \caption{A case in linear time approach: detection of a collision before previously recorded ones can trigger their recomputation.} \label{fig:invalidate} \end{figure} Figure \ref{fig:invalidate} demonstrates a case in the linear time improvement approach where, if the collision AC, with time $t_{AC} < t_{AB}$ is detected after the collisions AB. In that case, the sphere B is invalidated and its next collision time has to be recomputed. If this is not done, sphere B triggers an event at time $t_{AB}$, but at this point, sphere A has already collided with sphere C and is somewhere entirely else. Note that in this procedure, we also have to beware of zero-time events, as they could lead to infinite loops. To prevent such an occasion, we keep track of any collision $IJ$ that happens at $t_{IJ} = 0$ and avoid reprocessing them if the aforementioned invalidation case occurs. See Appendix for a detailed outline of the algorithm. \section{Results} Figure \ref{fig:results} demonstrates the operation times as the square cube of the number of balls are increased from 2 to 13. As expected, removing the physics computation to another thread helped us reach a simulation of 2197 balls. The dominant factors in the computation seem to be the visualization, followed by the communication with the physics thread. \begin{figure}[ht!] \centering \includegraphics[width=1.0\linewidth]{results.png} \caption{The operation times for frame set up, communication with physics thread, updating ball positions and visualization.} \label{fig:results} \end{figure} \section{Future work} As an extension to this simulation, several constraints could be weakened. The spheres could have different radii or different masses. Also the restriction on a centered, axis-aligned cube can be weakened to support arbitrary orientated planes. This all requires changes in the collision formulas. \appendix[Detailed physics thread] The following algorithms show the details of the physics calculation. \begin{algorithm} \caption{initial collision test} \label{alg3.1} \begin{algorithmic} \REQUIRE $n$,$timeCache$,$partnerCache$,$invalidSpheres$ \FORALL{$\{i',j'\} \in \binom{\{0,...,n-1\}}{2}$} \STATE $t \leftarrow $ collision time between sphere $i'$ and $j'$ (see \ref{SSC}) \IF{$t$ is finite and non-zero \AND $t<timeCache[i']$ \AND $t<timeCache[j']$} \IF{$\exists k' : partnerCache[i']=\text{'Sphere'}k'$} \STATE $invalidSpheres$ += $k'$ \STATE $timeCache[k'] \leftarrow$ $\infty$ \STATE $partnerCache[k'] \leftarrow$ 'NoPartner' \ENDIF \IF{$\exists k' : partnerCache[j']=\text{'Sphere'}k'$} \STATE $invalidSpheres$ += $k'$ \STATE $timeCache[k'] \leftarrow$ $\infty$ \STATE $partnerCache[k'] \leftarrow$ 'NoPartner' \ENDIF \STATE $timeCache[i'] \leftarrow t$ \STATE $timeCache[j'] \leftarrow t$ \STATE $partnerCache[i'] \leftarrow \text{'Sphere'}j'$ \STATE $partnerCache[j'] \leftarrow \text{'Sphere'}i'$ \ENDIF \ENDFOR \FORALL{$i' \in \{0,...,n-1\}$} \STATE $t \leftarrow $ collision time between sphere $i'$ and the surrounding cube (see \ref{SCC}) \IF{$t$ is finite and non-zero \AND $t<timeCache[i']$} \IF{$\exists k' : partnerCache[i']=\text{'Sphere'}k'$} \STATE $invalidSpheres$ += $k'$ \STATE $timeCache[k'] \leftarrow$ $\infty$ \STATE $partnerCache[k'] \leftarrow$ 'NoPartner' \ENDIF \STATE $timeCache[i'] \leftarrow t$ \STATE $partnerCache[i'] \leftarrow \text{'Cube'}j'$ \ENDIF \ENDFOR \end{algorithmic} \end{algorithm} \begin{algorithm} \caption{recalculate invalidated spheres} \label{alg3.2} \begin{algorithmic} \REQUIRE $n$,$timeCache$,$partnerCache$,$invalidSpheres$ \WHILE{$invalidSpheres$ is not empty} \STATE $i' \leftarrow invalidSpheres.pop()$ \FORALL{$j' \in \{0,...,n-1\} \backslash \{i'\}$} \STATE $t \leftarrow $ collision time between sphere $i'$ and $j'$ (see \ref{SSC}) \IF{$t$ is finite and non-zero \AND $t<timeCache[j']$} \IF{$\exists k' : partnerCache[j']=\text{'Sphere'}k'$} \STATE $invalidSpheres$ += $k'$ \STATE $timeCache[k'] \leftarrow$ $\infty$ \STATE $partnerCache[k'] \leftarrow$ 'NoPartner' \ENDIF \STATE $timeCache[i'] \leftarrow t$ \STATE $timeCache[j'] \leftarrow t$ \STATE $partnerCache[i'] \leftarrow \text{'Sphere'}j'$ \STATE $partnerCache[j'] \leftarrow \text{'Sphere'}i'$ \ENDIF \ENDFOR \STATE $t \leftarrow $ collision time between sphere $i'$ and the surrounding cube (see \ref{SCC}) \IF{$t$ is finite and non-zero \AND $t<timeCache[i']$} \IF{$\exists k' : partnerCache[i']=\text{'Sphere'}k'$} \STATE $invalidSpheres$ += $k'$ \STATE $timeCache[k'] \leftarrow$ $\infty$ \STATE $partnerCache[k'] \leftarrow$ 'NoPartner' \ENDIF \STATE $timeCache[i'] \leftarrow t$ \STATE $partnerCache[i'] \leftarrow \text{'Cube'}j'$ \ENDIF \ENDWHILE \end{algorithmic} \end{algorithm} \begin{algorithm} \caption{physics thread - $O(n)$} \label{alg3} \begin{algorithmic} \REQUIRE the initial set of spheres $S$ and the queue used for communication \STATE $t_\text{global}=0$ \COMMENT{start time} \STATE $timeCache$ : array[n] \STATE $partnerCache$ : array[n] \STATE fill $timeCache$ with $\infty$ \STATE fill $partnerCache$ with 'NoPartner' \STATE $invalidSpheres$ = $\emptyset$ \COMMENT{Set of sphers which must be recalculated} \STATE run the initial collision test, \ref{alg3.1} \LOOP[main loop] \STATE recalculate invalidated spheres, \ref{alg3.2} \STATE $i \leftarrow \text{null}$, $j \leftarrow \text{null}$. \STATE $\Delta t \leftarrow \infty$. \FORALL[Search next event]{$i' \in \{0,...,n-1\}$} \IF{$timeCache[i'] < \Delta t$} \STATE $i \leftarrow i'$ \STATE $j \leftarrow partnerCache[i']$ \STATE $\Delta t \leftarrow timeCache[i']$ \ENDIF \ENDFOR \STATE Move all spheres $\Delta t$ time steps. \STATE Add $\Delta t$ to $t_\text{global}$. \IF{$j$ indicates a sphere} \STATE Modify $V_i$, $V_j$ according to \ref{SSV}. \STATE Add event $(t_\text{global}, \{(i, A_i, V_i), (j, A_j, V_j)\})$ to the queue, wait if necessary. \ELSE[$j$ indicates a cube] \STATE Modify $V_i$ according to \ref{SCV}. \STATE Add event $(t_\text{global}, \{(i, A_i, V_i)\})$ to the queue, wait if necessary. \STATE $timeCache[j] \leftarrow$ $\infty$ \STATE $partnerCache[j] \leftarrow$ 'NoPartner' \ENDIF \STATE $timeCache[i] \leftarrow$ $\infty$ \STATE $partnerCache[i] \leftarrow$ 'NoPartner' \ENDLOOP \end{algorithmic} \end{algorithm} \end{document}
#include <iterator> #include <fstream> #include <string> #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/qi_parse.hpp> #include <boost/spirit/include/phoenix.hpp> #include "binparse.h" namespace qi = boost::spirit::qi; std::string leb128_encode_s(std::intmax_t value) { std::string encoding; std::uintmax_t uvalue; std::memcpy(&uvalue, &value, sizeof(uvalue)); const bool neg = value < 0; for(bool more = true; more; ) { unsigned char byte = uvalue & std::uintmax_t(0b0111'1111u); uvalue >>= 7; if(neg) uvalue |= (~std::uintmax_t(0u)) << (CHAR_BIT * sizeof(std::uintmax_t) - 7); bool signbit = static_cast<bool>(byte & 0b0100'0000u); if((uvalue == 0 and (not signbit)) or ((uvalue == (~std::uintmax_t(0u))) and signbit)) more = false; else byte |= 0b1000'0000u; encoding.push_back(byte); } return encoding; } std::string leb128_encode_u(std::uintmax_t value) { std::string encoding; do { unsigned char byte = static_cast<unsigned char>(value & 0b0111'1111u); value >>= 7; if(value > 0u) byte |= 0b1000'0000u; encoding.push_back(byte); } while(value > 0u); return encoding; } void print_encoding(std::string_view sv) { for(auto chr: sv) std::cout << (unsigned)chr << ", "; } int main(int argc, char** argv) { for(std::uint8_t uv = 0; uv < 0b0111'1111u; ++uv) { std::string uenc(leb128_encode_u(uv)); std::uintmax_t v{0}; assert(qi::parse(begin(uenc), end(uenc), wasm::parse::varuint7[boost::phoenix::ref(v) = qi::_1])); if(v != uv) std::cerr << std::uintmax_t(uv) << " != " << v << std::endl; assert(v == uv); } for(std::uint8_t uv = 0b1000'0000u; uv < 0b1111'1111; ++uv) { std::string uenc(leb128_encode_u(uv)); assert(not qi::parse(begin(uenc), end(uenc), wasm::parse::varuint7)); } for(std::int8_t sv = -(1 << 6); sv < ((1 << 6) - 1); ++sv) { std::string senc(leb128_encode_s(sv)); signed char v; bool matched = qi::parse(begin(senc), end(senc), wasm::parse::varint7[boost::phoenix::ref(v) = qi::_1]); if(not matched) { std::cerr << int(sv) << " -> "; for(auto chr: senc) std::cerr << int(chr) << ", "; std::cerr << std::endl; } assert(matched); assert(v == sv); } std::string enc; std::uintmax_t uv_in{0}; std::uintmax_t uv_out{0}; std::intmax_t sv_in{0}; std::intmax_t sv_out{0}; bool matched = false; enc = leb128_encode_u(uv_in); matched = qi::parse( begin(enc), end(enc), wasm::parse::varuint32[boost::phoenix::ref(uv_out) = qi::_1] ); assert(matched); assert(uv_in == uv_out); uv_in = std::numeric_limits<std::uint32_t>::max(); enc = leb128_encode_u(uv_in); matched = qi::parse( begin(enc), end(enc), wasm::parse::varuint32[boost::phoenix::ref(uv_out) = qi::_1] ); assert(matched); assert(uv_in == uv_out); uv_in = static_cast<std::uintmax_t>(12345678); enc = leb128_encode_u(uv_in); matched = qi::parse( begin(enc), end(enc), wasm::parse::varuint32[boost::phoenix::ref(uv_out) = qi::_1] ); assert(matched); assert(uv_in == uv_out); uv_in = static_cast<std::uintmax_t>(std::numeric_limits<std::uint32_t>::max()) + 1; enc = leb128_encode_u(uv_in); matched = qi::parse( begin(enc), end(enc), wasm::parse::varuint32[boost::phoenix::ref(uv_out) = qi::_1] ); assert(not matched); sv_in = 0; enc = leb128_encode_s(sv_in); matched = qi::parse( begin(enc), end(enc), wasm::parse::varint32[boost::phoenix::ref(sv_out) = qi::_1] ); assert(matched); assert(sv_in == sv_out); sv_in = std::numeric_limits<std::int32_t>::max(); enc = leb128_encode_u(sv_in); matched = qi::parse( begin(enc), end(enc), wasm::parse::varint32[boost::phoenix::ref(sv_out) = qi::_1] ); assert(matched); assert(sv_in == sv_out); sv_in = std::numeric_limits<std::int32_t>::min(); enc = leb128_encode_u(sv_in); matched = qi::parse( begin(enc), end(enc), wasm::parse::varint32[boost::phoenix::ref(sv_out) = qi::_1] ); assert(matched); assert(sv_in == sv_out); sv_in = 12345678; enc = leb128_encode_u(sv_in); matched = qi::parse( begin(enc), end(enc), wasm::parse::varint32[boost::phoenix::ref(sv_out) = qi::_1] ); assert(matched); assert(sv_in == sv_out); sv_in = static_cast<std::uintmax_t>(std::numeric_limits<std::uint32_t>::max()) + 1; enc = leb128_encode_u(sv_in); matched = qi::parse( begin(enc), end(enc), wasm::parse::varint32[boost::phoenix::ref(sv_out) = qi::_1] ); assert(not matched); return 0; }
Zhou Tong 's fictional life story can be pieced together from two sources : The Story of Yue Fei and Iron Arm , Golden Sabre . The Story of Yue Fei is a fictionalized retelling of Yue Fei 's young life , military exploits , and execution . It was written by a native of <unk> named Qian Cai ( <unk> ) , who lived sometime between the reigns of the Kangxi and Qianlong emperors in the Qing dynasty . The preface dates the book 's publication to 1684 . It was deemed a threat by the Qing emperors and banned during the Qianlong era . In the novel , Zhou is portrayed as an elderly widower and Yue 's only military arts tutor . The General 's historical spear master Chen Guang is never mentioned . Zhou teaches Yue Fei and his sworn brothers military and literary arts from chapters two through five , before his death .
function u = pend_control(x) load('pend_data', 'K', 'U', 'domain'); p = [x(2) x(4)]; u = tpcontroller(p, x, K, U, domain);
Theorem frobenius (A : Set) (p : A -> Prop) (q : Prop): (exists x : A, q /\ p x) <-> (q /\ exists x : A, p x). Proof. split. intros [y [H1 H2]]. split. assumption. exists y. assumption. intros [H1 [y H2]]. exists y. split. assumption. assumption. Qed. Parameter A B C : Set. (* f : A -> B -> C *) Definition curry (f : A * B -> C) := fun a => fun b => f (a, b). Definition uncurry (g : A -> B -> C) := fun p => g (fst p) (snd p). Theorem prf0 : forall f a b, uncurry (curry f) (a, b)= f (a, b). Proof. intros. unfold curry, uncurry. simpl. reflexivity. Qed. Theorem prf1 : forall g a b, curry (uncurry g) a b = g a b. Proof. intros. unfold curry, uncurry. simpl. auto. Qed.
If $f(0) = 0$ and $g(0) = 0$, then $f(g(p)) = (f \circ g)(p)$.
lemma continuous_on_max [continuous_intros]: fixes f g :: "'a::topological_space \<Rightarrow> 'b::linorder_topology" shows "continuous_on A f \<Longrightarrow> continuous_on A g \<Longrightarrow> continuous_on A (\<lambda>x. max (f x) (g x))"
(** * Univalent Foundations. Vladimir Voevodsky. Feb. 2010 - Sep. 2011. Port to coq trunk (8.4-8.5) in March 2014. The third part of the original uu0 file, created on Dec. 3, 2014. Only one universe is used and never as a type. *) (** ** Contents - Sections of "double fibration" [(P : T -> UU) (PP : ∏ t : T, P t -> UU)] and pairs of sections - General case - Functions on dependent sum (to a [total2]) - Functions to direct product - Homotopy fibers of the map [∏ x : X, P x -> ∏ x : X, Q x] - General case - The weak equivalence between sections spaces (dependent products) defined by a family of weak equivalences [(P x) ≃ (Q x)] - Composition of functions with a weak equaivalence on the right - The map between section spaces (dependent products) defined by the map between the bases [ f : Y -> X ] - General case - Composition of functions with a weak equivalence on the left - Sections of families over an empty type and over coproducts - General case - Functions from the empty type - Functions from a coproduct - Sections of families over contractible types and over [ total2 ] (over dependent sums) - General case - Functions from [unit] and from contractible types - Functions from [total2] - Functiosn from direct product - Theorem saying that if each member of a family is of h-level n then the space of sections of the family is of h-level n. - General case - Functions to a contractible type - Functions to a proposition - Functions to an empty type (generalization of [isapropneg]) - Theorems saying that [ iscontr T ], [ isweq f ] etc. are of h-level 1 - Theorems saying that various [ pr1 ] maps are inclusions - Various weak equivalences between spaces of weak equivalences - Composition with a weak equivalence is a weak equivalence on weak equivalences - Invertion on weak equivalences as a weak equivalence - h-levels of spaces of weak equivalences - Weak equivalences to and from types of h-level (S n) - Weak equivalences to and from contractible types - Weak equivalences to and from propositions - Weak equivalences to and from sets - Weak equivalences to an empty type - Weak equivalences from an empty type - Weak equivalences to and from [unit] - Weak auto-equivalences of a type with an isolated point *) (** ** Preamble *) (** Imports *) Require Export UniMath.Foundations.PartC. (** ** Sections of "double fibration" [(P : T -> UU) (PP : ∏ t : T, P t -> UU)] and pairs of sections *) (** *** General case *) Definition totaltoforall {X : UU} (P : X -> UU) (PP : ∏ x, P x -> UU) : (∑ (s0 : ∏ x, P x), ∏ x, PP x (s0 x)) -> ∏ x, ∑ p, PP x p. Proof. intros X0 x. exists (pr1 X0 x). apply (pr2 X0 x). Defined. Definition foralltototal {X : UU} (P : X -> UU) (PP : ∏ x, P x -> UU) : (∏ x, ∑ p, PP x p) -> (∑ (s0 : ∏ x, P x), ∏ x, PP x (s0 x)). Proof. intros X0. exists (λ x, pr1 (X0 x)). apply (λ x, pr2 (X0 x)). Defined. Theorem isweqforalltototal {X : UU} (P : X -> UU) (PP : ∏ x, P x -> UU) : isweq (foralltototal P PP). Proof. intros. simple refine (isweq_iso (foralltototal P PP) (totaltoforall P PP) _ _). - apply idpath. - apply idpath. Defined. Theorem isweqtotaltoforall {X : UU} (P : X -> UU) (PP : ∏ x, P x -> UU) : isweq (totaltoforall P PP). Proof. intros. simple refine (isweq_iso (totaltoforall P PP) (foralltototal P PP) _ _). - apply idpath. - apply idpath. Defined. Definition weqforalltototal {X : UU} (P : X -> UU) (PP : ∏ x, P x -> UU) : (∏ x, ∑ y, PP x y) ≃ (∑ s : (∏ x, P x), (∏ x, PP x (s x))) := make_weq _ (isweqforalltototal P PP). Definition weqtotaltoforall {X : UU} (P : X -> UU) (PP : ∏ x, P x -> UU) : (∑ s : (∏ x, P x), (∏ x, PP x (s x))) ≃ (∏ x, ∑ y, PP x y) := invweq (weqforalltototal P PP). (** *** Functions to a dependent sum (to a [ total2 ]) *) Definition weqfuntototaltototal (X : UU) {Y : UU} (Q : Y -> UU) : (X → ∑ y, Q y) ≃ (∑ f : X → Y, ∏ x, Q (f x)) := weqforalltototal (λ x, Y) (λ x, Q). (** *** Functions to direct product *) (** Note: we give direct proofs for this special case. *) Definition funtoprodtoprod {X Y Z : UU} (f : X -> Y × Z) : (X -> Y) × (X -> Z) := make_dirprod (λ x, pr1 (f x)) (λ x, (pr2 (f x))). Definition prodtofuntoprod {X Y Z : UU} (fg : (X -> Y) × (X -> Z)) : X -> Y × Z := λ x, (pr1 fg x ,, pr2 fg x). Theorem weqfuntoprodtoprod (X Y Z : UU) : (X -> Y × Z) ≃ (X -> Y) × (X -> Z). Proof. intros. simple refine (make_weq _ (isweq_iso (@funtoprodtoprod X Y Z) (@prodtofuntoprod X Y Z) _ _)). - intro a. apply funextfun. intro x. apply idpath. - intro a. induction a as [ fy fz ]. apply idpath. Defined. (** ** Homotopy fibers of the map [∏ x, P x -> ∏ x, Q x] *) (** *** General case *) Definition maponsec {X : UU} (P Q : X -> UU) (f : ∏ x, P x -> Q x) : (∏ x, P x) -> (∏ x, Q x) := λ (s : ∏ x, P x) (x : X), (f x) (s x). Definition maponsec1 {X Y : UU} (P : Y -> UU) (f : X -> Y) : (∏ y : Y, P y) -> (∏ x, P (f x)) := λ (sy : ∏ y : Y, P y) (x : X), sy (f x). Definition hfibertoforall {X : UU} (P Q : X -> UU) (f : ∏ x, P x -> Q x) (s : ∏ x, Q x) : hfiber (maponsec _ _ f) s -> ∏ x, hfiber (f x) (s x). Proof. unfold hfiber. set (map1 := totalfun (λ (pointover : ∏ x, P x), (λ x, f x (pointover x)) = s) (λ (pointover : ∏ x, P x), ∏ x, (f x) (pointover x) = s x) (λ (pointover : ∏ x, P x), toforallpaths _ (λ x, f x (pointover x)) s)). set (map2 := totaltoforall P (λ x pointover, f x pointover = s x)). exact (map2 ∘ map1). Defined. Definition foralltohfiber {X : UU} (P Q : X -> UU) (f : ∏ x, P x -> Q x) (s : ∏ x, Q x) : (∏ x, hfiber (f x) (s x)) -> hfiber (maponsec _ _ f) s. Proof. unfold hfiber. set (map2inv := foralltototal P (λ x pointover, f x pointover = s x)). set (map1inv := totalfun (λ pointover, ∏ x, f x (pointover x) = s x) (λ pointover, (λ x, f x (pointover x)) = s) (λ pointover, funextsec _ (λ x, f x (pointover x)) s)). exact (λ a, map1inv (map2inv a)). Defined. Theorem isweqhfibertoforall {X : UU} (P Q : X -> UU) (f : ∏ x, P x -> Q x) (s : ∏ x, Q x) : isweq (hfibertoforall P Q f s). Proof. use twooutof3c. - exact (isweqfibtototal _ _ (λ pointover, weqtoforallpaths _ _ _)). - apply isweqtotaltoforall. Defined. Definition weqhfibertoforall {X : UU} (P Q : X -> UU) (f : ∏ x, P x -> Q x) (s : ∏ x, Q x) : hfiber (maponsec P Q f) s ≃ ∏ x, hfiber (f x) (s x) := make_weq _ (isweqhfibertoforall P Q f s). Theorem isweqforalltohfiber {X : UU} (P Q : X -> UU) (f : ∏ x, P x -> Q x) (s : ∏ x, Q x) : isweq (foralltohfiber _ _ f s). Proof. use (twooutof3c (Y := @total2 (forall x, P x) (λ (s0 : forall x, P x), forall x, (λ x0 (pointover : P x0), f x0 pointover = s x0) x (s0 x)))). - exact (isweqforalltototal P (λ x, (λ pointover, f x pointover = s x))). - exact (isweqfibtototal _ _ (λ pointover, weqfunextsec _ _ _)). Defined. Definition weqforalltohfiber {X : UU} (P Q : X -> UU) (f : ∏ x, P x -> Q x) (s : ∏ x, Q x) : (∏ x, hfiber (f x) (s x)) ≃ hfiber (maponsec P Q f) s := make_weq _ (isweqforalltohfiber P Q f s). (** *** The weak equivalence between section spaces (dependent products) defined by a family of weak equivalences [ (P x) ≃ (Q x) ] *) Corollary isweqmaponsec {X : UU} (P Q : X -> UU) (f : ∏ x, (P x) ≃ (Q x)) : isweq (maponsec _ _ f). Proof. intros. unfold isweq. intro y. assert (is1 : iscontr (∏ x, hfiber (f x) (y x))). { assert (is2 : ∏ x, iscontr (hfiber (f x) (y x))) by (intro x; apply ((pr2 (f x)) (y x))). apply funcontr. assumption. } apply (iscontrweqb (weqhfibertoforall P Q f y) is1). Defined. Definition weqonsecfibers {X : UU} (P Q : X -> UU) (f : ∏ x, (P x) ≃ (Q x)) : (∏ x, P x) ≃ (∏ x, Q x) := make_weq _ (isweqmaponsec P Q f). (** *** Composition of functions with a weak equivalence on the right *) Definition weqffun (X : UU) {Y Z : UU} (w : Y ≃ Z) : (X -> Y) ≃ (X -> Z) := weqonsecfibers _ _ (λ x, w). (** ** The map between section spaces (dependent products) defined by the map between the bases [ f : Y -> X ] *) (** *** General case *) Definition maponsec1l0 {X : UU} (P : X -> UU) (f : X -> X) (h : ∏ x, f x = x) : (∏ x, P x) -> (∏ x, P x) := λ s x, transportf P (h x) (s (f x)). Lemma maponsec1l1 {X : UU} (P : X -> UU) (x : X) (s : ∏ x, P x) : maponsec1l0 P (λ x, x) idpath s x = s x. Proof. intros. unfold maponsec1l0. apply idpath. Defined. Lemma maponsec1l2 {X : UU} (P : X -> UU) (f : X -> X) (h : ∏ x, f x = x) (s : ∏ x, P x) x : maponsec1l0 P f h s x = s x. Proof. intros. set (map := λ (ff : (∑ (f0 : X -> X), ∏ x, (f0 x) = x)), maponsec1l0 P (pr1 ff) (pr2 ff) s x). assert (is1 : iscontr (∑ (f0 : X -> X), ∏ x, (f0 x) = x)) by apply funextcontr. assert (e: (f,,h) = tpair (λ g, ∏ x, g x = x) (λ x, x) idpath) by (apply proofirrelevancecontr; assumption). apply (maponpaths map e). Defined. Theorem isweqmaponsec1 {X Y : UU} (P : Y -> UU) (f : X ≃ Y) : isweq (maponsec1 P f). Proof. intros. set (map := maponsec1 P f). set (invf := invmap f). set (e1 := homotweqinvweq f). set (e2 := homotinvweqweq f). set (im1 := λ (sx : ∏ x, P (f x)) y, sx (invf y)). set (im2 := λ (sy': ∏ y : Y, P (f (invf y))) y, transportf _ (homotweqinvweq f y) (sy' y)). set (invmapp := λ (sx : ∏ x, P (f x)), im2 (im1 sx)). assert (efg0 : ∏ (sx : (∏ x, P (f x))) x, (map (invmapp sx)) x = sx x). { intro. intro. unfold map. unfold invmapp. unfold im1. unfold im2. unfold maponsec1. simpl. fold invf. set (ee := e2 x). fold invf in ee. set (e3x := λ x0 : X, invmaponpathsweq f (invf (f x0)) x0 (homotweqinvweq f (f x0))). set (e3 := e3x x). assert (e4 : homotweqinvweq f (f x) = maponpaths f e3) by apply (pathsinv0 (pathsweq4 f (invf (f x)) x _)). assert (e5 : transportf P (homotweqinvweq f (f x)) (sx (invf (f x))) = transportf P (maponpaths f e3) (sx (invf (f x)))) by apply (maponpaths (λ e40, (transportf P e40 (sx (invf (f x))))) e4). assert (e6 : transportf P (maponpaths f e3) (sx (invf (f x))) = transportf (λ x, P (f x)) e3 (sx (invf (f x)))) by apply (pathsinv0 (functtransportf f P e3 (sx (invf (f x))))). set (ff := λ x, invf (f x)). assert (e7 : transportf (λ x, P (f x)) e3 (sx (invf (f x))) = sx x) by apply (maponsec1l2 (λ x, P (f x)) ff e3x sx x). apply (pathscomp0 (pathscomp0 e5 e6) e7). } assert (efg : ∏ sx : (∏ x, P (f x)), map (invmapp sx) = sx) by (intro; apply (funextsec _ _ _ (efg0 sx))). assert (egf0 : ∏ sy : (∏ y : Y, P y), ∏ y : Y, (invmapp (map sy)) y = sy y). { intros. unfold invmapp. unfold map. unfold im1. unfold im2. unfold maponsec1. set (ff := λ y : Y, f (invf y)). fold invf. apply (maponsec1l2 P ff (homotweqinvweq f) sy y). } assert (egf : ∏ sy : (∏ y : Y, P y), invmapp (map sy) = sy) by (intro; apply (funextsec _ _ _ (egf0 sy))). apply (isweq_iso map invmapp egf efg). Defined. Definition weqonsecbase {X Y : UU} (P : Y -> UU) (f : X ≃ Y) : (∏ y : Y, P y) ≃ (∏ x, P (f x)) := make_weq _ (isweqmaponsec1 P f). (** *** Composition of functions with a weak equivalence on the left *) Definition weqbfun {X Y : UU} (Z : UU) (w : X ≃ Y) : (Y -> Z) ≃ (X -> Z) := weqonsecbase _ w. (** ** Sections of families over an empty type and over coproducts *) (** *** General case *) Definition iscontrsecoverempty (P : empty -> UU) : iscontr (∏ x : empty, P x). Proof. split with (λ x : empty, fromempty x). intro t. apply funextsec. intro t0. induction t0. Defined. Definition iscontrsecoverempty2 {X : UU} (P : X -> UU) (is : neg X) : iscontr (∏ x, P x). Proof. intros. set (w := weqtoempty is). set (w' := weqonsecbase P (invweq w)). apply (iscontrweqb w' (iscontrsecoverempty _)). Defined. Definition secovercoprodtoprod {X Y : UU} (P : X ⨿ Y -> UU) (a : ∏ xy : X ⨿ Y, P xy) : (∏ x, P (ii1 x)) × (∏ y : Y, P (ii2 y)) := make_dirprod (λ x, a (ii1 x)) (λ y : Y, a (ii2 y)). Definition prodtosecovercoprod {X Y : UU} (P : X ⨿ Y -> UU) (a : (∏ x, P (ii1 x)) × (∏ y : Y, P (ii2 y))) : ∏ xy : X ⨿ Y, P xy. Proof. intros. induction xy as [ x | y ]. - exact (pr1 a x). - exact (pr2 a y). Defined. Definition weqsecovercoprodtoprod {X Y : UU} (P : X ⨿ Y -> UU) : (∏ xy : X ⨿ Y, P xy) ≃ (∏ x, P (ii1 x)) × (∏ y : Y, P (ii2 y)). Proof. intros. use (weq_iso (secovercoprodtoprod P) (prodtosecovercoprod P)). - intro. apply funextsec. intro t. induction t; reflexivity. - intro a. apply pathsdirprod. + apply funextsec. apply homotrefl. + apply funextsec. apply homotrefl. Defined. (** *** Functions from the empty type *) Theorem iscontrfunfromempty (X : UU) : iscontr (empty -> X). Proof. split with fromempty. intro t. apply funextfun. intro x. induction x. Defined. Theorem iscontrfunfromempty2 (X : UU) {Y : UU} (is : neg Y) : iscontr (Y -> X). Proof. intros. set (w := weqtoempty is). set (w' := weqbfun X (invweq w)). apply (iscontrweqb w' (iscontrfunfromempty X)). Defined. (** *** Functions from a coproduct *) Definition funfromcoprodtoprod {X Y Z : UU} (f : X ⨿ Y -> Z) : (X -> Z) × (Y -> Z) := make_dirprod (λ x, f (ii1 x)) (λ y : Y, f (ii2 y)). Definition prodtofunfromcoprod {X Y Z : UU} (fg : (X -> Z) × (Y -> Z)) : X ⨿ Y -> Z := sumofmaps (pr1 fg) (pr2 fg). Theorem weqfunfromcoprodtoprod (X Y Z : UU) : (X ⨿ Y -> Z) ≃ ((X -> Z) × (Y -> Z)). Proof. intros. simple refine ( make_weq _ (isweq_iso (@funfromcoprodtoprod X Y Z) (@prodtofunfromcoprod X Y Z) _ _)). - intro a. apply funextfun; intro xy. induction xy as [ x | y ]; apply idpath. - intro a. induction a as [fx fy]. apply idpath. Defined. (** ** Sections of families over contractible types and over [ total2 ] (over dependent sums) *) (** *** General case *) Definition tosecoverunit (P : unit -> UU) (p : P tt) : ∏ t : unit, P t. Proof. intros. induction t. apply p. Defined. Definition weqsecoverunit (P : unit -> UU) : (∏ t : unit, P t) ≃ (P tt). Proof. set (f := λ a : ∏ t : unit, P t, a tt). set (g := tosecoverunit P). split with f. assert (egf : ∏ a, g (f a) = a). { intro. apply funextsec. intro t. induction t. apply idpath. } assert (efg : ∏ a, f (g a) = a) by (intros; apply idpath). apply (isweq_iso _ _ egf efg). Defined. Definition weqsecovercontr {X : UU} (P : X -> UU) (is : iscontr X) : (∏ x, P x) ≃ (P (pr1 is)). Proof. intros. set (w1 := weqonsecbase P (wequnittocontr is)). apply (weqcomp w1 (weqsecoverunit _)). Defined. Definition tosecovertotal2 {X : UU} (P : X -> UU) (Q : (∑ x, P x) -> UU) (a : ∏ x, ∏ p : P x, Q (x ,, p)) : ∏ xp : (∑ x, P x), Q xp. Proof. intros. induction xp as [ x p ]. apply (a x p). Defined. (** General equivalence between curried and uncurried function types *) Definition weqsecovertotal2 {X : UU} (P : X -> UU) (Q : (∑ x, P x) -> UU) : (∏ xp : (∑ x, P x), Q xp) ≃ (∏ x, ∏ p : P x, Q (x,, p)). Proof. intros. set (f := λ a : ∏ xp : (∑ x, P x), Q xp, λ x, λ p : P x, a (x,, p)). set (g := tosecovertotal2 P Q). split with f. assert (egf : ∏ a, g (f a) = a). { intro. apply funextsec. intro xp. induction xp as [ x p ]. apply idpath. } assert (efg : ∏ a, f (g a) = a). { intro. apply funextsec. intro x. apply funextsec. intro p. apply idpath. } apply (isweq_iso _ _ egf efg). Defined. (** *** Functions from [ unit ] and from contractible types *) Definition weqfunfromunit (X : UU) : (unit -> X) ≃ X := weqsecoverunit _. Definition weqfunfromcontr {X : UU} (Y : UU) (is : iscontr X) : (X -> Y) ≃ Y := weqsecovercontr _ is. (** *** Functions from [ total2 ] *) Definition weqfunfromtotal2 {X : UU} (P : X -> UU) (Y : UU) : ((∑ x, P x) -> Y) ≃ (∏ x, P x -> Y) := weqsecovertotal2 P _. (** *** Functions from direct product *) Definition weqfunfromdirprod (X X' Y : UU) : (X × X' -> Y) ≃ (∏ x, X' -> Y) := weqsecovertotal2 _ _. (** ** Theorem saying that if each member of a family is of h-level n then the space of sections of the family is of h-level n. *) (** *** General case *) Theorem impred (n : nat) {T : UU} (P : T -> UU) : (∏ t : T, isofhlevel n (P t)) -> (isofhlevel n (∏ t : T, P t)). Proof. revert T P. induction n as [ | n IHn ]. - intros T P X. apply (funcontr P X). - intros T P X. unfold isofhlevel in X. unfold isofhlevel. intros x x'. assert (is : ∏ t : T, isofhlevel n (x t = x' t)) by (intro; apply (X t (x t) (x' t))). assert (is2 : isofhlevel n (∏ t : T, x t = x' t)) by apply (IHn _ (λ t0 : T, x t0 = x' t0) is). set (u := toforallpaths P x x'). assert (is3: isweq u) by apply isweqtoforallpaths. set (v:= invmap (make_weq u is3)). assert (is4: isweq v) by apply isweqinvmap. apply (isofhlevelweqf n (make_weq v is4)). assumption. Defined. Corollary impred_iscontr {T : UU} (P : T -> UU) : (∏ t : T, iscontr (P t)) -> (iscontr (∏ t : T, P t)). Proof. intros. apply (impred 0). assumption. Defined. Corollary impred_isaprop {T : UU} (P : T -> UU) : (∏ t : T, isaprop (P t)) -> (isaprop (∏ t : T, P t)). Proof. apply impred. Defined. Corollary impred_isaset {T : UU} (P : T -> UU) : (∏ t : T, isaset (P t)) -> (isaset (∏ t : T, P t)). Proof. intros. apply (impred 2). assumption. Defined. Corollary impredtwice (n : nat) {T T' : UU} (P : T -> T' -> UU) : (∏ (t : T) (t': T'), isofhlevel n (P t t')) -> (isofhlevel n (∏ (t : T) (t': T'), P t t')). Proof. intros X. assert (is1 : ∏ t : T, isofhlevel n (∏ t': T', P t t')) by (intro; apply (impred n _ (X t))). apply (impred n _ is1). Defined. Corollary impredfun (n : nat) (X Y : UU) (is : isofhlevel n Y) : isofhlevel n (X -> Y). Proof. intros. apply (impred n (λ x , Y) (λ x, is)). Defined. Theorem impredtech1 (n : nat) (X Y : UU) : (X -> isofhlevel n Y) -> isofhlevel n (X -> Y). Proof. revert X Y. induction n as [ | n IHn ]. intros X Y X0. simpl. split with (λ x, pr1 (X0 x)). - intro t. assert (s1 : ∏ x, t x = pr1 (X0 x)) by (intro; apply proofirrelevancecontr; apply (X0 x)). apply funextsec. assumption. - intros X Y X0. simpl. assert (X1 : X -> isofhlevel (S n) (X -> Y)) by (intro X1; apply impred; assumption). intros x x'. assert (s1 : isofhlevel n (∏ xx, x xx = x' xx)) by (apply impred; intro t; apply (X0 t)). assert (w : (∏ xx, x xx = x' xx) ≃ (x = x')) by apply (weqfunextsec _ x x'). apply (isofhlevelweqf n w s1). Defined. (** *** Functions to a contractible type *) Theorem iscontrfuntounit (X : UU) : iscontr (X -> unit). Proof. split with (λ x, tt). intro f. apply funextfun. intro x. induction (f x). apply idpath. Defined. Theorem iscontrfuntocontr (X : UU) {Y : UU} (is : iscontr Y) : iscontr (X -> Y). Proof. set (w := weqcontrtounit is). set (w' := weqffun X w). apply (iscontrweqb w' (iscontrfuntounit X)). Defined. (** *** Functions to a proposition *) Lemma isapropimpl (X Y : UU) (isy : isaprop Y) : isaprop (X -> Y). Proof. apply impred. intro. assumption. Defined. (** *** Functions to an empty type (generalization of [ isapropneg ]) *) Theorem isapropneg2 (X : UU) {Y : UU} (is : neg Y) : isaprop (X -> Y). Proof. intros. apply impred. intro. apply (isapropifnegtrue is). Defined. (** ** Theorems saying that [ iscontr T ], [ isweq f ] etc. are of h-level 1 *) Theorem iscontriscontr {X : UU} (is : iscontr X) : iscontr (iscontr X). Proof. assert (is0 : ∏ (x x' : X), x = x') by (apply proofirrelevancecontr; assumption). assert (is1 : ∏ cntr : X, iscontr (∏ x, x = cntr)). { intro. assert (is2 : ∏ x, iscontr (x = cntr)). { assert (is2 : isaprop X) by (apply isapropifcontr; assumption). unfold isaprop in is2. unfold isofhlevel in is2. intro x. apply (is2 x cntr). } apply funcontr. assumption. } set (f := @pr1 X (λ cntr : X, ∏ x, x = cntr)). assert (X1 : isweq f) by (apply isweqpr1; assumption). change (∑ (cntr : X), ∏ x, x = cntr) with (iscontr X) in X1. apply (iscontrweqb (make_weq f X1)). assumption. Defined. Theorem isapropiscontr (T : UU) : isaprop (iscontr T). Proof. intros. unfold isaprop. unfold isofhlevel. intros x x'. assert (is : iscontr(iscontr T)). apply iscontriscontr. apply x. assert (is2 : isaprop (iscontr T)) by apply (isapropifcontr is). apply (is2 x x'). Defined. Theorem isapropisweq {X Y : UU} (f : X -> Y) : isaprop (isweq f). Proof. intros. unfold isweq. apply (impred (S O) (λ y : Y, iscontr (hfiber f y)) (λ y : Y, isapropiscontr (hfiber f y))). Defined. Theorem isapropisisolated (X : UU) (x : X) : isaprop (isisolated X x). (* uses funextemptyAxiom *) Proof. intros. apply isofhlevelsn. intro is. apply impred. intro x'. apply (isapropdec _ (isaproppathsfromisolated X x is x')). Defined. Theorem isapropisdeceq (X : UU) : isaprop (isdeceq X). (* uses funextemptyAxiom *) Proof. apply (isofhlevelsn 0). intro is. unfold isdeceq. apply impred. intro x. apply (isapropisisolated X x). Defined. Theorem isapropisofhlevel (n : nat) (X : UU) : isaprop (isofhlevel n X). Proof. revert X. induction n as [ | n IHn ]. - apply isapropiscontr. - intro X. apply impred. intros t. apply impred. intros t0. apply IHn. Defined. Corollary isapropisaprop (X : UU) : isaprop (isaprop X). Proof. intro. apply (isapropisofhlevel (S O)). Defined. Definition isapropisdecprop (X : UU) : isaprop (isdecprop X). Proof. intros. unfold isdecprop. apply (isofhlevelweqf 1 (weqdirprodcomm _ _)). apply isofhleveltotal2. - apply isapropisaprop. - intro i. apply isapropdec. assumption. Defined. Corollary isapropisaset (X : UU) : isaprop (isaset X). Proof. intro. apply (isapropisofhlevel (S (S O))). Defined. Theorem isapropisofhlevelf (n : nat) {X Y : UU} (f : X -> Y) : isaprop (isofhlevelf n f). Proof. intros. unfold isofhlevelf. apply impred. intro y. apply isapropisofhlevel. Defined. Definition isapropisincl {X Y : UU} (f : X -> Y) : isaprop (isofhlevelf 1 f) := isapropisofhlevelf 1 f. Lemma isaprop_isInjective {X Y : UU} (f : X -> Y) : isaprop (isInjective f). Proof. intros. unfold isInjective. apply impred; intro. apply impred; intro. apply isapropisweq. Defined. Lemma incl_injectivity {X Y : UU} (f : X -> Y) : isincl f ≃ isInjective f. Proof. intros. apply weqimplimpl. - apply isweqonpathsincl. - apply isinclweqonpaths. - apply isapropisincl. - apply isaprop_isInjective. Defined. (** ** Theorems saying that various [ pr1 ] maps are inclusions *) Theorem isinclpr1weq (X Y : UU) : isincl (pr1weq : X ≃ Y -> X -> Y). Proof. intros. refine (isinclpr1 _ _). intro f. apply isapropisweq. Defined. Corollary isinjpr1weq (X Y : UU) : isInjective (pr1weq : X ≃ Y -> X -> Y). Proof. intros. apply isweqonpathsincl. apply isinclpr1weq. Defined. Theorem isinclpr1isolated (T : UU) : isincl (pr1isolated T). Proof. intro. apply (isinclpr1 _ (λ t : T, isapropisisolated T t)). Defined. (** associativity of weqcomp **) Definition weqcomp_assoc {W X Y Z : UU} (f : W ≃ X) (g: X ≃ Y) (h : Y ≃ Z) : (h ∘ (g ∘ f) = (h ∘ g) ∘ f)%weq. Proof. intros. apply subtypePath. - intros p. apply isapropisweq. - simpl. apply idpath. Defined. Lemma eqweqmap_pathscomp0 {A B C : UU} (p : A = B) (q : B = C) : weqcomp (eqweqmap p) (eqweqmap q) = eqweqmap (pathscomp0 p q). Proof. induction p. induction q. apply pair_path_in2. apply isapropisweq. Defined. Lemma inv_idweq_is_idweq {A : UU} : idweq A = invweq (idweq A). Proof. apply pair_path_in2. apply isapropisweq. Defined. Lemma eqweqmap_pathsinv0 {A B : UU} (p : A = B) : eqweqmap (!p) = invweq (eqweqmap p). Proof. induction p. exact inv_idweq_is_idweq. Defined. (** ** Various weak equivalences between spaces of weak equivalences *) (** *** Composition with a weak quivalence is a weak equivalence on weak equivalences *) Theorem weqfweq (X : UU) {Y Z : UU} (w : Y ≃ Z) : (X ≃ Y) ≃ (X ≃ Z). Proof. intros. set (f := λ a : X ≃ Y, weqcomp a w). set (g := λ b : X ≃ Z, weqcomp b (invweq w)). split with f. assert (egf : ∏ a, g (f a) = a). { intro a. apply (invmaponpathsincl _ (isinclpr1weq _ _)). apply funextfun. intro x. apply (homotinvweqweq w (a x)). } assert (efg : ∏ b, f (g b) = b). { intro b. apply (invmaponpathsincl _ (isinclpr1weq _ _)). apply funextfun. intro x. apply (homotweqinvweq w (b x)). } apply (isweq_iso _ _ egf efg). Defined. Theorem weqbweq {X Y : UU} (Z : UU) (w : X ≃ Y) : (Y ≃ Z) ≃ (X ≃ Z). Proof. intros. set (f := λ a : Y ≃ Z, weqcomp w a). set (g := λ b : X ≃ Z, weqcomp (invweq w) b). split with f. assert (egf : ∏ a, g (f a) = a). { intro a. apply (invmaponpathsincl _ (isinclpr1weq _ _)). apply funextfun. intro y. apply (maponpaths a (homotweqinvweq w y)). } assert (efg : ∏ b, f (g b) = b). { intro b. apply (invmaponpathsincl _ (isinclpr1weq _ _)). apply funextfun. intro x. apply (maponpaths b (homotinvweqweq w x)). } apply (isweq_iso _ _ egf efg). Defined. Theorem weqweq {X Y : UU} (w: X ≃ Y) : (X ≃ X) ≃ (Y ≃ Y). Proof. intros. intermediate_weq (X ≃ Y). - apply weqfweq. assumption. - apply invweq. apply weqbweq. assumption. Defined. (** *** Invertion on weak equivalences as a weak equivalence *) (** Comment : note that full form of [ funextfun ] is only used in the proof of this theorem in the form of [ isapropisweq ]. The rest of the proof can be completed using eta-conversion. *) Theorem weqinvweq (X Y : UU) : (X ≃ Y) ≃ (Y ≃ X). Proof. intros. apply (weq_iso invweq invweq). - intro. apply (invmaponpathsincl _ (isinclpr1weq _ _)). apply funextfun. apply homotrefl. - intro. apply (invmaponpathsincl _ (isinclpr1weq _ _)). apply funextfun. apply homotrefl. Defined. (** ** h-levels of spaces of weak equivalences *) (** *** Weak equivalences to and from types of h-level (S n) *) Theorem isofhlevelsnweqtohlevelsn (n : nat) (X Y : UU) (is : isofhlevel (S n) Y) : isofhlevel (S n) (X ≃ Y). Proof. intros. apply (isofhlevelsninclb n _ (isinclpr1weq _ _)). apply impred. intro. exact is. Defined. Theorem isofhlevelsnweqfromhlevelsn (n : nat) (X Y : UU) (is : isofhlevel (S n) Y) : isofhlevel (S n) (Y ≃ X). Proof. intros. apply (isofhlevelweqf (S n) (weqinvweq X Y)). apply isofhlevelsnweqtohlevelsn. exact is. Defined. (** *** Weak equivalences to and from contractible types *) Theorem isapropweqtocontr (X : UU) {Y : UU} (is : iscontr Y) : isaprop (X ≃ Y). Proof. intros. apply (isofhlevelsnweqtohlevelsn 0 _ _ (isapropifcontr is)). Defined. Theorem isapropweqfromcontr (X : UU) {Y : UU} (is : iscontr Y) : isaprop (Y ≃ X). Proof. intros. apply (isofhlevelsnweqfromhlevelsn 0 X _ (isapropifcontr is)). Defined. (** *** Weak equivalences to and from propositions *) Theorem isapropweqtoprop (X Y : UU) (is : isaprop Y) : isaprop (X ≃ Y). Proof. intros. apply (isofhlevelsnweqtohlevelsn 0 _ _ is). Defined. Theorem isapropweqfromprop (X Y : UU) (is : isaprop Y) : isaprop (Y ≃ X). Proof. intros. apply (isofhlevelsnweqfromhlevelsn 0 X _ is). Defined. (** *** Weak equivalences to and from sets *) Theorem isasetweqtoset (X Y : UU) (is : isaset Y) : isaset (X ≃ Y). Proof. intros. apply (isofhlevelsnweqtohlevelsn 1 _ _ is). Defined. Theorem isasetweqfromset (X Y : UU) (is : isaset Y) : isaset (Y ≃ X). Proof. intros. apply (isofhlevelsnweqfromhlevelsn 1 X _ is). Defined. (** *** Weak equivalences to an empty type *) Theorem isapropweqtoempty (X : UU) : isaprop (X ≃ empty). Proof. intro. apply (isofhlevelsnweqtohlevelsn 0 _ _ (isapropempty)). Defined. Theorem isapropweqtoempty2 (X : UU) {Y : UU} (is : neg Y) : isaprop (X ≃ Y). Proof. intros. apply (isofhlevelsnweqtohlevelsn 0 _ _ (isapropifnegtrue is)). Defined. (** *** Weak equivalences from an empty type *) Theorem isapropweqfromempty (X : UU) : isaprop (empty ≃ X). Proof. intro. apply (isofhlevelsnweqfromhlevelsn 0 X _ (isapropempty)). Defined. Theorem isapropweqfromempty2 (X : UU) {Y : UU} (is : neg Y) : isaprop (Y ≃ X). Proof. intros. apply (isofhlevelsnweqfromhlevelsn 0 X _ (isapropifnegtrue is)). Defined. (** *** Weak equivalences to and from [ unit ] *) Theorem isapropweqtounit (X : UU) : isaprop (X ≃ unit). Proof. intro. apply (isofhlevelsnweqtohlevelsn 0 _ _ (isapropunit)). Defined. Theorem isapropweqfromunit (X : UU) : isaprop (unit ≃ X). Proof. intros. apply (isofhlevelsnweqfromhlevelsn 0 X _ (isapropunit)). Defined. (** ** Weak auto-equivalences of a type with an isolated point *) Definition cutonweq {T : UU} t (is : isisolated T t) (w : T ≃ T) : isolated T × (compl T t ≃ compl T t). Proof. intros. split. - exists (w t). apply isisolatedweqf. assumption. - intermediate_weq (compl T (w t)). + apply weqoncompl. + apply weqtranspos0. * apply isisolatedweqf. assumption. * assumption. Defined. Definition invcutonweq {T : UU} (t : T) (is : isisolated T t) (t'w : isolated T × (compl T t ≃ compl T t)) : T ≃ T := weqcomp (weqrecomplf t t is is (pr2 t'w)) (weqtranspos t (pr1 (pr1 t'w)) is (pr2 (pr1 t'w))). Lemma pathsinvcuntonweqoft {T : UU} (t : T) (is : isisolated T t) (t'w : isolated T × (compl T t ≃ compl T t)) : invcutonweq t is t'w t = pr1 (pr1 t'w). Proof. intros. unfold invcutonweq. simpl. unfold recompl. unfold coprodf. unfold invmap. simpl. unfold invrecompl. induction (is t) as [ ett | nett ]. - apply pathsfuntransposoft1. - induction (nett (idpath _)). Defined. Definition weqcutonweq (T : UU) (t : T) (is : isisolated T t) : (T ≃ T) ≃ isolated T × (compl T t ≃ compl T t). Proof. intros. set (f := cutonweq t is). set (g := invcutonweq t is). apply (weq_iso f g). - intro w. Set Printing Coercions. idtac. apply (invmaponpathsincl _ (isinclpr1weq _ _)). apply funextfun; intro t'. simpl. unfold invmap; simpl. unfold coprodf, invrecompl. induction (is t') as [ ett' | nett' ]. + simpl. rewrite (pathsinv0 ett'). apply pathsfuntransposoft1. + unfold funtranspos0; simpl. induction (is (w t)) as [ etwt | netwt ]. * induction (is (w t')) as [ etwt' | netwt' ]. -- induction (negf (invmaponpathsincl w (isofhlevelfweq 1 w) t t') nett' (pathscomp0 (pathsinv0 etwt) etwt')). -- simpl. assert (newtt'' := netwt'). rewrite etwt in netwt'. apply (pathsfuntransposofnet1t2 t (w t) is _ (w t') newtt'' netwt'). * simpl. induction (is (w t')) as [ etwt' | netwt' ]. -- simpl. rewrite (pathsinv0 etwt'). apply (pathsfuntransposoft2 t (w t) is _). -- simpl. assert (ne : neg (w t = w t')) by apply (negf (invmaponpathsweq w _ _) nett'). apply (pathsfuntransposofnet1t2 t (w t) is _ (w t') netwt' ne). - intro xw. induction xw as [ x w ]. induction x as [ t' is' ]. simpl in w. apply pathsdirprod. + apply (invmaponpathsincl _ (isinclpr1isolated _)). simpl. unfold recompl, coprodf, invmap; simpl. unfold invrecompl. induction (is t) as [ ett | nett ]. * apply pathsfuntransposoft1. * induction (nett (idpath _)). + simpl. apply (invmaponpathsincl _ (isinclpr1weq _ _) _ _). apply funextfun. intro x. induction x as [ x netx ]. unfold g, invcutonweq; simpl. set (int := funtranspos (t,, is) (t',, is') (recompl T t (coprodf w (λ x0 :unit, x0) (invmap (weqrecompl T t is) t)))). assert (eee : int = t'). { unfold int. unfold recompl, coprodf, invmap; simpl. unfold invrecompl. induction (is t) as [ ett | nett ]. - apply pathsfuntransposoft1. - induction (nett (idpath _)). } assert (isint : isisolated _ int). { rewrite eee. apply is'. } apply (ishomotinclrecomplf _ _ isint (funtranspos0 _ _ _) _ _). simpl. change (recomplf int t isint (funtranspos0 int t is)) with (funtranspos (int,, isint) (t,, is)). assert (ee : (int,, isint) = (t',, is')). { apply (invmaponpathsincl _ (isinclpr1isolated _) _ _). simpl. apply eee. } rewrite ee. set (e := homottranspost2t1t1t2 t t' is is' (recompl T t (coprodf w (λ x0 : unit, x0) (invmap (weqrecompl T t is) x)))). simpl in e. rewrite e. unfold recompl, coprodf, invmap; simpl. unfold invrecompl. induction (is x) as [ etx | netx' ]. * induction (netx etx). * apply (maponpaths (@pr1 _ _)). apply (maponpaths w). apply (invmaponpathsincl _ (isinclpr1compl _ _) _ _). simpl. apply idpath. Unset Printing Coercions. Defined. (* Coprojections i.e. functions which are weakly equivalent to functions of the form ii1 : X -> X ⨿ Y Definition locsplit (X : UU) (Y : UU) (f : X -> Y) := ∏ y : Y, (hfiber f y) ⨿ (hfiber f y -> empty). Definition dnegimage (X : UU) (Y : UU) (f : X -> Y) := total2 Y (λ y : Y, dneg(hfiber f y)). Definition dnegimageincl (X Y : UU) (f : X -> Y) := pr1 Y (λ y : Y, dneg(hfiber f y)). Definition xtodnegimage (X : UU) (Y : UU) (f : X -> Y) : X -> dnegimage f := λ x, tpair (f x) ((todneg _) (make_hfiber f (f x) x (idpath (f x)))). Definition locsplitsec (X : UU) (Y : UU) (f : X -> Y) (ls : locsplit f) : dnegimage f -> X := λ u, match u with tpair y psi => match (ls y) with ii1 z => pr1 z| ii2 phi => fromempty (psi phi) end end. Definition locsplitsecissec (X Y : UU) (f : X -> Y) (ls : locsplit f) (u:dnegimage f) : paths (xtodnegimage f (locsplitsec f ls u)) u. Proof. intros. set (p := xtodnegimage f). set (s := locsplitsec f ls). assert (paths (pr1 (p (s u))) (pr1 u)). unfold p. unfold xtodnegimage. unfold s. unfold locsplitsec. simpl. induction u. set (lst := ls t). induction lst. simpl. apply (pr2 x0). induction (x y). assert (is : isofhlevelf (S O) (dnegimageincl f)). apply (isofhlevelfpr1 (S O) (λ y : Y, isapropdneg (hfiber f y))). assert (isw: isweq (maponpaths (dnegimageincl f) (p (s u)) u)). apply (isofhlevelfonpaths O _ is). apply (invmap _ isw X0). Defined. Definition negimage (X : UU) (Y : UU) (f : X -> Y) := total2 Y (λ y : Y, neg(hfiber f y)). Definition negimageincl (X Y : UU) (f : X -> Y) := pr1 Y (λ y : Y, neg(hfiber f y)). Definition imsum (X : UU) (Y : UU) (f : X -> Y) : (dnegimage f) ⨿ (negimage f) -> Y := λ u, match u with ii1 z => pr1 z| ii2 z => pr1 z end. *) (** some lemmas about weak equivalences *) Definition weqcompidl {X Y} (f:X ≃ Y) : weqcomp (idweq X) f = f. Proof. intros. apply (invmaponpathsincl _ (isinclpr1weq _ _)). apply funextsec; intro x; simpl. apply idpath. Defined. Definition weqcompidr {X Y} (f:X ≃ Y) : weqcomp f (idweq Y) = f. Proof. intros. apply (invmaponpathsincl _ (isinclpr1weq _ _)). apply funextsec; intro x; simpl. apply idpath. Defined. Definition weqcompinvl {X Y} (f:X ≃ Y) : weqcomp (invweq f) f = idweq Y. Proof. intros. apply (invmaponpathsincl _ (isinclpr1weq _ _)). apply funextsec; intro y; simpl. apply homotweqinvweq. Defined. Definition weqcompinvr {X Y} (f:X ≃ Y) : weqcomp f (invweq f) = idweq X. Proof. intros. apply (invmaponpathsincl _ (isinclpr1weq _ _)). apply funextsec; intro x; simpl. apply homotinvweqweq. Defined. Definition weqcompassoc {X Y Z W} (f:X ≃ Y) (g:Y ≃ Z) (h:Z ≃ W) : weqcomp (weqcomp f g) h = weqcomp f (weqcomp g h). Proof. intros. apply (invmaponpathsincl _ (isinclpr1weq _ _)). apply funextsec; intro x; simpl. apply idpath. Defined. Definition weqcompweql {X Y Z} (f:X ≃ Y) : isweq (λ g:Y ≃ Z, weqcomp f g). Proof. intros. simple refine (isweq_iso _ _ _ _). { intro h. exact (weqcomp (invweq f) h). } { intro g. simpl. rewrite <- weqcompassoc. rewrite weqcompinvl. apply weqcompidl. } { intro h. simpl. rewrite <- weqcompassoc. rewrite weqcompinvr. apply weqcompidl. } Defined. Definition weqcompweqr {X Y Z} (g:Y ≃ Z) : isweq (λ f:X ≃ Y, weqcomp f g). Proof. intros. simple refine (isweq_iso _ _ _ _). { intro h. exact (weqcomp h (invweq g)). } { intro f. simpl. rewrite weqcompassoc. rewrite weqcompinvr. apply weqcompidr. } { intro h. simpl. rewrite weqcompassoc. rewrite weqcompinvl. apply weqcompidr. } Defined. Definition weqcompinjr {X Y Z} {f f':X ≃ Y} (g:Y ≃ Z) : weqcomp f g = weqcomp f' g -> f = f'. Proof. apply (invmaponpathsincl _ (isinclweq _ _ _ (weqcompweqr g))). Defined. Definition weqcompinjl {X Y Z} (f:X ≃ Y) {g g':Y ≃ Z} : weqcomp f g = weqcomp f g' -> g = g'. Proof. apply (invmaponpathsincl _ (isinclweq _ _ _ (weqcompweql f))). Defined. Definition invweqcomp {X Y Z} (f:X ≃ Y) (g:Y ≃ Z) : invweq (weqcomp f g) = weqcomp (invweq g) (invweq f). Proof. intros. apply (weqcompinjr (weqcomp f g)). rewrite weqcompinvl. rewrite weqcompassoc. rewrite <- (weqcompassoc (invweq f)). rewrite weqcompinvl. rewrite weqcompidl. rewrite weqcompinvl. apply idpath. Defined. Definition invmapweqcomp {X Y Z} (f:X ≃ Y) (g:Y ≃ Z) : invmap (weqcomp f g) = weqcomp (invweq g) (invweq f). Proof. reflexivity. Defined. (* End of the file uu0d.v *)
(* Title: HOL/Auth/n_g2kAbsAfter_lemma_inv__59_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__59_on_rules imports n_g2kAbsAfter_lemma_on_inv__59 begin section{*All lemmas on causal relation between inv__59*} lemma lemma_inv__59_on_rules: assumes b1: "r \<in> rules N" and b2: "(f=inv__59 )" 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__59) 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__59) 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__59) 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__59) 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__59) 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__59) 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__59) 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__59) 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__59) 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__59) 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__59) 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__59) 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__59) 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__59) 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__59) 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__59) 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__59) 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__59) 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__59) 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__59) 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__59) 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__59) 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__59) 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__59) 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__59) 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__59) 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__59) 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__59) done } ultimately show "invHoldForRule s f r (invariants N)" by satx qed end
! { dg-do run } ! { dg-options "-fdump-tree-original" } program p implicit none type :: t1 integer, allocatable :: t(:) end type t1 type :: t2 type(t1), allocatable :: x1(:) end type t2 type(t2) :: var(10) integer :: i do i= 1, 10 allocate(var(i)%x1(100)) allocate(var(i)%x1(1)%t(100)) enddo open(unit = 37, file = "/dev/null", status = "old") call s(1) close(unit = 37) do i=1,10 deallocate(var(i)%x1) enddo contains subroutine s(counter) implicit none integer, intent(in) :: counter integer :: i, j, n do j=1, counter n = size( [ ( var(i)%x1 , i = 1, size(var) ) ] ) write(unit = 37, fmt = '(i5)') n enddo end subroutine end program p ! { dg-final { scan-tree-dump-times "__builtin_malloc" 4 "original" } } ! { dg-final { scan-tree-dump-times "__builtin_free" 4 "original" } }
rm(list = objects()) library(dplyr) library(data.table) # introducir la ubicacion donde se encuentren los archivos home_folder <- 'ubicacion' # introducir el nobre del archivo con el dataset dataset_file <- file.path(home_folder, 'nombre_archivo_dataset') # introducir el nombre del archivo del modelo model_file <- file.path(home_folder, 'nombre_archivo_modelo') # introducir el nombre del archivo de las variables features_file <- file.path(home_folder, 'nombre_archivo_variables') # cargamos las generic utilities que contienen la funcion DrawROCCurve # este script esta en GitHub source('generic_utilities.R') dt <- data.table::fread(dataset_file) model <- readRDS(model_file) features <- readRDS(features_file) dt <- datasets$dev # tests train test and dev obtenidos de la documentacion dt[, set := dplyr::case_when( YEAR_MONTH_DAY <= 20171130 ~ 'train', YEAR_MONTH_DAY >= 20171201 & YEAR_MONTH_DAY <= 20180131 ~ 'dev', YEAR_MONTH_DAY >= 20180201 ~ 'test' )] # hay que añadir la columna train porque se guardo en los nobmres de variables pero no tiene incidencia sobre la performance dt[, train := 1] # nos aseguramos de que las variables a usar estén en formato numerico dt[, (features) := lapply(.SD, as.numeric), .SDcols = features] mtx <- as.matrix(dt[, features, with = FALSE]) target <- dt[, TARGET_BINARY_TARG] xgb_matrix <- xgboost::xgb.DMatrix(mtx, label = target) predictions <- predict(model, xgb_matrix) %T>% testthat::expect_length(nrow(dt)) output <- data.table::data.table( set = dt[, set], target = dt[, TARGET_BINARY_TARG], score = predictions ) DrawROCCurve(validationSet = output[set == 'train'], target = 'target', scores = 'score', title = 'Train Set') DrawROCCurve(validationSet = output[set == 'dev'], target = 'target', scores = 'score', title = 'Dev Set') DrawROCCurve(validationSet = output[set == 'test'], target = 'target', scores = 'score', title = 'Test Set')
# Test methods for reduced infinite variables @testset "Reduced Variable" begin # initialize model and references m = InfiniteModel() @infinite_parameter(m, 1 <= par1 <= 2) @infinite_parameter(m, 1 <= par2 <= 2) @infinite_variable(m, 0 <= inf1(par1, par2) <= 1, Int) @infinite_variable(m, inf2(par1, par2) == 1, Bin, start = 0) index = m.next_var_index + 1 rvref1 = ReducedInfiniteVariableRef(m, index) m.reduced_info[index] = ReducedInfiniteInfo(inf1, Dict(1 => 1)) rvref2 = ReducedInfiniteVariableRef(m, index + 1) m.reduced_info[index + 1] = ReducedInfiniteInfo(inf2, Dict(2 => 1)) # test _reduced_info @testset "_reduced_info" begin @test InfiniteOpt._reduced_info(rvref1).infinite_variable_ref == inf1 @test InfiniteOpt._reduced_info(rvref2).infinite_variable_ref == inf2 @test InfiniteOpt._reduced_info(rvref1).eval_supports == Dict(1 => 1) @test InfiniteOpt._reduced_info(rvref2).eval_supports == Dict(2 => 1) end # test infinite_variable_ref @testset "infinite_variable_ref" begin @test infinite_variable_ref(rvref1) == inf1 @test infinite_variable_ref(rvref2) == inf2 end # test eval_supports @testset "eval_supports" begin @test eval_supports(rvref1) == Dict(1 => 1) @test eval_supports(rvref2) == Dict(2 => 1) end # test name @testset "JuMP.name" begin @test name(rvref1) == "inf1(1, par2)" @test name(rvref2) == "inf2(par1, 1)" end # parameter_refs (reduced infinite variable) @testset "parameter_refs (reduced infinite)" begin # test the references @test parameter_refs(rvref1) == (par2, ) @test parameter_refs(rvref2) == (par1, ) end # has_lower_bound @testset "JuMP.has_lower_bound" begin @test has_lower_bound(rvref1) @test !has_lower_bound(rvref2) end # lower_bound @testset "JuMP.lower_bound" begin @test lower_bound(rvref1) == 0 @test_throws ErrorException lower_bound(rvref2) end # _lower_bound_index @testset "JuMP._lower_bound_index" begin @test JuMP._lower_bound_index(rvref1) == JuMP._lower_bound_index(inf1) @test_throws ErrorException JuMP._lower_bound_index(rvref2) end # LowerBoundRef @testset "JuMP.LowerBoundRef" begin @test LowerBoundRef(rvref1) == LowerBoundRef(inf1) @test_throws ErrorException LowerBoundRef(rvref2) end # has_upper_bound @testset "JuMP.has_upper_bound" begin @test has_upper_bound(rvref1) @test !has_upper_bound(rvref2) end # upper_bound @testset "JuMP.upper_bound" begin @test upper_bound(rvref1) == 1 @test_throws ErrorException upper_bound(rvref2) end # _upper_bound_index @testset "JuMP._upper_bound_index" begin @test JuMP._upper_bound_index(rvref1) == JuMP._upper_bound_index(inf1) @test_throws ErrorException JuMP._upper_bound_index(rvref2) end # UpperBoundRef @testset "JuMP.UpperBoundRef" begin @test UpperBoundRef(rvref1) == UpperBoundRef(inf1) @test_throws ErrorException UpperBoundRef(rvref2) end # is_fixed @testset "JuMP.is_fixed" begin @test is_fixed(rvref2) @test !is_fixed(rvref1) end # fix_value @testset "JuMP.fix_value" begin @test fix_value(rvref2) == 1 @test_throws ErrorException fix_value(rvref1) end # _fix_index @testset "JuMP._fix_index" begin @test JuMP._fix_index(rvref2) == JuMP._fix_index(inf2) @test_throws ErrorException JuMP._fix_index(rvref1) end # FixRef @testset "JuMP.FixRef" begin @test FixRef(rvref2) == FixRef(inf2) @test_throws ErrorException FixRef(rvref1) end # start_value @testset "JuMP.start_value" begin @test start_value(rvref2) == 0 end # is_binary @testset "JuMP.is_binary" begin @test is_binary(rvref2) @test !is_binary(rvref1) end # _binary_index @testset "JuMP._binary_index" begin @test JuMP._binary_index(rvref2) == JuMP._binary_index(inf2) @test_throws ErrorException JuMP._binary_index(rvref1) end # BinaryRef @testset "JuMP.BinaryRef" begin @test BinaryRef(rvref2) == BinaryRef(inf2) @test_throws ErrorException BinaryRef(rvref1) end # is_integer @testset "JuMP.is_integer" begin @test is_integer(rvref1) @test !is_integer(rvref2) end # _integer_index @testset "JuMP._integer_index" begin @test JuMP._integer_index(rvref1) == JuMP._integer_index(inf1) @test_throws ErrorException JuMP._integer_index(rvref2) end # IntegerRef @testset "JuMP.IntegerRef" begin @test IntegerRef(rvref1) == IntegerRef(inf1) @test_throws ErrorException IntegerRef(rvref2) end # used_by_constraint @testset "used_by_constraint" begin # test not used @test !used_by_constraint(rvref1) # prepare use case m.reduced_to_constrs[JuMP.index(rvref1)] = [1] # test used @test used_by_constraint(rvref1) end # used_by_measure @testset "used_by_measure" begin # test not used @test !used_by_measure(rvref1) # prepare use case m.reduced_to_meas[JuMP.index(rvref1)] = [1] # test used @test used_by_measure(rvref1) end # test is_valid @testset "JuMP.is_valid" begin @test is_valid(m, rvref1) @test is_valid(m, rvref2) @test !is_valid(m, ReducedInfiniteVariableRef(m, 100)) end end
Hand screened. Unisex. Grey. Tri color. Each blend unique. Variations. Heather military green and blackberry poly/cotton blend. Glow in the dark ink. Large Small Medium 2XLarge - $23.00 XLarge 3XLarge - $23.00 Small Heather military green glow Medium Heather military green glow Large Heather military green glow XLarge Heather military green glow 2XLarge Heather military green glow - $23.00 3XLarge Heather military green glow - $23.00 Small Blackberry glow Medium Blackberry glow Large Blackberry glow XLarge Blackberry glow 2XLarge Blackberry glow - $23.00 3XLarge Blackberry glow - $23.00 Small black glow Medium black glow Large black glow XLarge black glow 2Xlarge black glow - $23.00 3XLarge black glow - $23.00 Small black tri color Medium black tri color Large black tri color XLarge black tri color 2XLarge black tri color - $23.00 3XLarge black tri color - $23.00 4Xlarge black tri color - $23.00 5Xlarge black tri color - $23.00 Kram 6oz 100% cotton XL color charcoal.
%!TEX root=../main.tex \chapter{Simulation Results} \label{chap:simulation} \minitoc In this chapter the numerical discrete dynamic gradient damage model summarized in \cref{algo:implicit,algo:explicit} is applied to investigate numerous academic or real-world fracture problems. Since this part constitutes an essential part of the present work, the organization of these simulation results is described as follows: \begin{itemize} \item \textbf{Ordering}: the fracture problems considered in this chapter are ordered in terms of \emph{computational complexity}. The FEniCS implementation is used first to analyze some academic problems under the small displacement hypothesis: the crack nucleation problem in a one-dimensional bar (\cref{sec:1d}), the 2-d scalar antiplane tearing problem (\cref{sec:antiplane}) and the 2-d plane crack kinking problem (\cref{sec:kinking}). Afterwards, real-world dynamic fracture problems are considered in the EPX software environment: the 2-d plane crack branching problem (\cref{sec:branching}), the Kalthoff experiment (\cref{sec:kalthoff}) and the crack arrest problem (\cref{sec:gregoire}). Application to concrete structures are considered at the end: the Brazilian test on concrete cylinders (\cref{sec:brazilian}), the dynamic fracture problem of a L-shaped concrete specimen (\cref{sec:L-specimen}) and the CEA impact test on beams (\cref{sec:beam}). If one focuses on different phases of crack evolution, the following diagram can be obtained. \cref{sec:brazilian,sec:L-specimen,sec:beam} constitute an application of the dynamic gradient damage model to real concrete structures and are not listed in the diagram. \begin{center} \begin{tabular}{ccccccc} Nucleation &$\to$& Propagation &$\to$& Kinking \& Branching &$\to$& Arrest \\ \cref{sec:1d} && \cref{sec:antiplane} && \cref{sec:kinking,sec:branching,sec:kalthoff} && \cref{sec:gregoire} \end{tabular} \end{center} \item \textbf{Objectives}: using the classification given in \cref{sec:scope}, the scope of these simulations is to carry out an investigation of several damage constitutive laws and tension-compression asymmetry formulations (link with phase-field approaches represented by $\alpha\leftrightarrow\phi$), to provide a better understanding of gradient-damage modeling of fracture $\nabla\alpha\to\Gamma$) and to compare the simulation results with the experimental data (simulation validation). The precise objectives and the thematic subjects covered will be as usual recalled at the beginning of each section. \end{itemize} Contrary to previous chapters, a conclusion is provided at the end of each numerical simulation. According to the definition of the thematic subjects given in \cref{sec:scope}, these numerical simulations can be classified in \cref{tab:summsim}. \begin{table}[htbp] \centering \caption{Thematic subjects covered in the numerical simulations of this chapter} \label{tab:summsim} \begin{tabular}{cccc} \toprule & $\alpha\leftrightarrow\phi$ & $\nabla\alpha\to\Gamma$ & Experimental validation \\ \midrule Numerics & \cref{sec:branching,sec:kalthoff,sec:brazilian} & \cref{sec:1d,sec:antiplane,sec:kinking,sec:branching,sec:kalthoff,sec:brazilian,sec:L-specimen} & \cref{sec:branching,sec:kalthoff,sec:gregoire,sec:brazilian,sec:L-specimen,sec:beam} \\ \bottomrule \end{tabular} \end{table} \section{Crack Nucleation in a Bar Under Impact} \label{sec:1d} This section is devoted to a numerical analysis of a one-dimensional bar under impact loading conditions. The focus is on crack nucleation in dynamics using the gradient damage model. In the absence of an initial crack in the problem setting, the classical Griffith's theory of fracture is incapable of predicting material and structural failure. Hence here the simulation results will be compared to local strain-softening models (conventional damage models for instance). The objective is to illustrate the crack nucleation criterion in gradient damage models and the role played by the internal length in such process. The thematic subjects covered here are thus summarized in \cref{tab:summbar}. \begin{table}[htbp] \centering \caption{Thematic subjects covered in this section} \label{tab:summbar} \begin{tabular}{ccccc} \toprule & Going dynamical & $\alpha\leftrightarrow\phi$ & $\nabla\alpha\to\Gamma$ & Experimental validation \\ \midrule Theoretics & & & & \\ Numerics & & & \rightthumbsup & \\ \bottomrule \end{tabular} \end{table} \subsection{Analytical solutions for local strain-softening materials} This problem is initially considered by \cite{Bazant:1985aa} for an elastic strain-softening material. The one-dimensional initially stationary bar occupying the interval $[-L,L]$ is subject at both ends to a tensile shock $\vec{U}_t=\pm vt\,\vec{e}_1$ where $v$ measures the intensity, see \cref{fig:elassoftening}. Due to the jump condition, the strain waves propagate with an initial value of $\varepsilon=v/c$ at the wave speed $c=\sqrt{E/\rho}$. At $t=\frac{L}{c}$ when the two waves meet at the center, the strain at $x=0$ is doubled $\varepsilon=2v/c$ and continues to propagate to the rest part of the bar. We will only focus on the dynamic evolution in the time interval $[0,\frac{2L}{c}]$ before the waves travel the whole length. In \cite{Bazant:1985aa}, the material strain-softening condition is satisfied at a given critical strain level $\varepsilon_\mc$. If this criterion is never met, the analytical solution corresponds to a purely elastodynamic problem, which is given by \begin{align*} u &= -v\inp{t-\frac{x+L}{c}}+v\inp{t+\frac{x-L}{c}}\,, \\ \varepsilon &= \frac{v}{c}\mH\left(t-\frac{x+L}{c}\right)+\frac{v}{c}\mH\left(t+\frac{x-L}{c}\right)\,, \end{align*} where $\inp{x}=(\abs{x}+x)/2$ and $\mH$ denotes the Heaviside step function. The strain field evolution is illustrated in \cref{fig:elassoftening}(a). \begin{figure}[htbp] \centering \includegraphics[width=\textwidth]{elassoftening.pdf} \caption{Strain field before and after the wave crossing at $t=\frac{L}{c}$ for (a) the elastodynamic model (or if the strain-softening criterion $\varepsilon_\mc$ is never met) and (b) the local strain-softening model if $\varepsilon_\mc$ is met at $t=\frac{L}{c}$} \label{fig:elassoftening} \end{figure} Otherwise, two cases could be separately discussed concerning the intensity of the impact velocity $v$ and the strain-softening criterion $\varepsilon_\mc$: \begin{enumerate} \item If $v$ is sufficiently high such that at $t=0$ the strain-softening criterion is met, \emph{i.e.} $\frac{v}{c}>\varepsilon_\mc$, then fracture takes place immediately at $t=0$ when the impact is applied. The impacted ends $x=\pm L$ are broken and the rest part of the bar remains stationary. \item If the strain-softening criterion $\varepsilon_\mc$ is satisfied when the two tensile waves arrive at the center at $t=\frac{L}{c}$, \emph{i.e.} $\frac{2v}{c}>\varepsilon_\mc$ but $\frac{v}{c}<\varepsilon_\mc$, then according to \cite{Bazant:1985aa}, the analytical solution becomes \begin{equation} \label{eq:elaslocal} \begin{aligned} u &= -v\inp{t-\frac{x+L}{c}}-v\inp{t-\frac{L-x}{c}}\,, \\ \varepsilon &= \frac{v}{c}\mH\left(t-\frac{x+L}{c}\right)-\frac{v}{c}\mH\left(t-\frac{L-x}{c}\right)+4v\inp{t-\frac{L}{c}}\delta_0\,, \end{aligned} \end{equation} which is applicable for $x\leq 0$. For $x>0$ a symmetric solution applies. The strain field before and after the wave-crossing is illustrated in \cref{fig:elassoftening}(b). At $t=\frac{L}{c}$ the bar breaks instantaneously at the center. For $t\geq\frac{L}{c}$, the displacement develops at the center a discontinuity of magnitude $4v\inp{t-\frac{L}{c}}$. Hence a Dirac distribution is present in the strain field expression. \end{enumerate} Several remarks can be given concerning the physical deficiencies of local strain-softening models in this particular dynamic problem: \begin{itemize} \item The ultimate fracture takes place instantaneously when the strain-softening criterion is satisfied. The structural failure mechanism is size-independent. \item Fracture takes place instantaneously with a vanishing energy dissipation, consequently spurious mesh dependency is observed for finite element solutions, see our discussions on this point in \cref{sec:twointerpretations}. It can be observed that \eqref{eq:elaslocal} corresponds to the elastodynamic solution of the bar initially broken at $x=0$, which implies total mechanical energy conservation and no additional energy dissipation when fracture happens at $t=\frac{L}{c}$. \end{itemize} As we shall see in the sequel, the gradient-damage approach of fracture permits a better modeling of crack nucleation, via the introduction of a length scale. \subsection{Gradient-damage modeling} The dynamic gradient damage model outlined in \cref{def:dynagraddama} is applied for this particular one-dimensional problem. Symmetry is taken into account and only the interval $\Omega=[0,L]$ is modeled. The displacement at $x=0$ is blocked due to symmetry. The explicit time-stepping described by \cref{algo:explicit} is used in the FEniCS implementation, see \cite{LiMaurini:2015}. The Lagrangian involved in the generalized space-time action integral \eqref{eq:actionG} reads \[ \mathcal{L}(u_t,\dot{u}_t,\alpha_t)=\int_\Omega\left(\frac{1}{2}\mathsf{a}(\alpha_t)Eu_t'^2+w(\alpha_t)+w_1\eta^2\alpha_t'^2-\frac{1}{2}\rho\dot{u}_t^2\right)\D{x}. \] A rescaling of the displacement by $u_\mc$ and a normalization of the space/time scales is performed to obtain a non-dimensional problem. Specifically, displacement is scaled by a factor of $u_\mc=\sigma_\mc L/E$ where $\sigma_\mc$ corresponds to the critical stress of the gradient damage material, see \eqref{eq:sigc0}, and $u_\mc$ is thus the critical displacement at the end $x=L$ of a bar fixed at $x=0$ in the quasi-static condition. The half-bar length $L$ and the corresponding time $L/c$ for the elastic wave to travel such distance is used to normalize the spatial and temporal scales. We have thus \begin{align} u(x,t) &= u_\mc\,\uhat\left(\frac{x}{L},\frac{ct}{L}\right)=u_\mc\,\uhat(y,\tau)\,, \label{eq:uhat} \\ \alpha(x) &= \ahat\left(\frac{x}{L}\right)=\ahat(y)\,, \notag \end{align} where $y$ and $\tau$ designate respectively the normalized space and time coordinates. In this work the damage constitutive law \eqref{eq:at1} is used. According to \cref{sec:ingredients}, the critical stress is then given by $\sigma_\mc=\sqrt{w_1E}$, which leads to the following non-dimensional Lagrangian \begin{equation} \label{eq:nondimensionalL} \widehat{\mathcal{L}}(\uhat_\tau,\dot{\uhat}_\tau,\ahat_\tau)=w_1L\int_0^1\left(\frac{1}{2}(1-\ahat_\tau)^2\uhat_\tau'^2+\ahat_\tau+\widehat{\eta}^2\ahat_\tau'^2-\frac{1}{2}\dot{\uhat}_\tau^2\right)\D{y}. \end{equation} For a given finite $\eta$, the length scale $\widehat{\eta}=\eta/L$ is the only non-dimensional parameter influencing the qualitative behaviors of the problem. Numerically, this amounts to solve the evolution problem in the normalized interval $[0,1]$ with the parameters indicated in \cref{tab:para1d}. The relationship \eqref{eq:gcingd} between $w_1$ and $\gc$ is also used. \begin{table}[htbp] \centering \caption{Geometric and material parameters for the crack nucleation problem} \label{tab:para1d} \begin{tabular}{lllll} \toprule $L$ & $\rho$ & $E$ & $\gc$ & $\sigma_\mc$ \\ \midrule 1 & 1 & 1 & $\frac{8}{3}\eta$ & 1 \\ \bottomrule \end{tabular} \end{table} Using the normalized space and time scales, we assume that at $y=1$ the bar is subject to the impact condition $\widehat{\vec{U}}_\tau=\widehat{v}\tau\,\vec{e}_1$. The time interval of interest is $\tau\in[0,2]$. Using the definition of the critical stress \eqref{eq:sigc0}, after normalization, the damage initiation criterion \eqref{eq:damageinitiationsound} for an initially sound body (with $\widehat{\alpha}_\tau=0$ almost everywhere) reads hence \begin{equation} \label{eq:nuclecrit} \uhat_\tau'^2=1. \end{equation} This implies that damage could takes place wherever \eqref{eq:nuclecrit} is satisfied. Tension-compression asymmetry \eqref{eq:elasticTC} is not considered here. Using the jump condition, we have thus \begin{itemize} \item If $\widehat{v}>1$, then the damage criterion is instantaneously met at $y=1$ and subsequent crack nucleation could take place soon. \item If $0.5<\widehat{v}<1$, then the damage criterion is satisfied at $\tau=1$ when the two waves arrive at the center. A typical strain and damage evolution obtained with the dynamic gradient damage model is indicated in \cref{fig:grad3d}. Strain localization takes place and damage evolves at the center, which resembles the result obtained with the local strain-softening model in \cref{fig:elassoftening}. \end{itemize} \begin{figure}[htbp] \centering \includegraphics[width=0.95\textwidth]{grad3d.pdf} \caption{Strain (a) and damage (b) before and after the wave crossing at $t=\frac{L}{c}$ in the dynamic gradient damage model with $\widehat{\eta}=0.01$} \label{fig:grad3d} \end{figure} \subsection{Numerical convergence properties} We first analyze the numerical convergence properties of dynamic gradient damage models given a fixed length ratio $\eta/L$. With a uniform linear finite element interpolation with typical mesh size $h$ and the explicit Newmark scheme (along with mass lumping) with a time increment corresponding to the CFL time step $\Delta \tau=\Delta \tau_\mathrm{CFL}=h$ (since the wave speed is normalized to 1), it is known that the displacement $u_h$ at time $\tau\in[0,2]$ for an elastodynamic problem (without damage or strain-softening) converges with order $\mathcal{O}(h^2)$ in the $L^2$ norm for the error defined by \begin{equation} \label{eq:error} e_h=\frac{\norm{u_h-u_\mathrm{ref}}_{L_2}}{\norm{u_\mathrm{ref}}_{L_2}}=\frac{\sqrt{\int_\Omega(u_h-u_\mathrm{ref})^2\D{x}}}{\sqrt{\int_\Omega u_\mathrm{ref}^2\D{x}}}. \end{equation} Furthermore, superconvergence can be observed for this particular one-dimensional problem with the above numerical parameters, see \cite{Hughes:1987}. In this case the obtained results are exact (with respect to the original time-space continuous problem) at discretization nodes independently of how few elements are used. The convergence rate as well as this property can be illustrated numerically by considering an elastic bar subject to $\widehat{\vec{U}}_\tau=\frac{1}{2}(1-\cos(\pi \tau))\,\vec{e}_1$ at $y=1$. A snapshot of the dynamic system state at $\tau=1$ is taken. In \eqref{eq:error}, $u_\mathrm{ref}$ is taken to be a reference solution obtained with $h=\num{1e-3}$. From \cref{fig:elasconv}, the quadratic convergence as well as the superconvergence property is verified. If a velocity shock is applied here, since the analytical solution is piecewise linear, the finite element solution would coincide exactly with the theoretic one. \begin{figure}[htbp] \centering \includegraphics[width=0.95\textwidth]{elas_h.pdf} \caption{Numerical convergence for the elastodynamic problem} \label{fig:elasconv} \end{figure} In the dynamic gradient damage model, numerical convergence is studied for the displacement and the damage at $\tau=2$, with an impact speed $\widehat{v}=0.6$ and two length scales $\widehat{\eta}=0.1$ or $0.2$. The results are indicated in \cref{fig:gradhell0x1,fig:gradhell0x2}. The reference solution is obtained with $h=\widehat{\eta}/100$. \begin{figure}[htbp] \includegraphics[width=0.95\textwidth]{grad_h_ell0x1.pdf} \caption{Numerical convergence study for $\widehat{\eta}=0.1$: (a) displacement at $\tau=2$ and (b) convergence rates} \label{fig:gradhell0x1} \end{figure} \begin{figure}[htbp] \includegraphics[width=0.95\textwidth]{grad_h_ell0x2.pdf} \caption{Numerical convergence study for $\widehat{\eta}=0.2$: (a) displacement at $\tau=2$ and (b) convergence rates} \label{fig:gradhell0x2} \end{figure} Several remarks are given as follows. \begin{itemize} \item The superconvergence property is lost, since it can be observed that solutions with different discretization sizes no longer agree with each other exactly at the nodes. \item The quadratic convergence rate for the displacement and the damage may degenerate according to the value of the length scale $\widehat{\eta}$. As $\widehat{\eta}\to 0$ (see \cref{fig:gradhell0x1}), strain is more localized near $y=0$, which may lead to a lower convergence rate. In any case, convergence is ensured. We assume that $h=\widehat{\eta}/10$ gives sufficiently accurate results and hence will be used in all subsequent calculations. \end{itemize} \subsection{Energy dissipation at fracture} Consider the case when the damage criterion \eqref{eq:nuclecrit} will be first satisfied at $\tau=1$ when the two tensile waves encounter at the center. Fracture in gradient damage models is defined as the event when/where $\widehat{\alpha}_t(y)\approx 1$ somewhere in the bar. Numerically the value of 0.99 is used as the threshold. For the shock velocity $\widehat{v}=0.6$ and the length scale $\widehat{\eta}=0.1$, the final damage field at fracture is illustrated in \cref{fig:alphatf}. \begin{figure}[htbp] \centering \includegraphics[width=0.5\linewidth]{alpha.pdf} \caption{Damage field at fracture with $\widehat{v}=0.6$ and $\widehat{\eta}=0.1$} \label{fig:alphatf} \end{figure} The analytical quasi-static optimal damage field \eqref{eq:at1alpha} is also indicated. Recall that the optimal damage field \eqref{eq:defoptimaldamage} corresponds to the equivalent fracture toughness \eqref{eq:gcingd}. Since here the damage band obtained is wider than the optimal one, more energy is dissipated than the $\gc$ defined via \eqref{eq:gcingd}. This overdissipation is analyzed for different length scales and shock velocities, see \cref{fig:Gc-ell}. The energy dissipated at fracture is normalized by the quasi-static fracture toughness defined via \eqref{eq:gcingd}. We observe that the overdissipation of approximately 30\% seems to be independent of the length ratio $\eta/L$ and shows little dependence on the shock velocity. In any case, with a gradient damage modeling of fracture, fracture takes place always with a non-vanishing energy dissipation. Future work will be devoted to a better understanding of this over-dissipation. \begin{figure}[htbp] \centering \includegraphics[width=0.5\linewidth]{Gc-ell.pdf} \caption{Dissipated energy when the bar breaks} \label{fig:Gc-ell} \end{figure} \subsection{Size effect} Recall that in local strain-softening models the instant of fracture coincides with the instant when the strain-softening mechanism is satisfied. This implies that the structural failure is size-independent. Consider first the case when fracture takes place at $\tau=1$ in local models, \emph{i.e.} for $\widehat{v}\in(0.5,1)$. The instant of fracture $\tau_\mathrm{f}$ for different length scales $\eta/L$ is illustrated in \cref{fig:tfell}, where the result $\tau_\mathrm{f}=1$ for local models is also indicated. \begin{figure}[htbp] \centering \includegraphics[width=0.5\linewidth]{tf-ell.pdf} \caption{Size effect illustrated by the instant of fracture for different length scales for $\widehat{v}\in(0.5,1)$} \label{fig:tfell} \end{figure} Several remarks are given as follows. \begin{itemize} \item With dynamic gradient damage models, the instant of fracture normalized by the factor $\frac{L}{c}$ depends on the length scale $\eta/L$, which illustrates a size effect. In local strain-softening models fracture takes place always at $t=\frac{L}{c}$, or $\tau=1$. \item At fixed internal length $\eta$ (material property), shorter bars delay ultimate fracture (\emph{smaller is stronger}), while for longer bars the fracture behavior is similar to that predicted by the local model. Comparison between these two models can be analyzed in the limit $\eta/L\to 0$. It will be performed in the next section. \item Contrary to quasi-static situations, this size effect depends also on the shock velocity. For higher velocities $\widehat{v}\approx 1^-$, the fracture instant approaches that of the local strain-softening model. The reverse is observed for lower shock speeds for $\widehat{v}\approx 0.5^+$. \end{itemize} For higher shock speeds $\widehat{v}>1$, fracture will take place immediately at $\tau=0$ for local models independently of the size of the bar. For gradient damage models, another size effect diagram is observed, see \cref{fig:sizeeffectv1}(a). In can be seen that longer bars behave exactly like the local strain-softening models, \emph{i.e.} $\tau_\mathrm{f}\to 0$. Again, fracture can be delayed for shorter bars. For small length ratios $\eta/L$, the instant of fracture $\tau_\mathrm{f}$ scales linearly with $\eta/L$. With $\eta/L=0.01$, the dependence of the instant of fracture on the shock velocity is analyzed in \cref{fig:sizeeffectv1}(b). According to these two diagrams in \cref{fig:sizeeffectv1}, we have the following estimation for small length scales $\eta/L\ll 1$ and large shock velocities $\widehat{v}\gg 1$ \[ \tau_\mathrm{f}\propto\widehat{\eta}\cdot\widehat{v}^{\,-1.75}. \] \begin{figure}[htbp] \centering \includegraphics[width=\linewidth]{tf-ell2v.pdf} \caption{(a) Size effect illustrated by the instant of fracture for different length scales $\widehat{v}>1$. (b) Dependence of the instant of fracture on the shock velocity with $\eta/L=0.01$} \label{fig:sizeeffectv1} \end{figure} Using the definition of the rescaled time $\tau$, the linear scaling of the rescaled instant of fracture with respect to the length scale $\tau_\mathrm{f}\propto\widehat{\eta}$ leads to \begin{equation} \label{eq:tfc} t_\mathrm{f}\propto\frac{\eta}{c}. \end{equation} It can be seen that here the value of the internal length determines the actual structural failure instant and should be considered as a material parameter. Future work will be devoted to a theoretic understanding of \eqref{eq:tfc}. \subsection{Link with local strain-softening models} As indicated by \cref{fig:tfell,fig:sizeeffectv1}, the fracture behaviors of longer bars are similar to that predicted by the local strain-softening model. At $\tau=0.6$, the asymptotic behavior of the rescaled displacement when $\eta/L\to 0$ is indicated in \cref{fig:comp1d} for two shock velocities. The solution due to the local strain-softening model is also indicated. \begin{figure}[htbp] \centering \includegraphics[width=\textwidth]{comp_1d.pdf} \caption{Asymptotic behavior of the rescaled displacement when $\eta/L\to 0$ compared with the local strain-softening model: (a) $\widehat{v}=0.6$ and (b) $\widehat{v}=0.9$} \label{fig:comp1d} \end{figure} A slow convergence can be observed in the $L^2$-norm of the normalized displacement, see \cref{fig:conv_ell}. The convergence rate shows dependence on the shock velocity. In the limit $\ell/L\to 0$, the normalized displacement $\widehat{u}$ thus converges to that predicted by the local strain-softening model. \begin{figure}[htbp] \centering \includegraphics[width=0.5\linewidth]{conv_ell.pdf} \caption{Convergence rate for the rescaled displacement when $\eta/L\to 0$} \label{fig:conv_ell} \end{figure} However note that this convergence toward the local strain-softening model can never be attained and should only be considered as a limiting behavior of dynamic gradient damage models, see also the discussion between the variational approach to fracture and gradient damage approaches in \cref{sec:twointerpretations}. Several remarks are given as follows. \begin{itemize} \item The above convergence is established for the normalized displacement. Using the definition \eqref{eq:uhat}, for $\widehat{v}\in(0.5,1)$ the real displacement tends to develop a sharp discontinuity at $x=0$ with a jump of magnitude \[ \llbracket u_t(0)\rrbracket=4vu_\mc\inp{t-\frac{L}{c}}=4v\sqrt{\frac{3\gc}{8E\eta}}L\inp{t-\frac{L}{c}}. \] \item For very long bars $L\to\infty$, the two tensile waves can never arrive at the center and for $\widehat{v}\in(0.5,1)$ fracture will never take place, since $\llbracket u_t(0)\rrbracket\to 0$ when $L\to \infty$. \item Very small internal lengths $\ell\to 0$ imply an infinite critical stress $\sigma_\mc\to\infty$ through \eqref{eq:sigc0}, hence again fracture can never take place. Instead $\ell$ should be considered as a material parameter, see \cref{sec:twointerpretations}. \end{itemize} \subsection*{Conclusion} As is demonstrated by numerical simulations, a gradient-damage approach of dynamic fracture leads to a better modeling of crack nucleation in the following aspects: \begin{itemize} \item In the Griffith's theory crack nucleation is not possible for an initially sound body. In the gradient damage model (with a fixed internal length $\ell$), crack can nucleate and the damage initiation criterion is given by \eqref{eq:nuclecrit}. \item The internal length $\ell$ influences numerical convergence properties and needs further investigation concerning in particular the convergence rates. \item In gradient damage models, fracture takes place with a finite non-vanishing energy dissipation while in local strain-softening models it is not the case. In dynamics a systematic over-dissipation is observed for all internal lengths and needs further investigation. \item In local strain-softening models the fracture mechanism is size-independent. In gradient damage models the length ratio $\ell/L$ achieves a size effect in terms of the fracture instant. The general belief \emph{smaller is stronger} is verified. \item A certain link between gradient damage models and local strain-softening models is found by investigating the limit $\ell/L\to 0$. In such process, the fracture behavior of gradient damage models is qualitatively similar to that of local models, if the normalized displacement \eqref{eq:uhat} is considered. \end{itemize} \section{Antiplane Tearing} \label{sec:antiplane} In \cref{sec:1d} the crack \emph{nucleation} is considered and a stress-based criterion \eqref{eq:damageinitiationsound2} governs the damage initiation. This section discusses a particular numerical experiment tailored to highlight the properties of the dynamic gradient damage model while focusing on the \emph{initiation} and \emph{propagation} phases of defect evolution. Specifically, we will investigate the fracture mechanics criterion for an existing phase-field crack to \emph{initiate}, and then to \emph{propagate} along a certain path. This experiment constitutes a numerical verification of the generalized Griffith criterion given in \cref{prop:Ggriffithlaw} and its asymptotic interpretation outlined in \cref{prop:whenellpetit}. Recall that these properties can also be considered as a dynamic extension of the theoretic results established in \cite{SicsicMarigo:2013} for quasi-static gradient damage models. Another objective is to investigate the quasi-static limit of the dynamic model summarized in \cref{def:dynagraddama}. The thematic subjects covered here are thus summarized in \cref{tab:summanti}. \begin{table}[htbp] \centering \caption{Thematic subjects covered in this section} \label{tab:summanti} \begin{tabular}{ccccc} \toprule & Going dynamical & $\alpha\leftrightarrow\phi$ & $\nabla\alpha\to\Gamma$ & Experimental validation \\ \midrule Theoretics & & & & \\ Numerics & \rightthumbsup & & \rightthumbsup & \\ \bottomrule \end{tabular} \end{table} \paragraph{Problem setting} We consider a mode-\RNN{3} antiplane tearing of a two dimensional plate $\Omega=[0,L]\times[-H,H]$ subject to a hard device $\vec{U}_t=\operatorname{sgn}(y)kt\,\vec{e}_3$ on its left border $x=0$, see \cref{fig:antiplane}. \begin{figure}[htbp] \centering \includegraphics[width=0.45\textwidth]{antiplane.pdf} \caption{Mode III antiplane tearing of a two dimensional plate $\Omega=[0,L]\times[-H,H]$ with a loading speed parametrized by $k$. An initial crack $[0,l_0]\times\set{0}$ is present in the domain. The crack is enforced to propagate along the constant direction $\vec{e}_1$} \label{fig:antiplane} \end{figure} An initial damage field corresponding to a preexisting crack $\Gamma_0=\set{\vec{x}\in\mathbb{R}^2|\alpha_0(\vec{x})=1}=[0,l_0]\times\set{0}$ is present in the domain. For that we prescribe naturally $\dvec^{-1}=1$ on $\Gamma_0$ using \cref{algo:init}. The loading velocity $k$ will be varied and its effect on the crack propagation speed will be studied. With a modification of the damage dependence of the elastic energy $\mathcal{E}(\vec{u}_t,\alpha_t)$ proposed in \cite{Bourdin:2011}, the crack tip $t\mapsto\vec{P}_t$ is enforced to propagate along the constant direction $\vec{e}_1$, which prohibits consequently crack kinking or branching. Denoting $u$ as the out-of-plane displacement, the elastic energy density \eqref{eq:elasticG} in this particular situation reads \begin{equation} \label{eq:straightmode3} \psi(\nabla u_t,\alpha_t)=\frac{1}{2}\mu\left(a(\alpha_t)\left(\frac{\partial u_t}{\partial x_2}\right)^2+\left(\frac{\partial u_t}{\partial x_1}\right)^2\right)\,, \end{equation} where damage acts only on the $\partial_2 u$ component of the displacement gradient. We assume that this modification \eqref{eq:straightmode3} can be regarded as a particular case of the original model \eqref{eq:elasticG} when the crack actually propagates along a specific path without kinking or branching. It allows us to focus on the crack propagation stage. \begin{remark} If the original model is used, \emph{i.e.} when the degradation function also acts on $\frac{\partial u_t}{\partial x_1}$, numerically it is observed that for low propagation speeds crack curving (including kinking and branching) does not take place and the modification \eqref {eq:straightmode3} produces the same response as the original model. However for higher propagation speeds (for example due to a larger loading velocity $k$), crack curving is observed (see for example \cite{Bourdin:2011}) and these two models no longer predict the same crack evolution. Crack path prediction is exactly the \emph{raison d'être} of phase-field models of fracture. An investigation of crack kinking/branching phenomena is a very important task and will be separately considered in \cref{sec:kinking} and \cref{sec:branching}. Nevertheless, the current contribution focuses on the behavior of gradient damage models when these dynamic instabilities (kinking, branching) are somehow suppressed (see for example \cite{LivneBen-DavidFineberg:2007} for an experimental investigation on this point), which permits a direct comparison with the classical Griffith's theory of dynamic fracture. \end{remark} This problem is initially raised in \cite{Bourdin:2011}. In their model the crack surface energy is approximated by the Ambrosio and Tortorelli elliptic regularization (the \eqref{eq:at2} model), whereas here the damage constitutive law \eqref{eq:at1} is used. The objective is to compare the crack evolution obtained in the dynamic gradient damage model with that predicted by Griffith's law which determines initiation and propagation of cracks. Two experiments will be considered: \begin{enumerate} \item In the first case, the fracture toughness $\gc$ is assumed to be homogeneous throughout the domain. The loading speed is of the same order of the material sound speed $c=\sqrt{\mu/\rho}$ and we will use the explicit Newmark time-stepping method, \emph{i.e.} \cref{algo:explicit}. \item In the second case, $\gc$ may admit a spatial discontinuity in the propagation direction. We also prescribe a relatively small loading speed in order to investigate the quasi-static limit of the dynamic model. Depending on whether the crack propagation speed itself is smaller with respect to the sound speed or not (the term \emph{unstable} propagation often refers to this case), the implicit (\cref{algo:implicit}) or the explicit Newmark method will be used. \end{enumerate} A rescaling of the displacement and a normalization of the space/time scales are performed to obtain a non-dimensional problem. Specifically, a reference elastic constant $\overline{\mu}$, material density $\overline{\rho}$ and fracture toughness $\overline{\gc}$ have been chosen and the displacement is scaled by a factor of \[ \overline{u}=\sqrt{\overline{\gc}H/\overline{\mu}}. \] The height of the plate $H$ and the corresponding time $H/\overline{c}$ for the reference elastic wave (with speed $\overline{c}=\sqrt{\overline{\mu}/\overline{\rho}}$) to travel such distance is used to normalize the spatial and temporal scales. We have thus \begin{align*} \vec{u}(\vec{x},t) &= \overline{u}\,\uhat\left(\frac{\vec{x}}{H},\frac{\overline{c}t}{H}\right)\vec{e}_3\,, \\ \alpha(\vec{x},t) &= \ahat\left(\frac{\vec{x}}{H},\frac{\overline{c}t}{H}\right)\,. \end{align*} Rewriting Lagrangian defined in \eqref{eq:action} using $\uhat$ and $\ahat$ amounts to adopt the following non-dimensional quantities \[ \widehat{\rho}=\frac{\rho}{\overline{\rho}}\,,\quad \widehat{\mu}=\frac{\mu}{\overline{\mu}}\,,\quad \widehat{\gc}=\frac{\gc}{\overline{\gc}}\quad\text{and}\quad\widehat{\ell}=\frac{\ell}{H}. \] For notational simplicity, we drop the bar and use directly non-dimensional quantities in the sequel. A structured crossed triangular mesh with a uniform discretization spacing $\Delta x=\Delta y=h$ is generated. For the explicit time-stepping method, the Courant–Friedrichs–Lewy (CFL) time-step is used \begin{equation} \label{eq:tcfl} \Delta t_\mathrm{CFL}=\frac{h}{c}=\frac{h}{\sqrt{\mu/\rho}}. \end{equation} The parameters adopted for all subsequent calculations are summarized in \cref{tab:paraanti}. \begin{table}[htbp] \centering \caption{Geometric, material and numerical parameters for the antiplane tearing experiment} \label{tab:paraanti} \begin{tabular}{lllllllll} \toprule $L$ & $H$ & $l_0$ & $\mu$ & $\rho$ & $\gc$ & $\eta$ & $h$ & $\Delta t$\\ \midrule 5 & 1 & 1 & 0.2 & 1 & 0.01 & 0.05 & 0.01 & $\Delta t_\mathrm{CFL}$ \\ \bottomrule \end{tabular} \end{table} A typical damage field obtained in this simulation is illustrated in \cref{fig:antiplane_2d_new}, where the damage varies from 0 (blue zones) to 1 (red zones). Thanks to the $\Gamma$-convergence result summarized in \cref{sec:fm98,sec:graddamage}, the current crack length $l_t$ could be approximately derived from the damage dissipation energy using the estimation \eqref{eq:gammaconvergence}. For the \eqref{eq:at1} model, the coefficient $c$ in \eqref{eq:gceff} reads $c=3/8$ (see \cite{HossainHsuehBourdinBhattachary:2014}), hence the following effective fracture toughness is used \[ (\gc)_\mathrm{eff}=\left(1+\frac{3h}{8\eta}\right)\gc. \] However \eqref{eq:gammaconvergence} does not immediately apply to the case where $\gc$ admits a spatial discontinuity. For consistency, the current crack tip $\vec{P}_t=(l_t,0)$ is located on the contour $\alpha=0.5$. The crack speed can thus be obtained by a linear regression analysis during the steady propagation phase. \begin{figure}[htbp] \centering \includegraphics[width=0.65\textwidth]{antiplane_2d_new.pdf} \caption{Typical damage field obtained in the antiplane tearing example. The damage varies from 0 (blue zones) to 1 (red zones)} \label{fig:antiplane_2d_new} \end{figure} \subsection{Link between damage and fracture in dynamics} \label{sec:homo} \paragraph{Comparison with the Griffith's theory of dynamic fracture} In the first case a homogeneous plate will be considered. This antiplane tearing example is physically similar to the 1-d film peeling problem which can be studied using the classical Griffith's theory of dynamic fracture. According to \cite{DumouchelMarigoCharlotte:2008} and \cite{BourdinFrancfortMarigo:2008}, the crack speed, with respect to the loading displacement $U=kt$ or to the physical time $t$, as a function of the loading velocity $k$, is given by \begin{equation} \label{eq:dumouchel} \frac{\mathrm{d} l}{\mathrm{d} U}(k)=\sqrt{\frac{\mu H}{\gc+\rho Hk^2}}\quad\text{or}\quad\frac{\mathrm{d} l}{\mathrm{d} t}(k)=\sqrt{\frac{\mu Hk^2}{\gc+\rho Hk^2}} \end{equation} from which we retrieve the quasi-static limit $\mathrm{d} l/\mathrm{d} U(0)=\sqrt{\mu H/\gc}$ predicted in \cite{BourdinFrancfortMarigo:2008} and the dynamic limit as the shear wave speed $\mathrm{d} l/\mathrm{d} t(\infty)=\sqrt{\mu/\rho}$, which is a classical result of the Griffith's theory of dynamic fracture, see \cref{sec:griffithfreund}. We also observe that for low loading speeds $k\approx 0$, the dynamic crack speed $\mathrm{d} l/\mathrm{d} t\approx k\sqrt{\mu H/\gc}$ scales linearly in $k$, which agrees with the remark given in \cite{Bourdin:2011}. Comparisons between the numerical results using the dynamic gradient model and this theoretic result \eqref{eq:dumouchel} with $\gc$ replaced by $(\gc)_\mathrm{eff}$ are illustrated in \cref{fig:mode3}. \begin{figure}[htbp] \centering \includegraphics[width=\textwidth]{crack_speed.pdf} \caption{Crack speeds as a function of the loading velocity. The crack speed respect to $t$ is indicated in (a), while in (b) the crack speed with respect to $U$ is used. Comparison with the 1-d analytical solution \eqref{eq:dumouchel} based on the Griffith's criterion} \label{fig:mode3} \end{figure} Despite the transverse wave reflection present in the two-dimensional numerical model, a very good quantitative agreement is found between them. In particular, as it is also observed in \cite{Bourdin:2011}, the numerically obtained crack speed indeed approaches the limiting shear wave speed when the loading speed increases. The explicit time-stepping described in \cref{algo:explicit} as well as its FEniCS implementation work fine even at supersonic loading speeds. \paragraph{Verification of Griffith's law} Next we investigate how exactly the crack propagates in the dynamic gradient damage model, \emph{i.e.} provide a fracture mechanics interpretation of the three physical principles given in \cref{def:dynagraddama}. We propose hence to verify the generalized Griffith criterion (\cref{prop:Ggriffithlaw}) and the asymptotic interpretation (\cref{prop:whenellpetit}), by comparing the conventional dynamic energy release rate $G^\alpha_t$ and the damage dissipation rate $\gamma_t$. Written in the form of \eqref{eq:GtC}, $G^\alpha_t$ involves an integral in the cells and hence is more convenient and accurate compared to a path integral ($J$-integral for instance) in a finite element calculation. The use of traditional $J$-integrals in a gradient damage or phase-field modeling of fracture can be found in \cite{HossainHsuehBourdinBhattachary:2014,KlinsmannRosatoKamlahMcMeeking:2015} for instance. A widely used definition of the virtual perturbation \cite{DestuynderDjaouaLescure:1983} is recalled as follows. Suppose that the crack $\Gamma_t$ lies on the $x$-axis and its current crack tip $\vec{P}_t=(l_t,0)$ is propagating along the $\vec{e}_1$ direction. The virtual perturbation $\vtheta_t$ which introduces a fictive crack advance admits the form $\vtheta_t=\theta_t\vec{e}_1$. The construction of the continuous scalar field $0\leq\theta_t\leq 1$ parametrized by two radii $r<R$ is given in \cref{fig:thetaAnt}. \begin{figure}[htbp] \centering \includegraphics[width=0.7\textwidth]{theta_field.pdf} \caption{A particular virtual perturbation $\vtheta_t=\theta_t\vec{e}_1$ parametrized by two radii $r<R$. We have $\theta_t=1$ inside the ball $B_r(\vec{P}_t)$, $\theta_t=0$ outside the ball $B_R(\vec{P}_t)$, and a linear interpolation in between} \label{fig:thetaAnt} \end{figure} The conventional dynamic energy release rate \eqref{eq:GtC} is numerically computed and the validity of the asymptotic Griffith's law (\cref{prop:whenellpetit}) is analyzed by varying the inner radius $r$ of virtual perturbations defined in \cref{fig:thetaAnt}. During the propagation phase $\dot{l}_t>0$, three arbitrary time instants are taken when the crack length attains respectively $l_t\approx 1.6$, $l_t\approx 2$ and $l_t\approx 2.4$. An evident $r$-dependence of $G^\alpha_t$ is illustrated in \cref{fig:indvelocity}, where the ratio $R/r=\frac{5}{2}$ is fixed. \begin{figure}[htbp] \centering \includegraphics[width=0.5\textwidth]{Gtheta_of_r.pdf} \caption{Conventional dynamic energy release rate $G^\alpha$ as a function of the inner radius $r$ of the virtual perturbation $\vtheta_t$ with a fixed ratio $R/r=\frac{5}{2}$. Three arbitrary instants when the crack propagates $\dot{l}_t>0$ are chosen} \label{fig:indvelocity} \end{figure} In the Griffith's theory of linear elastic dynamic fracture, according to \cref{prop:J}, the energy release rate $G_t$ is independent of the virtual perturbation field $\vtheta_t$ since it is related directly to the dynamic stress intensity factors at the crack tip. In gradient damage models however, there is no more stress singularities. When $r$ is small, we go directly into the process zone (crack tip problem) dominated by damage-induced strain softening and $G^\alpha_t\to 0$ is expected as $r\to 0$. However, as $r$ increases, $G^\alpha_t$ captures well the outer mechanical fields of the outer Griffith's fracture problem. An equivalent energy release rate can thus be defined, and according to \cref{prop:whenellpetit}, we have the desired result $G^\alpha_t=\gamma_t\to (\gc)_\mathrm{eff}$. We will then turn to the evolution of the conventional dynamic energy release rate when the existing crack initiates and further propagates. From the above $r$-dependence analysis, a fixed inner radius $r=2\eta$ is used which should already correctly capture the far mechanical fields. The crack length $l_t$ given by \eqref{eq:gammaconvergence} as well as the calculated $G^\alpha_t$ are given as a function of the loading displacement in \cref{fig:evoGtGc}, where three separate calculations corresponding to three loading speeds $k$ are reported. \begin{figure}[htbp] \centering \includegraphics[width=0.55\textwidth]{dyn_Gtheta_k.pdf} \caption{Conventional dynamic energy release rate $G^\alpha$ as a function of the loading displacement. Three loading speeds $k$ are used: $k=0.1\approx 0.2c$, $k=0.2\approx 0.4c$ and $k=0.3\approx 0.7c$} \label{fig:evoGtGc} \end{figure} Recall that an initial crack of length 1 is present in the body and we observe $G^\alpha_t=0$ before the waves arrive at the initial crack tip. When the energy release rate $G^\alpha_t$ at the initial crack tip attains the fracture toughness $(\gc)_\mathrm{eff}$, the existing crack $\Gamma_0=[0,1]\times\set{0}$ initiates and then propagates with the equality $G^\alpha_t=(\gc)_\mathrm{eff}$ if the spatial and temporal numerical discretization errors are ignored. Indeed this equality is not enforced algorithmically during the solving of the $(\vec{u},\alpha)$ evolution which is instead determined by \cref{algo:explicit}. We may conclude that the crack-tip evolution (initiation and propagation) is well governed by the asymptotic Griffith's law (\cref{prop:whenellpetit}) in the dynamic gradient damage model, when outer fields are considered. The internal length $\ell$ (hence the maximal material stress \eqref{eq:sigc0}) plays a rather subtle role during the propagation phase. The crack tip is governed by the asymptotic Griffith's law (\cref{prop:whenellpetit}) if and only if a separation of scales between the inner damage problem and the outer LEFM is possible, \emph{i.e.} only when the internal length is sufficiently small compared to any other structural length. Although $\ell$ is indeed hidden in \cref{prop:whenellpetit}, the validity of the latter depends directly on it. Below we present the simulation results with a fixed loading speed $k=0.2$ and three small enough internal lengths. As can be seen from \cref{fig:evoGtGcell}, the crack evolution is globally conforming with Griffith's law, as long as the involved quantities are calculated with a virtual perturbation $\vtheta_t$ capturing correctly the far fields. Here according to \cref{fig:indvelocity}, we use an inner radius adapted with the internal length $r=2\eta$, which should produce an error less than $3\%$. \begin{figure}[htbp] \centering \includegraphics[width=0.55\textwidth]{dyn_Gtheta_ell.pdf} \caption{Crack evolution as a function of the loading displacement. Three small enough internal lengths are used} \label{fig:evoGtGcell} \end{figure} The stress distribution along a vertical slice $\set{(x,y)\in\mathbb{R}^2|x=l_t}$ passing by the current crack tip $\vec{P}_t$ will illustrate and highlight the separation of scales when $\ell$ is small. For the sake of simplicity, we consider a stationary crack $[0,2]\times\set{0}$ and solve the static problem with the gradient damage model and the LEFM model (linear elastic body with a sharp crack embedded in the domain). On the one hand, we can verify from \cref{fig:stress} that the LEFM develops a well-known inverse square root singularity for the two stress components $\sigma_{13}$ and $\sigma_{23}$ and their near-tip fields are well approximated by the theoretic asymptotic solutions. \begin{figure}[htbp] \centering \includegraphics[width=\textwidth]{asymptotic-sig.pdf} \caption{Stress distribution along a vertical slice $\set{(x,y)\in\mathbb{R}^2|x=l_t}$ passing by the current crack tip $\vec{P}_t$. The $\sigma_{13}$ (a) and the $\sigma_{23}$ (b) components are indicated. The gradient damage model and the LEFM model are compared} \label{fig:stress} \end{figure} On the other hand, the gradient damage model provides a better modeling of the stress field near the crack tip as their values are bounded. A good matching can be observed far from the crack tip whereas the discrepancy with the outer LEFM model is concentrated within a process zone proportionally dependent on the internal length. When $\ell$ is very large, the process zone could cover the whole structural domain and a separation of scales is no longer possible. In this case the asymptotic Griffith's law (\cref{prop:whenellpetit}) is not applicable since we are no longer dealing with a fracture mechanics problem. \subsection{Quasi-static limit of the dynamic model} As another illustration of the Griffith-conforming crack evolution obtained with the dynamic gradient damage model, we consider the quasi-static limits of the model in the presence of a possible fracture toughness discontinuity in the previous plate \[ \gc=\begin{cases} K_1 & x\leq x_0 \\ K_2 & x>x_0 \end{cases} \] A preexisting crack is always present and is introduced via an initial damage field. A theoretic convergence investigation of the dynamic gradient damage model with a vanishing loading speed $k\to 0$ is performed in \cite{Versieux:2015}. The analysis is based on the hypothesis that the crack evolution $t\mapsto l_t$ is at least continuous in time (as in the classical Griffith's theory). This implies that in the presence of brutal or unstable crack propagation, the convergence may not be observed. Nevertheless in the absence of these situations, the dynamic gradient damage model (\cref{def:dynagraddama}) should converge to the following \begin{definition}[First-Order Quasi-Static Gradient Damage Evolution Law] \label{def:firstorderqs} \noindent \begin{enumerate} \item \textbf{Irreversibility}: the damage $t\mapsto\alpha_t$ is a non-decreasing function of time. \item \textbf{First-order stability}: the first-order variation of the potential energy is non-negative with respect to arbitrary admissible displacement and damage fields \begin{equation} \label{eq:viqs} \mathcal{P}'(\vec{u}_t,\alpha_t)(\vec{v}_t-\vec{u}_t,\beta_t-\alpha_t)\geq 0\text{ for all $\vec{v}_t\in\mathcal{C}_t$ and all $\beta_t\in\mathcal{D}(\alpha_t)$}. \end{equation} \item \textbf{Energy balance}: the only energy dissipation is due to damage such that the energy balance condition \eqref{eq:qseb} is satisfied. \end{enumerate} \end{definition} Compared to the original quasi-static model (\cref{def:qsgraddama}), the more general meta-stability principle \eqref{eq:qsstability} is replaced by its first-order condition \eqref{eq:viqs}. However as it is noted in \cref{sec:ellipticregul}, numerically it is the first-order stability condition \eqref{eq:viqs} that is effectively implemented by the alternate minimization procedure, while the energy balance condition \eqref{eq:qseb} can only be at best checked \emph{a posteriori}. From this viewpoint, \cref{def:firstorderqs} can thus be considered as the effective quasi-static gradient-damage model. \paragraph{Homogeneous case $K_1=K_2$} The homogeneous antiplane tearing problem is firstly solved by the dynamic gradient damage model and the above first-order quasi-static gradient damage model. In the dynamic calculation a small loading speed $k=0.001\approx 0.2\%c$ is assumed and we use the unconditionally stable implicit Newmark scheme as described in \cref{algo:implicit}, with $\beta=\frac{1}{4}$. The time step is set to $\Delta t=10\Delta t_\mathrm{CFL}$. In \cref{fig:homoGcqs} we plot the crack length evolution as well as the conventional energy release rate $G^\alpha_t$ both for the dynamic model and the first-order quasi-static model. \begin{figure}[htbp] \centering \includegraphics[width=0.55\textwidth]{dyn_qs.pdf} \caption{Crack length and conventional energy release rate $G^\alpha$ for the homogeneous fracture toughness plate at a very slow loading speed. Comparison between the dynamic model and the first-order quasi-static model} \label{fig:homoGcqs} \end{figure} It is recalled that the static $G^\alpha_t$ can be simply obtained by setting $\dot{\vec{u}}_t$ and $\ddot{\vec{u}}_t$ to zero in \eqref{eq:GtC}. We observe that these two solutions coincide, and both present a time-continuous crack evolution (initiation and propagation) conforming to the asymptotic Griffith's law (\cref{prop:whenellpetit}). The numerically computed quasi-static crack speed (with respect to $U=kt$) is compared in \cref{tab:compqsv} to the analytical value $\sqrt{\mu H/\gc}$ announced in \cite{BourdinFrancfortMarigo:2008}. A very good agreement can be found if the numerically amplified fracture toughness $(\gc)_\mathrm{eff}$ is used in the formula. \begin{table}[htbp] \centering \caption{Comparison of the numerically computed quasi-static crack speed in the homogeneous case with the theoretic one $\sqrt{\mu H/\gc}$ given in \cite{BourdinFrancfortMarigo:2008}} \label{tab:compqsv} \begin{tabular}{lllll} \toprule & Numerical & Theoretic & Error \\ \midrule Quasi-static crack speed & 4.326 & 4.391 & 1.5\% \\ \bottomrule \end{tabular} \end{table} \paragraph{When $K_1<K_2$} We then turn to the case where the fracture toughness jumps suddenly from a lower value $K_1=0.01$ to a higher one $K_2=2K_1=0.02$ at $x=2$. The unconditionally stable implicit Newmark scheme with $\beta=\frac{1}{4}$ is used again with a time increment $\Delta t=10\Delta t_\mathrm{CFL}$. As can be observed from \cref{fig:hardGcqs} the convergence of the dynamic model toward the quasi-static one is verified and the crack initiates and propagates following Griffith's law. A temporary arrest phase is present shortly after the crack reaches the interface at $x=2$. Due to continuous loading the energy release rate increases and the crack then restarts and begins to propagate in the second material when the energy release rate $G^\alpha_t$ attains the higher fracture toughness $K_2$. \begin{figure}[htbp] \centering \includegraphics[width=0.55\textwidth]{dyn_hardening.pdf} \caption{Crack length and conventional energy release rate $G^\alpha$ for the hardening fracture toughness plate at a very slow loading speed. Comparison between the dynamic model and the first-order quasi-static model. The numerically amplified fracture toughness $(\gc)_\mathrm{eff}$ is calculated based on $K_1=0.01$} \label{fig:hardGcqs} \end{figure} \paragraph{When $K_1>K_2$} However, for the case where the fracture toughness $K_1=2K_2=0.02$ suddenly drops to a smaller value $K_2=0.01$ at $x=1$ (exceptionally here the initial crack length is $\frac{1}{4}$), a relatively good matching can only be found before and after the jump phase produced at the discontinuity, both in terms of the crack length evolution and the energy release rate. It is exactly at the jump phase that these two models strongly disagree, cf. \cref{eq:ressoftening}. \begin{figure}[htbp] \centering \includegraphics[width=0.55\textwidth]{dyn_softening.pdf} \caption{Crack length and the conventional energy release rate $G^\alpha$ for the softening fracture toughness plate at a very slow loading speed. Comparison between the dynamic model and the first-order quasi-static model. The numerically amplified fracture toughness $(\gc)_\mathrm{eff}$ is calculated based on $K_2=0.01$} \label{eq:ressoftening} \end{figure} Here due to the unstable crack propagation during the jump, the explicit Newmark scheme is used for the dynamic calculation with $\Delta t=\Delta t_\mathrm{CFL}$. When the crack arrives at the discontinuity, the \emph{first-order} quasi-static \emph{numerical} model underestimates the crack jump and predicts no further crack arrest, by relating directly the static energy release rate $G^\alpha_t$ to the fracture toughness $K_2$ just after the jump. For the dynamic model, the jump length is bigger and a subsequent temporary crack arrest is observed, as the dynamic energy release rate oscillates with a high frequency but remains smaller than the fracture toughness $K_2$ after the jump. We observe that in both cases the jump takes place at $x\approx 0.9$ somewhat prior to the fracture toughness discontinuity $x=1$. We suspect that this is due to the damage regularization of cracks with a half-band $D=2\eta=0.1$ using the constitutive laws of \eqref{eq:at1}. The crack length after the jump with this effect ignored is recorded in \cref{tab:compljump} for each case. From the static energy release rate evolution, we see that the crack length $l_\mathrm{m}$ after the jump predicted in the \emph{first-order} quasi-static \emph{numerical} model is governed by $G(l_\mathrm{m})=\gc(l_\mathrm{m})$ from which authors of \cite{DumouchelMarigoCharlotte:2008} find $l_\mathrm{m}=\sqrt{K_1/K_2}=\sqrt{2}$. However their dynamic analysis shows that the crack length after the jump $l_\mathrm{c}$ should instead be given by the total (quasi-static) energy conservation principle $\mathcal{P}(1)=\mathcal{P}(l_\mathrm{c})$, which results in $l_\mathrm{c}=K_1/K_2=2$. We see from \cref{tab:compljump} that our dynamic gradient damage model indeed reproduces this correct value. \begin{table}[htbp] \centering \caption{Comparison of the numerical crack lengths after the jump with the theoretic predictions} \label{tab:compljump} \begin{tabular}{lll} \toprule & Quasi-static & Dynamic \\ \midrule Numerical & 1.465 & 1.995 \\ Theoretic & $\sqrt{2}$ & 2 \\ Error & 3.6\% & 0.25\% \\ \bottomrule \end{tabular} \end{table} To better analyze the jump phase, energy evolutions are investigated against the crack length in \cref{fig:evoRNJjump}. \begin{figure}[htbp] \centering \includegraphics[width=0.5\textwidth]{dynqsET_softening.pdf} \caption{Energy variation as a function of the crack length for the softening fracture toughness plate at a very slow loading speed. Comparison between the dynamic model and the first-order quasi-static model} \label{fig:evoRNJjump} \end{figure} In the quasi-static case we pick the total energy $\mathcal{P}=\mathcal{E}+\mathcal{S}$ while in the dynamic case we plot separately the static energy $\mathcal{P}=\mathcal{E}+\mathcal{S}$ and the kinetic one $\mathcal{K}$. Before and sufficiently after the jump a good agreement between these two potential energies can be found. We observe that the (incorrect) quasi-static jump (\emph{i.e.}, an \emph{unstable} or \emph{brutal} crack propagation) is accompanied by a slight loss of the total energy $\Delta \mathcal{P}_\mathrm{stat.}$, contradicting the balance condition \eqref{eq:qseb}. This phenomenon has already been observed by several authors such as \cite{BourdinFrancfortMarigo:2008,AmorMarigoMaurini:2009,PhamAmorMarigoMaurini:2011,Bourdin:2011}. On the one hand, it can be regarded as a numerical issue as the effective implementation of the quasi-static model is solely based on the first-order stability condition \eqref{eq:viqs}. For this particular problem based on quasi-static energy conservation we could predict a correct quasi-static crack evolution toward which the dynamic solution converges when the loading speed becomes small, see \cite{DumouchelMarigoCharlotte:2008}. On the other hand, from a theoretic point of view, it is already known in \cite{Pham:2010} that there may not exist an energy-conserving evolution which also respects the stability criterion at every time. Moreover even equipped with the energy balance condition, the quasi-static model may still differ from the dynamic analysis \cite{LazzaroniBargelliniDumouchelMarigo:2012}. A natural and physical remedy for all general unstable crack propagation cases is to introduce inertial effects. In \cref{fig:evoRNJjump} the dynamic jump process is \emph{continuous} (the crack propagates at a finite speed bounded by the shear wave speed) compared to the quasi-static one where the jump occurs necessarily in a discontinuous fashion between two iterations. We verify the conclusions drawn in \cite{DumouchelMarigoCharlotte:2008} that the kinetic energy $\mathcal{K}$ plays only a transient role in this problem, as it attains a finite value during the jump and becomes again negligible after. The dynamic potential energy $\mathcal{P}=\mathcal{E}+\mathcal{S}$ after the jump is slightly bigger that its value before the jump, due to the fact that the loading speed $k=0.001$ is small but not zero. During the jump, the crack propagates at a speed comparable to the material speed of sound which, according to \cite{DumouchelMarigoCharlotte:2008}, is given by \begin{equation} \label{eq:vjump} v_\mathrm{jump}=\frac{\left(\sqrt{\widehat{K}_1+\epsilon^2}+\epsilon\right)^2-\widehat{K}_2}{\left(\sqrt{\widehat{K}_1+\epsilon^2}+\epsilon\right)^2+\widehat{K}_2}\cdot c \end{equation} with the non-dimensional fracture toughness $\widehat{K}_i=K_i/(2\mu H)$ and the normalized loading speed $\epsilon=k/c$. The crack length evolution during the jump is illustrated in \cref{fig:softGcqs_jump}. \begin{figure}[htbp] \centering \includegraphics[width=0.5\textwidth]{jump.pdf} \caption{Zoom in time at the crack length jump due to sudden toughness softening for the dynamic model} \label{fig:softGcqs_jump} \end{figure} Due to transverse wave reflection in this 2-d problem, the crack propagates during this interval with a small fluctuation of period $T$ approximately corresponding to the first standing wave between the boundary and the crack $T\approx 2H/c\approx 4.5$. That is why we calculate from \cref{fig:softGcqs_jump} only the initial crack speed at jump for comparison in \cref{tab:compjumpv}. A good agreement can be found between the numerical and the theoretic ones. \begin{table}[htbp] \centering \caption{Comparison of the numerically computed crack jump speed with the theoretic one \eqref{eq:vjump} given in \cite{DumouchelMarigoCharlotte:2008}} \label{tab:compjumpv} \begin{tabular}{llll} \toprule & Numerical & Theoretic & Error \\ \midrule Relative jump speed $v_\mathrm{jump}/c$ & 0.3325 & 0.3396 & 2\% \\ \bottomrule \end{tabular} \end{table} \subsection*{Conclusion} Further physical insights into the dynamic gradient damage model are provided via a simple antiplane tearing experiment. As a phase-field approach to brittle fracture, it can indeed be regarded as a generalization or a superset of the LEFM theory, since the crack evolution is shown to be Griffith-conforming in several situations: \begin{itemize} \item In the dynamic tearing example of a homogeneous plate, it is verified that the crack evolution is governed by the asymptotic Griffith's law (\cref{prop:whenellpetit}), as long as the material internal length is sufficiently small to establish a separation of scales between the inner damage problem and the outer LEFM problem. The conventional dynamic energy release rate is numerically computed and verified as a tool to translate gradient damage mechanics results in fracture mechanics terminology. We conducted a comparison with the 1-d peeling problem \cite{DumouchelMarigoCharlotte:2008} analytically studied with the classical Griffith's theory of dynamic fracture. A good agreement between them can be found in terms of the crack speeds prediction as a function of the loading speed. \item We then investigated the quasi-static limits of the dynamic gradient damage model. In the absence of \emph{brutal} or \emph{unstable} crack propagation when the classical static Griffith's theory fails, the dynamic model converges to the first-order quasi-static gradient damage model, when the loading speed decreases. However when the crack may propagate at a speed comparable to the material speed of sound, the dynamic model should be preferred in order to correctly account for inertial effects. The crack evolution in the dynamic gradient damage model is in quantitative accordance with the LEFM predictions on the 1-d peeling problem. \end{itemize} These numerical experiments provide hence a justification of the dynamic gradient damage model along with its current implementation, when it is used as a genuine physical model for complex real-world dynamic fracture problems. \section{Plane Crack Kinking} \label{sec:kinking} The three physical principles of \cref{def:dynagraddama} determine \emph{when} and \emph{how} the crack propagates. In \cref{sec:antiplane} the initiation and propagation phases of defect evolution are considered. According to \cref{sec:dynafrac}, it focuses on \emph{when} cracks propagate. In this section, we will focus on the path along which the crack propagates, \emph{i.e.} \emph{how} cracks evolve. Specifically, this section is devoted to a numerical analysis of plane crack kinking predicted by the gradient damage model. The thematic subjects covered here are thus summarized in \cref{tab:summkink}. \begin{table}[htbp] \centering \caption{Thematic subjects covered in this section} \label{tab:summkink} \begin{tabular}{ccccc} \toprule & Going dynamical & $\alpha\leftrightarrow\phi$ & $\nabla\alpha\to\Gamma$ & Experimental validation \\ \midrule Theoretics & & & & \\ Numerics & & & \rightthumbsup & \\ \bottomrule \end{tabular} \end{table} \paragraph{Problem setting} The problem setting is adapted from \cite{HakimKarma:2005,HakimKarma:2009}. We consider a unit disk centered at the origin $\Omega=B_1(\vec{0})$ subject to a mixed-mode hard device $\vec{U}(\overline{G},K_2/K_1)$ prescribed on its boundary $\partial\Omega$, see \cref{fig:kinking}. \begin{figure}[htbp] \centering \includegraphics[width=0.5\textwidth]{kinking_pb.pdf} \caption{Plane crack kinking problem in a pre-cracked unit ball centered at the origin $\Omega=B_1(\vec{0})$. A hard device $\vec{U}(\overline{G},K_2/K_1)$ is prescribed on the boundary $\partial\Omega$} \label{fig:kinking} \end{figure} An existing \emph{stationary} plane crack $\Gamma_0=[-1,0]\times\set{0}$ is modeled by an initial damage field via $\dvec^{-1}=1$ on $\Gamma_0$, see \cref{algo:init}. In the presence of this \emph{stationary} damage field $\alpha_0$, the elasto-static displacement corresponding to the mixed-mode Dirichlet condition $\vec{U}(\overline{G},K_2/K_1)$ is pre-computed and will be used as the initial condition for the subsequent dynamic calculation. For this problem the initialization procedure is summarized in \cref{algo:init2}. The dynamic analysis is performed in an interval $[0,T]$, while the external displacement $\vec{U}(\overline{G},K_2/K_1)$ is maintained constant. \begin{algorithm}[htbp] \caption{Initialization for the plane crack kinking problem adapted from \cref{algo:init}} \label{algo:init2} \begin{algorithmic}[1]\linespread{1.2}\selectfont\normalsize \State Given initial conditions $\uvec^0=\vec{0}$, $\dot{\uvec}^0=\vec{0}$ and $\dvec^{-1}=1$ on $\Gamma_0$. \State Reinitialize the damage by solving \[ \dvec^0=\operatorname{arg min}q_{\,\vec{0}}(\cdot)\text{ subjected to constraints $0\leq\dvec^{-1}\leq\dvec^0\leq 1$}. \] \State Initialize the displacement by solving the following elasto-static problem with the previously computed $\dvec^0$ \[ \uvec^0=\operatorname{arg min}\vec{F}_\mathrm{int}(\cdot,\dvec^0)-\vec{F}_\mathrm{ext}^0(\cdot). \] \State Initialize the acceleration $\vec{M}\ddot{\uvec}^0=\vec{F}_\mathrm{ext}^0-\vec{F}_\mathrm{int}(\uvec^0,\dvec^0)$. \end{algorithmic} \end{algorithm} The precise objective here is to compare the apparent kinking angle $\theta$ with several theoretic criteria commonly used in the Griffith's theory of fracture, cf. \cref{sec:theoexpcrit}. The prescribed displacement $\vec{U}(\overline{G},K_2/K_1)$ corresponds to the asymptotic expansion of the displacement field near the \emph{stationary} crack tip $\vec{P}_0=(0,0)$ with the opening and sliding intensity factors $K_1>0$ and $K_2\geq 0$, see \eqref{eq:singularform}. The plane stress condition is assumed. By virtue of Irwin's formula \eqref{eq:GasafunctionofK} the imposed energy release rate is given by \[ \overline{G}=\frac{K_1^2+K_2^2}{E}. \] Thanks to Griffith's law (\cref{prop:Ggriffithlaw,prop:whenellpetit}) in the gradient damage model as well as its numerical verification in \cref{sec:antiplane}, to ensure that the gradient-damage crack will indeed propagate to another point $\vec{P}^*$ under $\vec{U}$, the value of $\overline{G}$ should be larger than the effective material toughness $G_0>(\gc)_\mathrm{eff}$. To represent different types of mixed-mode loading, the ratio $K_2/K_1$ will be varied and its influence on the kinking behavior will be analyzed. A non-structured triangular mesh is used to discretize the domain $\Omega$. The damage constitutive law \eqref{eq:at1} is used. We use the explicit time stepping procedure outlined in \cref{algo:explicit} for the solving of the dynamic $(\vec{u},\alpha)$ problem. The material, loading and numerical parameters used in this problem are summarized in \cref{tab:kinking}. \begin{table}[htbp] \centering \caption{Material, loading and numerical parameters for the plane crack kinking experiment} \label{tab:kinking} \begin{tabular}{lllllll} \toprule $\rho$ & $E$ & $\nu$ & $\gc$ & $\eta$ & $\overline{G}$ & $h$ \\ \midrule 1 & 1 & 0.2 & 1 & 5\% or 1\% & 1.1 or 1.5 & $\eta/5$ \\ \bottomrule \end{tabular} \end{table} \paragraph{Simulation results and discussion} The dynamic evolution of the damage field $\alpha_t$ is indicated in \cref{fig:kinking_t}. An apparent crack kinking is observed due to the initial mixed-mode loading condition. \begin{figure}[htbp] \centering \includegraphics[width=0.9\textwidth]{kinking_G1x5_K0x6.pdf} \caption{Damage field evolution obtained with $\eta=1\%$ and $\overline{G}=1.5$ for $K_2/K_1=0.6$: (a) $t=0$, (b) $t=0.25$ and (c) $t=0.5$} \label{fig:kinking_t} \end{figure} Several simulations corresponding to different $K_2/K_1$ ratio are performed. Typical numerical results are illustrated by the damage field after kinking in \cref{fig:kinking_k2k1}. \begin{figure}[htbp] \centering \includegraphics[width=0.9\textwidth]{kinking_G1x5.pdf} \caption{Damage field obtained with $\eta=1\%$ and $\overline{G}=1.5$ for three $K_2/K_1$ ratios: (a) $K_2/K_1=0.6$, (b) $K_2/K_1=0.8$ and (c) $K_2/K_1=1$} \label{fig:kinking_k2k1} \end{figure} The apparent kinking angle predicted by the gradient damage model is compared in \cref{fig:kinking_comp} with several commonly used kinking criteria in fracture mechanics, see \cref{sec:theoexpcrit}. \begin{figure}[htbp] \centering \includegraphics[width=0.5\textwidth]{kinking_comp.pdf} \caption{Apparent kinking angle predicted by the gradient damage model compared with some commonly used kinking criteria in fracture mechanics} \label{fig:kinking_comp} \end{figure} The influence of the mixed-mode ratio $K_2/K_1$, the internal length $\ell$ and the intensity of the prescribed displacement $\overline{G}$ is analyzed as follows. \begin{itemize} \item Numerically obtained kinking angles are conforming to the theoretic predictions of several kinking criteria in fracture mechanics. In the isotropic case, the PLS, the $\sigma_{\theta\theta}$-max and the $G$-max criteria give similar kinking angles, see for instance \cite{ChambolleFrancfortMarigo:2009}. Anisotropy may be needed to distinguish between them, cf. \cite{HakimKarma:2005}. \item The internal length $\ell$, or equivalently the maximal stress \eqref{eq:sigc0}, again plays a subtle role here similarly to the antiplane problem in \cref{sec:antiplane}. From \cref{fig:kinking_comp}, the kinking angle shows little dependence with respect to the internal length used. This confirms that as long as the internal length is sufficiently small compared to that of the body, the gradient-damage crack behaves just like a real sharp-interface crack. \item The intensity $\overline{G}$ determines how brutal the kinking process is, which can be measured by the post-kink add-crack length $\delta l$. According to the simulation results, a smaller $\overline{G}$ produces also a smaller $\delta l$. However the kink angle seems independent of $\overline{G}$ in \cref{fig:kinking_comp}. \item By comparing the three figures in \eqref{fig:kinking_k2k1}, it can be observed that the mixed-mode ratio $K_2/K_1$ also determines how unstable the crack propagation is during the kink. In particular, a larger $K_2/K_1$ leads to a larger $\delta l$. This point needs further theoretical investigation in the future. \end{itemize} In this section the kinking of an initially stationary crack is analyzed by the gradient damage model. Dynamics are not expected to play an essential role during such process. For a crack propagating at a given velocity, the spatial path undertaken by the crack could be different (kinking and/or branching). Future work could be devoted to a thorough dynamic analysis of this problem. \section{Dynamic Crack Branching} \label{sec:branching} In this section we will study the dynamic crack branching problem for a 2-d plane stress glass plate under constant pressure applied on its upper and lower boundaries. This particular problem has already been investigated within the phase-field community \cite{BordenVerhooselScottHughesLandis:2012,SchlueterWillenbuecherKuhnMueller:2014} where the numerical convergence aspect as well as some physical insights into the branching mechanism are analyzed. Here in this work we will first focus on the computational efficiency of \cref{algo:explicit} implemented in the EPX software as well as the possible use of several damage constitutive laws to approximate fracture. This last strengthens the bridge between the phase-field and the gradient-damage communities. Finally we provide some fracture mechanics interpretations of the branching mechanism predicted in the gradient damage model. The thematic subjects covered here are thus summarized in \cref{tab:summbranching}. \begin{table}[htbp] \centering \caption{Thematic subjects covered in this section} \label{tab:summbranching} \begin{tabular}{ccccc} \toprule & Going dynamical & $\alpha\leftrightarrow\phi$ & $\nabla\alpha\to\Gamma$ & Experimental validation \\ \midrule Theoretics & & & & \\ Numerics & & \rightthumbsup & \rightthumbsup & \rightthumbsup \\ \bottomrule \end{tabular} \end{table} \paragraph{Problem setting} The geometry as well as the loading conditions are depicted in \cref{fig:branching}. \begin{figure}[htbp] \centering \includegraphics[width=0.55\linewidth]{plateres.pdf} \caption{Geometry and loading conditions for the dynamic crack branching problem. Damage field $\alpha_t$ at $t=\SI{8e-5}{s}$ ranging from 0 (gray) to 1 (white) obtained by the \eqref{eq:at1} model} \label{fig:branching} \end{figure} Due to symmetry only the upper half part is modeled. The initial crack $\Gamma_0$ is introduced via an initial damage field $\dvec^{-1}$. Material parameters are borrowed from \cite{BordenVerhooselScottHughesLandis:2012} where the internal length $\eta$ is set to $\SI{0.25}{mm}$. We use a structured quadrilateral elements of equal discretization spacing $h\approx\SI{0.045}{mm}$ in both directions achieving approximately 1 million elements. The current time increment is calculated based on the CFL condition with a security factor of 0.8. An unstructured mesh should be in general preferred. However the original analysis on mesh-induced anisotropy is conducted on structured triangular elements \cite{Negri:1999}. Furthermore the numerical study of \cite{LorentzGodard:2011} shows that the crack direction is insensitive to the orientation of a structured quadrilateral grids. We firstly use the damage constitutive law \eqref{eq:at1}. The symmetric tension-compression formulation is also adopted. This choice is justified by an \emph{a posteriori} verification of non-interpenetration of matter. The simulation result is illustrated in \cref{fig:branching} by the damage field $\alpha_t$ at $t=\SI{8e-5}{s}$ ranging from 0 (gray) to 1 (white). Similar contours have been obtained in \cite{BordenVerhooselScottHughesLandis:2012,SchlueterWillenbuecherKuhnMueller:2014}. \subsection{Computational efficiency in a parallel computing context} The parallel computing framework for the dynamic gradient damage model has been developed by the author in the EPX software \cite{EPX:2015}. A strong scaling analysis is here conducted for several processor cores $\mathrm{NP}$ in the cluster \texttt{ASTER5} provided by the Electricité de France. We have verified that all simulations give nearly the same results in terms of global energy evolution and field contours. The difference of the elastic energy at $t=\SI{8e-5}{s}$ is within 0.2\% between the sequential and the parallel $\mathrm{NP}=16$ cases, which may be due to floating point arithmetic and different setting of preconditioners. The scaling results are given in \cref{fig:scaling}. The calculation time is partitioned into 4 items: \begin{enumerate} \item The ``elastodynamics'' part related to the solving of \eqref{eq:waveeqsdis}, \item The ``damage assembly'' part where the global Hessian matrix $\vec{H}$ and the second member $\vec{b}$ is constructed, \item The ``damage solving'' part where \eqref{eq:crackstdis} is solved, \item The ``communication'' part corresponding to the data exchange among processors. \end{enumerate} The computational load is well balanced and the maximum value among all processors are used. Quasi-ideal scaling is observed for the total computational time. The proportion of the ``elastodynamics'' and the ``damage assembly'' parts are decreasing, due to the increase of the ``communication'' overhead reaching 15\% with 16 cores and becoming comparable to that of the ``damage solving''. \begin{figure}[htbp] \centering \includegraphics[width=0.5\linewidth]{plate_scaling.pdf} \caption{Strong scaling results for the dynamic crack branching problem with 1 million elements} \label{fig:scaling} \end{figure} We remark that the quadratic bound-constrained minimization problem \eqref{eq:crackstdis} solved by the GPCG scheme implemented in PETSc is not very costly and represents in sequential and parallel calculations only 13\% of the total computational time. In the phase-field literature the damage problem is often solved by an unconstrained minimization of \eqref{eq:crackstdis} corresponding to a linear system \eqref{eq:linearsystem}. The irreversibility condition is then approximated by several physical or numerical methods, see \cref{sec:phasefields}. However, it should be kept in mind that the above computationally-appealing strategy only applies to the damage constitutive law \eqref{eq:at2}, where the solution of \eqref{eq:linearsystem} lies necessarily between 0 and 1 and the objective functional \eqref{eq:qdiscrete} is indeed quadratic with respect to $\dvec$. Otherwise a specific numerical scheme for bound-constrained problems is needed. Nevertheless we would like to point out that the GPCG solver is extremely efficient even compared to the above strategy consisting of only one linear system. The same crack branching analysis is conducted using the damage constitutive model \eqref{eq:at2} and a same internal length $\eta=\SI{0.25}{mm}$, and the results obtained with the GPCG solver and the \emph{a posteriori} projection method described in \cref{sec:phasefields} are compared. In the latter case the same preconditioned conjugate gradient method is employed to solve \eqref{eq:linearsystem}. The results are slightly different as expected, since the projection method does not solve exactly the full minimization problem \eqref{eq:crackstdis}. To compare their relative computational costs, the time consumed in damage solving is separately normalized by that corresponding to the elastodynamic problem in \cref{tab:gpcg_vs_cg_proj}. \begin{table}[htbp] \centering \caption{Relative damage-solving cost normalized by the time devoted to the elastodynamic part during a parallel calculation $\mathrm{NP}=16$. The damage constitutive law \eqref{eq:at2} is used. Comparison between the GPCG solver and the \emph{a posteriori} projection method} \label{tab:gpcg_vs_cg_proj} \begin{tabular}{lll} \toprule & CG + projection & GPCG \\ \midrule Damage-solving cost & 50\% & 77\% \\ \bottomrule \end{tabular} \end{table} Opposed to what is suggested by \cite{AmorMarigoMaurini:2009}, the use of a bound-constrained minimization solver implies a relative computational cost only 27\% higher than a traditional linear solver. This can be seen in the normalized histogram of CG iterations per time step illustrated in \cref{fig:histcg}. We recall that each CG iteration implies a matrix-vector multiplication, the most costly part of the algorithm. When only one linear system is to be solved in the \emph{a posteriori} projection method, approximately 20 CG iterations are needed in 35\% of all time steps. When the GPCG solver is used, we observe that the histogram is more spread out and more than 50 CG iterations may be needed for some time steps. Nevertheless the distribution is more concentrated around 10 to 30 iterations. \begin{figure}[htbp] \centering \includegraphics[width=0.5\linewidth]{hist_cg_tao_vs_cg_proj.pdf} \caption{Normalized histogram of CG iterations per time step. The damage constitutive law \eqref{eq:at2} is used. Comparison between the GPCG solver and the \emph{a posteriori} projection method} \label{fig:histcg} \end{figure} \subsection{Comparison between two damage constitutive laws} We then turn to the choice of different damage constitutive laws from a computational and physical point of view. We take the simulation results using \eqref{eq:at1} as a reference and compare them with results obtained by the widely used damage constitutive law \eqref{eq:at2} in the phase-field modeling of fracture. The quantitative effects of the internal length actually depend on the damage constitutive model used. Here we propose two natural choices of $\ell$ in the \eqref{eq:at2} case: one corresponding to the same value $\eta=\SI{0.25}{mm}$ as used in the \eqref{eq:at1} case, the other corresponding to a same maximal tensile stress as used in the \eqref{eq:at1} case, which gives $\eta\approx\SI{0.07}{mm}$ according to \eqref{eq:sigc0} and \eqref{eq:gcingd}. The same GPCG solver is used and the relative damage-solving costs separately normalized by the time devoted to the elastodynamic part are reported in \cref{tab:at1_vs_at2}. \begin{table}[htbp] \centering \caption{Relative damage-solving cost normalized by the time devoted to the elastodynamic part during a parallel calculation $\mathrm{NP}=16$. The GPCG solver is used. Comparison between different constitutive laws} \label{tab:at1_vs_at2} \begin{tabular}{ll} \toprule & Damage-solving cost \\ \midrule \eqref{eq:at1} & 32\% \\ \eqref{eq:at2} with a same $\ell$ & 77\% \\ \eqref{eq:at2} with a same $\sigma_\mathrm{m}$ & 36\% \\ \bottomrule \end{tabular} \end{table} We remark that the use of the constitutive law \eqref{eq:at1} or a smaller internal length $\ell$ reduces significantly the \emph{relative} damage-solving cost. A viable explanation is given as follows. The theoretical 1-d damage profile of \eqref{eq:at2} corresponds to an exponential function without a finite support, see \eqref{eq:at2alpha}. The numerically obtained damage band, \emph{i.e.} in which $\alpha_t>0$, is much wider than in the \eqref{eq:at1} case \eqref{eq:at1alpha}. Consequently, less \emph{active} nodes are present and the GPCG solver identifies much more \emph{free} nodes for the \eqref{eq:at2} case, which induces a bigger linear system to be solved. Similarly, a reduction of the material internal length will imply finer mesh along the crack path (hence more computational cost in absolute values), however the damage is more concentrated and the \emph{relative} solving cost of \eqref{eq:crackstdis} is decreased. The damage field $\alpha_t$ at $t=\SI{8e-5}{s}$ obtained with the constitutive law \eqref{eq:at2} is illustrated in \cref{fig:at2_ell_sigm}. Recall that the same mesh with $h=\SI{0.05}{mm}$ is used and should be sufficient for both calculations. Compared to \cref{fig:branching} obtained with \eqref{eq:at1}, the \emph{transition area} where $0<\alpha_t<1$ is more pronounced especially in \cref{fig:at2_ell_sigm} with $\eta=\SI{0.25}{mm}$, conforming to the above discussions on the damage band. Another reason behind a relatively large zone with intermediate damage values is due to the different stress-strain behavior of these two constitutive laws during a homogeneous traction experiment discussed in \cref{sec:ingredients}. In the \eqref{eq:at1} case the material possesses a purely elastic domain and damage doesn't evolve as long as the maximal stress is not reached. Then the material follows a classical softening behavior as damage grows from 0 to 1. However for the constitutive law \eqref{eq:at2} widely used in phase-field modeling, damage evolves the instant when the material is subjected to external loadings. An elastic domain is absent and stress-hardening is observed within the interval $[0,\frac{1}{4}]$. In this case the phase-field $\alpha_t$ loses its physical interpretation as \emph{damage}, and hence correctly handling and interpreting crack healing is not trivial, see \cref{sec:phasefields}. \begin{figure}[htbp] \centering \includegraphics[width=0.9\textwidth]{AT2_ell_sigm.pdf} \caption{Damage field $\alpha_t$ at $t=\SI{8e-5}{s}$ ranging from 0 (blue) to 1 (red) for the dynamic branching problem. Comparison between (a) $\eta=\SI{0.25}{mm}$ and (b) $\eta\approx\SI{0.07}{mm}$ with the same constitutive model \eqref{eq:at2}} \label{fig:at2_ell_sigm} \end{figure} Furthermore, this peculiar behavior of the constitutive law \eqref{eq:at2} also contributes to an overestimation of the dissipated energy, as is noted in \cite{BordenVerhooselScottHughesLandis:2012,VignolletMayBorstVerhoosel:2014}. The energy evolution in this dynamic crack branching problem is given in \cref{fig:energy_at1_at2}. It is observed that the \eqref{eq:at2} law produces a dissipated energy much bigger than the \eqref{eq:at1} case, although according to \cref{fig:at2_ell_sigm} the damage fields are similar. \begin{figure}[htbp] \centering \includegraphics[width=0.5\linewidth]{damage_constitutive_laws.pdf} \caption{Energy evolution for the dynamic crack branching problem obtained with several constitutive laws} \label{fig:energy_at1_at2} \end{figure} As can be seen from \cref{fig:at2_ell_sigm,fig:energy_at1_at2}, apparently the results obtained with the same internal length $\ell$ resembles better the \eqref{eq:at1} calculation in \cref{fig:branching}, even though it corresponds to a smaller maximal stress than the latter case. It should be reminded that $\ell$ does not play merely the role of determination of the maximal stress as in \eqref{eq:sigc0}. From \cref{sec:linkDF,sec:antiplane,sec:kinking}, this parameter also contributes qualitatively to the separation of the outer linear elastic fracture mechanics problem and the inner crack tip problem in an asymptotic context. A smaller internal length implies a wider region outside the crack where the fracture mechanics theory may apply. We admit that the choice of this parameter is not a simple one and may constitute one of the difficulties in phase-field modeling of fracture problems. \subsection{Physical insights into the branching mechanism} \label{sec:microbrachingstu} Here a physical understanding of crack branching predicted by the dynamic gradient damage model is proposed. According to a brief discussion in \cref{sec:kinematics}, two different branching mechanisms can be distinguished \emph{a priori}. \begin{enumerate} \item The first one concerns micro-branching, where micro-cracks nucleate and propagate along the main crack. \item The second refers to macro-branching, where the main crack splits into two or more branches. \end{enumerate} However it is observed experimentally that macro-branching is always preceded by the micro-branching phenomenon. Using the terminology used in \cite{SharonFineberg:1996}, micro-branches corresponds to ``frustrated'' branching events while macro-branches are ``successful'' ones. It is experimental evidence that the microstructure of the crack surface, or equivalently the fracture process zone where nonlinearities dominate, plays an essential role during such branching events, see the pioneer work of \cite{Ravi-ChandarKnauss:1984,Ravi-ChandarKnauss:1984a} and a review of these aspects in \cite{FinebergMarder:1999}. In the presence of such events, from a macroscopic modeling viewpoint the main crack propagates with an ensemble of many interacting microcracks. More energy is thus dissipated due to the evolution of these micro-branches, see \cite{SharonGrossFineberg:1996}. In gradient damage models, the cross-section of a crack is modeled by a damage profile of a finite band proportional to the internal length, see \cref{sec:ingredients}. The fracture toughness $\gc$ can be identified by the energy consumed during the creation of an optimal damage profile \eqref{eq:defoptimaldamage} in a quasi-static setting, see \cref{sec:ingredients}. In dynamics, our numerical simulations indicate that in some circumstances the damage would develop a wider band across the gradient-damage crack, which results in an over-dissipation of energy. We suspect that this phenomenon could be considered as a macroscopic representation of micro-branching with the gradient-damage approach. In \cref{fig:micro-macro}, the final damage field obtained with the \eqref{eq:at1} model is indicated. Before a critical time $t_\mc$, the initial crack $\vec{P}_0$ propagates with an optimal damage profile $\alpha_*$. This kind of \emph{simple} propagation is theoretically and numerically investigated in \cref{sec:linkDF,sec:antiplane}. From a critical time $t_\mc$, we observe that the damage band across the crack is wider than the previous case. The continuous widening (micro-branching) eventually leads to the macro-branching of the main gradient-damage crack. \begin{figure}[htbp] \centering \includegraphics[width=0.6\linewidth]{plate-micro-macro.pdf} \caption{Distinction between micro and macro branching in gradient damage models} \label{fig:micro-macro} \end{figure} The damage profile at the initial crack tip $\vec{P}_0$ and at a crack tip after this critical time $t_\mc$ is compared with the optimal damage profile in \cref{fig:plate_alpha}. In the absence of micro-branching, the damage develops an optimal damage profile across the crack if the spatial discretization error (where $\alpha=1$ in an interval of width approximately $h$, see \eqref{eq:gceff}) is ignored, see \cref{sec:ellipticregul}. However during micro-branching, the damage band is even more widened. This implies an increased damage dissipation and may be considered to represent macroscopically the interaction of micro-branches. \begin{figure}[htbp] \centering \includegraphics[width=0.5\linewidth]{plate_alpha.pdf} \caption{Damage profile in absence (for instance at the initial crack tip $\vec{P}_0$) and in presence (for instance at a crack tip just after the critical time $t_\mc$) of micro-branching, compared with the optimal damage profile} \label{fig:plate_alpha} \end{figure} Now we propose to perform a zoom in time and in space at $t_\mc$ to better understand the physics behind the micro-branching event. Note that during microbranching the classical $\Gamma$-convergence estimation \eqref{eq:gammaconvergence} is no longer valid, since the damage profile varies along the main crack and not necessarily corresponds to the optimal damage profile \eqref{eq:defoptimaldamage}. It may only be used to estimate the current energy dissipation rate normalized by the quasi-static fracture toughness \begin{equation} \label{eq:circl} \overset{\circ}{l}_t=\frac{\dot{\mathcal{S}}_t}{(\gc)_\mathrm{eff}} \end{equation} where spatial discretization effect is taken into account, see \eqref{eq:gceff}. The current location of the main crack given by its length $l_t$ is tracked on the contour $\alpha_t(l_t,0)=0.95$, where $y=0$ refers to the propagation path. The current crack velocity $\dot{l}_t$ is then deduced by applying a second-order difference scheme. The comparison between $\overset{\circ}{l}_t$ and $\dot{l}_t$ is illustrated in \cref{fig:plate-v}. \begin{figure}[htbp] \centering \includegraphics[width=0.5\linewidth]{plate_v.pdf} \caption{Crack velocity evolution derived from the dissipated energy $\mathcal{S}$ using \eqref{eq:circl} or from the contour where $\alpha_t(l_t,0)=0.95$. $A$ denotes an instant before micro-branching, $B$ denotes the onset of micro-branching and $C$ refers to the macro-branching event} \label{fig:plate-v} \end{figure} Several remarks are given below. \begin{itemize} \item Before micro-branching (for example at the point $A$), these two estimations give the same crack velocity. It implies that in the absence of micro-branching a dynamic gradient-damage crack also dissipates the same amount of energy when propagating. This energy dissipation corresponds again to the creation of an optimal damage profile \eqref{eq:defoptimaldamage}. \item From the point $B$ or for $t>t_\mathrm{c}$, these two estimations of the crack velocity diverge quickly. This point $B$ or the time $t_\mc$ marks the onset of micro-branching. From this point, the value of $\overset{\circ}{l}_t$ no longer measures the crack speed but only a normalized total energy dissipation due to crack propagation. According to \eqref{eq:circl}, much more energy is dissipated during the propagation of the main crack $l_t$, while its velocity $\dot{l}_t$ is well below a fraction (60\%) of the Rayleigh wave speed $c_\mathrm{R}$. In this work, we share the viewpoint announced in \cite{SharonFineberg:1996} that a lower limiting fracture velocity compared to the Griffith's theory (see \cref{sec:theoexpcrit}) can be attributed to an energy over-dissipation due to micro-branching. This leads to the definition of a velocity dependent apparent fracture toughness $\Gamma(\dot{l}_t)$ for the main crack, see \cite{SharonFineberg:1996,SharonFineberg:1999}. Note that $\Gamma(\dot{l}_t)$ is only apparent for a single macroscopic crack containing an ensemble of interacting micro-cracks. It measures the total surface creation due to not only the main crack but also micro-cracks nucleated along the previous one. However the real energy dissipated per unit crack surface creation is still constant and is given by the quasi-static $\gc$, see \cite{SharonFineberg:1996}. \item The critical velocity $v_\mc$ above which the main crack develops micro-branches is approximately $v_\mc=\SI{0.4}{c_\mathrm{R}}$. This value agrees with the experimental evidence reported for brittle materials such as PMMA in \cite{FinebergGrossMarderSwinney:1992a}. A comprehensive review on the microbranching mechanism can be found in \cite{FinebergMarder:1999}. The gradient damage model provides thus a better modeling of the critical velocity than several theoretical approaches based on a sharp-interface crack without microbranch interaction (approximately $0.6c_\mathrm{R}$ according to Yoffe, see \cref{fig:yoffe} and $0.46c_\mathrm{R}$ obtained in \cite{KatzavAdda-BediaArias:2007}). This confirms the viewpoint shared in \cite{Ravi-Chandar:1998} that the determination of the critical speed itself $v_\mc$ calls for a theory of process zone describing nonlinear material behaviors near the crack tip. The gradient damage approach seems to be a good candidate. \end{itemize} The next objective is to investigate stress distribution before and at the onset of micro-branching. In particular, the hoop (circumferential) stress $\sigma_{\theta\theta}$ is analyzed near the current crack tip. Its evolution as a function of the distance to the crack $r$ and as a function of the angle $\theta$ with respect to the propagation direction ($x$-axis) are separately considered. For the latter case, at several distances $r$ from the crack tip, the hoop stresses are separately normalized by their values at $\theta=0$ which gives \[ \Sigma_\mathrm{H}(r,\theta)=\frac{\sigma_{\theta\theta}(r,\theta)}{\sigma_{\theta\theta}(r,0)}. \] The angular variation of these normalized hoop stresses $\Sigma_\mathrm{H}$ will be compared to the asymptotic expansion of the stress tensor in the Griffith's theory (LEFM) given in \eqref{eq:singularform}, where the current crack speed $\dot{l}_t$ derived from the gradient damage crack tip is used in the angular functions $\vec{\Theta}_i(\theta,\dot{l})$. A least-square analysis is performed to identify the possible $\widehat{K}_\RNN{2}=K_\RNN{2}/K_\RNN{1}$ perturbation in the simulation. The hoop stress variation situated at $r=D$ is used for such analysis, since according to the analysis in \cref{sec:asymptotic} the stress outside the damage process zone contributes to the fracture behavior of the material. Before the micro-branching event we consider an arbitrary instant $A$ in \cref{fig:plate-v} where the current crack speed $\dot{l}_t=0.26c_\mathrm{R}$). The hoop stress distribution is indicated in \cref{fig:SigT200}. To normalize the spatial distance, the damage band $D=2\eta$ is used. \begin{figure}[htbp] \centering \includegraphics[width=\linewidth]{SigT200.pdf} \caption{Hoop stress distribution before micro-branching: (a) dependence on the distance to the crack $r$ and (b) dependence on the angle $\theta$ with respect to the propagation direction. To normalize the spatial distance, the damage band $D=2\eta$ is used} \label{fig:SigT200} \end{figure} Several remarks are given below. \begin{itemize} \item Contrary to the Griffith's theory, the stress tensor is no more singular at the ``crack tip'', see also \cref{fig:stress}. The hoop stress is maximized just outside the damage band at $r\approx D=2\eta$. \item Mode-II perturbation is not detected and the angular variation matches perfectly with the linear elastic Griffith's theory in particular for $r>D$, \emph{i.e.} outside the damage process zone. The gradient-damage crack just behaves like a Griffith crack similar to the antiplane experiment in \cref{sec:antiplane} and a separation between the outer linear elastic problem and the inner damage crack tip problem can be achieved. The curve at $r=0.5D$ is situated a little above the theoretic prediction, hence the $r$-dependence and the $\theta$-dependence of the stress tensor is no longer decoupled compared to the linear elastic prediction \eqref{eq:singularform}. It can be verified that the stress is indeed maximal in front of the crack tip at $\theta=0$. \end{itemize} At the onset of microbranching $t\approx t_\mc$, two arbitrary but close instants near point $B$ in \cref{fig:plate-v} are chosen and the normalized hoop stress distribution is indicated in \cref{fig:SigMB}. \begin{figure}[htbp] \centering \includegraphics[width=\linewidth]{SigMB.pdf} \caption{Normalized hoop stress distribution at the onset of micro-branching: (a) $\dot{l}_t\approx 0.36c_\mathrm{R}$ and (b) $\dot{l}_t\approx 0.43c_\mathrm{R}$} \label{fig:SigMB} \end{figure} Compared to situation at point $A$, several qualitative behaviors of the stress distribution near the crack tip are noteworthy. Using the angular variation at $r=D$, a slight mode-II perturbation $\widehat{K}_\RNN{2}\approx 0.09$ is detected at the onset of microbranching, \emph{i.e.} a loss of symmetry. The existence of such perturbations may be due to structural effects and has already been observed in dynamic fracture experiments, see \cite{BoueCohenFineberg:2015}. A mode-II component in the stress tensor contributes to the crack branching instability, but it is not taken into account in many theoretic approaches to crack branching. From \cref{fig:SigMB}, we observe that the maximum of the normalized hoop stress begins to deviate from the propagation direction $\theta=0$, especially for the curve $r=0.5D$. This indicates that the microbranching phenomenon satisfies a generalized Yoffe's criterion, since in gradient damage models the angular variation depends also on the distance $r$ to the crack. Such criterion should be only considered as a necessary condition of crack branching. However it could be used to indicate a possible crack branching event. Only mode-I asymptotic expansions are considered in the original Yoffe's criterion, which leads to a higher branching speed $v_\mc\approx 0.6c_\mathrm{R}$. According to \cref{fig:SigMB}, this critical velocity can be reduced by including a mode-II perturbation. \subsection*{Conclusion} The dynamic gradient damage model could be computationally more demanding compared to traditional approaches based on a sharp description of cracks. Griffith's law combined with specialized numerical methods could perform reasonably well with much less computational cost for fracture problems in the absence of crack nucleation and complex topology changes. The major advantage of phase-field modeling reside in its generality in treating 2d and 3d crack evolution problems by providing a unified framework from onset to structural failure. Thanks to an efficient parallelization of the solving algorithm (\cref{algo:explicit}), the computing time can also be significantly reduced as demonstrated in \cref{fig:scaling}. Two particular damage constitutive laws \eqref{eq:at2} and \eqref{eq:at1} are compared both from a computational and physical point of view. On one hand, the widely used crack surface density function \eqref{eq:at2} is less suitable to model brittle fracture since an elastic domain is absent. On the other hand the actual solving of the damage minimization problem \eqref{eq:crackstdis} is more costly than the damage constitutive law \eqref{eq:at1} which possesses an optimal damage profile of finite band. It is also illustrated that the cost of a general quadratic bound-constrained minimization solver (GPCG) is acceptable. Finally a better understanding of crack branching predicted by the dynamic gradient damage model is provided. The nucleation of micro-cracks and their subsequent interaction with the main crack is macroscopically identified by a widening of the damage profile perpendicular to the gradient-damage crack. Through numerical simulations, a critical velocity $v_\mc\approx 0.4c_\mathrm{R}$ is detected above which micro-branching events take place, which implies an over-dissipation of energy as the main crack propagates. This critical velocity agrees with the experimental findings and gives a better prediction compared to other theoretical approaches based on a sharp-interface description of cracks which neglects the nonlinear fracture process zone near the crack tip. Before microbranching, the stress distribution agrees well with the Griffith's theory especially outside the damage process zone with a pure mode-I contribution. However at the onset of microbranching, a mode-II component perturbs the stress distribution. It provides a necessary condition toward an explanation of the branching instability reproduced by the dynamic gradient damage model. Future work will be devoted to a thorough theoretic investigation of this point. In particular, the exact role played by the internal length should be analyzed. \section{Edge-Cracked Plate Under Shearing Impact} \label{sec:kalthoff} We consider in this section a pre-notched two-dimensional plane strain plate impacted by a projectile. In the dynamic fracture community this is often referred as the Kalthoff-Winkler experiment reported by \emph{e.g.} \cite{Kalthoff:2000} where a failure mode transition from brittle to ductile fracture is observed for a high strength maraging steel when the impact velocity is increased. The objective here is to investigate the use of several tension-compression asymmetry formulations analyzed in \cref{sec:TC} in a dynamic brittle fracture problem. In particular, the widely used elastic energy density split proposed in \cite{MieheHofackerWelschinger:2010} among the phase-field community will be compared with other models. Furthermore, some dynamic fracture phenomena reproduced by the gradient damage model are also presented. The thematic subjects covered here are thus summarized in \cref{tab:summkalthoff}. \begin{table}[htbp] \centering \caption{Thematic subjects covered in this section} \label{tab:summkalthoff} \begin{tabular}{ccccc} \toprule & Going dynamical & $\alpha\leftrightarrow\phi$ & $\nabla\alpha\to\Gamma$ & Experimental validation \\ \midrule Theoretics & & & & \\ Numerics & & \rightthumbsup & \rightthumbsup & \rightthumbsup \\ \bottomrule \end{tabular} \end{table} \paragraph{Problem setting} Due to symmetry, only the upper half part of the plate will be considered. The geometry and the boundary conditions for the reduced problem are described in \cref{fig:kalthoff}. \begin{figure}[htbp] \centering \includegraphics[width=0.45\linewidth]{kalthoff.pdf} \caption{Geometry and boundary conditions for the edge-cracked plate under shearing impact problem. Damage field $\alpha_t$ at $t=\SI{8e-5}{s}$ ranging from 0 (gray) to 1 (white)} \label{fig:kalthoff} \end{figure} As in \cite{BordenVerhooselScottHughesLandis:2012,HofackerMiehe:2012}, the projectile impact is modeled by a prescribed velocity with an initial rise time of \SI{1e-6}{s} to avoid velocity shocks. The material parameters are borrowed from \cite{BordenVerhooselScottHughesLandis:2012} except that the internal length $\eta$ is set to $\SI{0.2}{mm}$. An unstructured and uniform triangular mesh with $h\approx \SI{0.1}{mm}$ is used, arriving at approximately 3 million elements. The explicit time-stepping (\cref{algo:explicit}) implemented in the EPX software is adopted. The current time increment is again calculated based on the CFL condition with a security factor of 0.8. Due to a lower computational cost and a more brittle material behavior, the damage constitutive law \eqref{eq:at1} is used for this simulation. As a reference, we use the elastic energy split proposed in \cite{FreddiRoyer-Carfagni:2010} where the positive semidefinite part of the total strain will contribute to damage. The initial crack is introduced via a real notch in the geometry. A similar strong scaling curve as \cref{fig:scaling} is obtained with up to 16 cores, see \cref{fig:kalscaling}. \begin{figure}[htbp] \centering \includegraphics[width=0.5\linewidth]{kalthoff_scaling.pdf} \caption{Strong scaling results for the Kalthoff problem with 3 million elements} \label{fig:kalscaling} \end{figure} Due to the additional spectral decomposition, the ``damage assembly'' phase represents now approximately 50\% of the total computational time while the ``damage solving'' still accounts for only 10\%. The actual computation of the eigenvalues and eigenvectors of a $3\times 3$ symmetric matrix is described in \cref{sec:implementation}. The energy evolution obtained by varying the number of processors is indicated in \cref{fig:kalenergy}. \begin{figure}[htbp] \centering \includegraphics[width=0.5\linewidth]{kalthoff_energies_NP.pdf} \caption{Energy evolution obtained by varying the number of processors} \label{fig:kalenergy} \end{figure} Similar to \cref{sec:branching}, small differences can be observed between these parallel computations in terms of global energy evolution, which may be again due to floating point arithmetic and different setting of preconditioners. With an imposed impact speed $v=\SI{16.5}{m/s}$, the damage field $\alpha_t$ at $t=\SI{8e-5}{s}$ produced by the EPX software is depicted in \cref{fig:kalthoff}. The initial (\SI{73}{\degree}) and average (\SI{64}{\degree}) propagation angles are in good agreement with the experimental results and other phase-field simulations \cite{BordenVerhooselScottHughesLandis:2012,HofackerMiehe:2012} based on the damage constitutive law \eqref{eq:at2} and the tension-compression asymmetry formulation proposed by \cite{MieheHofackerWelschinger:2010}. \subsection{Gradient-damage modeling of dynamic fracture} If the initial crack $\Gamma_0$ is modeled via an initial damage field $\alpha^{-1}$, as for the previous dynamic crack branching example, no crack propagation is observed and the structures behaves as if the crack does not exist, \emph{i.e.} the crack closure phenomenon. The horizontal displacement $u_x$ obtained in both cases at $t\approx\SI{2.4e-5}{s}$ when the real notch case starts to propagate is presented in \cref{fig:alpha0}. \begin{figure}[htbp] \centering \includegraphics[width=0.9\textwidth]{alpha0.pdf} \caption{Displacement $u_x$ ranging from \SI{0}{mm} (blue) to \SI{0.4}{mm} (red) for (a) the real notch induced initial crack and (b) the damage induced initial crack, at $t\approx\SI{2.4e-5}{s}$ when the crack starts to propagate in the real notch case (a)} \label{fig:alpha0} \end{figure} In the real notch induced initial crack case, \emph{contact condition is not prescribed} on the initial crack lips distanced by a finite height $\approx h$ in the geometry. As can be checked from \cref{fig:alpha0}, no material interpenetration happens in the real notch case and waves propagate in the plate through the lower impacted edge. However in the damage induced initial crack case, possible normal compressive stresses can indeed be transferred to the upper part of the plate, via the tension-compression asymmetry model \cite{FreddiRoyer-Carfagni:2010} which simulates a crack closure. Nevertheless, our simulation illustrates that this model also prohibits tangential relative movement along the crack lips, and a \emph{perfect adhesion} (no-slip condition) is observed, \emph{i.e.} exactly the opposite situation compared to the real notch case. This result is expected from our discussions on future improvement of these tension-compression formulations in \cref{sec:howtochoose}. The failure of these elastic energy decompositions to account for the actual damage value or its gradient approximating the crack normal has been reported by \cite{MayVignolletBorst:2015,Strobl:2015aa}. In the subsequent discussions we will only consider the case where the initial crack is introduced via a real notch in the geometry. The numerically obtained damage profile on a cross-section in the reference configuration parallel to the crack normal is compared to the theoretical one \eqref{eq:at1alpha}. From \cref{fig:damageprofile}, it can be observed that the numerical damage profile is wider than the analytical prediction by approximately $h=\SI{0.1}{mm}$. This phenomena leads to the definition of a numerically amplified effective fracture toughness $(\gc)_\mathrm{eff}$, see \eqref{eq:gceff}, which in this example is given by $(\gc)_\mathrm{eff}=\bigl(1+3h/(8\eta)\bigr)\gc$ corresponding to the constitutive law \eqref{eq:at1} adapted from \cite{HossainHsuehBourdinBhattachary:2014}. \begin{figure}[htbp] \centering \includegraphics[width=0.5\linewidth]{kalthoff_alpha.pdf} \caption{Damage profile perpendicular to the crack} \label{fig:damageprofile} \end{figure} Assuming that micro-branching does not take place, from the $\Gamma$-convergence result the crack length $l_t$ can be estimated by \eqref{eq:gammaconvergence}. A 2nd-order difference scheme is then used to calculate the crack velocity. The temporal evolution of the crack length and the velocity is indicated in \cref{fig:crack_length_speed}. \begin{figure}[htbp] \centering \includegraphics[width=0.55\linewidth]{kalthoff_length_speed.pdf} \caption{Crack length and velocity obtained for the edge-cracked plate with an imposed impact speed $v=\SI{16.5}{m/s}$} \label{fig:crack_length_speed} \end{figure} As can be seen from \cref{fig:crack_length_speed}, the crack speed is well bounded by the Rayleigh wave speed (here $0.7c_\mathrm{R}$), the theoretical limiting speed for an in-plane crack. It should be noted that this upper bound is rooted in the stability condition \eqref{eq:vi} and the energy balance \eqref{eq:dyngdeb}, contrary to the thick level set approach \cite{MoreauMoesPicartStainier:2015} where this limiting speed is considered as an additional modeling parameter. The crack length is approximately \SI{90}{mm} at $t=\SI{8e-5}{s}$ when the crack is about to reach the boundary, cf. \cref{fig:kalthoff}. This estimation agrees fairly well with a direct calculation based on a straight crack propagating at \SI{64}{\degree}, which gives about \SI{83}{mm}. We believe that the discrepancy on crack length as well as a smaller limiting speed for brittle materials reported in experiments can be attributed to the dynamic instability mechanism reviewed in \cite{FinebergMarder:1999} and discussed in this work in \cref{sec:microbrachingstu}. As the crack speed approaches a critical speed approximately $0.4c_\mathrm{R}$, micro-branches appear along the main crack and hence more energy is dissipated during propagation. In that case \eqref{eq:gammaconvergence} is no longer valid and the apparent fracture toughness should be adapted to be velocity-dependent. With the \eqref{eq:at2} constitutive law, authors of \cite{BordenVerhooselScottHughesLandis:2012,VignolletMayBorstVerhoosel:2014} report a systematic overestimation of the damage dissipation energy with \eqref{eq:gammaconvergence}. Following our discussion in \cref{sec:branching}, it could be mainly due to the absence of a purely elastic domain and the fact that damage evolves even in the stress-hardening phase. However in the definition of the fracture toughness, this phenomena is not taken into account, see \cite{BourdinFrancfortMarigo:2008}. \subsection{Velocity effect and use of different tension-compression models} When the prescribed impact velocity is increased from $v=\SI{16.5}{m/s}$ to $v=\SI{100}{m/s}$, successive crack branching and nucleation of cracks at the lower-right corner due to high tensile stresses are observed as can be seen from \cref{fig:v1d5}. The hydrostatic stress $p_t=\frac{1}{2}\tr\sig_t$ is presented in the deformed configuration and we verify that no damage is produced in the compression zones. To visualize the crack, elements with $\alpha_t>0.9$ are hidden in the graphical output. Similar phenomena have been reported in \cite{HofackerMiehe:2012} with $v=\SI{50}{m/s}$. Recall that in the Kalthoff-Winkler experiment a failure-mode transition from mode-\RNN{1} to mode-\RNN{2} is observed when the impact velocity increases. The discrepancy between our simulation and the experiment is due to the material constitutive behavior. As a material parameter, the tension-compression formulation of \cite{FreddiRoyer-Carfagni:2010} coupled with a purely elastic model favors propagation of mode-\RNN{1} cracks in the direction perpendicular to the maximal principle stress. On the contrary, the high strength steel used in the experiment develops a considerable plastic zone along the mode-\RNN{2} crack and an elastic-plastic-damage model should be more suitable, see for example the work of \cite{MieheHofackerSchaenzelAldakheel:2015}. Nevertheless, experimentally more bifurcations are indeed observed for brittle materials such as glass when the impact velocity is increased, which is known as a \emph{velocity effect} in \cite{Schardin:2012}. \begin{figure}[htbp] \centering \includegraphics[width=0.9\textwidth]{kalthoff_TC6.pdf} \caption{Simulation results at $t=\SI{4e-5}{s}$ with an impact speed $v=\SI{100}{m/s}$: (a) the damage field $\alpha_t$ ranging from 0 (blue) to 1 (red), and (b) the hydrostatic stress $\frac{1}{2}\tr\sig_t$ ranging from less than \SI{-1e4}{MPa} (blue) to more than \SI{1.5e3}{MPa} (red). The tension-compression asymmetry model \cite{FreddiRoyer-Carfagni:2010} is used} \label{fig:v1d5} \end{figure} On the other hand, the widely used elastic energy density split proposed in \cite{MieheHofackerWelschinger:2010} produces diffusive damage in compression zones. From \cref{fig:v1d5_miehe}, we observe appearance of damage at the lower-left corner and at the lower surface of the initial crack edge, even though they are both under compression. This phenomena is conforming to our previous theoretical analysis of this model on a homogeneous uniaxial compression experiment in \cref{sec:uniaxial}, where it is found that damage grows even though the compressive stress is still increasing in its absolute value. \begin{figure}[htbp] \centering \includegraphics[width=0.9\textwidth]{kalthoff_TC5.pdf} \caption{Simulation results at $t=\SI{4e-5}{s}$ with an impact speed $v=\SI{100}{m/s}$: (a) the damage field $\alpha_t$ ranging from 0 (blue) to 1 (red), and (b) the hydrostatic stress $\frac{1}{2}\tr\sig_t$ ranging from less than \SI{-1e4}{MPa} (blue) to more than \SI{1.5e3}{MPa} (red). The tension-compression asymmetry model \cite{MieheHofackerWelschinger:2010} is used} \label{fig:v1d5_miehe} \end{figure} The tension-compression split based on the trace of the total strain \cite{AmorMarigoMaurini:2009} is also tested. In \cite{LancioniRoyer-Carfagni:2009}, the pure compression version of this model is used to simulate shear cracking behavior in the stone ashlars. In this dynamic impact problem, we also observe at $t\approx\SI{7e-6}{s}$ appearance of mode-\RNN{2} cracks originating from the impacted-edge, see \cref{fig:TC2}. We conclude that the tension-compression split \eqref{eq:elasticTC} could indeed be considered as a material parameter as it represents the fracture mechanism determined by the microstructure and leads to different macroscopic fracture patterns. Note however that the calculation suddenly stops after that time due to an extremely small CFL time step $\Delta t_\mathrm{CFL}=h/c$, which is caused by a highly distorted element $h\to 0$ in the explicit dynamics context. The same numerical issue has been reported by \cite{PieroLancioniMarch:2007} in which an Ogen hyperelastic model is used. Remark that the use of a tension-compression split based on the positive eigenvalues of the strain, \emph{i.e.} that of \cite{MieheHofackerWelschinger:2010,FreddiRoyer-Carfagni:2010}, actually circumvents this problem by revising the material constitutive behavior. \begin{figure}[htbp] \centering \includegraphics[height=5cm]{TC2_v1d5_alpha.png} \caption{Damage field at $t\approx\SI{7e-6}{s}$ obtained for the edge-cracked plate with an imposed impact speed $v=\SI{100}{m/s}$. The elastic energy split \cite{AmorMarigoMaurini:2009} is used} \label{fig:TC2} \end{figure} \subsection*{Conclusion} Different tension-compression asymmetry formulations in \cref{sec:TC} are analyzed numerically here. Some physical properties derived through a uniaxial traction experiment are verified in actual dynamic fracture problems. The elastic energy split proposed by \cite{FreddiRoyer-Carfagni:2010} is recommended for brittle materials because homogeneous (diffusive) damage does not occur under compression. However these models should be modified to correctly account for the unilateral contact condition. A better strategy may be to use a transition algorithm between the smeared and the sharp-interface description of cracks. To successfully model the transition from mode-I to mode-II, one may need to couple a plasticity model with the current dynamic gradient damage model. \section{Crack Arrest Due to the Presence of a Hole} \label{sec:gregoire} This section is devoted to a two-dimensional experimental validation of the dynamic gradient damage model for brittle materials. The thematic subjects covered here are thus summarized in \cref{tab:summhole}. \begin{table}[htbp] \centering \caption{Thematic subjects covered in this section} \label{tab:summhole} \begin{tabular}{ccccc} \toprule & Going dynamical & $\alpha\leftrightarrow\phi$ & $\nabla\alpha\to\Gamma$ & Experimental validation \\ \midrule Theoretics & & & & \\ Numerics & & & & \rightthumbsup \\ \bottomrule \end{tabular} \end{table} \paragraph{Problem setting} The problem considered is the ``one crack two holes'' test studied in \cite{HaboussaGregoireElguedjMaigreCombescure:2011}, where it is found that in dynamics cracks may be pushed away from the holes present in the domain due to wave reflections. The geometry and the boundary conditions are recalled in \cref{fig:gregoire}. \begin{figure}[htbp] \centering \includegraphics[width=0.7\linewidth]{gregoire.pdf} \caption{Geometry and boundary conditions for the ``one crack two holes'' experiment studied in \cite{HaboussaGregoireElguedjMaigreCombescure:2011}. Damage field $\alpha_t$ at $t=\SI{2e-4}{s}$ ranging from 0 (gray) to 1 (white)} \label{fig:gregoire} \end{figure} Plane stress condition is assumed. Initial crack is introduced via a real notch in the geometry. The damage constitutive law \eqref{eq:at1} is used again due to its interesting properties discussed in the dynamic crack branching problem. Since PMMA is a brittle material \cite{GregoireMaigreRethoreCombescure:2007} and the model of \cite{MieheHofackerWelschinger:2010} possesses a peculiar behavior under high compression, the tension-compression asymmetry formulation proposed by \cite{FreddiRoyer-Carfagni:2010} is adopted. Materials properties of PMMA, including the density, the dynamic Young's modulus and the Poisson ratio, are borrowed from \cite{HaboussaGregoireElguedjMaigreCombescure:2011}. In their calculations, crack propagation is based on a variant of the Griffith's law where one critical stress intensity factor $K_\mathrm{IC}=\SI{1.03}{MPa\sqrt{m}}$ predicts initiation and another $K_\mathrm{IA}=\SI{0.8}{MPa\sqrt{m}}$ determines crack propagation and arrest. The latter one is used in our calculation as it deals with the most important phase of crack evolution. It is then converted to the fracture toughness \begin{equation} \label{eq:pmmagc} \gc=\frac{K_\mathrm{IA}^2}{E}\approx\SI{0.2667}{N/mm} \end{equation} thanks to the Irwin's formula under plane stress condition. The material internal length, or equivalently the maximal tensile stress of PMMA through \eqref{eq:sigc0}, is unknown. Two reasonable values are tested corresponding respectively to a critical stress $\SI{70}{MPa}$ or $\SI{80}{MPa}$, which gives along with \eqref{eq:pmmagc} either $\eta\approx\SI{0.05}{mm}$ or $\eta\approx\SI{0.0375}{mm}$. An unconstrained mixed triangular-quadrilateral mesh refined with $h\approx\SI{2e-2}{mm}$ near the initial crack and all possible nucleation sites is used, arriving at approximately \num{400000} elements. The explicit time-stepping (\cref{algo:explicit}) implemented in the EPX software is adopted. The current time increment is updated based on the CFL condition with a security factor of 0.8. \paragraph{Simulation results and discussion} The simulations results are illustrated in \cref{fig:siggregoire}. \begin{figure}[htbp] \centering \includegraphics[width=\textwidth]{gregoire_7080.pdf} \caption{Hydrostatic stress $p_t=\frac{1}{2}\tr\sig_t$ ranging from less than \SI{-30}{MPa} (blue) to more than \SI{30}{MPa} (red) for (a) $\sigma_\mathrm{m}=\SI{70}{MPa}$ at $t\approx\SI{1.6e-4}{s}$, and (b) $\sigma_\mathrm{m}=\SI{80}{MPa}$ at $t\approx\SI{1.8e-4}{s}$, in the crack arrest problem} \label{fig:siggregoire} \end{figure} In both cases crack arrest is reproduced due to the high compression area under the right circular hole. In the case when the maximal tensile stress is set to $\sigma_\mathrm{m}=\SI{70}{MPa}$, secondary crack nucleation is observed at the right circular hole boundary under high tension. This phenomena is not observed in experiments and hence the critical stress value of $\sigma_\mathrm{m}=\SI{70}{MPa}$ is thus underestimated. In the $\sigma_\mathrm{m}=\SI{80}{MPa}$ case, no secondary crack nucleation is found. This result again highlights the role played by the internal length $\ell$ as a material parameter. \begin{figure}[htbp] \centering \includegraphics[width=0.5\linewidth]{gregoire_cracktip.pdf} \caption{Crack tip abscissa evolution in the crack arrest problem. Comparison between the $\sigma_\mathrm{m}=\SI{80}{MPa}$ case and the experimental results} \label{fig:cracktip} \end{figure} As the crack front is not explicitly tracked in phase-field modeling of fracture, here the current crack tip is located on the contour $\alpha=0.9$ at the farthest point in the $x$-direction. We then compare the numerical crack tip abscissa evolution with the experimental one \cite{HaboussaGregoireElguedjMaigreCombescure:2011}, in \cref{fig:cracktip}. Very good agreement can be found in the crack initiation and propagation phase. The crack arrest predicted is slightly conservative compared to the experimental one. This could be due to the small deviation of the initial crack from the symmetry axis in the experiment \cite{HaboussaGregoireElguedjMaigreCombescure:2011}. Meanwhile the maximal tensile stress $\sigma_\mathrm{m}\geq\SI{80}{MPa}$ could be considered as an adjusting parameter of the model. More simulations could be performed to determine its best value, at a price of using a more refined mesh since $\ell\propto1/\sigma_\mathrm{m}^2$ according to \eqref{eq:sigc0}. \paragraph{Conclusion} The dynamic gradient damage model outlined in \cref{def:dynagraddama} along with the \eqref{eq:at1} damage constitutive law and the tension-compression model of \cite{FreddiRoyer-Carfagni:2010} is experimentally validated for PMMA specimens. Further studies will focus on applications to concrete structures. \section{Brazilian Splitting Test on Concrete Cylinders} \label{sec:brazilian} This section is devoted to three-dimensional numerical simulations of the Brazilian tests on concrete cylinders. Due to an increasing compressive load applied along the diameter direction, eventually fracture takes place along the loading direction and the cylinder splits vertically into two parts. One objective here is to verify the EPX implementation of the explicit time-stepping procedure summarized in \cref{algo:explicit} during a three-dimensional calculation. Furthermore, different tension-compression asymmetry formulations analyzed in \cref{sec:TC} are compared with respect to their aptitude to reproduce such fracture pattern. The size effect reported by various authors such as \cite{RoccoGuineaPlanasElices:1999,RuizOrtizPandolfi:2000} is also investigated using the dynamic gradient damage model. The thematic subjects covered here are thus summarized in \cref{tab:summbrazilian}. \begin{table}[htbp] \centering \caption{Thematic subjects covered in this section} \label{tab:summbrazilian} \begin{tabular}{ccccc} \toprule & Going dynamical & $\alpha\leftrightarrow\phi$ & $\nabla\alpha\to\Gamma$ & Experimental validation \\ \midrule Theoretics & & & & \\ Numerics & & \rightthumbsup & \rightthumbsup & \rightthumbsup \\ \bottomrule \end{tabular} \end{table} \paragraph{Problem setting} The geometry and loading conditions are summarized in \cref{fig:brazilian}. Two diameters will be considered here to investigate possible size effects: $D=\SI{500}{mm}$ and $D=\SI{200}{mm}$. The bearing strips are introduced to prevent ill-posed concentration. In this work they are assumed to be a part of the cylinder for the sake of simplicity, however more realistic modeling involving unilateral contact conditions is possible. The compressive loads are prescribed by a given velocity evolution $\vec{V}_t$ on the outer surface of the strips. In this work the dynamic effect is not the main objective and hence a relatively low loading velocity is used $\norm{\vec{V}_t}=\SI{\pm 0.1}{m/s}$. An initial rise time of \SI{1e-6}{s} is introduced to avoid velocity shocks. \begin{figure}[htbp] \centering \includegraphics[width=0.4\textwidth]{brazilian.pdf} \caption{Three-dimensional Brazilian test on a concrete cylinder characterized by its diameter $D$ and its height $W$. The compressive loads modeled as prescribed velocities are transmitted to the cylinder along the vertical diameter direction via two bearing strips of width $D/16$} \label{fig:brazilian} \end{figure} The material parameters for a typical concrete are borrowed from \cite{RuizOrtizPandolfi:2000}. Numerically an unstructured tetrahedral mesh is used to discretize the cylinder volume. A uniform mesh size of $h\approx\SI{10}{mm}$ leads to approximately \num{1e5} finite elements for $D=\SI{500}{mm}$ and \num{25000} elements for the small cylinder with $D=\SI{200}{mm}$. The material and numerical parameters are summarized in \cref{tab:brazilian}. The damage constitutive law \eqref{eq:at1} is used. Using the identification of the equivalent fracture toughness \eqref{eq:gcingd}, the internal length $\eta$ can be derived from $\gc$ and $\sigma_\mc$, which gives $\eta\approx \SI{46}{mm}$. \begin{table}[htbp] \centering \caption{Material and numerical parameters for the Brazilian test} \label{tab:brazilian} \begin{tabular}{llllll} \toprule $\rho$ & $E$ & $\nu$ & $\gc$ & $\sigma_\mc$ & $h$ \\ \midrule \SI{2450}{kg/m^3} & \SI{37.9}{GPa} & 0.15 & \SI{66.2}{N/m} & \SI{4.53}{MPa} & \SI{10}{mm} \\ \bottomrule \end{tabular} \end{table} \subsection{Fracture pattern predicted by different tension-compression models} Pursuing the work of \cref{sec:kalthoff}, the use of different tension-compression asymmetry formulations as discussed in \cref{sec:TC} are investigated here with respect to their aptitude to reproduce the desired vertical splitting fracture pattern of the cylinder. As a genuine material parameter, the choice of these formulations in a numerical simulation should be justified by experimental facts on the specific material. In this work two particular models are compared: the approach proposed by \cite{AmorMarigoMaurini:2009} by separating the deviatoric and spheric part of the sound elastic energy and the model proposed by \cite{FreddiRoyer-Carfagni:2010} which is recommended following our analyses in \cref{sec:kalthoff}. The big cylinder with $D=\SI{500}{mm}$ is first used. The final fracture pattern obtained by these two formulations is indicated in \cref{fig:brazilian_tc}. \begin{figure}[htbp] \centering \includegraphics[width=0.9\textwidth]{brazilian_TC.pdf} \caption{Fracture pattern represented by the damage field ranging from 0 (blue) to 1 (red) for the Brazilian splitting test obtained by two tension-compression asymmetry models: (a) the model of \cite{AmorMarigoMaurini:2009} and (b) the model of \cite{FreddiRoyer-Carfagni:2010}} \label{fig:brazilian_tc} \end{figure} Several remarks are given as follows. \begin{itemize} \item With the model proposed by \cite{AmorMarigoMaurini:2009}, damage is concentrated where the loads are applied. This experiment illustrates its deficiency to describe the microscopic/macroscopic fracture mechanism of concrete. \item Vertical splitting is reproduced by the formulation of \cite{FreddiRoyer-Carfagni:2010}. It illustrates that the damage mechanism in concrete is indeed induced by local tensile stresses. It can be seen that fracture is homogeneous in the height $W$ direction. A two-dimensional modeling could suffice. In this work the obtained three-dimensional simulation results verify the generality of the variational formulation outlined in \cref{def:dynagraddama} and the robustness of the EPX implementation described in \cref{sec:epx}. \end{itemize} \subsection{Temporal evolution of global quantities and fields} The evolution of global quantities and fields is now investigated. A useful reference time scale $t_\mathrm{ref}=D/c$, which corresponds to the time for the elastic wave to travel across the cylinder diameter, is used to normalize the time variable. First, we are interested in the temporal evolution of the applied vertical load $F_t$ transmitted through the bearing strip. From basic static elastic analyses, the load $F_t$ induces a maximum splitting tensile stress $\sigma$ at the center of the diameter which is given by \begin{equation} \label{eq:sigmaFWD} \sigma=\frac{2F}{\pi WD} \end{equation} According to the damage criterion \eqref{eq:localdamagefirstorder} for an initially sound body (as analyzed in \cref{sec:1d}), damage or fracture is expected to take place at the center where the criterion is firstly satisfied. A critical load $F_\mathrm{ref}$ which corresponds to the critical stress $\sigma_\mc$ in \eqref{eq:sigmaFWD} can thus be defined. It is used for normalization. The evolution for $t\mapsto F_t$ is illustrated in \cref{fig:brazilian_ft}. Some snapshots of the damage field at some particular instants are taken to complement the curve. \begin{figure}[htbp] \centering \includegraphics[width=0.5\textwidth]{brazilian-ft.pdf} \caption{Temporal evolution of the applied load transmitted through the bearing strip with or without activation of the erosion mechanism available in the EPX software, illustrated by snapshots of the damage field ranging from 0 (blue) to 1 (red)} \label{fig:brazilian_ft} \end{figure} The curve labeled ``Without erosion'' is first analyzed. It can be verified that damage begins to evolve at the center when the splitting stress induced by the transmitted load $F_t$ attains the material critical stress. As $F_t$ increases, damage develops and propagates into a crack band along the vertical diameter direction until a complete split of the cylinder. However the temporal evolution of $F_t$ requires further investigation: \begin{itemize} \item The applied load attains a peak of approximately $1.2F_\mathrm{ref}$, which may due to structural hardening effects between the damage initiation when $F_t\approx F_\mathrm{ref}$ and the onset of fracture. \item After the peak, unexpectedly the load is not instantaneously decreasing to zero. However, its temporal evolution indicates that there exists still some residual stiffness along the vertical crack. Remark that the loading condition is very similar to the edge-cracked plate experiment studied in \cref{sec:kalthoff}, \emph{i.e.} sliding loads parallel to an existing or established gradient-damage crack. Continuing our analyses there, it is suspected that this peculiar temporal evolution is again due to the deficiency of the existing tension-compression models to represent a genuine unilateral condition, see \cref{sec:howtochoose}. In particular, the crack normal direction is not considered in these models, hence some residual stresses may be present parallel to the crack. The definition of such normal vectors, nevertheless, is not trivial due to the smeared description. We reiterate the conclusion of \cref{sec:kalthoff} that a better strategy may be to use a transition algorithm between the smeared and the sharp-interface description of cracks. \item A possible remedy within the EPX environment may be to activate the ``erosion'' mechanism. When a crack is detected (for example when the effective degradation \eqref{eq:aeff} approaches zero within a tolerance) for a certain finite element, its contribution to the internal force vector \eqref{eq:Fint} will be ignored. By doing so, an approximative stress-free condition is thus by default prescribed along the crack lip. With the activation of the erosion mechanism, the fracture pattern is not altered however as can be seen from \cref{fig:brazilian_ft}, the transmitted load quickly decreases to zero after the peak value, which corresponds to ultimate structural failure. Future work will be devoted to a thorough investigation of the erosion mechanism to take into account for instance unilateral effects. \end{itemize} Temporal evolution of global energetic quantities is illustrated in \cref{fig:brazilian_e}. It can be seen that initially inertia is not important which in turn ensures the validity of \eqref{eq:sigmaFWD}. During crack nucleation and propagation along the diameter, the kinetic energy suddenly develops and becomes comparable to the elastic energy, which illustrates the unstable or brutal nature of the crack propagation phase. A full dynamic analysis is indeed more appropriate for this Brazilian test. \begin{figure}[htbp] \centering \includegraphics[width=0.5\textwidth]{brazilian-energy.pdf} \caption{Temporal evolution of global energetic quantities with the erosion mechanism} \label{fig:brazilian_e} \end{figure} \subsection{Size effect} A size effect is present for the present Brazilian test following the analyses in \cite{RoccoGuineaPlanasElices:1999,RuizOrtizPandolfi:2000}. In particular, smaller cylinders should produce higher peak loads (normalized by $F_\mathrm{ref}$ determined by the material critical stress and the diameter) at the onset of fracture, confirming the commonly acknowledged idea \emph{smaller is stronger}. On the other hand, bigger cylinders should break as soon as the critical material stress is reached. The temporal evolution of the applied load $F_t$ for two concrete cylinders with different diameters are indicated in \cref{fig:brazilian_size}. It can be seen that the fracture pattern remains similar. The above size effect is numerically verified and reproduced by the dynamic gradient damage model. The existence of such size effects is due to the introduction of the material internal length $\ell$, see also the work on crack nucleation of a bar in \cref{sec:1d}. \begin{figure}[htbp] \centering \includegraphics[width=0.5\textwidth]{brazilian-size.pdf} \caption{Temporal evolution of the applied load transmitted through the bearing strip for two concrete cylinders with different diameters} \label{fig:brazilian_size} \end{figure} \subsection*{Conclusion} In terms of fracture pattern prediction for concrete structures, the tension-compression model proposed by \cite{FreddiRoyer-Carfagni:2010} seems to be a good candidate compared to other choices. However the crack normal vector is not taken into account and residual stiffness may be present along and parallel to the crack lip. The ``erosion'' mechanism available in the EPX software could produce a real crack however its use need further investigation. Size effect for Brazilian tests on concrete cylinders is reproduced by the gradient damage model. The existence of such experimentally validated size effects is due to the introduction of the material internal length $\ell$. \section{Dynamic Fracture of L-Shaped Concrete Specimen} \label{sec:L-specimen} This section is devoted to a gradient-damage modeling of the dynamic tensile test on a two-dimensional plane-strain L-shaped concrete specimen. Compared to \cref{sec:brazilian}, the objective here is to investigate dynamic or velocity effects in dynamic fracture problems on concrete structures, \emph{i.e.} their influence on the temporal evolution of global quantities and spatial crack path. An experimental validation of the model is also considered against the results obtained in \cite{OzboltBedeSharmaMayer:2015}. The thematic subjects covered here are thus summarized in \cref{tab:summL}. \begin{table}[htbp] \centering \caption{Thematic subjects covered in this section} \label{tab:summL} \begin{tabular}{ccccc} \toprule & Going dynamical & $\alpha\leftrightarrow\phi$ & $\nabla\alpha\to\Gamma$ & Experimental validation \\ \midrule Theoretics & & & & \\ Numerics & & & \rightthumbsup & \rightthumbsup \\ \bottomrule \end{tabular} \end{table} \paragraph{Problem setting} The geometry and loading conditions are adapted from \cite{OzboltBedeSharmaMayer:2015} and are summarized in \cref{fig:L-specimen}. \begin{figure}[htbp] \centering \includegraphics[width=0.45\linewidth]{L-specimen.pdf} \caption{Geometry and loading conditions for the L-specimen problem. Damage field $\alpha_t$ at $t=\SI{6e-4}{s}$ ranging from 0 (gray) to 1 (white) obtained by $\eta=\SI{1}{mm}$, for $v=\SI{0.74}{m/s}$} \label{fig:L-specimen} \end{figure} A hard device (displacement control) is applied on the lower left arm \SI{30}{mm} from the edge through a disc of $D=\SI{45}{mm}$ to avoid local concentration. The load is applied through unilateral contact (EPX keyword \texttt{IMPACT}) with an imposed velocity $\vec{V}(t)=\overline{V}f(t)\vec{e}_2$. The intensity is scaled via the factor $\overline{V}$. The function $f(t)$ defined below ensures that at crack initiation the loading velocity is approximately $V$: \begin{lstlisting} FONC 1 TABL 5 0D0 0D0 1.5D-4 1D0 2D-4 1D0 4D-4 2D0 1D0 2D0. \end{lstlisting} The concrete material properties are borrowed from \cite{OzboltBedeSharmaMayer:2015} and are summarized in \cref{tab:L}. The damage constitutive law \eqref{eq:at1} is used. Using \eqref{eq:gcingd}, the internal length $\eta$ can be derived from $\gc$ and $\sigma_\mc$, which gives $\eta\approx \SI{72}{mm}$. The analysis is performed in the temporal interval $[0,\SI{6e-4}{s}]$ and the explicit time-stepping method (\cref{algo:explicit}) is used. According to the comparative analyses in \cref{sec:kalthoff,sec:brazilian}, the tension-compression model proposed by \cite{FreddiRoyer-Carfagni:2010} should be preferred for brittle materials. The domain is discretized by a non-structured quadrilateral mesh with a typical size $h\approx\SI{10}{mm}$, arriving at approximately \num{2000} elements. \begin{table}[htbp] \centering \caption{Material and numerical parameters for the L-specimen test} \label{tab:L} \begin{tabular}{llllll} \toprule $\rho$ & $E$ & $\nu$ & $\gc$ & $\sigma_\mc$ & $h$ \\ \midrule \SI{2210}{kg/m^3} & \SI{32.2}{GPa} & 0.18 & \SI{58.56}{N/m} & \SI{3.12}{MPa} & \SI{10}{mm} \\ \bottomrule \end{tabular} \end{table} \subsection{Path prediction} The internal length here $\eta\approx \SI{72}{mm}$ is not small by comparison with the dimension of the body (with a side length $\SI{250}{mm}$). We had the same situation for the Brazilian test in \cref{sec:brazilian} with $D=\SI{200}{mm}$. However in \cref{sec:brazilian} due to symmetry crack nucleates and propagates along the central diameter direction away from the boundary. Furthermore dynamic effects are not important and diffuse damage is not observed. In this problem however, crack path prediction is one of the objectives of the simulation and a large internal length, which implies a large damage band and a more smeared description of cracks, may complicate the identification of the crack path. \begin{figure}[htbp] \centering \includegraphics[width=0.9\textwidth]{v740-1200-sigm.pdf} \caption{Damage field $\alpha_t$ ranging from 0 (blue) to 1 (red) for two different loading speeds obtained with $\ell\approx\SI{72}{mm}$: (a) $v=\SI{0.74}{m/s}$ and (b) $v=\SI{1.2}{m/s}$} \label{fig:v7401200sigm} \end{figure} In \cref{fig:v7401200sigm} the final damage field obtained with $\eta\approx\SI{72}{mm}$ for two different loading speeds is indicated. The simulation results are to be compared with the experimental fracture patterns indicated in \cref{fig:v7401200exp}. For a lower loading speed $v=\SI{0.74}{m/s}$, the initial nucleation angle is close to the experimental one. However the damage field simulated seems to indicate a crack branching event which is not observed in the experiment. For a higher loading speed $v=\SI{1.2}{m/s}$, a relatively large diffusive damage zone is produced near the nucleation corner. The crack branching is reproduced, however the branching location and subsequent crack propagation path do not agree with the experimental results. \begin{figure}[htbp] \centering \includegraphics[width=0.9\textwidth]{v740-1200-exp.pdf} \caption{Fracture patterns observed in experiments conducted by \cite{OzboltBedeSharmaMayer:2015}} \label{fig:v7401200exp} \end{figure} The failure to reproduce the experimentally observed fracture pattern in this example can be partially attributed to the followings difficulties: \begin{itemize} \item With a relatively large internal length, the elliptic damage problem interferes with the border $\partial\Omega$ through the boundary condition prescribed in the damage criterion \eqref{eq:localdamagefirstorder} and the consistency condition \eqref{eq:damageconsis}. The value of $\ell$ should be ``reduced'' for smaller structures, see \cite{LorentzGodard:2011}. Furthermore, the separation of scales between the outer fracture mechanics problem and the inner damage strain-softening problem considered in \cref{sec:linkDF,sec:antiplane,sec:kinking} is no longer possible with a large internal length. In that case the gradient damage model can not be considered as an approximation of the \emph{fracture} problem. \item With the damage constitutive law \eqref{eq:at1} (but also with \eqref{eq:at2}), since no additional parameters are introduced, the internal length is directly computed from \eqref{eq:gcingd} from the fracture toughness and the maximal material stress. For brittle materials such as PMMA considered in \cref{sec:gregoire}, it leads to an extremely small internal length ($\eta\approx\SI{0.0375}{mm}$ is used there) compared to industrial specimen or structures. It calls for a computationally costly numerical simulation with parallel computing techniques, however a confined damage process zone leads to a separation of scales described above and a link between damage and fracture can be achieved. For concrete on the other hand, one obtains with \eqref{eq:gcingd} an internal length of several centimeters. The modeling of fracture phenomena in small concrete specimens with these kind of constitutive laws is questionable. \end{itemize} Due to this reason, another series of simulation is performed with $\eta=\SI{1}{mm}$. Using the definition of the maximal stress \eqref{eq:sigc0} and the fracture toughness \eqref{eq:gcingd}, it leads to an overestimation of the maximal tensile strength $\sigma_\mathrm{m}\approx \SI{27}{MPa}$ of the concrete. At a lower loading speed $v=\SI{0.74}{m/s}$, the final fracture pattern indicated by the damage field with $\eta=\SI{1}{mm}$ is illustrated in \cref{fig:L-specimen}. A better agreement between the simulation and the experimental observed crack path is found. The temporal evolution of the applied force is then analyzed for two different internal lengths. In \cref{fig:F_v740_ell}, it can be observed that the they predict different global structural behaviors only during the post-crack initiation phase. In particular, the peak load is not sensible to the internal length. It could be explained by the presence of the geometric singularity where the damage initiates, which implies that the material critical stress is quickly reached when the waves arrive at the corner. \begin{figure}[htbp] \centering \includegraphics[width=0.5\textwidth]{F_v740_ell.pdf} \caption{Temporal evolution of the applied force with $v=\SI{0.74}{m/s}$} \label{fig:F_v740_ell} \end{figure} \subsection{Dynamical effects} We then turn to the global dynamic structural response obtained with different loading rates. As it is expected, the peak load increases with the prescribed velocity, cf. \cref{fig:F-v-exp}(a). A good agreement with the experimental measurement is also found at $v=\SI{1.5}{m/s}$ as illustrated in \cref{fig:F-v-exp}(b). Knowing that no strain rates effects is currently taken into account in the material constitutive modeling, this increase of peak load for higher loading rates can be attributed to inertia. According to \cite{OzboltBedeSharmaMayer:2015}, this progressive increase of resistance is a pure consequence of inertial effects and not from velocity-dependent material strength or fracture energy. \begin{figure}[htbp] \centering \includegraphics[width=\textwidth]{F-v-exp.pdf} \caption{Temporal evolution of the applied force: (a) dynamical effects illustrated by two loading speeds and (b) comparison with experimental measurement at $v=\SI{1.5}{m/s}$} \label{fig:F-v-exp} \end{figure} The final crack pattern for $v=\SI{1.5}{m/s}$ is also indicated in \cref{fig:F-v-exp}(b). As it is observed in experiments, crack branching is reproduced. However the crack path corresponds not exactly to what is seen in real concrete specimens. We suspect that it is mainly due to the loading condition which is not described in detail in \cite{OzboltBedeSharmaMayer:2015}. Another possible reason could be the use of a smaller internal length chosen due to the small size of the specimen. Using the true internal length derived from the maximal tensile strength of the concrete, a different branching direction appears to take place in \cref{fig:v7401200sigm}. \subsection*{Conclusion} The dynamic gradient damage model is here applied to a relatively small concrete structure with the \eqref{eq:at1} damage constitutive model. Since the internal length deduced from the fracture toughness and the tensile strength is not small compared to the dimension of the body, relatively diffuse damage takes place and the gradient damage model can no longer be considered as a good approximation of brittle fracture. The damage process zone where strain softening dominates is large and the link between damage and fracture outlined in \cref{sec:linkDF} and numerically verified in \cref{sec:antiplane} is not possible. The dynamic gradient damage model does not give a satisfactory prediction of the experimentally observed crack path. The difficulty resides in the simplicity of the \eqref{eq:at1} damage constitutive model. No additional parameters are introduced and the internal length $\ell$, which determines the damage band, is fixed as long as $\gc$ and $\sigma_\mathrm{m}$ are. Future work will be devoted to the use of more sophisticated constitutive models proposed by \cite{LorentzCuvilliezKazymyrenko:2011,AlessiMarigoVidoli:2015} which introduce additional modeling parameters. Note however that this implies that the minimization problem for the damage variable \eqref{eq:crackmin} is no more quadratic, which leads to a higher computational cost. \section{CEA Impact Test on Beams} \label{sec:beam} Finally we propose a preliminary gradient-damage modeling of a three-dimensional reinforced concrete beam under impact. The original experimental campaign is performed in the \emph{laboratoire d'étude de dynamique} (DYN) of CEA Saclay, see for example \cite{Guilbaud:2015} for an overview of the test setting. The objective is to investigate the application of the dynamic gradient damage model to industrial concrete structures with steel reinforcements. The thematic subjects covered here are thus summarized in \cref{tab:summbeam}. \begin{table}[htbp] \centering \caption{Thematic subjects covered in this section} \label{tab:summbeam} \begin{tabular}{ccccc} \toprule & Going dynamical & $\alpha\leftrightarrow\phi$ & $\nabla\alpha\to\Gamma$ & Experimental validation \\ \midrule Theoretics & & & & \\ Numerics & & & & \rightthumbsup \\ \bottomrule \end{tabular} \end{table} \paragraph{Problem setting} The geometric and loading conditions are recalled in \cref{fig:beam}. Due to symmetry, only a quarter $\Omega$ of the reinforced beam is modeled (corresponding to the gray domain in \cref{fig:beam}). The beam is \SI{1.3}{m} long and is subject to a steel projectile with a vertical impact velocity of $v=\SI{8.3}{m/s}$. It is unilaterally supported with a span of \SI{1}{m} both at the upper and lower surface via bearing strips of width \SI{30}{mm}. In this example, the concrete beam is reinforced by two \SI{8}{mm} steel rebars at the top and two \SI{12}{mm} rebars at the bottom. Perfect bonding between these rebars and the concrete beam is assumed. The impact is modeled by a unilateral contact condition between the steel projectile with an initial speed $v$ and the upper surface of the beam. The exact dimensions and other details can be found in \cite{Guilbaud:2015} and references therein. The problem setting described here is also similar to that investigated in \cite{OzboltSharma:2011,AdhikaryLiFujikake:2012}. \begin{figure}[htbp] \centering \includegraphics[width=0.9\textwidth]{beam-schema.pdf} \caption{Geometric and loading conditions for the CEA impact test on beams} \label{fig:beam} \end{figure} We now turn to a gradient-damage modeling of the problem. The concrete is governed by a gradient damage material the parameters of which are summarized in \cref{tab:beamconcrete}. Using \eqref{eq:gcingd}, the internal length $\eta$ can be derived from $\gc$ and $\sigma_\mc$, which gives $\eta\approx \SI{60}{mm}$. The rebars obey a typical elasto-plastic law with isotropic hardening for steels. They are considered to be non-damageable in the analysis. Hence the energy minimization principle \eqref{eq:crackmin}, \emph{i.e.} the damage criterion, is now written only for the concrete domain. Due to its appropriate physical properties and a lower computational cost, the damage constitutive law \eqref{eq:at1} is used for this simulation. Similar to previous examples, the tension-compression model proposed by \cite{FreddiRoyer-Carfagni:2010} is preferred to characterize tensile fracture behaviors of brittle materials. \begin{table}[htbp] \centering \caption{Material and numerical parameters for the beam test} \label{tab:beamconcrete} \begin{tabular}{llllll} \toprule $\rho$ & $E$ & $\nu$ & $\gc$ & $\sigma_\mc$ & $h$ \\ \midrule \SI{2300}{kg/m^3} & \SI{25}{GPa} & 0.2 & \SI{57}{N/m} & \SI{3}{MPa} & \SI{5}{mm} \\ \bottomrule \end{tabular} \end{table} Numerically a uniform 8-node hexahedral solid elements are used to discretize the concrete domain with a typical mesh size $h\approx\SI{5}{mm}$, arriving at approximately \num{80000} elements, see \cref{fig:beammesh}. The steel rebars are also discretized with the same solid elements. The explicit time-stepping (\cref{algo:explicit}) implemented in the EPX software is adopted. The current time increment is calculated based on the CFL condition with a security factor of 0.8. \begin{figure}[htbp] \centering \includegraphics[width=0.4\textwidth]{beam-mesh.png} \caption{8-node hexahedral solid elements used to discretize the concrete domain after symmetry considerations} \label{fig:beammesh} \end{figure} \paragraph{With original concrete parameters} Using the material parameters given in \cref{tab:beamconcrete}, it can be observed that while the material internal length $\eta$ is small by comparison to the beam length (about 0.05\%), it still accounts for 30\% of the height. According to the previous analysis in \cref{sec:L-specimen}, it may lead to some modeling difficulties when the crack direction possesses a component parallel to the length direction. The damage field obtained during numerical simulation is illustrated in \cref{fig:beamsigm}. \begin{figure}[htbp] \centering \includegraphics[width=\textwidth]{beam-sigm.pdf} \caption{Fracture pattern with the parameters indicated in \cref{tab:beamconcrete} at (a) $t=\SI{4e-4}{s}$ and (b) $t=\SI{7e-4}{s}$} \label{fig:beamsigm} \end{figure} This numerical result (\cref{fig:beamsigm}) is to be compared with the experimentally observed fracture pattern reported in \cite{Guilbaud:2015}, see \cref{fig:beamexp}. In the experiment, the structural failure is characterized by the nucleation of two main inclined cracks forming a cone at the center of the beam. Several minor vertical cracks are also observed in the shear plug. However here a large diffuse damage region is produced at the center of the beam, which implies that the concrete material is totally disintegrated. Diffuse damage also takes place at the upper surface and near the lower supporting location. Although the central damage region is well delimited by a similar inclined cone, the presence of the diffuse damage compromises the use of gradient damage approaches for an appropriate modeling of brittle fracture. Furthermore, we observe a gradual propagation of the diffuse damage in the beam such that at $t=\SI{7e-4}{s}$ a large region of the beam is totally damaged. \begin{figure}[htbp] \centering \includegraphics[width=0.4\textwidth]{beam-exp.png} \caption{Experimentally observed fracture pattern corresponding to the formation of a shear plug at the center under the projectile} \label{fig:beamexp} \end{figure} \paragraph{Use of a smaller internal length} Similarly to \cref{sec:L-specimen}, we expect that the use of a more sophisticated damage constitutive law that introduces additional parameters could provide a better characterization of brittle behaviors of concrete for relatively small structures. Future work will be devoted to this point. Here we present in the sequel some preliminary results obtained with a smaller internal length. We artificially decrease the internal length to $\eta=\SI{10}{mm}$, which amounts to increase the critical stress to $\sigma_\mathrm{m}=\SI{7}{MPa}$. The damage field obtained at $t=\SI{4e-4}{s}$ is illustrated in \cref{fig:beamell0x1}. \begin{figure}[htbp] \centering \includegraphics[width=0.9\textwidth]{beam-ell0x1.png} \caption{Fracture pattern obtained with $\eta=\SI{10}{mm}$ at $t=\SI{4e-4}{s}$} \label{fig:beamell0x1} \end{figure} The formation of two main inclined cracks becomes more apparent. Some minor vertical cracks are also reproduced on the upper surface of the beam, as it is observed in the experiment described in \cite{OzboltSharma:2011}. However diffuse damage still takes place at the center of the beam. The temporal evolution of certain quantities is analyzed. In particular, we illustrate in \cref{fig:projectileU} the vertical displacement evolution of the projectile. On the one hand, using the standard critical stress $\sigma_\mathrm{m}=\SI{3}{MPa}$ of concrete, we observe progressive descending of the projectile. The resistance of the beam is not strong enough to stop the impactor. On the other hand, when using a larger critical stress obtained with $\eta=\SI{10}{mm}$, the rebound of the projectile is observed after a transient descending phase when structural fracture of the beam takes place. In the experiment reported in \cite{Guilbaud:2015}, the final vertical displacement is stabilized at $u_y\approx \SI{-24}{mm}$. The current gradient-damage modeling fails to give an accurate global evolution prediction. \begin{figure}[htbp] \centering \includegraphics[width=\textwidth]{projectile-U.pdf} \caption{Vertical displacement of the impactor for two internal lengths: (a) comparison between $\sigma_\mathrm{m}=\SI{3}{MPa}$ and $\eta=\SI{10}{mm}$ ($\sigma_\mathrm{m}\approx \SI{7}{MPa}$) and (b) temporal zoom for $\eta=\SI{10}{mm}$} \label{fig:projectileU} \end{figure} If the internal length is further decreased to $\eta=\SI{5}{mm}$ ($\sigma_\mathrm{m}\approx \SI{10}{MPa}$), several shear cracks forming an angle of approximately \SI{45}{\degree} with respect to the $x$-axis are observed under the impactor, see \cref{fig:beamsigmell0x005}(a). For this calculation a more refined mesh with $h=\SI{2.5}{mm}$ is used, arriving at approximately \num{640000} 8-nodes hexahedral elements. This fracture pattern is commonly observed in impact experiments on concrete beams, see \cite{OzboltSharma:2011}. The angle also matches well with the experimental results reported in \cite{Guilbaud:2015}. A diffuse damage region due to high tensile stresses is produced on the lower surface under the projectile. \begin{figure}[htbp] \centering \includegraphics[width=\textwidth]{beam-ell0x005.pdf} \caption{Fracture pattern obtained with $\eta=\SI{5}{mm}$ at (a) $t=\SI{2e-4}{s}$ and (b) $t=\SI{3e-4}{s}$} \label{fig:beamsigmell0x005} \end{figure} As can be seen from \cref{fig:beamsigmell0x005}, secondary cracks appear and then propagate from the upper surface of the beam. This phenomenon is also produced in the numerical study of \cite{AdhikaryLiFujikake:2012}. The biggest eigenvalue of the stress tensor at $t=\SI{1.6e-4}{s}$ is illustrated in \cref{fig:beameig} just before crack nucleation in the beam. The compressive area is localized on the upper surface just under the impactor and is not visible in the figure. We observe tensile stress areas generated by the impactor which correspond to the crack nucleation sites observed in \cref{fig:beamsigmell0x005}. This fracture pattern is thus the result of the tension-compression asymmetry formulation \cite{FreddiRoyer-Carfagni:2010} which favors mode-I cracks induced by positive principal stresses. \begin{figure}[htbp] \centering \includegraphics[width=\textwidth]{ell0x005-eig.png} \caption{The biggest eigenvalue of the stress tensor at $t=\SI{1.6e-4}{s}$ ranging from less than \SI{-7}{MPa} (blue) to more than \SI{3}{MPa} (red). The compressive area is localized on the upper surface just under the impactor} \label{fig:beameig} \end{figure} Finally we turn to the computational aspect of a parallel 3d calculation with the dynamic gradient damage model. Domain decomposition using 64 processors is performed. The final calculation time is fixed to $t=\SI{4e-4}{s}$ after the structural failure of the beam, see \cref{fig:beamsigmell0x005}. The partition of the total computational time using the convention given in \cref{sec:branching} is given in \cref{tab:partimebeam}. The mean value among all processors is used. Since the damage is a scalar field, the actual solving of the damage problem \eqref{eq:cracknummin} through the GPCG algorithm described in \cref{sec:implementation} still accounts for approximately 10\% of the total computational time as in the 2d cases, see \cref{fig:scaling,fig:kalscaling}. If the communication overhead is ignored, the cost of a gradient-damage constitutive modeling of brittle materials (damage assembly and solving) represents less than 2 times the cost for the $\vec{u}$-problem. The same observation is found for two-dimensional problems. Note however if a more sophisticated damage constitutive law is used, the cost for the damage problem may increase due to variable Hessian matrix. \begin{table}[htbp] \centering \caption{Partition of the total computational time for the CEA impact test on beams with 64 processors} \label{tab:partimebeam} \begin{tabular}{lllll} \toprule Total time & Elastodynamics & Damage assembly & Damage solving & Communication \\ \midrule \SI{39}{mn} & 32\% & 43\% & 13\% & 12\% \\ \bottomrule \end{tabular} \end{table} \paragraph*{Conclusion} In this experiment the dynamic gradient damage model is used to investigate the structural failure of a reinforced beam under severe impact. Similarly to \cref{sec:L-specimen}, it is illustrated that a more sophisticated damage constitutive law could be devised for the concrete material that introduces additional modeling parameters. Indeed, the internal length $\eta$ derived from the other material parameters in the \eqref{eq:at1} law may not be small by comparison with other structural length, which leads to a degenerated modeling of brittle fracture phenomena. By introducing additional modeling parameters such as in \cite{LorentzCuvilliezKazymyrenko:2011,AlessiMarigoVidoli:2015}, a relatively small internal length could be used. Theoretical and numerical investigation of these laws in dynamics could be performed in the future. On the other hand, the discrepancy between the numerical result presented in particular in \cref{fig:beamsigm} and the experimental one reported in \cite{Guilbaud:2015} could also be attributed to the complex constitutive behaviors of concrete under compression. Under such loading conditions, strain softening is often accompanied by extensive plastic deformation, which is typical of a ductile material. In highly confined compression, stiffness degradation and inelastic expansion could also be significantly reduced. Future work could be devoted to a coupling between a plastic model that takes into account possible inelastic strains and the current gradient damage approach that accounts for brittle fracture in tension. Another possible reason concerns strain-rate effects in the material constitutive modeling. From a macroscopic modeling point of view, a rate-dependent damage criterion could be used to account for a higher resistance of concrete for large strain rates, see \cite{Hentz:2003}. In the current variational formulation of the dynamic gradient damage model outlined in \cref{def:dynagraddama}, it is not taken into account. By introducing for example viscosity into the plasticity model, we would obtain a threshold for damage initiation that increases with the strain-rate. This rate-dependency need further investigation in the future for a better modeling of concrete behaviors.
# The Euler equations of gas dynamics This is the first of two notebooks on the Euler equations. In this notebook, we discuss the equations and the structure of the exact solution to the Riemann problem. In [Euler_approximate_solvers.ipynb](Euler_approximate_solvers.ipynb), we will investigate approximate Riemann solvers. ## Fluid dynamics In this chapter we study the system of hyperbolic PDEs that governs the motions of a compressible gas in the absence of viscosity. These consist of conservation laws for **mass, momentum**, and **energy**. Together, they are referred to as the **compressible Euler equations**, or simply the Euler equations. Our discussion here is fairly brief; for much more detail see <cite data-cite="fvmhp"><a href="riemann.html#fvmhp">(LeVeque, 2002)</a></cite> or <cite data-cite="toro2013riemann"><a href="riemann.html#toro2013riemann">(Toro, 2013)</a></cite>. ### Mass conservation We will use $\rho(x,t)$ to denote the fluid density and $u(x,t)$ for its velocity. Then the equation for conservation of mass is just the familiar **continuity equation**: $$\rho_t + (\rho u)_x = 0.$$ ### Momentum conservation We discussed the conservation of momentum in a fluid already in [Acoustics.ipynb](Acoustics.ipynb). For convenience, we review the ideas here. The momentum density is given by the product of mass density and velocity, $\rho u$. The momentum flux has two components. First, the momentum is transported in the same way that the density is; this flux is given by the momentum density times the velocity: $\rho u^2$. To understand the second term in the momentum flux, we must realize that a fluid is made up of many tiny molecules. The density and velocity we are modeling are average values over some small region of space. The individual molecules in that region are not all moving with exactly velocity $u$; that's just their average. Each molecule also has some additional random velocity component. These random velocities are what accounts for the **pressure** of the fluid, which we'll denote by $p$. These velocity components also lead to a net flux of momentum. Thus the momentum conservation equation is $$(\rho u)_t + (\rho u^2 + p)_x = 0.$$ This is very similar to the conservation of momentum equation in the shallow water equations, as discussed in [Shallow_water.ipynb](Shallow_water.ipynb), in which case $hu$ is the momentum density and $\frac 1 2 gh^2$ is the hydrostatic pressure. For gas dynamics, a different expression must be used to compute the pressure $p$ from the conserved quantities. This relation is called the *equation of state* of the gas, as discussed further below. ### Energy conservation The energy has two components: internal energy density $\rho e$ and kinetic energy density $\rho u^2/2$: $$E = \rho e + \frac{1}{2}\rho u^2.$$ Like the momentum flux, the energy flux involves both bulk transport ($Eu$) and transport due to pressure ($pu$): $$E_t + (u(E+p)) = 0.$$ ### Equation of state You may have noticed that we have 4 unknowns (density, momentum, energy, and pressure) but only 3 conservation laws. We need one more relation to close the system. That relation, known as the equation of state, expresses how the pressure is related to the other quantities. We'll focus on the case of a polytropic ideal gas, for which $$p = \rho e (\gamma-1).$$ Here $\gamma$ is the ratio of specific heats, which for air is approximately 1.4. ## The Euler equations We can write the three conservation laws as a single system $q_t + f(q)_x = 0$ by defining \begin{align} q & = \begin{pmatrix} \rho \\ \rho u \\ E\end{pmatrix}, & f(q) & = \begin{pmatrix} \rho u \\ \rho u^2 + p \\ u(E+p)\end{pmatrix}. \label{euler_conserved} \end{align} This is the 1D Euler system. In three dimensions, the equations are similar. We have two additional velocity components $v, w$, and their corresponding fluxes. Additionally, we have to account for fluxes in the $y$ and $z$ directions. We can write the full system as $$ q_t + f(q)_x + g(q)_y + h(q)_z = 0$$ with \begin{align} q & = \begin{pmatrix} \rho \\ \rho u \\ \rho v \\ \rho w \\ E\end{pmatrix}, & f(q) & = \begin{pmatrix} \rho u \\ \rho u^2 + p \\ \rho u v \\ \rho u w \\ u(E+p)\end{pmatrix} & g(q) & = \begin{pmatrix} \rho v \\ \rho uv \\ \rho v^2 + p \\ \rho v w \\ v(E+p)\end{pmatrix} & h(q) & = \begin{pmatrix} \rho w \\ \rho uw \\ \rho vw \\ \rho w^2 + p \\ w(E+p)\end{pmatrix}. \end{align} In the rest of the chapter we focus on the 1D system. ## Hyperbolic structure of the 1D Euler equations In our discussion of the structure of these equations, it is convenient to work with the primitive variables $(\rho, u, p)$ rather than the conserved variables. The quasilinear form is particularly simple in the primitive variables: \begin{align} \label{euler_primitive} \begin{bmatrix} \rho \\ u \\ p \end{bmatrix}_t + \begin{bmatrix} u & \rho & 0 \\ 0 & u & 1/\rho \\ 0 & \gamma \rho & u \end{bmatrix} \begin{bmatrix} \rho \\ u \\ p \end{bmatrix}_x & = 0. \end{align} ### Characteristic velocities The eigenvalues of the flux Jacobian $f'(q)$ for the 1D Euler equations are: \begin{align} \lambda_1 & = u-c & \lambda_2 & = u & \lambda_3 & = u+c \end{align} Here $c$ is the sound speed: $$ c = \sqrt{\frac{\gamma p}{\rho}}.$$ These are also the eigenvalues of the coefficient matrix appearing in (\ref{euler_primitive}), and show that acoustic waves propagate at speeds $\pm c$ relative to the fluid velocity $u$. There is also a characteristic speed $\lambda_2 =u$ corresponding to the transport of entropy at the fluid velocity, as discussed further below. The eigenvectors of the coefficient matrix appearing in (\ref{euler_primitive}) are: \begin{align}\label{euler_evecs} r_1 & = \begin{bmatrix} -\rho/c \\ 1 \\ - \rho c \end{bmatrix} & r_2 & = \begin{bmatrix} 1 \\ 0 \\ 0 \end{bmatrix} & r_3 & = \begin{bmatrix} \rho/c \\ 1 \\ \rho c \end{bmatrix}. \end{align} These vectors show the relation between jumps in the primitive variables across waves in each family. The eigenvectors of the flux Jacobian $f'(q)$ arising from the conservative form (\ref{euler_conserved}) would be different, and would give the relation between jumps in the conserved variables across each wave. Notice that the second characteristic speed, $\lambda_2$, depends only on $u$ and that $u$ does not change as we move in the direction of $r_2$. In other words, the 2-characteristic velocity is constant on 2-integral curves. This is similar to the wave that carries changes in the tracer that we considered in [Shallow_tracer.ipynb](Shallow_tracer.ipynb). We say this characteristic field is **linearly degenerate**; it admits neither shocks nor rarefactions. In a simple 2-wave, all characteristics are parallel. A jump in this family carries a change only in the density, and is referred to as a **contact discontinuity**. The other two fields have characteristic velocities that **do** vary along the corresponding integral curves; thus the 1-wave and the 3-wave in any Riemann solution will be either a shock or a rarefaction. We say these characteristic fields are **genuinely nonlinear**. Mathematically, the $p$th field is linearly degenerate if $$\nabla \lambda_p(q) \cdot r_p(q) = 0$$ and genuinely nonlinear if $$\nabla \lambda_p(q) \cdot r_p(q) \ne 0.$$ ### Entropy Another important quantity in gas dynamics is the **specific entropy**: $$ s = c_v \log(p/\rho^\gamma) + C,$$ where $c_v$ and $C$ are constants. From the expression (\ref{euler_evecs}) for the eigenvector $r_2$, we see that the pressure and velocity are constant across a 2-wave. A simple 2-wave is also called an **entropy wave** because a variation in density while the pressure remains constant requires a variation in the entropy of the gas as well. On the other hand a simple acoustic wave (a continuously varying pure 1-wave or 3-wave) has constant entropy throughout the wave; the specific entropy is a Riemann invariant for these families. A shock wave (either a 1-wave or 3-wave) satisfies the Rankine-Hugoniot conditions and exhibits a jump in entropy. To be physically correct, the entropy of the gas must *increase* as gas molecules pass through the shock, leading to the **entropy condition** for selecting shock waves. We have already seen this term used in the context of shallow water flow even though the entropy condition in that case did not involve the physical entropy. ### Riemann invariants Since the Euler equations have three components, we expect each integral curve (a 1D set in 3D space) to be defined by two Riemann invariants. These are: \begin{align} 1 & : s, u+\frac{2c}{\gamma-1} \\ 2 & : u, p \\ 3 & : s, u-\frac{2c}{\gamma-1}. \end{align} ### Integral curves The level sets of these Riemann invariants are two-dimensional surfaces; the intersection of two appropriate level sets defines an integral curve. The 2-integral curves, of course, are simply lines of constant pressure and velocity (with varying density). Since the field is linearly degenerate, these coincide with the Hugoniot loci. We can determine the form of the 1- and 3-integral curves using the Riemann invariants above. For a curve passing through $(\rho_0,u_0,p_0)$, we find \begin{align} \rho(p) &= (p/p_0)^{1/\gamma} \rho_0,\\ u(p) & = u_0 \pm \frac{2c_0}{\gamma-1}\left(1-(p/p_0)^{(\gamma-1)/(2\gamma)}\right). \end{align} Here the plus sign is for 1-waves and the minus sign is for 3-waves. Below we plot the projection of some integral curves on the $p-u$ plane. ```python %matplotlib inline ``` ```python from exact_solvers import Euler from exact_solvers import euler_stripes from ipywidgets import widgets from ipywidgets import interact State = Euler.Primitive_State gamma = 1.4 ``` ```python interact(Euler.plot_integral_curves, gamma=widgets.FloatSlider(min=1.1,max=3,value=1.4), rho_0=widgets.FloatSlider(min=0.1,max=3.,value=1., description=r'$\rho_0$')); ``` ## Rankine-Hugoniot jump conditions The Hugoniot loci for 1- and 3-shocks are \begin{align} \rho(p) &= \left(\frac{1 + \beta p/p_0}{p/p_l + \beta} \right),\\ u(p) & = u_0 \pm \frac{2c_0}{\sqrt{2\gamma(\gamma-1)}} \left(\frac{1-p/p_0}{\sqrt{1+\beta p/p_0}}\right), \\ \end{align} where $\beta = (\gamma+1)/(\gamma-1)$. Here the plus sign is for 1-shocks and the minus sign is for 3-shocks. Below we plot the projection of some integral curves on the $p-u$ plane. ```python interact(Euler.plot_hugoniot_loci, gamma=widgets.FloatSlider(min=1.1,max=3,value=1.4), rho_0=widgets.FloatSlider(min=0.1,max=3.,value=1., description=r'$\rho_0$')) ``` ### Entropy condition As mentioned above, a shock wave is physically relevant only if the entropy of the gas increases as the gas particles move through the shock. A discontinuity satisfying the Rankine-Hugoniot jump conditions that violates this entropy condition (an "entropy-violating shock") is not physically correct and should be replaced by a rarefaction wave in the Riemann solution. This physical entropy condition is equivalent to the mathematical condition that for a 1-shock to be physically relevant the 1-characteristics must impinge on the shock. If the entropy condition is violated, the 1-characteristics would spread out, allowing the insertion of an expansion fan (rarefaction wave). ## Exact solution of the Riemann problem The general Riemann solution is found following the steps listed below. This is essentially the same procedure used to determine the correct solution to the Riemann problem for the shallow water equations in [Shallow_water.ipynb](Shallow_water.ipynb), where more details are given. The Euler equations are a system of three equations and the general Riemann solution consists of three waves, so we must determine two intermediate states rather than the one intermediate state in the shallow water equations. However, it is nearly as simple because of the fact that we know the pressure and velocity are constant across the 2-wave, and so there is a single intermediate pressure $p_m$ and velocity $u_m$ in both intermediate states, and it is only the density that takes different values $\rho_{m1}$ and $\rho_{m2}$. Moreover any jump in density is allowed across the 2-wave, and we have expressions given above for how $u(p)$ varies along any integral curve or Hugoniot locus, expressions that do not explicitly involve $\rho$. So we can determine the intermediate $p_m$ by finding the intersection point of two relevant curves, in step 3 of this general algorithm: 1. Define a piecewise function giving the middle state velocity $u_m$ that can be connected to the left state by an entropy-satisfying shock or rarefaction, as a function of the middle-state pressure $p_m$. 2. Define a piecewise function giving the middle state velocity $u_m$ that can be connected to the right state by an entropy-satisfying shock or rarefaction, as a function of the middle-state pressure $p_m$. 3. Use an iterative solver to find the intersection of the two functions defined above. 4. Use the Riemann invariants to find the intermediate state densities and the solution structure inside any rarefaction waves. ### The structure of centered rarefaction waves Step 4 above requires finding the structure of rarefaction waves. This can be done using the the fact that the Riemann invaiants are constant through the rarefaction wave. See Chapter 14 of <cite data-cite="fvmhp"><a href="riemann.html#fvmhp">(LeVeque, 2002)</a></cite> for more details. **Give the formulas here?** ## Examples of Riemann solutions Here we present some representative examples of Riemann problems and solutions. The examples chosen are closely related to the examples used in [Shallow_water.ipynb](Shallow_water.ipynb) and you might want to refer back to that notebook and compare the results. If you wish to examine the Python code for this chapter, see: - [exact_solvers/Euler.py](exact_solvers/Euler.py) ### Problem 1: Sod shock tube First we consider the classic shock tube problem. The initial condition consists of high density and pressure on the left, low density and pressure on the right and zero velocity on both sides. The solution is composed of a shock propagating to the right (3-shock), while a left-going rarefaction forms (1-rarefaction). In between these two waves, there is a jump in the density, which is the contact discontinuity (2-wave) in the linearly degenerate characteristic field. Note that this set of initial conditions is analogous to the "dam break" problem for shallow water quations, and the resulting structure of the solution is very similar to that obtained when those equations are solved with the addition of a scalar tracer. However, in the Euler equations the entropy jump across a 2-wave does affect the fluid dynamics on either side, so this is not a passive tracer and solving the Riemann problem is slightly more complex. ```python left_state = State(Density = 3., Velocity = 0., Pressure = 3.) right_state = State(Density = 1., Velocity = 0., Pressure = 1.) Euler.riemann_solution(left_state,right_state) ``` Here is a plot of the solution in the phase plane, showing the integral curve connecting the left and middle states, and the Hugoniot locus connecting the middle and right states. ```python Euler.phase_plane_plot(left_state, right_state) ``` ### Problem 2: Symmetric expansion Next we consider the case of equal densities and pressures, and equal and opposite velocities, with the initial states moving away from each other. The result is two rarefaction waves (the contact has zero strength). ```python left_state = State(Density = 1., Velocity = -3., Pressure = 1.) right_state = State(Density = 1., Velocity = 3., Pressure = 1.) Euler.riemann_solution(left_state,right_state); ``` ```python Euler.phase_plane_plot(left_state, right_state) ``` ### Problem 3: Colliding flows Next, consider the case in which the left and right states are moving toward each other. This leads to a pair of shocks, with a high-density, high-pressure state in between. ```python left_state = State(Density = 1., Velocity = 3., Pressure = 1.) right_state = State(Density = 1., Velocity = -3., Pressure = 1.) Euler.riemann_solution(left_state,right_state) ``` ```python Euler.phase_plane_plot(left_state, right_state) ``` ## Plot particle trajectories In the next plot of the Riemann solution in the $x$-$t$ plane, we also plot the trajectories of a set of particles initially distributed along the $x$ axis at $t=0$, with the spacing inversely proportional to the density. The evolution of the distance between particles gives an indication of how the density changes. ```python left_state = State(Density = 3., Velocity = 0., Pressure = 3.) right_state = State(Density = 1., Velocity = 0., Pressure = 1.) Euler.plot_riemann_trajectories(left_state, right_state) ``` Recall that the evolution of the distance between particles gives an indication of how the density changes. Note that it increases across the shock wave and decreases through the rarefaction wave, and that in general there is a jump in density across the contact discontinuity. ## Riemann solution with a colored tracer Next we plot the Riemann solution with the density plot also showing an advected color to help visualize the flow better. The fluid initially to the left of $x=0$ is colored red and that initially to the right of $x=0$ is colored blue, with stripes of different shades of these colors to help visualize the motion of the fluid. For the code that produces the plot, see this file: [exact_solvers/euler_stripes.py](exact_solvers/euler_stripes.py) Let's plot the Sod shock tube data with this colored tracer: ```python def plot_exact_riemann_solution_stripes_t_slider(t): euler_stripes.plot_exact_riemann_solution_stripes(rho_l=3.,u_l=0.,p_l=3., rho_r=1.,u_r=0.,p_r=1., gamma=gamma,t=t) interact(plot_exact_riemann_solution_stripes_t_slider, t=widgets.FloatSlider(min=0.,max=1.,step=0.1,value=0.5)); ``` Note the following in the figure above: - The edges of each stripe are being advected with the fluid velocity, so you can visualize how the fluid is moving. - The width of each stripe initially is inversely proportional to the density of the fluid, so that the total mass of gas within each stripe is the same. - The total mass within each stripe remains constant as the flow evolves, and the width of each stripe remains inversely proportional to the local density. - The interface between the red and blue gas moves with the contact discontinuity. The velocity and pressure are constant but the density can vary across this wave. ## Interactive Riemann solver Here you can set up your own Riemann problem and immediately see the solution. If you don't want to download and run the notebook, an online interactive version is [here](http://sagecell.sagemath.org/?z=eJytWNtu47YWfQ-Qf2BnHiLJsmzFGeAgqIsCnfaxOCgGpw-DwJAtOiaOLgwviTJf30VSlKjYSgdog8FEIdfeXPvKLbGat0KRRtf8lRSSNPz6irm1ulC8alXF9hl_NU9mn1fq-uoo2prIA-OvWcsVq9k3Snqho2yrZ3p9dX1V0iOhXXFQO8FoXTTNDltasbaJnnZV-rQTabf9vW1oqtyvx6Kui22e3cX311cEPx8-fPiDKi0aok7U6SJeB1GtXf3D6SZctPuK1uSFqRNhDVOsqIhUhaKSmOPwn8icWvx8geSgiUlyaGuuFS1JoQjsoQS2NiXhLWuUJB2JXk5UUDzUxSvZU1KQ_LP3mRDFazyqnpzBGqglz_SgWiEBpZbzoW0kFc847kkXjQJXkNwDaDZbrSDjwF_FqU11yh-ywSHuAeu7imyNZV_XD25NDyv5wyrc-HXYuO1XRiXC7ohAiV-xSkSgxG8YJW7tI_nF-Y1U9Og8JtjjSTm_IyRUSo3_HJpbGpGN8jLP4iQyxJZknX1KrD0JLEiS29jDxRlcBHABuHDw72IjW40VySkte0IHS6jhmXwSyh2UgOTKkok9RlzACIsRcejNouKnYsJ4Fd1mif2rB-6pGhELixjAgRUnevg_ObaCHIpnBu7IUbfHjjbISxulBblNIpiwAMVQEfmRrO-HJEQQkMLk5pdBFSmpQj7S8gcEtUPuNY_ZzYgXruBMQYbWfSSf6ZE1Ln-hkT4K1NdBI4uldfVJP7YNQ4-o2gPr6fawnYXtcixtSVXU-7IgnNxbW4wVMGIVxjnPlhFfIRJxkkQX3RnHF0_YnJ9gMsacIC6eIP72BG_WDmZpCRtmLfA5cus0JKPamCQkivKls2kA5guTD4lbvXzcZt6c7ztOXDxOxPE0ti7l0OMQXWFDnC9fimdqWmNB5KnFLvJRoCcd0YSHhDQtnp_Yrop4fO8zaMwl5Cv_aQvz7n1avXUn5EY4rSQdkG-TZ0D-W5yF4XzOVcxx3Xw31ymy72YnNo2ld9vSczlvYzUry4r6ZpoSTfavBEVYomRd6dmThaSBeTxlzbFNCaMiJbV8xKnuSo5wUEoiRGNh8-I2S4-6qnbuvtl-EZqmnWorXMB0md_Fns1vcKJUosWZgS9lioZaU3NXyv4A0pjWSk604kO7AosftnnYjv4JPXN2K7brLA-YrgNff8Sli_Aj-LoqSYNudCo4p800zj2pIFGDRvlnIRr4994bVTKnCHf2MxWPNOyVoxgs8fHTMMkH168NvkTwpmEtaSPt_R_c6zts2btvaIJ5tnJtCaVtIcEFPkGLS2jxNhk_-nnHlo0tmvBefJHuyvtGRSujT_Eg9cXNLsrOYUbg3gtgKICMvmCtK0R7GY_ZMznOVp5tEiNPaFwbjdEwGKDxjc5JNHq1m4HC5XiiIDcKrCK3bEt2RBxGR7-53ldzGi0lx-XgYxAept2GlfSh760Tb6y7G6yzc0xvhphaN12ectn01t3NWSfes25Wo154yXO6buowE9EQ5POm1bfE56LSJqnHbt220szNdrreFxLDb9tczj-4rDNd3Mwg93i0JlSskbw40AhXXGr-rde-8oFXI14Bv87-k9RFF0Gu2Muoi-NV8OeLnN5_nbSuTBR4_mnIoOHbUUmeF47L6eHNAcVb0klmHwsv1pmO361U3xbM6BDMGomfHcwMh4eOxX6KW9hx0AptzoTcBBAd7MNFIcQ3H0vHjwc6XwKNeXk1Trpx3y2C2WFQsRnz06vo2FJvpirErApuOOCMxCjJ-5m6V9UjNhYhLGLTT9QTxNjlcAsYPt2P286UYexeGOC2qPupX-k3c7eZD3v5uHfrBV1peMTtiNj0CDFFbEbEnUNshr07L-JfoAxXMmWr57nqWaZ6jqCe46WnrLTnxC9x4vOc-CwnPseJz3HiU07cc-r7RB_c1PktdVSB8Algp7WqxTuyyRLAUjMJdX5yOzIzQfBKZXjCq2aEX5J9o9soX6d3Qy4KVuOSRWVvx1dqt9UUZoDB8s1nexO_3qQ3_6PmHcY-_rd_hb3p4UXn0OuHZNMzwHjE0AjQBJpHGm3CmdKgvzLTOkErK8pyJ_XeWBPl6SZlizxowE_GDs8TQsHIBOusUJc-pWiD9IWV6rTdxFMIXFTRyNoD8VAzWh-Umwb4NFkGaSyzZrpcsuPRvOkbqaVFnRmUSap2rxWro8jsLzGQJVYuNVKL4U_vf_u5CAMyxqKD9B-KcGHUv9mgOdD4twni0KBtOwCfPLszt8n11c925kW3HZNjN_OZydb6Vlbo0QIu_5SayRFCha4U_JfqcXf56c32Ok75u8K25uf2c6NcvK_8PWFAxs9g7vsNn7wlo6jefjcJv9PwyQtvAPZfTcIG-2T1f7W6UjKoTM3BDx4iPEQ4iFVkIGLyTenvb-uhjIF85_OgORKFnhI0BfdhMPySEtQE9A2LQ59Agadd_BeW1ABm&lang=python). ```python interact(euler_stripes.plot_exact_riemann_solution_stripes, rho_l=widgets.FloatSlider(min=1.,max=10.,step=0.1,value=3.,description=r'$\rho_l$'), u_l=widgets.FloatSlider(min=-10.,max=10.,step=0.1,value=0.,description=r'$u_l$'), p_l=widgets.FloatSlider(min=1.,max=10.,step=0.1,value=3.,description=r'$p_l$'), rho_r=widgets.FloatSlider(min=1.,max=10.,step=0.1,value=1.,description=r'$\rho_r$'), u_r=widgets.FloatSlider(min=-10.,max=10.,step=0.1,value=0.,description=r'$u_r$'), p_r=widgets.FloatSlider(min=1.,max=10.,step=0.1,value=1.,description=r'$p_r$'), gamma=widgets.FloatSlider(min=1.1,max=2.,step=0.1,value=1.4,description=r'$\gamma$'), t=widgets.FloatSlider(min=0.,max=1.,step=0.1,value=0.5)); ``` ## Riemann problems with vacuum A vacuum state (with zero pressure and density) in the Euler equations is similar to a dry state (with depth $h=0$) in the shallow water equations. It can arise in the solution of the Riemann problem in two ways: 1. An initial left or right vacuum state: in this case the Riemann solution consists of a single rarefaction, connecting the non-vacuum state to vacuum. 2. A problem where the left and right states are not vacuum but middle states are vacuum. Since this means the middle pressure is smaller than that to the left or right, this can occur only if the 1- and 3-waves are both rarefactions. These rarefactions are precisely those required to connect the left and right states to the middle vacuum state. ### Initial vacuum state The velocity plot looks a bit strange, but note that the velocity is undefined in vacuum. ```python left_state = State(Density =0., Velocity = 0., Pressure = 0.) right_state = State(Density = 1., Velocity = -3., Pressure = 1.) Euler.riemann_solution(left_state,right_state) ``` ```python Euler.phase_plane_plot(left_state, right_state) ``` ### Middle vacuum state ```python left_state = State(Density =1., Velocity = -10., Pressure = 1.) right_state = State(Density = 1., Velocity = 10., Pressure = 1.) Euler.riemann_solution(left_state,right_state) ``` ```python Euler.phase_plane_plot(left_state, right_state) ```
If two paths are homotopic, then their reverses are homotopic.
function blkStruct = slblocks blkStruct.Name = sprintf('DC Motor Library'); blkStruct.OpenFcn = 'dc_motor_lib'; blkStruct.MaskDisplay = 'disp(''DC Motor Library'')'; % Information for Simulink Library Browser Browser(1).Library = 'dc_motor_lib'; Browser(1).Name = 'DC Motor Library'; Browser(1).IsFlat = 1;% Is this library "flat" blkStruct.Browser = Browser;
theory Simulink imports Main begin (*fun Gain :: "nat \<Rightarrow> nat \<Rightarrow> nat" where "Gain x y = mult x y"*) primrec add :: "nat \<Rightarrow> nat \<Rightarrow> nat" where "add 0 n = n" | "add (Suc m) n = Suc(add m n)" primrec mult :: "nat \<Rightarrow> nat \<Rightarrow> nat" where "mult 0 n = 0" | "mult (Suc m) n = add (mult m n) m" primrec pow :: "nat => nat => nat" where "pow 0 x = Suc 0" | "pow (Suc n) x = mult x (pow n x)" definition threegains :: "nat \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> nat" where "threegains t x y z = t*x*y*z" declare threegains_def[simp] primrec feedback :: "nat \<Rightarrow> nat" where "feedback 0 = Suc(0)"| "feedback (Suc t) = (feedback t)*3" theorem sum_of_naturals: "2 * (\<Sum>i::nat=0..n. i) = n * (n + 1)" (is "?P n" is "?S n = _") proof (induct n) show "?P 0" by simp next fix n have "?S (n + 1) = ?S n + 2 * (n + 1)" by simp assume "?P n" also have "\<dots> + 2 * (n + 1) = (n + 1) * (n + 2)" by simp finally show "?P (Suc n)" by simp qed lemma th1: "threegains 3 4 5 6 = 360" apply(simp) done (* lemma th3: "feedback t = pow 3 t" apply(induct t) apply(simp) apply(auto) apply(sym) done *) (*\<lbrakk> if foo then a \<noteq> a else b \<noteq> b \<rbrakk>*) (* lemma th2: "\<not>(t>5) \<or> ((feedback t) > 200)" (is "?H(t)" is "?P(t)\<or>?Q(t)" is "(?P(t))\<or>(?F(t) > 200)") proof(induct t) case 0 show "?P 0 \<or> ?Q 0" by simp next have b: "?F (Suc(t)) \<ge> ?F(t)" by simp assume a:" ?F(t) > 200" from b and a have c: "?F(Suc(t)) > 200" by simp from c have e: "?Q(Suc(t))" by simp assume d: "?P(t) = False" from d have f:"?P(Suc(t)) = False" by simp from f and e have g: "?P(Suc(t))\<or>?Q(Suc(t))" by simp from a and d and g have h: "?P(t)\<or>?Q(t) \<Longrightarrow> ?P(Suc(t))\<or>?Q(Suc(t))" by simp from a and d have "?H(Suc(t))" by simp qed *) lemma th2: "\<not>(t>5) \<or> ((feedback t) > 200)" proof (induct t) case 0 show ?case by simp next case (Suc t) thus ?case proof assume "\<not>t > 5" moreover have "feedback 6 = 729" by code_simp -- \<open>"simp add: eval_nat_numeral" would also work\<close> ultimately show ?thesis by (cases "t = 5") auto next assume "feedback t > 200" thus ?thesis by simp qed qed lemma th3: "\<not>(t>5) \<or> ((feedback t) > 200)" proof (induct t) case (Suc t) moreover have "feedback 6 = 729" by code_simp ultimately show ?case by (cases "t = 5") auto qed simp_all
(* -------------------------------------------------------------------- *) From mathcomp Require Import all_ssreflect all_algebra finmap. From mathcomp.analysis Require Import boolp classical_sets ereal reals realseq realsum distr xfinmap. (* ------- *) Require Import xbigops misc maxflow elift. Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Unset SsrOldRewriteGoalsOrder. Import GRing.Theory Num.Theory Order.Theory. Local Open Scope ring_scope. (* -------------------------------------------------------------------- *) Local Notation edge T := (vertex T * vertex T)%type. Local Notation "← x" := (inl x) (at level 2). Local Notation "→ x" := (inr x) (at level 2). Local Notation "⇐ x" := (inl (Some x)) (at level 2). Local Notation "⇒ x" := (inr (Some x)) (at level 2). (* ==================================================================== *) Local Notation distr T := {distr T / R}. (* -------------------------------------------------------------------- *) Lemma nbounded_sub_mono (u : nat -> R) : nbounded u -> {α : nat -> nat & {b : bool | {homo α : x y / (x < y)%N} & {homo ((-1) ^+ b \*o (u \o α)) : x y / (x <= y)%N >-> (x <= y)} } }. Proof. move=> bnd_u; pose E n := `[<forall m, (n < m)%N -> (u m < u n)%R>]. case: (discrete.existsTP (fun s : seq nat => {subset E <= s})) => /=; last first. + case/natpred_finiteN => α homo_α Eα; exists α, true => //. move=> m n le_mn; rewrite expr1 /= !mulN1r ler_oppr opprK. move: le_mn; rewrite leq_eqVlt => /orP[/eqP->//|lt_mn]. by have /asboolP := Eα m => /(_ (α n) (homo_α _ _ lt_mn)) /ltW. case=> s sub_sE; pose N := \max_(i <- s) i.+1. have h k : (N <= k)%N -> exists k', (k < k')%N && (u k <= u k'). + move=> le_Nk; case/boolP: (E k). * move/sub_sE => k_in_s; move: le_Nk; rewrite /N. rewrite (perm_big _ (perm_to_rem (k_in_s))) /=. by rewrite big_cons geq_max ltnn. case/existsp_asboolPn=> k' /asboolPn /imply_asboolPn. case=> lt_kk' /negP; rewrite -leNgt => le_ukuk'. by exists k'; rewrite lt_kk' le_ukuk'. pose α := fix α n := if n is n.+1 then xchoose (h _ (leq_addr (α n - N) N)) else N%N. have geN_α n : (N <= α n)%N. + elim: n => //= n ih; have := xchooseP (h _ (leq_addr (α n - N) N)). case/andP; rewrite {1}subnKC // => /(leq_trans _) h' _. by apply/h'; apply/(leq_trans ih). have homo_α : {homo α : x y / (x < y)%N}. + apply/homoS_lt => -[|n] /=. * have := xchooseP (h _ (leq_addr (N - N) N)). by case/andP; rewrite subnn {1}addn0. set m := xchoose _; have := xchooseP (h _ (leq_addr (m - N) N)). case/andP; rewrite {1}subnKC //. have := xchooseP (h _ (leq_addr (α n - N) N)). rewrite {1}subnKC ?geN_α // => /andP[h' _]. by apply/(leq_trans _ h')/ltnW/geN_α. exists (fun n => α n.+1), false => //. + by move=> m n; rewrite -ltnS => /homo_α. apply/homoS_ler=> n; rewrite expr0 /= !mul1r. set m := xchoose _; have := xchooseP (h _ (leq_addr (m - N) N)). set k := xchoose _ => /andP[]; rewrite subnKC //. have := xchooseP (h _ (leq_addr (α n - N) N)); rewrite -/m. by rewrite subnKC ?geN_α // => /andP[/ltnW /(leq_trans (geN_α _))]. Qed. (* -------------------------------------------------------------------- *) Lemma BW (u : nat -> R) : nbounded u -> {α : nat -> nat | {homo α : x y / (x < y)%N} & iscvg (u \o α)}. Proof. move=> bnd; have bndcp f : nbounded (u \o f). + by case: bnd => v hv; exists v => n; apply/hv. case/nbounded_sub_mono: (bnd) => [α] [[]] homo_α homo_uα; last first. + exists α => //; have /ncvg_mono_bnd: nbounded (u \o α) by apply/bndcp. case=> [x y /homo_uα|]; first by rewrite !expr0 /= !mul1r. by move=> l cvl; exists l. exists α => //; have /ncvg_mono_bnd: nbounded ((\- u) \o α). + case: bnd; elim/nbh_finW => e gt0_e /= h. exists (NFin _ gt0_e) => n /=; move: (h (α n)); rewrite !inE. by rewrite !subr0 normrN. case=> [x y /homo_uα|]; first by rewrite !expr1 /= !mulN1r. move=> l cvl; exists (- l) => /=; apply/(ncvg_eq (v := \- (\- u \o α))). + by move=> x /=; rewrite opprK. + by apply/(@ncvgN _ _ l%:E). Qed. (* -------------------------------------------------------------------- *) Axiom DCT : forall {T: choiceType} (un : nat -> T -> R) (u g : T -> R), (forall x, ncvg (un^~ x) (u x)%:E) -> (forall n x, `|un n x| <= g x) -> summable g -> summable u /\ ncvg (fun n => psum (un n)) (psum u)%:E. (* -------------------------------------------------------------------- *) Lemma DCT_swap {T: choiceType} (un : nat -> T -> R) (u g : T -> R) : (forall x, ncvg (un^~ x) (u x)%:E) -> (forall n x, `|un n x| <= g x) -> summable g -> real_of_er (nlim (fun n => psum (un n))) = psum (fun a => (real_of_er (nlim (un^~ a)))). Proof. move=> h1 h2 h3; case: (DCT h1 h2 h3) => _ /nlimE ->. by apply/eq_psum => x /=; rewrite (nlimE (h1 x)). Qed. (* -------------------------------------------------------------------- *) Lemma DCT_ncvg {T: choiceType} (un : nat -> T -> R) (u g : T -> R) : (forall x, ncvg (un^~ x) (u x)%:E) -> (forall n x, `|un n x| <= g x) -> summable g -> ncvg (fun n => psum (un n)) (psum u)%:E. Proof. by move=> h1 h2 h3; case: (@DCT T un u g). Qed. (* ==================================================================== *) Section CountableSeqCompacityForDistr. Context {A : countType} (μ : nat -> distr A). (* -------------------------------------------------------------------- *) Lemma strcvg : {Ω : nat -> nat | {homo Ω : x y / (x < y)%N} & forall a : A, iscvg (fun n => μ (Ω n) a)}. Proof. have α a θ: {α : nat -> nat | {homo α : x y / (x < y)%N} & iscvg (μ^~ a \o θ \o α)}. + case: (@BW (μ^~ a \o θ)) => [|α mono_α cvg_μα]; last by exists α. apply/asboolP/nboundedP; exists 2%:R => // n. by rewrite (@le_lt_trans _ _ 1) ?ltr1n // ger0_norm //= le1_mu1. have homo_α a θ : {homo tag (α a θ) : x y / (x < y)%N} by case: (α a θ). pose ω θ n := odflt idfun (omap (fun a => tag (α a θ)) (choice.unpickle n)). have homo_ω k θ: {homo θ : m n / (m < n)%N} -> {homo ω θ k : m n / (m < n)%N}. + move=> homo_θ m n lt_mn; rewrite /ω; case: choice.unpickle => //=. * by move=> a; apply/homo_α. pose Ω := fix Ω k := if k is k'.+1 then let σ := ω (Ω k').2 k' in (σ, (Ω k').2 \o σ) else (idfun, idfun). have Ω1SE i: (Ω i.+1).1 =1 ω (Ω i).2 i by []. have Ω2E i: (Ω i).2 =1 \big[comp/idfun]_(0 <= j < i) (Ω j.+1).1. + elim: i => /= [|i ih] n; first by rewrite big_geq. by rewrite big_nat_recr //= -ih. have ΩD2E n m: (Ω (n + m)%N).2 =1 (Ω n).2 \o \big[comp/idfun]_(0 <= j < m) (Ω (n.+1+j)%N).1 => [k /=|]. + rewrite !Ω2E -addnE (big_cat_nat _ (n := n)) ?leq_addr //=. congr (_ _); rewrite -{1}[n]add0n big_addn addKn. by apply/eq_bigcomp => {}k _; rewrite addnC. have homoΩ2 n: {homo (Ω n).2 : x y / (x < y)%N}. + by elim: n => //= n ih; apply/homo_comp => //=; apply/homo_ω. have homoΩ1 n: {homo (Ω n).1 : x y / (x < y)%N}. + by case: n => //= n; apply/homo_ω/homoΩ2. exists (fun n => (Ω n).2 n) => [|a]. + move=> m n lt_mn; rewrite -{1}[n](subnK (ltnW lt_mn)) addnC. rewrite ΩD2E (@leq_trans ((Ω m).2 n)) //; first by apply/homoΩ2. rewrite (misc.homo_leq_mono (homoΩ2 _)) homo_geidfun //. by apply/homo_bigcomp => k _; apply/homoΩ1. have [p pE]: exists p, p = (choice.pickle a).+1 by exists (choice.pickle a).+1. rewrite (iscvg_shift p); pose T n := (Ω (n + p)%N).2 (n + p)%N. have h: exists2 σ, {homo σ : x y / (x < y)%N} & T =1 (Ω p).2 \o σ. + exists (fun n => (\big[comp/idfun]_(0 <= j < n) (Ω (p.+1+j)%N).1) (n+p)%N). * move=> x y ltxy; rewrite -(homo_ltn_mono (homoΩ2 p)). have /=<- := ΩD2E p x (x+p)%N; have /=<- := ΩD2E p y (y+p)%N. rewrite (leq_trans (homoΩ2 _ (x+p)%N (y+p)%N _)) ?ltn_add2r //. rewrite -{2}[y](@subnK x) ?[(x <= y)%N]ltnW // addnA addnAC. rewrite [in X in (_ <= X)%N]ΩD2E (misc.homo_leq_mono (homoΩ2 _)). by apply/homo_geidfun/homo_bigcomp => k _; apply/homoΩ1. * by move=> n /=; rewrite /T addnC ΩD2E. case: h => σ homoσ TE; pose X := ((μ^~ a) \o (Ω p).2) \o σ. apply/(@iscvg_eq _ _ X); first by move=> k /=; rewrite -/(T _) TE. apply/iscvg_sub => //; rewrite {p T TE X}pE /=; set ξ := Ω _. by rewrite /ω choice.pickleK /=; case: (α a ξ.2). Qed. End CountableSeqCompacityForDistr. (* -------------------------------------------------------------------- *) Lemma strcvg2 {A B : countType} (μ1 : nat -> distr A) (μ2 : nat -> distr B) : { Ω : nat -> nat | {homo Ω : x y / (x < y)%N} & [/\ forall a : A, iscvg (fun n => μ1 (Ω n) a) & forall b : B, iscvg (fun n => μ2 (Ω n) b) ] }. Proof. case: (strcvg μ1) => ω1 mono1 cvg1. case: (strcvg (μ2 \o ω1)) => ω2 mono2 cvg2. (exists (ω1 \o ω2); last split) => // [m n|a]. + by move/mono2/mono1. + by apply/(iscvg_sub (u := (μ1 \o ω1)^~ a) (σ := ω2)). Qed. (* ==================================================================== *) Section RevStrassen. Context {A B : finType}. Context (ε δ : R) (μ1 : distr A) (μ2 : distr B) (S : pred (A * B)). Hypothesis (ge0_ε : 0 <= ε) (ge0_δ : 0 <= δ). Hypothesis alift : elift ε δ μ1 μ2 S. Theorem StrassenI X : \P_[μ1] X <= Ω ε * \P_[μ2] (fun y => [exists x in X, S (x, y)]) + δ. Proof. case: alift => /= -[μL μR] [EL ER RμL RμR /edist_le -/(_ ge0_ε) /= leδ]. pose T := [pred ab : option A * option B | if ab is (Some a, _) then X a else false]. move/(_ T): leδ; rewrite !pr_dmargin => /le_trans. rewrite -(eqr_pr _ EL) -(eqr_pr _ ER) !pr_dmargin; apply. rewrite ler_add2r ler_pmul2l ?gt0_Ω //; apply/le_in_pr => /=. case=> [[a|] b] // /RμR /=; rewrite !inE /= => Sab aX. by apply/existsP; exists a; rewrite Sab andbT. Qed. End RevStrassen. (* ==================================================================== *) Section FinStrassen. Context {A B : finType}. Context (ε δ : R) (μ1 : distr A) (μ2 : distr B) (S : pred (A * B)). Hypothesis (ge0_ε : 0 <= ε) (ge0_δ : 0 <= δ). Hypothesis mono : forall X, \P_[μ1] X <= Ω ε * \P_[μ2] (fun y => [exists x in X, S (x, y)]) + δ. Local Notation ω := (dweight μ2 + Ω (- ε) * δ). Local Notation N := (option A + option B)%type. Lemma ge0_ω : 0 <= ω. Proof. by apply/addr_ge0/mulr_ge0 => //; rewrite ?(ge0_pr, ge0_Ω). Qed. Local Hint Immediate ge0_ω : core. Local Notation ge0 := (ler01, ge0_Ω, ge0_ω, ge0_ε, ge0_δ, ge0_mu, ler0n). (* -------------------------------------------------------------------- *) Section VertexCase. Context (P : vertex N -> Prop). Hypothesis Psrc : P ⊤. Hypothesis Pdst : P ⊥. Hypothesis PLN : P (↓ (← None)). Hypothesis PL : forall a, P (↓ (⇐ a)). Hypothesis PRN : P (↓ (→ None)). Hypothesis PR : forall b, P (↓ (⇒ b)). Lemma vtx_ind v : P v. Proof. by case: v => -[[|]|[[a|]|[b|]]]. Qed. End VertexCase. (* -------------------------------------------------------------------- *) Definition c (e : edge N) : R := match e.1, e.2 return R with | ⊤, ↓ (← (None )) => ω - Ω (- ε) * (dweight μ1) | ⊤, ↓ (⇐ a ) => Ω (- ε) * μ1 a | ↓ (→ (None )), ⊥ => Ω (- ε) * δ | ↓ (⇒ b ), ⊥ => μ2 b | ↓ (← None), ↓ (→ _ ) => ω | ↓ (← _ ), ↓ (→ None) => ω | ↓ (⇐ a), ↓ (⇒ b) => (S (a, b))%:R * ω | _, _ => 0 end. (* -------------------------------------------------------------------- *) Lemma isnetwork_c : isnetwork (finfun c). Proof. apply/networkP=> /= -[a b]; elim/vtx_ind: b; elim/vtx_ind: a => *; rewrite ?ffunE /c //=; try by rewrite ?mulr_ge0 1?ge0. rewrite -addrA -mulrBr -(@pmulr_rge0 _ (Ω ε)) ?gt0_Ω //. rewrite [X in _ <= X]mulrDr mulrA -ΩD subrr Ω0 mul1r addrA. rewrite subr_ge0 (le_trans (mono _)) // ler_add2r ler_pmul2l ?gt0_Ω //. by apply/le_in_pr. Qed. Local Notation NF := (Network isnetwork_c). Local Notation cut := (pred N). (* -------------------------------------------------------------------- *) Lemma enum_VN_perm : perm_eq (enum {: vertex N}) (⊤ :: ⊥ :: ↓ (← None) :: ↓ (→ None) :: [seq ↓ (⇐ a) | a : A] ++ [seq ↓ (⇒ b) | b : B]). Proof. have h: perm_eql (enum {: vertex N}) [seq Vertex x | x : bool + N]. + apply/permPl; apply/uniq_perm; rewrite ?enum_uniq //. - by rewrite map_inj_uniq ?enum_uniq // => ?? []. by case=> v; rewrite mem_enum; apply/esym/map_f; rewrite enumT. rewrite /image_mem [X in _ ++ X]map_comp [X in X ++ _]map_comp. rewrite -map_cat -!map_cons {}h; apply/perm_map. set s1 := (X in X ++ _); set s2 := (X in _ ++ X). rewrite (permPl enum_sum_perm) /=. rewrite (perm_cat2rE _ (perm_map _ enum_bool_perm)) /=. rewrite !perm_cons [X in _ ++ X]map_comp [X in X ++ _]map_comp. rewrite -map_cat -!map_cons; apply/perm_map => {s1 s2}. rewrite (permPl enum_sum_perm) /=. rewrite (perm_cat2rE _ (perm_map _ enum_option_perm)) /= perm_cons. rewrite perm_sym -cat1s -perm_catCA /= perm_cat //. + by rewrite -[X in perm_eq _ X]map_comp; apply/perm_map. rewrite perm_sym map_comp -map_cons perm_map //. by apply/enum_option_perm. Qed. (* -------------------------------------------------------------------- *) Lemma sum_cLE : \sum_(a : A) c (⊤, ↓ (⇐ a)) = Ω (-ε) * dweight μ1. Proof. rewrite pr_predT psum_fin mulr_sumr; apply/eq_bigr. by move=> a _; rewrite ger0_norm. Qed. (* -------------------------------------------------------------------- *) Lemma sum_cRE : \sum_(b : B) c (↓ (⇒ b), ⊥) = dweight μ2. Proof. rewrite pr_predT psum_fin; apply/eq_bigr. by move=> b _; rewrite ger0_norm. Qed. (* -------------------------------------------------------------------- *) Lemma sum_cLSE : \sum_(a : option A) c (⊤, ↓ (← a)) = ω. Proof. rewrite big_option /= sum_cLE /c /=; set ω := ω. by rewrite addrAC -addrA subrr addr0. Qed. (* -------------------------------------------------------------------- *) Lemma sum_cRSE : \sum_(b : option B) c (↓ (→ b), ⊥) = ω. Proof. by rewrite big_option /= sum_cRE /c /= addrC. Qed. (* -------------------------------------------------------------------- *) Lemma le_NFfc (f : flow NF) e : f e <= c e. Proof. by have /(_ e) /= := flow_lecp f; rewrite ffunE. Qed. (* -------------------------------------------------------------------- *) Lemma ge0_flowNF (f : flow NF) (a : option A) (b : option B): 0 <= f (↓ (← a), ↓ (→ b)). Proof. by apply/flow_ge0; rewrite ffunE; case: a b => [a|] [b|]. Qed. (* -------------------------------------------------------------------- *) Lemma sum_flowNFL (f : flow NF) (a : option A) : \sum_v f (↓ (← a), v) = \sum_b f (↓ (← a), ↓ (→ b)) - f (⊤, ↓ (← a)). Proof. pose XB : {set vertex N} := [set ↓ (→ b) | b : option B]. rewrite (bigID (mem XB)) big_imset /= => [b1 b2 _ _ [//]|]. rewrite (eq_bigl xpredT) //; congr +%R; rewrite (bigD1 ⊤) /=. + by apply/imsetP; case. rewrite flow_antisym big1 ?addr0 // => v /andP[h1 h2]. apply/flow_eq0; rewrite ffunE. + elim/vtx_ind: v h1 h2 => //=; try by case: a. * by move/imsetP=> []; exists None. * by move=> b /imsetP[]; exists (Some b). + by elim/vtx_ind: {h1} v h2. Qed. (* -------------------------------------------------------------------- *) Lemma sum_flowNFR (f : flow NF) (b : option B) : \sum_v f (↓ (→ b), v) = \sum_a f (↓ (→ b), ↓ (← a)) - f (⊥, ↓ (→ b)). Proof. pose XA : {set vertex N} := [set ↓ (← a) | a : option A]. rewrite (bigID (mem XA)) big_imset /= => [a1 a2 _ _ [//]|]. rewrite (eq_bigl xpredT) //; congr +%R; rewrite (bigD1 ⊥) /=. + by apply/imsetP; case. rewrite flow_antisym big1 ?addr0 // => v /andP[h1 h2]. apply/flow_eq0; rewrite ffunE. + by elim/vtx_ind: v h1 h2; case: b. + elim/vtx_ind: v h1 h2 => //. * by move/imsetP=> []; exists None. * by move=> a /imsetP[]; exists (Some a). Qed. (* -------------------------------------------------------------------- *) Lemma kcf_flowNFL (f : flow NF) (a : option A) : f (⊤, ↓ (← a)) = \sum_b f (↓ (← a), ↓ (→ b)). Proof. apply/esym/eqP; rewrite -subr_eq0 -sum_flowNFL. by apply/eqP/flow_kirchnoff. Qed. (* -------------------------------------------------------------------- *) Lemma kcf_flowNFR (f : flow NF) (b : option B) : f (↓ (→ b), ⊥) = \sum_a f (↓ (← a), ↓ (→ b)). Proof. apply/eqP; rewrite -subr_eq0 -(rwP eqP) -[RHS](flow_kirchnoff f (→ b)). rewrite sum_flowNFR [RHS]addrC -flow_antisym; congr +%R. by rewrite -sumrN; apply/eq_bigr=> /= a _; rewrite -flow_antisym. Qed. (* -------------------------------------------------------------------- *) Lemma cweightE (C : cut) : cweight C NF = (if C ← None then \sum_(b | ~~ C (⇒ b)) ω else ω - Ω (-ε) * dweight μ1) + (if C → None then Ω (-ε) * δ else \sum_(a | C (⇐ a)) ω) + ((C ← None && ~~ C → None)%:R * ω) + Ω (-ε) * \P_[μ1] [pred a | ~~ C ⇐ a] + \P_[μ2] [pred b | C ⇒ b] + \sum_(ab | C ⇐ (ab.1) && ~~ C ⇒ (ab.2)) (S ab)%:R * ω. Proof. set c1 := IFP; set c2 := IFP. set Pμ1 := \P_[μ1] _; set Pμ2 := \P_[μ2] [pred b | C ⇒ b]. pose XA : {set vertex N} := [set ↓ (⇐ x) | x in A]. pose XB : {set vertex N} := [set ↓ (⇒ x) | x in B]. rewrite /cweight {1} /index_enum -enumT /=. rewrite (perm_big _ enum_VN_perm) /= 2!big_cons /=. rewrite (bigID (mem XA)) /= -addrA addrCA big_mkcond /=. rewrite (bigD1 (↓ (← None))) //= !ffunE /= big1 ?addr0. + move=> v; rewrite ffunE; case: ifP=> // /andP[]. by elim/vtx_ind: v => // a _ /imsetP[]; exists a. rewrite cut_grdE (_ : _ \notin XA = true) ?andbT. + by apply/imsetP; case. rewrite {1}/c /= if_neg addrCA; set c1a := IFP. rewrite big_andbC big_mkcondr big_imset /= => [a1 a2 _ _ [//]|]. rewrite (eq_bigl xpredT) // [X in X + _ = _](_ : _ = Ω (-ε) * Pμ1). + rewrite /Pμ1 pr_finE mulr_sumr; apply/eq_bigr=> a _. rewrite !cut_grdE ffunE /c /= if_neg; case: ifP=> //= _. - by rewrite !(mul0r, mulr0). - by rewrite !(mul1r, mulr1). rewrite [_ + (_ * Pμ1)]addrC -!addrA; congr +%R. rewrite addrC big_mkcond /= big_cons -big_mkcond /= cut_grdE. rewrite (bigID (mem XB)) /= -[IFF]addr0 -fun2_if; set c1b := IFP. rewrite [LHS]addrC -(_ : c1a + c1b = c1) -?addrA. + rewrite {}/c1a {}/c1b fun2_if !(addr0, add0r); congr IFP. rewrite big_mkcondl big_imset /= => [b1 b2 _ _ [//]|]. rewrite (eq_bigl xpredT) // [RHS]big_mkcond /=. by apply/eq_bigr=> b _; rewrite cut_grdE ffunE. do 2! congr +%R; move=> {c1 c1a c1b}. rewrite big_mkcond (bigD1 (↓ (→ None))) //= big1 ?addr0. + move=> v; rewrite ffunE; case: ifP=> // /andP[]. by elim/vtx_ind: v => // b _ /imsetP[]; exists b. rewrite cut_grdE [X in _ && X](_ : _ = true) ?andbT. + by apply/imsetP; case. rewrite ffunE {1}/c /= [RHS]addrCA; congr +%R. + by do 2? case: ifP; rewrite !Monoid.simpm. rewrite big_cons cut_grdE -[IFF]add0r -fun2_if if_same. rewrite (bigD1 ⊥) //= ffunE {1}/c /= big1 ?addr0. + by move=> v; rewrite ffunE => /andP[_]; elim/vtx_ind: v. set c2a := IFP; rewrite big_cat /= !addrA [RHS]addrAC. congr +%R; last rewrite big_mkcond /= big_map /Pμ2; last first. + rewrite pr_finE [in RHS]/index_enum -enumT; apply/eq_bigr=> b _. rewrite cut_grdE /=; case: ifP=> _; rewrite Monoid.simpm //. rewrite (bigD1 ⊥) //= ffunE {1}/c /= big1 ?addr0 //. by move=> v /andP[_]; rewrite ffunE; elim/vtx_ind: v. rewrite exchange_big big_mkcond (bigD1 (↓ (→ None))) //=. rewrite cut_grdE if_neg; set c2b := IFP; rewrite -(_ : c2a + c2b = c2). + rewrite {}/c2a {}/c2b /c2 fun2_if ?(addr0, add0r); congr IFP. rewrite big_mkcond big_map [RHS]big_mkcond /=. rewrite [in RHS]/index_enum -enumT; apply/eq_bigr=> a _. by rewrite cut_grdE ffunE; case: ifP. rewrite -!addrA; do 2! congr +%R; move=> {c2a c2b c2}. rewrite -big_mkcondl (bigID (mem XB)) /= addrC big1 ?add0r. + move=> v; rewrite -andbA => /and3P [_ h1 h2]; rewrite big_map. rewrite big1 // => a _; rewrite ffunE; move: h1 h2. by elim/vtx_ind: v => // b _ /imsetP[]; exists b. rewrite big_andbC big_mkcondr big_imset /= => [b1 b2 _ _ [//]|]. rewrite (eq_bigl xpredT) // -big_mkcond big_andbC /=. rewrite exchange_big big_map enumT pair_big /=; apply/eq_big. + by move=> ab; rewrite !cut_grdE. by case=> [a b] /=; rewrite !cut_grdE ffunE. Qed. (* -------------------------------------------------------------------- *) Lemma cweightE_cutL : cweight pred0 NF = \sum_a c (⊤, ↓ (← a)). Proof. rewrite cweightE /= !(pr_pred0, pr_predT, big_pred0_eq). rewrite !Monoid.simpm -addrA addNr addr0 big_option /=. rewrite {1}/c /= !pr_predT -[LHS]addr0 -!addrA. do 2! congr+%R; apply/esym/eqP; rewrite addrC subr_eq0. rewrite psum_fin mulr_sumr; apply/eqP/eq_bigr. by move=> a _; rewrite /c /= ger0_norm. Qed. (* -------------------------------------------------------------------- *) Lemma cweight_cutL : cweight pred0 NF = ω. Proof. by rewrite cweightE_cutL -sum_cLSE. Qed. (* -------------------------------------------------------------------- *) Lemma cweightE_cutR : cweight predT NF = \sum_b c (↓ (→ b), ⊥). Proof. rewrite cweightE /= !(pr_pred0, pr_predT, big_pred0_eq). rewrite !Monoid.simpm big_option /=; congr +%R. by rewrite psum_fin; apply/eq_bigr=> b _; rewrite ger0_norm. Qed. (* -------------------------------------------------------------------- *) Lemma cweight_cutR : cweight predT NF = ω. Proof. by rewrite cweightE_cutR -sum_cRSE. Qed. (* -------------------------------------------------------------------- *) Lemma geω_cut (C : cut) : ω <= cweight C NF. Proof. rewrite cweightE; set ω := ω. set sL := C ← None; set sR := C → None; set i1 := IFP; set i2 := IFP; set s4 := (X in _ <= _ + X); set s3 := (X in _ + X + s4); set s2 := (X in _ + X + s3); set s1 := (X in _ + X + s2). have h: forall (I : finType) P, 0 <= \sum_(i : I | P i) ω. + by move=> I P; apply/sumr_ge0=> i _; apply/ge0_ω. have [h1 h2 h3 h4]: [/\ 0 <= s1, 0 <= s2, 0 <= s3 & 0 <= s4]; first (split; try by rewrite 1?mulr_ge0 ?(ge0, ge0_pr)). + by apply/sumr_ge0=> /= ab _; rewrite mulr_ge0 ?ge0. have [hi1 hi2]: [/\ 0 <= i1 & 0 <= i2]; first split. + rewrite /i1; case: ifP=> // _; move/forallP: isnetwork_c=> /=. by move/(_ (⊤, ↓ (← None))); rewrite ffunE /c /=. + by rewrite /i2; case: ifP=> // _; rewrite mulr_ge0 ?ge0. rewrite /i2; case/boolP: {+}sR => hR; last first. + case/boolP: [exists a, C ⇐ a] => [/existsP /= [a Ca]|]. * by rewrite (bigD1 a) //= !addrA 5?ler_paddr // -addrA ler_paddl. rewrite negb_exists => /forallP /= NCA; rewrite /s1 hR andbT. case/boolP: {+}sL; rewrite !Monoid.simpm /= => hL. * by rewrite 3?ler_paddr // -!addrA 2?ler_paddl. rewrite /i1 -if_neg hL /s2 2?ler_paddr // [X in _ <= X]addrAC. rewrite ler_paddr // addrAC -addrA -mulrBr ler_paddr //. rewrite mulr_ge0 ?ge0_Ω // subr_ge0; apply/le_in_pr. by move=> a _ _; apply/NCA. rewrite /i1; case/boolP: {+}sL => hL. + case/boolP: [forall b, C ⇒ b] => [/forallP /=|]; last first. * rewrite negb_forall => /existsP [b CNb]; rewrite (bigD1 b) //=. by rewrite -6!addrA ler_paddr // !addr_ge0 // mulr_ge0 1?ge0. move=> CB; rewrite -![in X in _ <= X]addrA ler_paddl //. rewrite /ω [X in X <= _]addrC ler_add2l 2?ler_paddl //. by rewrite ler_paddr //; apply/le_in_pr=> b _ _; apply/CB. case/boolP: [exists ab : A * B, C ⇐ (ab.1) && ~~ C ⇒ (ab.2) && (S ab)]. + set s := ω - _; rewrite /s4 => /existsP[ab /andP [hCab hab]]. rewrite (bigD1 ab) ?hCab //= hab mul1r [ω + _]addrC addrA. rewrite ler_paddl // addr_ge0 //; last first. * by apply/sumr_ge0=> ? _; rewrite mulr_ge0 ?ge0. do 4! rewrite addr_ge0 //. * by have := hi1; rewrite /i1 -if_neg hL. * by rewrite mulr_ge0 ?ge0. rewrite negb_exists => /forallP /= hS; rewrite ler_paddr //. rewrite /s1 hR !Monoid.simpm -4!addrA ler_addl addrC. rewrite subr_ge0 !addrA addrAC; set s := _ + s3. apply/(@le_trans _ _ (Ω (-ε) * \P_[μ1] [pred a | C ⇐ a] + s2)). + rewrite /s2 -mulrDr ler_pmul2l ?gt0_Ω // -pr_or_indep. * by move=> a; rewrite !inE negbK. by apply/le_in_pr=> a _ _; rewrite 2!inE orbN. rewrite ler_add2r /s addrC -(@ler_pmul2l _ (Ω ε)) ?gt0_Ω //. rewrite mulrDr !mulrA -ΩD subrr Ω0 !Monoid.simpm /s3. pose Pa := [pred a | C ⇐ a]. pose Pb := [pred b | [exists a in Pa, S (a, b)]]. apply/(@le_trans _ _ (Ω ε * \P_[μ2] Pb + δ)); first by apply/mono. rewrite ler_add2r ler_pmul2l ?gt0_Ω //; apply/le_in_pr. move=> b _ /existsP[a /andP[Pa_a Sab]]; move/(_ (a, b)): hS => /=. by rewrite inE in Pa_a; rewrite Pa_a Sab !Monoid.simpm negbK. Qed. (* -------------------------------------------------------------------- *) Lemma mincut_ω : { C : cut | cweight C NF = ω }. Proof. by exists predT; rewrite cweight_cutR. Qed. (* -------------------------------------------------------------------- *) Definition StrassenC := nosimpl (proj1_sig mincut_ω). (* -------------------------------------------------------------------- *) Lemma weight_StrassenC : cweight StrassenC NF = ω. Proof. by rewrite /StrassenC; case: mincut_ω. Qed. (* -------------------------------------------------------------------- *) Lemma min_StrassenC (C : cut) : cweight StrassenC NF <= cweight C NF. Proof. by rewrite weight_StrassenC; apply/geω_cut. Qed. (* -------------------------------------------------------------------- *) Section StrassenUnderMaxFlow. Variable (f : flow NF) (fmax : fmass f = ω). (* -------------------------------------------------------------------- *) Lemma fLE (a : option A) : f (⊤, ↓ (← a)) = c (⊤, ↓ (← a)). Proof. have := cweightE_cutL; rewrite sum_cLSE -fmax cweightE_cutL fmassE. pose XA : {set vertex N} := [set ↓ (← a) | a : option A]. move/esym; rewrite (bigID (mem XA)) big_imset /= => [a1 a2 _ _ [//]|]. rewrite (eq_bigl xpredT) // addrC big1 ?add0r. + move=> v vXA; apply/flow_eq0; rewrite ffunE. * by elim/vtx_ind: v vXA => // [|a'] /imsetP[]; eexists. * by elim/vtx_ind: {vXA} v. move/eqP; rewrite eq_le =>/andP[_ h]; apply/eqP. apply/contraLR: h; rewrite eq_le le_NFfc -!ltNge => lt. rewrite !(bigD1 (P := predT) a) //= ltr_le_add //. by apply/ler_sum=> a' _; apply/le_NFfc. Qed. (* -------------------------------------------------------------------- *) Lemma fRE (b : option B) : f (↓ (→ b), ⊥) = c (↓ (→ b), ⊥). Proof. have := cweightE_cutR; rewrite sum_cRSE -fmax cweightE_cutR fmass_snkE. pose XB : {set vertex N} := [set ↓ (→ b) | b : option B]. move/esym; rewrite (bigID (mem XB)) big_imset /= => [b1 b2 _ _ [//]|]. rewrite (eq_bigl xpredT) // addrC big1 ?add0r. + move=> v vXB; apply/flow_eq0; rewrite ffunE. * by elim/vtx_ind: v vXB => // [|b'] /imsetP[]; eexists. * by elim/vtx_ind: {vXB} v. move/eqP; rewrite eq_le =>/andP[_ h]; apply/eqP. apply/contraLR: h; rewrite eq_le le_NFfc -!ltNge => lt. rewrite !(bigD1 (P := predT) b) //= ltr_le_add //. by apply/ler_sum=> b' _; apply/le_NFfc. Qed. (* -------------------------------------------------------------------- *) Definition SμL_r (ab : A * option B) : R := Ω ε * f (↓ (⇐ (ab.1)), ↓ (→ (ab.2))). Definition SμR_r (ab : option A * B) : R := f (↓ (← (ab.1)), ↓ (⇒ (ab.2))). (* -------------------------------------------------------------------- *) Lemma dweight_SμL : \sum_ab SμL_r ab = dweight μ1. Proof. rewrite /SμL_r; pose F a b := Ω ε * f (↓ (⇐ a), ↓ (→ b)). rewrite -(pair_big xpredT xpredT F) /= {}/F pr_predT psum_fin. apply/eq_bigr=> a _; rewrite ger0_norm // -mulr_sumr. by rewrite -kcf_flowNFL fLE /c /= mulrA -ΩD subrr Ω0 mul1r. Qed. (* -------------------------------------------------------------------- *) Lemma dweight_SμR : \sum_ab SμR_r ab = dweight μ2. Proof. rewrite /SμR_r; pose F a b := f (↓ (← a), ↓ (⇒ b)). rewrite -(pair_big xpredT xpredT F) /= {}/F pr_predT psum_fin. rewrite exchange_big; apply/eq_bigr=> b _ /=; rewrite ger0_norm //. by rewrite -kcf_flowNFR fRE. Qed. (* -------------------------------------------------------------------- *) Lemma isdistr_SμL : isdistr SμL_r. Proof. apply/isdistr_finP=> /=; split => [ab|]. + by rewrite mulr_ge0 ?(ge0, ge0_flowNF). + by rewrite dweight_SμL le1_pr. Qed. (* -------------------------------------------------------------------- *) Lemma isdistr_SμR : isdistr SμR_r. Proof. apply/isdistr_finP=> /=; split => [ab|]. + by rewrite ge0_flowNF. + by rewrite dweight_SμR le1_pr. Qed. (* -------------------------------------------------------------------- *) Definition SμL := nosimpl (mkdistr isdistr_SμL). Definition SμR := nosimpl (mkdistr isdistr_SμR). (* -------------------------------------------------------------------- *) Lemma FinWeakStrassen : elift ε δ μ1 μ2 S. Proof. exists (SμL, SμR) => /=; split. + move=> a; rewrite dfstE psum_fin /= /SμL_r /=. have ->: μ1 a = Ω ε * c (⊤, ↓ (⇐ a)). - by rewrite /c /= mulrA -ΩD subrr Ω0 mul1r. rewrite -fLE kcf_flowNFL mulr_sumr; apply/eq_bigr. by move=> b _; rewrite normrM !ger0_norm // (ge0, ge0_flowNF). + move=> b; rewrite dsndE psum_fin /= /SμR_r /=. have ->: μ2 b = c (↓ (⇒ b), ⊥) by []. rewrite -fRE kcf_flowNFR; apply/eq_bigr. by move=> a _; rewrite ger0_norm // ge0_flowNF. + move=> a b /dinsuppP /=; rewrite /SμL_r /= => /eqP. rewrite mulf_eq0 gt_eqF ?gt0_Ω //=; set e := (X in f X). move=> nz_fe; have := le_NFfc f e; rewrite /c /=. case: S => //; rewrite mul0r le_eqVlt (negbTE (nz_fe)) /=. by rewrite ltNge ge0_flowNF. + move=> a b /dinsuppP /=; rewrite /SμR_r /= => /eqP. set e := (X in f X) => nz_fe; have := le_NFfc f e; rewrite /c /=. case: S => //; rewrite mul0r le_eqVlt (negbTE (nz_fe)) /=. by rewrite ltNge ge0_flowNF. apply/edist_le=> //= X; rewrite !pr_dmargin. pose P1 := [pred x | ((Some x.1, None) \in X) && (x.2 == None :> option B)]. pose P2 := [pred x | ((Some x.1, x.2 ) \in X) && (x.2 != None)]. set P := (X in X <= _); have {P}->: P = \P_[SμL] P1 + \P_[SμL] P2. + rewrite /P (prID _ (fun ab => ab.2 == None)) /=; congr +%R. apply/eq_in_pr=> /= -[a b] _; rewrite !inE /in_mem /=. by case: (b =P None) => [->|_]; rewrite !(andbT, andbF). pose Q1 := [pred x | ((None, Some x.2) \in X) && (x.1 == None :> option A)]. pose Q2 := [pred x | ((x.1 , Some x.2) \in X) && (x.1 != None)]. set Q := (X in _ * X); have {Q}->: Q = \P_[SμR] Q1 + \P_[SμR] Q2. + rewrite /Q (prID _ (fun ab => ab.1 == None)) /=; congr +%R. apply/eq_in_pr=> /= -[a b] _; rewrite !inE /in_mem /=. by case: (a =P None) => [->|_]; rewrite !(andbT, andbF). pose g a b := f (↓ (← a), ↓ (→ b)). have {P1}->: \P_[SμL] P1 = Ω ε * \sum_(a : A | (Some a, None) \in X) g (Some a) None. + pose F a b := (P1 (a, b))%:R * SμL (a, b). rewrite pr_finE -(pair_big xpredT xpredT F) exchange_big /=. rewrite (bigD1 None) //= [X in _ + X]big1 ?addr0. - case=> // b _; rewrite {}/F /P1 big1 //. by move=> a _; rewrite inE /= andbF mul0r. rewrite mulr_sumr [RHS]big_mkcond {}/F /P1; apply/eq_bigr=> a _. by rewrite !inE /= eqxx andbT; case: ifP; rewrite !Monoid.simpm. have {P2}->: \P_[SμL] P2 = Ω ε * \sum_(ab | (Some ab.1, Some ab.2) \in X) g (Some ab.1) (Some ab.2). + pose F a b := (P2 (a, b))%:R * SμL (a, b). rewrite pr_finE -(pair_big xpredT xpredT F) /=. rewrite exchange_big big_option big1 /= ?add0r. - by move=> a _; rewrite {}/F /P2; rewrite inE andbF mul0r. rewrite exchange_big pair_big mulr_sumr [RHS]big_mkcond /=. apply/eq_bigr=> -[a b] _ /=; rewrite /F /P2 !inE /=. by case: ifP=> //= _; rewrite !Monoid.simpm. have {Q1}->: \P_[SμR] Q1 = \sum_(b : B | (None, Some b) \in X) g None (Some b). + pose F a b := (Q1 (a, b))%:R * SμR (a, b). rewrite pr_finE -(pair_big xpredT xpredT F) /=. rewrite (bigD1 None) //= [X in _ + X]big1 ?addr0. - case=> // a _; rewrite {}/F /Q1 big1 //. by move=> b _; rewrite inE /= andbF mul0r. rewrite [RHS]big_mkcond {}/F /Q1; apply/eq_bigr=> b _. by rewrite !inE /= eqxx andbT; case: ifP; rewrite !Monoid.simpm. have {Q2}->: \P_[SμR] Q2 = \sum_(ab | (Some ab.1, Some ab.2) \in X) g (Some ab.1) (Some ab.2). + pose F a b := (Q2 (a, b))%:R * SμR (a, b). rewrite pr_finE -(pair_big xpredT xpredT F) big_option /= big1. - by move=> b _; rewrite {}/F /Q2 /= andbF mul0r. rewrite add0r pair_big [RHS]big_mkcond /=. apply/eq_bigr=> -[a b] _ /=; rewrite /F /Q2 !inE /=. by case: ifP=> //= _; rewrite !Monoid.simpm. rewrite -ler_subl_addl -mulrDr -mulrBr opprD addrACA subrr addr0. rewrite mulrBr ler_subl_addr ler_paddr //. + rewrite mulr_ge0 ?ge0_Ω //; apply/sumr_ge0. by move=> b _; apply/ge0_flowNF. apply/(@le_trans _ _ (Ω ε * \sum_a g a None)). + rewrite ler_pmul2l ?gt0_Ω // big_mkcond /=. rewrite big_option ler_paddl //; first by apply/ge0_flowNF. by apply/ler_sum=> a _; case: ifP=> // _; apply/ge0_flowNF. by rewrite /g -kcf_flowNFR fRE /c /= mulrA -ΩD subrr Ω0 mul1r. Qed. End StrassenUnderMaxFlow. (* -------------------------------------------------------------------- *) Theorem FinStrassen : elift ε δ μ1 μ2 S. Proof. case: (maxflow_mincut NF)=> f [hf fmax]; apply/(@FinWeakStrassen f). case: fmax => /= C fmE; rewrite fmE (rwP eqP) eq_le geω_cut andbT. by rewrite -fmE -cweight_cutR hf. Qed. End FinStrassen. (* -------------------------------------------------------------------- *) Section RLift. Context {T : choiceType} {U : Type}. Context (c : {fset T}) (f : c -> U) (x0 : U). Definition rlift := fun x => if @idP (x \in c) is ReflectT h then f [`h]%fset else x0. Lemma rlift_val x : rlift (fsval x) = f x. Proof. rewrite /rlift; case: {-}_ / idP => // h; congr f. by apply/eqP; rewrite eqE /= eqxx. Qed. End RLift. Section DistrFinRestr. Context {A : choiceType} (c : {fset A}) (μ : distr A). Definition mfinrestr (x : c) := μ (val x). Lemma mfinrestr_is_distr : isdistr mfinrestr. Proof. apply/isdistr_finP; split=> [x|]; first by apply/ge0_mu. have /gerfin_psum -/(_ c) := summable_mu μ. move/le_trans => /(_ _ (le1_mu μ)) /(le_trans _); apply. by apply/ler_sum=> /= x _; rewrite ger0_norm. Qed. Definition dfinrestr := locked (mkdistr (mfinrestr_is_distr)). Lemma dfinrestrE x : dfinrestr x = μ (val x). Proof. by unlock dfinrestr. Qed. Lemma pr_dfinrestr (X : pred c) : \P_[dfinrestr] X = \P_[μ] (rlift X false). Proof. rewrite [in RHS]/pr (psum_finseq (r := (enum_fset c))). + by apply/fset_uniq. + move=> x; rewrite {1}/in_mem /= mulf_eq0 negb_or => /andP[]. by rewrite /rlift; case: {-}_ / idP => //; rewrite eqxx. rewrite -big_fset_seq /= /pr psum_fin; apply/eq_bigr => /= x _. by rewrite dfinrestrE rlift_val. Qed. End DistrFinRestr. (* -------------------------------------------------------------------- *) Section FinSuppStrassen. Context {A B : choiceType}. Context (ε δ : R) (μ1 : distr A) (μ2 : distr B). Context (c1 : {fset A}) (c2 : {fset B}) (S : pred (A * B)). Hypothesis (ge0_ε : 0 <= ε) (ge0_δ : 0 <= δ). Hypothesis (hc1 : {subset dinsupp μ1 <= mem c1}). Hypothesis (hc2 : {subset dinsupp μ2 <= mem c2}). Hypothesis mono : forall X, \P_[μ1] X <= Ω ε * \P_[μ2] (fun y => `[< exists2 x, x \in X & S (x, y) >]) + δ. (* FIXME: factor out facts about dfinrestr *) Theorem FinSuppStrassen : elift ε δ μ1 μ2 S. Proof. pose ν1 : distr c1 := dfinrestr c1 μ1. pose ν2 : distr c2 := dfinrestr c2 μ2. pose p (x : c1 * c2) := S (val x.1, val x.2). have h (X : pred c1) : \P_[ν1] X <= Ω ε * \P_[ν2] (fun y : c2 => [exists x in X, p (x, y)]) + δ. + rewrite pr_dfinrestr (le_trans (mono _)) // ler_add2r. rewrite ler_wpmul2l ?ge0_Ω // pr_dfinrestr. apply/le_in_pr=> b bsupp; rewrite /in_mem /=. case/asboolP=> a; rewrite {1}/rlift; case: {-}_ / idP => //. move=> ha Xa Sab; rewrite /rlift; case: {-}_ / idP; last first. * by move: bsupp; rewrite {1}/in_mem /= => /hc2. by move=> hb; apply/existsP; exists [`ha]%fset; rewrite Xa. case: (FinStrassen (S := p) ge0_ε ge0_δ h) => {h} /=. move=> -[η1 η2] /= [ν1E ν2E hs1 hs2 hed]. pose T1 := (A * option B)%type; pose T2 := (option A * B)%type. pose U1 := (c1 * option c2)%type; pose U2 := (option c1 * c2)%type. pose U := (option c1 * option c2)%type. pose f1 (xy : U1) := (val xy.1, omap val xy.2). pose f2 (xy : U2) := (omap val xy.1, val xy.2). pose ζ1 : distr T1 := dmargin f1 η1. pose ζ2 : distr T2 := dmargin f2 η2. exists (ζ1, ζ2) => /=; split. + move=> a; rewrite dlet_dlet; set fa := fun xy : U1 => dlet _ _. rewrite (eq_in_dlet (g := fun xy => dunit (val xy.1)) (nu := η1)) //=. * by move=> xy _ {}a; rewrite dlet_unit. case/boolP: (a \in c1) => ac1; last first. * rewrite dlet_eq0 => /= [[a' b'] _ /=|]. - by apply/contra: ac1 => /eqP<-. apply/esym; apply/(dinsuppPn μ1); rewrite /in_mem. by apply/contra: ac1 => /hc1. have := ν1E [`ac1]%fset; rewrite dfinrestrE /= => <-. rewrite dmarginE !dletE /=; apply/eq_psum=> /=. by case=> [a' b'] /=; rewrite !dunit1E /=. + move=> b; rewrite dlet_dlet; set fb := fun xy : U2 => dlet _ _. rewrite (eq_in_dlet (g := fun xy => dunit (val xy.2)) (nu := η2)) //=. * by move=> xy _ {}b; rewrite dlet_unit. case/boolP: (b \in c2) => ac2; last first. * rewrite dlet_eq0 => /= [[a' b'] _ /=|]. - by apply/contra: ac2 => /eqP<-. apply/esym; apply/(dinsuppPn μ2); rewrite /in_mem. by apply/contra: ac2 => /hc2. have := ν2E [`ac2]%fset; rewrite dfinrestrE /= => <-. rewrite dmarginE !dletE /=; apply/eq_psum=> /=. by case=> [a' b'] /=; rewrite !dunit1E /=. + move=> a b /dinsupp_dlet[/=] [] ha [hb|] h /=; last first. * by rewrite dunit1E [X in (_ (X _))%:R]eqE /= andbF eqxx. rewrite dunit1E [X in (_ (X _))%:R]eqE /=; case: andP. * by case=> /eqP<- /eqP[<-] _; move/hs1: h. * by rewrite eqxx. + move=> a b /dinsupp_dlet[/=] [] [ha|] hb h /=; last first. * by rewrite dunit1E [X in (_ (X _))%:R]eqE /= eqxx. rewrite dunit1E [X in (_ (X _))%:R]eqE /=; case: andP. * by case=> /eqP[<-] /eqP<- _; move/hs2: h. * by rewrite eqxx. + move: hed; rewrite /edist; case: ltrP => // _. set v1 : R := sup _; set v2 : R := sup _; suff ->: v1 = v2 by []. congr (sup _); rewrite predeqE => /= z; split; last first. * case=> /= q ->; pose rq (xy : U) := q (omap val xy.1, omap val xy.2). exists rq => /=; congr (_ - _ * _). - by rewrite !pr_dmargin; apply/eq_in_pr. - by rewrite !pr_dmargin; apply/eq_in_pr. case=> /= q ->; pose qr (xy : option A * option B) := let a : option c1 := obind (rlift some None) xy.1 in let b : option c2 := obind (rlift some None) xy.2 in q (a, b). exists qr; congr (_ - _ * _). - rewrite !pr_dmargin; apply/eq_in_pr=> /= -[a b] _ //=. rewrite /in_mem /qr /= rlift_val; case: b => //= b. by rewrite rlift_val. - rewrite !pr_dmargin; apply/eq_in_pr => /= -[a b] _ //=. rewrite /in_mem /qr /= rlift_val; case: a => //= a. by rewrite rlift_val. Qed. End FinSuppStrassen. (* -------------------------------------------------------------------- *) Section CountableStrassen. Context {A B : countType}. Context (ε δ : R) (μ1 : distr A) (μ2 : distr B) (S : pred (A * B)). Hypothesis (ge0_ε : 0 <= ε) (ge0_δ : 0 <= δ). Definition E {T : countType} i : {fset T} := seq_fset tt (pmap choice.unpickle (iota 0 i)). Definition imS (X : pred A) := [pred y | `[< exists2 x, x \in X & S (x, y) >]]. Hypothesis mono : forall X, \P_[μ1] X <= Ω ε * \P_[μ2] (imS X) + δ. Let η1 n := (drestr (mem (E n)) μ1). Let η2 n := (drestr (mem (E n)) μ2). Let Δ n := (Ω ε * \P_[μ2] (predC (mem (E n))) + δ). Lemma ge0_Δ n : 0 <= Δ n. Proof. by rewrite addr_ge0 // mulr_ge0 ?(ge0_Ω, ge0_pr). Qed. Lemma mono_drestr n X : \P_[η1 n] X <= Ω ε * \P_[η2 n] (imS X) + Δ n. Proof. apply/(@le_trans _ _ (\P_[μ1] X)). + apply/le_mu_pr => a _ _; rewrite drestrE. by case: ifP => // _; rewrite ge0_mu. apply/(le_trans (mono X)); rewrite addrA ler_add2r. rewrite -mulrDr ler_wpmul2l ?ge0_Ω // pr_drestr. rewrite -pr_or_indep => [b /andP[/=]|]; first by rewrite !inE negbK. by apply/le_in_pr=> b _; rewrite !inE => ->; rewrite andbT orbN. Qed. Local Notation T := (distr (A * option B) * distr (option A * B))%type. Local Notation elift_r n η := [/\ dfst η.1 =1 η1 n, dsnd η.2 =1 η2 n , (forall a b, (a, Some b) \in dinsupp η.1 -> S (a, b)) , (forall a b, (Some a, b) \in dinsupp η.2 -> S (a, b)) & edist ε (deliftL η.1) (deliftR η.2) <= Δ n]. Local Notation R η := (forall a b, η.2 (Some a, b) <= η.1 (a, Some b) <= Ω ε * η.2 (Some a, b)). Lemma elift_dfinrestr n : { η : T | elift_r n η /\ R η }. Proof. suff: elift ε (Δ n) (η1 n) (η2 n) S by move/(elift_bnd ge0_ε). apply/(FinSuppStrassen (c1 := E n) (c2 := E n)) => //. + by apply/ge0_Δ. + by move=> x; rewrite dinsupp_restr => /andP[]. + by move=> x; rewrite dinsupp_restr => /andP[]. + by apply/mono_drestr. Qed. Let ηL n : distr (A * option B) := (tag (elift_dfinrestr n)).1. Let ηR n : distr (option A * B) := (tag (elift_dfinrestr n)).2. Let ω : nat -> nat := tag (strcvg2 ηL ηR). Local Lemma homo_ω : {homo ω : x y / (x < y)%N}. Proof. by rewrite /ω; case: strcvg2. Qed. Let ξL : distr (A * option B) := dlim (ηL \o ω). Let ξR : distr (option A * B) := dlim (ηR \o ω). Local Lemma iscvg_ηL x : iscvg (fun n => ηL (ω n) x). Proof. by rewrite /ω; case: strcvg2 => /= h _ []. Qed. Local Lemma iscvg_ηR x : iscvg (fun n => ηR (ω n) x). Proof. by rewrite /ω; case: strcvg2 => /= h _ []. Qed. Lemma Strassen : elift ε δ μ1 μ2 S. Proof. pose GL a := if a is Some a then μ1 a else 1. pose GR b := if b is Some b then Ω ε * μ2 b else 1. have sblGl: summable GL by apply/summable_option/summable_mu. have sblGR: summable GR by apply/summable_option/summableZ. have le_μ1 n a : η1 n a <= μ1 a. + by rewrite drestrE; case: ifP => // _; apply/ge0_mu. have le_μ2 n b : η2 n b <= μ2 b. + by rewrite drestrE; case: ifP => // _; apply/ge0_mu. have hLL n a : psum (fun b => ηL n (a, b)) <= μ1 a. + by rewrite -dfstE exlift_dfstL le_μ1. have hRR n b : psum (fun a => ηR n (a, b)) <= μ2 b. + by rewrite -dsndE exlift_dsndR le_μ2. have hLR n a (b : option B) : ηL n (a, b) <= GR b. + case: b => /= [b|]; last by apply/le1_mu1. apply/(le_trans (exlift_leLR _ _ _)). rewrite ler_wpmul2l ?ge0_Ω // (le_trans _ (le_μ2 n _)) //. rewrite -(exlift_dsndR (elift_dfinrestr _)) -!/(ηR _) dsndE /=. rewrite (le_trans _ (gerfinseq_psum (r := [:: Some a]) _ _)) //. - by rewrite big_seq1 ler_norm. - by apply/summable_snd. have hRL n (a : option A) b : ηR n (a, b) <= GL a. + case: a => /= [a|]; last by apply/le1_mu1. rewrite (le_trans (exlift_leRL _ _ _)) 1?(le_trans _ (le_μ1 n _)) //. rewrite -(exlift_dfstL (elift_dfinrestr _)) -!/(ηL _) dfstE /=. rewrite (le_trans _ (gerfinseq_psum (r := [:: Some b]) _ _)) //. - by rewrite big_seq1 ler_norm. - by apply/summable_fst. pose FL a n (b : option B) := ηL (ω n) (a, b). pose FR b n (a : option A) := ηR (ω n) (a, b). exists (ξL, ξR) => /=; split => [a|b|||]. + rewrite dfstE (eq_psum (F2 := fun b => real_of_er (nlim ((FL a)^~ b)))) /=. * by move=> b; rewrite [in LHS]dlimE. transitivity (real_of_er (nlim (fun n => psum (FL a n)))). * rewrite (@DCT_swap _ _ (fun b => ξL (a, b)) GR) => //=. - move=> b; rewrite dlimE /FL; case: (iscvg_ηL (a, b)). by move=> l hl; rewrite (nlimE hl). - by move=> n b; rewrite ger0_norm // (ge0_mu, hLR). pose pa := choice.pickle a; have ->: μ1 a = real_of_er (nlim (fun n => η1 (ω n) a)). * rewrite -(nlim_lift _ pa.+1) (eq_nlim (v := (μ1 a)%:S)) ?nlimC //. move=> n /=; rewrite drestrE /E /= sort_keysE mem_pmap. case: mapP => // -[]; exists pa; rewrite ?choice.pickleK //. rewrite mem_iota leq0n add0n (@leq_trans (n + pa.+1)) //. - by rewrite leq_addl. - by apply/homo_geidfun/homo_ω. congr real_of_er; apply/eq_nlim => n /=. by rewrite -(exlift_dfstL (elift_dfinrestr _)) dfstE. + rewrite dsndE (eq_psum (F2 := fun a => real_of_er (nlim ((FR b)^~ a)))) /=. * by move=> a; rewrite [in LHS]dlimE. transitivity (real_of_er (nlim (fun n => psum (FR b n)))). * rewrite (@DCT_swap _ _ (fun a => ξR (a, b)) GL) => //=. - move=> a; rewrite dlimE /FR; case: (iscvg_ηR (a, b)). by move=> l hl; rewrite (nlimE hl). - by move=> n a; rewrite ger0_norm // (ge0_mu, hRL). pose pb := choice.pickle b; have ->: μ2 b = real_of_er (nlim (fun n => η2 (ω n) b)). * rewrite -(nlim_lift _ pb.+1) (eq_nlim (v := (μ2 b)%:S)) ?nlimC //. move=> n /=; rewrite drestrE /E /= sort_keysE mem_pmap. case: mapP => // -[]; exists pb; rewrite ?choice.pickleK //. rewrite mem_iota leq0n add0n (@leq_trans (n + pb.+1)) //. - by rewrite leq_addl. - by apply/homo_geidfun/homo_ω. congr real_of_er; apply/eq_nlim => n /=. by rewrite -(exlift_dsndR (elift_dfinrestr _)) dsndE. + by move=> a b /dinsupp_dlim [K] /(_ _ (leqnn _)) /exlift_dsuppL. + by move=> a b /dinsupp_dlim [K] /(_ _ (leqnn _)) /exlift_dsuppR. apply/edist_le_supp => //= X subX. pose L n : elift.R := \P_[deliftL (ηL (ω n))] X. pose R n : elift.R := \P_[deliftR (ηR (ω n))] X. have cvgL: ncvg L (\P_[deliftL ξL] X)%:E. * pose F n a b := (X (a, b))%:R * (deliftL (ηL (ω n)) (a, b)). pose G n := psum (fun a => psum (fun b => F n a b)). apply/(ncvg_eq (v := G)); rewrite {}/L {}/G /=. - by move=> n; rewrite /pr psum_pair //=; apply/summable_condl. pose G (a : option A) b := (X (a, b))%:R * deliftL ξL (a, b). rewrite /pr psum_pair /=; first by apply/summable_condl. move=> [: hcv1]; apply/(@DCT_ncvg _ _ (fun a => (psum (G a))) GL) => //=. - abstract: hcv1 => a /=; apply (@DCT_ncvg _ _ (G a) GR) => //=. + move=> b; apply/ncvgZ; case: a => /= [a|]. * apply/(@ncvg_eq _ (fun n => ηL (ω n) (a, b))). - by move=> n /=; rewrite deliftLE. rewrite deliftLE /ξL; case: (iscvg_ηL (a, b)). by move=> l hl; rewrite dlimE (nlimE hl). * apply/(@ncvg_eq _ 0%:S) => [n|]. - by rewrite deliftLE. - by rewrite deliftLE; apply/ncvgC. + move=> n b; rewrite ger0_norm ?mulr_ge0 ?(ler0n, ge0_mu) //. rewrite (@le_trans _ _ (deliftL (ηL (ω n)) (a, b))) //. * by rewrite ler_pimull ?ge0_mu // lern1 leq_b1. case: a => /= [a|]; first by rewrite deliftLE hLR. rewrite deliftLE /= /GR; case: b => /= [b|]. * by rewrite mulr_ge0 ?(ge0_mu, ge0_Ω). * by rewrite ler01. - move=> n a; rewrite ger0_norm ?ge0_psum //; case: a => /=. + move=> a; apply/(le_trans _ (hLL (ω n) _))/le_psum => /=. * move=> b; rewrite /F deliftLE mulr_ge0 //= ?ler0n //. by rewrite ler_pimull // lern1 leq_b1. * by apply/summable_fst. + by rewrite psum_eq0 ?ler01 //= => b; rewrite /F deliftLE mulr0. have cvgR: ncvg R (\P_[deliftR ξR] X)%:E. * pose F n a b := (X (a, b))%:R * (deliftR (ηR (ω n)) (a, b)). pose G n := psum (fun b => psum (fun a => F n a b)). apply/(ncvg_eq (v := G)); rewrite {}/R {}/G /=. - by move=> n; rewrite /pr psum_pair_swap //=; apply/summable_condl. rewrite /pr psum_pair_swap /=; first by apply/summable_condl. pose G (b : option B) a := (X (a, b))%:R * deliftR ξR (a, b). move=> [: hcv1]; apply/(@DCT_ncvg _ _ (fun b => (psum (G b))) GR) => //=. - abstract: hcv1 => b /=; apply (@DCT_ncvg _ _ (G b) GL) => //=. + move=> a; apply/ncvgZ; case: b => /= [b|]. * apply/(@ncvg_eq _ (fun n => ηR (ω n) (a, b))). - by move=> n /=; rewrite deliftRE. rewrite deliftRE /ξR; case: (iscvg_ηR (a, b)). by move=> l hl; rewrite dlimE (nlimE hl). * apply/(@ncvg_eq _ 0%:S) => [n|]. - by rewrite deliftRE. - by rewrite deliftRE; apply/ncvgC. + move=> n a; rewrite ger0_norm ?mulr_ge0 ?(ler0n, ge0_mu) //. rewrite (@le_trans _ _ (deliftR (ηR (ω n)) (a, b))) //. * by rewrite ler_pimull ?ge0_mu // lern1 leq_b1. case: b => /= [b|]; first by rewrite deliftRE hRL. rewrite deliftRE /= /GL; case: a => /= [a|]. * by rewrite ge0_mu. * by rewrite ler01. - move=> n b; rewrite ger0_norm ?ge0_psum //; case: b => /=. + move=> b; apply/(@le_trans _ _ (μ2 b)); last first. * by rewrite ler_pemull // Ω_ge1. apply/(le_trans _ (hRR (ω n) _))/le_psum => /=. * move=> a; rewrite /F deliftRE mulr_ge0 //= ?ler0n //. by rewrite ler_pimull // lern1 leq_b1. * by apply/summable_snd. + by rewrite psum_eq0 ?ler01 //= => b; rewrite /F deliftRE mulr0. rewrite addrC -ler_subl_addr; set V := (X in X <= _). suff cvgΔ: ncvg Δ δ%:E. * move/(ncvg_sub homo_ω)/ncvg_le: cvgΔ => /(_ (L \- Ω ε \*o R) V%:E) /=. apply=> [n|]; last by apply/ncvgB/ncvgZ. rewrite ler_subl_addr addrC /L /R. have := exlift_edist (elift_dfinrestr (ω n)) => /edist_le. by move/(_ ge0_ε X); rewrite -/(ηL _) -/(ηR _). rewrite -[δ]add0r -[X in (X + _)%:E](mulr0 (Ω ε)). apply/ncvgD/ncvgC/ncvgZ; rewrite -[X in X%:E](@psum0 _ B). apply/(DCT_ncvg (g := μ2)) => //; last first. * move=> n b; rewrite ger0_norm ?mulr_ge0 ?ler0n //. by rewrite ler_pimull // lern1 leq_b1. move=> b; apply/ncvgMl; last first. * apply/asboolP/nboundedP; exists 2%:R => // _. apply/(@le_lt_trans _ _ 1) => //; last by rewrite (@ltr_nat _ 1). by rewrite ger0_norm // le1_mu1. elim/nbh_finW => /= e gt0_e; exists (choice.pickle b).+1 => n le_bn. rewrite inE subr0; apply/(le_lt_trans _ gt0_e). rewrite normr_le0 pnatr_eq0 eqb0 negbK /E seq_fsetE. rewrite mem_pmap; apply/mapP; exists (choice.pickle b). * by rewrite mem_iota /= add0n. * by rewrite choice.pickleK. Qed. End CountableStrassen.
(* * Copyright 2020, Data61, CSIRO (ABN 41 687 119 230) * * SPDX-License-Identifier: BSD-2-Clause *) theory ModifiesProofs imports CLanguage begin (* Rules for breaking down modifies goals before feeding them to the VCG. Helps avoid some pathological performance issues. *) definition modifies_inv_refl :: "('a \<Rightarrow> 'a set) \<Rightarrow> bool" where "modifies_inv_refl P \<equiv> \<forall>x. x \<in> P x" definition modifies_inv_incl :: "('a \<Rightarrow> 'a set) \<Rightarrow> bool" where "modifies_inv_incl P \<equiv> \<forall>x y. y \<in> P x \<longrightarrow> P y \<subseteq> P x" definition modifies_inv_prop :: "('a \<Rightarrow> 'a set) \<Rightarrow> bool" where "modifies_inv_prop P \<equiv> modifies_inv_refl P \<and> modifies_inv_incl P" lemma modifies_inv_prop: "modifies_inv_refl P \<Longrightarrow> modifies_inv_incl P \<Longrightarrow> modifies_inv_prop P" by (simp add: modifies_inv_prop_def) named_theorems modifies_inv_intros context fixes P :: "'a \<Rightarrow> 'a set" assumes p: "modifies_inv_prop P" begin private lemmas modifies_inv_prop' = p[unfolded modifies_inv_prop_def modifies_inv_refl_def modifies_inv_incl_def] private lemma modifies_inv_prop_lift: assumes c: "\<And>\<sigma>. \<Gamma>\<turnstile>\<^bsub>/F\<^esub> {\<sigma>} c (P \<sigma>),(P \<sigma>)" shows "\<Gamma>\<turnstile>\<^bsub>/F\<^esub> (P \<sigma>) c (P \<sigma>),(P \<sigma>)" using modifies_inv_prop' by (fastforce intro: c hoarep.Conseq) private lemma modifies_inv_prop_lower: assumes c: "\<And>\<sigma>. \<Gamma>\<turnstile>\<^bsub>/F\<^esub> (P \<sigma>) c (P \<sigma>),(P \<sigma>)" shows "\<Gamma>\<turnstile>\<^bsub>/F\<^esub> {\<sigma>} c (P \<sigma>),(P \<sigma>)" using modifies_inv_prop' by (fastforce intro: c hoarep.Conseq) private lemma modifies_inv_Seq [modifies_inv_intros]: assumes c: "\<And>\<sigma>. \<Gamma>\<turnstile>\<^bsub>/F\<^esub> {\<sigma>} c1 (P \<sigma>),(P \<sigma>)" "\<And>\<sigma>. \<Gamma>\<turnstile>\<^bsub>/F\<^esub> {\<sigma>} c2 (P \<sigma>),(P \<sigma>)" shows "\<Gamma>\<turnstile>\<^bsub>/F\<^esub> {\<sigma>} c1 ;; c2 (P \<sigma>),(P \<sigma>)" by (intro modifies_inv_prop_lower HoarePartial.Seq[OF c[THEN modifies_inv_prop_lift]]) private lemma modifies_inv_Cond [modifies_inv_intros]: assumes c: "\<And>\<sigma>. \<Gamma>\<turnstile>\<^bsub>/F\<^esub> {\<sigma>} c1 (P \<sigma>),(P \<sigma>)" "\<And>\<sigma>. \<Gamma>\<turnstile>\<^bsub>/F\<^esub> {\<sigma>} c2 (P \<sigma>),(P \<sigma>)" shows "\<Gamma>\<turnstile>\<^bsub>/F\<^esub> {\<sigma>} Cond b c1 c2 (P \<sigma>),(P \<sigma>)" by (auto intro: HoarePartial.Cond c) private lemma modifies_inv_Guard_strip [modifies_inv_intros]: assumes c: "\<And>\<sigma>. \<Gamma>\<turnstile>\<^bsub>/UNIV\<^esub> {\<sigma>} c (P \<sigma>),(P \<sigma>)" shows "\<Gamma>\<turnstile>\<^bsub>/UNIV\<^esub> {\<sigma>} Guard f b c (P \<sigma>),(P \<sigma>)" by (rule HoarePartial.GuardStrip[OF subset_refl c UNIV_I]) private lemma modifies_inv_Skip [modifies_inv_intros]: shows "\<Gamma>\<turnstile>\<^bsub>/F\<^esub> {\<sigma>} SKIP (P \<sigma>),(P \<sigma>)" using modifies_inv_prop' by (auto intro: modifies_inv_prop_lift HoarePartial.Skip) private lemma modifies_inv_Skip' [modifies_inv_intros]: shows "\<Gamma>\<turnstile>\<^bsub>/F\<^esub> {\<sigma>} SKIP (P \<sigma>)" using modifies_inv_prop' by (auto intro: modifies_inv_prop_lift HoarePartial.Skip) private lemma modifies_inv_whileAnno [modifies_inv_intros]: assumes c: "\<And>\<sigma>. \<Gamma>\<turnstile>\<^bsub>/F\<^esub> {\<sigma>} c (P \<sigma>),(P \<sigma>)" shows "\<Gamma>\<turnstile>\<^bsub>/F\<^esub> {\<sigma>} whileAnno b I V c (P \<sigma>),(P \<sigma>)" apply (rule HoarePartial.reannotateWhileNoGuard[where I="P \<sigma>"]) by (intro HoarePartial.While hoarep.Conseq; fastforce simp: modifies_inv_prop' intro: modifies_inv_prop_lift c) private lemma modifies_inv_While [modifies_inv_intros]: assumes c: "\<And>\<sigma>. \<Gamma>\<turnstile>\<^bsub>/F\<^esub> {\<sigma>} c (P \<sigma>),(P \<sigma>)" shows "\<Gamma>\<turnstile>\<^bsub>/F\<^esub> {\<sigma>} While b c (P \<sigma>),(P \<sigma>)" by (intro modifies_inv_whileAnno[unfolded whileAnno_def] c) private lemma modifies_inv_Throw [modifies_inv_intros]: shows "\<Gamma>\<turnstile>\<^bsub>/F\<^esub> {\<sigma>} THROW (P \<sigma>),(P \<sigma>)" using modifies_inv_prop' by (auto intro: modifies_inv_prop_lift HoarePartial.Throw) private lemma modifies_inv_Catch [modifies_inv_intros]: assumes c: "\<And>\<sigma>. \<Gamma>\<turnstile>\<^bsub>/F\<^esub> {\<sigma>} c1 (P \<sigma>),(P \<sigma>)" "\<And>\<sigma>. \<Gamma>\<turnstile>\<^bsub>/F\<^esub> {\<sigma>} c2 (P \<sigma>),(P \<sigma>)" shows "\<Gamma>\<turnstile>\<^bsub>/F\<^esub> {\<sigma>} TRY c1 CATCH c2 END (P \<sigma>),(P \<sigma>)" by (intro modifies_inv_prop_lower HoarePartial.Catch[OF c[THEN modifies_inv_prop_lift]]) private lemma modifies_inv_Catch_all [modifies_inv_intros]: assumes 1: "\<And>\<sigma>. \<Gamma>\<turnstile>\<^bsub>/F\<^esub> {\<sigma>} c1 (P \<sigma>),(P \<sigma>)" assumes 2: "\<And>\<sigma>. \<Gamma>\<turnstile>\<^bsub>/F\<^esub> {\<sigma>} c2 (P \<sigma>)" shows "\<Gamma>\<turnstile>\<^bsub>/F\<^esub> {\<sigma>} TRY c1 CATCH c2 END (P \<sigma>)" apply (intro HoarePartial.Catch[OF 1] hoarep.Conseq, clarsimp) apply (metis modifies_inv_prop' 2 singletonI) done private lemma modifies_inv_switch_Nil [modifies_inv_intros]: shows "\<Gamma>\<turnstile>\<^bsub>/F\<^esub> {\<sigma>} switch v [] (P \<sigma>),(P \<sigma>)" by (auto intro: modifies_inv_Skip) private lemma modifies_inv_switch_Cons [modifies_inv_intros]: assumes c: "\<And>\<sigma>. \<Gamma>\<turnstile>\<^bsub>/F\<^esub> {\<sigma>} c (P \<sigma>),(P \<sigma>)" "\<And>\<sigma>. \<Gamma>\<turnstile>\<^bsub>/F\<^esub> {\<sigma>} switch p vcs (P \<sigma>),(P \<sigma>)" shows "\<Gamma>\<turnstile>\<^bsub>/F\<^esub> {\<sigma>} switch p ((v,c) # vcs) (P \<sigma>),(P \<sigma>)" by (auto intro: c modifies_inv_Cond) end context fixes P :: "('c, 'd) state_scheme \<Rightarrow> ('c, 'd) state_scheme set" assumes p: "modifies_inv_prop P" begin private lemma modifies_inv_creturn [modifies_inv_intros]: assumes c: "\<And>\<sigma>. \<Gamma>\<turnstile>\<^bsub>/F\<^esub> {\<sigma>} Basic (\<lambda>s. xfu (\<lambda>_. v s) s) (P \<sigma>),(P \<sigma>)" "\<And>\<sigma>. \<Gamma>\<turnstile>\<^bsub>/F\<^esub> {\<sigma>} Basic (rtu (\<lambda>_. Return)) (P \<sigma>),(P \<sigma>)" shows "\<Gamma>\<turnstile>\<^bsub>/F\<^esub> {\<sigma>} creturn rtu xfu v (P \<sigma>),(P \<sigma>)" unfolding creturn_def by (intro p c modifies_inv_intros) private lemma modifies_inv_creturn_void [modifies_inv_intros]: assumes c: "\<And>\<sigma>. \<Gamma>\<turnstile>\<^bsub>/F\<^esub> {\<sigma>} Basic (rtu (\<lambda>_. Return)) (P \<sigma>),(P \<sigma>)" shows "\<Gamma>\<turnstile>\<^bsub>/F\<^esub> {\<sigma>} creturn_void rtu (P \<sigma>),(P \<sigma>)" unfolding creturn_void_def by (intro p c modifies_inv_intros) private lemma modifies_inv_cbreak [modifies_inv_intros]: assumes c: "\<And>\<sigma>. \<Gamma>\<turnstile>\<^bsub>/F\<^esub> {\<sigma>} Basic (rtu (\<lambda>_. Break)) (P \<sigma>),(P \<sigma>)" shows "\<Gamma>\<turnstile>\<^bsub>/F\<^esub> {\<sigma>} cbreak rtu (P \<sigma>),(P \<sigma>)" unfolding cbreak_def by (intro p c modifies_inv_intros) private lemma modifies_inv_ccatchbrk [modifies_inv_intros]: shows "\<Gamma>\<turnstile>\<^bsub>/F\<^esub> {\<sigma>} ccatchbrk rt (P \<sigma>),(P \<sigma>)" unfolding ccatchbrk_def by (intro p modifies_inv_intros) end end
#include <math.h> #include <stdio.h> #include <stdlib.h> #include <limits.h> #include <sys/time.h> #include <inttypes.h> #include <omp.h> #include <gsl/gsl_math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_heapsort.h> #include "sph_data_types.h" #include "sph_linked_list.h" #include "sph_compute.h" extern const double fk_bspline_32[32]; extern const double fk_bspline_128[128]; extern const double fk_bspline_1024[1024]; #pragma omp declare simd double w_bspline_3d(double r,double h){ const double A_d = 3./(2.*M_PI*h*h*h); double q=0.; if(r<0||h<=0.) exit(10); q = r/h; if(q<=1) return A_d*(2./3.-q*q + q*q*q/2.0); else if((1.<=q)&&(q<2.)) return A_d*(1./6.)*(2.-q)*(2.-q)*(2.-q); else return 0.; } double w_bspline_3d_constant(double h){ return 3./(2.*M_PI*h*h*h); } #pragma omp declare simd double w_bspline_3d_simd(double q){ double wq = 0.0; double wq1 = (0.6666666666666666 - q*q + 0.5*q*q*q); double wq2 = 0.16666666666666666*(2.-q)*(2.-q)*(2.-q); if(q<2.) wq = wq2; if(q<1.) wq = wq1; return wq; } #pragma omp declare simd double dwdq_bspline_3d_simd(double q){ double wq = 0.0; double wq1 = (1.5*q*q - 2.*q); double wq2 = -0.5*(2.-q)*(2.-q); if(q<2.) wq = wq2; if(q<1.) wq = wq1; return wq; } // https://stackoverflow.com/questions/56417115/efficient-integer-floor-function-in-c // 341.333333333 = 1024./3. #pragma omp declare simd double w_bspline_3d_LUT_1024(double q){ int kq = (int)(341.333333333*q); double phi = q-kq*0.002929688; double wq = phi*fk_bspline_1024[kq] + (1.-phi)*fk_bspline_1024[kq+1]; return wq; } #pragma omp declare simd double w_bspline_3d_LUT_128(double q){ int kq = (int)(42.666666667*q); double phi = q-kq*0.0234375; double wq = phi*fk_bspline_128[kq] + (1.-phi)*fk_bspline_128[kq+1]; return wq; } #pragma omp declare simd double w_bspline_3d_LUT_32(double q){ int kq = (int)(10.666666667*q); double phi = q-kq*0.09375; double wq = (1.-phi)*fk_bspline_32[kq] + phi*fk_bspline_32[kq+1]; return wq; } double dwdq_bspline_3d(double r,double h){ const double A_d = 3./(2.*M_PI*h*h*h*h); double q=0.; if(r<0||h<=0.) exit(10); q = r/h; if(q<=1) return A_d*q*(-2.+1.5*q); else if((1.<=q)&&(q<2.)) return -A_d*0.5*(2.-q)*(2.-q); else return 0.; } double distance_2d(double xi,double yi, double xj,double yj){ double dist = 0.0; dist += (xi-xj)*(xi-xj); dist += (yi-yj)*(yi-yj); return sqrt(dist); } #pragma omp declare simd double distance_3d(double xi,double yi,double zi, double xj,double yj,double zj){ double dist = 0.0; dist += (xi-xj)*(xi-xj); dist += (yi-yj)*(yi-yj); dist += (zi-zj)*(zi-zj); return sqrt(dist); } /**********************************************************************/ int compute_density_3d_chunk(int64_t node_begin, int64_t node_end, int64_t nb_begin, int64_t nb_end,double h, double* restrict x, double* restrict y, double* restrict z, double* restrict nu, double* restrict rho){ const double inv_h = 1./h; const double kernel_constant = w_bspline_3d_constant(h); #pragma omp parallel for for(int64_t ii=node_begin;ii<node_end;ii+=1){ double xii = x[ii]; double yii = y[ii]; double zii = z[ii]; double rhoii = 0.0; #pragma omp simd reduction(+:rhoii) nontemporal(rhoii) for(int64_t jj=nb_begin;jj<nb_end;jj+=1){ double q = 0.; double xij = xii-x[jj]; double yij = yii-y[jj]; double zij = zii-z[jj]; q += xij*xij; q += yij*yij; q += zij*zij; q = sqrt(q)*inv_h; rhoii += nu[jj]*w_bspline_3d_simd(q); //rhoii += nu[jj]*w_bspline_3d_LUT(q); } rho[ii] += rhoii*kernel_constant; } return 0; } int compute_density_3d_innerOmp(int N, double h, SPHparticle *lsph, linkedListBox *box){ int res; double dist = 0.0; khiter_t kbegin,kend; int64_t node_hash=-1,node_begin=0, node_end=0; int64_t nb_begin= 0, nb_end = 0; int64_t nblist[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)]; for (kbegin = kh_begin(box->hbegin); kbegin != kh_end(box->hbegin); kbegin++){ if (kh_exist(box->hbegin, kbegin)){ kend = kh_get(1, box->hend, kh_key(box->hbegin, kbegin)); node_hash = kh_key(box->hbegin, kbegin); node_begin = kh_value(box->hbegin, kbegin); node_end = kh_value(box->hend, kend); for(int64_t ii=node_begin;ii<node_end;ii+=1)// this loop inside was the problem lsph->rho[ii] = 0.0; res = neighbour_hash_3d(node_hash,nblist,box->width,box); for(unsigned int j=0;j<(2*box->width+1)*(2*box->width+1)*(2*box->width+1);j+=1){ if(nblist[j]>=0){ //nb_hash = nblist[j]; nb_begin = kh_value(box->hbegin, kh_get(0, box->hbegin, nblist[j]) ); nb_end = kh_value(box->hend , kh_get(1, box->hend , nblist[j]) ); compute_density_3d_chunk(node_begin,node_end,nb_begin,nb_end,h, lsph->x,lsph->y,lsph->z,lsph->nu,lsph->rho); } } } } return 0; } /**********************************************************************/ int compute_density_3d_chunk_noomp(int64_t node_begin, int64_t node_end, int64_t nb_begin, int64_t nb_end,double h, double* restrict x, double* restrict y, double* restrict z, double* restrict nu, double* restrict rho){ const double inv_h = 1./h; const double kernel_constant = w_bspline_3d_constant(h); for(int64_t ii=node_begin;ii<node_end;ii+=1){ double xii = x[ii]; double yii = y[ii]; double zii = z[ii]; double rhoii = 0.0; #pragma omp simd reduction(+:rhoii) for(int64_t jj=nb_begin;jj<nb_end;jj+=1){ double q = 0.; double xij = xii-x[jj]; double yij = yii-y[jj]; double zij = zii-z[jj]; q += xij*xij; q += yij*yij; q += zij*zij; q = sqrt(q)*inv_h; rhoii += nu[jj]*w_bspline_3d_simd(q); //rhoii += nu[jj]*w_bspline_3d_LUT(q); } rho[ii] += rhoii*kernel_constant; } return 0; } int compute_density_3d(int N, double h, SPHparticle *lsph, linkedListBox *box){ int64_t pair_count = 0; const khint32_t num_boxes = kh_size(box->hbegin); const khiter_t hbegin_start = kh_begin(box->hbegin), hbegin_finish = kh_end(box->hbegin); //for (khint32_t kbegin = hbegin_start; kbegin != hbegin_finish; kbegin++) #pragma omp parallel for num_threads(24) for (khint32_t kbegin = kh_begin(box->hbegin); kbegin != kh_end(box->hbegin); kbegin++){ int res; int64_t node_hash=-1,node_begin=0, node_end=0; int64_t nb_begin= 0, nb_end = 0; int64_t nblist[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)]; if (kh_exist(box->hbegin, kbegin)){ // I have to call this! khint32_t kend = kh_get(1, box->hend, kh_key(box->hbegin, kbegin)); node_hash = kh_key(box->hbegin, kbegin); node_begin = kh_value(box->hbegin, kbegin); node_end = kh_value(box->hend, kend); for(int64_t ii=node_begin;ii<node_end;ii+=1) lsph->rho[ii] = 0.0; res = neighbour_hash_3d(node_hash,nblist,box->width,box); for(unsigned int j=0;j<(2*box->width+1)*(2*box->width+1)*(2*box->width+1);j+=1){ if(nblist[j]>=0){ //nb_hash = nblist[j]; nb_begin = kh_value(box->hbegin, kh_get(0, box->hbegin, nblist[j]) ); nb_end = kh_value(box->hend , kh_get(1, box->hend , nblist[j]) ); pair_count += (node_end-node_begin)*(nb_end-nb_begin); compute_density_3d_chunk_noomp(node_begin,node_end,nb_begin,nb_end,h, lsph->x,lsph->y,lsph->z,lsph->nu,lsph->rho); } } } //printf("thread %d - %lf %lf\n",i,lsph->rho[node_begin],lsph->rho[node_end-1]); } printf("pair_count = %ld\n",pair_count); //for(int64_t i=0;i<N;i+=1000) // printf("%ld - %lf\n",i,lsph->rho[i]); return 0; } /**********************************************************************/ int compute_density_3d_chunk_loopswapped(int64_t node_begin, int64_t node_end, int64_t node_hash,linkedListBox *box, double h, double* restrict x, double* restrict y, double* restrict z, double* restrict nu, double* restrict rho) { int64_t pair_count; int res=0,nb_count=0,fused_count=0; //int64_t nb_begin= 0, nb_end = 0; const double inv_h = 1./h; const double kernel_constant = w_bspline_3d_constant(h); int64_t nblist[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)]; int64_t nb_begin[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)]; int64_t nb_end[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)]; res = neighbour_hash_3d(node_hash,nblist,box->width,box); for(unsigned int j=0;j<(2*box->width+1)*(2*box->width+1)*(2*box->width+1);j+=1){ if(nblist[j]>=0){ nb_begin[nb_count] = kh_value(box->hbegin, kh_get(0, box->hbegin, nblist[j]) ); nb_end[nb_count] = kh_value(box->hend , kh_get(1, box->hend , nblist[j]) ); nb_count+=1; } else{ nb_begin[nb_count] = -1; nb_end[nb_count] = -1; } } qsort(nb_begin,nb_count,sizeof(int64_t),compare_int64_t); qsort(nb_end ,nb_count,sizeof(int64_t),compare_int64_t); fused_count = nb_count; { int64_t tmp; unsigned int j=0; while(j<nb_count-1){ if(nb_begin[j] < 0){ nb_begin[j] = nb_begin[nb_count-1]+1; nb_end[j] = nb_end[nb_count-1]+1; } else if(nb_end[j]==nb_begin[j+1]){ //printf("%ld:%ld , %ld:%d",nb_begin[j],nb_begin[j+1]); nb_end[j] = nb_end[j+1]; tmp = nb_begin[j]; nb_begin[j] = nb_begin[j+1]; nb_begin[j+1] = tmp; tmp = nb_end[j]; nb_end[j] = nb_end[j+1]; nb_end[j+1] = tmp; nb_begin[j] = nb_begin[nb_count-1]+1; nb_end[j] = nb_end[nb_count-1]+1; fused_count -= 1; } j+=1; } } qsort(nb_begin,nb_count,sizeof(int64_t),compare_int64_t); qsort(nb_end ,nb_count,sizeof(int64_t),compare_int64_t); for(unsigned int j=0;j<fused_count;j+=1){ pair_count += (node_end-node_begin)*(nb_end[j]-nb_begin[j]); for(int64_t ii=node_begin;ii<node_end;ii+=1){ double xii = x[ii]; double yii = y[ii]; double zii = z[ii]; #pragma omp simd for(int64_t jj=nb_begin[j];jj<nb_end[j];jj+=1){ double q = 0.; double xij = xii-x[jj]; double yij = yii-y[jj]; double zij = zii-z[jj]; q += xij*xij; q += yij*yij; q += zij*zij; q = sqrt(q)*inv_h; rho[ii] += nu[jj]*w_bspline_3d_simd(q); } } } for(int64_t ii=node_begin;ii<node_end;ii+=1) rho[ii] *= kernel_constant; return pair_count; } int compute_density_3d_loopswapped(int N, double h, SPHparticle *lsph, linkedListBox *box){ int64_t pair_count = 0, ppc; const khint32_t num_boxes = kh_size(box->hbegin); const khiter_t hbegin_start = kh_begin(box->hbegin), hbegin_finish = kh_end(box->hbegin); //for (khint32_t kbegin = hbegin_start; kbegin != hbegin_finish; kbegin++) #pragma omp parallel for num_threads(24) for (khint32_t kbegin = kh_begin(box->hbegin); kbegin != kh_end(box->hbegin); kbegin++){ int res; int64_t node_hash=-1,node_begin=0, node_end=0; if (kh_exist(box->hbegin, kbegin)){ // I have to call this! khint32_t kend = kh_get(1, box->hend, kh_key(box->hbegin, kbegin)); node_hash = kh_key(box->hbegin, kbegin); node_begin = kh_value(box->hbegin, kbegin); node_end = kh_value(box->hend, kend); for(int64_t ii=node_begin;ii<node_end;ii+=1) lsph->rho[ii] = 0.0; ppc = compute_density_3d_chunk_loopswapped(node_begin,node_end,node_hash,box,h, lsph->x,lsph->y,lsph->z,lsph->nu,lsph->rho); pair_count += ppc; } } printf("pair_count = %ld\n",pair_count); return 0; } /*******************************************************************/ int count_box_pairs(linkedListBox *box){ int64_t pair_count = 0, particle_pair_count = 0; for (khint32_t kbegin = kh_begin(box->hbegin); kbegin != kh_end(box->hbegin); kbegin++){ int res; int64_t node_hash=-1,node_begin=0, node_end=0; int64_t nb_begin= 0, nb_end = 0; int64_t nblist[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)]; if (kh_exist(box->hbegin, kbegin)){ // I have to call this! khint32_t kend = kh_get(1, box->hend, kh_key(box->hbegin, kbegin)); node_hash = kh_key(box->hbegin, kbegin); node_begin = kh_value(box->hbegin, kbegin); node_end = kh_value(box->hend, kend); res = neighbour_hash_3d(node_hash,nblist,box->width,box); for(unsigned int j=0;j<(2*box->width+1)*(2*box->width+1)*(2*box->width+1);j+=1){ if(nblist[j]>=0){ //nb_hash = nblist[j]; nb_begin = kh_value(box->hbegin, kh_get(0, box->hbegin, nblist[j]) ); nb_end = kh_value(box->hend , kh_get(1, box->hend , nblist[j]) ); pair_count += 1; particle_pair_count += (node_end-node_begin)*(nb_end-nb_begin); } } } } printf("unique ordered particle_pair_count = %ld\n",particle_pair_count); return pair_count; } int setup_box_pairs(linkedListBox *box, int64_t *node_begin,int64_t *node_end, int64_t *nb_begin,int64_t *nb_end) { int64_t pair_count = 0; for (khint32_t kbegin = kh_begin(box->hbegin); kbegin != kh_end(box->hbegin); kbegin++){ int res; int64_t node_hash=-1; int64_t nblist[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)]; if (kh_exist(box->hbegin, kbegin)){ // I have to call this! khint32_t kend = kh_get(1, box->hend, kh_key(box->hbegin, kbegin)); node_hash = kh_key(box->hbegin, kbegin); res = neighbour_hash_3d(node_hash,nblist,box->width,box); for(unsigned int j=0;j<(2*box->width+1)*(2*box->width+1)*(2*box->width+1);j+=1){ if(nblist[j]>=0){ //nb_hash = nblist[j]; node_begin[pair_count] = kh_value(box->hbegin, kbegin); node_end[pair_count] = kh_value(box->hend, kend); nb_begin[pair_count] = kh_value(box->hbegin, kh_get(0, box->hbegin, nblist[j]) ); nb_end[pair_count] = kh_value(box->hend , kh_get(1, box->hend , nblist[j]) ); pair_count += 1;//(node_end-node_begin)*(nb_end-nb_begin); } } } //printf("thread %d - %lf %lf\n",i,lsph->rho[node_begin],lsph->rho[node_end-1]); } return pair_count; } int compute_density_3d_chunk_noomp_shift(int64_t node_begin, int64_t node_end, int64_t nb_begin, int64_t nb_end,double h, double* restrict x, double* restrict y, double* restrict z, double* restrict nu, double* restrict rho){ const double inv_h = 1./h; const double kernel_constant = w_bspline_3d_constant(h); for(int64_t ii=node_begin;ii<node_end;ii+=1){ double xii = x[ii]; double yii = y[ii]; double zii = z[ii]; double rhoii = 0.0; #pragma omp simd reduction(+:rhoii) for(int64_t jj=nb_begin;jj<nb_end;jj+=1){ double q = 0.; double xij = xii-x[jj]; double yij = yii-y[jj]; double zij = zii-z[jj]; q += xij*xij; q += yij*yij; q += zij*zij; q = sqrt(q)*inv_h; rhoii += nu[jj]*w_bspline_3d_simd(q); } rho[ii-node_begin] += rhoii*kernel_constant; } return 0; } int compute_density_3d_load_ballanced(int N, double h, SPHparticle *lsph, linkedListBox *box){ int64_t *node_begin,*node_end,*nb_begin,*nb_end; int64_t max_box_pair_count = 0; max_box_pair_count = count_box_pairs(box); node_begin = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t)); node_end = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t)); nb_begin = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t)); nb_end = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t)); setup_box_pairs(box,node_begin,node_end,nb_begin,nb_end); for(int64_t ii=0;ii<N;ii+=1) lsph->rho[ii] = 0.0; #pragma omp parallel for num_threads(24) for(size_t i=0;i<max_box_pair_count;i+=1){ double local_rho[node_end[i]-node_begin[i]]; for(size_t ii=0;ii<node_end[i]-node_begin[i];ii+=1) local_rho[ii] = 0.; compute_density_3d_chunk_noomp_shift(node_begin[i],node_end[i],nb_begin[i],nb_end[i], h,lsph->x,lsph->y,lsph->z,lsph->nu,local_rho); #pragma omp critical { for(size_t ii=node_begin[i];ii<node_end[i];ii+=1) lsph->rho[ii] += local_rho[ii - node_begin[i]]; } } free(node_begin); free(node_end); free(nb_begin); free(nb_end); //for(int64_t i=0;i<N;i+=1000) // printf("%ld - %lf\n",i,lsph->rho[i]); return 0; } /*******************************************************************/ /*******************************************************************/ /* Pit from hell */ int compute_density_3d_chunk_symmetrical(int64_t node_begin, int64_t node_end, int64_t nb_begin, int64_t nb_end,double h, double* restrict x, double* restrict y, double* restrict z, double* restrict nu, double* restrict rhoi, double* restrict rhoj){ const double inv_h = 1./h; for(int64_t ii=node_begin;ii<node_end;ii+=1){ double xii = x[ii]; double yii = y[ii]; double zii = z[ii]; #pragma omp simd for(int64_t jj=nb_begin;jj<nb_end;jj+=1){ double q = 0.; double xij = xii-x[jj]; double yij = yii-y[jj]; double zij = zii-z[jj]; q += xij*xij; q += yij*yij; q += zij*zij; q = sqrt(q)*inv_h; double wij = w_bspline_3d_simd(q); rhoi[ii-node_begin] += nu[jj]*wij; rhoj[jj-nb_begin] += nu[ii]*wij; } } return 0; } #define min(a,b) \ ({ __typeof__ (a) _a = (a); \ __typeof__ (b) _b = (b); \ _a < _b ? _a : _b; }) int compute_density_3d_chunk_symm_nlo(int64_t node_begin, int64_t node_end, int64_t nb_begin, int64_t nb_end,double h, double* restrict x, double* restrict y, double* restrict z, double* restrict nu, double* restrict rhoi, double* restrict rhoj){ const int64_t STRIP=512; const double inv_h = 1./h; /* for(int64_t ii=node_begin;ii<node_end;ii+=1){ #pragma omp simd for(int64_t jj=nb_begin;jj<nb_end;jj+=1){ double q = 0.; double xii = x[ii]; double yii = y[ii]; double zii = z[ii]; double xij = xii-x[jj]; double yij = yii-y[jj]; double zij = zii-z[jj]; q += xij*xij; q += yij*yij; q += zij*zij; q = sqrt(q)*inv_h; double wij = w_bspline_3d_simd(q); rhoi[ii-node_begin] += nu[jj]*wij; rhoj[jj-nb_begin] += nu[ii]*wij; } }*/ for(int64_t i=0;i<(node_end-node_begin);i+=STRIP) for(int64_t j=0;j<( nb_end - nb_begin );j+=STRIP) for(int64_t ii=i;ii<min(node_end-node_begin,i+STRIP);ii+=1) #pragma omp simd for(int64_t jj=j;jj<min( nb_end - nb_begin ,j+STRIP);jj+=1){ double q = 0.; double xij = x[ii+node_begin]-x[jj+nb_begin]; double yij = y[ii+node_begin]-y[jj+nb_begin]; double zij = z[ii+node_begin]-z[jj+nb_begin]; q += xij*xij; q += yij*yij; q += zij*zij; q = sqrt(q)*inv_h; double wij = w_bspline_3d_simd(q); rhoi[ii] += nu[jj + nb_begin]*wij; rhoj[jj] += nu[ii+node_begin]*wij; } return 0; } int compute_density_3d_chunk_symm_colapse(int64_t node_begin, int64_t node_end, int64_t nb_begin, int64_t nb_end,double h, double* restrict x, double* restrict y, double* restrict z, double* restrict nu, double* restrict rhoi, double* restrict rhoj){ const double inv_h = 1./h; #pragma omp simd for(int64_t ii=node_begin;ii<node_end;ii+=1){ for(int64_t jj=nb_begin;jj<nb_end;jj+=1){ double q = 0.; double xij = x[ii]-x[jj]; double yij = y[ii]-y[jj]; double zij = z[ii]-z[jj]; q += xij*xij; q += yij*yij; q += zij*zij; q = sqrt(q)*inv_h; double wij = w_bspline_3d_simd(q); rhoi[ii-node_begin] += nu[jj]*wij; rhoj[jj-nb_begin] += nu[ii]*wij; } } return 0; } int cpr_int64_t(const void *a, const void *b){ return ( *(int64_t*)a - *(int64_t*)b ); } int unique_box_bounds(int64_t max_box_pair_count, int64_t *node_begin, int64_t *node_end, int64_t *nb_begin, int64_t *nb_end) { int64_t box_skip=0; if(node_begin==NULL || node_end==NULL || nb_begin==NULL || nb_end==NULL) return -1; for(int64_t i=0;i<max_box_pair_count;i+=1){ if(node_begin[i]>=0){ for(int64_t j=i+1;j<max_box_pair_count;j+=1){ if((node_begin[j]==nb_begin[i]) && (nb_begin[j]==node_begin[i]) ){ node_begin[j] = -1; node_end[j] = -1; nb_begin[j] = -1; nb_end[j] = -1; //node_begin[j] -= -1; node_end[j] -= -1; //nb_begin[j] -= -1; nb_end[j] -= -1; box_skip += 1; } } } } //qsort(node_begin,max_box_pair_count, sizeof(int64_t),cpr_int64_t); //qsort(node_end ,max_box_pair_count, sizeof(int64_t),cpr_int64_t); //qsort(nb_begin ,max_box_pair_count, sizeof(int64_t),cpr_int64_t); //qsort(nb_end ,max_box_pair_count, sizeof(int64_t),cpr_int64_t); /* if(node_begin[i]<=nb_begin[i]){ box_keep +=1; } qsort(node_begin,max_box_pair_count, sizeof(int64_t),cpr_int64_t); qsort(node_end ,max_box_pair_count, sizeof(int64_t),cpr_int64_t); qsort(nb_begin ,max_box_pair_count, sizeof(int64_t),cpr_int64_t); qsort(nb_end ,max_box_pair_count, sizeof(int64_t),cpr_int64_t); max_box_pair_count = box_keep; //max_box_pair_count - box_subtract; for(int64_t i=0;i<max_box_pair_count;i+=1){ node_begin[i] *= -1; node_end[i] *= -1; nb_begin[i] *= -1; nb_end[i] *= -1; } qsort(node_begin,max_box_pair_count, sizeof(int64_t),cpr_int64_t); qsort(node_end ,max_box_pair_count, sizeof(int64_t),cpr_int64_t); qsort(nb_begin ,max_box_pair_count, sizeof(int64_t),cpr_int64_t); qsort(nb_end ,max_box_pair_count, sizeof(int64_t),cpr_int64_t);*/ return box_skip; } int setup_unique_box_pairs(linkedListBox *box, int64_t *node_begin,int64_t *node_end, int64_t *nb_begin,int64_t *nb_end) { int64_t pair_count = 0; for (khint32_t kbegin = kh_begin(box->hbegin); kbegin != kh_end(box->hbegin); kbegin++){ int res; int64_t node_hash=-1; int64_t nblist[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)]; if (kh_exist(box->hbegin, kbegin)){ // I have to call this! khint32_t kend = kh_get(1, box->hend, kh_key(box->hbegin, kbegin)); node_hash = kh_key(box->hbegin, kbegin); res = neighbour_hash_3d(node_hash,nblist,box->width,box); for(unsigned int j=0;j<(2*box->width+1)*(2*box->width+1)*(2*box->width+1);j+=1){ if(nblist[j]>=0){ //nb_hash = nblist[j]; if(kh_value(box->hbegin, kbegin) <= kh_value(box->hbegin, kh_get(0, box->hbegin, nblist[j]) )) { node_begin[pair_count] = kh_value(box->hbegin, kbegin); node_end[pair_count] = kh_value(box->hend, kend); nb_begin[pair_count] = kh_value(box->hbegin, kh_get(0, box->hbegin, nblist[j]) ); nb_end[pair_count] = kh_value(box->hend , kh_get(1, box->hend , nblist[j]) ); pair_count += 1;//(node_end-node_begin)*(nb_end-nb_begin); } } } } //printf("thread %d - %lf %lf\n",i,lsph->rho[node_begin],lsph->rho[node_end-1]); } return pair_count; } int compute_density_3d_symmetrical_load_ballance(int N, double h, SPHparticle *lsph, linkedListBox *box){ int64_t *node_begin,*node_end,*nb_begin,*nb_end; int64_t max_box_pair_count = 0, particle_pair_count = 0; int64_t box_skip = 0; const double kernel_constant = w_bspline_3d_constant(h); max_box_pair_count = count_box_pairs(box); printf("max_box_pair_count = %ld\n",max_box_pair_count); node_begin = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t)); node_end = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t)); nb_begin = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t)); nb_end = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t)); max_box_pair_count = setup_unique_box_pairs(box,node_begin,node_end,nb_begin,nb_end);//setup_box_pairs(box,node_begin,node_end,nb_begin,nb_end); printf("unique max_box_pair_count = %ld\n",max_box_pair_count); double avg_nb_len = 0.0; for(int64_t i=0;i<max_box_pair_count;i+=1) avg_nb_len += (nb_end[i]-nb_begin[i]); avg_nb_len /= max_box_pair_count; printf("avg_nb_len = %lf\n",avg_nb_len); for(int64_t i=0;i<max_box_pair_count;i+=1) particle_pair_count += (node_end[i]-node_begin[i])*(nb_end[i]-nb_begin[i]); printf("unique unordered particle_pair_count = %ld\n",particle_pair_count); //box_skip = unique_box_bounds(max_box_pair_count,node_begin,node_end,nb_begin,nb_end); for(int64_t ii=0;ii<N;ii+=1) lsph->rho[ii] = 0.0; #pragma omp parallel for schedule(dynamic,5) proc_bind(master) for(size_t i=0;i<max_box_pair_count;i+=1){ double local_rhoi[node_end[i] - node_begin[i]]; double local_rhoj[ nb_end[i] - nb_begin[i]]; for(size_t ii=0;ii<node_end[i]-node_begin[i];ii+=1) local_rhoi[ii] = 0.; for(size_t ii=0;ii<nb_end[i]-nb_begin[i];ii+=1) local_rhoj[ii] = 0.; compute_density_3d_chunk_symmetrical(node_begin[i],node_end[i],nb_begin[i],nb_end[i],h, lsph->x,lsph->y,lsph->z,lsph->nu,local_rhoi,local_rhoj); //compute_density_3d_chunk_symm_nlo(node_begin[i],node_end[i],nb_begin[i],nb_end[i],h, // lsph->x,lsph->y,lsph->z,lsph->nu,local_rhoi,local_rhoj); //compute_density_3d_chunk_symm_colapse(node_begin[i],node_end[i],nb_begin[i],nb_end[i],h, // lsph->x,lsph->y,lsph->z,lsph->nu,local_rhoi,local_rhoj); #pragma omp critical { for(size_t ii=node_begin[i];ii<node_end[i];ii+=1){ lsph->rho[ii] += kernel_constant*local_rhoi[ii - node_begin[i]]; } if(node_begin[i] != nb_begin[i]) for(size_t ii=nb_begin[i];ii<nb_end[i];ii+=1){ lsph->rho[ii] += kernel_constant*local_rhoj[ii - nb_begin[i]]; } } } free(node_begin); free(node_end); free(nb_begin); free(nb_end); return 0; } int compute_density_3d_symmetrical_lb_branching(int N, double h, SPHparticle *lsph, linkedListBox *box){ int64_t *node_begin,*node_end,*nb_begin,*nb_end; int64_t max_box_pair_count = 0, particle_pair_count = 0; int64_t box_skip = 0; const double kernel_constant = w_bspline_3d_constant(h); max_box_pair_count = count_box_pairs(box); printf("max_box_pair_count = %ld\n",max_box_pair_count); node_begin = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t)); node_end = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t)); nb_begin = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t)); nb_end = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t)); max_box_pair_count = setup_box_pairs(box,node_begin,node_end,nb_begin,nb_end); box_skip = unique_box_bounds(max_box_pair_count,node_begin,node_end,nb_begin,nb_end); for(int64_t i=0;i<max_box_pair_count;i+=1) if(node_end[i] >= 0) particle_pair_count += (node_end[i]-node_begin[i])*(nb_end[i]-nb_begin[i]); printf("unique unordered particle_pair_count = %ld\n",particle_pair_count); for(int64_t ii=0;ii<N;ii+=1) lsph->rho[ii] = 0.0; #pragma omp parallel for for(size_t i=0;i<max_box_pair_count;i+=1){ if(node_end[i]<0) continue; double local_rhoi[node_end[i] - node_begin[i]]; double local_rhoj[ nb_end[i] - nb_begin[i]]; for(size_t ii=0;ii<node_end[i]-node_begin[i];ii+=1) local_rhoi[ii] = 0.; for(size_t ii=0;ii<nb_end[i]-nb_begin[i];ii+=1) local_rhoj[ii] = 0.; compute_density_3d_chunk_symmetrical(node_begin[i],node_end[i],nb_begin[i],nb_end[i],h, lsph->x,lsph->y,lsph->z,lsph->nu,local_rhoi,local_rhoj); #pragma omp critical { for(size_t ii=node_begin[i];ii<node_end[i];ii+=1) lsph->rho[ii] += kernel_constant*local_rhoi[ii - node_begin[i]]; if(node_begin[i] != nb_begin[i]) for(size_t ii=nb_begin[i];ii<nb_end[i];ii+=1) lsph->rho[ii] += kernel_constant*local_rhoj[ii - nb_begin[i]]; /* if(node_begin[i]!=nb_begin[i]) for(size_t ii=nb_begin[i];ii<nb_end[i];ii+=1) lsph->rho[ii] += kernel_constant*local_rhoj[ii - nb_begin[i]];*/ } } free(node_begin); free(node_end); free(nb_begin); free(nb_end); return 0; } /*******************************************************************/ /*******************************************************************/ /* int compute_density_3d_chunk_symmetrical(int64_t node_begin, int64_t node_end, int64_t nb_begin, int64_t nb_end,double h, double* restrict x, double* restrict y, double* restrict z, double* restrict nu, double* restrict rho) { const double inv_h = 1./h; const double kernel_constant = w_bspline_3d_constant(h); double rhoi[node_end-node_begin]; double rhoj[nb_end-nb_begin]; for(int64_t ii=0;ii<node_end-node_begin;ii+=1) rhoi[ii] = 0.; for(int64_t jj=0;jj<nb_end-nb_begin;jj+=1) rhoj[jj] = 0.; for(int64_t ii=node_begin;ii<node_end;ii+=1){ double xii = x[ii]; double yii = y[ii]; double zii = z[ii]; #pragma omp simd for(int64_t jj=nb_begin;jj<nb_end;jj+=1){ double q = 0.; double xij = xii-x[jj]; double yij = yii-y[jj]; double zij = zii-z[jj]; q += xij*xij; q += yij*yij; q += zij*zij; q = sqrt(q)*inv_h; double wij = w_bspline_3d_simd(q); rhoi[ii-node_begin] += nu[jj]*wij; rhoj[jj-nb_begin] += nu[ii]*wij; } } for(int64_t ii=node_begin;ii<node_end;ii+=1) rho[ii] += rhoi[ii-node_begin]*kernel_constant; if(nb_begin == node_begin) return 0; for(int64_t jj=nb_begin;jj<nb_end;jj+=1) rho[jj] += rhoj[jj-nb_begin]*kernel_constant; return 0; }*/ /* int cpr_int64_t(const void *a, const void *b){ return ( *(int64_t*)a - *(int64_t*)b ); } */ /* int unique_box_bounds(int64_t max_box_pair_count, int64_t *node_begin, int64_t *node_end, int64_t *nb_begin, int64_t *nb_end) { int64_t box_keep=0; if(node_begin==NULL || node_end==NULL || nb_begin==NULL || nb_end==NULL) return -1; for(int64_t i=0;i<max_box_pair_count;i+=1) if(node_begin[i]<=nb_begin[i]){ node_begin[i] *= -1; node_end[i] *= -1; nb_begin[i] *= -1; nb_end[i] *= -1; box_keep +=1; } qsort(node_begin,max_box_pair_count, sizeof(int64_t),cpr_int64_t); qsort(node_end ,max_box_pair_count, sizeof(int64_t),cpr_int64_t); qsort(nb_begin ,max_box_pair_count, sizeof(int64_t),cpr_int64_t); qsort(nb_end ,max_box_pair_count, sizeof(int64_t),cpr_int64_t); max_box_pair_count = box_keep; //max_box_pair_count - box_subtract; for(int64_t i=0;i<max_box_pair_count;i+=1){ node_begin[i] *= -1; node_end[i] *= -1; nb_begin[i] *= -1; nb_end[i] *= -1; } qsort(node_begin,max_box_pair_count, sizeof(int64_t),cpr_int64_t); qsort(node_end ,max_box_pair_count, sizeof(int64_t),cpr_int64_t); qsort(nb_begin ,max_box_pair_count, sizeof(int64_t),cpr_int64_t); qsort(nb_end ,max_box_pair_count, sizeof(int64_t),cpr_int64_t); return max_box_pair_count; } int compute_density_3d_symmetrical_lb(int N, double h, SPHparticle *lsph, linkedListBox *box){ int64_t *node_begin,*node_end,*nb_begin,*nb_end; int64_t max_box_pair_count = 0; max_box_pair_count = count_box_pairs(box); node_begin = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t)); node_end = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t)); nb_begin = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t)); nb_end = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t)); setup_box_pairs(box,node_begin,node_end,nb_begin,nb_end); max_box_pair_count = unique_box_bounds(max_box_pair_count,node_begin,node_end,nb_begin,nb_end); for(int64_t ii=0;ii<N;ii+=1) lsph->rho[ii] = 0.0; #pragma omp parallel for num_threads(24) for(size_t i=0;i<max_box_pair_count;i+=1){ if(node_begin[i] > nb_begin[i]) continue; compute_density_3d_chunk_symmetrical(node_begin[i],node_end[i],nb_begin[i],nb_end[i], h,lsph->x,lsph->y,lsph->z,lsph->nu,lsph->rho); } free(node_begin); free(node_end); free(nb_begin); free(nb_end); //for(int64_t i=0;i<N;i+=1000) // printf("%ld - %lf\n",i,lsph->rho[i]); return 0; }*/ /*******************************************************************/ /*******************************************************************/ /*******************************************************************/ #pragma omp declare simd double pressure_from_density(double rho){ double p = cbrt(rho); p = 0.5*p*rho; return p; } #pragma omp declare simd double gamma_from_u(double ux,double uy,double uz){ double gamma = 1.0; gamma += ux*ux; gamma += uy*uy; gamma += uz*uz; gamma = sqrt(gamma); return gamma; } /* int compute_force_3d(int N, double h, SPHparticle *lsph, linkedListBox *box){ int err, res; double dist = 0.0; khiter_t kbegin,kend; int64_t node_hash=-1,node_begin=0, node_end=0; int64_t nb_hash=-1 , nb_begin= 0, nb_end = 0; int64_t nblist[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)]; for (kbegin = kh_begin(box->hbegin); kbegin != kh_end(box->hbegin); kbegin++){ if (kh_exist(box->hbegin, kbegin)){ kend = kh_get(1, box->hend, kh_key(box->hbegin, kbegin)); node_hash = kh_key(box->hbegin, kbegin); node_begin = kh_value(box->hbegin, kbegin); node_end = kh_value(box->hend, kend); for(int64_t ii=node_begin;ii<node_end;ii+=1)// this loop inside was the problem lsph->rho[ii] = 0.0; res = neighbour_hash_3d(node_hash,nblist,box->width,box); for(unsigned int j=0;j<(2*box->width+1)*(2*box->width+1)*(2*box->width+1);j+=1){ if(nblist[j]>=0){ nb_hash = nblist[j]; nb_begin = kh_value(box->hbegin, kh_get(0, box->hbegin, nblist[j]) ); nb_end = kh_value(box->hend , kh_get(1, box->hend , nblist[j]) ); for(int64_t ii=node_begin;ii<node_end;ii+=1){ // this loop inside was the problem for(int64_t jj=nb_begin;jj<nb_end;jj+=1){ dist = distance_3d(lsph->x[i],lsph->y[i],lsph->z[i], lsph->x[j],lsph->y[j],lsph->z[j]); lsph->rho[ii] += (lsph->nu[jj])*(box->w(dist,h)); } } } } } } return 0; } */ /* int compute_force_3d(int N, double h, SPHparticle *lsph, linkedListBox *box){ int err, res; double dist = 0.0; khiter_t kbegin,kend; int64_t node_hash=-1,node_begin=0, node_end=0; int64_t nb_hash=-1 , nb_begin= 0, nb_end = 0; int64_t nblist[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)]; for (kbegin = kh_begin(box->hbegin); kbegin != kh_end(box->hbegin); kbegin++){ if (kh_exist(box->hbegin, kbegin)){ kend = kh_get(1, box->hend, kh_key(box->hbegin, kbegin)); node_hash = kh_key(box->hbegin, kbegin); node_begin = kh_value(box->hbegin, kbegin); node_end = kh_value(box->hend, kend); for(int64_t ii=node_begin;ii<node_end;ii+=1){ lsph[ii].F.x = 0.0; lsph[ii].F.y = 0.0; lsph[ii].F.z = 0.0; } res = neighbour_hash_3d(node_hash,nblist,box->width,box); for(unsigned int j=0;j<(2*box->width+1)*(2*box->width+1)*(2*box->width+1);j+=1){ if(nblist[j]>=0){ nb_hash = nblist[j]; nb_begin = kh_value(box->hbegin, kh_get(0, box->hbegin, nblist[j]) ); nb_end = kh_value(box->hend , kh_get(1, box->hend , nblist[j]) ); for(int64_t ii=node_begin;ii<node_end;ii+=1){ // this loop inside was the problem for(int64_t jj=nb_begin;jj<nb_end;jj+=1){ dist = double4_distance_3d(&(lsph[ii].r),&(lsph[jj].r)); = (); lsph[ii].F.x += ((lsph[ii].r.x-lsph[jj].r.x)/dist); lsph[ii].F.y += ; lsph[ii].F.z += ; } } } } } } return 0; } */ const double fk_bspline_32[32] = { 6.66666667e-01, 6.57754579e-01, 6.32830944e-01, 5.94614705e-01, 5.45824802e-01, 4.89180177e-01, 4.27399774e-01, 3.63202533e-01, 2.99307397e-01, 2.38433308e-01, 1.83299207e-01, 1.36445011e-01, 9.83294731e-02, 6.80686561e-02, 4.47562463e-02, 2.74859298e-02, 1.53513925e-02, 7.44632048e-03, 2.86439976e-03, 6.99316348e-04, 4.47562463e-05, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00}; const double fk_bspline_128[128] = { 6.66666667e-01, 6.66115256e-01, 6.64487387e-01, 6.61822602e-01, 6.58160445e-01, 6.53540459e-01, 6.48002188e-01, 6.41585176e-01, 6.34328964e-01, 6.26273098e-01, 6.17457119e-01, 6.07920573e-01, 5.97703001e-01, 5.86843948e-01, 5.75382957e-01, 5.63359570e-01, 5.50813333e-01, 5.37783787e-01, 5.24310476e-01, 5.10432945e-01, 4.96190735e-01, 4.81623391e-01, 4.66770456e-01, 4.51671473e-01, 4.36365986e-01, 4.20893537e-01, 4.05293671e-01, 3.89605931e-01, 3.73869861e-01, 3.58125002e-01, 3.42410900e-01, 3.26767097e-01, 3.11233137e-01, 2.95848563e-01, 2.80652918e-01, 2.65685747e-01, 2.50986591e-01, 2.36594995e-01, 2.22550503e-01, 2.08892657e-01, 1.95661000e-01, 1.82895077e-01, 1.70634431e-01, 1.58916000e-01, 1.47746458e-01, 1.37112949e-01, 1.27002291e-01, 1.17401303e-01, 1.08296805e-01, 9.96756140e-02, 9.15245505e-02, 8.38304328e-02, 7.65800797e-02, 6.97603101e-02, 6.33579430e-02, 5.73597971e-02, 5.17526914e-02, 4.65234448e-02, 4.16588760e-02, 3.71458040e-02, 3.29710476e-02, 2.91214257e-02, 2.55837572e-02, 2.23448610e-02, 1.93915558e-02, 1.67106607e-02, 1.42889945e-02, 1.21133759e-02, 1.01706240e-02, 8.44755758e-03, 6.93099549e-03, 5.60775662e-03, 4.46465985e-03, 3.48852404e-03, 2.66616806e-03, 1.98441079e-03, 1.43007110e-03, 9.89967859e-04, 6.50919937e-04, 3.99746206e-04, 2.23265538e-04, 1.08296805e-04, 4.16588760e-05, 1.01706240e-05, 6.50919937e-07, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00}; const double fk_bspline_1024[1024] = { 6.66666667e-01, 6.66658079e-01, 6.66632368e-01, 6.66589608e-01, 6.66529876e-01, 6.66453246e-01, 6.66359796e-01, 6.66249599e-01, 6.66122732e-01, 6.65979271e-01, 6.65819291e-01, 6.65642868e-01, 6.65450077e-01, 6.65240994e-01, 6.65015696e-01, 6.64774257e-01, 6.64516753e-01, 6.64243260e-01, 6.63953853e-01, 6.63648609e-01, 6.63327602e-01, 6.62990909e-01, 6.62638605e-01, 6.62270765e-01, 6.61887466e-01, 6.61488783e-01, 6.61074792e-01, 6.60645569e-01, 6.60201188e-01, 6.59741726e-01, 6.59267259e-01, 6.58777861e-01, 6.58273610e-01, 6.57754579e-01, 6.57220846e-01, 6.56672485e-01, 6.56109573e-01, 6.55532184e-01, 6.54940396e-01, 6.54334282e-01, 6.53713920e-01, 6.53079384e-01, 6.52430750e-01, 6.51768095e-01, 6.51091493e-01, 6.50401020e-01, 6.49696752e-01, 6.48978765e-01, 6.48247134e-01, 6.47501935e-01, 6.46743244e-01, 6.45971135e-01, 6.45185686e-01, 6.44386971e-01, 6.43575066e-01, 6.42750048e-01, 6.41911990e-01, 6.41060970e-01, 6.40197063e-01, 6.39320344e-01, 6.38430889e-01, 6.37528774e-01, 6.36614075e-01, 6.35686866e-01, 6.34747225e-01, 6.33795226e-01, 6.32830944e-01, 6.31854457e-01, 6.30865839e-01, 6.29865166e-01, 6.28852514e-01, 6.27827959e-01, 6.26791575e-01, 6.25743439e-01, 6.24683626e-01, 6.23612213e-01, 6.22529274e-01, 6.21434885e-01, 6.20329123e-01, 6.19212062e-01, 6.18083778e-01, 6.16944347e-01, 6.15793845e-01, 6.14632348e-01, 6.13459930e-01, 6.12276668e-01, 6.11082637e-01, 6.09877913e-01, 6.08662571e-01, 6.07436688e-01, 6.06200339e-01, 6.04953599e-01, 6.03696545e-01, 6.02429251e-01, 6.01151794e-01, 5.99864249e-01, 5.98566692e-01, 5.97259199e-01, 5.95941844e-01, 5.94614705e-01, 5.93277856e-01, 5.91931373e-01, 5.90575332e-01, 5.89209808e-01, 5.87834877e-01, 5.86450616e-01, 5.85057098e-01, 5.83654401e-01, 5.82242599e-01, 5.80821769e-01, 5.79391986e-01, 5.77953326e-01, 5.76505864e-01, 5.75049676e-01, 5.73584838e-01, 5.72111425e-01, 5.70629514e-01, 5.69139179e-01, 5.67640496e-01, 5.66133541e-01, 5.64618390e-01, 5.63095118e-01, 5.61563801e-01, 5.60024515e-01, 5.58477335e-01, 5.56922337e-01, 5.55359597e-01, 5.53789190e-01, 5.52211192e-01, 5.50625678e-01, 5.49032725e-01, 5.47432408e-01, 5.45824802e-01, 5.44209983e-01, 5.42588027e-01, 5.40959010e-01, 5.39323007e-01, 5.37680094e-01, 5.36030346e-01, 5.34373840e-01, 5.32710650e-01, 5.31040853e-01, 5.29364524e-01, 5.27681738e-01, 5.25992573e-01, 5.24297102e-01, 5.22595402e-01, 5.20887548e-01, 5.19173617e-01, 5.17453683e-01, 5.15727823e-01, 5.13996112e-01, 5.12258626e-01, 5.10515440e-01, 5.08766630e-01, 5.07012271e-01, 5.05252441e-01, 5.03487213e-01, 5.01716663e-01, 4.99940869e-01, 4.98159904e-01, 4.96373845e-01, 4.94582767e-01, 4.92786746e-01, 4.90985857e-01, 4.89180177e-01, 4.87369781e-01, 4.85554745e-01, 4.83735144e-01, 4.81911054e-01, 4.80082550e-01, 4.78249708e-01, 4.76412605e-01, 4.74571315e-01, 4.72725914e-01, 4.70876478e-01, 4.69023083e-01, 4.67165804e-01, 4.65304717e-01, 4.63439897e-01, 4.61571420e-01, 4.59699362e-01, 4.57823799e-01, 4.55944806e-01, 4.54062459e-01, 4.52176833e-01, 4.50288004e-01, 4.48396048e-01, 4.46501040e-01, 4.44603057e-01, 4.42702173e-01, 4.40798465e-01, 4.38892008e-01, 4.36982877e-01, 4.35071149e-01, 4.33156899e-01, 4.31240203e-01, 4.29321136e-01, 4.27399774e-01, 4.25476193e-01, 4.23550468e-01, 4.21622675e-01, 4.19692890e-01, 4.17761188e-01, 4.15827645e-01, 4.13892336e-01, 4.11955338e-01, 4.10016726e-01, 4.08076576e-01, 4.06134962e-01, 4.04191962e-01, 4.02247650e-01, 4.00302103e-01, 3.98355395e-01, 3.96407603e-01, 3.94458803e-01, 3.92509069e-01, 3.90558477e-01, 3.88607104e-01, 3.86655025e-01, 3.84702315e-01, 3.82749050e-01, 3.80795307e-01, 3.78841159e-01, 3.76886684e-01, 3.74931957e-01, 3.72977053e-01, 3.71022048e-01, 3.69067018e-01, 3.67112038e-01, 3.65157185e-01, 3.63202533e-01, 3.61248159e-01, 3.59294138e-01, 3.57340545e-01, 3.55387457e-01, 3.53434949e-01, 3.51483097e-01, 3.49531976e-01, 3.47581662e-01, 3.45632230e-01, 3.43683758e-01, 3.41736319e-01, 3.39789989e-01, 3.37844845e-01, 3.35900962e-01, 3.33958416e-01, 3.32017282e-01, 3.30077636e-01, 3.28139553e-01, 3.26203110e-01, 3.24268382e-01, 3.22335444e-01, 3.20404373e-01, 3.18475243e-01, 3.16548131e-01, 3.14623112e-01, 3.12700262e-01, 3.10779657e-01, 3.08861372e-01, 3.06945483e-01, 3.05032065e-01, 3.03121194e-01, 3.01212946e-01, 2.99307397e-01, 2.97404622e-01, 2.95504697e-01, 2.93607697e-01, 2.91713698e-01, 2.89822776e-01, 2.87935006e-01, 2.86050465e-01, 2.84169227e-01, 2.82291369e-01, 2.80416966e-01, 2.78546093e-01, 2.76678827e-01, 2.74815243e-01, 2.72955417e-01, 2.71099424e-01, 2.69247340e-01, 2.67399241e-01, 2.65555202e-01, 2.63715299e-01, 2.61879608e-01, 2.60048204e-01, 2.58221163e-01, 2.56398561e-01, 2.54580473e-01, 2.52766975e-01, 2.50958142e-01, 2.49154051e-01, 2.47354777e-01, 2.45560395e-01, 2.43770982e-01, 2.41986612e-01, 2.40207362e-01, 2.38433308e-01, 2.36664524e-01, 2.34901086e-01, 2.33143071e-01, 2.31390554e-01, 2.29643610e-01, 2.27902316e-01, 2.26166746e-01, 2.24436977e-01, 2.22713084e-01, 2.20995143e-01, 2.19283229e-01, 2.17577418e-01, 2.15877786e-01, 2.14184409e-01, 2.12497361e-01, 2.10816720e-01, 2.09142560e-01, 2.07474956e-01, 2.05813986e-01, 2.04159724e-01, 2.02512246e-01, 2.00871628e-01, 1.99237945e-01, 1.97611273e-01, 1.95991688e-01, 1.94379265e-01, 1.92774080e-01, 1.91176209e-01, 1.89585728e-01, 1.88002711e-01, 1.86427235e-01, 1.84859375e-01, 1.83299207e-01, 1.81746806e-01, 1.80202249e-01, 1.78665611e-01, 1.77136968e-01, 1.75616394e-01, 1.74103967e-01, 1.72599761e-01, 1.71103853e-01, 1.69616317e-01, 1.68137230e-01, 1.66666667e-01, 1.65204687e-01, 1.63751281e-01, 1.62306426e-01, 1.60870094e-01, 1.59442261e-01, 1.58022902e-01, 1.56611992e-01, 1.55209505e-01, 1.53815416e-01, 1.52429700e-01, 1.51052331e-01, 1.49683285e-01, 1.48322536e-01, 1.46970060e-01, 1.45625830e-01, 1.44289821e-01, 1.42962009e-01, 1.41642368e-01, 1.40330873e-01, 1.39027499e-01, 1.37732220e-01, 1.36445011e-01, 1.35165848e-01, 1.33894704e-01, 1.32631555e-01, 1.31376375e-01, 1.30129139e-01, 1.28889822e-01, 1.27658399e-01, 1.26434845e-01, 1.25219133e-01, 1.24011240e-01, 1.22811140e-01, 1.21618807e-01, 1.20434217e-01, 1.19257343e-01, 1.18088162e-01, 1.16926648e-01, 1.15772775e-01, 1.14626518e-01, 1.13487852e-01, 1.12356752e-01, 1.11233193e-01, 1.10117149e-01, 1.09008596e-01, 1.07907507e-01, 1.06813859e-01, 1.05727624e-01, 1.04648779e-01, 1.03577299e-01, 1.02513157e-01, 1.01456328e-01, 1.00406788e-01, 9.93645117e-02, 9.83294731e-02, 9.73016473e-02, 9.62810090e-02, 9.52675330e-02, 9.42611942e-02, 9.32619673e-02, 9.22698271e-02, 9.12847483e-02, 9.03067058e-02, 8.93356743e-02, 8.83716286e-02, 8.74145435e-02, 8.64643938e-02, 8.55211542e-02, 8.45847996e-02, 8.36553047e-02, 8.27326442e-02, 8.18167931e-02, 8.09077259e-02, 8.00054177e-02, 7.91098430e-02, 7.82209767e-02, 7.73387936e-02, 7.64632684e-02, 7.55943760e-02, 7.47320911e-02, 7.38763885e-02, 7.30272430e-02, 7.21846293e-02, 7.13485223e-02, 7.05188966e-02, 6.96957272e-02, 6.88789888e-02, 6.80686561e-02, 6.72647039e-02, 6.64671071e-02, 6.56758404e-02, 6.48908785e-02, 6.41121963e-02, 6.33397686e-02, 6.25735701e-02, 6.18135756e-02, 6.10597598e-02, 6.03120976e-02, 5.95705638e-02, 5.88351331e-02, 5.81057803e-02, 5.73824802e-02, 5.66652075e-02, 5.59539371e-02, 5.52486438e-02, 5.45493022e-02, 5.38558872e-02, 5.31683736e-02, 5.24867361e-02, 5.18109496e-02, 5.11409888e-02, 5.04768285e-02, 4.98184434e-02, 4.91658084e-02, 4.85188982e-02, 4.78776876e-02, 4.72421515e-02, 4.66122645e-02, 4.59880014e-02, 4.53693371e-02, 4.47562463e-02, 4.41487038e-02, 4.35466844e-02, 4.29501628e-02, 4.23591138e-02, 4.17735123e-02, 4.11933330e-02, 4.06185507e-02, 4.00491401e-02, 3.94850760e-02, 3.89263333e-02, 3.83728867e-02, 3.78247109e-02, 3.72817808e-02, 3.67440712e-02, 3.62115568e-02, 3.56842123e-02, 3.51620127e-02, 3.46449326e-02, 3.41329469e-02, 3.36260303e-02, 3.31241576e-02, 3.26273035e-02, 3.21354430e-02, 3.16485507e-02, 3.11666014e-02, 3.06895699e-02, 3.02174310e-02, 2.97501595e-02, 2.92877301e-02, 2.88301177e-02, 2.83772970e-02, 2.79292427e-02, 2.74859298e-02, 2.70473328e-02, 2.66134267e-02, 2.61841863e-02, 2.57595862e-02, 2.53396013e-02, 2.49242063e-02, 2.45133761e-02, 2.41070854e-02, 2.37053089e-02, 2.33080216e-02, 2.29151981e-02, 2.25268132e-02, 2.21428418e-02, 2.17632586e-02, 2.13880383e-02, 2.10171558e-02, 2.06505858e-02, 2.02883032e-02, 1.99302826e-02, 1.95764990e-02, 1.92269270e-02, 1.88815414e-02, 1.85403171e-02, 1.82032287e-02, 1.78702512e-02, 1.75413592e-02, 1.72165275e-02, 1.68957310e-02, 1.65789443e-02, 1.62661424e-02, 1.59572999e-02, 1.56523917e-02, 1.53513925e-02, 1.50542771e-02, 1.47610203e-02, 1.44715968e-02, 1.41859815e-02, 1.39041492e-02, 1.36260745e-02, 1.33517323e-02, 1.30810974e-02, 1.28141446e-02, 1.25508485e-02, 1.22911841e-02, 1.20351261e-02, 1.17826493e-02, 1.15337284e-02, 1.12883382e-02, 1.10464536e-02, 1.08080492e-02, 1.05731000e-02, 1.03415805e-02, 1.01134657e-02, 9.88873037e-03, 9.66734920e-03, 9.44929700e-03, 9.23454856e-03, 9.02307866e-03, 8.81486208e-03, 8.60987360e-03, 8.40808799e-03, 8.20948005e-03, 8.01402454e-03, 7.82169626e-03, 7.63246998e-03, 7.44632048e-03, 7.26322254e-03, 7.08315094e-03, 6.90608047e-03, 6.73198590e-03, 6.56084202e-03, 6.39262360e-03, 6.22730542e-03, 6.06486228e-03, 5.90526893e-03, 5.74850018e-03, 5.59453079e-03, 5.44333554e-03, 5.29488923e-03, 5.14916663e-03, 5.00614251e-03, 4.86579166e-03, 4.72808886e-03, 4.59300890e-03, 4.46052654e-03, 4.33061658e-03, 4.20325378e-03, 4.07841294e-03, 3.95606884e-03, 3.83619624e-03, 3.71876994e-03, 3.60376471e-03, 3.49115534e-03, 3.38091660e-03, 3.27302328e-03, 3.16745016e-03, 3.06417201e-03, 2.96316362e-03, 2.86439976e-03, 2.76785523e-03, 2.67350479e-03, 2.58132323e-03, 2.49128533e-03, 2.40336587e-03, 2.31753963e-03, 2.23378139e-03, 2.15206594e-03, 2.07236804e-03, 1.99466249e-03, 1.91892406e-03, 1.84512753e-03, 1.77324769e-03, 1.70325931e-03, 1.63513718e-03, 1.56885607e-03, 1.50439077e-03, 1.44171605e-03, 1.38080670e-03, 1.32163749e-03, 1.26418322e-03, 1.20841865e-03, 1.15431857e-03, 1.10185776e-03, 1.05101100e-03, 1.00175307e-03, 9.54058747e-04, 9.07902817e-04, 8.63260059e-04, 8.20105252e-04, 7.78413178e-04, 7.38158617e-04, 6.99316348e-04, 6.61861154e-04, 6.25767814e-04, 5.91011108e-04, 5.57565818e-04, 5.25406723e-04, 4.94508604e-04, 4.64846242e-04, 4.36394418e-04, 4.09127910e-04, 3.83021501e-04, 3.58049970e-04, 3.34188099e-04, 3.11410666e-04, 2.89692454e-04, 2.69008242e-04, 2.49332811e-04, 2.30640942e-04, 2.12907414e-04, 1.96107009e-04, 1.80214506e-04, 1.65204687e-04, 1.51052331e-04, 1.37732220e-04, 1.25219133e-04, 1.13487852e-04, 1.02513157e-04, 9.22698271e-05, 8.27326442e-05, 7.38763885e-05, 6.56758404e-05, 5.81057803e-05, 5.11409888e-05, 4.47562463e-05, 3.89263333e-05, 3.36260303e-05, 2.88301177e-05, 2.45133761e-05, 2.06505858e-05, 1.72165275e-05, 1.41859815e-05, 1.15337284e-05, 9.23454856e-06, 7.26322254e-06, 5.59453079e-06, 4.20325378e-06, 3.06417201e-06, 2.15206594e-06, 1.44171605e-06, 9.07902817e-07, 5.25406723e-07, 2.69008242e-07, 1.13487852e-07, 3.36260303e-08, 4.20325378e-09, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00};
with(Groebner): F:={2*x1 + 5*x2 + x3,2*x1 + x2 + x3,9*x1 + 6*x2 + x3,x1^2 + x2^2 + x3^2 - 1}: m_ord:=tdeg(x1,x2,x3): G:=Basis(F,m_ord): NormalSet(G,m_ord)[1]
\section*{Question \#4B} I knew something was wrong here, this is why I started writing down the domain and ranges of the functions (in problems A to C). In my case, I defaulted to thinking that $\left(f^{-1} \circ f \right)\left(x\right) = x$, which is only true for $0 \leq x \leq \pi$ (which is a really dumb mistake in hindsight). \begin{figure}[!h] \definecolor{linecolor}{HTML}{0074C8} \providecommand{\ival}[2]{\lbrack #1,#2 \rbrack} \begin{tikzpicture}[scale=1.2,every node/.style={font=\small}] \begin{scope}[dashed,line width=1pt,x=6cm/360] \draw[black!60,solid,line width=0.3pt,-latex] (-110,0) -- (290,0) node[right] {$x$}; \draw[black!60,solid,line width=0.3pt,-latex] (0,-1.5) -- (0,1.5) node[above] {$y$}; \pgfplothandlerlineto \pgfplotfunction{\x}{-90,-85,...,270}{\pgfpointxy{\x}{cos(\x)}} \pgfusepath{stroke} \node[black,below right] at (0,0) {$0$}; \foreach \pos in {-90,90,180,270} \draw[black!60,line width=0.3pt,solid,shift={(\pos,0)}] (0pt,3pt) -- (0pt,-3pt); \foreach \pos in {-1,1} \draw[black!60,line width=0.3pt,solid,shift={(0,\pos)}] (3pt,0pt) -- (-3pt,0pt) node[black,left] {$\pos$}; \node[black,below] at (90,-0.1) {$\tfrac{\tau}{4}$}; \node[black,below] at (180,-0.1) {$\tfrac{\tau}{2}$}; \node[black,below] at (-90,-0.1) {$-\tfrac{\tau}{4}$}; \node[black,below] at (270,-0.1) {$\tfrac{3\tau}{4}$}; \node[black,above] at (90,1) {$y=\cos\;x$}; \end{scope} \begin{scope}[color=linecolor,line width=1.5pt,x=6cm/360] \pgfplothandlerlineto \pgfplotfunction{\x}{0,5,...,180}{\pgfpointxy{\x}{cos(\x)}} \pgfusepath{stroke} \fill (0,1) circle (2pt); \fill (180,-1) circle (2pt); \end{scope} \end{tikzpicture}\vspace{-6mm} \end{figure} \newpage Anyway the following is what I should have written: \newcommand{\Comp}[3]{\left({#1} \circ {#2} \right)\left( {#3} \right)} \newcommand{\Cos}[1]{\cos \left( {#1} \right)} \newcommand{\Sin}[1]{\sin \left( {#1} \right)} \newcommand{\Arccos}[1]{\arccos \left( {#1} \right)} Given $\Comp{\arccos}{\cos}{\frac{7}{4}\pi}$: \begin{equation} \begin{split} \Cos{\frac{7}{4}\pi} &= \Cos{\frac{14}{8}\pi} \\ &= \Cos{\pi + \frac{6}{8}\pi} \\ &= \Cos{\pi}\Cos{\frac{6}{8}\pi} - \Sin{\pi}\Sin{\frac{6}{8}\pi} \\ &= (-1)\left(-\frac{\sqrt{2}}{2} \right) - 0\Sin{\frac{6}{8}\pi} \\ &= \frac{\sqrt{2}}{2} \\ &= \alpha \end{split} \end{equation} Therefore, we now consider $\Arccos{\alpha}$, which is a special angle and therefore easy to identify (in my case I memorized the special angles in terms of fractions of a circle): \begin{equation} \begin{split} \Arccos{\alpha} &= \Arccos{\frac{\sqrt{2}}{2}} \\ &= \frac{1}{8}\tau \\ &= \frac{1}{4}\pi \end{split} \end{equation} Therefore: \begin{equation} \begin{split} \Comp{\arccos}{\cos}{\frac{7}{4}\pi} &= \frac{1}{4}\pi \end{split} \end{equation} \section*{Regarding better studying habits} Overall, I should really do \textbf{all} of the practice problems (at least some from each topic). Although this applies more to my calculus class (e.g. I was pretty confident about a topic, and therefore I didn't bother to review the associated practice material, which has happened on two occasions, and in both, there was something weird that tripped me up.) \section*{Miscellaneous} Regarding the remark that fractions are our friends, this was because it was evaluated VIA a calculator, which I punched in as fast as I could. What happened is that in a few places, I happen to use the same variable names as in the given formulas, and therefore got a few symbols mixed up (i.e. in one place, $\alpha$ should have been $\beta$ and vice-versa.). After I realized my mistake, I recomputed the answers as fast as I could.
theory Instance_Graph_Combination imports Type_Graph_Combination Instance_Graph begin section "Combining instance graphs" definition ig_combine_ident :: "'id set \<Rightarrow> ('id \<Rightarrow> ('nt, 'lt) NodeDef) \<Rightarrow> 'id set \<Rightarrow> ('id \<Rightarrow> ('nt, 'lt) NodeDef) \<Rightarrow> 'id \<Rightarrow> ('nt, 'lt) NodeDef" where "ig_combine_ident Id1 ident1 Id2 ident2 i = ( if i \<in> Id1 \<and> i \<in> Id2 \<and> ident1 i = ident2 i then ident1 i else if i \<in> Id1 \<and> i \<in> Id2 \<and> ident1 i \<noteq> ident2 i then invalid else if i \<in> Id1 \<and> i \<notin> Id2 then ident1 i else if i \<notin> Id1 \<and> i \<in> Id2 then ident2 i else undefined )" definition ig_combine :: "('nt, 'lt, 'id) instance_graph \<Rightarrow> ('nt, 'lt, 'id) instance_graph \<Rightarrow> ('nt, 'lt, 'id) instance_graph" where "ig_combine IG1 IG2 \<equiv> \<lparr> TG = tg_combine (TG IG1) (TG IG2), Id = Id IG1 \<union> Id IG2, N = N IG1 \<union> N IG2, E = E IG1 \<union> E IG2, ident = ig_combine_ident (Id IG1) (ident IG1) (Id IG2) (ident IG2) \<rparr>" lemma ig_combine_identity: assumes structure_mult_domain: "\<And>e. e \<notin> ET (TG IG) \<Longrightarrow> mult (TG IG) e = undefined" assumes validity_inh_trans: "trans (inh (TG IG))" assumes structure_ident_domain: "\<And>i. i \<notin> Id IG \<Longrightarrow> ident IG i = undefined" shows "ig_combine IG ig_empty = truncate IG" unfolding truncate_def ig_combine_def proof show "tg_combine (TG IG) (TG ig_empty) = TG IG \<and> Id IG \<union> Id ig_empty = Id IG \<and> N IG \<union> N ig_empty = N IG \<and> E IG \<union> E ig_empty = E IG \<and> ig_combine_ident (Id IG) (ident IG) (Id ig_empty) (ident ig_empty) = ident IG \<and> () = ()" proof (intro conjI) have "tg_combine tg_empty (TG IG) = type_graph.truncate (TG IG)" by (intro tg_combine_identity) (simp_all add: assms) then show "tg_combine (TG IG) (TG ig_empty) = TG IG" unfolding type_graph.truncate_def ig_empty_def using tg_combine_commute by simp next show "ig_combine_ident (Id IG) (ident IG) (Id ig_empty) (ident ig_empty) = ident IG" proof fix i show "ig_combine_ident (Id IG) (ident IG) (Id ig_empty) (ident ig_empty) i = ident IG i" unfolding ig_combine_ident_def ig_empty_def by (simp add: structure_ident_domain) qed qed (simp_all) qed lemma ig_combine_identity_alt[simp]: assumes instance_graph_valid: "instance_graph IG" shows "ig_combine IG ig_empty = truncate IG" proof (intro ig_combine_identity) show "\<And>e. e \<notin> ET (TG IG) \<Longrightarrow> mult (TG IG) e = undefined" using instance_graph_valid instance_graph.validity_type_graph type_graph.structure_mult_domain by blast next show "trans (inh (TG IG))" using instance_graph_valid instance_graph.validity_type_graph type_graph.validity_inh_trans by blast next show "\<And>i. i \<notin> Id IG \<Longrightarrow> ident IG i = undefined" using instance_graph_valid instance_graph.structure_ident_domain by metis qed lemma ig_combine_ident_commute: "ig_combine_ident (Id IG1) (ident IG1) (Id IG2) (ident IG2) = ig_combine_ident (Id IG2) (ident IG2) (Id IG1) (ident IG1)" unfolding ig_combine_ident_def by fastforce lemma ig_combine_commute[simp]: "ig_combine IG1 IG2 = ig_combine IG2 IG1" unfolding ig_combine_def proof show "tg_combine (TG IG1) (TG IG2) = tg_combine (TG IG2) (TG IG1) \<and> Id IG1 \<union> Id IG2 = Id IG2 \<union> Id IG1 \<and> N IG1 \<union> N IG2 = N IG2 \<union> N IG1 \<and> E IG1 \<union> E IG2 = E IG2 \<union> E IG1 \<and> ig_combine_ident (Id IG1) (ident IG1) (Id IG2) (ident IG2) = ig_combine_ident (Id IG2) (ident IG2) (Id IG1) (ident IG1) \<and> () = ()" proof (intro conjI) show "ig_combine_ident (Id IG1) (ident IG1) (Id IG2) (ident IG2) = ig_combine_ident (Id IG2) (ident IG2) (Id IG1) (ident IG1)" by (fact ig_combine_ident_commute) qed (simp_all add: Un_commute) qed lemma ig_combine_idemp: assumes structure_mult_domain: "\<And>e. e \<notin> ET (TG IG) \<Longrightarrow> mult (TG IG) e = undefined" assumes validity_inh_trans: "trans (inh (TG IG))" assumes structure_ident_domain: "\<And>i. i \<notin> Id IG \<Longrightarrow> ident IG i = undefined" shows "ig_combine IG IG = truncate IG" unfolding truncate_def ig_combine_def proof show "tg_combine (TG IG) (TG IG) = TG IG \<and> Id IG \<union> Id IG = Id IG \<and> N IG \<union> N IG = N IG \<and> E IG \<union> E IG = E IG \<and> ig_combine_ident (Id IG) (ident IG) (Id IG) (ident IG) = ident IG \<and> () = ()" proof (intro conjI) have "tg_combine (TG IG) (TG IG) = type_graph.truncate (TG IG)" using tg_combine_idemp structure_mult_domain validity_inh_trans by blast then show "tg_combine (TG IG) (TG IG) = TG IG" unfolding type_graph.truncate_def by simp next show "ig_combine_ident (Id IG) (ident IG) (Id IG) (ident IG) = ident IG" proof fix i show "ig_combine_ident (Id IG) (ident IG) (Id IG) (ident IG) i = ident IG i" unfolding ig_combine_ident_def by (simp add: structure_ident_domain) qed qed (simp_all) qed lemma ig_combine_idemp_alt[simp]: assumes instance_graph_valid: "instance_graph IG" shows "ig_combine IG IG = truncate IG" proof (intro ig_combine_idemp) show "\<And>e. e \<notin> ET (TG IG) \<Longrightarrow> mult (TG IG) e = undefined" using instance_graph_valid instance_graph.validity_type_graph type_graph.structure_mult_domain by blast next show "trans (inh (TG IG))" using instance_graph_valid instance_graph.validity_type_graph type_graph.validity_inh_trans by blast next show "\<And>i. i \<notin> Id IG \<Longrightarrow> ident IG i = undefined" using instance_graph_valid instance_graph.structure_ident_domain by metis qed lemma ig_combine_ident_assoc: shows "ig_combine_ident (Id (ig_combine IG1 IG2)) (ident (ig_combine IG1 IG2)) (Id IG3) (ident IG3) = ig_combine_ident (Id IG1) (ident IG1) (Id (ig_combine IG2 IG3)) (ident (ig_combine IG2 IG3))" proof fix i have id_ig1_cases: "i \<in> Id IG1 \<or> i \<notin> Id IG1" by simp have id_ig2_cases: "i \<in> Id IG2 \<or> i \<notin> Id IG2" by simp have id_ig3_cases: "i \<in> Id IG3 \<or> i \<notin> Id IG3" by simp have ident_ig1_ig2_eq_cases: "ident IG1 i = ident IG2 i \<or> ident IG1 i \<noteq> ident IG2 i" by simp have ident_ig1_ig3_eq_cases: "ident IG1 i = ident IG3 i \<or> ident IG1 i \<noteq> ident IG3 i" by simp have ident_ig2_ig3_eq_cases: "ident IG2 i = ident IG3 i \<or> ident IG2 i \<noteq> ident IG3 i" by simp show "ig_combine_ident (Id (ig_combine IG1 IG2)) (ident (ig_combine IG1 IG2)) (Id IG3) (ident IG3) i = ig_combine_ident (Id IG1) (ident IG1) (Id (ig_combine IG2 IG3)) (ident (ig_combine IG2 IG3)) i" using id_ig1_cases id_ig2_cases id_ig3_cases proof (elim disjE) assume ig1_in_set: "i \<in> Id IG1" assume ig2_in_set: "i \<in> Id IG2" then have ig12_in_set: "i \<in> Id (ig_combine IG1 IG2)" unfolding ig_combine_def by simp assume ig3_in_set: "i \<in> Id IG3" then have ig23_in_set: "i \<in> Id (ig_combine IG2 IG3)" unfolding ig_combine_def by simp show ?thesis using ident_ig1_ig2_eq_cases ident_ig2_ig3_eq_cases ident_ig1_ig3_eq_cases proof (elim disjE) assume ig1_ig2_eq: "ident IG1 i = ident IG2 i" then have ig12_def: "ident (ig_combine IG1 IG2) i = ident IG1 i" unfolding ig_combine_def ig_combine_ident_def using ig1_in_set ig2_in_set by simp assume ig2_ig3_eq: "ident IG2 i = ident IG3 i" then have ig23_def: "ident (ig_combine IG2 IG3) i = ident IG2 i" unfolding ig_combine_def ig_combine_ident_def using ig2_in_set ig3_in_set by simp assume ig1_ig3_eq: "ident IG1 i = ident IG3 i" then have "ident (ig_combine IG1 IG2) i = ident IG3 i" using ig12_def by simp then have ig12_ig3_def: "ig_combine_ident (Id (ig_combine IG1 IG2)) (ident (ig_combine IG1 IG2)) (Id IG3) (ident IG3) i = ident IG1 i" unfolding ig_combine_ident_def using ig12_in_set ig3_in_set ig1_ig3_eq by simp have "ident IG1 i = ident (ig_combine IG2 IG3) i" using ig1_ig2_eq ig23_def by simp then have "ig_combine_ident (Id IG1) (ident IG1) (Id (ig_combine IG2 IG3)) (ident (ig_combine IG2 IG3)) i = ident IG1 i" unfolding ig_combine_ident_def using ig1_in_set ig23_in_set by simp then show ?thesis using ig12_ig3_def by simp next assume ig1_ig2_eq: "ident IG1 i = ident IG2 i" then have ig12_def: "ident (ig_combine IG1 IG2) i = ident IG1 i" unfolding ig_combine_def ig_combine_ident_def using ig1_in_set ig2_in_set by simp assume ig2_ig3_not_eq: "ident IG2 i \<noteq> ident IG3 i" then have ig23_def: "ident (ig_combine IG2 IG3) i = invalid" unfolding ig_combine_def ig_combine_ident_def using ig2_in_set ig3_in_set by simp assume ig1_ig3_not_eq: "ident IG1 i \<noteq> ident IG3 i" then have "ident (ig_combine IG1 IG2) i \<noteq> ident IG3 i" using ig12_def by simp then have ig12_ig3_def: "ig_combine_ident (Id (ig_combine IG1 IG2)) (ident (ig_combine IG1 IG2)) (Id IG3) (ident IG3) i = invalid" unfolding ig_combine_ident_def using ig12_in_set ig3_in_set by simp have "ig_combine_ident (Id IG1) (ident IG1) (Id (ig_combine IG2 IG3)) (ident (ig_combine IG2 IG3)) i = invalid" unfolding ig_combine_ident_def using ig1_in_set ig23_in_set ig23_def by simp then show ?thesis using ig12_ig3_def by simp next assume ig1_ig2_not_eq: "ident IG1 i \<noteq> ident IG2 i" then have ig12_def: "ident (ig_combine IG1 IG2) i = invalid" unfolding ig_combine_def ig_combine_ident_def using ig1_in_set ig2_in_set by simp assume ig2_ig3_eq: "ident IG2 i = ident IG3 i" then have ig23_def: "ident (ig_combine IG2 IG3) i = ident IG2 i" unfolding ig_combine_def ig_combine_ident_def using ig2_in_set ig3_in_set by simp assume ig1_ig3_not_eq: "ident IG1 i \<noteq> ident IG3 i" have "ident IG1 i \<noteq> ident (ig_combine IG2 IG3) i" using ig23_def ig1_ig2_not_eq by simp then have ig1_ig23_def: "ig_combine_ident (Id IG1) (ident IG1) (Id (ig_combine IG2 IG3)) (ident (ig_combine IG2 IG3)) i = invalid" unfolding ig_combine_ident_def using ig1_in_set ig23_in_set by simp have "ig_combine_ident (Id (ig_combine IG1 IG2)) (ident (ig_combine IG1 IG2)) (Id IG3) (ident IG3) i = invalid" unfolding ig_combine_ident_def using ig12_in_set ig3_in_set ig12_def by simp then show ?thesis using ig1_ig23_def by simp next assume ig1_ig2_not_eq: "ident IG1 i \<noteq> ident IG2 i" then have ig12_def: "ident (ig_combine IG1 IG2) i = invalid" unfolding ig_combine_def ig_combine_ident_def using ig1_in_set ig2_in_set by simp assume ig2_ig3_not_eq: "ident IG2 i \<noteq> ident IG3 i" then have ig23_def: "ident (ig_combine IG2 IG3) i = invalid" unfolding ig_combine_def ig_combine_ident_def using ig2_in_set ig3_in_set by simp assume ig1_ig3_eq: "ident IG1 i = ident IG3 i" have ig1_ig23_def: "ig_combine_ident (Id IG1) (ident IG1) (Id (ig_combine IG2 IG3)) (ident (ig_combine IG2 IG3)) i = invalid" unfolding ig_combine_ident_def using ig1_in_set ig23_in_set ig23_def by simp have "ig_combine_ident (Id (ig_combine IG1 IG2)) (ident (ig_combine IG1 IG2)) (Id IG3) (ident IG3) i = invalid" unfolding ig_combine_ident_def using ig12_in_set ig3_in_set ig12_def by simp then show ?thesis using ig1_ig23_def by simp next assume ig1_ig2_not_eq: "ident IG1 i \<noteq> ident IG2 i" then have ig12_def: "ident (ig_combine IG1 IG2) i = invalid" unfolding ig_combine_def ig_combine_ident_def using ig1_in_set ig2_in_set by simp assume ig2_ig3_not_eq: "ident IG2 i \<noteq> ident IG3 i" then have ig23_def: "ident (ig_combine IG2 IG3) i = invalid" unfolding ig_combine_def ig_combine_ident_def using ig2_in_set ig3_in_set by simp assume ig1_ig3_not_eq: "ident IG1 i \<noteq> ident IG3 i" have ig1_ig23_def: "ig_combine_ident (Id IG1) (ident IG1) (Id (ig_combine IG2 IG3)) (ident (ig_combine IG2 IG3)) i = invalid" unfolding ig_combine_ident_def using ig1_in_set ig23_in_set ig23_def by simp have "ig_combine_ident (Id (ig_combine IG1 IG2)) (ident (ig_combine IG1 IG2)) (Id IG3) (ident IG3) i = invalid" unfolding ig_combine_ident_def using ig12_in_set ig3_in_set ig12_def by simp then show ?thesis using ig1_ig23_def by simp qed (simp_all) next assume ig1_in_set: "i \<in> Id IG1" then have ig12_in_set: "i \<in> Id (ig_combine IG1 IG2)" unfolding ig_combine_def by simp assume ig2_in_set: "i \<in> Id IG2" then have ig23_in_set: "i \<in> Id (ig_combine IG2 IG3)" unfolding ig_combine_def by simp assume ig3_not_in_set: "i \<notin> Id IG3" show ?thesis using ident_ig1_ig2_eq_cases proof (elim disjE) assume ig1_ig2_eq: "ident IG1 i = ident IG2 i" then have ig12_def: "ident (ig_combine IG1 IG2) i = ident IG1 i" unfolding ig_combine_def ig_combine_ident_def using ig1_in_set ig2_in_set by simp then have ig12_ig3_def: "ig_combine_ident (Id (ig_combine IG1 IG2)) (ident (ig_combine IG1 IG2)) (Id IG3) (ident IG3) i = ident IG1 i" unfolding ig_combine_ident_def using ig12_in_set ig3_not_in_set by simp have ig23_def: "ident (ig_combine IG2 IG3) i = ident IG2 i" unfolding ig_combine_def ig_combine_ident_def using ig2_in_set ig3_not_in_set by simp then have "ig_combine_ident (Id IG1) (ident IG1) (Id (ig_combine IG2 IG3)) (ident (ig_combine IG2 IG3)) i = ident IG1 i" unfolding ig_combine_ident_def using ig1_in_set ig23_in_set ig1_ig2_eq by simp then show ?thesis using ig12_ig3_def by simp next assume ig1_ig2_not_eq: "ident IG1 i \<noteq> ident IG2 i" then have ig12_def: "ident (ig_combine IG1 IG2) i = invalid" unfolding ig_combine_def ig_combine_ident_def using ig1_in_set ig2_in_set by simp then have ig12_ig3_def: "ig_combine_ident (Id (ig_combine IG1 IG2)) (ident (ig_combine IG1 IG2)) (Id IG3) (ident IG3) i = invalid" unfolding ig_combine_ident_def using ig12_in_set ig3_not_in_set by simp have ig23_def: "ident (ig_combine IG2 IG3) i = ident IG2 i" unfolding ig_combine_def ig_combine_ident_def using ig2_in_set ig3_not_in_set by simp then have "ig_combine_ident (Id IG1) (ident IG1) (Id (ig_combine IG2 IG3)) (ident (ig_combine IG2 IG3)) i = invalid" unfolding ig_combine_ident_def using ig1_in_set ig23_in_set ig1_ig2_not_eq by simp then show ?thesis using ig12_ig3_def by simp qed next assume ig1_in_set: "i \<in> Id IG1" then have ig12_in_set: "i \<in> Id (ig_combine IG1 IG2)" unfolding ig_combine_def by simp assume ig2_not_in_set: "i \<notin> Id IG2" assume ig3_in_set: "i \<in> Id IG3" then have ig23_in_set: "i \<in> Id (ig_combine IG2 IG3)" unfolding ig_combine_def by simp show ?thesis using ident_ig1_ig3_eq_cases proof (elim disjE) assume ig1_ig3_eq: "ident IG1 i = ident IG3 i" then have ig12_def: "ident (ig_combine IG1 IG2) i = ident IG1 i" unfolding ig_combine_def ig_combine_ident_def using ig1_in_set ig2_not_in_set by simp then have ig12_ig3_def: "ig_combine_ident (Id (ig_combine IG1 IG2)) (ident (ig_combine IG1 IG2)) (Id IG3) (ident IG3) i = ident IG1 i" unfolding ig_combine_ident_def using ig12_in_set ig3_in_set ig1_ig3_eq by simp have ig23_def: "ident (ig_combine IG2 IG3) i = ident IG3 i" unfolding ig_combine_def ig_combine_ident_def using ig2_not_in_set ig3_in_set by simp then have "ig_combine_ident (Id IG1) (ident IG1) (Id (ig_combine IG2 IG3)) (ident (ig_combine IG2 IG3)) i = ident IG1 i" unfolding ig_combine_ident_def using ig1_in_set ig23_in_set ig1_ig3_eq by simp then show ?thesis using ig12_ig3_def by simp next assume ig1_ig3_not_eq: "ident IG1 i \<noteq> ident IG3 i" then have ig12_def: "ident (ig_combine IG1 IG2) i = ident IG1 i" unfolding ig_combine_def ig_combine_ident_def using ig1_in_set ig2_not_in_set by simp then have ig12_ig3_def: "ig_combine_ident (Id (ig_combine IG1 IG2)) (ident (ig_combine IG1 IG2)) (Id IG3) (ident IG3) i = invalid" unfolding ig_combine_ident_def using ig12_in_set ig3_in_set ig1_ig3_not_eq by simp have ig23_def: "ident (ig_combine IG2 IG3) i = ident IG3 i" unfolding ig_combine_def ig_combine_ident_def using ig2_not_in_set ig3_in_set by simp then have "ig_combine_ident (Id IG1) (ident IG1) (Id (ig_combine IG2 IG3)) (ident (ig_combine IG2 IG3)) i = invalid" unfolding ig_combine_ident_def using ig1_in_set ig23_in_set ig1_ig3_not_eq by simp then show ?thesis using ig12_ig3_def by simp qed next assume ig1_in_set: "i \<in> Id IG1" then have ig12_in_set: "i \<in> Id (ig_combine IG1 IG2)" unfolding ig_combine_def by simp assume ig2_not_in_set: "i \<notin> Id IG2" assume ig3_not_in_set: "i \<notin> Id IG3" have ig23_not_in_set: "i \<notin> Id (ig_combine IG2 IG3)" unfolding ig_combine_def using ig2_not_in_set ig3_not_in_set by simp then have ig1_ig23_def: "ig_combine_ident (Id IG1) (ident IG1) (Id (ig_combine IG2 IG3)) (ident (ig_combine IG2 IG3)) i = ident IG1 i" unfolding ig_combine_ident_def using ig1_in_set ig23_not_in_set by simp have ig12_def: "ident (ig_combine IG1 IG2) i = ident IG1 i" unfolding ig_combine_def ig_combine_ident_def using ig1_in_set ig2_not_in_set by simp then have "ig_combine_ident (Id (ig_combine IG1 IG2)) (ident (ig_combine IG1 IG2)) (Id IG3) (ident IG3) i = ident IG1 i" unfolding ig_combine_ident_def using ig12_in_set ig3_not_in_set by simp then show ?thesis using ig1_ig23_def by simp next assume ig1_not_in_set: "i \<notin> Id IG1" assume ig2_in_set: "i \<in> Id IG2" then have ig12_in_set: "i \<in> Id (ig_combine IG1 IG2)" unfolding ig_combine_def by simp assume ig3_in_set: "i \<in> Id IG3" then have ig23_in_set: "i \<in> Id (ig_combine IG2 IG3)" unfolding ig_combine_def by simp show ?thesis using ident_ig2_ig3_eq_cases proof (elim disjE) assume ig2_ig3_eq: "ident IG2 i = ident IG3 i" have ig12_def: "ident (ig_combine IG1 IG2) i = ident IG2 i" unfolding ig_combine_def ig_combine_ident_def using ig1_not_in_set ig2_in_set by simp then have ig12_ig3_def: "ig_combine_ident (Id (ig_combine IG1 IG2)) (ident (ig_combine IG1 IG2)) (Id IG3) (ident IG3) i = ident IG2 i" unfolding ig_combine_ident_def using ig12_in_set ig3_in_set ig2_ig3_eq by simp have ig23_def: "ident (ig_combine IG2 IG3) i = ident IG2 i" unfolding ig_combine_def ig_combine_ident_def using ig2_in_set ig3_in_set ig2_ig3_eq by simp then have "ig_combine_ident (Id IG1) (ident IG1) (Id (ig_combine IG2 IG3)) (ident (ig_combine IG2 IG3)) i = ident IG2 i" unfolding ig_combine_ident_def using ig1_not_in_set ig23_in_set by simp then show ?thesis using ig12_ig3_def by simp next assume ig2_ig3_not_eq: "ident IG2 i \<noteq> ident IG3 i" have ig12_def: "ident (ig_combine IG1 IG2) i = ident IG2 i" unfolding ig_combine_def ig_combine_ident_def using ig1_not_in_set ig2_in_set by simp then have ig12_ig3_def: "ig_combine_ident (Id (ig_combine IG1 IG2)) (ident (ig_combine IG1 IG2)) (Id IG3) (ident IG3) i = invalid" unfolding ig_combine_ident_def using ig12_in_set ig3_in_set ig2_ig3_not_eq by simp have ig23_def: "ident (ig_combine IG2 IG3) i = invalid" unfolding ig_combine_def ig_combine_ident_def using ig2_in_set ig3_in_set ig2_ig3_not_eq by simp then have "ig_combine_ident (Id IG1) (ident IG1) (Id (ig_combine IG2 IG3)) (ident (ig_combine IG2 IG3)) i = invalid" unfolding ig_combine_ident_def using ig1_not_in_set ig23_in_set by simp then show ?thesis using ig12_ig3_def by simp qed next assume ig1_not_in_set: "i \<notin> Id IG1" assume ig2_in_set: "i \<in> Id IG2" then have ig12_in_set: "i \<in> Id (ig_combine IG1 IG2)" unfolding ig_combine_def by simp have ig23_in_set: "i \<in> Id (ig_combine IG2 IG3)" unfolding ig_combine_def using ig2_in_set by simp assume ig3_not_in_set: "i \<notin> Id IG3" have ig12_def: "ident (ig_combine IG1 IG2) i = ident IG2 i" unfolding ig_combine_def ig_combine_ident_def using ig1_not_in_set ig2_in_set by simp then have ig12_ig3_def: "ig_combine_ident (Id (ig_combine IG1 IG2)) (ident (ig_combine IG1 IG2)) (Id IG3) (ident IG3) i = ident IG2 i" unfolding ig_combine_ident_def using ig12_in_set ig3_not_in_set by simp have ig23_def: "ident (ig_combine IG2 IG3) i = ident IG2 i" unfolding ig_combine_def ig_combine_ident_def using ig2_in_set ig3_not_in_set by simp then have "ig_combine_ident (Id IG1) (ident IG1) (Id (ig_combine IG2 IG3)) (ident (ig_combine IG2 IG3)) i = ident IG2 i" unfolding ig_combine_ident_def using ig1_not_in_set ig23_in_set by simp then show ?thesis using ig12_ig3_def by simp next assume ig1_not_in_set: "i \<notin> Id IG1" assume ig2_not_in_set: "i \<notin> Id IG2" assume ig3_in_set: "i \<in> Id IG3" then have ig23_in_set: "i \<in> Id (ig_combine IG2 IG3)" unfolding ig_combine_def by simp have ig12_not_in_set: "i \<notin> Id (ig_combine IG1 IG2)" unfolding ig_combine_def using ig1_not_in_set ig2_not_in_set by simp then have ig12_ig3_def: "ig_combine_ident (Id (ig_combine IG1 IG2)) (ident (ig_combine IG1 IG2)) (Id IG3) (ident IG3) i = ident IG3 i" unfolding ig_combine_ident_def using ig12_not_in_set ig3_in_set by simp have ig12_def: "ident (ig_combine IG2 IG3) i = ident IG3 i" unfolding ig_combine_def ig_combine_ident_def using ig2_not_in_set ig3_in_set by simp then have "ig_combine_ident (Id IG1) (ident IG1) (Id (ig_combine IG2 IG3)) (ident (ig_combine IG2 IG3)) i = ident IG3 i" unfolding ig_combine_ident_def using ig1_not_in_set ig23_in_set by simp then show ?thesis using ig12_ig3_def by simp next assume ig1_not_in_set: "i \<notin> Id IG1" assume ig2_not_in_set: "i \<notin> Id IG2" assume ig3_not_in_set: "i \<notin> Id IG3" have ig12_not_in_set: "i \<notin> Id (ig_combine IG1 IG2)" unfolding ig_combine_def using ig1_not_in_set ig2_not_in_set by simp then have ig12_ig3_def: "ig_combine_ident (Id (ig_combine IG1 IG2)) (ident (ig_combine IG1 IG2)) (Id IG3) (ident IG3) i = undefined" unfolding ig_combine_ident_def using ig3_not_in_set by simp have ig23_not_in_set: "i \<notin> Id (ig_combine IG2 IG3)" unfolding ig_combine_def using ig2_not_in_set ig3_not_in_set by simp then have "ig_combine_ident (Id IG1) (ident IG1) (Id (ig_combine IG2 IG3)) (ident (ig_combine IG2 IG3)) i = undefined" unfolding ig_combine_ident_def using ig1_not_in_set by simp then show ?thesis using ig12_ig3_def by simp qed qed lemma ig_combine_assoc: "ig_combine (ig_combine IG1 IG2) IG3 = ig_combine IG1 (ig_combine IG2 IG3)" proof- have "\<And>IG12 IG23. IG12 = ig_combine IG1 IG2 \<Longrightarrow> IG23 = ig_combine IG2 IG3 \<Longrightarrow> ig_combine IG12 IG3 = ig_combine IG1 IG23" proof- fix IG12 fix IG23 assume ig12_def: "IG12 = ig_combine IG1 IG2" assume ig23_def: "IG23 = ig_combine IG2 IG3" show "ig_combine IG12 IG3 = ig_combine IG1 IG23" unfolding ig_combine_def proof show "tg_combine (TG IG12) (TG IG3) = tg_combine (TG IG1) (TG IG23) \<and> Id IG12 \<union> Id IG3 = Id IG1 \<union> Id IG23 \<and> N IG12 \<union> N IG3 = N IG1 \<union> N IG23 \<and> E IG12 \<union> E IG3 = E IG1 \<union> E IG23 \<and> ig_combine_ident (Id IG12) (ident IG12) (Id IG3) (ident IG3) = ig_combine_ident (Id IG1) (ident IG1) (Id IG23) (ident IG23) \<and> () = ()" proof (intro conjI) show "tg_combine (TG IG12) (TG IG3) = tg_combine (TG IG1) (TG IG23)" using ig12_def ig23_def ig_combine_def instance_graph.select_convs(1) tg_combine_assoc by metis next show "ig_combine_ident (Id IG12) (ident IG12) (Id IG3) (ident IG3) = ig_combine_ident (Id IG1) (ident IG1) (Id IG23) (ident IG23)" using ig12_def ig23_def ig_combine_ident_assoc by blast qed (simp_all add: ig12_def ig23_def sup_assoc ig_combine_def) qed qed then show ?thesis by blast qed lemma ig_combine_correct[intro]: assumes first_instance_graph_valid: "instance_graph IG1" assumes second_instance_graph_valid: "instance_graph IG2" assumes validity_identity: "\<And>i. i \<in> Id IG1 \<Longrightarrow> i \<in> Id IG2 \<Longrightarrow> ident IG1 i = ident IG2 i" assumes validity_type_graph: "type_graph (tg_combine (TG IG1) (TG IG2))" assumes validity_outgoing_mult: "\<And>et n. et \<in> ET (TG IG1) \<union> ET (TG IG2) \<Longrightarrow> n \<in> N IG1 \<union> N IG2 \<Longrightarrow> (type\<^sub>n n, src et) \<in> (inh (TG IG1) \<union> inh (TG IG2))\<^sup>+ \<Longrightarrow> card {e \<in> E IG1 \<union> E IG2. src e = n \<and> type\<^sub>e e = et} in m_out (tg_combine_mult (ET (TG IG1)) (mult (TG IG1)) (ET (TG IG2)) (mult (TG IG2)) et)" assumes validity_ingoing_mult: "\<And>et n. et \<in> ET (TG IG1) \<union> ET (TG IG2) \<Longrightarrow> n \<in> N IG1 \<union> N IG2 \<Longrightarrow> (type\<^sub>n n, tgt et) \<in> (inh (TG IG1) \<union> inh (TG IG2))\<^sup>+ \<Longrightarrow> card {e \<in> E IG1 \<union> E IG2. tgt e = n \<and> type\<^sub>e e = et} in m_in (tg_combine_mult (ET (TG IG1)) (mult (TG IG1)) (ET (TG IG2)) (mult (TG IG2)) et)" assumes validity_contained_node: "\<And>n. n \<in> N IG1 \<union> N IG2 \<Longrightarrow> card { e \<in> E IG1 \<union> E IG2. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG1) \<union> contains (TG IG2) } \<le> 1" assumes validity_containment: "irrefl ((edge_to_tuple ` {e \<in> E IG1 \<union> E IG2. type\<^sub>e e \<in> contains (TG IG1) \<union> contains (TG IG2)})\<^sup>+)" shows "instance_graph (ig_combine IG1 IG2)" proof (intro instance_graph.intro) fix n assume "n \<in> N (ig_combine IG1 IG2)" then have "n \<in> N IG1 \<union> N IG2" unfolding ig_combine_def by simp then show "n \<in> Node" using first_instance_graph_valid second_instance_graph_valid instance_graph.structure_nodes_wellformed by auto next fix s l t assume "(s, l, t) \<in> E (ig_combine IG1 IG2)" then have "(s, l, t) \<in> E IG1 \<union> E IG2" unfolding ig_combine_def by simp then show "s \<in> N (ig_combine IG1 IG2) \<and> l \<in> ET (TG (ig_combine IG1 IG2)) \<and> t \<in> N (ig_combine IG1 IG2)" proof (intro conjI) assume "(s, l, t) \<in> E IG1 \<union> E IG2" then have "s \<in> N IG1 \<union> N IG2" using first_instance_graph_valid second_instance_graph_valid instance_graph.structure_edges_wellformed_src_node by blast then show "s \<in> N (ig_combine IG1 IG2)" unfolding ig_combine_def by simp next assume "(s, l, t) \<in> E IG1 \<union> E IG2" then have "l \<in> ET (TG IG1) \<union> ET (TG IG2)" using first_instance_graph_valid second_instance_graph_valid instance_graph.structure_edges_wellformed_edge_type by blast then show "l \<in> ET (TG (ig_combine IG1 IG2))" unfolding ig_combine_def tg_combine_def by simp next assume "(s, l, t) \<in> E IG1 \<union> E IG2" then have "t \<in> N IG1 \<union> N IG2" using first_instance_graph_valid second_instance_graph_valid instance_graph.structure_edges_wellformed_tgt_node by blast then show "t \<in> N (ig_combine IG1 IG2)" unfolding ig_combine_def by simp qed next fix i assume "i \<in> Id (ig_combine IG1 IG2)" then have "i \<in> Id IG1 \<union> Id IG2" unfolding ig_combine_def by simp then have "i \<in> Id IG1 \<inter> Id IG2 \<or> i \<in> Id IG1 - Id IG2 \<or> i \<in> Id IG2 - Id IG1" by blast then have "ig_combine_ident (Id IG1) (ident IG1) (Id IG2) (ident IG2) i \<in> N IG1 \<union> N IG2 \<and> type\<^sub>n (ig_combine_ident (Id IG1) (ident IG1) (Id IG2) (ident IG2) i) \<in> Lab\<^sub>t" proof (elim disjE) assume i_in_both: "i \<in> Id IG1 \<inter> Id IG2" then have "ig_combine_ident (Id IG1) (ident IG1) (Id IG2) (ident IG2) i = ident IG1 i" unfolding ig_combine_ident_def using validity_identity by simp then show ?thesis proof (intro conjI) assume "ig_combine_ident (Id IG1) (ident IG1) (Id IG2) (ident IG2) i = ident IG1 i" then have "ig_combine_ident (Id IG1) (ident IG1) (Id IG2) (ident IG2) i \<in> N IG1" using i_in_both first_instance_graph_valid instance_graph.structure_ident_wellformed_node by fastforce then show "ig_combine_ident (Id IG1) (ident IG1) (Id IG2) (ident IG2) i \<in> N IG1 \<union> N IG2" by simp next assume "ig_combine_ident (Id IG1) (ident IG1) (Id IG2) (ident IG2) i = ident IG1 i" then show "type\<^sub>n (ig_combine_ident (Id IG1) (ident IG1) (Id IG2) (ident IG2) i) \<in> Lab\<^sub>t" using i_in_both first_instance_graph_valid instance_graph.structure_ident_wellformed_node_type by fastforce qed next assume i_in_ig1: "i \<in> Id IG1 - Id IG2" then have "ig_combine_ident (Id IG1) (ident IG1) (Id IG2) (ident IG2) i = ident IG1 i" unfolding ig_combine_ident_def by simp then show ?thesis proof (intro conjI) assume "ig_combine_ident (Id IG1) (ident IG1) (Id IG2) (ident IG2) i = ident IG1 i" then have "ig_combine_ident (Id IG1) (ident IG1) (Id IG2) (ident IG2) i \<in> N IG1" using i_in_ig1 first_instance_graph_valid instance_graph.structure_ident_wellformed_node by fastforce then show "ig_combine_ident (Id IG1) (ident IG1) (Id IG2) (ident IG2) i \<in> N IG1 \<union> N IG2" by simp next assume "ig_combine_ident (Id IG1) (ident IG1) (Id IG2) (ident IG2) i = ident IG1 i" then show "type\<^sub>n (ig_combine_ident (Id IG1) (ident IG1) (Id IG2) (ident IG2) i) \<in> Lab\<^sub>t" using i_in_ig1 first_instance_graph_valid instance_graph.structure_ident_wellformed_node_type by fastforce qed next assume i_in_ig2: "i \<in> Id IG2 - Id IG1" then have "ig_combine_ident (Id IG1) (ident IG1) (Id IG2) (ident IG2) i = ident IG2 i" unfolding ig_combine_ident_def by simp then show ?thesis proof (intro conjI) assume "ig_combine_ident (Id IG1) (ident IG1) (Id IG2) (ident IG2) i = ident IG2 i" then have "ig_combine_ident (Id IG1) (ident IG1) (Id IG2) (ident IG2) i \<in> N IG2" using i_in_ig2 second_instance_graph_valid instance_graph.structure_ident_wellformed_node by fastforce then show "ig_combine_ident (Id IG1) (ident IG1) (Id IG2) (ident IG2) i \<in> N IG1 \<union> N IG2" by simp next assume "ig_combine_ident (Id IG1) (ident IG1) (Id IG2) (ident IG2) i = ident IG2 i" then show "type\<^sub>n (ig_combine_ident (Id IG1) (ident IG1) (Id IG2) (ident IG2) i) \<in> Lab\<^sub>t" using i_in_ig2 second_instance_graph_valid instance_graph.structure_ident_wellformed_node_type by fastforce qed qed then show "ident (ig_combine IG1 IG2) i \<in> N (ig_combine IG1 IG2) \<and> type\<^sub>n (ident (ig_combine IG1 IG2) i) \<in> Lab\<^sub>t" unfolding ig_combine_def by simp next fix i assume "i \<notin> Id (ig_combine IG1 IG2)" then have "i \<notin> Id IG1 \<and> i \<notin> Id IG2" unfolding ig_combine_def by simp then have "ig_combine_ident (Id IG1) (ident IG1) (Id IG2) (ident IG2) i = undefined" unfolding ig_combine_ident_def by simp then show "ident (ig_combine IG1 IG2) i = undefined" unfolding ig_combine_def by simp next have "type_graph (tg_combine (TG IG1) (TG IG2))" by (fact assms) then show "type_graph (TG (ig_combine IG1 IG2))" unfolding ig_combine_def by simp next fix n assume "n \<in> N (ig_combine IG1 IG2)" then have "n \<in> N IG1 \<union> N IG2" unfolding ig_combine_def by simp then have "type\<^sub>n n \<in> NT (TG IG1) \<union> NT (TG IG2)" proof (elim UnE) assume "n \<in> N IG1" then show "type\<^sub>n n \<in> NT (TG IG1) \<union> NT (TG IG2)" using first_instance_graph_valid instance_graph.validity_node_typed by blast next assume "n \<in> N IG2" then show "type\<^sub>n n \<in> NT (TG IG1) \<union> NT (TG IG2)" using second_instance_graph_valid instance_graph.validity_node_typed by blast qed then show "type\<^sub>n n \<in> NT (TG (ig_combine IG1 IG2))" unfolding ig_combine_def tg_combine_def by simp next fix e assume "e \<in> E (ig_combine IG1 IG2)" then have "e \<in> E IG1 \<union> E IG2" unfolding ig_combine_def by simp then have "(type\<^sub>n (src e), src (type\<^sub>e e)) \<in> (inh (TG IG1) \<union> inh (TG IG2))\<^sup>+" proof (elim UnE) assume "e \<in> E IG1" then have "(type\<^sub>n (src e), src (type\<^sub>e e)) \<in> inh (TG IG1)" using first_instance_graph_valid instance_graph.validity_edge_src_typed by blast then have "(type\<^sub>n (src e), src (type\<^sub>e e)) \<in> inh (TG IG1) \<union> inh (TG IG2)" by simp then show "(type\<^sub>n (src e), src (type\<^sub>e e)) \<in> (inh (TG IG1) \<union> inh (TG IG2))\<^sup>+" by auto next assume "e \<in> E IG2" then have "(type\<^sub>n (src e), src (type\<^sub>e e)) \<in> inh (TG IG2)" using second_instance_graph_valid instance_graph.validity_edge_src_typed by blast then have "(type\<^sub>n (src e), src (type\<^sub>e e)) \<in> inh (TG IG1) \<union> inh (TG IG2)" by simp then show "(type\<^sub>n (src e), src (type\<^sub>e e)) \<in> (inh (TG IG1) \<union> inh (TG IG2))\<^sup>+" by auto qed then show "(type\<^sub>n (src e), src (type\<^sub>e e)) \<in> inh (TG (ig_combine IG1 IG2))" unfolding ig_combine_def tg_combine_def by simp next fix e assume "e \<in> E (ig_combine IG1 IG2)" then have "e \<in> E IG1 \<union> E IG2" unfolding ig_combine_def by simp then have "(type\<^sub>n (tgt e), tgt (type\<^sub>e e)) \<in> (inh (TG IG1) \<union> inh (TG IG2))\<^sup>+" proof (elim UnE) assume "e \<in> E IG1" then have "(type\<^sub>n (tgt e), tgt (type\<^sub>e e)) \<in> inh (TG IG1)" using first_instance_graph_valid instance_graph.validity_edge_tgt_typed by blast then have "(type\<^sub>n (tgt e), tgt (type\<^sub>e e)) \<in> inh (TG IG1) \<union> inh (TG IG2)" by simp then show "(type\<^sub>n (tgt e), tgt (type\<^sub>e e)) \<in> (inh (TG IG1) \<union> inh (TG IG2))\<^sup>+" by auto next assume "e \<in> E IG2" then have "(type\<^sub>n (tgt e), tgt (type\<^sub>e e)) \<in> inh (TG IG2)" using second_instance_graph_valid instance_graph.validity_edge_tgt_typed by blast then have "(type\<^sub>n (tgt e), tgt (type\<^sub>e e)) \<in> inh (TG IG1) \<union> inh (TG IG2)" by simp then show "(type\<^sub>n (tgt e), tgt (type\<^sub>e e)) \<in> (inh (TG IG1) \<union> inh (TG IG2))\<^sup>+" by auto qed then show "(type\<^sub>n (tgt e), tgt (type\<^sub>e e)) \<in> inh (TG (ig_combine IG1 IG2))" unfolding ig_combine_def tg_combine_def by simp next fix n assume "n \<in> N (ig_combine IG1 IG2)" then have "n \<in> N IG1 \<union> N IG2" unfolding ig_combine_def by simp then have "type\<^sub>n n \<notin> (abs (TG IG1) - NT (TG IG2)) \<union> (abs (TG IG2) - NT (TG IG1)) \<union> (abs (TG IG1) \<inter> abs (TG IG2))" proof (elim UnE) assume n_in_ig1: "n \<in> N IG1" then have "type\<^sub>n n \<notin> abs (TG IG1)" using first_instance_graph_valid instance_graph.validity_abs_no_instances by blast then show "type\<^sub>n n \<notin> (abs (TG IG1) - NT (TG IG2)) \<union> (abs (TG IG2) - NT (TG IG1)) \<union> (abs (TG IG1) \<inter> abs (TG IG2))" using n_in_ig1 instance_graph.validity_node_typed first_instance_graph_valid by fastforce next assume n_in_ig2: "n \<in> N IG2" then have "type\<^sub>n n \<notin> abs (TG IG2)" using second_instance_graph_valid instance_graph.validity_abs_no_instances by blast then show "type\<^sub>n n \<notin> (abs (TG IG1) - NT (TG IG2)) \<union> (abs (TG IG2) - NT (TG IG1)) \<union> (abs (TG IG1) \<inter> abs (TG IG2))" using n_in_ig2 instance_graph.validity_node_typed second_instance_graph_valid by fastforce qed then show "type\<^sub>n n \<notin> abs (TG (ig_combine IG1 IG2))" unfolding ig_combine_def tg_combine_def by simp next fix et n assume "et \<in> ET (TG (ig_combine IG1 IG2))" then have et_in_ef: "et \<in> ET (TG IG1) \<union> ET (TG IG2)" unfolding ig_combine_def tg_combine_def by simp assume "n \<in> N (ig_combine IG1 IG2)" then have n_in_in: "n \<in> N IG1 \<union> N IG2" unfolding ig_combine_def by simp assume "(type\<^sub>n n, src et) \<in> inh (TG (ig_combine IG1 IG2))" then have type_extend: "(type\<^sub>n n, src et) \<in> (inh (TG IG1) \<union> inh (TG IG2))\<^sup>+" unfolding ig_combine_def tg_combine_def by simp have "card {e \<in> E IG1 \<union> E IG2. src e = n \<and> type\<^sub>e e = et} in m_out (tg_combine_mult (ET (TG IG1)) (mult (TG IG1)) (ET (TG IG2)) (mult (TG IG2)) et)" using et_in_ef n_in_in type_extend by (fact assms) then show "card {e \<in> E (ig_combine IG1 IG2). src e = n \<and> type\<^sub>e e = et} in m_out (mult (TG (ig_combine IG1 IG2)) et)" unfolding ig_combine_def tg_combine_def by simp next fix et n assume "et \<in> ET (TG (ig_combine IG1 IG2))" then have et_in_ef: "et \<in> ET (TG IG1) \<union> ET (TG IG2)" unfolding ig_combine_def tg_combine_def by simp assume "n \<in> N (ig_combine IG1 IG2)" then have n_in_in: "n \<in> N IG1 \<union> N IG2" unfolding ig_combine_def by simp assume "(type\<^sub>n n, tgt et) \<in> inh (TG (ig_combine IG1 IG2))" then have type_extend: "(type\<^sub>n n, tgt et) \<in> (inh (TG IG1) \<union> inh (TG IG2))\<^sup>+" unfolding ig_combine_def tg_combine_def by simp have "card {e \<in> E IG1 \<union> E IG2. tgt e = n \<and> type\<^sub>e e = et} in m_in (tg_combine_mult (ET (TG IG1)) (mult (TG IG1)) (ET (TG IG2)) (mult (TG IG2)) et)" using et_in_ef n_in_in type_extend by (fact assms) then show "card {e \<in> E (ig_combine IG1 IG2). tgt e = n \<and> type\<^sub>e e = et} in m_in (mult (TG (ig_combine IG1 IG2)) et)" unfolding ig_combine_def tg_combine_def by simp next fix n assume "n \<in> N (ig_combine IG1 IG2)" then have "n \<in> N IG1 \<union> N IG2" unfolding ig_combine_def tg_combine_def by simp then have "card {e \<in> E IG1 \<union> E IG2. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG1) \<union> contains (TG IG2)} \<le> 1" by (fact assms) then show "card {e \<in> E (ig_combine IG1 IG2). tgt e = n \<and> type\<^sub>e e \<in> contains (TG (ig_combine IG1 IG2))} \<le> 1" unfolding ig_combine_def tg_combine_def by simp next fix p show "\<not>pre_digraph.cycle (instance_graph_containment_proj (ig_combine IG1 IG2)) p" proof (intro validity_containmentI) show "\<And>e. e \<in> E (ig_combine IG1 IG2) \<Longrightarrow> type\<^sub>e e \<in> contains (TG (ig_combine IG1 IG2)) \<Longrightarrow> src e \<in> N (ig_combine IG1 IG2) \<and> tgt e \<in> N (ig_combine IG1 IG2)" proof (intro conjI) fix e assume "e \<in> E (ig_combine IG1 IG2)" then have "e \<in> E IG1 \<union> E IG2" unfolding ig_combine_def by simp then have "src e \<in> N IG1 \<union> N IG2" using first_instance_graph_valid second_instance_graph_valid instance_graph.structure_edges_wellformed_src_node_alt by blast then show "src e \<in> N (ig_combine IG1 IG2)" unfolding ig_combine_def by simp next fix e assume "e \<in> E (ig_combine IG1 IG2)" then have "e \<in> E IG1 \<union> E IG2" unfolding ig_combine_def by simp then have "tgt e \<in> N IG1 \<union> N IG2" using first_instance_graph_valid second_instance_graph_valid instance_graph.structure_edges_wellformed_tgt_node_alt by blast then show "tgt e \<in> N (ig_combine IG1 IG2)" unfolding ig_combine_def by simp qed next have "irrefl ((edge_to_tuple ` {e \<in> E IG1 \<union> E IG2. type\<^sub>e e \<in> contains (TG IG1) \<union> contains (TG IG2)})\<^sup>+)" by (fact validity_containment) then show "irrefl ((edge_to_tuple ` {e \<in> E (ig_combine IG1 IG2). type\<^sub>e e \<in> contains (TG (ig_combine IG1 IG2))})\<^sup>+)" unfolding ig_combine_def tg_combine_def by simp qed qed lemma ig_combine_merge_correct[intro]: assumes first_instance_graph_valid: "instance_graph IG1" assumes second_instance_graph_valid: "instance_graph IG2" assumes type_graph_combination_valid: "type_graph (tg_combine (TG IG1) (TG IG2))" assumes combine_edges_distinct: "ET (TG IG1) \<inter> ET (TG IG2) = {}" assumes validity_identity: "\<And>i. i \<in> Id IG1 \<Longrightarrow> i \<in> Id IG2 \<Longrightarrow> ident IG1 i = ident IG2 i" assumes validity_outgoing_mult_first: "\<And>et n. et \<in> ET (TG IG1) \<Longrightarrow> n \<in> N IG1 \<union> N IG2 \<Longrightarrow> (type\<^sub>n n, src et) \<in> (inh (TG IG1) \<union> inh (TG IG2))\<^sup>+ \<Longrightarrow> card {e \<in> E IG1. src e = n \<and> type\<^sub>e e = et} in m_out (mult (TG IG1) et)" assumes validity_outgoing_mult_second: "\<And>et n. et \<in> ET (TG IG2) \<Longrightarrow> n \<in> N IG1 \<union> N IG2 \<Longrightarrow> (type\<^sub>n n, src et) \<in> (inh (TG IG1) \<union> inh (TG IG2))\<^sup>+ \<Longrightarrow> card {e \<in> E IG2. src e = n \<and> type\<^sub>e e = et} in m_out (mult (TG IG2) et)" assumes validity_ingoing_mult_first: "\<And>et n. et \<in> ET (TG IG1) \<Longrightarrow> n \<in> N IG1 \<union> N IG2 \<Longrightarrow> (type\<^sub>n n, tgt et) \<in> (inh (TG IG1) \<union> inh (TG IG2))\<^sup>+ \<Longrightarrow> card {e \<in> E IG1. tgt e = n \<and> type\<^sub>e e = et} in m_in (mult (TG IG1) et)" assumes validity_ingoing_mult_second: "\<And>et n. et \<in> ET (TG IG2) \<Longrightarrow> n \<in> N IG1 \<union> N IG2 \<Longrightarrow> (type\<^sub>n n, tgt et) \<in> (inh (TG IG1) \<union> inh (TG IG2))\<^sup>+ \<Longrightarrow> card {e \<in> E IG2. tgt e = n \<and> type\<^sub>e e = et} in m_in (mult (TG IG2) et)" assumes validity_contained_node: "\<And>n. n \<in> N IG1 \<inter> N IG2 \<Longrightarrow> card {e \<in> E IG1 \<union> E IG2. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG1) \<union> contains (TG IG2)} \<le> 1" assumes validity_containment: "irrefl ((edge_to_tuple ` {e \<in> E IG1. type\<^sub>e e \<in> contains (TG IG1)} \<union> edge_to_tuple ` {e \<in> E IG2. type\<^sub>e e \<in> contains (TG IG2)})\<^sup>+)" shows "instance_graph (ig_combine IG1 IG2)" proof (intro ig_combine_correct) fix et n assume et_in_tg_e: "et \<in> ET (TG IG1) \<union> ET (TG IG2)" assume n_in_in_igs: "n \<in> N IG1 \<union> N IG2" assume edge_of_type: "(type\<^sub>n n, src et) \<in> (inh (TG IG1) \<union> inh (TG IG2))\<^sup>+" show "card {e \<in> E IG1 \<union> E IG2. src e = n \<and> type\<^sub>e e = et} in m_out (tg_combine_mult (ET (TG IG1)) (mult (TG IG1)) (ET (TG IG2)) (mult (TG IG2)) et)" using et_in_tg_e edge_of_type proof (elim UnE) assume et_in_e: "et \<in> ET (TG IG1)" then have mult_et: "m_out (tg_combine_mult (ET (TG IG1)) (mult (TG IG1)) (ET (TG IG2)) (mult (TG IG2)) et) = m_out (mult (TG IG1) et)" unfolding tg_combine_mult_def using combine_edges_distinct by auto have set_et: "{e \<in> E IG1 \<union> E IG2. src e = n \<and> type\<^sub>e e = et} = {e \<in> E IG1. src e = n \<and> type\<^sub>e e = et}" proof show "{e \<in> E IG1 \<union> E IG2. src e = n \<and> type\<^sub>e e = et} \<subseteq> {e \<in> E IG1. src e = n \<and> type\<^sub>e e = et}" proof fix x assume "x \<in> {e \<in> E IG1 \<union> E IG2. src e = n \<and> type\<^sub>e e = et}" then show "x \<in> {e \<in> E IG1. src e = n \<and> type\<^sub>e e = et}" proof assume assumpt: "x \<in> E IG1 \<union> E IG2 \<and> src x = n \<and> type\<^sub>e x = et" then have "x \<notin> E IG2" using et_in_e combine_edges_distinct first_instance_graph_valid second_instance_graph_valid using instance_graph.structure_edges_wellformed_edge_type_alt by blast then have "x \<in> E IG1 \<and> src x = n \<and> type\<^sub>e x = et" using assumpt by simp then show "x \<in> {e \<in> E IG1. src e = n \<and> type\<^sub>e e = et}" by simp qed qed next show "{e \<in> E IG1. src e = n \<and> type\<^sub>e e = et} \<subseteq> {e \<in> E IG1 \<union> E IG2. src e = n \<and> type\<^sub>e e = et}" by auto qed have "card {e \<in> E IG1. src e = n \<and> type\<^sub>e e = et} in m_out (mult (TG IG1) et)" using et_in_e n_in_in_igs edge_of_type by (fact validity_outgoing_mult_first) then show "card {e \<in> E IG1 \<union> E IG2. src e = n \<and> type\<^sub>e e = et} in m_out (tg_combine_mult (ET (TG IG1)) (mult (TG IG1)) (ET (TG IG2)) (mult (TG IG2)) et)" using mult_et set_et by simp next assume et_in_e: "et \<in> ET (TG IG2)" then have mult_et: "m_out (tg_combine_mult (ET (TG IG1)) (mult (TG IG1)) (ET (TG IG2)) (mult (TG IG2)) et) = m_out (mult (TG IG2) et)" unfolding tg_combine_mult_def using combine_edges_distinct by auto have set_et: "{e \<in> E IG1 \<union> E IG2. src e = n \<and> type\<^sub>e e = et} = {e \<in> E IG2. src e = n \<and> type\<^sub>e e = et}" proof show "{e \<in> E IG1 \<union> E IG2. src e = n \<and> type\<^sub>e e = et} \<subseteq> {e \<in> E IG2. src e = n \<and> type\<^sub>e e = et}" proof fix x assume "x \<in> {e \<in> E IG1 \<union> E IG2. src e = n \<and> type\<^sub>e e = et}" then show "x \<in> {e \<in> E IG2. src e = n \<and> type\<^sub>e e = et}" proof assume assumpt: "x \<in> E IG1 \<union> E IG2 \<and> src x = n \<and> type\<^sub>e x = et" then have "x \<notin> E IG1" using et_in_e combine_edges_distinct first_instance_graph_valid second_instance_graph_valid using instance_graph.structure_edges_wellformed_edge_type_alt by blast then have "x \<in> E IG2 \<and> src x = n \<and> type\<^sub>e x = et" using assumpt by simp then show "x \<in> {e \<in> E IG2. src e = n \<and> type\<^sub>e e = et}" by simp qed qed next show "{e \<in> E IG2. src e = n \<and> type\<^sub>e e = et} \<subseteq> {e \<in> E IG1 \<union> E IG2. src e = n \<and> type\<^sub>e e = et}" by auto qed have "card {e \<in> E IG2. src e = n \<and> type\<^sub>e e = et} in m_out (mult (TG IG2) et)" using et_in_e n_in_in_igs edge_of_type by (fact validity_outgoing_mult_second) then show "card {e \<in> E IG1 \<union> E IG2. src e = n \<and> type\<^sub>e e = et} in m_out (tg_combine_mult (ET (TG IG1)) (mult (TG IG1)) (ET (TG IG2)) (mult (TG IG2)) et)" using mult_et set_et by simp qed next fix et n assume et_in_tg_e: "et \<in> ET (TG IG1) \<union> ET (TG IG2)" assume n_in_in_igs: "n \<in> N IG1 \<union> N IG2" assume edge_of_type: "(type\<^sub>n n, tgt et) \<in> (inh (TG IG1) \<union> inh (TG IG2))\<^sup>+" show "card {e \<in> E IG1 \<union> E IG2. tgt e = n \<and> type\<^sub>e e = et} in m_in (tg_combine_mult (ET (TG IG1)) (mult (TG IG1)) (ET (TG IG2)) (mult (TG IG2)) et)" using et_in_tg_e edge_of_type proof (elim UnE) assume et_in_e: "et \<in> ET (TG IG1)" then have mult_et: "m_in (tg_combine_mult (ET (TG IG1)) (mult (TG IG1)) (ET (TG IG2)) (mult (TG IG2)) et) = m_in (mult (TG IG1) et)" unfolding tg_combine_mult_def using combine_edges_distinct by auto have set_et: "{e \<in> E IG1 \<union> E IG2. tgt e = n \<and> type\<^sub>e e = et} = {e \<in> E IG1. tgt e = n \<and> type\<^sub>e e = et}" proof show "{e \<in> E IG1 \<union> E IG2. tgt e = n \<and> type\<^sub>e e = et} \<subseteq> {e \<in> E IG1. tgt e = n \<and> type\<^sub>e e = et}" proof fix x assume "x \<in> {e \<in> E IG1 \<union> E IG2. tgt e = n \<and> type\<^sub>e e = et}" then show "x \<in> {e \<in> E IG1. tgt e = n \<and> type\<^sub>e e = et}" proof assume assumpt: "x \<in> E IG1 \<union> E IG2 \<and> tgt x = n \<and> type\<^sub>e x = et" then have "x \<notin> E IG2" using et_in_e combine_edges_distinct first_instance_graph_valid second_instance_graph_valid using instance_graph.structure_edges_wellformed_edge_type_alt by blast then have "x \<in> E IG1 \<and> tgt x = n \<and> type\<^sub>e x = et" using assumpt by simp then show "x \<in> {e \<in> E IG1. tgt e = n \<and> type\<^sub>e e = et}" by simp qed qed next show "{e \<in> E IG1. tgt e = n \<and> type\<^sub>e e = et} \<subseteq> {e \<in> E IG1 \<union> E IG2. tgt e = n \<and> type\<^sub>e e = et}" by auto qed have "card {e \<in> E IG1. tgt e = n \<and> type\<^sub>e e = et} in m_in (mult (TG IG1) et)" using et_in_e n_in_in_igs edge_of_type by (fact validity_ingoing_mult_first) then show "card {e \<in> E IG1 \<union> E IG2. tgt e = n \<and> type\<^sub>e e = et} in m_in (tg_combine_mult (ET (TG IG1)) (mult (TG IG1)) (ET (TG IG2)) (mult (TG IG2)) et)" using mult_et set_et by simp next assume et_in_e: "et \<in> ET (TG IG2)" then have mult_et: "m_in (tg_combine_mult (ET (TG IG1)) (mult (TG IG1)) (ET (TG IG2)) (mult (TG IG2)) et) = m_in (mult (TG IG2) et)" unfolding tg_combine_mult_def using combine_edges_distinct by auto have set_et: "{e \<in> E IG1 \<union> E IG2. tgt e = n \<and> type\<^sub>e e = et} = {e \<in> E IG2. tgt e = n \<and> type\<^sub>e e = et}" proof show "{e \<in> E IG1 \<union> E IG2. tgt e = n \<and> type\<^sub>e e = et} \<subseteq> {e \<in> E IG2. tgt e = n \<and> type\<^sub>e e = et}" proof fix x assume "x \<in> {e \<in> E IG1 \<union> E IG2. tgt e = n \<and> type\<^sub>e e = et}" then show "x \<in> {e \<in> E IG2. tgt e = n \<and> type\<^sub>e e = et}" proof assume assumpt: "x \<in> E IG1 \<union> E IG2 \<and> tgt x = n \<and> type\<^sub>e x = et" then have "x \<notin> E IG1" using et_in_e combine_edges_distinct first_instance_graph_valid second_instance_graph_valid using instance_graph.structure_edges_wellformed_edge_type_alt by blast then have "x \<in> E IG2 \<and> tgt x = n \<and> type\<^sub>e x = et" using assumpt by simp then show "x \<in> {e \<in> E IG2. tgt e = n \<and> type\<^sub>e e = et}" by simp qed qed next show "{e \<in> E IG2. tgt e = n \<and> type\<^sub>e e = et} \<subseteq> {e \<in> E IG1 \<union> E IG2. tgt e = n \<and> type\<^sub>e e = et}" by auto qed have "card {e \<in> E IG2. tgt e = n \<and> type\<^sub>e e = et} in m_in (mult (TG IG2) et)" using et_in_e n_in_in_igs edge_of_type by (fact validity_ingoing_mult_second) then show "card {e \<in> E IG1 \<union> E IG2. tgt e = n \<and> type\<^sub>e e = et} in m_in (tg_combine_mult (ET (TG IG1)) (mult (TG IG1)) (ET (TG IG2)) (mult (TG IG2)) et)" using mult_et set_et by simp qed next fix n assume "n \<in> N IG1 \<union> N IG2" then have n_in_in_igs: "n \<in> N IG1 \<inter> N IG2 \<or> n \<in> N IG1 - N IG2 \<or> n \<in> N IG2 - N IG1" by auto then show "card {e \<in> E IG1 \<union> E IG2. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG1) \<union> contains (TG IG2)} \<le> 1" proof (elim disjE) assume "n \<in> N IG1 \<inter> N IG2" then show "card {e \<in> E IG1 \<union> E IG2. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG1) \<union> contains (TG IG2)} \<le> 1" by (fact assms) next assume n_in_ig1_not_ig2: "n \<in> N IG1 - N IG2" have set_ie_eq: "{e \<in> E IG1 \<union> E IG2. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG1) \<union> contains (TG IG2)} = {e \<in> E IG1. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG1)}" proof show "{e \<in> E IG1 \<union> E IG2. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG1) \<union> contains (TG IG2)} \<subseteq> {e \<in> E IG1. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG1)}" proof fix x assume "x \<in> {e \<in> E IG1 \<union> E IG2. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG1) \<union> contains (TG IG2)}" then show "x \<in> {e \<in> E IG1. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG1)}" proof assume assumpt: "x \<in> E IG1 \<union> E IG2 \<and> tgt x = n \<and> type\<^sub>e x \<in> contains (TG IG1) \<union> contains (TG IG2)" then have x_not_in_ig2: "x \<notin> E IG2" using n_in_ig1_not_ig2 second_instance_graph_valid instance_graph.structure_edges_wellformed_tgt_node_alt by blast then have x_in_ig1: "x \<in> E IG1" using assumpt by simp then have "type\<^sub>e x \<in> ET (TG IG1)" using first_instance_graph_valid instance_graph.structure_edges_wellformed_edge_type_alt by blast then have "type\<^sub>e x \<notin> contains (TG IG2)" using combine_edges_distinct second_instance_graph_valid using instance_graph.validity_type_graph type_graph.structure_contains_wellformed by blast then have "type\<^sub>e x \<in> contains (TG IG1)" using assumpt by simp then show "x \<in> {e \<in> E IG1. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG1)}" using assumpt x_in_ig1 by simp qed qed next show "{e \<in> E IG1. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG1)} \<subseteq> {e \<in> E IG1 \<union> E IG2. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG1) \<union> contains (TG IG2)}" by auto qed have "n \<in> N IG1" using n_in_ig1_not_ig2 by simp then have "card {e \<in> E IG1. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG1)} \<le> 1" using first_instance_graph_valid instance_graph.validity_contained_node by simp then show "card {e \<in> E IG1 \<union> E IG2. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG1) \<union> contains (TG IG2)} \<le> 1" using set_ie_eq by simp next assume n_in_ig2_not_ig1: "n \<in> N IG2 - N IG1" have set_ie_eq: "{e \<in> E IG1 \<union> E IG2. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG1) \<union> contains (TG IG2)} = {e \<in> E IG2. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG2)}" proof show "{e \<in> E IG1 \<union> E IG2. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG1) \<union> contains (TG IG2)} \<subseteq> {e \<in> E IG2. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG2)}" proof fix x assume "x \<in> {e \<in> E IG1 \<union> E IG2. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG1) \<union> contains (TG IG2)}" then show "x \<in> {e \<in> E IG2. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG2)}" proof assume assumpt: "x \<in> E IG1 \<union> E IG2 \<and> tgt x = n \<and> type\<^sub>e x \<in> contains (TG IG1) \<union> contains (TG IG2)" then have x_not_in_ig1: "x \<notin> E IG1" using n_in_ig2_not_ig1 first_instance_graph_valid instance_graph.structure_edges_wellformed_tgt_node_alt by blast then have x_in_ig2: "x \<in> E IG2" using assumpt by simp then have "type\<^sub>e x \<in> ET (TG IG2)" using second_instance_graph_valid instance_graph.structure_edges_wellformed_edge_type_alt by blast then have "type\<^sub>e x \<notin> contains (TG IG1)" using combine_edges_distinct first_instance_graph_valid using instance_graph.validity_type_graph type_graph.structure_contains_wellformed by blast then have "type\<^sub>e x \<in> contains (TG IG2)" using assumpt by simp then show "x \<in> {e \<in> E IG2. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG2)}" using assumpt x_in_ig2 by simp qed qed next show "{e \<in> E IG2. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG2)} \<subseteq> {e \<in> E IG1 \<union> E IG2. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG1) \<union> contains (TG IG2)}" by auto qed have "n \<in> N IG2" using n_in_ig2_not_ig1 by simp then have "card {e \<in> E IG2. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG2)} \<le> 1" using second_instance_graph_valid instance_graph.validity_contained_node by simp then show "card {e \<in> E IG1 \<union> E IG2. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG1) \<union> contains (TG IG2)} \<le> 1" using set_ie_eq by simp qed next have containment_relation_def: "{e \<in> E IG1 \<union> E IG2. type\<^sub>e e \<in> contains (TG IG1) \<union> contains (TG IG2)} = {e \<in> E IG1. type\<^sub>e e \<in> contains (TG IG1)} \<union> {e \<in> E IG2. type\<^sub>e e \<in> contains (TG IG2)}" proof show "{e \<in> E IG1 \<union> E IG2. type\<^sub>e e \<in> contains (TG IG1) \<union> contains (TG IG2)} \<subseteq> {e \<in> E IG1. type\<^sub>e e \<in> contains (TG IG1)} \<union> {e \<in> E IG2. type\<^sub>e e \<in> contains (TG IG2)}" proof fix x assume "x \<in> {e \<in> E IG1 \<union> E IG2. type\<^sub>e e \<in> contains (TG IG1) \<union> contains (TG IG2)}" then show "x \<in> {e \<in> E IG1. type\<^sub>e e \<in> contains (TG IG1)} \<union> {e \<in> E IG2. type\<^sub>e e \<in> contains (TG IG2)}" proof assume assump: "x \<in> E IG1 \<union> E IG2 \<and> type\<^sub>e x \<in> contains (TG IG1) \<union> contains (TG IG2)" then have in_e_cases: "x \<in> E IG1 \<union> E IG2" by simp have type_cases: "type\<^sub>e x \<in> contains (TG IG1) \<union> contains (TG IG2)" using assump by simp show "x \<in> {e \<in> E IG1. type\<^sub>e e \<in> contains (TG IG1)} \<union> {e \<in> E IG2. type\<^sub>e e \<in> contains (TG IG2)}" using in_e_cases type_cases proof (elim UnE) assume x_def: "x \<in> E IG1" assume type_x_def: "type\<^sub>e x \<in> contains (TG IG1)" show ?thesis using x_def type_x_def by blast next assume "x \<in> E IG1" then have type_in_ig: "type\<^sub>e x \<in> ET (TG IG1)" using assms(1) instance_graph.structure_edges_wellformed_edge_type_alt by blast assume "type\<^sub>e x \<in> contains (TG IG2)" then have "type\<^sub>e x \<in> ET (TG IG2)" by (simp add: instance_graph.validity_type_graph second_instance_graph_valid type_graph.structure_contains_wellformed) then have "type\<^sub>e x \<notin> ET (TG IG1)" using combine_edges_distinct by blast then show ?thesis using type_in_ig by simp next assume "x \<in> E IG2" then have "type\<^sub>e x \<in> ET (TG IG2)" using second_instance_graph_valid instance_graph.structure_edges_wellformed_edge_type_alt by blast then have "type\<^sub>e x \<notin> ET (TG IG1)" using combine_edges_distinct by blast then have type_not_in_ig: "type\<^sub>e x \<notin> contains (TG IG1)" using instance_graph.validity_type_graph first_instance_graph_valid type_graph.structure_contains_wellformed by blast assume "type\<^sub>e x \<in> contains (TG IG1)" then show ?thesis using type_not_in_ig by simp next assume x_def: "x \<in> E IG2" assume type_x_def: "type\<^sub>e x \<in> contains (TG IG2)" show ?thesis using x_def type_x_def by blast qed qed qed next show "{e \<in> E IG1. type\<^sub>e e \<in> contains (TG IG1)} \<union> {e \<in> E IG2. type\<^sub>e e \<in> contains (TG IG2)} \<subseteq> {e \<in> E IG1 \<union> E IG2. type\<^sub>e e \<in> contains (TG IG1) \<union> contains (TG IG2)}" proof fix x assume "x \<in> {e \<in> E IG1. type\<^sub>e e \<in> contains (TG IG1)} \<union> {e \<in> E IG2. type\<^sub>e e \<in> contains (TG IG2)}" then show "x \<in> {e \<in> E IG1 \<union> E IG2. type\<^sub>e e \<in> contains (TG IG1) \<union> contains (TG IG2)}" proof (elim UnE) assume "x \<in> {e \<in> E IG1. type\<^sub>e e \<in> contains (TG IG1)}" then show ?thesis by simp next assume "x \<in> {e \<in> E IG2. type\<^sub>e e \<in> contains (TG IG2)}" then show ?thesis by simp qed qed qed have "irrefl ((edge_to_tuple ` {e \<in> E IG1. type\<^sub>e e \<in> contains (TG IG1)} \<union> edge_to_tuple ` {e \<in> E IG2. type\<^sub>e e \<in> contains (TG IG2)})\<^sup>+)" by (fact validity_containment) then have "irrefl ((edge_to_tuple ` ({e \<in> E IG1. type\<^sub>e e \<in> contains (TG IG1)} \<union> {e \<in> E IG2. type\<^sub>e e \<in> contains (TG IG2)}))\<^sup>+)" using image_Un by metis then show "irrefl ((edge_to_tuple ` {e \<in> E IG1 \<union> E IG2. type\<^sub>e e \<in> contains (TG IG1) \<union> contains (TG IG2)})\<^sup>+)" using containment_relation_def by simp qed (simp_all add: assms) lemma ig_combine_merge_no_containment_imod1_correct[intro]: assumes first_instance_graph_valid: "instance_graph IG1" assumes second_instance_graph_valid: "instance_graph IG2" assumes type_graph_combination_valid: "type_graph (tg_combine (TG IG1) (TG IG2))" assumes combine_edges_distinct: "ET (TG IG1) \<inter> ET (TG IG2) = {}" assumes combine_no_containment: "contains (TG IG1) = {}" assumes validity_identity: "\<And>i. i \<in> Id IG1 \<Longrightarrow> i \<in> Id IG2 \<Longrightarrow> ident IG1 i = ident IG2 i" assumes validity_outgoing_mult_first: "\<And>et n. et \<in> ET (TG IG1) \<Longrightarrow> n \<in> N IG1 \<union> N IG2 \<Longrightarrow> (type\<^sub>n n, src et) \<in> (inh (TG IG1) \<union> inh (TG IG2))\<^sup>+ \<Longrightarrow> card {e \<in> E IG1. src e = n \<and> type\<^sub>e e = et} in m_out (mult (TG IG1) et)" assumes validity_outgoing_mult_second: "\<And>et n. et \<in> ET (TG IG2) \<Longrightarrow> n \<in> N IG1 \<union> N IG2 \<Longrightarrow> (type\<^sub>n n, src et) \<in> (inh (TG IG1) \<union> inh (TG IG2))\<^sup>+ \<Longrightarrow> card {e \<in> E IG2. src e = n \<and> type\<^sub>e e = et} in m_out (mult (TG IG2) et)" assumes validity_ingoing_mult_first: "\<And>et n. et \<in> ET (TG IG1) \<Longrightarrow> n \<in> N IG1 \<union> N IG2 \<Longrightarrow> (type\<^sub>n n, tgt et) \<in> (inh (TG IG1) \<union> inh (TG IG2))\<^sup>+ \<Longrightarrow> card {e \<in> E IG1. tgt e = n \<and> type\<^sub>e e = et} in m_in (mult (TG IG1) et)" assumes validity_ingoing_mult_second: "\<And>et n. et \<in> ET (TG IG2) \<Longrightarrow> n \<in> N IG1 \<union> N IG2 \<Longrightarrow> (type\<^sub>n n, tgt et) \<in> (inh (TG IG1) \<union> inh (TG IG2))\<^sup>+ \<Longrightarrow> card {e \<in> E IG2. tgt e = n \<and> type\<^sub>e e = et} in m_in (mult (TG IG2) et)" shows "instance_graph (ig_combine IG1 IG2)" proof (intro ig_combine_merge_correct) show "\<And>et n. et \<in> ET (TG IG1) \<Longrightarrow> n \<in> N IG1 \<union> N IG2 \<Longrightarrow> (type\<^sub>n n, src et) \<in> (inh (TG IG1) \<union> inh (TG IG2))\<^sup>+ \<Longrightarrow> card {e \<in> E IG1. src e = n \<and> type\<^sub>e e = et} in m_out (mult (TG IG1) et)" by (fact validity_outgoing_mult_first) next show "\<And>et n. et \<in> ET (TG IG2) \<Longrightarrow> n \<in> N IG1 \<union> N IG2 \<Longrightarrow> (type\<^sub>n n, src et) \<in> (inh (TG IG1) \<union> inh (TG IG2))\<^sup>+ \<Longrightarrow> card {e \<in> E IG2. src e = n \<and> type\<^sub>e e = et} in m_out (mult (TG IG2) et)" by (fact validity_outgoing_mult_second) next show "\<And>et n. et \<in> ET (TG IG1) \<Longrightarrow> n \<in> N IG1 \<union> N IG2 \<Longrightarrow> (type\<^sub>n n, tgt et) \<in> (inh (TG IG1) \<union> inh (TG IG2))\<^sup>+ \<Longrightarrow> card {e \<in> E IG1. tgt e = n \<and> type\<^sub>e e = et} in m_in (mult (TG IG1) et)" by (fact validity_ingoing_mult_first) next show "\<And>et n. et \<in> ET (TG IG2) \<Longrightarrow> n \<in> N IG1 \<union> N IG2 \<Longrightarrow> (type\<^sub>n n, tgt et) \<in> (inh (TG IG1) \<union> inh (TG IG2))\<^sup>+ \<Longrightarrow> card {e \<in> E IG2. tgt e = n \<and> type\<^sub>e e = et} in m_in (mult (TG IG2) et)" by (fact validity_ingoing_mult_second) next fix n assume n_in_both: "n \<in> N IG1 \<inter> N IG2" have "{e \<in> E IG1 \<union> E IG2. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG1) \<union> contains (TG IG2)} = {e \<in> E IG2. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG2)}" proof show "{e \<in> E IG1 \<union> E IG2. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG1) \<union> contains (TG IG2)} \<subseteq> {e \<in> E IG2. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG2)}" proof fix x assume x_in_edges: "x \<in> {e \<in> E IG1 \<union> E IG2. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG1) \<union> contains (TG IG2)}" then have "type\<^sub>e x \<in> contains (TG IG1) \<union> contains (TG IG2)" by blast then have type_x_in_contains_tg2: "type\<^sub>e x \<in> contains (TG IG2)" using combine_no_containment by blast have tgt_x_is_n: "tgt x = n" using x_in_edges by simp have "x \<in> E IG1 \<union> E IG2" using x_in_edges by simp then show "x \<in> {e \<in> E IG2. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG2)}" proof (elim UnE) assume x_in_ig1: "x \<in> E IG1" then have "type\<^sub>e x \<in> ET (TG IG1)" using first_instance_graph_valid instance_graph.structure_edges_wellformed_edge_type_alt by blast then have "type\<^sub>e x \<notin> ET (TG IG2)" using combine_edges_distinct by blast then have "type\<^sub>e x \<notin> contains (TG IG2)" using second_instance_graph_valid instance_graph.validity_type_graph type_graph.structure_contains_wellformed by blast then show ?thesis using type_x_in_contains_tg2 by simp next assume x_in_ig2: "x \<in> E IG2" then show ?thesis using type_x_in_contains_tg2 tgt_x_is_n by simp qed qed next show "{e \<in> E IG2. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG2)} \<subseteq> {e \<in> E IG1 \<union> E IG2. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG1) \<union> contains (TG IG2)}" proof fix x assume "x \<in> {e \<in> E IG2. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG2)}" then have "x \<in> E IG2 \<and> tgt x = n \<and> type\<^sub>e x \<in> contains (TG IG2)" by blast then show "x \<in> {e \<in> E IG1 \<union> E IG2. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG1) \<union> contains (TG IG2)}" by simp qed qed then show "card {e \<in> E IG1 \<union> E IG2. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG1) \<union> contains (TG IG2)} \<le> 1" using second_instance_graph_valid instance_graph.validity_contained_node n_in_both by fastforce next have "{e \<in> E IG1. type\<^sub>e e \<in> contains (TG IG1)} = {}" proof show "{e \<in> E IG1. type\<^sub>e e \<in> contains (TG IG1)} \<subseteq> {}" proof fix x assume x_in_edges: "x \<in> {e \<in> E IG1. type\<^sub>e e \<in> contains (TG IG1)}" then have "type\<^sub>e x \<in> contains (TG IG1)" by blast then show "x \<in> {}" using combine_no_containment by simp qed next show "{} \<subseteq> {e \<in> E IG1. type\<^sub>e e \<in> contains (TG IG1)}" by simp qed then have "edge_to_tuple ` {e \<in> E IG1. type\<^sub>e e \<in> contains (TG IG1)} = {}" by blast then have "edge_to_tuple ` {e \<in> E IG1. type\<^sub>e e \<in> contains (TG IG1)} \<union> edge_to_tuple ` {e \<in> E IG2. type\<^sub>e e \<in> contains (TG IG2)} = edge_to_tuple ` {e \<in> E IG2. type\<^sub>e e \<in> contains (TG IG2)}" by blast then have containment_ig1_empty: "(edge_to_tuple ` {e \<in> E IG1. type\<^sub>e e \<in> contains (TG IG1)} \<union> edge_to_tuple ` {e \<in> E IG2. type\<^sub>e e \<in> contains (TG IG2)})\<^sup>+ = (edge_to_tuple ` {e \<in> E IG2. type\<^sub>e e \<in> contains (TG IG2)})\<^sup>+" by fastforce have "irrefl ((edge_to_tuple ` {e \<in> E IG2. type\<^sub>e e \<in> contains (TG IG2)})\<^sup>+)" proof (intro validity_containment_alt) fix e assume e_in_ig2: "e \<in> E IG2" then show "src e \<in> N IG2 \<and> tgt e \<in> N IG2" using second_instance_graph_valid instance_graph.structure_edges_wellformed_src_node_alt instance_graph.structure_edges_wellformed_tgt_node_alt by metis next fix p show "\<not>pre_digraph.cycle (instance_graph_containment_proj IG2) p" using second_instance_graph_valid instance_graph.validity_containment by blast qed then show "irrefl ((edge_to_tuple ` {e \<in> E IG1. type\<^sub>e e \<in> contains (TG IG1)} \<union> edge_to_tuple ` {e \<in> E IG2. type\<^sub>e e \<in> contains (TG IG2)})\<^sup>+)" using second_instance_graph_valid instance_graph.validity_contained_node containment_ig1_empty by simp qed (simp_all add: assms) lemma ig_combine_merge_no_containment_imod2_correct[intro]: assumes first_instance_graph_valid: "instance_graph IG1" assumes second_instance_graph_valid: "instance_graph IG2" assumes type_graph_combination_valid: "type_graph (tg_combine (TG IG1) (TG IG2))" assumes combine_edges_distinct: "ET (TG IG1) \<inter> ET (TG IG2) = {}" assumes combine_no_containment: "contains (TG IG2) = {}" assumes validity_identity: "\<And>i. i \<in> Id IG1 \<Longrightarrow> i \<in> Id IG2 \<Longrightarrow> ident IG1 i = ident IG2 i" assumes validity_outgoing_mult_first: "\<And>et n. et \<in> ET (TG IG1) \<Longrightarrow> n \<in> N IG1 \<union> N IG2 \<Longrightarrow> (type\<^sub>n n, src et) \<in> (inh (TG IG1) \<union> inh (TG IG2))\<^sup>+ \<Longrightarrow> card {e \<in> E IG1. src e = n \<and> type\<^sub>e e = et} in m_out (mult (TG IG1) et)" assumes validity_outgoing_mult_second: "\<And>et n. et \<in> ET (TG IG2) \<Longrightarrow> n \<in> N IG1 \<union> N IG2 \<Longrightarrow> (type\<^sub>n n, src et) \<in> (inh (TG IG1) \<union> inh (TG IG2))\<^sup>+ \<Longrightarrow> card {e \<in> E IG2. src e = n \<and> type\<^sub>e e = et} in m_out (mult (TG IG2) et)" assumes validity_ingoing_mult_first: "\<And>et n. et \<in> ET (TG IG1) \<Longrightarrow> n \<in> N IG1 \<union> N IG2 \<Longrightarrow> (type\<^sub>n n, tgt et) \<in> (inh (TG IG1) \<union> inh (TG IG2))\<^sup>+ \<Longrightarrow> card {e \<in> E IG1. tgt e = n \<and> type\<^sub>e e = et} in m_in (mult (TG IG1) et)" assumes validity_ingoing_mult_second: "\<And>et n. et \<in> ET (TG IG2) \<Longrightarrow> n \<in> N IG1 \<union> N IG2 \<Longrightarrow> (type\<^sub>n n, tgt et) \<in> (inh (TG IG1) \<union> inh (TG IG2))\<^sup>+ \<Longrightarrow> card {e \<in> E IG2. tgt e = n \<and> type\<^sub>e e = et} in m_in (mult (TG IG2) et)" shows "instance_graph (ig_combine IG1 IG2)" proof (intro ig_combine_merge_correct) show "\<And>et n. et \<in> ET (TG IG1) \<Longrightarrow> n \<in> N IG1 \<union> N IG2 \<Longrightarrow> (type\<^sub>n n, src et) \<in> (inh (TG IG1) \<union> inh (TG IG2))\<^sup>+ \<Longrightarrow> card {e \<in> E IG1. src e = n \<and> type\<^sub>e e = et} in m_out (mult (TG IG1) et)" by (fact validity_outgoing_mult_first) next show "\<And>et n. et \<in> ET (TG IG2) \<Longrightarrow> n \<in> N IG1 \<union> N IG2 \<Longrightarrow> (type\<^sub>n n, src et) \<in> (inh (TG IG1) \<union> inh (TG IG2))\<^sup>+ \<Longrightarrow> card {e \<in> E IG2. src e = n \<and> type\<^sub>e e = et} in m_out (mult (TG IG2) et)" by (fact validity_outgoing_mult_second) next show "\<And>et n. et \<in> ET (TG IG1) \<Longrightarrow> n \<in> N IG1 \<union> N IG2 \<Longrightarrow> (type\<^sub>n n, tgt et) \<in> (inh (TG IG1) \<union> inh (TG IG2))\<^sup>+ \<Longrightarrow> card {e \<in> E IG1. tgt e = n \<and> type\<^sub>e e = et} in m_in (mult (TG IG1) et)" by (fact validity_ingoing_mult_first) next show "\<And>et n. et \<in> ET (TG IG2) \<Longrightarrow> n \<in> N IG1 \<union> N IG2 \<Longrightarrow> (type\<^sub>n n, tgt et) \<in> (inh (TG IG1) \<union> inh (TG IG2))\<^sup>+ \<Longrightarrow> card {e \<in> E IG2. tgt e = n \<and> type\<^sub>e e = et} in m_in (mult (TG IG2) et)" by (fact validity_ingoing_mult_second) next fix n assume n_in_both: "n \<in> N IG1 \<inter> N IG2" have "{e \<in> E IG1 \<union> E IG2. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG1) \<union> contains (TG IG2)} = {e \<in> E IG1. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG1)}" proof show "{e \<in> E IG1 \<union> E IG2. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG1) \<union> contains (TG IG2)} \<subseteq> {e \<in> E IG1. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG1)}" proof fix x assume x_in_edges: "x \<in> {e \<in> E IG1 \<union> E IG2. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG1) \<union> contains (TG IG2)}" then have "type\<^sub>e x \<in> contains (TG IG1) \<union> contains (TG IG2)" by blast then have type_x_in_contains_tg1: "type\<^sub>e x \<in> contains (TG IG1)" using combine_no_containment by blast have tgt_x_is_n: "tgt x = n" using x_in_edges by simp have "x \<in> E IG1 \<union> E IG2" using x_in_edges by simp then show "x \<in> {e \<in> E IG1. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG1)}" proof (elim UnE) assume x_in_ig1: "x \<in> E IG1" then show ?thesis using type_x_in_contains_tg1 tgt_x_is_n by simp next assume x_in_ig2: "x \<in> E IG2" then have "type\<^sub>e x \<in> ET (TG IG2)" using second_instance_graph_valid instance_graph.structure_edges_wellformed_edge_type_alt by blast then have "type\<^sub>e x \<notin> ET (TG IG1)" using combine_edges_distinct by blast then have "type\<^sub>e x \<notin> contains (TG IG1)" using first_instance_graph_valid instance_graph.validity_type_graph type_graph.structure_contains_wellformed by blast then show ?thesis using type_x_in_contains_tg1 by simp qed qed next show "{e \<in> E IG1. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG1)} \<subseteq> {e \<in> E IG1 \<union> E IG2. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG1) \<union> contains (TG IG2)}" proof fix x assume "x \<in> {e \<in> E IG1. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG1)}" then have "x \<in> E IG1 \<and> tgt x = n \<and> type\<^sub>e x \<in> contains (TG IG1)" by blast then show "x \<in> {e \<in> E IG1 \<union> E IG2. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG1) \<union> contains (TG IG2)}" by simp qed qed then show "card {e \<in> E IG1 \<union> E IG2. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG1) \<union> contains (TG IG2)} \<le> 1" using first_instance_graph_valid instance_graph.validity_contained_node n_in_both by fastforce next have "{e \<in> E IG2. type\<^sub>e e \<in> contains (TG IG2)} = {}" proof show "{e \<in> E IG2. type\<^sub>e e \<in> contains (TG IG2)} \<subseteq> {}" proof fix x assume x_in_edges: "x \<in> {e \<in> E IG2. type\<^sub>e e \<in> contains (TG IG2)}" then have "type\<^sub>e x \<in> contains (TG IG2)" by blast then show "x \<in> {}" using combine_no_containment by simp qed next show "{} \<subseteq> {e \<in> E IG2. type\<^sub>e e \<in> contains (TG IG2)}" by simp qed then have "edge_to_tuple ` {e \<in> E IG2. type\<^sub>e e \<in> contains (TG IG2)} = {}" by blast then have "edge_to_tuple ` {e \<in> E IG1. type\<^sub>e e \<in> contains (TG IG1)} \<union> edge_to_tuple ` {e \<in> E IG2. type\<^sub>e e \<in> contains (TG IG2)} = edge_to_tuple ` {e \<in> E IG1. type\<^sub>e e \<in> contains (TG IG1)}" by blast then have containment_ig2_empty: "(edge_to_tuple ` {e \<in> E IG1. type\<^sub>e e \<in> contains (TG IG1)} \<union> edge_to_tuple ` {e \<in> E IG2. type\<^sub>e e \<in> contains (TG IG2)})\<^sup>+ = (edge_to_tuple ` {e \<in> E IG1. type\<^sub>e e \<in> contains (TG IG1)})\<^sup>+" by fastforce have "irrefl ((edge_to_tuple ` {e \<in> E IG1. type\<^sub>e e \<in> contains (TG IG1)})\<^sup>+)" proof (intro validity_containment_alt) fix e assume e_in_ig2: "e \<in> E IG1" then show "src e \<in> N IG1 \<and> tgt e \<in> N IG1" using first_instance_graph_valid instance_graph.structure_edges_wellformed_src_node_alt instance_graph.structure_edges_wellformed_tgt_node_alt by metis next fix p show "\<not>pre_digraph.cycle (instance_graph_containment_proj IG1) p" using first_instance_graph_valid instance_graph.validity_containment by blast qed then show "irrefl ((edge_to_tuple ` {e \<in> E IG1. type\<^sub>e e \<in> contains (TG IG1)} \<union> edge_to_tuple ` {e \<in> E IG2. type\<^sub>e e \<in> contains (TG IG2)})\<^sup>+)" using second_instance_graph_valid instance_graph.validity_contained_node containment_ig2_empty by simp qed (simp_all add: assms) lemma ig_combine_distinct_correct[intro]: assumes first_instance_graph_valid: "instance_graph IG1" assumes second_instance_graph_valid: "instance_graph IG2" assumes combine_nodes_distinct: "NT (TG IG1) \<inter> NT (TG IG2) = {}" assumes validity_identity: "\<And>i. i \<in> Id IG1 \<Longrightarrow> i \<in> Id IG2 \<Longrightarrow> ident IG1 i = ident IG2 i" shows "instance_graph (ig_combine IG1 IG2)" proof (intro ig_combine_merge_correct) show "type_graph (tg_combine (TG IG1) (TG IG2))" proof (intro tg_combine_distinct_correct) show "type_graph (TG IG1)" using first_instance_graph_valid by (fact instance_graph.validity_type_graph) next show "type_graph (TG IG2)" using second_instance_graph_valid by (fact instance_graph.validity_type_graph) qed (simp_all add: assms) next show "ET (TG IG1) \<inter> ET (TG IG2) = {}" using combine_nodes_distinct disjoint_iff_not_equal first_instance_graph_valid instance_graph.validity_type_graph using second_instance_graph_valid type_graph.structure_edges_wellformed_tgt_node_alt by metis next fix et n assume et_in_tg_ig: "et \<in> ET (TG IG1)" then have "src et \<in> NT (TG IG1)" using instance_graph.validity_type_graph first_instance_graph_valid type_graph.structure_edges_wellformed_alt by blast then have src_et_not_tg2: "src et \<notin> NT (TG IG2)" using combine_nodes_distinct by blast assume n_in_in_ig: "n \<in> N IG1 \<union> N IG2" assume "(type\<^sub>n n, src et) \<in> (inh (TG IG1) \<union> inh (TG IG2))\<^sup>+" then have "(type\<^sub>n n, src et) \<in> inh (TG IG1) \<union> inh (TG IG2)" using combine_nodes_distinct instance_graph.validity_type_graph using first_instance_graph_valid second_instance_graph_valid tg_combine_distinct_inh by blast then have type_in_inh_ig: "(type\<^sub>n n, src et) \<in> inh (TG IG1)" using UnE type_graph.structure_inheritance_wellformed_second_node second_instance_graph_valid using instance_graph.validity_type_graph src_et_not_tg2 by metis then have "type\<^sub>n n \<in> NT (TG IG1)" using first_instance_graph_valid instance_graph.validity_type_graph type_graph.structure_inheritance_wellformed_first_node by blast then have "type\<^sub>n n \<notin> NT (TG IG2)" using combine_nodes_distinct by blast then have "n \<notin> N IG2" using second_instance_graph_valid instance_graph.validity_node_typed by blast then have "n \<in> N IG1" using n_in_in_ig by simp then show "card {e \<in> E IG1. src e = n \<and> type\<^sub>e e = et} in m_out (mult (TG IG1) et)" using type_in_inh_ig et_in_tg_ig first_instance_graph_valid instance_graph.validity_outgoing_mult by simp next fix et n assume et_in_tg_ig: "et \<in> ET (TG IG2)" then have "src et \<in> NT (TG IG2)" using instance_graph.validity_type_graph second_instance_graph_valid type_graph.structure_edges_wellformed_alt by blast then have src_et_not_tg1: "src et \<notin> NT (TG IG1)" using combine_nodes_distinct by blast assume n_in_in_ig: "n \<in> N IG1 \<union> N IG2" assume "(type\<^sub>n n, src et) \<in> (inh (TG IG1) \<union> inh (TG IG2))\<^sup>+" then have "(type\<^sub>n n, src et) \<in> inh (TG IG1) \<union> inh (TG IG2)" using combine_nodes_distinct instance_graph.validity_type_graph using first_instance_graph_valid second_instance_graph_valid tg_combine_distinct_inh by blast then have type_in_inh_ig: "(type\<^sub>n n, src et) \<in> inh (TG IG2)" using UnE type_graph.structure_inheritance_wellformed_second_node first_instance_graph_valid using instance_graph.validity_type_graph src_et_not_tg1 by metis then have "type\<^sub>n n \<in> NT (TG IG2)" using second_instance_graph_valid instance_graph.validity_type_graph type_graph.structure_inheritance_wellformed_first_node by blast then have "type\<^sub>n n \<notin> NT (TG IG1)" using combine_nodes_distinct by blast then have "n \<notin> N IG1" using first_instance_graph_valid instance_graph.validity_node_typed by blast then have "n \<in> N IG2" using n_in_in_ig by simp then show "card {e \<in> E IG2. src e = n \<and> type\<^sub>e e = et} in m_out (mult (TG IG2) et)" using type_in_inh_ig et_in_tg_ig second_instance_graph_valid instance_graph.validity_outgoing_mult by simp next fix et n assume et_in_tg_ig: "et \<in> ET (TG IG1)" then have "tgt et \<in> NT (TG IG1)" using instance_graph.validity_type_graph first_instance_graph_valid type_graph.structure_edges_wellformed_alt by blast then have tgt_et_not_tg2: "tgt et \<notin> NT (TG IG2)" using combine_nodes_distinct by blast assume n_in_in_ig: "n \<in> N IG1 \<union> N IG2" assume "(type\<^sub>n n, tgt et) \<in> (inh (TG IG1) \<union> inh (TG IG2))\<^sup>+" then have "(type\<^sub>n n, tgt et) \<in> inh (TG IG1) \<union> inh (TG IG2)" using combine_nodes_distinct instance_graph.validity_type_graph using first_instance_graph_valid second_instance_graph_valid tg_combine_distinct_inh by blast then have type_in_inh_ig: "(type\<^sub>n n, tgt et) \<in> inh (TG IG1)" using UnE type_graph.structure_inheritance_wellformed_second_node second_instance_graph_valid using instance_graph.validity_type_graph tgt_et_not_tg2 by metis then have "type\<^sub>n n \<in> NT (TG IG1)" using first_instance_graph_valid instance_graph.validity_type_graph type_graph.structure_inheritance_wellformed_first_node by blast then have "type\<^sub>n n \<notin> NT (TG IG2)" using combine_nodes_distinct by blast then have "n \<notin> N IG2" using second_instance_graph_valid instance_graph.validity_node_typed by blast then have "n \<in> N IG1" using n_in_in_ig by simp then show "card {e \<in> E IG1. tgt e = n \<and> type\<^sub>e e = et} in m_in (mult (TG IG1) et)" using type_in_inh_ig et_in_tg_ig first_instance_graph_valid instance_graph.validity_ingoing_mult by simp next fix et n assume et_in_tg_ig: "et \<in> ET (TG IG2)" then have "tgt et \<in> NT (TG IG2)" using instance_graph.validity_type_graph second_instance_graph_valid type_graph.structure_edges_wellformed_alt by blast then have tgt_et_not_tg1: "tgt et \<notin> NT (TG IG1)" using combine_nodes_distinct by blast assume n_in_in_ig: "n \<in> N IG1 \<union> N IG2" assume "(type\<^sub>n n, tgt et) \<in> (inh (TG IG1) \<union> inh (TG IG2))\<^sup>+" then have "(type\<^sub>n n, tgt et) \<in> inh (TG IG1) \<union> inh (TG IG2)" using combine_nodes_distinct instance_graph.validity_type_graph using first_instance_graph_valid second_instance_graph_valid tg_combine_distinct_inh by blast then have type_in_inh_ig: "(type\<^sub>n n, tgt et) \<in> inh (TG IG2)" using UnE type_graph.structure_inheritance_wellformed_second_node first_instance_graph_valid using instance_graph.validity_type_graph tgt_et_not_tg1 by metis then have "type\<^sub>n n \<in> NT (TG IG2)" using second_instance_graph_valid instance_graph.validity_type_graph type_graph.structure_inheritance_wellformed_first_node by blast then have "type\<^sub>n n \<notin> NT (TG IG1)" using combine_nodes_distinct by blast then have "n \<notin> N IG1" using first_instance_graph_valid instance_graph.validity_node_typed by blast then have "n \<in> N IG2" using n_in_in_ig by simp then show "card {e \<in> E IG2. tgt e = n \<and> type\<^sub>e e = et} in m_in (mult (TG IG2) et)" using type_in_inh_ig et_in_tg_ig second_instance_graph_valid instance_graph.validity_ingoing_mult by simp next fix n assume "n \<in> N IG1 \<inter> N IG2" then have "type\<^sub>n n \<in> NT (TG IG1) \<inter> NT (TG IG2)" using first_instance_graph_valid second_instance_graph_valid instance_graph.validity_node_typed by blast then show "card {e \<in> E IG1 \<union> E IG2. tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG1) \<union> contains (TG IG2)} \<le> 1" using combine_nodes_distinct by simp next have irrefl_ig1: "irrefl ((edge_to_tuple ` {e \<in> E IG1. type\<^sub>e e \<in> contains (TG IG1)})\<^sup>+)" using first_instance_graph_valid instance_graph.validity_containment_alt' by blast have irrefl_ig2: "irrefl ((edge_to_tuple ` {e \<in> E IG2. type\<^sub>e e \<in> contains (TG IG2)})\<^sup>+)" using second_instance_graph_valid instance_graph.validity_containment_alt' by blast have "(edge_to_tuple ` {e \<in> E IG1. type\<^sub>e e \<in> contains (TG IG1)} \<union> edge_to_tuple ` {e \<in> E IG2. type\<^sub>e e \<in> contains (TG IG2)})\<^sup>+ = (edge_to_tuple ` {e \<in> E IG1. type\<^sub>e e \<in> contains (TG IG1)})\<^sup>+ \<union> (edge_to_tuple ` {e \<in> E IG2. type\<^sub>e e \<in> contains (TG IG2)})\<^sup>+" proof show "(edge_to_tuple ` {e \<in> E IG1. type\<^sub>e e \<in> contains (TG IG1)} \<union> edge_to_tuple ` {e \<in> E IG2. type\<^sub>e e \<in> contains (TG IG2)})\<^sup>+ \<subseteq> (edge_to_tuple ` {e \<in> E IG1. type\<^sub>e e \<in> contains (TG IG1)})\<^sup>+ \<union> (edge_to_tuple ` {e \<in> E IG2. type\<^sub>e e \<in> contains (TG IG2)})\<^sup>+" proof fix x assume "x \<in> (edge_to_tuple ` {e \<in> E IG1. type\<^sub>e e \<in> contains (TG IG1)} \<union> edge_to_tuple ` {e \<in> E IG2. type\<^sub>e e \<in> contains (TG IG2)})\<^sup>+" then show "x \<in> (edge_to_tuple ` {e \<in> E IG1. type\<^sub>e e \<in> contains (TG IG1)})\<^sup>+ \<union> (edge_to_tuple ` {e \<in> E IG2. type\<^sub>e e \<in> contains (TG IG2)})\<^sup>+" proof (induct x) case (Pair a b) then show ?case proof (induct) case (base y) then show ?case by blast next case (step y z) show ?case using step.hyps(3) proof (elim UnE) assume ay_in_containment_set: "(a, y) \<in> (edge_to_tuple ` {e \<in> E IG1. type\<^sub>e e \<in> contains (TG IG1)})\<^sup>+" then have "y \<in> N IG1" proof (induct) case (base m) then show ?case proof fix x assume x_in_set: "x \<in> {e \<in> E IG1. type\<^sub>e e \<in> contains (TG IG1)}" assume tuple_def: "(a, m) = edge_to_tuple x" show "m \<in> N IG1" using tuple_def x_in_set first_instance_graph_valid instance_graph.structure_edges_wellformed_tgt_node_alt by fastforce qed next case (step m n) show ?case using step.hyps(2) proof fix x assume x_in_set: "x \<in> {e \<in> E IG1. type\<^sub>e e \<in> contains (TG IG1)}" assume tuple_def: "(m, n) = edge_to_tuple x" show "n \<in> N IG1" using tuple_def x_in_set first_instance_graph_valid instance_graph.structure_edges_wellformed_tgt_node_alt by fastforce qed qed then have "type\<^sub>n y \<in> NT (TG IG1)" using first_instance_graph_valid instance_graph.validity_node_typed by blast then have "type\<^sub>n y \<notin> NT (TG IG2)" using combine_nodes_distinct by blast then have "y \<notin> N IG2" using second_instance_graph_valid instance_graph.validity_node_typed by blast then have "(y, z) \<notin> edge_to_tuple ` {e \<in> E IG2. type\<^sub>e e \<in> contains (TG IG2)}" using second_instance_graph_valid instance_graph.structure_edges_wellformed_src_node_alt by fastforce then have "(y, z) \<in> edge_to_tuple ` {e \<in> E IG1. type\<^sub>e e \<in> contains (TG IG1)}" using step.hyps(2) by simp then have "(a, z) \<in> (edge_to_tuple ` {e \<in> E IG1. type\<^sub>e e \<in> contains (TG IG1)})\<^sup>+" using ay_in_containment_set by simp then show ?thesis by simp next assume ay_in_containment_set: "(a, y) \<in> (edge_to_tuple ` {e \<in> E IG2. type\<^sub>e e \<in> contains (TG IG2)})\<^sup>+" then have "y \<in> N IG2" proof (induct) case (base m) then show ?case proof fix x assume x_in_set: "x \<in> {e \<in> E IG2. type\<^sub>e e \<in> contains (TG IG2)}" assume tuple_def: "(a, m) = edge_to_tuple x" show "m \<in> N IG2" using tuple_def x_in_set second_instance_graph_valid instance_graph.structure_edges_wellformed_tgt_node_alt by fastforce qed next case (step m n) show ?case using step.hyps(2) proof fix x assume x_in_set: "x \<in> {e \<in> E IG2. type\<^sub>e e \<in> contains (TG IG2)}" assume tuple_def: "(m, n) = edge_to_tuple x" show "n \<in> N IG2" using tuple_def x_in_set second_instance_graph_valid instance_graph.structure_edges_wellformed_tgt_node_alt by fastforce qed qed then have "type\<^sub>n y \<in> NT (TG IG2)" using second_instance_graph_valid instance_graph.validity_node_typed by blast then have "type\<^sub>n y \<notin> NT (TG IG1)" using combine_nodes_distinct by blast then have "y \<notin> N IG1" using first_instance_graph_valid instance_graph.validity_node_typed by blast then have "(y, z) \<notin> edge_to_tuple ` {e \<in> E IG1. type\<^sub>e e \<in> contains (TG IG1)}" using first_instance_graph_valid instance_graph.structure_edges_wellformed_src_node_alt by fastforce then have "(y, z) \<in> edge_to_tuple ` {e \<in> E IG2. type\<^sub>e e \<in> contains (TG IG2)}" using step.hyps(2) by simp then have "(a, z) \<in> (edge_to_tuple ` {e \<in> E IG2. type\<^sub>e e \<in> contains (TG IG2)})\<^sup>+" using ay_in_containment_set by simp then show ?thesis by simp qed qed qed qed next show "(edge_to_tuple ` {e \<in> E IG1. type\<^sub>e e \<in> contains (TG IG1)})\<^sup>+ \<union> (edge_to_tuple ` {e \<in> E IG2. type\<^sub>e e \<in> contains (TG IG2)})\<^sup>+ \<subseteq> (edge_to_tuple ` {e \<in> E IG1. type\<^sub>e e \<in> contains (TG IG1)} \<union> edge_to_tuple ` {e \<in> E IG2. type\<^sub>e e \<in> contains (TG IG2)})\<^sup>+" proof fix x assume "x \<in> (edge_to_tuple ` {e \<in> E IG1. type\<^sub>e e \<in> contains (TG IG1)})\<^sup>+ \<union> (edge_to_tuple ` {e \<in> E IG2. type\<^sub>e e \<in> contains (TG IG2)})\<^sup>+" then show "x \<in> (edge_to_tuple ` {e \<in> E IG1. type\<^sub>e e \<in> contains (TG IG1)} \<union> edge_to_tuple ` {e \<in> E IG2. type\<^sub>e e \<in> contains (TG IG2)})\<^sup>+" proof (elim UnE) assume "x \<in> (edge_to_tuple ` {e \<in> E IG1. type\<^sub>e e \<in> contains (TG IG1)})\<^sup>+" then show "x \<in> (edge_to_tuple ` {e \<in> E IG1. type\<^sub>e e \<in> contains (TG IG1)} \<union> edge_to_tuple ` {e \<in> E IG2. type\<^sub>e e \<in> contains (TG IG2)})\<^sup>+" proof (induct x) case (Pair a b) then show ?case proof (induct) case (base y) then show ?case by blast next case (step y z) then have "(a, z) \<in> (edge_to_tuple ` {e \<in> E IG1. type\<^sub>e e \<in> contains (TG IG1)})\<^sup>+" by simp then show ?case using step.hyps(2) step.hyps(3) by (simp add: trancl.trancl_into_trancl) qed qed next assume "x \<in> (edge_to_tuple ` {e \<in> E IG2. type\<^sub>e e \<in> contains (TG IG2)})\<^sup>+" then show "x \<in> (edge_to_tuple ` {e \<in> E IG1. type\<^sub>e e \<in> contains (TG IG1)} \<union> edge_to_tuple ` {e \<in> E IG2. type\<^sub>e e \<in> contains (TG IG2)})\<^sup>+" proof (induct x) case (Pair a b) then show ?case proof (induct) case (base y) then show ?case by blast next case (step y z) then have "(a, z) \<in> (edge_to_tuple ` {e \<in> E IG2. type\<^sub>e e \<in> contains (TG IG2)})\<^sup>+" by simp then show ?case using step.hyps(2) step.hyps(3) by (simp add: trancl.trancl_into_trancl) qed qed qed qed qed then show "irrefl ((edge_to_tuple ` {e \<in> E IG1. type\<^sub>e e \<in> contains (TG IG1)} \<union> edge_to_tuple ` {e \<in> E IG2. type\<^sub>e e \<in> contains (TG IG2)})\<^sup>+)" using irrefl_ig1 irrefl_ig2 by (simp add: irrefl_def) qed (simp_all add: assms) end
r=358.80 https://sandbox.dams.library.ucdavis.edu/fcrepo/rest/collection/sherry-lehmann/catalogs/d7bg69/media/images/d7bg69-022/svc:tesseract/full/full/358.80/default.jpg Accept:application/hocr+xml
<h1 style='font-size:4rem;color:red;'>Math 267 Project #3 --- Name ________________________. Student ID ____________________. Enter your name and studet ID in this cell. --- # Spring mass system. The second order equation of an unforced spring/mass system with mass m, damping constant b and spring constant k is given by:<p> $$ mx''(t) + bx'(t) +kx(t) = 0. $$ Recall that $x(t)$ represents the displacement of the mass from its resting position ( with x>0 the spring is stretched and x<0 the spring is compressed). Therefore the velocity of the moving mass is $ x'(t)$ and the acceleration is $x’’(t)$. To approximate the solution for this system using Euler’s method we convert the equation into a system by introducing the variable $$ y = x’.$$ So our two unknowns are: $x$ for the position of the mass and $y$ for the velocity of the mass. As a system the second order equation becomes ( using m = 1) \begin{align} x'(t) &= \; y(t) \\ y'(t) &= -k \cdot x(t) - b \cdot y(t) \end{align} and unlike the Predator-Prey model of exercise 2. this system is linear and can be represented in matrix notation: \begin{align} \begin{pmatrix} x'(t) \\ y'(t) \end{pmatrix}= \begin{pmatrix} 0 & 1 \\ -k & -b \end{pmatrix}\cdot \begin{pmatrix} x(t) \\ y(t) \end{pmatrix} \end{align} --- ### Collaboration. Students are allowed to work together on this project. Colaboration is encouraged. However you final submission must be your own work. ### Run the cell below to import the necessary libraries. ```python # import libraries import numpy as np import matplotlib.pyplot as plt from IPython.display import Image # uncomment the line below if you are running a macbook #%config InlineBackend.figure_format ='retina' ``` ## Exericse 1. For this exercise you will approximate the solution of an unforced mass-spring system with mass m =1, damping constant b = 1 and spring constant k = 2. The second order equation for this system is given by: $$x''(t) + 1x'(t) + 2x(t) = 0.$$ Use the initial conditions $x(0) = 0$ and $ x'(0)=y(0) = 1$. Use the improved Euler’s method to solve the system. You will need to convert the second order equation to a system as demonstrated above. Choose a Δt=h of 0.1 and a time interval of 12 seconds. Create two plots. One showing x(t) versus time and the second showing the solution curve "trajectory" for the system in the xy (phase) plane. ## Complete the code cell below to solve the sytstem. ```python # define the slope functions def f(x,y): return y def g(x,y): return -1*y -2*x h = 0.1 # set delta t t = np.arange(0,12,h) # Initialeze arrays to store the results. x = np.zeros_like(t) y = np.zeros_like(t) # Set initial conditions: x[0] = 0 y[0] = 1 # implement the Improved Euler's method # Your code goes here, look at project #2 ``` ### Execute the cell below to graph your results. You should see a damped sinusoid. ```python plt.figure(figsize=(8,5)) plt.plot(t,x) plt.grid() plt.xlabel('t') plt.ylabel('x'); plt.title("Damping b = 1"); ``` ### Execute the cell below to see the trajectory in the phase plane for this problem. You should see a spiral. ```python plt.figure(figsize=(8,5)) plt.plot(x,y,linewidth=2) plt.xlim(-1.5,1.5) plt.ylim(-1.5,1.5) plt.grid() plt.xlabel('x-displacement') plt.ylabel('y-velocity'); plt.title("Trajectory for spring mass system b = 1"); ``` ### Repeat the steps above for b=3 and b=0. Copy and paste cells above and make the necessary modifications. You should show time plots and phase plane plots for b=0 and b=3. ```python #Your code here ``` --- # Exercise 2. For this exercise you will approximate the solution of an undamped periodically forced spring-mass system with mass m =1 and spring constant k = 1, no damping. The second order equation for this system is given by: $$ x''(t) + x(t) = Cos(\omega t).$$ Use the initial conditions $x(0) = 0$ and $ x'(0) = y(0) = 0$. Use the improved Euler’s method to solve the system. Note this system is not autonomous so the slope functions could depend on x,y and t. Generate plots of $x(t)$ versus time for ω = 1.1 and ω = 1. Use a time interval of 50 seconds for $ \omega = 1 $ and 150 seconds for $ \omega = 1.1$. For both cases set Δt=0.1. Duplicate and modify the code above to generate the plots. Label the plots appropriately. There are no phase plane plots for Exercise 2. ```python #Your code here ``` ```python ``` ```python ``` ## Answer the questions below. Create a text cell to enter your answers. 1. Expain and discuss the results of exercise 1. 2. Compute the period of oscillation for exerice 1. b=0. Compare to value obtained from the graph. 3. Discuss the results of exercise 2. Hint: look at the envelopes. ```python ```
# Code for solving assuming that all other cars have a single identical behavior model mutable struct SingleBehaviorSolver <: Solver inner_solver::Solver behavior::BehaviorModel end mutable struct SingleBehaviorPolicy <: Policy inner_policy::Policy behavior::BehaviorModel end set_rng!(solver::SingleBehaviorSolver, rng::AbstractRNG) = set_rng!(solver.inner_solver, rng) srand(p::SingleBehaviorPolicy, s) = srand(p.inner_policy, s) function solve(solver::SingleBehaviorSolver, mdp::NoCrashProblem) dmodel = NoCrashIDMMOBILModel(mdp.dmodel, DiscreteBehaviorSet(BehaviorModel[solver.behavior], Weights([1.0]))) single_behavior_mdp = NoCrashMDP{typeof(mdp.rmodel), DiscreteBehaviorSet}(dmodel, mdp.rmodel, mdp.discount, mdp.throw) inner_policy = solve(solver.inner_solver, single_behavior_mdp) return SingleBehaviorPolicy(inner_policy, solver.behavior) end function action_info(p::SingleBehaviorPolicy, s::Union{MLPhysicalState, MLState}) as = actions(p.inner_policy.mdp, s) if length(as) == 1 return first(as), Dict(:tree_queries=>missing, :search_time_us=>missing) end return action_info(p.inner_policy, single_behavior_state(s, p.behavior)) end action_info(p::SingleBehaviorPolicy, agg::AggressivenessBelief) = action_info(p, agg.physical) action(p::SingleBehaviorPolicy, s) = first(action_info(p, s)) function single_behavior_state(s::Union{MLState, MLPhysicalState}, behavior) new_cars = Vector{CarState}(undef, length(s.cars)) for (i,c) in enumerate(s.cars) new_cars[i] = CarState(c.x, c.y, c.vel, c.lane_change, behavior, c.id) end return MLState(s, new_cars) end
//This code is under MIT licence, you can find the complete file here: https://github.com/kwiato88/WinApi/blob/master/LICENSE #include <windows.h> #include <algorithm> #include <commctrl.h> #include <boost/assign/list_of.hpp> #include "ListBoxDialog.hpp" #include "ListBoxDialogDef.h" #include "DialogMsgMatchers.hpp" #include "ContextMenu.hpp" #include "Clipboard.hpp" #include "StringConversion.hpp" namespace WinApi { namespace { class ItemAdder { public: ItemAdder(Handle p_list) { m_list = p_list; } void operator()(const std::string& p_item) { TCHAR l_itemString[1024]; stringToArray(p_item, l_itemString); SendMessage(m_list, LB_ADDSTRING, 0, (LPARAM)l_itemString); } private: Handle m_list; }; typedef int Pixel; Pixel getCharWidth() { return 9;/*TODO: get value from system. Try: GetDialogBaseUnits*/ } Pixel getWindowWidthUnit() { return getCharWidth()/4; } Pixel getListBoxBorderWidth() { return getWindowWidthUnit()*2; } Pixel getStringWidth(std::size_t p_lenght) { return getCharWidth()*p_lenght; } Pixel getWidthToDisplay(std::size_t p_stringLength) { return 2* getListBoxBorderWidth() + getStringWidth(p_stringLength); } struct StringLengthComparator { bool operator()(const std::string& p_lhs, const std::string& p_rhs) { return p_lhs.size() < p_rhs.size(); } }; } ListBoxDialog::ListBoxDialog( InstanceHandle p_hInstance, Handle p_parentparentWindow, const std::string& p_name, const std::string& p_itemCopySeparator) : Dialog(p_hInstance, p_parentparentWindow, ResourceId(ID_LIST_BOX_DIALOG), p_name), m_selectedItemIndex(-1), itemsSeparator(p_itemCopySeparator) { registerHandler(MsgMatchers::ButtonClick(IDOK), std::bind(&ListBoxDialog::onOkClick, this)); registerHandler(MsgMatchers::ButtonClick(IDCANCEL), std::bind(&ListBoxDialog::onCancleClick, this)); registerHandler(MsgMatchers::MsgCodeAndValue(ID_LIST_BOX, LBN_SELCHANGE), std::bind(&ListBoxDialog::onListUpdate, this)); registerHandler(MsgMatchers::MsgCodeAndValue(ID_LIST_BOX, LBN_DBLCLK), std::bind(&ListBoxDialog::onListDoubleClick, this)); } void ListBoxDialog::onInit() { setListBoxItems(); setListBoxHorizontalScroll(); setFocusOnListBox(); } Handle ListBoxDialog::getListBoxHandle() const { return getItem(ResourceId(ID_LIST_BOX)); } void ListBoxDialog::setFocusOnListBox() { SetFocus(getListBoxHandle()); } void ListBoxDialog::setListBoxHorizontalScroll() { std::size_t l_itemsMaxLength = std::max_element(m_items.begin(), m_items.end(), StringLengthComparator())->size(); SendMessage(getListBoxHandle(), LB_SETHORIZONTALEXTENT, getWidthToDisplay(l_itemsMaxLength), 0); } void ListBoxDialog::setListBoxItems() { std::for_each(m_items.begin(), m_items.end(), ItemAdder(getListBoxHandle())); } void ListBoxDialog::onOkClick() { close(RESULT_OK); } void ListBoxDialog::onCancleClick() { m_selectedItemIndex = -1; close(RESULT_CANCEL); } void ListBoxDialog::onListUpdate() { m_selectedItemIndex = (int)SendMessage(getListBoxHandle(), LB_GETCURSEL, 0, 0); } void ListBoxDialog::onListDoubleClick() { onListUpdate(); close(RESULT_OK); } int ListBoxDialog::getSelectedItemIndex() const { return m_selectedItemIndex; } void ListBoxDialog::setItems(const std::vector<std::string>& p_items) { m_items = p_items; } bool ListBoxDialog::showContextMenu(int p_xPos, int p_yPos) { ContextMenu menu(m_self); menu.add(ContextMenu::Item{ "Copy table", std::bind(&ListBoxDialog::copyAll, this) }); menu.add(ContextMenu::Item{ "Copy selected row", std::bind(&ListBoxDialog::copySelected, this) }); menu.show(p_xPos, p_yPos); return true; } void ListBoxDialog::copyAll() const { std::string out; for (const auto& row : m_items) out += row + itemsSeparator; Clipboard::set(Clipboard::String(out)); } void ListBoxDialog::copySelected() const { auto selected = (int)SendMessage(getListBoxHandle(), LB_GETCURSEL, 0, 0); if (selected < m_items.size()) Clipboard::set(Clipboard::String(m_items[selected] + itemsSeparator)); } } // namespace WinApi
State Before: l : List Bool hl : Chain' (fun x x_1 => x ≠ x_1) l b : Bool ⊢ 2 * count b l = if Even (length l) then length l else if (some b == head? l) = true then length l + 1 else length l - 1 State After: case pos l : List Bool hl : Chain' (fun x x_1 => x ≠ x_1) l b : Bool h2 : Even (length l) ⊢ 2 * count b l = if Even (length l) then length l else if (some b == head? l) = true then length l + 1 else length l - 1 case neg l : List Bool hl : Chain' (fun x x_1 => x ≠ x_1) l b : Bool h2 : ¬Even (length l) ⊢ 2 * count b l = if Even (length l) then length l else if (some b == head? l) = true then length l + 1 else length l - 1 Tactic: by_cases h2 : Even (length l) State Before: case pos l : List Bool hl : Chain' (fun x x_1 => x ≠ x_1) l b : Bool h2 : Even (length l) ⊢ 2 * count b l = if Even (length l) then length l else if (some b == head? l) = true then length l + 1 else length l - 1 State After: no goals Tactic: rw [if_pos h2, hl.two_mul_count_bool_of_even h2] State Before: case neg l : List Bool hl : Chain' (fun x x_1 => x ≠ x_1) l b : Bool h2 : ¬Even (length l) ⊢ 2 * count b l = if Even (length l) then length l else if (some b == head? l) = true then length l + 1 else length l - 1 State After: case neg.nil b : Bool hl : Chain' (fun x x_1 => x ≠ x_1) [] h2 : ¬Even (length []) ⊢ 2 * count b [] = if Even (length []) then length [] else if (some b == head? []) = true then length [] + 1 else length [] - 1 case neg.cons b x : Bool l : List Bool hl : Chain' (fun x x_1 => x ≠ x_1) (x :: l) h2 : ¬Even (length (x :: l)) ⊢ 2 * count b (x :: l) = if Even (length (x :: l)) then length (x :: l) else if (some b == head? (x :: l)) = true then length (x :: l) + 1 else length (x :: l) - 1 Tactic: cases' l with x l State Before: case neg.cons b x : Bool l : List Bool hl : Chain' (fun x x_1 => x ≠ x_1) (x :: l) h2 : ¬Even (length (x :: l)) ⊢ 2 * count b (x :: l) = if Even (length (x :: l)) then length (x :: l) else if (some b == head? (x :: l)) = true then length (x :: l) + 1 else length (x :: l) - 1 State After: case neg.cons b x : Bool l : List Bool hl : Chain' (fun x x_1 => x ≠ x_1) (x :: l) h2 : ¬Even (length (x :: l)) ⊢ (2 * count b l + 2 * if b = x then 1 else 0) = if (some b == some x) = true then length (x :: l) + 1 else length (x :: l) - 1 Tactic: simp only [if_neg h2, count_cons', mul_add, head?, Option.mem_some_iff, @eq_comm _ x] State Before: case neg.cons b x : Bool l : List Bool hl : Chain' (fun x x_1 => x ≠ x_1) (x :: l) h2 : ¬Even (length (x :: l)) ⊢ (2 * count b l + 2 * if b = x then 1 else 0) = if (some b == some x) = true then length (x :: l) + 1 else length (x :: l) - 1 State After: case neg.cons b x : Bool l : List Bool hl : Chain' (fun x x_1 => x ≠ x_1) (x :: l) h2 : Even (length l) ⊢ (2 * count b l + 2 * if b = x then 1 else 0) = if (some b == some x) = true then length (x :: l) + 1 else length (x :: l) - 1 Tactic: rw [length_cons, Nat.even_add_one, not_not] at h2 State Before: case neg.cons b x : Bool l : List Bool h2 : Even (length l) hl : Chain' (fun x x_1 => x ≠ x_1) l ⊢ (2 * count b l + 2 * if b = x then 1 else 0) = if (some b == some x) = true then length (x :: l) + 1 else length (x :: l) - 1 State After: case neg.cons b x : Bool l : List Bool h2 : Even (length l) hl : Chain' (fun x x_1 => x ≠ x_1) l ⊢ (length l + 2 * if b = x then 1 else 0) = if (some b == some x) = true then length (x :: l) + 1 else length (x :: l) - 1 Tactic: rw [hl.two_mul_count_bool_of_even h2] State Before: case neg.cons b x : Bool l : List Bool h2 : Even (length l) hl : Chain' (fun x x_1 => x ≠ x_1) l ⊢ (length l + 2 * if b = x then 1 else 0) = if (some b == some x) = true then length (x :: l) + 1 else length (x :: l) - 1 State After: no goals Tactic: cases b <;> cases x <;> split_ifs <;> simp <;> contradiction State Before: case neg.nil b : Bool hl : Chain' (fun x x_1 => x ≠ x_1) [] h2 : ¬Even (length []) ⊢ 2 * count b [] = if Even (length []) then length [] else if (some b == head? []) = true then length [] + 1 else length [] - 1 State After: no goals Tactic: exact (h2 even_zero).elim
section \<open>Data\<close> text \<open>This theory defines the data types and notations, and some preliminary results about them.\<close> theory Data imports Main begin subsection \<open>Function notations\<close> abbreviation \<epsilon> :: "'a \<rightharpoonup> 'b" where "\<epsilon> \<equiv> \<lambda>x. None" fun combine :: "('a \<rightharpoonup> 'b) \<Rightarrow> ('a \<rightharpoonup> 'b) \<Rightarrow> ('a \<rightharpoonup> 'b)" ("_;;_" 20) where "(f ;; g) x = (if g x = None then f x else g x)" lemma dom_combination_dom_union: "dom (\<tau>;;\<tau>') = dom \<tau> \<union> dom \<tau>'" by auto subsection \<open>Values, expressions and execution contexts\<close> datatype const = Unit | F | T datatype (RID\<^sub>V: 'r, LID\<^sub>V: 'l,'v) val = CV const | Var 'v | Loc 'l | Rid 'r | Lambda 'v "('r,'l,'v) expr" and (RID\<^sub>E: 'r, LID\<^sub>E: 'l,'v) expr = VE "('r,'l,'v) val" | Apply "('r,'l,'v) expr" "('r,'l,'v) expr" | Ite "('r,'l,'v) expr" "('r,'l,'v) expr" "('r,'l,'v) expr" | Ref "('r,'l,'v) expr" | Read "('r,'l,'v) expr" | Assign "('r,'l,'v) expr" "('r,'l,'v) expr" | Rfork "('r,'l,'v) expr" | Rjoin "('r,'l,'v) expr" datatype (RID\<^sub>C: 'r, LID\<^sub>C: 'l,'v) cntxt = Hole ("\<box>") | ApplyL\<^sub>\<E> "('r,'l,'v) cntxt" "('r,'l,'v) expr" | ApplyR\<^sub>\<E> "('r,'l,'v) val" "('r,'l,'v) cntxt" | Ite\<^sub>\<E> "('r,'l,'v) cntxt" "('r,'l,'v) expr" "('r,'l,'v) expr" | Ref\<^sub>\<E> "('r,'l,'v) cntxt" | Read\<^sub>\<E> "('r,'l,'v) cntxt" | AssignL\<^sub>\<E> "('r,'l,'v) cntxt" "('r,'l,'v) expr" | AssignR\<^sub>\<E> 'l "('r,'l,'v) cntxt" | Rjoin\<^sub>\<E> "('r,'l,'v) cntxt" subsection \<open>Plugging and decomposing\<close> fun plug :: "('r,'l,'v) cntxt \<Rightarrow> ('r,'l,'v) expr \<Rightarrow> ('r,'l,'v) expr" (infix "\<lhd>" 60) where "\<box> \<lhd> e = e" | "ApplyL\<^sub>\<E> \<E> e1 \<lhd> e = Apply (\<E> \<lhd> e) e1" | "ApplyR\<^sub>\<E> val \<E> \<lhd> e = Apply (VE val) (\<E> \<lhd> e)" | "Ite\<^sub>\<E> \<E> e1 e2 \<lhd> e = Ite (\<E> \<lhd> e) e1 e2" | "Ref\<^sub>\<E> \<E> \<lhd> e = Ref (\<E> \<lhd> e)" | "Read\<^sub>\<E> \<E> \<lhd> e = Read (\<E> \<lhd> e)" | "AssignL\<^sub>\<E> \<E> e1 \<lhd> e = Assign (\<E> \<lhd> e) e1" | "AssignR\<^sub>\<E> l \<E> \<lhd> e = Assign (VE (Loc l)) (\<E> \<lhd> e)" | "Rjoin\<^sub>\<E> \<E> \<lhd> e = Rjoin (\<E> \<lhd> e)" translations "\<E>[x]" \<rightleftharpoons> "\<E> \<lhd> x" lemma injective_cntxt [simp]: "(\<E>[e1] = \<E>[e2]) = (e1 = e2)" by (induction \<E>) auto lemma VE_empty_cntxt [simp]: "(VE v = \<E>[e]) = (\<E> = \<box> \<and> VE v = e)" by (cases \<E>, auto) inductive redex :: "('r,'l,'v) expr \<Rightarrow> bool" where app: "redex (Apply (VE (Lambda x e)) (VE v))" | iteTrue: "redex (Ite (VE (CV T)) e1 e2)" | iteFalse: "redex (Ite (VE (CV F)) e1 e2)" | ref: "redex (Ref (VE v))" | read: "redex (Read (VE (Loc l)))" | assign: "redex (Assign (VE (Loc l)) (VE v))" | rfork: "redex (Rfork e)" | rjoin: "redex (Rjoin (VE (Rid r)))" inductive_simps redex_simps [simp]: "redex e" inductive_cases redexE [elim]: "redex e" lemma plugged_redex_not_val [simp]: "redex r \<Longrightarrow> (\<E> \<lhd> r) \<noteq> (VE t)" by (cases \<E>) auto inductive decompose :: "('r,'l,'v) expr \<Rightarrow> ('r,'l,'v) cntxt \<Rightarrow> ('r,'l,'v) expr \<Rightarrow> bool" where top_redex: "redex e \<Longrightarrow> decompose e \<box> e" | lapply: "\<lbrakk> \<not>redex (Apply e\<^sub>1 e\<^sub>2); decompose e\<^sub>1 \<E> r \<rbrakk> \<Longrightarrow> decompose (Apply e\<^sub>1 e\<^sub>2) (ApplyL\<^sub>\<E> \<E> e\<^sub>2) r" | rapply: "\<lbrakk> \<not>redex (Apply (VE v) e); decompose e \<E> r \<rbrakk> \<Longrightarrow> decompose (Apply (VE v) e) (ApplyR\<^sub>\<E> v \<E>) r" | ite: "\<lbrakk> \<not>redex (Ite e\<^sub>1 e\<^sub>2 e\<^sub>3); decompose e\<^sub>1 \<E> r \<rbrakk> \<Longrightarrow> decompose (Ite e\<^sub>1 e\<^sub>2 e\<^sub>3) (Ite\<^sub>\<E> \<E> e\<^sub>2 e\<^sub>3) r" | ref: "\<lbrakk> \<not>redex (Ref e); decompose e \<E> r \<rbrakk> \<Longrightarrow> decompose (Ref e) (Ref\<^sub>\<E> \<E>) r" | read: "\<lbrakk> \<not>redex (Read e); decompose e \<E> r \<rbrakk> \<Longrightarrow> decompose (Read e) (Read\<^sub>\<E> \<E>) r" | lassign: "\<lbrakk> \<not>redex (Assign e\<^sub>1 e\<^sub>2); decompose e\<^sub>1 \<E> r \<rbrakk> \<Longrightarrow> decompose (Assign e\<^sub>1 e\<^sub>2) (AssignL\<^sub>\<E> \<E> e\<^sub>2) r" | rassign: "\<lbrakk> \<not>redex (Assign (VE (Loc l)) e\<^sub>2); decompose e\<^sub>2 \<E> r \<rbrakk> \<Longrightarrow> decompose (Assign (VE (Loc l)) e\<^sub>2) (AssignR\<^sub>\<E> l \<E>) r" | rjoin: "\<lbrakk> \<not>redex (Rjoin e); decompose e \<E> r \<rbrakk> \<Longrightarrow> decompose (Rjoin e) (Rjoin\<^sub>\<E> \<E>) r" inductive_cases decomposeE [elim]: "decompose e \<E> r" lemma plug_decomposition_equivalence: "redex r \<Longrightarrow> decompose e \<E> r = (\<E>[r] = e)" proof (rule iffI) assume x: "decompose e \<E> r" show "\<E>[r] = e" proof (use x in \<open>induct rule: decompose.induct\<close>) case (top_redex e) thus "\<box>[e] = e" by simp next case (lapply e\<^sub>1 e\<^sub>2 \<E> r) have "(ApplyL\<^sub>\<E> \<E> e\<^sub>2) [r] = Apply (\<E>[r]) e\<^sub>2" by simp also have "... = Apply e\<^sub>1 e\<^sub>2" using \<open>\<E>[r] = e\<^sub>1\<close> by simp then show ?case by simp qed simp+ next assume red: "redex r" and eq: "\<E>[r] = e" have "decompose (\<E>[r]) \<E> r" by (induct \<E>) (use red in \<open>auto intro: decompose.intros\<close>) thus "decompose e \<E> r" by (simp add: eq) qed lemma unique_decomposition: "decompose e \<E>\<^sub>1 r\<^sub>1 \<Longrightarrow> decompose e \<E>\<^sub>2 r\<^sub>2 \<Longrightarrow> \<E>\<^sub>1 = \<E>\<^sub>2 \<and> r\<^sub>1 = r\<^sub>2" by (induct arbitrary: \<E>\<^sub>2 rule: decompose.induct) auto lemma completion_eq [simp]: assumes red_e: "redex r" and red_e': "redex r'" shows "(\<E>[r] = \<E>'[r']) = (\<E> = \<E>' \<and> r = r')" proof (rule iffI) show "\<E>[r] = \<E>'[r'] \<Longrightarrow> \<E> = \<E>' \<and> r = r'" proof (rule conjI) assume eq: "\<E>[r] = \<E>'[r']" have "decompose (\<E>[r]) \<E> r" using plug_decomposition_equivalence red_e by blast hence fst_decomp:"decompose (\<E>'[r']) \<E> r" by (simp add: eq) have snd_decomp: "decompose (\<E>'[r']) \<E>' r'" using plug_decomposition_equivalence red_e' by blast show cntxts_eq: "\<E> = \<E>'" using fst_decomp snd_decomp unique_decomposition by blast show "r = r'" using cntxts_eq eq by simp qed qed simp subsection \<open>Stores and states\<close> type_synonym ('r,'l,'v) store = "'l \<rightharpoonup> ('r,'l,'v) val" type_synonym ('r,'l,'v) local_state = "('r,'l,'v) store \<times> ('r,'l,'v) store \<times> ('r,'l,'v) expr" type_synonym ('r,'l,'v) global_state = "'r \<rightharpoonup> ('r,'l,'v) local_state" fun doms :: "('r,'l,'v) local_state \<Rightarrow> 'l set" where "doms (\<sigma>,\<tau>,e) = dom \<sigma> \<union> dom \<tau>" fun LID_snapshot :: "('r,'l,'v) local_state \<Rightarrow> ('r,'l,'v) store" ("_\<^sub>\<sigma>" 200) where "LID_snapshot (\<sigma>,\<tau>,e) = \<sigma>" fun LID_local_store :: "('r,'l,'v) local_state \<Rightarrow> ('r,'l,'v) store" ("_\<^sub>\<tau>" 200) where "LID_local_store (\<sigma>,\<tau>,e) = \<tau>" fun LID_expression :: "('r,'l,'v) local_state \<Rightarrow> ('r,'l,'v) expr" ("_\<^sub>e" 200) where "LID_expression (\<sigma>,\<tau>,e) = e" end
from __future__ import print_function import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.distributions as D from torch.autograd import Variable from helpers.utils import same_type, long_type class GumbelSoftmax(nn.Module): def __init__(self, config, dim=-1): """ Gumbel Softmax reparameterization of Categorical distribution. :param config: argparse :param dim: dim to operate over :returns: GumberlSoftmax object :rtype: nn.Module """ super(GumbelSoftmax, self).__init__() self.is_discrete = True self._setup_anneal_params() self.dim = dim self.iteration = 0 self.config = config self.input_size = self.config['discrete_size'] self.output_size = self.config['discrete_size'] def prior_params(self, batch_size, **kwargs): """ Helper to get prior parameters :param batch_size: the size of the batch :returns: a dictionary of parameters :rtype: dict """ uniform_probs = same_type(self.config['half'], self.config['cuda'])( batch_size, self.output_size).zero_() uniform_probs += 1.0 / self.output_size return { 'discrete': { 'logits': D.OneHotCategorical(probs=uniform_probs).logits } } def prior_distribution(self, batch_size, **kwargs): """ get a torch distrbiution prior :param batch_size: size of the prior :returns: uniform categorical :rtype: torch.distribution """ params = self.prior_params(batch_size, **kwargs) return D.OneHotCategorical(logits=params['discrete']['logits']) def prior(self, batch_size, **kwargs): """ Sample the prior for batch_size samples. :param batch_size: number of prior samples. :returns: prior :rtype: torch.Tensor """ cat = self.prior_distribution(batch_size, **kwargs) return cat.sample() def get_reparameterizer_scalars(self): """ Returns any scalars used in reparameterization. :returns: dict of scalars :rtype: dict """ return {'tau_scalar': self.tau} def _setup_anneal_params(self): """ Setup the base gumbel rates. TODO: needs parameterization in argparse. :returns: None :rtype: None """ self.tau, self.tau0 = 1.0, 1.0 self.anneal_rate = 3e-6 self.min_temp = 0.5 def anneal(self, anneal_interval=10): """ Helper to anneal the temperature. :param anneal_interval: the interval to employ annealing. :returns: None :rtype: None """ if self.training \ and self.iteration > 0 \ and self.iteration % anneal_interval == 0: # smoother annealing rate = -self.anneal_rate * self.iteration self.tau = np.maximum(self.tau0 * np.exp(rate), self.min_temp) # hard annealing # self.tau = np.maximum(0.9 * self.tau, self.min_temp) def reparmeterize(self, logits): """ Given logits reparameterize to a categorical :param logits: unactivated logits :returns: reparameterized tensor (if training), hard version, soft version. :rtype: torch.Tensor, torch.Tensor, torch.Tensor """ logits_shp = logits.size() log_q_z = F.log_softmax(logits.clone(), dim=self.dim) z, z_hard = self.sample_gumbel(logits, self.tau, hard=True, dim=self.dim, use_cuda=logits.is_cuda) return z.view(logits_shp), z_hard.view(logits_shp), log_q_z def mutual_info_analytic(self, params, eps=1e-9): """ I(z_d; x) ~ H(z_prior, z_d) + H(z_prior), i.e. analytic version. :param params: parameters of distribution :param eps: tolerance :returns: batch_size mutual information (prop-to) tensor. :rtype: torch.Tensor """ targets = torch.argmax( F.softmax(params['discrete']['logits'], -1), dim=-1 ).type(long_type(self.config['cuda'])) crossent_loss = F.cross_entropy(input=params['q_z_given_xhat']['discrete']['logits'], target=targets, reduce=False) ent_loss = -torch.sum(D.OneHotCategorical(logits=params['discrete']['z_hard']).entropy(), -1) return ent_loss + crossent_loss def mutual_info_monte_carlo(self, params, eps=1e-9): """ I(z_d; x) ~ H(z_prior, z_d) + H(z_prior) but does the single-sample monte-carlo approximation of it. :param params: parameters of distribution :param eps: tolerance :returns: batch_size mutual information (prop-to) tensor. :rtype: torch.Tensor """ log_q_z_given_x_hat = params['q_z_given_xhat']['discrete']['log_q_z'] p_z = F.softmax(params['discrete']['logits'], dim=-1) crossent_loss = torch.sum(p_z * log_q_z_given_x_hat, dim=-1) ent_loss = -torch.sum(p_z * params['discrete']['log_q_z'], dim=-1) return ent_loss + crossent_loss def mutual_info(self, params, eps=1e-9): """ Returns Ent + xent where xent is taken against hard targets. :param params: distribution parameters :param eps: tolerance :returns: batch_size tensor of mutual info :rtype: torch.Tensor """ return self.config['discrete_mut_info']*self.mutual_info_monte_carlo(params) targets = torch.argmax(params['q_z_given_xhat']['discrete']['z_hard'].type( long_type(self.config['cuda'])), dim=-1) # soft_targets = F.softmax( # params['discrete']['logits'], -1 # ).type(long_type(self.config['cuda'])) # targets = torch.argmax(params['discrete']['log_q_z'], -1) # 3rd change, havent tried # crossent_loss = -F.cross_entropy(input=params['q_z_given_xhat']['discrete']['logits'], crossent_loss = -F.cross_entropy(input=params['discrete']['logits'], target=targets, reduce=False) # ent_loss = -torch.sum(D.OneHotCategorical(logits=params['discrete']['z_hard']).entropy(), -1) # ent_loss = torch.sum(D.OneHotCategorical(logits=params['discrete']['z_hard']).entropy(), -1) # print('xent = ', crossent_loss.shape, " |ent = ", ent_loss.shape) ent_loss = -torch.sum(D.OneHotCategorical(logits=params['discrete']['logits']).entropy(), -1) return -self.config['discrete_mut_info'] * (ent_loss + crossent_loss) # return self.config['discrete_mut_info'] * crossent_loss # def mutual_info(self, params, eps=1e-9): # """ Returns Ent + xent where xent is taken against hard targets. # :param params: distribution parameters # :param eps: tolerance # :returns: batch_size tensor of mutual info # :rtype: torch.Tensor # """ # targets = torch.argmax(params['discrete']['z_hard'].type(long_type(self.config['cuda'])), dim=-1) # # soft_targets = F.softmax( # # params['discrete']['logits'], -1 # # ).type(long_type(self.config['cuda'])) # # targets = torch.argmax(params['discrete']['log_q_z'], -1) # 3rd change, havent tried # crossent_loss = -F.cross_entropy(input=params['q_z_given_xhat']['discrete']['logits'], # target=targets, reduce=False) # ent_loss = -torch.sum(D.OneHotCategorical(logits=params['discrete']['z_hard']).entropy(), -1) # return self.config['discrete_mut_info'] * (ent_loss + crossent_loss) @staticmethod def _kld_categorical_uniform(log_q_z, dim=-1, eps=1e-9): """ KL divergence against a uniform categorical prior :param log_q_z: the soft logits :param dim: which dim to operate over :param eps: tolerance :returns: tensor of batch_size :rtype: torch.Tensor """ shp = log_q_z.size() p_z = 1.0 / shp[dim] log_p_z = np.log(p_z) kld_element = log_q_z.exp() * (log_q_z - log_p_z) return kld_element @staticmethod def _kl_tf_version(a, b): ''' nn_ops.softmax(a.logits)*(nn_ops.log_softmax(a.logits) - nn_ops.log_softmax(b.logits)) ''' return F.softmax(a.logits, dim=-1)*(F.log_softmax(a.logits, dim=-1) - F.log_softmax(b.logits, dim=-1)) def kl(self, dist_a, prior=None): """ KL divergence of dist_a against a prior, if none then Cat(1/k) :param dist_a: the distribution parameters :param prior: prior parameters (or None) :returns: batch_size kl-div tensor :rtype: torch.Tensor """ if prior is None: # use standard uniform prior # return torch.sum(GumbelSoftmax._kld_categorical_uniform( # dist_a['discrete']['log_q_z'], dim=self.dim # ), -1) prior = D.OneHotCategorical(logits=dist_a['discrete']['log_q_z']) return torch.sum(GumbelSoftmax._kl_tf_version( D.OneHotCategorical(logits=dist_a['discrete']['log_q_z']), prior ), -1) # we have two distributions provided (eg: VRNN) return torch.sum(GumbelSoftmax._kl_tf_version( D.OneHotCategorical(logits=dist_a['discrete']['log_q_z']), # D.OneHotCategorical(prior['discrete']['log_q_z']) D.OneHotCategorical(logits=prior['discrete']['log_q_z']) ), -1) @staticmethod def _gumbel_softmax(x, tau, eps=1e-9, dim=-1, use_cuda=False): """ Internal gumbel softmax call using temp tau: -ln(-ln(U + eps) + eps) :param x: input tensor :param tau: temperature :param eps: toleranace :param dim: dimension to operate over :param use_cuda: whether or not to use cuda :returns: gumbel annealed tensor :rtype: torch.Tensor """ noise = torch.rand(x.size()) noise.add_(eps).log_().neg_() noise.add_(eps).log_().neg_() if use_cuda: noise = noise.cuda() noise = Variable(noise) x = (x + noise) / tau x = F.softmax(x + eps, dim=dim) return x.view_as(x) @staticmethod def sample_gumbel(x, tau, hard=False, dim=-1, use_cuda=False): """ Sample from the gumbel distribution and return hard and soft versions. :param x: the input tensor :param tau: temperature :param hard: whether to generate hard version (argmax) :param dim: dimension to operate over :param use_cuda: whether or not to use cuda :returns: soft, hard or soft, None :rtype: torch.Tensor, Optional(torch.Tensor, None) """ y = GumbelSoftmax._gumbel_softmax(x, tau, dim=dim, use_cuda=use_cuda) if hard: y_max, _ = torch.max(y, dim=dim, keepdim=True) y_hard = Variable( torch.eq(y_max.data, y.data).type(x.dtype) ) y_hard_diff = y_hard - y y_hard = y_hard_diff.detach() + y return y.view_as(x), y_hard.view_as(x) return y.view_as(x), None def log_likelihood(self, z, params): """ Log-likelihood of z induced under params. :param z: inferred latent z :param params: the params of the distribution :returns: log-likelihood :rtype: torch.Tensor """ return D.OneHotCategorical(logits=params['discrete']['logits']).log_prob(z) def forward(self, logits, force=False): """ Returns a reparameterized categorical and it's params. NOTE: annealing doesn't take place if testing (even with force=True). :param logits: unactivated logits. :returns: reparam tensor and params. :rtype: torch.Tensor, dict """ self.anneal() # anneal first z, z_hard, log_q_z = self.reparmeterize(logits) params = { 'z_hard': z_hard, 'logits': logits, 'log_q_z': log_q_z, 'tau_scalar': self.tau } self.iteration += 1 if self.training or force: # return the reparameterization # and the params of gumbel return z, {'z': z, 'discrete': params} return z_hard, {'z': z, 'discrete': params}
State Before: R : Type u_1 inst✝⁹ : Ring R E : Type u_2 inst✝⁸ : AddCommGroup E inst✝⁷ : Module R E F : Type ?u.23402 inst✝⁶ : AddCommGroup F inst✝⁵ : Module R F G : Type ?u.23918 inst✝⁴ : AddCommGroup G inst✝³ : Module R G p q : Submodule R E S : Type ?u.24881 inst✝² : Semiring S M : Type ?u.24887 inst✝¹ : AddCommMonoid M inst✝ : Module S M m : Submodule S M f : E →ₗ[R] { x // x ∈ p } hf : ∀ (x : { x // x ∈ p }), ↑f ↑x = x ⊢ IsCompl p (ker f) State After: case disjoint R : Type u_1 inst✝⁹ : Ring R E : Type u_2 inst✝⁸ : AddCommGroup E inst✝⁷ : Module R E F : Type ?u.23402 inst✝⁶ : AddCommGroup F inst✝⁵ : Module R F G : Type ?u.23918 inst✝⁴ : AddCommGroup G inst✝³ : Module R G p q : Submodule R E S : Type ?u.24881 inst✝² : Semiring S M : Type ?u.24887 inst✝¹ : AddCommMonoid M inst✝ : Module S M m : Submodule S M f : E →ₗ[R] { x // x ∈ p } hf : ∀ (x : { x // x ∈ p }), ↑f ↑x = x ⊢ Disjoint p (ker f) case codisjoint R : Type u_1 inst✝⁹ : Ring R E : Type u_2 inst✝⁸ : AddCommGroup E inst✝⁷ : Module R E F : Type ?u.23402 inst✝⁶ : AddCommGroup F inst✝⁵ : Module R F G : Type ?u.23918 inst✝⁴ : AddCommGroup G inst✝³ : Module R G p q : Submodule R E S : Type ?u.24881 inst✝² : Semiring S M : Type ?u.24887 inst✝¹ : AddCommMonoid M inst✝ : Module S M m : Submodule S M f : E →ₗ[R] { x // x ∈ p } hf : ∀ (x : { x // x ∈ p }), ↑f ↑x = x ⊢ Codisjoint p (ker f) Tactic: constructor State Before: case disjoint R : Type u_1 inst✝⁹ : Ring R E : Type u_2 inst✝⁸ : AddCommGroup E inst✝⁷ : Module R E F : Type ?u.23402 inst✝⁶ : AddCommGroup F inst✝⁵ : Module R F G : Type ?u.23918 inst✝⁴ : AddCommGroup G inst✝³ : Module R G p q : Submodule R E S : Type ?u.24881 inst✝² : Semiring S M : Type ?u.24887 inst✝¹ : AddCommMonoid M inst✝ : Module S M m : Submodule S M f : E →ₗ[R] { x // x ∈ p } hf : ∀ (x : { x // x ∈ p }), ↑f ↑x = x ⊢ Disjoint p (ker f) State After: case disjoint R : Type u_1 inst✝⁹ : Ring R E : Type u_2 inst✝⁸ : AddCommGroup E inst✝⁷ : Module R E F : Type ?u.23402 inst✝⁶ : AddCommGroup F inst✝⁵ : Module R F G : Type ?u.23918 inst✝⁴ : AddCommGroup G inst✝³ : Module R G p q : Submodule R E S : Type ?u.24881 inst✝² : Semiring S M : Type ?u.24887 inst✝¹ : AddCommMonoid M inst✝ : Module S M m : Submodule S M f : E →ₗ[R] { x // x ∈ p } hf : ∀ (x : { x // x ∈ p }), ↑f ↑x = x ⊢ p ⊓ ker f ≤ ⊥ Tactic: rw [disjoint_iff_inf_le] State Before: case disjoint R : Type u_1 inst✝⁹ : Ring R E : Type u_2 inst✝⁸ : AddCommGroup E inst✝⁷ : Module R E F : Type ?u.23402 inst✝⁶ : AddCommGroup F inst✝⁵ : Module R F G : Type ?u.23918 inst✝⁴ : AddCommGroup G inst✝³ : Module R G p q : Submodule R E S : Type ?u.24881 inst✝² : Semiring S M : Type ?u.24887 inst✝¹ : AddCommMonoid M inst✝ : Module S M m : Submodule S M f : E →ₗ[R] { x // x ∈ p } hf : ∀ (x : { x // x ∈ p }), ↑f ↑x = x ⊢ p ⊓ ker f ≤ ⊥ State After: case disjoint.intro R : Type u_1 inst✝⁹ : Ring R E : Type u_2 inst✝⁸ : AddCommGroup E inst✝⁷ : Module R E F : Type ?u.23402 inst✝⁶ : AddCommGroup F inst✝⁵ : Module R F G : Type ?u.23918 inst✝⁴ : AddCommGroup G inst✝³ : Module R G p q : Submodule R E S : Type ?u.24881 inst✝² : Semiring S M : Type ?u.24887 inst✝¹ : AddCommMonoid M inst✝ : Module S M m : Submodule S M f : E →ₗ[R] { x // x ∈ p } hf : ∀ (x : { x // x ∈ p }), ↑f ↑x = x x : E hpx : x ∈ ↑p hfx : x ∈ ↑(ker f) ⊢ x ∈ ⊥ Tactic: rintro x ⟨hpx, hfx⟩ State Before: case disjoint.intro R : Type u_1 inst✝⁹ : Ring R E : Type u_2 inst✝⁸ : AddCommGroup E inst✝⁷ : Module R E F : Type ?u.23402 inst✝⁶ : AddCommGroup F inst✝⁵ : Module R F G : Type ?u.23918 inst✝⁴ : AddCommGroup G inst✝³ : Module R G p q : Submodule R E S : Type ?u.24881 inst✝² : Semiring S M : Type ?u.24887 inst✝¹ : AddCommMonoid M inst✝ : Module S M m : Submodule S M f : E →ₗ[R] { x // x ∈ p } hf : ∀ (x : { x // x ∈ p }), ↑f ↑x = x x : E hpx : x ∈ ↑p hfx : x ∈ ↑(ker f) ⊢ x ∈ ⊥ State After: case disjoint.intro R : Type u_1 inst✝⁹ : Ring R E : Type u_2 inst✝⁸ : AddCommGroup E inst✝⁷ : Module R E F : Type ?u.23402 inst✝⁶ : AddCommGroup F inst✝⁵ : Module R F G : Type ?u.23918 inst✝⁴ : AddCommGroup G inst✝³ : Module R G p q : Submodule R E S : Type ?u.24881 inst✝² : Semiring S M : Type ?u.24887 inst✝¹ : AddCommMonoid M inst✝ : Module S M m : Submodule S M f : E →ₗ[R] { x // x ∈ p } hf : ∀ (x : { x // x ∈ p }), ↑f ↑x = x x : E hpx : x ∈ ↑p hfx : x = 0 ⊢ x ∈ ⊥ Tactic: erw [SetLike.mem_coe, mem_ker, hf ⟨x, hpx⟩, mk_eq_zero] at hfx State Before: case disjoint.intro R : Type u_1 inst✝⁹ : Ring R E : Type u_2 inst✝⁸ : AddCommGroup E inst✝⁷ : Module R E F : Type ?u.23402 inst✝⁶ : AddCommGroup F inst✝⁵ : Module R F G : Type ?u.23918 inst✝⁴ : AddCommGroup G inst✝³ : Module R G p q : Submodule R E S : Type ?u.24881 inst✝² : Semiring S M : Type ?u.24887 inst✝¹ : AddCommMonoid M inst✝ : Module S M m : Submodule S M f : E →ₗ[R] { x // x ∈ p } hf : ∀ (x : { x // x ∈ p }), ↑f ↑x = x x : E hpx : x ∈ ↑p hfx : x = 0 ⊢ x ∈ ⊥ State After: no goals Tactic: simp only [hfx, SetLike.mem_coe, zero_mem] State Before: case codisjoint R : Type u_1 inst✝⁹ : Ring R E : Type u_2 inst✝⁸ : AddCommGroup E inst✝⁷ : Module R E F : Type ?u.23402 inst✝⁶ : AddCommGroup F inst✝⁵ : Module R F G : Type ?u.23918 inst✝⁴ : AddCommGroup G inst✝³ : Module R G p q : Submodule R E S : Type ?u.24881 inst✝² : Semiring S M : Type ?u.24887 inst✝¹ : AddCommMonoid M inst✝ : Module S M m : Submodule S M f : E →ₗ[R] { x // x ∈ p } hf : ∀ (x : { x // x ∈ p }), ↑f ↑x = x ⊢ Codisjoint p (ker f) State After: case codisjoint R : Type u_1 inst✝⁹ : Ring R E : Type u_2 inst✝⁸ : AddCommGroup E inst✝⁷ : Module R E F : Type ?u.23402 inst✝⁶ : AddCommGroup F inst✝⁵ : Module R F G : Type ?u.23918 inst✝⁴ : AddCommGroup G inst✝³ : Module R G p q : Submodule R E S : Type ?u.24881 inst✝² : Semiring S M : Type ?u.24887 inst✝¹ : AddCommMonoid M inst✝ : Module S M m : Submodule S M f : E →ₗ[R] { x // x ∈ p } hf : ∀ (x : { x // x ∈ p }), ↑f ↑x = x ⊢ ⊤ ≤ p ⊔ ker f Tactic: rw [codisjoint_iff_le_sup] State Before: case codisjoint R : Type u_1 inst✝⁹ : Ring R E : Type u_2 inst✝⁸ : AddCommGroup E inst✝⁷ : Module R E F : Type ?u.23402 inst✝⁶ : AddCommGroup F inst✝⁵ : Module R F G : Type ?u.23918 inst✝⁴ : AddCommGroup G inst✝³ : Module R G p q : Submodule R E S : Type ?u.24881 inst✝² : Semiring S M : Type ?u.24887 inst✝¹ : AddCommMonoid M inst✝ : Module S M m : Submodule S M f : E →ₗ[R] { x // x ∈ p } hf : ∀ (x : { x // x ∈ p }), ↑f ↑x = x ⊢ ⊤ ≤ p ⊔ ker f State After: case codisjoint R : Type u_1 inst✝⁹ : Ring R E : Type u_2 inst✝⁸ : AddCommGroup E inst✝⁷ : Module R E F : Type ?u.23402 inst✝⁶ : AddCommGroup F inst✝⁵ : Module R F G : Type ?u.23918 inst✝⁴ : AddCommGroup G inst✝³ : Module R G p q : Submodule R E S : Type ?u.24881 inst✝² : Semiring S M : Type ?u.24887 inst✝¹ : AddCommMonoid M inst✝ : Module S M m : Submodule S M f : E →ₗ[R] { x // x ∈ p } hf : ∀ (x : { x // x ∈ p }), ↑f ↑x = x x : E a✝ : x ∈ ⊤ ⊢ x ∈ p ⊔ ker f Tactic: intro x _ State Before: case codisjoint R : Type u_1 inst✝⁹ : Ring R E : Type u_2 inst✝⁸ : AddCommGroup E inst✝⁷ : Module R E F : Type ?u.23402 inst✝⁶ : AddCommGroup F inst✝⁵ : Module R F G : Type ?u.23918 inst✝⁴ : AddCommGroup G inst✝³ : Module R G p q : Submodule R E S : Type ?u.24881 inst✝² : Semiring S M : Type ?u.24887 inst✝¹ : AddCommMonoid M inst✝ : Module S M m : Submodule S M f : E →ₗ[R] { x // x ∈ p } hf : ∀ (x : { x // x ∈ p }), ↑f ↑x = x x : E a✝ : x ∈ ⊤ ⊢ x ∈ p ⊔ ker f State After: case codisjoint R : Type u_1 inst✝⁹ : Ring R E : Type u_2 inst✝⁸ : AddCommGroup E inst✝⁷ : Module R E F : Type ?u.23402 inst✝⁶ : AddCommGroup F inst✝⁵ : Module R F G : Type ?u.23918 inst✝⁴ : AddCommGroup G inst✝³ : Module R G p q : Submodule R E S : Type ?u.24881 inst✝² : Semiring S M : Type ?u.24887 inst✝¹ : AddCommMonoid M inst✝ : Module S M m : Submodule S M f : E →ₗ[R] { x // x ∈ p } hf : ∀ (x : { x // x ∈ p }), ↑f ↑x = x x : E a✝ : x ∈ ⊤ ⊢ ∃ y z, ↑y + ↑z = x Tactic: rw [mem_sup'] State Before: case codisjoint R : Type u_1 inst✝⁹ : Ring R E : Type u_2 inst✝⁸ : AddCommGroup E inst✝⁷ : Module R E F : Type ?u.23402 inst✝⁶ : AddCommGroup F inst✝⁵ : Module R F G : Type ?u.23918 inst✝⁴ : AddCommGroup G inst✝³ : Module R G p q : Submodule R E S : Type ?u.24881 inst✝² : Semiring S M : Type ?u.24887 inst✝¹ : AddCommMonoid M inst✝ : Module S M m : Submodule S M f : E →ₗ[R] { x // x ∈ p } hf : ∀ (x : { x // x ∈ p }), ↑f ↑x = x x : E a✝ : x ∈ ⊤ ⊢ ∃ y z, ↑y + ↑z = x State After: case codisjoint R : Type u_1 inst✝⁹ : Ring R E : Type u_2 inst✝⁸ : AddCommGroup E inst✝⁷ : Module R E F : Type ?u.23402 inst✝⁶ : AddCommGroup F inst✝⁵ : Module R F G : Type ?u.23918 inst✝⁴ : AddCommGroup G inst✝³ : Module R G p q : Submodule R E S : Type ?u.24881 inst✝² : Semiring S M : Type ?u.24887 inst✝¹ : AddCommMonoid M inst✝ : Module S M m : Submodule S M f : E →ₗ[R] { x // x ∈ p } hf : ∀ (x : { x // x ∈ p }), ↑f ↑x = x x : E a✝ : x ∈ ⊤ ⊢ x - ↑(↑f x) ∈ ker f Tactic: refine' ⟨f x, ⟨x - f x, _⟩, add_sub_cancel'_right _ _⟩ State Before: case codisjoint R : Type u_1 inst✝⁹ : Ring R E : Type u_2 inst✝⁸ : AddCommGroup E inst✝⁷ : Module R E F : Type ?u.23402 inst✝⁶ : AddCommGroup F inst✝⁵ : Module R F G : Type ?u.23918 inst✝⁴ : AddCommGroup G inst✝³ : Module R G p q : Submodule R E S : Type ?u.24881 inst✝² : Semiring S M : Type ?u.24887 inst✝¹ : AddCommMonoid M inst✝ : Module S M m : Submodule S M f : E →ₗ[R] { x // x ∈ p } hf : ∀ (x : { x // x ∈ p }), ↑f ↑x = x x : E a✝ : x ∈ ⊤ ⊢ x - ↑(↑f x) ∈ ker f State After: no goals Tactic: rw [mem_ker, LinearMap.map_sub, hf, sub_self]
lemma sets_image_in_sets: assumes N: "space N = X" assumes f: "f \<in> measurable N M" shows "sets (vimage_algebra X f M) \<subseteq> sets N"
module m_BC_and_Halo use m_TypeDef use m_Parameters use decomp_2d use m_Variables,only: mb1,hi1,hi_uxPrSrc,hi_uyPrSrc,hi_uzPrSrc implicit none private public:: SetBC_and_UpdateHalo,SetBC_and_UpdateHaloForPrSrc,SetBC_and_UpdateHalo_pr contains !****************************************************************** ! SetBC_and_UpdateHalo !****************************************************************** subroutine SetBC_and_UpdateHalo(ux,uy,uz,uy_ym) implicit none real(RK),dimension(mb1%xmm:mb1%xpm,mb1%ymm:mb1%ypm,mb1%zmm:mb1%zpm),intent(inout)::ux,uy,uz real(RK),dimension(ystart(1):yend(1),ystart(3):yend(3)),intent(in)::uy_ym ! locals integer::ic,kc ! yp-dir SELECT CASE(BcOption(yp_dir)) CASE(BC_NSLIP) do kc=ystart(3),yend(3) do ic=ystart(1),yend(1) ux(ic,nyp, kc) = uxBcValue(yp_dir)*two -ux(ic, nyc, kc) uy(ic,nyp, kc) = uyBcValue(yp_dir) uy(ic,nyp+1,kc) = uyBcValue(yp_dir)*two -uy(ic, nyc, kc) uz(ic,nyp, kc) = uzBcValue(yp_dir)*two -uz(ic, nyc, kc) enddo enddo CASE(BC_FSLIP) do kc=ystart(3),yend(3) do ic=ystart(1),yend(1) ux(ic, nyp, kc) = ux(ic, nyc, kc) uy(ic, nyp, kc) = zero uy(ic, nyp+1,kc) =-uy(ic, nyc, kc) uz(ic, nyp, kc) = uz(ic, nyc, kc) enddo enddo END SELECT ! ym-dir SELECT CASE(BcOption(ym_dir)) CASE(BC_NSLIP) do kc=ystart(3),yend(3) do ic=ystart(1),yend(1) ux(ic, 0, kc) = uxBcValue(ym_dir)*two-ux(ic, 1, kc) uy(ic, 1, kc) = uy_ym(ic,kc) uy(ic, 0, kc) = uy_ym(ic,kc)*two -uy(ic,2,kc) uz(ic, 0, kc) = uzBcValue(ym_dir)*two-uz(ic, 1, kc) enddo enddo CASE(BC_FSLIP) do kc=ystart(3),yend(3) do ic=ystart(1),yend(1) ux(ic, 0, kc) = ux(ic, 1, kc) uy(ic, 1, kc) = zero uy(ic, 0, kc) =-uy(ic, 2, kc) uz(ic, 0, kc) = uz(ic, 1, kc) enddo enddo END SELECT ! xp-dir SELECT CASE(myProcNghBC(y_pencil, 3)) CASE(BC_NSLIP) ux(nxp, 0:nyp,ystart(3):yend(3))= uxBcValue(xp_dir) ux(nxp+1,0:nyp,ystart(3):yend(3))= uxBcValue(xp_dir)*two -ux(nxc, 0:nyp,ystart(3):yend(3)) uy(nxp, 0:nyp,ystart(3):yend(3))= uyBcValue(xp_dir)*two -uy(nxc, 0:nyp,ystart(3):yend(3)) uz(nxp, 0:nyp,ystart(3):yend(3))= uzBcValue(xp_dir)*two -uz(nxc, 0:nyp,ystart(3):yend(3)) CASE(BC_FSLIP) ux(nxp, 0:nyp,ystart(3):yend(3))= zero ux(nxp+1,0:nyp,ystart(3):yend(3))=-ux(nxc, 0:nyp,ystart(3):yend(3)) uy(nxp, 0:nyp,ystart(3):yend(3))= uy(nxc, 0:nyp,ystart(3):yend(3)) uz(nxp, 0:nyp,ystart(3):yend(3))= uz(nxc, 0:nyp,ystart(3):yend(3)) END SELECT ! xm-dir SELECT CASE(myProcNghBC(y_pencil, 4)) CASE(BC_NSLIP) ux(1,0:nyp,ystart(3):yend(3)) = uxBcValue(xm_dir) ux(0,0:nyp,ystart(3):yend(3)) = uxBcValue(xm_dir)*two -ux(2,0:nyp,ystart(3):yend(3)) uy(0,0:nyp,ystart(3):yend(3)) = uyBcValue(xm_dir)*two -uy(1,0:nyp,ystart(3):yend(3)) uz(0,0:nyp,ystart(3):yend(3)) = uzBcValue(xm_dir)*two -uz(1,0:nyp,ystart(3):yend(3)) CASE(BC_FSLIP) ux(1,0:nyp,ystart(3):yend(3)) = zero ux(0,0:nyp,ystart(3):yend(3)) =-ux(2,0:nyp,ystart(3):yend(3)) uy(0,0:nyp,ystart(3):yend(3)) = uy(1,0:nyp,ystart(3):yend(3)) uz(0,0:nyp,ystart(3):yend(3)) = uz(1,0:nyp,ystart(3):yend(3)) END SELECT ! zp-dir SELECT CASE(myProcNghBC(y_pencil, 1)) CASE(BC_NSLIP) ux(ystart(1):yend(1), 0:nyp, nzp ) = uxBcValue(zp_dir)*two -ux(ystart(1):yend(1), 0:nyp, nzc) uy(ystart(1):yend(1), 0:nyp, nzp ) = uyBcValue(zp_dir)*two -uy(ystart(1):yend(1), 0:nyp, nzc) uz(ystart(1):yend(1), 0:nyp, nzp ) = uzBcValue(zp_dir) uz(ystart(1):yend(1), 0:nyp, nzp+1) = uzBcValue(zp_dir)*two -uz(ystart(1):yend(1), 0:nyp, nzc) CASE(BC_FSLIP) ux(ystart(1):yend(1), 0:nyp, nzp ) = ux(ystart(1):yend(1), 0:nyp, nzc) uy(ystart(1):yend(1), 0:nyp, nzp ) = uy(ystart(1):yend(1), 0:nyp, nzc) uz(ystart(1):yend(1), 0:nyp, nzp ) = zero uz(ystart(1):yend(1), 0:nyp, nzp+1) =-uz(ystart(1):yend(1), 0:nyp, nzc) END SELECT ! zm-dir SELECT CASE(myProcNghBC(y_pencil, 2)) CASE(BC_NSLIP) ux(ystart(1):yend(1), 0:nyp, 0) = uxBcValue(zm_dir)*two -ux(ystart(1):yend(1), 0:nyp, 1) uy(ystart(1):yend(1), 0:nyp, 0) = uyBcValue(zm_dir)*two -uy(ystart(1):yend(1), 0:nyp, 1) uz(ystart(1):yend(1), 0:nyp, 1) = uzBcValue(zm_dir) uz(ystart(1):yend(1), 0:nyp, 0) = uzBcValue(zm_dir)*two -uz(ystart(1):yend(1), 0:nyp, 2) CASE(BC_FSLIP) ux(ystart(1):yend(1), 0:nyp, 0) = ux(ystart(1):yend(1), 0:nyp, 1) uy(ystart(1):yend(1), 0:nyp, 0) = uy(ystart(1):yend(1), 0:nyp, 1) uz(ystart(1):yend(1), 0:nyp, 1) = zero uz(ystart(1):yend(1), 0:nyp, 0) =-uz(ystart(1):yend(1), 0:nyp, 2) END SELECT ! update halo call myupdate_halo(ux, mb1, hi1) call myupdate_halo(uy, mb1, hi1) call myupdate_halo(uz, mb1, hi1) end subroutine SetBC_and_UpdateHalo !****************************************************************** ! SetBC_and_UpdateHaloForPrSrc !****************************************************************** subroutine SetBC_and_UpdateHaloForPrSrc(ux,uy,uz,uy_ym) implicit none real(RK),dimension(mb1%xmm:mb1%xpm,mb1%ymm:mb1%ypm,mb1%zmm:mb1%zpm),intent(inout)::ux,uy,uz real(RK),dimension(ystart(1):yend(1),ystart(3):yend(3)),intent(in)::uy_ym ! locals integer::ic,kc ! yp-dir SELECT CASE(BcOption(yp_dir)) CASE(BC_NSLIP) do kc=ystart(3),yend(3) do ic=ystart(1),yend(1) uy(ic,nyp, kc) = uyBcValue(yp_dir) enddo enddo CASE(BC_FSLIP) do kc=ystart(3),yend(3) do ic=ystart(1),yend(1) uy(ic, nyp, kc) = zero enddo enddo END SELECT ! ym-dir SELECT CASE(BcOption(ym_dir)) CASE(BC_NSLIP) do kc=ystart(3),yend(3) do ic=ystart(1),yend(1) uy(ic, 1, kc) = uy_ym(ic,kc) enddo enddo CASE(BC_FSLIP) do kc=ystart(3),yend(3) do ic=ystart(1),yend(1) uy(ic, 1, kc) = zero enddo enddo END SELECT ! xp-dir SELECT CASE(myProcNghBC(y_pencil, 3)) CASE(BC_NSLIP) ux(nxp, 0:nyp,ystart(3):yend(3))= uxBcValue(xp_dir) CASE(BC_FSLIP) ux(nxp, 0:nyp,ystart(3):yend(3))= zero END SELECT ! xm-dir SELECT CASE(myProcNghBC(y_pencil, 4)) CASE(BC_NSLIP) ux(1,0:nyp,ystart(3):yend(3)) = uxBcValue(xm_dir) CASE(BC_FSLIP) ux(1,0:nyp,ystart(3):yend(3)) = zero END SELECT ! zp-dir SELECT CASE(myProcNghBC(y_pencil, 1)) CASE(BC_NSLIP) uz(ystart(1):yend(1), 0:nyp, nzp ) = uzBcValue(zp_dir) CASE(BC_FSLIP) uz(ystart(1):yend(1), 0:nyp, nzp ) = zero END SELECT ! zm-dir SELECT CASE(myProcNghBC(y_pencil, 2)) CASE(BC_NSLIP) uz(ystart(1):yend(1), 0:nyp, 1) = uzBcValue(zm_dir) CASE(BC_FSLIP) uz(ystart(1):yend(1), 0:nyp, 1) = zero END SELECT ! update halo call myupdate_halo(ux, mb1, hi_uxPrSrc) call myupdate_halo(uy, mb1, hi_uyPrSrc) call myupdate_halo(uz, mb1, hi_uzPrSrc) end subroutine SetBC_and_UpdateHaloForPrSrc !****************************************************************** ! SetBC_and_UpdateHalo_pr !****************************************************************** subroutine SetBC_and_UpdateHalo_pr(pressure) implicit none real(RK),dimension(mb1%xmm:mb1%xpm,mb1%ymm:mb1%ypm,mb1%zmm:mb1%zpm),intent(inout)::pressure ! locals integer::ic,kc ! yp-dir SELECT CASE(BcOption(yp_dir)) CASE(BC_NSLIP, BC_FSLIP) do kc=ystart(3),yend(3) do ic=ystart(1),yend(1) pressure(ic, nyp, kc) = pressure(ic, nyc, kc) enddo enddo END SELECT ! ym-dir SELECT CASE(BcOption(ym_dir)) CASE(BC_NSLIP, BC_FSLIP) do kc=ystart(3),yend(3) do ic=ystart(1),yend(1) pressure(ic, 0, kc) = pressure(ic, 1, kc) enddo enddo END SELECT ! xp-dir SELECT CASE(myProcNghBC(y_pencil, 3)) CASE(BC_NSLIP, BC_FSLIP) pressure(nxp, 0:nyp,ystart(3):yend(3)) = pressure(nxc, 0:nyp,ystart(3):yend(3)) END SELECT ! xm-dir SELECT CASE(myProcNghBC(y_pencil, 4)) CASE(BC_NSLIP, BC_FSLIP) pressure(0,0:nyp,ystart(3):yend(3)) = pressure(1,0:nyp,ystart(3):yend(3)) END SELECT ! zp-dir SELECT CASE(myProcNghBC(y_pencil, 1)) CASE(BC_NSLIP, BC_FSLIP) pressure(ystart(1):yend(1), 0:nyp, nzp) = pressure(ystart(1):yend(1), 0:nyp, nzc) END SELECT ! zm-dir SELECT CASE(myProcNghBC(y_pencil, 2)) CASE(BC_NSLIP, BC_FSLIP) pressure(ystart(1):yend(1), 0:nyp, 0) = pressure(ystart(1):yend(1), 0:nyp, 1) END SELECT call myupdate_halo(pressure, mb1, hi1) end subroutine SetBC_and_UpdateHalo_pr end module m_BC_and_Halo
\section{$\mathbf{X}=\mathbf{W}\mathbf{H}$ Non-Negative Matrix Factorization} Non-Negative Matrix Factorization (NNMF) is an approximate decomposition technique for positive data. It can be used, for example, for dimensionality reduction, blind source detection or topic extraction. The reputation is that it can often generate decompositions that are "sparse and meaningful". Following the convention in \citeasnoun{gillis2014nonnegative}, it works by expressing a positive data matrix $\mathbf{X}\in\mathbb{R}^{p\times n}_+$ in terms of two smaller positive matrices $\mathbf{W}\in\mathbb{R}_+^{p\times r}$ and $\mathbf{H}\in \mathbb{R}^{r\times n}_+$. Here the $n$ columns of the data matrix are data points and the rows are the $p$ features. An excellent introduction to NNMF is found in \possessivecite{morningpaper2019nnmf} blog post and in \citeasnoun{gillis2014nonnegative}. Dimensionality reduction derives from the ability to adjust the rank of the decomposition via the dimension $r$. The decomposition is simply: \begin{equation} \mathbf{X} \approx \mathbf{WH} \end{equation} Where the error $||\mathbf{X} - \mathbf{WH}||_\alpha$ is minimized with respect to some norm (normally, the Frobenius norm with $\alpha=2$). The decomposition allows the interpretation of $\mathbf{W} \in \mathbb{R}^{p\times r}$ as a matrix with a number of $r$ $p$-dimensional strictly positive basis vectors and of $\mathbf{H} \in \mathbb{R}^{r\times n}$ as a matrix of coefficients that express the $n$ data points in terms of linear sums of the $r$ basis vectors with strictly positive coefficients. One might ask: why NNMF when I can create linear decompositions of my data with SVD and PCA? After all, these techniques are well established and are known to give the optimal approximation under the Frobenius nurm. In my perception, the key difference is that NNMF solves the constrained problem of forcing both coefficients and basis vectors to be strictly positive. For many data types, negative values (word frequencies, pixel values) are unnatural, and so the results of NNMF are immediately more interpretable. NNMF is promising in particular in situations where a signal arises from the addition of a number of positive signals. A canonical example is hyperspectral imaging, where, assuming incoherent light, the measured spectrum is the linear sum of the spectra of the individual light sources. If all goes well, the basis vectors from NNMF of a hyperspectral image will be the source spectra. In the context of natural language processing, NNMF on a collection of documents can be interpreted as \textit{topics}. Figure \ref{fig:nnmf_eigenfaces} shows the NNMF-based decomposition and approximation of the "labeled faces in the wild" dataset, analogous to the SVD of the dataset shown in Figure \ref{fig:svd_eigenfaces}. The two are quite different. While for SVD, the faces look as if they are gradually coming into focus, for NNMF the faces are at first not recognizable. The portraits also become brighter in the plot as more basis components are added, because, in contrast to the SVD case, the composition is purely additive. The drawback is that NNMF is computationally more difficult (possibly NP hard), nor is the matrix approximation optimal, nor is the decomposition unique. \begin{figure} \centering \includegraphics[width=\textwidth]{nnmf_eigenfaces.png} \caption{Left: The first 34 basis faces stored in the $\mathbf{W}$ matrix extracted using NNMF under Frobenius norm from the "Labeled Faces in the Wild" Dataset. The basis images are normalized and shown on a log scale because they have very different contrast and brightness. The normalized images are then all shown on the same color scale. Right: Five sample portraits from the dataset approximated using different numbers of basis faces. The NNMF was done for a value of $r=300$. The original portraits had $2914$ pixels. In contrast to SVD, the basis vectors obtained through NNMF do not necessarily have an internal ordering in terms of how much of the variance in the dataset they explain.} \label{fig:nnmf_eigenfaces} \end{figure} \begin{figure} \centering \includegraphics[width=\textwidth]{nnmf_eigenfaces2.png} \caption{Left: The first 6 basis faces stored in the $\mathbf{W}$ matrix extracted using NNMF under Frobenius norm from the "Labeled Faces in the Wild" Dataset. Right: Sample images expressed in the reduced basis.} \label{fig:nnmf_eigenfaces2} \end{figure}
# Script to extract temperatures from set. complete for Rodger # March 18th, 2016 # Michelle Greenlaw p = bio.snowcrab::load.environment() set = snowcrab.db( DS ="set.clean", p=p ) head(set) set.t.2015 = set[which(set$yr == '2015'),] head(set.t.2015) extract = c('trip', 'set', 'station', 'lon', 'lat', 'timestamp', 'julian', 'yr', 't', 'tsd', 'z', 'zsd' ) set.t.2015 = set.t.2015[, extract] set.t.2015$z = exp(set.t.2015$z) set.t.2015$zsd = exp(set.t.2015$zsd) head(set.t.2015) outdir = file.path( "~", "tmp" ) fn = file.path( outdir, "SnowCrabTemperature2015.csv" ) write.table(set.t.2015, file=fn, sep = ",", col.names = TRUE, row.names=F)
\section{Mathematical Preliminaries} \subsection{Directed Graph} A directed graph $\mathcal{G}$, consists of a pair of finite sets, $(\emph{V},\emph{E})$. The elements of $\emph{V}$ are the vertices and the elements of $\emph{E}$ are the edges. An edge is a set formed by pairs of vertices. Further to this, there is a function, $\tau$, that associates an ordered pair of vertices for each edge in $\emph{E}$. The direction of an edge $\emph{e} = \{v_1, v_2\}$, is said to be $\tau(\emph{e}) = (v_1, v_2)$, where $\tau_{1}(e) = v_1$ is the source vertex and $\tau_{2}(e) = v_2$ is the target vertex. With our definitions, there comes a constraint for the function $\tau$. \begin{itemize} \item There are no self-loops, that is for each $\emph{e} \in \emph{E}$, if $\tau(\emph{e}) = (v_1, v_2)$ then $v_1 \neq v_2$. \end{itemize} There may exist neurons that are reciprocally connected, that is, there may be edges whereby we have $\emph{e}, \emph{e}^\prime \in \emph{E}$ such that $\tau(\emph{e})=(v_1,v_2)$ and $\tau(\emph{e}^\prime) = (v_2,v_1)$. A vertex $\emph{v} \in \mathcal{G}$ is said to be a sink if there exists no $\emph{e} \in \emph{E}$ such that $\emph{v}=\tau_1(\emph{e})$, but there is at least one edge $\emph{e}^\prime \in \emph{E}$ such that $\tau_2(\emph{e}^\prime) = \emph{v}$. Similarly, \emph{v} is said to be a source if there exists no $\emph{e} \in \emph{E}$ such that $\emph{v} = \tau_2(\emph{e})$, but there is at least one $\emph{e}^\prime \in \emph{E}$ such that $\tau_1(\emph{e}^\prime) = \emph{v}$. A path in a directed graph consists of a sequence of edges $(e_1, e_2, ..., e_n)$ such that for all $1 \leq k \leq n$, the target of $e_k$ is $e_{k+1}$, i.e.~$\tau_2(\emph{e}_k) = \tau_1(\emph{e}_{k+1})$. The length of the path $(e_1, e_2, ..., e_n)$ is n. If the target of $e_n$ is the source of $e_1$, that is $\tau_2(\emph{e}_n) = \tau_1(\emph{e}_1)$, then $(e_1, ..., e_n)$ is an oriented cycle. A directed graph that contains no oriented cycle is said to be acyclic. A directed graph is said to be fully connected if for every pair of distinct vertices, there exists a path from one to the other, in at least one direction. \subsection{Simplices} The singular of simplices is simplex. A simplex is a generalisation of the notion of a point, a line, a triangle up to some arbitrary dimension. The simplex is named as such since it is the simplest possible polytope in any given space. We have, for example, the following possible simplices: \begin{itemize} \item A 0 simplex which consists of a vertex. \item A 1 simplex which consists of two vertices and an edge with direction. \item A 2 simplex which consists of three vertices and three edges all having direction. There is also a clear source and a clear sink. An example is given below. \item A 3 simplex consists of 4 vertices and 6 edges all having direction and where we have a clear source and a clear sink. \end{itemize} To generalise this, a k-simplex is the convex hull of the k+1 vertices it contains \cite{2018}. \begin{figure}[H]% \centering \captionsetup{justification=centering} \subfloat[\centering 0 Simplex]{{\includegraphics[width=3cm]{graph/0simplex.png} }}% \qquad \subfloat[\centering 1 Simplex]{{\includegraphics[width=3cm]{graph/1simplex.png} }}% \qquad \subfloat[\centering 2 Simplex]{{\includegraphics[width=3cm]{graph/2simplex.png} }}% \qquad \subfloat[\centering 3 Simplex]{{\includegraphics[width=3cm]{graph/3simplex.png} }}% \caption{Simplices from dimension 0 through to 3}% \label{fig:example}% \end{figure} \subsection{Simplicial Complex} An abstract simplicial complex $\emph{S}$, is a collection of finite sets. These sets are closed under taking subsets, that is, every subset of a set in the family is also in the family. As an example, in a 2 dimensional simplicial complex, we have triangles, which are sets of size 3, their edges, which are sets of size 2 and their vertices which are sets of size 1 \cite{2008Gregarxiv:0809.4221}. However, we have a slight variation on this in that we have an abstract $\emph{directed}$ simplicial complex. This is where we again have a collection of sets denoted $\emph{S}$. However, this time, the sets are finite and ordered with the property that if $\sigma \in \emph{S}$, then every subset $\tau$ of $\sigma$, with the natural ordering inherited from $\sigma$, is also a member of $\emph{S}$. The elements $\sigma$ of a simplicial complex, as mentioned before, are simplices. The set of all simplices of $\emph{S}$ is denoted $\emph{S}_n$. A simplex $\tau$ is said to be a face of $\sigma$ if $\tau$ is a subset of $\sigma$ with a strictly smaller cardinality than $\sigma$. As an example, lets take Figure 3(c). This shows a simplex $\sigma$ of dimension 2, however, we can also consider the edge from vertex 1 to vertex 3 as a face of the 2 dimensional simplex, since this is defined using $\tau$(e) = ($v_1, v_3$) where $\tau$ is a subset of $\sigma$. These simplices may be joined along these faces. A simplex that is not the face of any other simplex is said to be maximal. Again, with the 2-simplex above, we can see that the maximal dimension of this is 2, and that the edges and vertices that construct this object are faces of the 2-simplex and faces of faces of the 2-simplex respectively. Thus, the set of all maximal simplices of a simplicial complex determines the entire simplicial complex since this is made up entirely of maximal simplicial complexes or a face of a simplicial complex. \subsection{Simplicial Complex applied to Directed Graphs} The directed graph $\mathcal{G}$ naturally creates the directed simplicial complex. The directed simplicial complex that is associated to the directed graph $\mathcal{G}$ is called the directed flag complex of $\mathcal{G}$. The directed flag complex is defined to be the ordered simplicial complex whose n-simplices are all ordered (n+1)-cliques. So, let it be that $\sigma = (v_0, v_1, ...v_n)$, such that $v_i \in \emph{V}$ $\forall i$ and ($v_i, v_j) \in \emph{E}$ for $i < j$. Then the ordered set of these completes the directed flag complex. Further to this, we note that $v_0$ is the initial vertex, or the source of $\sigma$, and that $v_n$ is the final or sink of $\sigma$. One final thing of note is that because of our assumption on $\tau$, an n-simplex in $\emph{S}$ is characterised by the ordered sequence $(v_o, v_1, ..., v_n)$ and not by the vertices. By example, $(v_0, v_1, v_2)$ and $(v_0, v_2, v_1)$ are two distinct 2-simplices that contain the same set of vertices. \subsection{Directionality} The directionality \cite{Reimann_2017} of a directed graph $\mathcal{G}$ is given by: \begin{equation} \Dr(\mathcal{G}) = \sum_{v \in V} \sd(\emph{v})^2 \enspace{,} \end{equation} where \begin{equation} \sd(\emph{v}) = \Indeg(\emph{v}) - \outd(\emph{v})\enspace{.} \end{equation} In words, the signed degree ($\sd$) is given as the in-degree minus the out-degree for each vertex in $\mathcal{G}$. Following on from this, the directionality of $\mathcal{G}$ is the sum of the squares of all the signed degrees for each vertex in the directed graph $\mathcal{G}$. Further to this, we can note that the sum of the signed degree for a finite graph is zero. That is, \begin{equation} \sum_{v \in \mathcal{G}}\sd(\emph{v}) = 0 \enspace{.} \end{equation} \subsection{Homology} Simplicial homology arose as a way to study topological spaces. The building blocks of which are our n-simplices. On top of this, we have further numerical quantities in order to describe the abstract directed flag complex. These include Betti numbers and the Euler Characteristic. These are described below. \subsection{Euler Characteristic} The Euler Characteristic is simply defined as the alternating sum of the number of simplices in each dimension. This can also be applied to Betti numbers in each dimension, however, for the Betti numbers for our models and even the Erdos-Renyi model in dimensions 1 through 3, this is not computationally viable since the required memory to compute the Betti numbers in these dimensions is upwards of 16GB. So, algebraically, the Euler Characteristic is given as follows: \begin{equation*} \chi = k_0 - k_1 + k_2 - k_3 + ... \end{equation*} \begin{equation} \Rightarrow \chi = \sum_{k \geq 0} (-1)^k \abs{S_k} \enspace{.} \end{equation} As a side note, there is a close relationship between the Euler Characteristic and Betti numbers \cite{Reimann_2017}, that are defined in the next section. This relationship is as follows: \begin{equation} \chi(\emph{S}) = \sum_{k\geq 0}(-1)^k \beta_{k}(\emph{S}) \end{equation} \subsection{Betti Numbers} Informally, the $k^{th}$ Betti number refers to the number of k-dimensional holes on a topological space, where a k-dimensional hole is a k-dimensional cycle that is not a boundary of a (k+1)-dimensional object. The definitions of the first few Betti numbers are as follows; \begin{itemize} \item $\beta_0$ is the number of connected components \item $\beta_1$ is the number of 1-dimensional or `circular' holes. \item $\beta_2$ is the number of 2-dimensional `voids' or `cavities'. \end{itemize} By example, lets take our triangular prism in Figure 4. We can see that the vertices are all connected as one object. This, as well as with the Bio-M MC, takes the zeroth Betti number to be 1. That is, $\beta_0 = 1$. Next, we take the informal definition of the 1-dimensional Betti number. We can see here that there are no holes that are of dimension 1, so $\beta_1 = 0$. Finally, we look at the second dimensional definition of a Betti number. We are looking for holes or cavities that are entirely enclosed by 2-dimensional objects. We can see that we have a hole that is enclosed by triangles. Therefore, $\beta_2 = 1$. Applying the Euler Characteristic to the Betti numbers of this example, we have, \begin{equation} \beta_0 - \beta_1 + \beta_2 = 1 - 0 + 1 = 2 \end{equation} So if we take the classical usage of the Euler characteristic, we can see the relationship, as stated above in the Euler characteristic section, is also 2 as follows: \begin{equation} V - E + F = 6 - 8 + 12 = 2 \end{equation} \begin{figure}[H]% \centering \captionsetup{justification=centering} {{\includegraphics[width=12cm]{graph/simplex_structure.png} }}% \caption{Triangular Prism} \label{fig:example}% \end{figure} Now, informally, let $\mathbb{F}_2$ denote a field of two elements. Let S be a simplicial complex. Define the chain complex C*(S, $\mathbb{F}_2$) to be the sequence ($C_n$ = $C_n$(S,$\mathbb{F}_2$))$_{n\geq0}$, such that $C_n$ is the $\mathbb{F}_2$-Vector space whose basis elements are the n-simplices $\sigma \in S_n$, for each $n\geq0$. In other words, the elements of $C_n$ are formal sums of n-simplices in S. For each $n\geq1$, there is a linear transformation called a \textit{differential}. \begin{equation} \partial_n : C_n \rightarrow C_{n-1} \enspace{.} \end{equation} specified by $\partial_n(\sigma) = \sigma^0 + \sigma^1 + ... + \sigma^n$ for every n-simplex $\sigma$, where $\sigma^i$ is the $i^{th}$ face of $\sigma$. Having defined $\partial_n$ on the basis, one then extends it linearly to the entire vector space $C_n$. The $n^{th}$ Betti number $\beta_n$(S) of a simplicial complex S is the $\mathbb{F}$2-vector space dimension of its $n^{th}$ mod-2 homology group, which is defined by, \begin{equation} \mathbb{H}_n(S, \mathbb{F}_2) = \frac{\Ker(\partial_n)}{ \ime(\partial_{n+1})} \enspace{,} \end{equation} for $n\geq 1$ and \begin{equation} \mathbb{H}_0(S, \mathbb{F}_2) = C_0/\ime(\partial_{1}) \enspace{.} \end{equation} For all $n\geq1$, there is an inclusion of vector subspaces i.e.~$\ime(\partial_{n+1}) \subseteq \Ker(\partial_{n}) \subseteq C_n$, and thus the definition of homology makes sense. Computing Betti numbers of a simplicial complex is conceptually very easy. Let $|S_n|$ denote the number of n-simplices in the simplicial complex S. If one encodes the differential $\partial_{n}$ as a $(|S_n-1| \times |S_n|)$-matrix $D_n$ with entries in $\mathbb{F}_2$, then one can easily compute its \textit{nullity}, null($\partial_n$), and its rank, rk($\partial_n$), which are the $\mathbb{F}_2$ dimensions of the null-space and the column space of $D_n$ respectively. The Betti numbers of S are then a sequence of natural numbers defined by, \begin{equation} \beta_0(S) = \text{dim}_{\mathbb{F}_2}(C_0) - \text{rk}(\partial_1) \enspace{,} \end{equation} \begin{equation} \beta_{n}(S) = \text{null}(\partial_{n}) - \text{rk}(\partial_{n+1}) \enspace{.} \end{equation} Since Im($\partial_{n+1}$) $\subseteq$ Ker($\partial_n$) for all $n\geq 1$, the Betti numbers are always non negative. The $n^{th}$ Betti number $\beta_n$ gives an indication of the n-dimensional cavities in the geometric realisation of S \cite{Reimann_2017}. \subsection{Blocks} Within the MC we have a set of neurons and a set of synapses, represented by vertices and directed edges respectively. Now, when we take into account the direction of information flow, an edge has with it a pair of ordered vertices. Now, when we subdivide the MC on a layer by layer basis, we are left with 25 subsets of ordered pairs of vertices, each belonging to a ``block''. An example of a block is L1-L4. That is, we have a set of ordered vertices where the pre-synaptic neurons set is from Layer 1 and the post-synaptic neurons are from Layer 4. This is not to say that there are a specific set of neurons that are pre-synaptic or post-synaptic, but rather, the neuron's state is determined by the order in which it appears in the ordered pair $\emph{e}$. \subsection{Total Variation distance} Here, we use the Total Variation (TV) distance to quantify statistical differences between distributions obtained from our models. Let $f$ and $g$ be two discrete distributions over a common support set $\{1,2,\ldots,n\}$. Thus, $\sum_{i=1}^{n}f_{i} = 1$ and $\sum_{i=1}^{n}f_{i} = 1$. Typically, we want to compare distribution $f$ obtained from a model with the distribution $g$ obtained from the Bio-M MC. To compare the distance between these two distributions, we take: \begin{equation} \delta(f, g) = \sum_{i=1}^{n}(|f_{i} - g_{i}|)\enspace{.} \end{equation} This will output a value in the range $[0, 2]$. Clearly $\delta(f, g)=0$ if $f=g$ and $\delta(f, g)=2$ if $f$ and $g$ have no common events.
# Lecture 18 ## MGFs to get moments of Expo and Normal, sums of Poissons, joint distributions ## MGF for $Expo(1)$ Let $X \sim Expo(1)$. We begin by finding the MGF of $X$: \begin{align} M(t) &= \mathbb{E}(e^{tX}) &\quad \text{ definition of MGF} \\ &= \int_{0}^{\infty} e^{-x} \, e^{tx} dx \\ &= \int_{0}^{\infty} e^{-x(1-t)} dx \\ &= \boxed{\frac{1}{1-t}} &\quad \text{ for } t < 1 \end{align} In finding the moments, by definition we have: * $M'(0) = \mathbb{E}(X)$ * $M''(0) = \mathbb{E}(X^2)$ * $M'''(0) = \mathbb{E}(X^3)$ * ... and so on ... Even though finding derivatives of $\frac{1}{1-t}$ is not all that bad, it is nevertheless annoying busywork. But since we know that the $n^{th}$ moment is the coefficient of the $n^{th}$ term of the Taylor Expansion of $X$, we can leverage that fact instead. \begin{align} \frac{1}{1-t} &= \sum_{n=0}^{\infty} t^n &\quad \text{ for } |t| < 1 \\ &= \sum_{n=0}^{\infty} \frac{n! \, t^n}{n!} &\quad \text{ since we need the form } \sum_{n=0}^{\infty} \left( \frac{\mathbb{E}(X^{n}) \, t^{n}}{n!}\right) \\ \\ \Rightarrow \mathbb{E}(X^n) &= \boxed{n!} \end{align} And now we can simply _generate_ arbitary moments for r.v. $X$! * $\mathbb{E}(X) = 1! = 1$ * $\mathbb{E}(X^2) = 2! = 2$ * $\Rightarrow \mathbb{Var}(X) = \mathbb{E}(X^2) - \mathbb{E}X^2 = 2 - 1 = 1$ ## MGF for $Expo(\lambda)$ Let $Y \sim Expo(\lambda)$. We begin with \begin{align} \text{let } X &= \lambda Y \\ \text{and so } X &= \lambda Y \sim Expo(1) \\ \\ \text{then } Y &= \frac{X}{\lambda} \\ Y^n &= \frac{X^n}{\lambda^n} \\ \\ \Rightarrow \mathbb{E}(Y^n) &= \frac{\mathbb{E}(X^n)}{\lambda^n} \\ &= \boxed{\frac{n!}{\lambda^n}} \end{align} And as before, we now can simply _generate_ arbitary moments for r.v. $Y$! * $\mathbb{E}(Y) = \frac{1!}{\lambda^1} = \frac{1}{\lambda}$ * $\mathbb{E}(Y^2) = \frac{2!}{\lambda^2} = \frac{2}{\lambda^2}$ * $\Rightarrow \mathbb{Var}(Y) = \mathbb{E}(Y^2) - \mathbb{E}Y^2 = \frac{2}{\lambda^2} - \left(\frac{1}{\lambda}\right)^2 = \frac{1}{\lambda^2}$ ## MGF for standard Normal $\mathcal{N}(0, 1)$ Let $Z \sim \mathcal{N}(0,1)$; find **all** its moments. We have seen before that, by symmetry, $\mathbb{E}(Z^{2n+1}) = 0$ for all odd values of $n$. So we will focus in on the _even_ values of $n$. Now the MGF $M(t) = e^{t^2/2}$. Without taking _any_ derivatives, we can immediately Taylor expand that, since it is continuous everywhere. \begin{align} M(t) &= e^{t^2/2} \\ &= \sum_{n=0}^{\infty} \frac{\left(t^2/2\right)^n}{n!} \\ &= \sum_{n=0}^{\infty} \frac{t^{2n}}{2^n \, n!} \\ &= \sum_{n=0}^{\infty} \frac{(2n)! \, t^{2n}}{2^n \, n! \, (2n)!} &\quad \text{ since we need the form } \sum_{n=0}^{\infty} \left( \frac{\mathbb{E}(X^{n}) \, t^{n}}{n!}\right) \\ \\ \Rightarrow \mathbb{E}(Z^{2n}) &= \boxed{\frac{(2n)!}{2^n \, n!}} \end{align} Let's double-check this with what know about $\mathbb{Var}(Z)$ * by symmetry, we know that $\mathbb{E}(Z) = 0$ * at $n = 1$, $\mathbb{E}(Z^2) = \frac{2!}{2 \times 1!} = 1$ * $\Rightarrow \mathbb{Var}(Z) = \mathbb{E}(Z^2) - \mathbb{E}Z^2 = 1 - 0 = 1$ * at $n = 2$, $\mathbb{E}(Z^4) = \frac{4!}{4 \times 2!} = 3$ * at $n = 3$, $\mathbb{E}(Z^6) = \frac{6!}{8 \times 3!} = 15$ And so you might have noticed a pattern here. Let us rewrite those even moments once more: * at $n = 1$, $\mathbb{E}(Z^2) = 1$ * at $n = 2$, $\mathbb{E}(Z^4) = 1 \times 3 = 3$ * at $n = 3$, $\mathbb{E}(Z^6) = 1 \times 3 \times 5 = 15$ ## MGF for $Pois(\lambda)$ Let $X \sim Pois(\lambda)$; now let's consider MGFs and how to use them to find sums of random variables (convolutions). \begin{align} M(t) &= \mathbb{E}(e^{tX}) \\ &= \sum_{k=0}^{\infty} e^{tk} \, \frac{\lambda^k e^{-\lambda}}{k!} \\ &= e^{-\lambda} \sum_{k=0}^{\infty} \frac{\lambda^k e^{tk}}{k!} \\ &= e^{-\lambda} e^{\lambda e^t} &\quad \text{but the right is just another Taylor expansion} \\ &= \boxed{e^{\lambda (e^t - 1)}} \end{align} Now let's let $Y \sim Pois(\mu)$, and it is independent of $X$. Find the distribution of $(X + Y)$. You may recall that with MGFs, all we need to do is _multiply_ the MGFs. \begin{align} e^{\lambda (e^t - 1)} \, e^{\mu (e^t - 1)} &= e^{(\lambda + \mu)(e^t - 1)} \\ \\ \Rightarrow X + Y &\sim \mathcal{Pois}(\lambda + \mu) \end{align} When adding a Poisson distribution $X$ with another independent Poisson distribution $Y$, the resulting convolution $X + Y$ will also be Poisson. This interesting relation only happens with Poisson distributions. Now think about what happens with $X$ and $Y$ are _not_ independent. Let $Y = X$, so that $X + Y = 2X$, which is clearly *not* Poisson, as * $X + Y = 2X$ is an even function which cannot be Poisson, since Poisson can take on all values both even _and_ odd * Mean $\mathbb{E}(2x) = 2\lambda$, but $\mathbb{Var}(2X) = 4\lambda$, and since the mean and variance are _not_ equal, this cannot be Poisson ### Some definitions In the most basic case of two r.v. in a joint distribution, consider both r.v.'s _together_: > **Joint CDF** > > In the general case, the joint CDF fof two r.v.'s is $ F(x,y) = P(X \le x, Y \le y)$ <p/> > **Joint PDF** > $f(x, y)$ such that, in the *continuous* case $P((X,Y) \in B) = \iint_B f(x,y)\,dx\,dy$ #### Joint PMF $f(x, y)$ such that, in the *discrete* case \begin{align} P(X=x, Y=y) \end{align} We also can consider a single r.v. of a joint distribution: #### Independence and Joint Distributions $X, Y$ are independent iff $F(x,y) = F_X(x) \, F_Y(y)$. \begin{align} P(X=x, Y=y) &= P(X=x) \, P(Y=y) &\quad \text{discrete case} \\ \\\\ f(x, y) &= f_X(x) \, f_Y(y) &\quad \text{continuous case} \end{align} ... with the caveat that this must be so for *all* $\text{x, y} \in \mathbb{R}$ #### Marginals (and how to get them) $P(X \le x)$ is the *marginal distribution* of $X$, where we consider one r.v. at a time. In the case of a two-r.v. joint distribution, we can get the marginals by using the joint distribution itself: \begin{align} P(X=x) &= \sum_y P(X=x, Y=y) &\quad \text{marginal PMF, discrete case, for } x \\ \\\\ f_Y(y) &= \int_{-\infty}^{\infty} f_{(X,Y)}(x,y) \, dx &\quad \text{marginal PDF, continuous case, for } y \end{align} ## Example: Discrete Joint Distribution Let $X, Y$ be both Bernoulli. $X$ and $Y$ may be independent; or they might be dependent. They may or may not have the same $p$. But they are both related in the form of a *joint distribution*. We can lay out this joint distribution in a $2 \times 2$ contigency table like below: | | $Y=0$ | $Y=1$ | |-------|:-----:|:-----:| | $X=0$ | 2/6 | 1/6 | | $X=1$ | 2/6 | 1/6 | In order to be a joint distribution, all of the values in our contigency table must be positive; and they must all sum up to 1. The example above shows such a PMF. Let's add the marginals for $X$ and $Y$ to our $2 \times 2$ contigency table: | | $Y=0$ | $Y=1$ | ... | |:-----:|:-----:|:-----:|:-----:| | $X=0$ | 2/6 | 1/6 | 3/6 | | $X=1$ | 2/6 | 1/6 | 3/6 | | ... | 4/6 | 2/6 | | Observe how in our example, we have: \begin{align} P(X=0,Y=0) &= P(X=0) \, P(Y=0) \\ &= 3/6 \times 4/6 = 12/36 &= \boxed{2/6} \\ \\ P(X=0,Y=1) &= P(X=0) \, P(Y=1) \\ &= 3/6 \times 2/6 = 6/36 &= \boxed{1/6} \\ P(X=1,Y=0) &= P(X=1) \, P(Y=0) \\ &= 3/6 \times 4/6 = 12/36 &= \boxed{2/6} \\ \\ P(X=1,Y=1) &= P(X=1) \, P(Y=1) \\ &= 3/6 \times 2/6 = 6/36 &= \boxed{1/6} \\ \end{align} and so you can see that $X$ and $Y$ are independent. Now here's an example of a two r.v. joint distribution where $X$ and $Y$ are _dependent_; check it out for yourself. | | $Y=0$ | $Y=1$ | |:-----:|:-----:|:-----:| | $X=0$ | 1/3 | 0 | | $X=1$ | 1/3 | 1/3 | ## Example: Continuous Joint Distribution Now say we had Uniform distributions on a square such that $x,y \in [0,1]$. The joint PDF would be constant on/within the square; and 0 outside. \begin{align} \text{joint PDF} &= \begin{cases} c &\quad \text{if } 0 \le x \le 1 \text{, } 0 \le y \le 1 \\ \\ 0 &\quad \text{otherwise} \end{cases} \end{align} In 1-dimension space, if you integrate $1$ over some interval you get the _length_ of that interval. In 2-dimension space, if you integrate $1$ over some region, you get the _area_ of that region. Normalizing $c$, we know that $c = \frac{1}{area} = 1$. Marginally, $X$ and $Y$ are independent $\mathcal{Unif}(1)$. ## Example: Dependent, Continuous Joint Distribution Now say we had Uniform distributions on a _disc_ such that $x^2 + y^2 \le 1$. #### Joint PDF In this case, the joint PDF is $Unif$ over the area of a disc centered at the origin with radius 1. \begin{align} \text{joint PDF} &= \begin{cases} \frac{1}{\pi} &\quad \text{if } x^2 + y^2 \le 1 \\ \\ 0 &\quad \text{otherwise} \end{cases} \end{align} #### Marginal PDF
\chapter{Puzzles, Algorithms \& Hardness} \label{ch:puzz-algo-hard} \section{Coloring Puzzle} \begin{figure}[h] \label{fig:graph} \centering \begin{tikzpicture}[style=thick] \draw (18:2cm) -- (90:2cm) -- (162:2cm) -- (234:2cm) -- (306:2cm) -- cycle; \draw (18:1cm) -- (162:1cm) -- (306:1cm) -- (90:1cm) -- (234:1cm) -- cycle; \foreach \x in {18,90,162,234,306}{ \draw (\x:1cm) -- (\x:2cm); } \draw[fill=black] (18:2cm) circle (4pt); \draw[fill=black] (90:2cm) circle (4pt); \draw[fill=black] (90:1cm) circle (4pt); \draw[fill=black] (18:1cm) circle (4pt); \draw[fill=black] (162:1cm) circle (4pt); \draw[fill=black] (162:2cm) circle (4pt); \draw[fill=black] (234:1cm) circle (4pt); \draw[fill=black] (234:2cm) circle (4pt); \draw[fill=black] (306:1cm) circle (4pt); \draw[fill=black] (306:2cm) circle (4pt); \end{tikzpicture} \end{figure} Consider the following puzzle. Given a figure as above, the goal is to give colors to the circles such that for every line, its end points have different colors. Furthermore, the number of colors used needs to be minimized. Without this condition the problem is trivial since using a different color for every circle would be a solution irrespective of the figure. Puzzles like above are very commonly encountered in a variety of real life instances. However known algorithms takes far too much time to complete even on instances with $20$ vertices. This thesis is about an explanation for the lack of efficient algorithms, for coloring like problems. \begin{figure}[h] \centering \begin{tikzpicture}[style=thick] \draw (18:2cm) -- (90:2cm) -- (162:2cm) -- (234:2cm) -- (306:2cm) -- cycle; \draw (18:1cm) -- (162:1cm) -- (306:1cm) -- (90:1cm) -- (234:1cm) -- cycle; \foreach \x in {18,90,162,234,306}{ \draw (\x:1cm) -- (\x:2cm); } \draw[fill=black] (18:2cm) circle (4pt); \draw[fill=black] (90:2cm) circle (4pt); \draw[fill=black] (90:1cm) circle (4pt); \draw[fill=black] (18:1cm) circle (4pt); \draw[fill=black] (162:1cm) circle (4pt); \draw[fill=black] (162:2cm) circle (4pt); \draw[fill=black] (234:1cm) circle (4pt); \draw[fill=black] (234:2cm) circle (4pt); \draw[fill=black] (306:1cm) circle (4pt); \draw[fill=black] (306:2cm) circle (4pt); \end{tikzpicture} \qquad \qquad \begin{tikzpicture}[style=thick] \draw (18:2cm) -- (90:2cm) -- (162:2cm) -- (234:2cm) -- (306:2cm) -- cycle; \draw (18:1cm) -- (162:1cm) -- (306:1cm) -- (90:1cm) -- (234:1cm) -- cycle; \foreach \x in {18,90,162,234,306}{ \draw (\x:1cm) -- (\x:2cm); } \draw[color=green,fill=green] (18:2cm) circle (4pt); \draw[color=red,fill=red] (90:2cm) circle (4pt); \draw[color=green,fill=green] (90:1cm) circle (4pt); \draw[color=red,fill=red] (18:1cm) circle (4pt); \draw[color=blue,fill=blue] (162:1cm) circle (4pt); \draw[color=green,fill=green] (162:2cm) circle (4pt); \draw[color=blue,fill=blue] (234:1cm) circle (4pt); \draw[color=red,fill=red] (234:2cm) circle (4pt); \draw[color=red,fill=red] (306:1cm) circle (4pt); \draw[color=blue,fill=blue] (306:2cm) circle (4pt); \end{tikzpicture} \caption{The figure on the right is a $3$-coloring of the graph on the left. However it does not have a $2$-coloring.} \label{fig:M1} \end{figure} Figures like above are commonly called \emph{graphs} (strictly speaking they are undirected graphs, but in this thesis will only be concerned with undirected graphs) . A graph $G=(V,E)$ consists of a set of \emph{vertices} $V$ (the circles) and a set $E$ containing some pairs of vertices, called \emph{edges} (the lines). Given a graph $G=(V,E)$ and a number $C$, a $C$-coloring of $G$ is an assignment of \emph{colors} denoted by $\{1,\cdots, C\}$ to the vertices such that the end points of every edge have different colors. For a given graph, a $C$-coloring might not exist for all values of $C$. But for any graph, the coloring which gives different colors to all vertices in $V$, is an $n$-coloring, where $n$ is the \emph{size} (the number of vertices in $V$) of $G$. \begin{definition} The \GraphColoring\ problem is, given a graph, find a coloring, using the minimum number of colors. This minimum value is commonly known as the \emph{chromatic number} of the graph. \end{definition} \section{Efficient Algorithms} If the maximum degree of $G$ is $\Delta$ then the following simple algorithm computes a $(\Delta+1)$-coloring in time bounded by the number of edges. \paragraph{} \begin{algorithm}[H] \caption{For graphs with maximum degree $\leq\Delta$.} \For{$v \in V$}{ give $v$ a color in $\{1,\cdots,\Delta+1\}$ different from the colors of its already colored neighbours. } \end{algorithm} \qquad Algorithm 1, does not solve the \GraphColoring\ problem since the chromatic number can be much smaller than $\Delta+1$. Suppose the graph has a $c$-coloring there is a simple algorithm to find it, which takes $c^n\cdot m$ time, where $m$ is the number of edges. \paragraph{} \begin{algorithm}[H] \label{alg:brut} \caption{Brute Force Algorithm} \For{every assignment $f \in \{1,\cdots,c\}^V$ of colors to the vertices }{ \For{every edge}{ check if $f$ assigns different colors to the end points. } } \end{algorithm} \qquad However note that the running time of Algorithm 2 grows \emph{exponentially} in $n$. Even for $n=20$, the running time ($> c^{20}$) is prohibitively large, while for Algorithm 1 it is still a reasonable number. This motivates the definition of efficient algorithms, as ones that has running time bounded by a polynomial in the input size. For simplicity, we consider only \emph{decision problems} (\ie problems that have a Boolean answer). For such problems the inputs are partitioned into YES and NO instances. We will often specify a decision problem by the set of YES instances. Though \GraphColoring\ problem is not a decision problem, we can consider the problem which have the number $C$ also in the input, where the goal is to check if the graph has a $C$-coloring. %TODO: Motivate and give references for efficient = polytime \begin{informal-definition}\label{def:p} \P\ is the class of decision problems, that has an algorithm with running time bounded by a polynomial in $n$ (the input size). \end{informal-definition} Note that for \GraphColoring, $(G,C) \in \YES$ (i.e. $G$ has a $C$-coloring), then there is a certificate that certifies that it is \YES\ instance, that can be verified in time proportional to the number of edges. The certificate is simply the $C$-coloring of the graph. And if $(G,C) \in \NO$, then any assignment of colors from $\{1,\cdots, C\}$, will leave some edge monochromatic. This property is true for a large class of problems. \begin{informal-definition} \label{def:np} \NP\ is the class of decision problems, for which there is an algorithm $V$ which takes an input $x$ and a proof $\pi$, runs in time polynomial in the size of $x$ and satisfies the following properties. \begin{itemize} \item Completeness : If $x \in \YES$ then there exists $\pi$ such that $V(x,\pi)=1$. \item Soundness : If $x\in \NO$ then for any $\pi$, $V(x, \pi)=0$. \end{itemize} \end{informal-definition} For any \NP\ problem, there is a trivial algorithm similar to Algorithm \ref{alg:brut}, which runs in time $c^n$ for some constant $c$. The algorithm just tries all possible certificates with the verification procedure. It is a major open problem if \P $=$ \NP. A surprising result is that there are certain class of problems called \NPComplete\ which capture the hardness of solving problems in \NP. That is, an instance of any \NP\ problem could be converted efficiently to an instance of such problems. The \GraphColoring\ problem is an \NPComplete\ problem. Hence unless $\P = \NP$, we cannot hope to have polynomial time algorithms for \GraphColoring. One can ask if there are polynomial time algorithms for a relaxed version of the problem. \section{Approximation Algorithms} \label{sec:approx} A relaxed version of the \GraphColoring\ problem is to compute the chromatic number approximately. An \emph{approximation algorithm} for chromatic number with approximation \emph{factor} $F \geq 1$, always outputs a number between $C$ and $C\cdot F$, where $C$ is the chromatic number of the input graph. However for a general graph, this relaxation is also a \emph{hard} problem. That is, assuming the famous $\P\neq \NP$ conjecture, it is known that this problem cannot be solved in polynomial time. Feige \& Kilian~\cite{FeigeK00} showed that computing this number approximately within a factor of $n^{1-\epsilon}$ for any small constant $\epsilon >0$ is known to be hard, assuming a different complexity conjecture. Therefore, there is not much hope of having an efficient algorithm, which does much better than the trivial $n$-coloring. Since the general approximation problem is hard, the focus shifted on solving it for subclasses of graphs. A natural subclass of graphs to consider, are the ones for which the chromatic number is a small constant $c$. For $c=2$, such graphs are commonly called \emph{bipartite}. There is a simple linear time algorithm for finding a $2$-coloring in such graphs. It just assigns a vertex one color, the other color to all its neighbours, and continues until all vertices are colored. However for $3$-colorable graphs, finding a $3$-coloring is \NPHard\ (it cannot be solved by efficient algorithms, assuming \P$\neq$ \NP). Hence a long series of works, was aimed at solving this problem approximately. \begin{definition} \ApproximateGraphColoring$(c,C)$ problem is to find a $C$-coloring, when the input graph is promised to be $c$-colorable. \end{definition} \begin{remark} We will often be considering the decision version of the problem, specified by disjoint sets of \YES\ ($c$-colorable graphs) and \NO\ (graphs with chromatic number $> C$) instances. The goal is to have an algorithm to accept all \YES\ instances and reject all \NO\ instances. The algorithm can either accept or reject inputs which are neither \YES\ nor \NO. \end{remark} For $3$-colorable graphs, Wigderson~\cite{Wigderson83} gave the first not trivial improvement of finding a $O(\sqrt n)$-coloring using combinatorial techniques. This was further improved to $O(n^{3/8})$-coloring by Blum~\cite{Blum94}. A major breakthrough was made by Karger, Motwani \& Sudan~\cite{KargerMS1998}, using semi-definite programming (SDP). For a $3$-colorable graph with maximum degree $d$, they gave an $O(d^{1/3})$-coloring algorithm. Combining this with Wigderson's algorithm, they obtained a $O(n^{1/4})$-coloring algorithm. Blum \& Karger~\cite{BlumK1997} combined the combinatorial methods of Blum~\cite{Blum94} with the SDP to get an $O(n^{3/14})$-coloring. The current best known (see results of Kawarabayashi \& Thorup \cite{KawarabayashiT2014}) efficient algorithms output a $n^{0.19996}$-coloring. \section{What this thesis is about?} This thesis is about giving an explanation for the lack of efficient algorithms for some generalizations of the \ApproximateGraphColoring$(c,C)$ problem, using the theory of \NPComplete ness and complexity conjectures similar to \P $\neq$ \NP. That is, we prove that efficient algorithms for the problem will imply that the corresponding conjecture is false. Such results are called \emph{hardness results} and the area in general, is commonly called in literature as the \emph{hardness of approximation}. The focus of our hardness results will be the case when $c$ is a small constant and $C$ can be any large constant or a function that depends on $n$. As described in the previous section, there are algorithms which solve these problems for $C=n^\alpha$ for some constant $\alpha <1$. We prove hardness results for larger values (exponentially larger in some cases) of $C$ than was previously known. We will describe these generalizations in the next three sections. \subsection{Almost Coloring} Assuming \P$\neq$ \NP, Khanna \etal~\cite{KhannaLS2000} showed hardness for the \ApproximateGraphColoring$(3,4)$ problem (that is there is no efficient algorithm which can find a $4$-coloring, in any $3$-colorable graph). Since then, there has been no progress in this problem. Later, results where proved using a complexity assumption called the Unique Games Conjecture (UGC), which is stronger than the P$\neq$ NP assumption. Starting with the work of Khot~\cite{Khot2002}, it was shown that UGC, explains the lack of efficient approximation algorithms for a variety of problems (eg. Vertex Cover, MAX-CUT). Dinur, Mossel \& Regev~\cite{DinurMR2009} showed hardness for \ApproximateGraphColoring$(3,C)$ for any constant $C$ using a conjecture similar to \UGC. Due to a technical problem (that \UGC\ does not have perfect completeness), their results which used \UGC\ exactly, showed hardness for the \AlmostGraphColoring{\epsilon}$(c,C)$ problem, for any small $\epsilon >0$. \begin{definition} The \AlmostGraphColoring{\epsilon}$(c,C)$ problem is of distiguishing graph from the following cases: \begin{itemize} \item \YES\ : There is a subgraph of size $(1-\epsilon)n$ that is $c$-colorable. \item \NO\ : Any independent set is the graph has size at most $n/C$. \end{itemize} \end{definition} \noindent \paragraph{\underline{Contributions of this Thesis:}} The work of Dinur \& Shinkar~\cite{DinurS2010} implies hardness results for \AlmostGraphColoring{\epsilon}$(3,\poly(\log n))$, using a stronger form of \UGC\ (where the dependence between the soundness and alphabet size is inverse polynomial). In \lref[Chapter]{ch:graph-hard}, we show hardness for the same problem, using a weaker form of UGC (in which the aforesaid dependence is super-polynomial) in some respects (joint work with Dinur, Harsha \& Srinivasan~\cite{DinurHSV2014}). The previous reductions (by Dinur, Mossel \& Regev~\cite{DinurMR2009} and Dinur \& Shinkar~\cite{DinurS2010}) followed the template of H\aa stad \cite{Hastad2001}, which employed a particular error correcting code known as the long code. As the name implies, this code has a large size which made the reductions inefficient. A shorter code called the low degree long code was proposed by Barak \etal~\cite{BarakGHMRS2012} . Dinur and Guruswami~\cite{DinurG2013} showed improved approximate covering (which we define in \lref[Section]{sec:intro-cover}) hardness results using this shorter code. In \lref[Chapter]{ch:graph-hard}, we adapt this shorter code to the reduction of Dinur, Mossel and Regev~\cite{DinurMR2009} for graph coloring, to get improved results. %Mention results of Sion Chan, Sanxia Huang, Khot, DinurMR, DS on graph coloring hardness \subsection{Hypergraph Coloring} Guruswami, H\aa stad \& Sudan~\cite{GuruswamiHS2002} initiated the study of hypergraph coloring problems, to get a better understanding of graph coloring and since it is a natural generalization. They showed hardness results for $c=2, C=\poly(\log \log n)$, for hypergraph coloring, assuming that \NP\ does not have quasi-polynomial algorithms (such results are commonly known as \emph{quasi-\NP-hardness} results). A \emph{$k$-uniform hypergraph} $G=(V,E)$ is similar to a graph, with the edges $E\subseteq {V \choose k}$ containing $k$ vertices. A $c$-coloring of a hypergraph is coloring of vertices using colors $\{1,\cdots, c\}$, such that every edge has $2$ vertices with distinct colors. For $k=2$, a hypergraph is simply a graph. %TODO: Strictly speaking this is not a generalization since all vertices in an edge % may not be distinct. But the proofs also holds for undirected versions. \begin{definition} The \ApproximateHypergraphColoring{k}$(c,C)$ problem is defined similar to \ApproximateGraphColoring$(c,C)$, as given a $c$-colorable $k$-uniform hypergraph, find a $C$-coloring. The decision version is also defined analogously. \end{definition} When $k>2$, for any constant $c>1$, known algorithms only guarantee an $n^\alpha$-coloring for some $\alpha < 1$. Starting with the work of Guruswami, H\aa stad \& Sudan \cite{GuruswamiHS2002}, there have been many results in hardness of hypergraph coloring. For the case of constant $c,k$, strongest known results due to Khot~\cite{Khot2002c}, who showed quasi-\NP-hardness for $C= \poly( \log n)$. \noindent \paragraph{\underline{Contributions of this Thesis:}} In \lref[Chapter]{ch:hypergraph-hard}, we exponentially improve the hardness results. In \lref[Section]{sec:33}, we first show hardness results (joint work with Guruswami, Harsha, H\aa stad \& Srinivasan~\cite{GuruswamiHHSV2014}) for $3$-uniform $3$-colorable hypergraphs by a more efficient reduction, that makes use of low degree long code (which we describe in \lref[Section]{sec:low-deg-long-code}). For the case of $4$-uniform $4$-colorable hypergraphs, our initial work (joint work with Guruswami, Harsha, H\aa stad \& Srinivasan~\cite{GuruswamiHHSV2014}) showed the first super-polylogarithmic coloring hardness (i.e. $C >> \poly(\log n)$) results, by using the low degree long code. Subsequent to our initial work Khot \& Saket~\cite{KhotS2014b} got hardness results of $2^{(\log n)^{1/21}}$, by using the low degree long code with degree $2$. Though their result was for $12$-uniform hypergraphs. We further observed~\cite{Varma2014} that by combining their methods with ours, the same hardness results can be obtained for $4$-uniform hypergraphs. Hence we improved the hardness results from $\poly(\log n)$ to $2^{(\log n)^{1/21}}$ for the case of $4$-colorable $4$-uniform hypergraphs. \subsection{Covering CSPs} \label{sec:intro-cover} The covering problem for constraint satisfaction~(CSP) is a generalization of the hypergraph coloring problem, introduced by Guruswami, H\aa stad and Sudan~\cite{GuruswamiHS2002} and later studied in detail by Dinur \& Kol~\cite{DinurK2013}. An instance of the problem consists of a hypergraph $G=(V,E)$ along with a \emph{predicate} $P \subseteq \{0,1\}^k$ and a \emph{literal} function $L:E\rightarrow \{0,1\}^k$. An \emph{assignment} $f:V \rightarrow \{0,1\}$ \emph{covers} an edge $e\in E$, if $f|_e \oplus L(e) \in P$ (by $f|_e$, we mean the $k$ bit string, obtained by restricting $f$ to vertices in $e$, and the $\oplus$ operation is coordinate-wise parity of the two strings). A \emph{cover} for a CSP instance is a set of assignments such that every edge is covered by one of the assignments. The goal of the covering problem is to find the minimum sized cover. When the predicate is the $3$-OR predicate, we can view the instance as a $3$-SAT instance, where each edge is a clause and the literal function specifies which variables are to be negated. Then the satisfiability problem is equivalent to finding a cover of size $1$. The covering problem can also be thought of as a generalization of the coloring problem. Consider an instance $G$ with the NAE( $:=\{0,1\}^k \setminus \{ \overline 0, \overline 1\}$) predicate and the trivial literal function $L(e) = 0^k$ for every edge $e$. It is not difficult to see that $G$ has a cover of size $t$ iff $G$ is $2^t$-colorable. The \emph{approximate covering} problem is defined as, given a $c$-coverable instance, find a $C$-covering.\\ \begin{definition}[\cov-$P$-\csp$(c,C)$] \label{def:cov-csp} For $P \subseteq \setq^k$ and $c,C \in \nat$, the \cov-$P$-\csp$(c,C)$ problem is, given a $c$-coverable instance $(G=(V,E),L)$ of $P$-\csp, find an $C$-covering. \end{definition} A predicate $P$ is \emph{odd}, if for every $x \in \{0,1\}^k$ either $x \in P$ or $\overline{x} \in P$. For odd predicates, there is a trivial algorithm with factor $2$, since any assignment and its complement covers the CSP instance. Dinur \& Kol~\cite{DinurK2013} asked the question whether, the approximate covering problem is hard for any constant $C>c$, for all non-odd predicates. Assuming a variant of UGC, they proceeded to show that if a non-odd predicate has a pairwise independent distribution in its support then, this is indeed the case. \noindent \paragraph{\underline{Contributions of this Thesis:}} In \lref[Chapter]{ch:covering-hard}, we answer the question of Dinur \& Kol in the affirmative (joint work with Bhangale \& Harsha~\cite{BhangaleHV2014}). That is, the approximate covering problem for a non-odd predicate is hard for any constant $C>c$ (assuming the same conjecture as Dinur \& Kol used). This leads to a complete characterization of predicates for which this result can be true, since there is a trivial $2$-covering algorithm for odd predicates. Our results also holds over non binary alphabets. We also show NP-hardness results, for the approximate covering problem with parameters $c=2, C = \log \log n$, for a class of predicates. Previously such results were known due to Dinur \& Kol for $4$-LIN with $c=2,C= \log \log \log n$. \section{Organization of Thesis} This thesis has two main parts. In \lref[Part]{part:two}, we will introduce some of the mathematical techniques used in proving the hardness results. \lref[Part]{part:three} contains all the hardness results. In \lref[Part]{part:two}, we also prove some lemmas which form the basis of the results in the next part. In \lref[Chapter]{ch:harmonic}, \lref[Section]{sec:har-poly} is a contribution of this thesis, were we prove analogues of results in Boolean function analysis to functions on subspaces. In \lref[Chapter]{ch:testing}, we discuss a linear algebraic result about testing low degree polynomials. \lref[Section]{sec:square-test} is a contribution of this thesis, though the analysis is similar to the results of Dinur \& Guruswami~\cite{DinurG2013} mentioned in \lref[Section]{sec:prod-test}. In \lref[Chapter]{ch:graph-prod}, we also give some combinatorial results about derandomized graph products. \lref[Section]{sec:derand-graph-prod} and \lref[Section]{sec:derand-maj-stab} are contributions of this thesis which uses the results proved in \lref[Section]{sec:square-test}. \lref[Part]{part:three} contains all the hardness results about almost graph coloring (\lref[Chapter]{ch:graph-hard}; joint work with Dinur, Harsha \& Srinivasan~\cite{DinurHSV2014}), hypergraph coloring (\lref[Chapter]{ch:hypergraph-hard}; joint work with Guruswami, Harsha, H\aa stad \& Srinivasan~\cite{GuruswamiHHSV2014} and the result \cite{Varma2014} ), and covering problem (\lref[Chapter]{ch:covering-hard}; joint work with Bhangale \& Harsha~\cite{BhangaleHV2014}). These results are the main contributions of this thesis, though much of the hardness reductions and analysis are similar to previous works.
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Reid Barton -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.limits.shapes.images import Mathlib.category_theory.filtered import Mathlib.tactic.equiv_rw import Mathlib.PostPort universes u namespace Mathlib namespace category_theory.limits.types /-- (internal implementation) the limit cone of a functor, implemented as flat sections of a pi type -/ def limit_cone {J : Type u} [small_category J] (F : J ⥤ Type u) : cone F := cone.mk (↥(functor.sections F)) (nat_trans.mk fun (j : J) (u : functor.obj (functor.obj (functor.const J) ↥(functor.sections F)) j) => subtype.val u j) /-- (internal implementation) the fact that the proposed limit cone is the limit -/ def limit_cone_is_limit {J : Type u} [small_category J] (F : J ⥤ Type u) : is_limit (limit_cone F) := is_limit.mk fun (s : cone F) (v : cone.X s) => { val := fun (j : J) => nat_trans.app (cone.π s) j v, property := sorry } /-- The category of types has all limits. See https://stacks.math.columbia.edu/tag/002U. -/ protected instance sort.category_theory.limits.has_limits : has_limits (Type u) := has_limits.mk fun (J : Type u) (𝒥 : small_category J) => has_limits_of_shape.mk fun (F : J ⥤ Type u) => has_limit.mk (limit_cone.mk (limit_cone F) (limit_cone_is_limit F)) /-- The equivalence between a limiting cone of `F` in `Type u` and the "concrete" definition as the sections of `F`. -/ def is_limit_equiv_sections {J : Type u} [small_category J] {F : J ⥤ Type u} {c : cone F} (t : is_limit c) : cone.X c ≃ ↥(functor.sections F) := iso.to_equiv (is_limit.cone_point_unique_up_to_iso t (limit_cone_is_limit F)) @[simp] theorem is_limit_equiv_sections_apply {J : Type u} [small_category J] {F : J ⥤ Type u} {c : cone F} (t : is_limit c) (j : J) (x : cone.X c) : coe (coe_fn (is_limit_equiv_sections t) x) j = nat_trans.app (cone.π c) j x := rfl @[simp] theorem is_limit_equiv_sections_symm_apply {J : Type u} [small_category J] {F : J ⥤ Type u} {c : cone F} (t : is_limit c) (x : ↥(functor.sections F)) (j : J) : nat_trans.app (cone.π c) j (coe_fn (equiv.symm (is_limit_equiv_sections t)) x) = coe x j := sorry /-- The equivalence between the abstract limit of `F` in `Type u` and the "concrete" definition as the sections of `F`. -/ def limit_equiv_sections {J : Type u} [small_category J] (F : J ⥤ Type u) : limit F ≃ ↥(functor.sections F) := is_limit_equiv_sections (limit.is_limit F) @[simp] theorem limit_equiv_sections_apply {J : Type u} [small_category J] (F : J ⥤ Type u) (x : limit F) (j : J) : coe (coe_fn (limit_equiv_sections F) x) j = limit.π F j x := rfl @[simp] theorem limit_equiv_sections_symm_apply {J : Type u} [small_category J] (F : J ⥤ Type u) (x : ↥(functor.sections F)) (j : J) : limit.π F j (coe_fn (equiv.symm (limit_equiv_sections F)) x) = coe x j := is_limit_equiv_sections_symm_apply (limit.is_limit F) x j /-- Construct a term of `limit F : Type u` from a family of terms `x : Π j, F.obj j` which are "coherent": `∀ (j j') (f : j ⟶ j'), F.map f (x j) = x j'`. -/ def limit.mk {J : Type u} [small_category J] (F : J ⥤ Type u) (x : (j : J) → functor.obj F j) (h : ∀ (j j' : J) (f : j ⟶ j'), functor.map F f (x j) = x j') : limit F := coe_fn (equiv.symm (limit_equiv_sections F)) { val := x, property := h } @[simp] theorem limit.π_mk {J : Type u} [small_category J] (F : J ⥤ Type u) (x : (j : J) → functor.obj F j) (h : ∀ (j j' : J) (f : j ⟶ j'), functor.map F f (x j) = x j') (j : J) : limit.π F j (limit.mk F x h) = x j := sorry -- PROJECT: prove this for concrete categories where the forgetful functor preserves limits theorem limit_ext {J : Type u} [small_category J] (F : J ⥤ Type u) (x : limit F) (y : limit F) (w : ∀ (j : J), limit.π F j x = limit.π F j y) : x = y := sorry theorem limit_ext_iff {J : Type u} [small_category J] (F : J ⥤ Type u) (x : limit F) (y : limit F) : x = y ↔ ∀ (j : J), limit.π F j x = limit.π F j y := { mp := fun (t : x = y) (_x : J) => t ▸ rfl, mpr := limit_ext F x y } -- TODO: are there other limits lemmas that should have `_apply` versions? -- Can we generate these like with `@[reassoc]`? -- PROJECT: prove these for any concrete category where the forgetful functor preserves limits? @[simp] theorem limit.w_apply {J : Type u} [small_category J] {F : J ⥤ Type u} {j : J} {j' : J} {x : limit F} (f : j ⟶ j') : functor.map F f (limit.π F j x) = limit.π F j' x := congr_fun (limit.w F f) x @[simp] theorem limit.lift_π_apply {J : Type u} [small_category J] (F : J ⥤ Type u) (s : cone F) (j : J) (x : cone.X s) : limit.π F j (limit.lift F s x) = nat_trans.app (cone.π s) j x := congr_fun (limit.lift_π s j) x @[simp] theorem limit.map_π_apply {J : Type u} [small_category J] {F : J ⥤ Type u} {G : J ⥤ Type u} (α : F ⟶ G) (j : J) (x : limit F) : limit.π G j (lim_map α x) = nat_trans.app α j (limit.π F j x) := congr_fun (lim_map_π α j) x /-- The relation defining the quotient type which implements the colimit of a functor `F : J ⥤ Type u`. See `category_theory.limits.types.quot`. -/ def quot.rel {J : Type u} [small_category J] (F : J ⥤ Type u) : (sigma fun (j : J) => functor.obj F j) → (sigma fun (j : J) => functor.obj F j) → Prop := fun (p p' : sigma fun (j : J) => functor.obj F j) => ∃ (f : sigma.fst p ⟶ sigma.fst p'), sigma.snd p' = functor.map F f (sigma.snd p) /-- A quotient type implementing the colimit of a functor `F : J ⥤ Type u`, as pairs `⟨j, x⟩` where `x : F.obj j`, modulo the equivalence relation generated by `⟨j, x⟩ ~ ⟨j', x'⟩` whenever there is a morphism `f : j ⟶ j'` so `F.map f x = x'`. -/ def quot {J : Type u} [small_category J] (F : J ⥤ Type u) := Quot sorry /-- (internal implementation) the colimit cocone of a functor, implemented as a quotient of a sigma type -/ def colimit_cocone {J : Type u} [small_category J] (F : J ⥤ Type u) : cocone F := cocone.mk (quot F) (nat_trans.mk fun (j : J) (x : functor.obj F j) => Quot.mk (quot.rel F) (sigma.mk j x)) /-- (internal implementation) the fact that the proposed colimit cocone is the colimit -/ def colimit_cocone_is_colimit {J : Type u} [small_category J] (F : J ⥤ Type u) : is_colimit (colimit_cocone F) := is_colimit.mk fun (s : cocone F) => Quot.lift (fun (p : sigma fun (j : J) => functor.obj F j) => nat_trans.app (cocone.ι s) (sigma.fst p) (sigma.snd p)) sorry /-- The category of types has all colimits. See https://stacks.math.columbia.edu/tag/002U. -/ protected instance sort.category_theory.limits.has_colimits : has_colimits (Type u) := has_colimits.mk fun (J : Type u) (𝒥 : small_category J) => has_colimits_of_shape.mk fun (F : J ⥤ Type u) => has_colimit.mk (colimit_cocone.mk (colimit_cocone F) (colimit_cocone_is_colimit F)) /-- The equivalence between the abstract colimit of `F` in `Type u` and the "concrete" definition as a quotient. -/ def colimit_equiv_quot {J : Type u} [small_category J] (F : J ⥤ Type u) : colimit F ≃ quot F := iso.to_equiv (is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit F) (colimit_cocone_is_colimit F)) @[simp] theorem colimit_equiv_quot_symm_apply {J : Type u} [small_category J] (F : J ⥤ Type u) (j : J) (x : functor.obj F j) : coe_fn (equiv.symm (colimit_equiv_quot F)) (Quot.mk (quot.rel F) (sigma.mk j x)) = colimit.ι F j x := rfl @[simp] theorem colimit_equiv_quot_apply {J : Type u} [small_category J] (F : J ⥤ Type u) (j : J) (x : functor.obj F j) : coe_fn (colimit_equiv_quot F) (colimit.ι F j x) = Quot.mk (quot.rel F) (sigma.mk j x) := sorry @[simp] theorem colimit.w_apply {J : Type u} [small_category J] {F : J ⥤ Type u} {j : J} {j' : J} {x : functor.obj F j} (f : j ⟶ j') : colimit.ι F j' (functor.map F f x) = colimit.ι F j x := congr_fun (colimit.w F f) x @[simp] theorem colimit.ι_desc_apply {J : Type u} [small_category J] (F : J ⥤ Type u) (s : cocone F) (j : J) (x : functor.obj F j) : colimit.desc F s (colimit.ι F j x) = nat_trans.app (cocone.ι s) j x := congr_fun (colimit.ι_desc s j) x @[simp] theorem colimit.ι_map_apply {J : Type u} [small_category J] {F : J ⥤ Type u} {G : J ⥤ Type u} (α : F ⟶ G) (j : J) (x : functor.obj F j) : functor.map colim α (colimit.ι F j x) = colimit.ι G j (nat_trans.app α j x) := congr_fun (colimit.ι_map α j) x theorem colimit_sound {J : Type u} [small_category J] {F : J ⥤ Type u} {j : J} {j' : J} {x : functor.obj F j} {x' : functor.obj F j'} (f : j ⟶ j') (w : functor.map F f x = x') : colimit.ι F j x = colimit.ι F j' x' := sorry theorem colimit_sound' {J : Type u} [small_category J] {F : J ⥤ Type u} {j : J} {j' : J} {x : functor.obj F j} {x' : functor.obj F j'} {j'' : J} (f : j ⟶ j'') (f' : j' ⟶ j'') (w : functor.map F f x = functor.map F f' x') : colimit.ι F j x = colimit.ι F j' x' := sorry theorem colimit_eq {J : Type u} [small_category J] {F : J ⥤ Type u} {j : J} {j' : J} {x : functor.obj F j} {x' : functor.obj F j'} (w : colimit.ι F j x = colimit.ι F j' x') : eqv_gen (quot.rel F) (sigma.mk j x) (sigma.mk j' x') := sorry theorem jointly_surjective {J : Type u} [small_category J] (F : J ⥤ Type u) {t : cocone F} (h : is_colimit t) (x : cocone.X t) : ∃ (j : J), ∃ (y : functor.obj F j), nat_trans.app (cocone.ι t) j y = x := sorry /-- A variant of `jointly_surjective` for `x : colimit F`. -/ theorem jointly_surjective' {J : Type u} [small_category J] {F : J ⥤ Type u} (x : colimit F) : ∃ (j : J), ∃ (y : functor.obj F j), colimit.ι F j y = x := jointly_surjective F (colimit.is_colimit F) x namespace filtered_colimit /- For filtered colimits of types, we can give an explicit description of the equivalence relation generated by the relation used to form the colimit. -/ /-- An alternative relation on `Σ j, F.obj j`, which generates the same equivalence relation as we use to define the colimit in `Type` above, but that is more convenient when working with filtered colimits. Elements in `F.obj j` and `F.obj j'` are equivalent if there is some `k : J` to the right where their images are equal. -/ protected def r {J : Type u} [small_category J] (F : J ⥤ Type u) (x : sigma fun (j : J) => functor.obj F j) (y : sigma fun (j : J) => functor.obj F j) := ∃ (k : J), ∃ (f : sigma.fst x ⟶ k), ∃ (g : sigma.fst y ⟶ k), functor.map F f (sigma.snd x) = functor.map F g (sigma.snd y) protected theorem r_ge {J : Type u} [small_category J] (F : J ⥤ Type u) (x : sigma fun (j : J) => functor.obj F j) (y : sigma fun (j : J) => functor.obj F j) : (∃ (f : sigma.fst x ⟶ sigma.fst y), sigma.snd y = functor.map F f (sigma.snd x)) → filtered_colimit.r F x y := sorry /-- Recognizing filtered colimits of types. -/ def is_colimit_of {J : Type u} [small_category J] (F : J ⥤ Type u) (t : cocone F) (hsurj : ∀ (x : cocone.X t), ∃ (i : J), ∃ (xi : functor.obj F i), x = nat_trans.app (cocone.ι t) i xi) (hinj : ∀ (i j : J) (xi : functor.obj F i) (xj : functor.obj F j), nat_trans.app (cocone.ι t) i xi = nat_trans.app (cocone.ι t) j xj → ∃ (k : J), ∃ (f : i ⟶ k), ∃ (g : j ⟶ k), functor.map F f xi = functor.map F g xj) : is_colimit t := is_colimit.of_iso_colimit (colimit.is_colimit F) (cocones.ext (equiv.to_iso (equiv.of_bijective (colimit.desc F t) sorry)) sorry) -- Strategy: Prove that the map from "the" colimit of F (defined above) to t.X -- is a bijection. protected theorem r_equiv {J : Type u} [small_category J] (F : J ⥤ Type u) [is_filtered_or_empty J] : equivalence (filtered_colimit.r F) := sorry protected theorem r_eq {J : Type u} [small_category J] (F : J ⥤ Type u) [is_filtered_or_empty J] : filtered_colimit.r F = eqv_gen fun (x y : sigma fun (j : J) => functor.obj F j) => ∃ (f : sigma.fst x ⟶ sigma.fst y), sigma.snd y = functor.map F f (sigma.snd x) := sorry theorem colimit_eq_iff_aux {J : Type u} [small_category J] (F : J ⥤ Type u) [is_filtered_or_empty J] {i : J} {j : J} {xi : functor.obj F i} {xj : functor.obj F j} : nat_trans.app (cocone.ι (colimit_cocone F)) i xi = nat_trans.app (cocone.ι (colimit_cocone F)) j xj ↔ ∃ (k : J), ∃ (f : i ⟶ k), ∃ (g : j ⟶ k), functor.map F f xi = functor.map F g xj := sorry theorem is_colimit_eq_iff {J : Type u} [small_category J] (F : J ⥤ Type u) {t : cocone F} [is_filtered_or_empty J] (ht : is_colimit t) {i : J} {j : J} {xi : functor.obj F i} {xj : functor.obj F j} : nat_trans.app (cocone.ι t) i xi = nat_trans.app (cocone.ι t) j xj ↔ ∃ (k : J), ∃ (f : i ⟶ k), ∃ (g : j ⟶ k), functor.map F f xi = functor.map F g xj := sorry theorem colimit_eq_iff {J : Type u} [small_category J] (F : J ⥤ Type u) [is_filtered_or_empty J] {i : J} {j : J} {xi : functor.obj F i} {xj : functor.obj F j} : colimit.ι F i xi = colimit.ι F j xj ↔ ∃ (k : J), ∃ (f : i ⟶ k), ∃ (g : j ⟶ k), functor.map F f xi = functor.map F g xj := is_colimit_eq_iff F (colimit.is_colimit F) end filtered_colimit /-- the image of a morphism in Type is just `set.range f` -/ def image {α : Type u} {β : Type u} (f : α ⟶ β) := ↥(set.range f) protected instance image.inhabited {α : Type u} {β : Type u} (f : α ⟶ β) [Inhabited α] : Inhabited (image f) := { default := { val := f Inhabited.default, property := sorry } } /-- the inclusion of `image f` into the target -/ def image.ι {α : Type u} {β : Type u} (f : α ⟶ β) : image f ⟶ β := subtype.val protected instance image.ι.category_theory.mono {α : Type u} {β : Type u} (f : α ⟶ β) : mono (image.ι f) := iff.mpr (mono_iff_injective (image.ι f)) subtype.val_injective /-- the universal property for the image factorisation -/ def image.lift {α : Type u} {β : Type u} {f : α ⟶ β} (F' : mono_factorisation f) : image f ⟶ mono_factorisation.I F' := fun (x : image f) => mono_factorisation.e F' (subtype.val (classical.indefinite_description (fun (x_1 : α) => f x_1 = subtype.val x) sorry)) theorem image.lift_fac {α : Type u} {β : Type u} {f : α ⟶ β} (F' : mono_factorisation f) : image.lift F' ≫ mono_factorisation.m F' = image.ι f := sorry /-- the factorisation of any morphism in Type through a mono. -/ def mono_factorisation {α : Type u} {β : Type u} (f : α ⟶ β) : mono_factorisation f := mono_factorisation.mk (image f) (image.ι f) (set.range_factorization f) /-- the facorisation through a mono has the universal property of the image. -/ def is_image {α : Type u} {β : Type u} (f : α ⟶ β) : is_image (mono_factorisation f) := is_image.mk image.lift protected instance category_theory.limits.has_image {α : Type u} {β : Type u} (f : α ⟶ β) : has_image f := has_image.mk (image_factorisation.mk (mono_factorisation f) (is_image f)) protected instance sort.category_theory.limits.has_images : has_images (Type u) := has_images.mk sorry protected instance sort.category_theory.limits.has_image_maps : has_image_maps (Type u) := has_image_maps.mk sorry
"""Lambdata - a collection of Data Science helper functions""" import pandas as pd import numpy as np FAVORITE_NUMBERS = [77,107.32,55,12,3.14] COLORS = ['cyan','teal','mauve','blue','crimson'] def increment(x): return x + 1 def df_cleaner(df): """Cleans a DF""" # TODO - implement df_cleaner pass def df_destroyer(df): """Destroys a DF""" pass
```python import seaborn as sns import matplotlib.pyplot as plt import pandas as pd import numpy as np #sns.set_theme(style="whitegrid") sns.set(rc={'figure.figsize':(16,13)}) ``` ```python # Absolute error def AE(y, y_hat, t, T): resid = np.abs(y - y_hat) return resid ############################################# # Temporal decay loss def EP_td(y, y_hat, t, T, losstype="loss", weight=1): decay = ((T-t)/T) resid = np.abs(y - y_hat) if losstype=="loss": EP = resid**decay if losstype=="penalty": EP = resid+ weight*(resid**decay) return EP # Progressive temporal decay loss def EP_prog_td(y, y_hat, t, T, losstype="loss", weight=1): decay = 1/t resid = np.abs(y - y_hat) if losstype=="loss": EP = resid*decay if losstype=="penalty": EP = resid+ weight*(resid*decay) return EP ``` ### Previous formulations \begin{equation}MAE_{PtD} = \frac{1}{N}\sum_{i=1}^{N}\frac{1}{T}\sum_{t=1}^{T_i}\mid y_{t}^i - \hat{y}_{t}^i\mid ^{\frac{T_i-t}{T_i}}\end{equation} and \begin{equation}MAE_{MtD} = \frac{1}{N}\sum_{i=1}^{N}\frac{1}{T}\sum_{t=1}^{T_i}\frac{\mid y_{t}^i - \hat{y}_{t}^i\mid}{t} \end{equation} ```python """ Missing the "balance" weight to adjust accuracy versus earliness, and missing a more flexible rate of decay form """ ``` ## Useful formulas for exponentials: <b>Radioactive decay example: </b> \begin{equation} X_{t+1} = \frac{X_{t}}{2} \end{equation} Half-life = 1 year <b>Bounded exponential growth (Logistic equation):</b> \begin{equation} X_{t+1} = rX_{t}\left(1-\frac{X_{t}}{max(X)}\right) \end{equation} ```python ``` # New loss formulation Basic components: \begin{equation} MAE + \beta f(MAE,\alpha) \end{equation} Where $\beta$ is the weighting parameter of the earliness component, versus the $\gamma$ parameter that weight normal accuracy. $\alpha$ acts as a decay-rate parameter specifying to which degree the temporal decay should prioritize the earliest events in a sequence/trace. The earliness/penalty component consist of: \begin{equation} f(MAE,\alpha) = \frac{1}{N}\sum_{i=1}^{N}\frac{1}{T}\sum_{t=1}^{T_i}\frac{\mid y_{t}^i - \hat{y}_{t}^i\mid}{\alpha t} \end{equation} and thus the full loss becomes: \begin{equation} MAE_{td}: \frac{1}{N}\sum_{i=1}^{N}\frac{1}{T}\sum_{t=1}^{T_i}\gamma\mid y_{t}^i - \hat{y}_{t}^i\mid + \beta \frac{\mid y_{t}^i - \hat{y}_{t}^i\mid}{\alpha t} \end{equation} However, the first batches of experiments show that adding the accuracy component only leads to inferior performance compared to baseline MAE. Current implementation of MAE_td is thus as simple as: \begin{equation} MAE_{td}: \frac{1}{N}\sum_{i=1}^{N}\frac{1}{T}\sum_{t=1}^{T_i}\frac{\mid y_{t}^i - \hat{y}_{t}^i\mid}{\alpha t} \end{equation} ```python # Temporal decay loss def EP_td(y, y_hat, t, T, losstype="penalty", alpha=1, beta=1, gamma=1): resid = np.abs(y - y_hat) EP = gamma*resid + beta*(resid/t*alpha) return EP ``` ```python def generate_obs(metric, T = 10, alpha = 1, beta = 1, gamma=1, loss_comp="loss"): y = np.linspace(start=250,stop=50, num=10,endpoint=True) y_hat = np.linspace(start=250,stop=50, num=10,endpoint=True)+50 t = np.array([1,2,3,4,5,6,7,8,9,10]) #placeholder resid = [0]*len(t) if metric == "AE": resid = AE(y, y_hat, t, T) if metric == "EP_td": resid = EP_td(y, y_hat, t, T, losstype=loss_comp, alpha=alpha, beta=beta, gamma=gamma) #if metric == "EP_prog_td": # resid = EP_prog_td(y, y_hat, t, T, losstype=loss_comp, weight=weight_1) df = pd.DataFrame({"y":y, "y_hat":y_hat, "t":t, "resid":resid, "loss":[metric]*T, "alpha":[alpha]*T, "beta":[beta]*T, "gamma":[gamma]*T}) return df """ Test the data generator with no loss function """ generate_obs("EP_td", T = 10, alpha = 1, beta = 1, gamma=1, loss_comp="loss") ``` <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>y</th> <th>y_hat</th> <th>t</th> <th>resid</th> <th>loss</th> <th>alpha</th> <th>beta</th> <th>gamma</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>250.000000</td> <td>300.000000</td> <td>1</td> <td>100.000000</td> <td>EP_td</td> <td>1</td> <td>1</td> <td>1</td> </tr> <tr> <th>1</th> <td>227.777778</td> <td>277.777778</td> <td>2</td> <td>75.000000</td> <td>EP_td</td> <td>1</td> <td>1</td> <td>1</td> </tr> <tr> <th>2</th> <td>205.555556</td> <td>255.555556</td> <td>3</td> <td>66.666667</td> <td>EP_td</td> <td>1</td> <td>1</td> <td>1</td> </tr> <tr> <th>3</th> <td>183.333333</td> <td>233.333333</td> <td>4</td> <td>62.500000</td> <td>EP_td</td> <td>1</td> <td>1</td> <td>1</td> </tr> <tr> <th>4</th> <td>161.111111</td> <td>211.111111</td> <td>5</td> <td>60.000000</td> <td>EP_td</td> <td>1</td> <td>1</td> <td>1</td> </tr> <tr> <th>5</th> <td>138.888889</td> <td>188.888889</td> <td>6</td> <td>58.333333</td> <td>EP_td</td> <td>1</td> <td>1</td> <td>1</td> </tr> <tr> <th>6</th> <td>116.666667</td> <td>166.666667</td> <td>7</td> <td>57.142857</td> <td>EP_td</td> <td>1</td> <td>1</td> <td>1</td> </tr> <tr> <th>7</th> <td>94.444444</td> <td>144.444444</td> <td>8</td> <td>56.250000</td> <td>EP_td</td> <td>1</td> <td>1</td> <td>1</td> </tr> <tr> <th>8</th> <td>72.222222</td> <td>122.222222</td> <td>9</td> <td>55.555556</td> <td>EP_td</td> <td>1</td> <td>1</td> <td>1</td> </tr> <tr> <th>9</th> <td>50.000000</td> <td>100.000000</td> <td>10</td> <td>55.000000</td> <td>EP_td</td> <td>1</td> <td>1</td> <td>1</td> </tr> </tbody> </table> </div> ```python metrics_of_interest = ["AE","EP_td"] #,"EP_prog_td" #accuracy/earliness balance betas = [1] #[0, 0.25, 0.5, 0.75, 1.0, 1.25, 1.5, 1.75] gammas = [1] #[0, 0.25, 0.5, 0.75, 1.0, 1.25, 1.5, 1.75] #decay rate parameter alphas = [0, 0.25, 0.5, 0.75, 1.0, 1.25, 1.5, 1.75] data = [] for balance1 in betas: for balance2 in gammas: for rate in alphas: for metric in metrics_of_interest: obs = generate_obs(metric, beta = balance1, gamma=balance2, alpha = rate) data.append(obs) residuals = pd.concat(data) residuals.head() ``` <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>y</th> <th>y_hat</th> <th>t</th> <th>resid</th> <th>loss</th> <th>alpha</th> <th>beta</th> <th>gamma</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>250.000000</td> <td>300.000000</td> <td>1</td> <td>50.0</td> <td>AE</td> <td>0.0</td> <td>1</td> <td>1</td> </tr> <tr> <th>1</th> <td>227.777778</td> <td>277.777778</td> <td>2</td> <td>50.0</td> <td>AE</td> <td>0.0</td> <td>1</td> <td>1</td> </tr> <tr> <th>2</th> <td>205.555556</td> <td>255.555556</td> <td>3</td> <td>50.0</td> <td>AE</td> <td>0.0</td> <td>1</td> <td>1</td> </tr> <tr> <th>3</th> <td>183.333333</td> <td>233.333333</td> <td>4</td> <td>50.0</td> <td>AE</td> <td>0.0</td> <td>1</td> <td>1</td> </tr> <tr> <th>4</th> <td>161.111111</td> <td>211.111111</td> <td>5</td> <td>50.0</td> <td>AE</td> <td>0.0</td> <td>1</td> <td>1</td> </tr> </tbody> </table> </div> ```python g = sns.FacetGrid(residuals, col="alpha", col_wrap=4, height=4, size=3, hue="loss", aspect=1) # g.map(sns.barplot, 't','resid') plt.savefig("loss_functions.png") plt.show() ``` ## Multiple settings ```python metrics_of_interest = ["EP_td"] #,"EP_prog_td" #accuracy/earliness balance betas = [1] #[0, 0.25, 0.5, 0.75, 1.0, 1.25, 1.5, 1.75] gammas = [0, 0.5, 1] #[0, 0.25, 0.5, 0.75, 1.0, 1.25, 1.5, 1.75] #decay rate parameter alphas = [0, 0.75, 1.0, 1.75] data = [] for balance1 in betas: for balance2 in gammas: for rate in alphas: for metric in metrics_of_interest: obs = generate_obs(metric, beta = balance1, gamma=balance2, alpha = rate) data.append(obs) residuals = pd.concat(data) residuals#.head(10) ``` <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>y</th> <th>y_hat</th> <th>t</th> <th>resid</th> <th>loss</th> <th>alpha</th> <th>beta</th> <th>gamma</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>250.000000</td> <td>300.000000</td> <td>1</td> <td>0.000000</td> <td>EP_td</td> <td>0.00</td> <td>1</td> <td>0.0</td> </tr> <tr> <th>1</th> <td>227.777778</td> <td>277.777778</td> <td>2</td> <td>0.000000</td> <td>EP_td</td> <td>0.00</td> <td>1</td> <td>0.0</td> </tr> <tr> <th>2</th> <td>205.555556</td> <td>255.555556</td> <td>3</td> <td>0.000000</td> <td>EP_td</td> <td>0.00</td> <td>1</td> <td>0.0</td> </tr> <tr> <th>3</th> <td>183.333333</td> <td>233.333333</td> <td>4</td> <td>0.000000</td> <td>EP_td</td> <td>0.00</td> <td>1</td> <td>0.0</td> </tr> <tr> <th>4</th> <td>161.111111</td> <td>211.111111</td> <td>5</td> <td>0.000000</td> <td>EP_td</td> <td>0.00</td> <td>1</td> <td>0.0</td> </tr> <tr> <th>...</th> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> </tr> <tr> <th>5</th> <td>138.888889</td> <td>188.888889</td> <td>6</td> <td>64.583333</td> <td>EP_td</td> <td>1.75</td> <td>1</td> <td>1.0</td> </tr> <tr> <th>6</th> <td>116.666667</td> <td>166.666667</td> <td>7</td> <td>62.500000</td> <td>EP_td</td> <td>1.75</td> <td>1</td> <td>1.0</td> </tr> <tr> <th>7</th> <td>94.444444</td> <td>144.444444</td> <td>8</td> <td>60.937500</td> <td>EP_td</td> <td>1.75</td> <td>1</td> <td>1.0</td> </tr> <tr> <th>8</th> <td>72.222222</td> <td>122.222222</td> <td>9</td> <td>59.722222</td> <td>EP_td</td> <td>1.75</td> <td>1</td> <td>1.0</td> </tr> <tr> <th>9</th> <td>50.000000</td> <td>100.000000</td> <td>10</td> <td>58.750000</td> <td>EP_td</td> <td>1.75</td> <td>1</td> <td>1.0</td> </tr> </tbody> </table> <p>120 rows × 8 columns</p> </div> ```python g = sns.FacetGrid(residuals, col="alpha", row="gamma", hue="loss") g.map(sns.barplot, 't','resid') ``` ```python metrics_of_interest = ["EP_td"] #,"EP_prog_td" balance_weights = np.linspace(start=0.5,stop=2, num=4,endpoint=True) #[ 0.5, 1.0, 1.5] rates = np.linspace(start=0.5, stop=2, num=4, endpoint=True) #[1.0, 1.25, 1.5] data = [] for rate in rates: for balance in balance_weights: for metric in metrics_of_interest: obs = generate_obs(metric, balance = balance, rate = rate) data.append(obs) residuals = pd.concat(data) residuals.head(20) ``` <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>y</th> <th>y_hat</th> <th>t</th> <th>resid</th> <th>loss</th> <th>balance</th> <th>rate</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>250.000000</td> <td>300.000000</td> <td>1</td> <td>62.500000</td> <td>EP_td</td> <td>0.5</td> <td>0.5</td> </tr> <tr> <th>1</th> <td>227.777778</td> <td>277.777778</td> <td>2</td> <td>56.250000</td> <td>EP_td</td> <td>0.5</td> <td>0.5</td> </tr> <tr> <th>2</th> <td>205.555556</td> <td>255.555556</td> <td>3</td> <td>54.166667</td> <td>EP_td</td> <td>0.5</td> <td>0.5</td> </tr> <tr> <th>3</th> <td>183.333333</td> <td>233.333333</td> <td>4</td> <td>53.125000</td> <td>EP_td</td> <td>0.5</td> <td>0.5</td> </tr> <tr> <th>4</th> <td>161.111111</td> <td>211.111111</td> <td>5</td> <td>52.500000</td> <td>EP_td</td> <td>0.5</td> <td>0.5</td> </tr> <tr> <th>5</th> <td>138.888889</td> <td>188.888889</td> <td>6</td> <td>52.083333</td> <td>EP_td</td> <td>0.5</td> <td>0.5</td> </tr> <tr> <th>6</th> <td>116.666667</td> <td>166.666667</td> <td>7</td> <td>51.785714</td> <td>EP_td</td> <td>0.5</td> <td>0.5</td> </tr> <tr> <th>7</th> <td>94.444444</td> <td>144.444444</td> <td>8</td> <td>51.562500</td> <td>EP_td</td> <td>0.5</td> <td>0.5</td> </tr> <tr> <th>8</th> <td>72.222222</td> <td>122.222222</td> <td>9</td> <td>51.388889</td> <td>EP_td</td> <td>0.5</td> <td>0.5</td> </tr> <tr> <th>9</th> <td>50.000000</td> <td>100.000000</td> <td>10</td> <td>51.250000</td> <td>EP_td</td> <td>0.5</td> <td>0.5</td> </tr> <tr> <th>0</th> <td>250.000000</td> <td>300.000000</td> <td>1</td> <td>75.000000</td> <td>EP_td</td> <td>1.0</td> <td>0.5</td> </tr> <tr> <th>1</th> <td>227.777778</td> <td>277.777778</td> <td>2</td> <td>62.500000</td> <td>EP_td</td> <td>1.0</td> <td>0.5</td> </tr> <tr> <th>2</th> <td>205.555556</td> <td>255.555556</td> <td>3</td> <td>58.333333</td> <td>EP_td</td> <td>1.0</td> <td>0.5</td> </tr> <tr> <th>3</th> <td>183.333333</td> <td>233.333333</td> <td>4</td> <td>56.250000</td> <td>EP_td</td> <td>1.0</td> <td>0.5</td> </tr> <tr> <th>4</th> <td>161.111111</td> <td>211.111111</td> <td>5</td> <td>55.000000</td> <td>EP_td</td> <td>1.0</td> <td>0.5</td> </tr> <tr> <th>5</th> <td>138.888889</td> <td>188.888889</td> <td>6</td> <td>54.166667</td> <td>EP_td</td> <td>1.0</td> <td>0.5</td> </tr> <tr> <th>6</th> <td>116.666667</td> <td>166.666667</td> <td>7</td> <td>53.571429</td> <td>EP_td</td> <td>1.0</td> <td>0.5</td> </tr> <tr> <th>7</th> <td>94.444444</td> <td>144.444444</td> <td>8</td> <td>53.125000</td> <td>EP_td</td> <td>1.0</td> <td>0.5</td> </tr> <tr> <th>8</th> <td>72.222222</td> <td>122.222222</td> <td>9</td> <td>52.777778</td> <td>EP_td</td> <td>1.0</td> <td>0.5</td> </tr> <tr> <th>9</th> <td>50.000000</td> <td>100.000000</td> <td>10</td> <td>52.500000</td> <td>EP_td</td> <td>1.0</td> <td>0.5</td> </tr> </tbody> </table> </div> ```python g = sns.FacetGrid(residuals, col="balance",row="rate", hue="loss") g.map(sns.barplot, 't','resid') ``` ```python ``` ```python ``` ```python ``` ```python ``` ```python ``` ```python ``` ```python ``` ```python ```
Load LFindLoad. From lfind Require Import LFind. From QuickChick Require Import QuickChick. From adtind Require Import goal33. Derive Show for natural. Derive Arbitrary for natural. Instance Dec_Eq_natural : Dec_Eq natural. Proof. dec_eq. Qed. Lemma conj19eqsynthconj2 : forall (lv0 : natural) (lv1 : natural) (lv2 : natural), (@eq natural (plus (mult lv0 lv1) lv2) (plus lv2 (mult lv1 (plus Zero lv0)))). Admitted. QuickChick conj19eqsynthconj2.
```python # !/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on 20190115 @author: zhangji """ %pylab inline pylab.rcParams['figure.figsize'] = (25, 11) fontsize = 40 import numpy as np import scipy as sp from scipy.optimize import leastsq, curve_fit from scipy import interpolate from scipy.interpolate import interp1d from scipy.io import loadmat, savemat # import scipy.misc import matplotlib from matplotlib import pyplot as plt from matplotlib import animation, rc import matplotlib.ticker as mtick from mpl_toolkits.axes_grid1.inset_locator import inset_axes, zoomed_inset_axes from mpl_toolkits.mplot3d import Axes3D, axes3d from sympy import symbols, simplify, series, exp from sympy.matrices import Matrix from sympy.solvers import solve from IPython.display import display, HTML from tqdm import tqdm_notebook as tqdm import pandas as pd import re from scanf import scanf import os import glob import importlib from time import time from codeStore import support_fun as spf from src.support_class import * rc('animation', html='html5') PWD = os.getcwd() font = {'size': 20} matplotlib.rc('font', **font) np.set_printoptions(linewidth=90, precision=5) ``` Populating the interactive namespace from numpy and matplotlib ```python def read_Liu_Fig2a_results(dir_name): t_dir = os.path.join(PWD, dir_name) txt_names = glob.glob('./%s/*.txt' % dir_name) psi2 = [] psi3 = [] psi61 = [] psi62 = [] ph = [] zf = [] uz = [] for txt_name in txt_names: with open(txt_name, 'r') as ftxt: FILE_DATA = ftxt.read() text_headle = 'Translation, helix forces and torques \[' temp1 = spf.read_array(text_headle, FILE_DATA, array_length=6) psi2.append(temp1[2]) psi61.append(temp1[5]) text_headle = 'Rotation, helix forces and torques \[' temp1 = spf.read_array(text_headle, FILE_DATA, array_length=6) psi62.append(temp1[2]) psi3.append(temp1[5]) text_headle = 'helix pitch: ' temp1 = spf.read_array(text_headle, FILE_DATA, array_length=1) ph.append(temp1) # below is our definition of zf # text_headle = 'geometry zoom factor is ' # temp1 = spf.read_array(text_headle, FILE_DATA, array_length=1) # if np.isclose(temp1, 1): # temp1 = 0 # zf.append(temp1) # below is Liu Bin's definition of zf text_headle = 'geometry zoom factor is ' temp1 = spf.read_array(text_headle, FILE_DATA, array_length=1) t_match = re.search('helix radius: \d+(\.\d+)? and \d+(\.\d+)?', FILE_DATA) rh1, rh2 = scanf('helix radius: %f and %f', FILE_DATA[t_match.start():t_match.end()]) if np.isclose(temp1, 1): temp1 = 0 temp1 = temp1 * (rh1 + rh2) / rh1 zf.append(temp1) text_headle = 'Norm forward helix velocity is ' temp1 = spf.read_array(text_headle, FILE_DATA, array_length=1) uz.append(temp1) data1 = pd.DataFrame({'ph': np.hstack(ph), 'zf': np.hstack(zf), 'psi2': np.hstack(psi2), 'psi3': np.hstack(psi3), 'psi61': np.hstack(psi61), 'psi62': np.hstack(psi62), 'uz': np.hstack(uz), })\ .pivot_table(columns=['zf']) psi2 = data1.loc['psi2'] psi3 = data1.loc['psi3'] psi61 = data1.loc['psi61'] psi62 = data1.loc['psi62'] uz = data1.loc['uz'] return psi2, psi3, psi61, psi62, uz ``` ```python job_name_list = ['theta_0.03', 'theta_0.13', 'theta_0.22', 'theta_0.32', 'theta_0.42'] m_psi_list = [] for job_name in job_name_list: dir_name = 'compare_Liu/mFig_2_a/' + job_name m_psi_list.append(read_Liu_Fig2a_results(dir_name)) fig = plt.figure(figsize=(14, 8)) fig.patch.set_facecolor('white') ax1 = fig.add_subplot(1, 2, 1) ax2 = fig.add_subplot(1, 2, 2) for t_psi, tlabel in zip(m_psi_list, job_name_list): tu = -t_psi[3] / t_psi[0] tu = tu / tu[0] ax1.plot(1 / tu.index, tu.values, '-*', label=tlabel) # ax1.plot(1 / tu.index, t_psi[4] / t_psi[4][0], '-*', label=t_label) ax1.set_xlim(1, 6) ax1.set_ylim(0.5, 4.5) ax1.legend() ax2.semilogy(1 / tu.index, np.abs(t_psi[2]), '-*b') ax2.semilogy(1 / tu.index, np.abs(t_psi[3]), '-^r') plt.tight_layout() ``` ```python fig = plt.figure(figsize=(14, 8)) fig.patch.set_facecolor('white') ax1 = fig.add_subplot(1, 1, 1) ax1.plot([0.81387, 0.2087 , 0.12624, 0.09674, 0.08461], [2000, 1000, 500, 125, 100], '-*') spf.fit_line(ax1, np.array([0.81387, 0.2087 , 0.12624, 0.09674, 0.08461]), np.array([2000, 1000, 500, 125, 100]), 0.1, 1, extendline=True ) tx = np.linspace(0, 1) ax1.plot(tx, 500+tx*2000) ``` ```python ```
Headboards come with matching pipping and buttoning as standard. We can also work with a customer’s own fabric so get in touch through our bespoke option if you’d like to discuss this. Bespoke: We work closely with local joiners to produce our headboards frames so we are more than happy to discuss bespoke commissions, we can help to design headboard shapes or advice on colour combinations as well as working to your own specific dimensions. Feel free to get in touch through the bespoke section of our website.
Require Import AutoSep Malloc Bootstrap FactorialRecur. Module Type S. Variable heapSize : nat. End S. Module Make(M : S). Import M. Section boot. Hypothesis heapSizeLowerBound : (3 <= heapSize)%nat. Definition size := heapSize + 50 + 0. Hypothesis mem_size : goodSize (size * 4)%nat. Let heapSizeUpperBound : goodSize (heapSize * 4). goodSize. Qed. Definition bootS := bootS heapSize 0. Definition boot := bimport [[ "malloc"!"init" @ [Malloc.initS], "top"!"top" @ [topS] ]] bmodule "main" {{ bfunctionNoRet "main"() [bootS] Sp <- (heapSize * 4)%nat;; Assert [PREonly[_] 0 =?> heapSize];; Call "malloc"!"init"(0, heapSize) [PREonly[_] mallocHeap 0];; Call "top"!"top"() [PREonly[_] [| False |] ] end }}. Theorem ok : moduleOk boot. vcgen; abstract genesis. Qed. Definition m0 := link Malloc.m boot. Definition m1 := link all m0. Lemma ok0 : moduleOk m0. link Malloc.ok ok. Qed. Lemma ok1 : moduleOk m1. link all_ok ok0. Qed. Variable stn : settings. Variable prog : program. Hypothesis inj : forall l1 l2 w, Labels stn l1 = Some w -> Labels stn l2 = Some w -> l1 = l2. Hypothesis agree : forall l pre bl, LabelMap.MapsTo l (pre, bl) (XCAP.Blocks m1) -> exists w, Labels stn l = Some w /\ prog w = Some bl. Hypothesis agreeImp : forall l pre, LabelMap.MapsTo l pre (XCAP.Imports m1) -> exists w, Labels stn l = Some w /\ prog w = None. Hypothesis omitImp : forall l w, Labels stn ("sys", l) = Some w -> prog w = None. Variable w : W. Hypothesis at_start : Labels stn ("main", Global "main") = Some w. Variable st : state. Hypothesis mem_low : forall n, (n < size * 4)%nat -> st.(Mem) n <> None. Hypothesis mem_high : forall w, ($(size * 4) <= w)%word -> st.(Mem) w = None. Theorem safe : sys_safe stn prog (w, st). safety ok1. Qed. End boot. End Make.
[STATEMENT] lemma tp_1_permutation_action: assumes "a \<in> carrier (Q\<^sub>p\<^bsup>i\<^esup>)" assumes "b \<in> carrier (Q\<^sub>p\<^bsup>j\<^esup>)" assumes "c \<in> carrier (Q\<^sub>p\<^bsup>n\<^esup>)" shows "permute_list (tp_1 i j) (b@a@c)= a@b@c" [PROOF STATE] proof (prove) goal (1 subgoal): 1. permute_list (tp_1 i j) (b @ a @ c) = a @ b @ c [PROOF STEP] proof- [PROOF STATE] proof (state) goal (1 subgoal): 1. permute_list (tp_1 i j) (b @ a @ c) = a @ b @ c [PROOF STEP] have 0:"length (permute_list (tp_1 i j) (b@a@c))= length (a@b@c)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. length (permute_list (tp_1 i j) (b @ a @ c)) = length (a @ b @ c) [PROOF STEP] by (metis add.commute append.assoc length_append length_permute_list) [PROOF STATE] proof (state) this: length (permute_list (tp_1 i j) (b @ a @ c)) = length (a @ b @ c) goal (1 subgoal): 1. permute_list (tp_1 i j) (b @ a @ c) = a @ b @ c [PROOF STEP] have "\<And>x. x < length (a@b@c) \<Longrightarrow> (permute_list (tp_1 i j) (b@a@c)) ! x= (a@b@c) ! x" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>x. x < length (a @ b @ c) \<Longrightarrow> permute_list (tp_1 i j) (b @ a @ c) ! x = (a @ b @ c) ! x [PROOF STEP] proof- [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>x. x < length (a @ b @ c) \<Longrightarrow> permute_list (tp_1 i j) (b @ a @ c) ! x = (a @ b @ c) ! x [PROOF STEP] fix x [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>x. x < length (a @ b @ c) \<Longrightarrow> permute_list (tp_1 i j) (b @ a @ c) ! x = (a @ b @ c) ! x [PROOF STEP] assume A: "x < length (a@b@c)" [PROOF STATE] proof (state) this: x < length (a @ b @ c) goal (1 subgoal): 1. \<And>x. x < length (a @ b @ c) \<Longrightarrow> permute_list (tp_1 i j) (b @ a @ c) ! x = (a @ b @ c) ! x [PROOF STEP] have B: "length (a @ b @ c) = i + j + length c" [PROOF STATE] proof (prove) goal (1 subgoal): 1. length (a @ b @ c) = i + j + length c [PROOF STEP] using add.assoc assms(1) assms(2) cartesian_power_car_memE length_append [PROOF STATE] proof (prove) using this: ?a + ?b + ?c = ?a + (?b + ?c) a \<in> carrier (Q\<^sub>p\<^bsup>i\<^esup>) b \<in> carrier (Q\<^sub>p\<^bsup>j\<^esup>) ?as \<in> carrier (?R\<^bsup>?n\<^esup>) \<Longrightarrow> length ?as = ?n length (?xs @ ?ys) = length ?xs + length ?ys goal (1 subgoal): 1. length (a @ b @ c) = i + j + length c [PROOF STEP] by metis [PROOF STATE] proof (state) this: length (a @ b @ c) = i + j + length c goal (1 subgoal): 1. \<And>x. x < length (a @ b @ c) \<Longrightarrow> permute_list (tp_1 i j) (b @ a @ c) ! x = (a @ b @ c) ! x [PROOF STEP] have C: "tp_1 i j permutes {..<length (a @ b @ c)}" [PROOF STATE] proof (prove) goal (1 subgoal): 1. tp_1 i j permutes {..<length (a @ b @ c)} [PROOF STEP] using B assms tp_1_permutes'[of i j "length b"] tp_1_permutes' [PROOF STATE] proof (prove) using this: length (a @ b @ c) = i + j + length c a \<in> carrier (Q\<^sub>p\<^bsup>i\<^esup>) b \<in> carrier (Q\<^sub>p\<^bsup>j\<^esup>) c \<in> carrier (Q\<^sub>p\<^bsup>n\<^esup>) tp_1 i j permutes {..<i + j + length b} tp_1 ?i ?j permutes {..<?i + ?j + ?k} goal (1 subgoal): 1. tp_1 i j permutes {..<length (a @ b @ c)} [PROOF STEP] by presburger [PROOF STATE] proof (state) this: tp_1 i j permutes {..<length (a @ b @ c)} goal (1 subgoal): 1. \<And>x. x < length (a @ b @ c) \<Longrightarrow> permute_list (tp_1 i j) (b @ a @ c) ! x = (a @ b @ c) ! x [PROOF STEP] have D: "length a = i" [PROOF STATE] proof (prove) goal (1 subgoal): 1. length a = i [PROOF STEP] using assms(1) cartesian_power_car_memE [PROOF STATE] proof (prove) using this: a \<in> carrier (Q\<^sub>p\<^bsup>i\<^esup>) ?as \<in> carrier (?R\<^bsup>?n\<^esup>) \<Longrightarrow> length ?as = ?n goal (1 subgoal): 1. length a = i [PROOF STEP] by blast [PROOF STATE] proof (state) this: length a = i goal (1 subgoal): 1. \<And>x. x < length (a @ b @ c) \<Longrightarrow> permute_list (tp_1 i j) (b @ a @ c) ! x = (a @ b @ c) ! x [PROOF STEP] have E: "length b = j" [PROOF STATE] proof (prove) goal (1 subgoal): 1. length b = j [PROOF STEP] using assms(2) cartesian_power_car_memE [PROOF STATE] proof (prove) using this: b \<in> carrier (Q\<^sub>p\<^bsup>j\<^esup>) ?as \<in> carrier (?R\<^bsup>?n\<^esup>) \<Longrightarrow> length ?as = ?n goal (1 subgoal): 1. length b = j [PROOF STEP] by blast [PROOF STATE] proof (state) this: length b = j goal (1 subgoal): 1. \<And>x. x < length (a @ b @ c) \<Longrightarrow> permute_list (tp_1 i j) (b @ a @ c) ! x = (a @ b @ c) ! x [PROOF STEP] show "(permute_list (tp_1 i j) (b@a@c)) ! x= (a@b@c) ! x" [PROOF STATE] proof (prove) goal (1 subgoal): 1. permute_list (tp_1 i j) (b @ a @ c) ! x = (a @ b @ c) ! x [PROOF STEP] proof(cases "x < i") [PROOF STATE] proof (state) goal (2 subgoals): 1. x < i \<Longrightarrow> permute_list (tp_1 i j) (b @ a @ c) ! x = (a @ b @ c) ! x 2. \<not> x < i \<Longrightarrow> permute_list (tp_1 i j) (b @ a @ c) ! x = (a @ b @ c) ! x [PROOF STEP] case True [PROOF STATE] proof (state) this: x < i goal (2 subgoals): 1. x < i \<Longrightarrow> permute_list (tp_1 i j) (b @ a @ c) ! x = (a @ b @ c) ! x 2. \<not> x < i \<Longrightarrow> permute_list (tp_1 i j) (b @ a @ c) ! x = (a @ b @ c) ! x [PROOF STEP] have T0: "(tp_1 i j x) = j + x" [PROOF STATE] proof (prove) goal (1 subgoal): 1. tp_1 i j x = j + x [PROOF STEP] using tp_1_def[of i j ] True [PROOF STATE] proof (prove) using this: tp_1 i j = (\<lambda>n. if n < i then j + n else if i \<le> n \<and> n < i + j then n - i else n) x < i goal (1 subgoal): 1. tp_1 i j x = j + x [PROOF STEP] by auto [PROOF STATE] proof (state) this: tp_1 i j x = j + x goal (2 subgoals): 1. x < i \<Longrightarrow> permute_list (tp_1 i j) (b @ a @ c) ! x = (a @ b @ c) ! x 2. \<not> x < i \<Longrightarrow> permute_list (tp_1 i j) (b @ a @ c) ! x = (a @ b @ c) ! x [PROOF STEP] then [PROOF STATE] proof (chain) picking this: tp_1 i j x = j + x [PROOF STEP] have "(b@ a @ c) ! (tp_1 i j x) = a!x" [PROOF STATE] proof (prove) using this: tp_1 i j x = j + x goal (1 subgoal): 1. (b @ a @ c) ! tp_1 i j x = a ! x [PROOF STEP] using D E assms(1) assms(2) assms(3) True nth_append [PROOF STATE] proof (prove) using this: tp_1 i j x = j + x length a = i length b = j a \<in> carrier (Q\<^sub>p\<^bsup>i\<^esup>) b \<in> carrier (Q\<^sub>p\<^bsup>j\<^esup>) c \<in> carrier (Q\<^sub>p\<^bsup>n\<^esup>) x < i (?xs @ ?ys) ! ?n = (if ?n < length ?xs then ?xs ! ?n else ?ys ! (?n - length ?xs)) goal (1 subgoal): 1. (b @ a @ c) ! tp_1 i j x = a ! x [PROOF STEP] by (metis nth_append_length_plus) [PROOF STATE] proof (state) this: (b @ a @ c) ! tp_1 i j x = a ! x goal (2 subgoals): 1. x < i \<Longrightarrow> permute_list (tp_1 i j) (b @ a @ c) ! x = (a @ b @ c) ! x 2. \<not> x < i \<Longrightarrow> permute_list (tp_1 i j) (b @ a @ c) ! x = (a @ b @ c) ! x [PROOF STEP] then [PROOF STATE] proof (chain) picking this: (b @ a @ c) ! tp_1 i j x = a ! x [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: (b @ a @ c) ! tp_1 i j x = a ! x goal (1 subgoal): 1. permute_list (tp_1 i j) (b @ a @ c) ! x = (a @ b @ c) ! x [PROOF STEP] using A B C assms permute_list_nth[of "tp_1 i j" "a@b@c"] [PROOF STATE] proof (prove) using this: (b @ a @ c) ! tp_1 i j x = a ! x x < length (a @ b @ c) length (a @ b @ c) = i + j + length c tp_1 i j permutes {..<length (a @ b @ c)} a \<in> carrier (Q\<^sub>p\<^bsup>i\<^esup>) b \<in> carrier (Q\<^sub>p\<^bsup>j\<^esup>) c \<in> carrier (Q\<^sub>p\<^bsup>n\<^esup>) \<lbrakk>tp_1 i j permutes {..<length (a @ b @ c)}; ?i < length (a @ b @ c)\<rbrakk> \<Longrightarrow> permute_list (tp_1 i j) (a @ b @ c) ! ?i = (a @ b @ c) ! tp_1 i j ?i goal (1 subgoal): 1. permute_list (tp_1 i j) (b @ a @ c) ! x = (a @ b @ c) ! x [PROOF STEP] by (metis D True \<open>length (permute_list (tp_1 i j) (b @ a @ c)) = length (a @ b @ c)\<close> length_permute_list nth_append permute_list_nth) [PROOF STATE] proof (state) this: permute_list (tp_1 i j) (b @ a @ c) ! x = (a @ b @ c) ! x goal (1 subgoal): 1. \<not> x < i \<Longrightarrow> permute_list (tp_1 i j) (b @ a @ c) ! x = (a @ b @ c) ! x [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. \<not> x < i \<Longrightarrow> permute_list (tp_1 i j) (b @ a @ c) ! x = (a @ b @ c) ! x [PROOF STEP] case False [PROOF STATE] proof (state) this: \<not> x < i goal (1 subgoal): 1. \<not> x < i \<Longrightarrow> permute_list (tp_1 i j) (b @ a @ c) ! x = (a @ b @ c) ! x [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) goal (1 subgoal): 1. permute_list (tp_1 i j) (b @ a @ c) ! x = (a @ b @ c) ! x [PROOF STEP] proof(cases "x < i + j") [PROOF STATE] proof (state) goal (2 subgoals): 1. x < i + j \<Longrightarrow> permute_list (tp_1 i j) (b @ a @ c) ! x = (a @ b @ c) ! x 2. \<not> x < i + j \<Longrightarrow> permute_list (tp_1 i j) (b @ a @ c) ! x = (a @ b @ c) ! x [PROOF STEP] case True [PROOF STATE] proof (state) this: x < i + j goal (2 subgoals): 1. x < i + j \<Longrightarrow> permute_list (tp_1 i j) (b @ a @ c) ! x = (a @ b @ c) ! x 2. \<not> x < i + j \<Longrightarrow> permute_list (tp_1 i j) (b @ a @ c) ! x = (a @ b @ c) ! x [PROOF STEP] then [PROOF STATE] proof (chain) picking this: x < i + j [PROOF STEP] have T0: "(tp_1 i j x) = x - i" [PROOF STATE] proof (prove) using this: x < i + j goal (1 subgoal): 1. tp_1 i j x = x - i [PROOF STEP] by (meson False not_less tp_1_def) [PROOF STATE] proof (state) this: tp_1 i j x = x - i goal (2 subgoals): 1. x < i + j \<Longrightarrow> permute_list (tp_1 i j) (b @ a @ c) ! x = (a @ b @ c) ! x 2. \<not> x < i + j \<Longrightarrow> permute_list (tp_1 i j) (b @ a @ c) ! x = (a @ b @ c) ! x [PROOF STEP] have "x - i < length b" [PROOF STATE] proof (prove) goal (1 subgoal): 1. x - i < length b [PROOF STEP] using E False True [PROOF STATE] proof (prove) using this: length b = j \<not> x < i x < i + j goal (1 subgoal): 1. x - i < length b [PROOF STEP] by linarith [PROOF STATE] proof (state) this: x - i < length b goal (2 subgoals): 1. x < i + j \<Longrightarrow> permute_list (tp_1 i j) (b @ a @ c) ! x = (a @ b @ c) ! x 2. \<not> x < i + j \<Longrightarrow> permute_list (tp_1 i j) (b @ a @ c) ! x = (a @ b @ c) ! x [PROOF STEP] then [PROOF STATE] proof (chain) picking this: x - i < length b [PROOF STEP] have T1: "permute_list (tp_1 i j) (b@ a @ c) ! x = b!(x-i)" [PROOF STATE] proof (prove) using this: x - i < length b goal (1 subgoal): 1. permute_list (tp_1 i j) (b @ a @ c) ! x = b ! (x - i) [PROOF STEP] using nth_append [PROOF STATE] proof (prove) using this: x - i < length b (?xs @ ?ys) ! ?n = (if ?n < length ?xs then ?xs ! ?n else ?ys ! (?n - length ?xs)) goal (1 subgoal): 1. permute_list (tp_1 i j) (b @ a @ c) ! x = b ! (x - i) [PROOF STEP] by (metis A C T0 \<open>length (permute_list (tp_1 i j) (b @ a @ c)) = length (a @ b @ c)\<close> length_permute_list permute_list_nth) [PROOF STATE] proof (state) this: permute_list (tp_1 i j) (b @ a @ c) ! x = b ! (x - i) goal (2 subgoals): 1. x < i + j \<Longrightarrow> permute_list (tp_1 i j) (b @ a @ c) ! x = (a @ b @ c) ! x 2. \<not> x < i + j \<Longrightarrow> permute_list (tp_1 i j) (b @ a @ c) ! x = (a @ b @ c) ! x [PROOF STEP] then [PROOF STATE] proof (chain) picking this: permute_list (tp_1 i j) (b @ a @ c) ! x = b ! (x - i) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: permute_list (tp_1 i j) (b @ a @ c) ! x = b ! (x - i) goal (1 subgoal): 1. permute_list (tp_1 i j) (b @ a @ c) ! x = (a @ b @ c) ! x [PROOF STEP] by (metis D False \<open>x - i < length b\<close> nth_append) [PROOF STATE] proof (state) this: permute_list (tp_1 i j) (b @ a @ c) ! x = (a @ b @ c) ! x goal (1 subgoal): 1. \<not> x < i + j \<Longrightarrow> permute_list (tp_1 i j) (b @ a @ c) ! x = (a @ b @ c) ! x [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. \<not> x < i + j \<Longrightarrow> permute_list (tp_1 i j) (b @ a @ c) ! x = (a @ b @ c) ! x [PROOF STEP] case False [PROOF STATE] proof (state) this: \<not> x < i + j goal (1 subgoal): 1. \<not> x < i + j \<Longrightarrow> permute_list (tp_1 i j) (b @ a @ c) ! x = (a @ b @ c) ! x [PROOF STEP] then [PROOF STATE] proof (chain) picking this: \<not> x < i + j [PROOF STEP] have "(tp_1 i j x) = x" [PROOF STATE] proof (prove) using this: \<not> x < i + j goal (1 subgoal): 1. tp_1 i j x = x [PROOF STEP] by (meson tp_1_def trans_less_add1) [PROOF STATE] proof (state) this: tp_1 i j x = x goal (1 subgoal): 1. \<not> x < i + j \<Longrightarrow> permute_list (tp_1 i j) (b @ a @ c) ! x = (a @ b @ c) ! x [PROOF STEP] then [PROOF STATE] proof (chain) picking this: tp_1 i j x = x [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: tp_1 i j x = x goal (1 subgoal): 1. permute_list (tp_1 i j) (b @ a @ c) ! x = (a @ b @ c) ! x [PROOF STEP] by (smt A C D E False add.commute add_diff_inverse_nat append.assoc length_append nth_append_length_plus permute_list_nth) [PROOF STATE] proof (state) this: permute_list (tp_1 i j) (b @ a @ c) ! x = (a @ b @ c) ! x goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: permute_list (tp_1 i j) (b @ a @ c) ! x = (a @ b @ c) ! x goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: permute_list (tp_1 i j) (b @ a @ c) ! x = (a @ b @ c) ! x goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: ?x4 < length (a @ b @ c) \<Longrightarrow> permute_list (tp_1 i j) (b @ a @ c) ! ?x4 = (a @ b @ c) ! ?x4 goal (1 subgoal): 1. permute_list (tp_1 i j) (b @ a @ c) = a @ b @ c [PROOF STEP] then [PROOF STATE] proof (chain) picking this: ?x4 < length (a @ b @ c) \<Longrightarrow> permute_list (tp_1 i j) (b @ a @ c) ! ?x4 = (a @ b @ c) ! ?x4 [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: ?x4 < length (a @ b @ c) \<Longrightarrow> permute_list (tp_1 i j) (b @ a @ c) ! ?x4 = (a @ b @ c) ! ?x4 goal (1 subgoal): 1. permute_list (tp_1 i j) (b @ a @ c) = a @ b @ c [PROOF STEP] using 0 [PROOF STATE] proof (prove) using this: ?x4 < length (a @ b @ c) \<Longrightarrow> permute_list (tp_1 i j) (b @ a @ c) ! ?x4 = (a @ b @ c) ! ?x4 length (permute_list (tp_1 i j) (b @ a @ c)) = length (a @ b @ c) goal (1 subgoal): 1. permute_list (tp_1 i j) (b @ a @ c) = a @ b @ c [PROOF STEP] by (metis list_eq_iff_nth_eq) [PROOF STATE] proof (state) this: permute_list (tp_1 i j) (b @ a @ c) = a @ b @ c goal: No subgoals! [PROOF STEP] qed