Datasets:
AI4M
/

text
stringlengths
0
3.34M
''' Assume df is a pandas dataframe object of the dataset given ''' import numpy as np import pandas as pd import random ''' Calculate the entropy of a target attribute ''' def entropy(target_attribute): elements, counts = np.unique(target_attribute,return_counts = True) entropy = np.sum([(-counts[i]/np.sum(counts))*np.log2(counts[i]/np.sum(counts)) for i in range(len(elements))]) return entropy ''' Calculate the entropy of the entire dataset #input:pandas_dataframe #output:int/float/double/large ''' def get_entropy_of_dataset(df): elements, counts = np.unique(df[df.columns[-1]], return_counts = True) total_entropy = np.sum([(-counts[i]/np.sum(counts))*np.log2(counts[i]/np.sum(counts)) for i in range(len(elements))]) return total_entropy ''' Return entropy of the attribute provided as parameter #input:pandas_dataframe,str {i.e the column name ,ex: Temperature in the Play tennis dataset} #output:int/float/double/large ''' def get_entropy_of_attribute(df,attribute): vals, counts= np.unique(df[attribute],return_counts=True) entropy_of_attribute = np.sum([(counts[i]/np.sum(counts))*entropy(df.where(df[attribute]==vals[i]).dropna()[df.columns[-1]]) for i in range(len(vals))]) return abs(entropy_of_attribute) ''' Return Information Gain of the attribute provided as parameter #input:int/float/double/large,int/float/double/large #output:int/float/double/large ''' def get_information_gain(df,attribute): return (get_entropy_of_dataset(df) - get_entropy_of_attribute(df,attribute)) ''' Returns Attribute with highest info gain #input: pandas_dataframe #output: ({dict},'str') Return a tuple with the first element as a dictionary which has IG of all columns and the second element as a string with the name of the column selected ''' def get_selected_attribute(df): information_gains = {} for i in range(len(df.columns)-1): information_gains[df.columns[i]]=get_information_gain(df,df.columns[i]) selected_column = max(information_gains, key = information_gains.get) return (information_gains,selected_column)
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #pragma once #include <memory> #include <numeric> #include <algorithm> #include <vector> #include <string> #include <limits> #include <memory> #include <optional> #include <list> #include <map> #include <deque> #include <chrono> #include <variant> #include <cassert> #include <wrl/client.h> #include <wrl/implements.h> #include <wil/wrl.h> #include <wil/result.h> #include <gsl/gsl> #include <d3d12.h> #include <d3d12sdklayers.h> #include "External/D3DX12/d3dx12.h" #include <DirectML.h> #include "core/common/common.h" #include "ErrorHandling.h" // DirectML helper libraries #include "External/DirectMLHelpers/ApiTraits.h" #include "External/DirectMLHelpers/ApiHelpers.h" #include "External/DirectMLHelpers/DirectMLSchema.h" #include "External/DirectMLHelpers/AbstractOperatorDesc.h" #include "External/DirectMLHelpers/GeneratedSchemaTypes.h" #include "External/DirectMLHelpers/SchemaHelpers.h" #include "External/DirectMLHelpers/GeneratedSchemaHelpers.h" using Microsoft::WRL::ComPtr; // Windows pollutes the macro space, causing a build break in schema.h. #undef OPTIONAL #include "core/providers/dml/DmlExecutionProvider/inc/DmlExecutionProvider.h" #include "core/providers/dml/OperatorAuthorHelper/MLOperatorAuthorHelper.h" #include "core/providers/dml/OperatorAuthorHelper/Common.h" #include "DmlCommon.h" #include "TensorDesc.h" #include "DescriptorPool.h" #include "IExecutionProvider.h"
------------------------------------------------------------------------ -- The Agda standard library -- -- Examples of format strings and printf ------------------------------------------------------------------------ {-# OPTIONS --safe --without-K #-} module README.Text.Printf where open import Data.Nat.Base open import Data.Char.Base open import Data.List.Base open import Data.String.Base open import Data.Sum.Base open import Relation.Binary.PropositionalEquality ------------------------------------------------------------------------ -- Format strings open import Text.Format -- We can specify a format by writing a string which will get interpreted -- by a lexer into a list of formatting directives. -- The specification types are always started with a '%' character: -- Integers (%d or %i) -- Naturals (%u) -- Floats (%f) -- Chars (%c) -- Strings (%s) -- Anything which is not a type specification is a raw string to be spliced -- in the output of printf. -- For instance the following format alternates types and raw strings _ : lexer "%s: %u + %u ≡ %u" ≡ inj₂ (`String ∷ Raw ": " ∷ `ℕ ∷ Raw " + " ∷ `ℕ ∷ Raw " ≡ " ∷ `ℕ ∷ []) _ = refl -- Lexing can fail. There are two possible errors: -- If we start a specification type with a '%' but the string ends then -- we get an UnexpectedEndOfString error _ : lexer "%s: %u + %u ≡ %" ≡ inj₁ (UnexpectedEndOfString "%s: %u + %u ≡ %") _ = refl -- If we start a specification type with a '%' and the following character -- does not correspond to an existing type, we get an InvalidType error -- together with a focus highlighting the position of the problematic type. _ : lexer "%s: %u + %a ≡ %u" ≡ inj₁ (InvalidType "%s: %u + %" 'a' " ≡ %u") _ = refl ------------------------------------------------------------------------ -- Printf open import Text.Printf -- printf is a function which takes a format string as an argument and -- returns a function expecting a value for each type specification present -- in the format and returns a string splicing in these values into the -- format string. -- For instance `printf "%s: %u + %u ≡ %u"` is a -- `String → ℕ → ℕ → ℕ → String` function. _ : String → ℕ → ℕ → ℕ → String _ = printf "%s: %u + %u ≡ %u" _ : printf "%s: %u + %u ≡ %u" "example" 3 2 5 ≡ "example: 3 + 2 ≡ 5" _ = refl -- If the format string str is invalid then `printf str` will have type -- `Error e` where `e` is the lexing error. _ : Text.Printf.Error (UnexpectedEndOfString "%s: %u + %u ≡ %") _ = printf "%s: %u + %u ≡ %" _ : Text.Printf.Error (InvalidType "%s: %u + %" 'a' " ≡ %u") _ = printf "%s: %u + %a ≡ %u" -- Trying to pass arguments to such an ̀Error` type will lead to a -- unification error which hopefully makes the problem clear e.g. -- `printf "%s: %u + %a ≡ %u" "example" 3 2 5` fails with the error: -- Text.Printf.Error (InvalidType "%s: %u + %" 'a' " ≡ %u") should be -- a function type, but it isn't -- when checking that "example" 3 2 5 are valid arguments to a -- function of type Text.Printf.Printf (lexer "%s: %u + %a ≡ %u")
/*! -*-c++-*- @file facecrop.cpp @author David Hirvonen @brief Batch processing to parse and synthesize new face images from various databases. \copyright Copyright 2017 Elucideye, Inc. All rights reserved. \license{This project is released under the 3 Clause BSD License.} 1) POSITIVES --input=<FILE> : filename + (optional) landmarks --format=(two|drishti|lfw|muct|helen|bioid|lfpw) --output=<POSITIVE_DIR> 2) POSITIVES + NEGATIVES (non-overlapping negatives) :: This would require adding object detection internally, it seems cleaner to leave hard negative :: sampling to another application. --input=<FILE> : filename + (optional) landmarks --format=(two|drishti|lfw|muct|helen|bioid|lfpw) --output=<POSITIVE_DIR> --negatives=<NEGATIVE_DIR> 3) NEGATIVES ONLY (raw input file list containing no faces) --input=<FILE> : filename + (optional) landmarks --format=raw --negatives=<NEGATIVE_DIR> 4) NEGATIVES w/ INPAINTING --input=<FILE> : filename + (optional) landmarks --format=raw --inpaint --background=<FILE> : background image list (no positives) --negatives=<NEGATIVE_DIR> */ #include "drishti/core/drishti_stdlib_string.h" // android workaround #include "drishti/core/Logger.h" #include "drishti/core/make_unique.h" #include "drishti/core/Parallel.h" #include "drishti/core/LazyParallelResource.h" #include "drishti/core/drishti_string_hash.h" #include "drishti/core/string_utils.h" #include "drishti/geometry/motion.h" #include "drishti/testlib/drishti_cli.h" #include "drishti/core/drishti_cv_cereal.h" #include "drishti/face/Face.h" // for face model // clang-format off #if defined(DRISHTI_BUILD_EOS) # include "drishti/face/FaceMeshMapperEOSLandmark.h" #endif // clang-format on #include "landmarks/FACE.h" #include "landmarks/MUCT.h" #include "landmarks/HELEN.h" #include "landmarks/BIOID.h" #include "landmarks/LFW.h" #include "landmarks/LFPW.h" #include "landmarks/DRISHTI.h" #include "landmarks/TWO.h" #include "landmarks/DlibXML.h" #include "FaceSpecification.h" #include "FaceJitterer.h" #include "Pyramid.h" // clang-format off #if defined(DRISHTI_USE_IMSHOW) # include "imshow/imshow.h" #endif // clang-format on #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <cereal/archives/json.hpp> #include <cereal/archives/xml.hpp> #include <cereal/types/array.hpp> #include <cereal/types/map.hpp> #include <Eigen/Geometry> #include "cxxopts.hpp" #include <fstream> enum GroundTruthFormat { MUCTFormat, FDDBFormat, HELENFormat, BIOIDFormat, LFWFormat, DRISHTIFormat, LFPWFormat, TWOFormat, RAWFormat }; #define SUPPORTED_FORMATS "muct,fddb,helen,bioid,lfw,drishti,lfpw,two" struct GroundTruth { GroundTruth() = default; GroundTruth(FACE::Table table, GroundTruthFormat format) : table(std::move(table)) , format(format) { } FACE::Table table; GroundTruthFormat format = MUCTFormat; }; // ######################### SHA1 ##################################### #include <cstdio> #include <string> #include <boost/version.hpp> // BOOST_VERSION #if (BOOST_VERSION >= 106800) # include <boost/uuid/detail/sha1.hpp> #else # include <boost/uuid/sha1.hpp> #endif #include <utility> std::string get_sha1(void const* buffer, std::size_t byte_count) { boost::uuids::detail::sha1 sha1; sha1.process_bytes(buffer, byte_count); unsigned hash[5] = { 0 }; sha1.get_digest(hash); // Back to string char buf[41] = { 0 }; for (int i = 0; i < 5; i++) { std::sprintf(buf + (i << 3), "%08x", hash[i]); } return std::string(buf); } /// ######################## >> FACE << ############################# struct FaceJittererMean : public FaceJitterer { FaceJittererMean(const FACE::Table& table, const FaceSpecification& face, const JitterParams& params) : FaceJitterer(table, face, params) { } void updateMean(const std::vector<FaceWithLandmarks>& faces) { for (const auto& f : faces) { mu.updateMean(f); jitteredFaces.push_back(f); } } // Maintain a list of jittered faces std::vector<FaceWithLandmarks> jitteredFaces; FaceWithLandmarksMean mu; }; // ----------------------------------------------- using ImageVec = std::vector<cv::Mat>; using FaceJittererMeanPtr = std::unique_ptr<FaceJittererMean>; using FaceResourceManager = drishti::core::LazyParallelResource<std::thread::id, FaceJittererMeanPtr>; static int saveNegatives(const FACE::Table& table, const std::string& sOutput, int sampleCount, int winSize, int threads, spdlog::logger& logger); static int saveInpaintedSamples(const FACE::Table& table, const std::string& sBackground, const std::string& sOutput, spdlog::logger& logger); static FaceWithLandmarks computeMeanFace(FaceResourceManager& manager); static void saveMeanFace(FaceResourceManager& manager, const FaceSpecification& faceSpec, const std::string& sImage, const std::string& sPoints, spdlog::logger& logger); static int saveDefaultConfigs(const std::string& sOutput, spdlog::logger& logger); static void save(std::vector<FaceWithLandmarks>& faces, const cv::Rect& roi, const std::string& dir, const std::string& filename, int index); static void previewFaceWithLandmarks(cv::Mat& image, const std::vector<cv::Point2f>& landmarks); static GroundTruth parseInput(const std::string& sInput, const std::string& sFormat, const std::string& sDirectoryIn, const std::string& sExtension); static FACE::Table parseRAW(const std::string& sInput); static int standardizeFaceData(const FACE::Table& table, const std::string& sOutput); #if defined(DRISHTI_BUILD_EOS) // Face pose estimation... using FaceMeshMapperPtr = std::unique_ptr<drishti::face::FaceMeshMapperEOSLandmark>; using FaceMeshMapperResourceManager = drishti::core::LazyParallelResource<std::thread::id, FaceMeshMapperPtr>; static void computePose(FACE::Table& table, const std::string& sModel, const std::string& sMapping, std::shared_ptr<spdlog::logger>& logger); #endif // DRISHTI_BUILD_POSE int gauze_main(int argc, char* argv[]) { const auto argumentCount = argc; // Instantiate line logger: auto logger = drishti::core::Logger::create("drishti-facecrop"); // ############################ // ### Command line parsing ### // ############################ std::string sInput; std::string sFormat; std::string sPositives; std::string sNegatives; std::string sDirectory; std::string sExtension; std::string sBackground; std::string sStandardize; std::string sFaceSpec; std::string sJitterIn; std::string sLandmarks; #if defined(DRISHTI_BUILD_EOS) std::string sEosModel; std::string sEosMapping; #endif int sampleCount = 0; int winSize = 48; // min crop width int threads = -1; bool doInpaint = false; bool doPreview = false; bool doBoilerplate = false; /* * These two parameters work in combination with the "--jitter" option * to control the cropping mode. */ bool doPhotometricJitter = false; bool doMirror = false; cxxopts::Options options("drishti-facecrop", "Command line interface for facecrop object detection."); // clang-format off options.add_options() ("i,input", "Input file", cxxopts::value<std::string>(sInput)) ("p,positives", "Positives directory", cxxopts::value<std::string>(sPositives)) ("f,format", "Format:" SUPPORTED_FORMATS, cxxopts::value<std::string>(sFormat)) ("d,directory", "Base (d)irectory", cxxopts::value<std::string>(sDirectory)) ("s,specification", "Face specification", cxxopts::value<std::string>(sFaceSpec)) ("j,jitter", "Jitter input parameters", cxxopts::value<std::string>(sJitterIn)) ("n,number", "Number of output samples to generate", cxxopts::value<int>(sampleCount)) ("b,boilerplate", "Write boilerplate config to output dir", cxxopts::value<bool>(doBoilerplate)) ("e,extension", "Image filename extensions", cxxopts::value<std::string>(sExtension)) ("w,window", "Do preview window", cxxopts::value<bool>(doPreview)) ("0,zero", "Zero jitter model (photometric jitter only)", cxxopts::value<bool>(doPhotometricJitter)) ("l,landmarks", "Master landmark file (xml format)", cxxopts::value<std::string>(sLandmarks)) ("m,mirror", "Perform jittering", cxxopts::value<bool>(doMirror)) #if defined(DRISHTI_BUILD_EOS) ("eos-model", "EOS 3D dephormable model", cxxopts::value<std::string>(sEosModel)) ("eos-mapping", "EOS Landmark mapping", cxxopts::value<std::string>(sEosMapping)) #endif ("standardize", "Standardize input files to filename + bounding boxes", cxxopts::value<std::string>(sStandardize)) // ### Negative options ### ("I,inpaint", "Inpaint faces", cxxopts::value<bool>(doInpaint)) ("N,negatives","Negatives", cxxopts::value<std::string>(sNegatives)) ("W,winsize", "Minimum window size", cxxopts::value<int>(winSize)) ("B,background", "Background image list", cxxopts::value<std::string>(sBackground)) // Output parameters: ("t,threads", "Thread count", cxxopts::value<int>(threads)) ("h,help", "Print help message"); // clang-format on auto parseResult = options.parse(argc, argv); if((argumentCount <= 1) || parseResult.count("help")) { std::cout << options.help({""}) << std::endl; return 0; } // ############################################ // ### Command line argument error checking ### // ############################################ // ### Directory if(sPositives.empty() && sNegatives.empty()) { logger->error("Must specify output directory (positives or negatives)"); return 1; } // ... positives ... if(!sPositives.empty()) { if(drishti::cli::directory::exists(sPositives, ".drishti-facecrop")) { std::string filename = sPositives + "/.drishti-facecrop"; remove(filename.c_str()); } else { logger->error("Specified directory {} does not exist or is not writeable", sPositives); return 1; } } if (!sLandmarks.empty()) { std::ofstream check(sLandmarks); if(check) { remove(sLandmarks.c_str()); } else { logger->error("Specified landmark file {} does not exist", sLandmarks); return 1; } } // ... negatives ... if(!sNegatives.empty()) { if(drishti::cli::directory::exists(sNegatives, ".drishti-facecrop")) { std::string filename = sNegatives + "/.drishti-facecrop"; remove(filename.c_str()); } else { logger->error("Specified directory {} does not exist or is not writeable", sNegatives); return 1; } } // ### Input if(sInput.empty()) { logger->error("Must specify input image or list of images"); return 1; } if(!drishti::cli::file::exists(sInput)) { logger->error("Specified input file does not exist or is not readable"); return 1; } //:::::::::::::::::::::::::: //::: Face jitter params ::: //:::::::::::::::::::::::::: JitterParams jitterParams; if(!sJitterIn.empty()) { std::ifstream is(sJitterIn); if(is) { cereal::JSONInputArchive ia(is); using Archive = decltype(ia); ia(GENERIC_NVP("jitter", jitterParams)); } } // else we will be performing straight cropping or mirroring //::::::::::::::::::::::::::::::::: //::: Face normalization params ::: //::::::::::::::::::::::::::::::::: FaceSpecification faceSpec; if(sFaceSpec.empty()) { logger->error("Error: must provide valid face specification"); return -1; } else { std::ifstream is(sFaceSpec); if(is) { cereal::JSONInputArchive ia(is); using Archive = decltype(ia); ia(GENERIC_NVP("face", faceSpec)); } else { logger->error("Error: unable to read face specification file: {}", sFaceSpec); return -1; } } //::::::::::::::::::::::::::::::: //::: Parse input + landmarks ::: //::::::::::::::::::::::::::::::: GroundTruth gt = parseInput(sInput, sFormat, sDirectory, sExtension); auto &table = gt.table; if(table.lines.empty()) { logger->error("Error: no images were found, please check input file and (optionally) base directory"); return -1; } else { // Try simple image read sanity test for user feedback: if(cv::imread(table.lines.front().filename).empty()) { logger->error("Error: unable to read input image, please check input file and (optionally) base directory"); return -1; } } if(!sStandardize.empty()) { return standardizeFaceData(table, sStandardize); } if(doBoilerplate) { if(int code = saveDefaultConfigs(sPositives, *logger) < 0) { return code; } } if(sPositives.empty() && !sNegatives.empty() && !doInpaint) { // ########################## // ### 3) NEGATIVES ONLY ### >>> Sample random negative windows and quit <<< // ########################## return saveNegatives(table, sNegatives, sampleCount, winSize, threads, *logger); } if(doInpaint && !sBackground.empty() && !sNegatives.empty()) { // ################################### // ### 4) NEGATIVES w/ INPAINTING ### // ################################### return saveInpaintedSamples(table, sBackground, sNegatives, *logger); } // ... ELSE STANDARD POSITIVES AND/OR NEGATIVES ... #if defined(DRISHTI_BUILD_EOS) if(!(sEosModel.empty() || sEosMapping.empty())) { computePose(table, sEosModel, sEosMapping, logger); { // Write name + angle: std::string filename; filename += sPositives; filename += "/angles.txt"; std::ofstream os(filename); if (os) { logger->info("Writing pose file: {}", filename); for(const auto &r : table.lines) { os << r.filename << " "; for(const auto &p : r.points) { os << p.x << " " << p.y << " "; } os << r.angle << std::endl; } } } return 0; } #endif // Determine samples: std::vector<int> repeat(table.lines.size(), 1); if(sampleCount > 0) { std::fill(begin(repeat), end(repeat), 0); std::vector<int> samples(sampleCount); cv::RNG().fill(samples, 0, 0, table.lines.size()); for(const auto &i : samples) { repeat[i]++; } } FaceResourceManager manager = [&]() { logger->info("Create resource..."); return drishti::core::make_unique<FaceJittererMean>(table, faceSpec, jitterParams); }; // #################### // ### 1) POSITIVES ### // #################### drishti::core::ParallelHomogeneousLambda harness = [&](int i) { // Get thread specific segmenter lazily: auto tid = std::this_thread::get_id(); auto &jitterer = manager[tid]; assert(jitterer.get()); // Load current image logger->info("{} = {}", table.lines[i].filename, repeat[i]); if(repeat[i] > 0) { cv::Mat image = cv::imread(table.lines[i].filename, cv::IMREAD_COLOR); if(!image.empty()) { std::vector<FaceWithLandmarks> faces; // Always crop the original faces.push_back((*jitterer)(image, table.lines[i].points, FaceJitterer::kCrop, doPhotometricJitter)); // no mirror if (sJitterIn.empty()) { if (doMirror) { faces.push_back((*jitterer)(image, table.lines[i].points, FaceJitterer::kMirror, doPhotometricJitter)); // mirror } } else { for(int i = 1; i < repeat[i]; i++) { faces.push_back((*jitterer)(image, table.lines[i].points, FaceJitterer::kJitter, doPhotometricJitter)); // no mirror } } if(!sPositives.empty()) { cv::Rect roi(cv::Point(faceSpec.border, faceSpec.border), faceSpec.size); save(faces, roi, sPositives, table.lines[i].filename, i); } jitterer->updateMean(faces); #if defined(DRISHTI_USE_IMSHOW) if(doPreview) { cv::Mat canvas = image.clone(); previewFaceWithLandmarks(canvas, table.lines[i].points); glfw::imshow("facecrop:image", canvas); std::vector<cv::Mat> images; for(const auto &f : faces) { cv::Mat chip = f.image.clone(); previewFaceWithLandmarks(chip, f.landmarks); images.push_back(chip); } cv::hconcat(images, canvas); glfw::imshow("facecrop:jitter", canvas); glfw::imshow("facecrop::mu", jitterer->mu.image); glfw::waitKey(0); } #endif } } }; //harness({0,static_cast<int>(table.lines.size())}); if(threads == 1 || threads == 0 || doPreview) { harness({0,static_cast<int>(table.lines.size())}); } else { cv::parallel_for_({0,static_cast<int>(table.lines.size())}, harness, std::max(threads, -1)); } saveMeanFace(manager, faceSpec, sPositives + "/mean.png", sPositives + "/mean", *logger); return 0; } int main(int argc, char **argv) { try { return gauze_main(argc, argv); } catch(cv::Exception &e) { std::cerr << e.what() << std::endl; } catch (std::exception &e) { std::cerr << e.what() << std::endl; } catch(...) { std::cerr << "Unknown exception catched" << std::endl; } exit(-1); } // ### utility ### using string_hash::operator "" _hash; static GroundTruth parseInput(const std::string &sInput, const std::string &sFormat, const std::string &sDirectoryIn, const std::string &sExtension) { GroundTruth gt; switch(string_hash::hash(sFormat)) { case "two"_hash: gt.format = TWOFormat; gt.table = parseTWO(sInput); break; case "drishti"_hash: gt.format = DRISHTIFormat; gt.table = parseDRISHTI(sInput); break; case "lfw"_hash : gt.format = LFWFormat; gt.table = parseLFW(sInput); break; case "muct"_hash : gt.format = MUCTFormat; gt.table = parseMUCT(sInput); break; case "helen"_hash : gt.format = HELENFormat; gt.table = parseHELEN(sInput); break; case "bioid"_hash : gt.format = BIOIDFormat; gt.table = parseBIOID(sInput); break; case "lfpw"_hash : gt.format = LFPWFormat; gt.table = parseLFPW(sInput); break; case "raw"_hash : gt.table = parseRAW(sInput); gt.format = RAWFormat; break; default : CV_Assert(false); } std::string sDirectory = sDirectoryIn; if(!sDirectory.empty()) { if(sDirectory.back() != '/') { sDirectory += "/"; } for(auto &l : gt.table.lines) { l.filename = sDirectory + l.filename; if(!sExtension.empty()) { l.filename += "."; l.filename += sExtension; } } } for(auto &l : gt.table.lines) { std::replace(begin(l.filename), end(l.filename), '\\', '/'); } return gt; } static FACE::Table parseRAW(const std::string &sInput) { const auto filenames = drishti::cli::expand(sInput); FACE::Table table; table.lines.resize(filenames.size()); for(int i = 0; i < filenames.size(); i++) { table.lines[i].filename = filenames[i]; } return table; } static std::map<std::string, std::vector<std::array<cv::Point2f, 5>>> standardizeFaceData(const FACE::Table &table) { std::map<std::string, std::vector<std::array<cv::Point2f, 5>>> landmarks; for(const auto &r : table.lines) { std::array<cv::Point2f, 5> points {{ r.points[table.eyeR.front()], r.points[table.eyeL.front()], r.points[table.nose.front()], r.points[table.mouthR.front()], r.points[table.mouthL.front()] }}; landmarks[r.filename].emplace_back(points); } return landmarks; } static int standardizeFaceData(const FACE::Table &table, const std::string &sOutput) { // Write default faces: std::ofstream os(sOutput); if(os) { auto landmarks = standardizeFaceData(table); cereal::JSONOutputArchive oa(os); using Archive = decltype(oa); oa(GENERIC_NVP("faces", landmarks)); } else { return -1; } return 0; } #if defined(DRISHTI_BUILD_EOS) //Quaternion q; //q.setFromTwoVectors( v0, v1 ); #include <fstream> #include <iostream> static void computePose(FACE::Table &table, const std::string &sModel, const std::string &sMapping, std::shared_ptr<spdlog::logger> &logger) { FaceMeshMapperResourceManager manager = [&]() { return drishti::core::make_unique<drishti::face::FaceMeshMapperEOSLandmark>(sModel, sMapping); }; drishti::core::ParallelHomogeneousLambda harness = [&](int i) { // Get thread specific segmenter lazily: auto tid = std::this_thread::get_id(); auto &meshMapper = manager[tid]; auto &record = table.lines[i]; if(record.points.size() == 68) { cv::Size size; if((record.filename.find(".png") != std::string::npos) || (record.filename.find(".PNG") != std::string::npos)) { size = read_png_size(record.filename); } if(size.area() == 0) { size = cv::imread(record.filename).size(); } cv::Mat dummy; dummy.cols = size.width; dummy.rows = size.height; auto result = (*meshMapper)(record.points, dummy); const auto &q = result->getQuaternion(); record.quaternion = { q[0], q[1], q[2], q[3] }; // Note: q1 == frontal for now Eigen::Quaternion<float> q0(q[0], q[1], q[2], q[3]), q1(0.f, 0.f, 0.f, 1.f), arc = q0 * q1.inverse(); #if defined(__ANDROID__) record.angle = ::acosf(arc.w()) * 2.f; #else record.angle = std::acosf(arc.w()) * 2.f; #endif } }; cv::parallel_for_({0,static_cast<int>(table.lines.size())}, harness, 8); } #endif static int saveLandmarksJson(const std::string &sOutput, const std::vector<cv::Point2f> &landmarks, spdlog::logger &logger) { // Write default jitter parameters: std::ofstream os(sOutput); if(os) { cereal::JSONOutputArchive oa(os); using Archive = decltype(oa); oa(GENERIC_NVP("landmarks", landmarks)); } else { logger.error("Error: unable to write mean landmarks"); return -1; } return 0; } static int saveLandmarksXml(const std::string &sOutput, const drishti::face::FaceModel &landmarks, spdlog::logger &logger) { // Write default jitter parameters: std::ofstream os(sOutput); if(os) { cereal::XMLOutputArchive oa(os); using Archive = decltype(oa); oa(GENERIC_NVP("landmarks", landmarks)); } else { logger.error("Error: unable to write mean landmarks"); return -1; } return 0; } static void saveMeanFace(FaceResourceManager &manager, const FaceSpecification &faceSpec, const std::string &sImage, const std::string &sPoints, spdlog::logger &logger) { // Save the mean face image: FaceWithLandmarks mu = computeMeanFace(manager); if(!sImage.empty()) { cv::Mat tmp; mu.image.convertTo(tmp, CV_8UC3, 255.0); cv::imwrite(sImage, tmp); } if(!sPoints.empty()) { // Output json for points saveLandmarksJson(sPoints + ".json", mu.landmarks, logger); // Legacy: save a mean face model structure (normalized): cv::Point2f tl(faceSpec.border, faceSpec.border); drishti::face::FaceModel model; model.eyeRightCenter = mu.landmarks[0]; model.eyeLeftCenter = mu.landmarks[1]; model.noseTip = mu.landmarks[2]; cv::Matx33f T = transformation::translate(-tl); cv::Matx33f S = transformation::scale(faceSpec.size.width, faceSpec.size.height); model = (S.inv() * T) * model; // remove border and normalize saveLandmarksXml(sPoints + ".xml", model, logger); } } static int saveDefaultJitter(const std::string &sOutput, spdlog::logger &logger) { // Write default jitter parameters: std::ofstream os(sOutput); if(os) { cereal::JSONOutputArchive oa(os); using Archive = decltype(oa); oa(GENERIC_NVP("jitter", JitterParams())); } else { logger.error("Error: unable to write default jitter parameters"); return -1; } return 0; } static int saveDefaultFaceSpec(const std::string &sOutput, spdlog::logger &logger) { // Write default face specification: std::ofstream os(sOutput); if(os) { cereal::JSONOutputArchive oa(os); using Archive = decltype(oa); oa(GENERIC_NVP("face", FaceSpecification())); } else { logger.error("Error: unable to write default face specification parameters"); return -1; } return 0; } static int saveDefaultConfigs(const std::string &sOutput, spdlog::logger &logger) { if(int code = saveDefaultJitter(sOutput + "/jitter.json", logger) != 0) { return code; } if(int code = saveDefaultFaceSpec(sOutput + "/face.json", logger) != 0) { return code; } return 0; } static FaceWithLandmarks computeMeanFace(FaceResourceManager &manager) { int count = 0; for(const auto &j : manager.getMap()) { count += j.second->mu.count; } FaceWithLandmarks mu; for(const auto &j : manager.getMap()) { if(!j.second->mu.image.empty()) { const double w = double(j.second->mu.count)/count; if(mu.image.empty()) { mu = (j.second->mu * w); } else { mu += (j.second->mu * w); } } } return mu; } // Save in piotr's toolbox bbGt version=3 format // // % bbGt version=3 // face 128 117 124 124 0 128 117 124 124 0 0 static void save_bbGtv3(const std::string &sOutput, const std::vector<cv::Rect> &objects) { static const char *sHeader = "% bbGt version=3"; static const char *sLabel = "face"; std::ofstream ofs(sOutput); if(ofs) { for(const auto &o : objects) { std::stringstream box; box << o.x << ' ' << o.y << ' ' << o.width << ' ' << o.height; ofs << sHeader << "\n" << sLabel << ' ' << box.str() << " 0 " << box.str() << " 0 0" << std::endl; } } } static void save(std::vector<FaceWithLandmarks> &faces, const cv::Rect &roi, const std::string &dir, const std::string &filename, int index) { for(int i = 0; i < faces.size(); i++) { std::stringstream ss; ss << std::setfill('0') << std::setw(6) << index << "_" << std::setw(2) << i; std::string base = drishti::core::basename(filename); { // save the image file std::string sOutput = dir; sOutput += "/"; sOutput += ss.str(); sOutput += "_"; sOutput += base; sOutput += ".png"; cv::imwrite(sOutput, faces[i].image); faces[i].filename = sOutput; } { // Save bbox file for each face (compatible w/ Piotr's toolbox): std::string sOutput = dir; sOutput += "/"; sOutput += ss.str(); sOutput += "_"; sOutput += base; sOutput += ".txt"; save_bbGtv3(sOutput, {roi}); } { // Save the landmarks in a flat file: std::string sOutput = dir; sOutput += "/"; sOutput += ss.str(); sOutput += "_"; sOutput += base; sOutput += ".pts"; std::ofstream ofs(sOutput); if(ofs) { for (const auto &p : faces[i].landmarks) { ofs << p.x << " " << p.y << " "; } ofs << std::endl; } } } } static void previewFaceWithLandmarks(cv::Mat &image, const std::vector<cv::Point2f> &landmarks) { for(const auto &p : landmarks) { cv::circle(image, p, 2, {0,255,0}, -1, 8); } } static int saveNegatives(const FACE::Table &table, const std::string &sOutput, int sampleCount, int winSize, int threads, spdlog::logger &logger) { std::vector<int> repeat(table.lines.size(), 1); if(sampleCount > 0) { std::fill(begin(repeat), end(repeat), 0); std::vector<int> samples(sampleCount); cv::RNG().fill(samples, 0, 0, repeat.size()); for(const auto &i : samples) { repeat[i]++; } } drishti::core::ParallelHomogeneousLambda harness = [&](int i) { cv::RNG rng; const auto &f = table.lines[i].filename; cv::Mat negative = cv::imread(f, cv::IMREAD_COLOR); int minDim = std::min(negative.cols, negative.rows); if((minDim >= winSize) && !negative.empty()) { std::string filename; for(int j = 0; j < repeat[i]; j++) { const int width = rng.uniform(winSize, minDim); const int x = rng.uniform(0, negative.cols-width); const int y = rng.uniform(0, negative.rows-width); logger.info("roi:{},{},{},{}({})", x, y, width, width, winSize); cv::Mat crop = negative(cv::Rect(x, y, width, width)); cv::resize(crop, crop, {winSize, winSize}, 0, 0, cv::INTER_AREA); std::string sha1 = get_sha1(crop.ptr<void>(), crop.total()); filename = sOutput; filename += "/"; filename += sha1; filename += ".png"; cv::imwrite(filename, crop); } } }; //cv::parallel_for_({0,static_cast<int>(sInput.size())}, harness, std::max(threads, -1)); harness({0,static_cast<int>(repeat.size())}); return 0; } static int saveInpaintedSamples(const FACE::Table &table, const std::string& sBackground, const std::string &sOutput, spdlog::logger &logger) { cv::RNG rng; // Read a bunch of negative samples: std::vector<cv::Mat> negatives; auto filenames = drishti::cli::expand(sBackground); for(int i = 0; i < std::min(100, static_cast<int>(filenames.size())); i++) { cv::Mat I = cv::imread(filenames[rng.uniform(0, filenames.size())], cv::IMREAD_COLOR); if(!I.empty()) { negatives.push_back(I); } } std::map< std::string, std::vector<const std::vector<cv::Point2f>*> > landmarks; for(const auto &r : table.lines) { landmarks[r.filename].push_back(&r.points); } drishti::core::ParallelHomogeneousLambda harness = [&](int i) { const auto &r = table.lines[i]; cv::Mat image = cv::imread(r.filename, cv::IMREAD_COLOR); if(!image.empty()) { logger.info("faceless:{}", r.filename); cv::Mat blended; auto iter = landmarks.find(r.filename); if(iter != landmarks.end()) { for(const auto &p : iter->second) { const cv::Rect roi = cv::boundingRect(*p); const cv::Point2f tl = roi.tl(), br = roi.br(), center = (br + tl) * 0.5f; const cv::RotatedRect face(center, cv::Size2f(roi.width, roi.height*2.f), 0); cv::Mat mask(image.size(), CV_8UC3, cv::Scalar::all(0)); cv::ellipse(mask, face, cv::Scalar::all(255), -1, 8); cv::Mat bg; cv::resize(negatives[rng.uniform(0, negatives.size())], bg, image.size(), 0, 0, cv::INTER_AREA); blended = blend(blended.empty() ? image : blended, bg, mask, 6); blended.convertTo(blended, CV_8UC3, 255.0); } } if(!blended.empty()) { std::string base = drishti::core::basename(r.filename); cv::imwrite(sOutput + "/" + base + "_faceless.png", blended); } } }; //cv::parallel_for_({0,static_cast<int>(table.lines.size()}, harness, std::max(threads, -1)); harness({0,static_cast<int>(table.lines.size())}); return 0; }
#' Perform LD clumping #' #' <full description> #' #' @param vcf VCF file or VCF object #' @param clump_kb Clumping kb window. Default is very strict, 10000 #' @param clump_r2 Clumping r2 threshold. Default is very strict, 0.001 #' @param clump_p Clumping sig level for index variants. Default = 1 (i.e. no threshold) #' @param pop Super-population to use as reference panel. Default = "EUR". Options are EUR, SAS, EAS, AFR, AMR. 'legacy' also available - which is a previously used verison of the EUR panel with a slightly different set of markers #' @param bfile If this is provided then will use the API. Default = NULL #' @param plink_bin If null and bfile is not null then will detect packaged plink binary for specific OS. Otherwise specify path to plink binary. Default = NULL #' @param access_token Google OAuth2 access token. Used to authenticate level of access to data #' #' @export #' @return data frame of clumped results clump_gwasvcf <- function(vcf, clump_kb=1000, clump_r2=0.001, clump_p=5e-8, pop=NULL, bfile=NULL, plink_bin=NULL, access_token=NULL) { message("Applying threshold to vcf") sig <- gwasvcf::query_gwas(vcf, pval=clump_p) if(is.null(bfile)) { message("Using API. Note that this could be slow, and to reduce server disruption it is recommended to use local LD reference files") message("See gwasglue vignette on how to do this") fn <- function(dat) { ieugwasr::ld_clump(dat, pop=pop, clump_kb=clump_kb, clump_r2=clump_r2, clump_p=clump_p, access_token=check_access_token()) } } else { fn <- function(dat) { ieugwasr::ld_clump(dat, clump_kb=clump_kb, clump_r2=clump_r2, clump_p=clump_p, bfile=bfile, plink_bin=plink_bin) } } # Clump clumped <- sig %>% gwasvcf::vcf_to_tibble() %>% dplyr::mutate(pval=10^{-LP}) %>% dplyr::select(rsid, pval) %>% fn(.) %>% {.$rsid} %>% {sig[names(sig) %in% .]} %>% SummarizedExperiment::rowRanges() %>% {dplyr::tibble(rsid = names(.), chrpos=paste0(SummarizedExperiment::seqnames(.), ":", SummarizedExperiment::ranges(.)@start))} return(clumped) }
(* Title: Metric and semimetric spaces Author: Tim Makarios <tjm1983 at gmail.com>, 2012 Maintainer: Tim Makarios <tjm1983 at gmail.com> *) header "Metric and semimetric spaces" theory Metric imports "~~/src/HOL/Multivariate_Analysis/Euclidean_Space" begin locale semimetric = fixes dist :: "'p \<Rightarrow> 'p \<Rightarrow> real" assumes nonneg [simp]: "dist x y \<ge> 0" and eq_0 [simp]: "dist x y = 0 \<longleftrightarrow> x = y" and symm: "dist x y = dist y x" begin lemma refl [simp]: "dist x x = 0" by simp end locale metric = fixes dist :: "'p \<Rightarrow> 'p \<Rightarrow> real" assumes [simp]: "dist x y = 0 \<longleftrightarrow> x = y" and triangle: "dist x z \<le> dist y x + dist y z" sublocale metric < semimetric proof { fix w have "dist w w = 0" by simp } note [simp] = this fix x y show "0 \<le> dist x y" proof - from triangle [of y y x] show "0 \<le> dist x y" by simp qed show "dist x y = 0 \<longleftrightarrow> x = y" by simp show "dist x y = dist y x" proof - { fix w z have "dist w z \<le> dist z w" proof - from triangle [of w z z] show "dist w z \<le> dist z w" by simp qed } hence "dist x y \<le> dist y x" and "dist y x \<le> dist x y" by simp+ thus "dist x y = dist y x" by simp qed qed definition norm_dist :: "('a::real_normed_vector) \<Rightarrow> 'a \<Rightarrow> real" where [simp]: "norm_dist x y \<equiv> norm (x - y)" interpretation norm_metric: metric norm_dist proof fix x y show "norm_dist x y = 0 \<longleftrightarrow> x = y" by simp fix z from norm_triangle_ineq [of "x - y" "y - z"] have "norm (x - z) \<le> norm (x - y) + norm (y - z)" by simp with norm_minus_commute [of x y] show "norm_dist x z \<le> norm_dist y x + norm_dist y z" by simp qed end
----------------------------------------------------------------------------- -- | -- Module : Numeric.LinearAlgebra.Vector.ST -- Copyright : Copyright (c) , Patrick Perry <[email protected]> -- License : BSD3 -- Maintainer : Patrick Perry <[email protected]> -- Stability : experimental -- -- Mutable vectors in the ST monad. module Numeric.LinearAlgebra.Vector.ST ( -- * Mutable vectors STVector, IOVector, create, -- * Read-only vectors RVector(..), -- * Creating new vectors new_, new, -- * Copying vectors newCopy, copyTo, swap, -- * Reading and writing vector elements read, write, modify, getIndices, getElems, getElems', getAssocs, getAssocs', setElems, setAssocs, clear, -- * List-like operations mapTo, zipWithTo, -- * Vector linear algebra getSumAbs, getNorm2, getWhichMaxAbs, getDot, scaleM_, addWithScaleM_, kroneckerTo, -- * Vector views withSlice, withDrop, withTake, withSplitAt, withSliceM, withDropM, withTakeM, withSplitAtM, -- * Vector math operations -- ** Num addTo, subTo, mulTo, negateTo, conjugateTo, absTo, signumTo, -- ** Fractional divTo, recipTo, -- ** Floating sqrtTo, expTo, logTo, powTo, sinTo, cosTo, tanTo, asinTo, acosTo, atanTo, sinhTo, coshTo, tanhTo, asinhTo, acoshTo, atanhTo, -- * Conversions between mutable and immutable vectors freeze, -- * Unsafe operations unsafeCopyTo, unsafeSwap, unsafeRead, unsafeWrite, unsafeModify, unsafeMapTo, unsafeZipWithTo, unsafeAddWithScaleM_, unsafeGetDot, ) where import Prelude() import Numeric.LinearAlgebra.Vector.STBase
import rba import numpy import pandas from .rba_Session import RBA_Session from scipy.stats.mstats import gmean class RBA_Calibrator(object): def __init__(self, xml_dir): self.rbaSession = RBA_Session(xml_dir) def estimate_specific_Kapps(self, proteomicsData, flux_bounds, mu, biomass_function=None, target_biomass_function=True): """ Parameters ---------- proteomicsData : pandas.DataFrame (in mmol/gDW) flux_bounds : pandas.DataFrame (in mmol/(gDW*h)) mu : float (in 1/h) biomass_function : str target_biomass_function : bool atp_maintenance_to_biomassfunction : bool eukaryotic : bool """ Avogadro_constant = 6.022e23 self.rbaSession.addExchangeReactions() self.rbaSession.setMu(mu) if target_biomass_function: self.rbaSession.buildFBA(objective='targets', maintenanceToBM=True) BMfunction = 'R_BIOMASS_targetsRBA' else: self.rbaSession.buildFBA(objective='classic', maintenanceToBM=False) BMfunction = biomass_function for j in [i for i in self.rbaSession.Medium.keys() if self.rbaSession.Medium[i] == 0]: Exrxn = 'R_EX_'+j.split('M_')[-1]+'_e' self.rbaSession.FBA.setUB({Exrxn: 0}) rxn_LBs = {} rxn_UBs = {} for rx in flux_bounds['Reaction_ID']: lb = flux_bounds.loc[flux_bounds['Reaction_ID'] == rx, 'LB'].values[0] ub = flux_bounds.loc[flux_bounds['Reaction_ID'] == rx, 'UB'].values[0] if not pandas.isna(lb): rxn_LBs.update({rx: lb}) if not pandas.isna(ub): rxn_UBs.update({rx: ub}) self.rbaSession.FBA.setLB(rxn_LBs) self.rbaSession.FBA.setUB(rxn_UBs) self.rbaSession.FBA.clearObjective() self.rbaSession.FBA.setObjectiveCoefficients({BMfunction: -1}) self.rbaSession.FBA.solveLP(feasibleStatuses=[1, 2, 3, 5, 6]) BMfluxOld = self.rbaSession.FBA.SolutionValues[BMfunction] self.rbaSession.FBA.parsimonise() self.rbaSession.FBA.setLB(rxn_LBs) self.rbaSession.FBA.setUB(rxn_UBs) self.rbaSession.FBA.setLB({BMfunction: BMfluxOld}) self.rbaSession.FBA.setUB({BMfunction: BMfluxOld}) self.rbaSession.FBA.solveLP(feasibleStatuses=[1, 2, 3, 5, 6]) FluxDistribution = pandas.DataFrame(index=list( self.rbaSession.FBA.SolutionValues.keys()), columns=['FluxValues']) FluxDistribution['FluxValues'] = list(self.rbaSession.FBA.SolutionValues.values()) BMfluxNew = self.rbaSession.FBA.SolutionValues[BMfunction] ProtoIDmap = {} for i in self.rbaSession.ModelStructure.ProteinInfo.Elements.keys(): ProtoID = self.rbaSession.ModelStructure.ProteinInfo.Elements[i]['ProtoID'] if ProtoID in list(proteomicsData.index): if not pandas.isna(proteomicsData.loc[ProtoID, 'copy_number']): if proteomicsData.loc[ProtoID, 'copy_number'] != 0: if ProtoID in ProtoIDmap.keys(): ProtoIDmap[ProtoID]['ModelProteins'].append(i) else: ProtoIDmap.update( {ProtoID: {'ModelProteins': [i], 'CopyNumber': proteomicsData.loc[ProtoID, 'copy_number']}}) ReactionMap = {} for i in self.rbaSession.ModelStructure.ReactionInfo.Elements.keys(): if '_duplicate_' in i: continue else: if i in list(FluxDistribution.index): if FluxDistribution.loc[i, 'FluxValues'] != 0: ReactionMap.update({i: {'ModelReactions': list( [i]+self.rbaSession.ModelStructure.ReactionInfo.Elements[i]['Twins']), 'Flux': FluxDistribution.loc[i, 'FluxValues']}}) IsoReaction2ProtoReaction = {} for i in ReactionMap.keys(): for j in ReactionMap[i]['ModelReactions']: IsoReaction2ProtoReaction[j] = i EnzymeMap = {} for i in self.rbaSession.ModelStructure.EnzymeInfo.Elements.keys(): if self.rbaSession.ModelStructure.EnzymeInfo.Elements[i]['Reaction'] in IsoReaction2ProtoReaction: CompositionDict = {self.rbaSession.ModelStructure.ProteinInfo.Elements[j]['ProtoID']: self.rbaSession.ModelStructure.EnzymeInfo.Elements[ i]['Subunits'][j] for j in self.rbaSession.ModelStructure.EnzymeInfo.Elements[i]['Subunits'].keys()} ProtoReaction = IsoReaction2ProtoReaction[self.rbaSession.ModelStructure.EnzymeInfo.Elements[i]['Reaction']] CopyNumbers = [] Stoichiometries = [] EnzymeNumbers = [] for j in CompositionDict.keys(): if j in ProtoIDmap.keys(): CopyNumbers.append(ProtoIDmap[j]['CopyNumber']) Stoichiometries.append(CompositionDict[j]) EnzymeNumbers.append(ProtoIDmap[j]['CopyNumber']/CompositionDict[j]) GM_enzymenumber = 0 if len(EnzymeNumbers) > 0: GM_enzymenumber = gmean(numpy.array(EnzymeNumbers)) EnzymeMap.update( {i: {'ProtoReaction': ProtoReaction, 'EnzymeNumber': GM_enzymenumber}}) EnzymeMap2 = {} for i in ReactionMap.keys(): totalIsoEnzymeNumber = 0 for j in ReactionMap[i]['ModelReactions']: respectiveEnzyme = self.rbaSession.ModelStructure.ReactionInfo.Elements[j]['Enzyme'] if respectiveEnzyme in EnzymeMap.keys(): totalIsoEnzymeNumber += EnzymeMap[respectiveEnzyme]['EnzymeNumber'] for j in ReactionMap[i]['ModelReactions']: respectiveEnzyme = self.rbaSession.ModelStructure.ReactionInfo.Elements[j]['Enzyme'] if respectiveEnzyme in EnzymeMap.keys(): if EnzymeMap[respectiveEnzyme]['EnzymeNumber'] != 0: specificFlux = ReactionMap[i]['Flux'] * \ EnzymeMap[respectiveEnzyme]['EnzymeNumber']/totalIsoEnzymeNumber concentration = EnzymeMap[respectiveEnzyme]['EnzymeNumber'] / \ Avogadro_constant EnzymeMap2.update({respectiveEnzyme: {'CopyNumber': EnzymeMap[respectiveEnzyme]['EnzymeNumber'], 'Concentration': concentration, 'Flux': specificFlux, 'Kapp': abs(specificFlux/concentration)}}) self.specific_Kapps = pandas.DataFrame() for i in EnzymeMap2.keys(): if EnzymeMap2[i]['CopyNumber'] == 0: continue self.specific_Kapps.loc[i, 'Enzyme_ID'] = i self.specific_Kapps.loc[i, 'CopyNumber'] = EnzymeMap2[i]['CopyNumber'] self.specific_Kapps.loc[i, 'Concentration'] = EnzymeMap2[i]['Concentration'] self.specific_Kapps.loc[i, 'Flux'] = EnzymeMap2[i]['Flux'] self.specific_Kapps.loc[i, 'Kapp'] = EnzymeMap2[i]['Kapp'] def estimate_default_Kapps(self, target_mu, compartment_densities_and_PGs=None, flux_bounds=None, eukaryotic=False, plateau_limit=4, mu_approximation_precision=0.0001, transporter_to_lumen_coefficient=10, default_kapp_LB=0, default_kapp_UB=None): """ Parameters ---------- target_mu : float compartment_densities : pandas.DataFrame compartment_PGs : pandas.DataFrame flux_bounds : pandas.DataFrame """ orig_enz = self.rbaSession.model.parameters.functions._elements_by_id[ 'default_efficiency'].parameters._elements_by_id['CONSTANT'].value out = pandas.DataFrame() for comp in list(compartment_densities_and_PGs['Compartment_ID']): self.rbaSession.model.parameters.functions._elements_by_id[str( 'fraction_protein_'+comp)].parameters._elements_by_id['CONSTANT'].value = 0.01*compartment_densities_and_PGs.loc[compartment_densities_and_PGs['Compartment_ID'] == comp, 'Density'] self.rbaSession.model.parameters.functions._elements_by_id[str('fraction_non_enzymatic_protein_'+comp)].parameters._elements_by_id['CONSTANT'].value = 0.01 * \ compartment_densities_and_PGs.loc[compartment_densities_and_PGs['Compartment_ID'] == comp, 'PG_fraction'] self.rbaSession.rebuild_from_model() self.rbaSession.addExchangeReactions() rxn_LBs = {} rxn_UBs = {} for rx in flux_bounds['Reaction_ID']: lb = flux_bounds.loc[flux_bounds['Reaction_ID'] == rx, 'LB'].values[0] ub = flux_bounds.loc[flux_bounds['Reaction_ID'] == rx, 'UB'].values[0] if not pandas.isna(lb): rxn_LBs.update({rx: lb}) if not pandas.isna(ub): rxn_UBs.update({rx: ub}) self.rbaSession.Problem.setLB(rxn_LBs) self.rbaSession.Problem.setUB(rxn_UBs) # self.rbaSession.setMedium(medium) if eukaryotic: self.rbaSession.eukaryoticDensities_calibration(CompartmentRelationships=False) kapp_LB = default_kapp_LB if default_kapp_UB is not None: kapp_UB = default_kapp_UB else: kapp_UB = orig_enz*1000 new_kapp = (kapp_UB+kapp_LB)/2 self.rbaSession.model.parameters.functions._elements_by_id[ 'default_efficiency'].parameters._elements_by_id['CONSTANT'].value = new_kapp self.rbaSession.model.parameters.functions._elements_by_id['default_transporter_efficiency'].parameters._elements_by_id[ 'CONSTANT'].value = transporter_to_lumen_coefficient*new_kapp Mu_pred = self.rbaSession.findMaxGrowthRate() Mus = [] Mus_Error = [] Kapps = [] last_Mu = numpy.nan plateau_count = 0 while abs(target_mu - Mu_pred) > mu_approximation_precision: if plateau_count >= plateau_limit: break self.rbaSession.model.parameters.functions._elements_by_id[ 'default_efficiency'].parameters._elements_by_id['CONSTANT'].value = new_kapp self.rbaSession.model.parameters.functions._elements_by_id['default_transporter_efficiency'].parameters._elements_by_id[ 'CONSTANT'].value = transporter_to_lumen_coefficient*new_kapp self.rbaSession.rebuild_from_model() self.rbaSession.addExchangeReactions() self.rbaSession.Problem.setLB(rxn_LBs) self.rbaSession.Problem.setUB(rxn_UBs) Mu_pred = self.rbaSession.findMaxGrowthRate() Mus_Error.append(abs(target_mu - Mu_pred)) Mus.append(Mu_pred) Kapps.append(new_kapp) if Mu_pred > target_mu: new_kapp_prelim = kapp_LB+(0.5*abs(kapp_LB-new_kapp)) kapp_UB = new_kapp elif Mu_pred < target_mu: new_kapp_prelim = kapp_UB-(0.5*abs(new_kapp-kapp_UB)) kapp_LB = new_kapp new_kapp = new_kapp_prelim if len(Mus) > 2: if Mus[-2] == Mu_pred: plateau_count += 1 else: plateau_count = 0 self.default_kapp_estimation = pandas.DataFrame() self.default_kapp_estimation['Mu'] = Mus self.default_kapp_estimation['delta_Mu'] = Mus_Error self.default_kapp_estimation['default_efficiency'] = Kapps self.default_kapp_estimation['default_transporter_efficiency'] = [ transporter_to_lumen_coefficient*i for i in Kapps] def inject_specific_kapps(self, specific_kapps, round_to_digits=0): """ Parameters ---------- specific_kapps : pandas.DataFrame """ parameterized = [] for enz in list(specific_kapps['Enzyme_ID']): if not pandas.isna(specific_kapps.loc[specific_kapps['Enzyme_ID'] == enz, 'Kapp'].values[0]): if enz not in parameterized: all_enzs = self.rbaSession.ModelStructure.EnzymeInfo.Elements[enz]['Isozymes'] all_enzs.append(enz) parameterized += all_enzs if len(all_enzs) == 1: proto_enz = all_enzs[0] else: proto_enz = [i for i in all_enzs if not '_duplicate_' in i][0] val = round(specific_kapps.loc[specific_kapps['Enzyme_ID'] == enz, 'Kapp'].values[0], round_to_digits) const = rba.xml.parameters.Function( str(proto_enz + '_kapp__constant'), 'constant', parameters={'CONSTANT': val}, variable=None) self.rbaSession.model.parameters.functions.append(const) count = 0 for e in self.rbaSession.model.enzymes.enzymes: if e.id in all_enzs: count += 1 e.forward_efficiency = str(proto_enz + '_kapp__constant') e.backward_efficiency = str(proto_enz + '_kapp__constant') if count == len(all_enzs): break
c c **************************************************************** c * * c * subroutine smcs_cut_step * c * * c * written by : ag * c * * c * last modified : 10/07/96 * c * * c * This routine checks if the load step size is too * c * large. If the plastic strain in any killable mises * c * element has grown more than max_plast_strain_change, * c * then permanently cut the load step size by half. * c * * c **************************************************************** c subroutine smcs_cut_step ( debug ) use global_data ! old common.main use elem_extinct_data, only : old_plast_strain use damage_data implicit integer (a-z) logical debug c c c local declarations c logical not_cut, duml double precision & new_plast_strain, two, dum1, dumd2, dumd3, dumd4, & dumd5, dumd6, dumd7 character(len=1) :: dums real dumr data two / 2.0 / c if ( debug ) write ( out, * ) '>>>>>> in smcs_cut_step' c c loop over all killable mises elements c not_cut = .true. do elem = 1, noelem elem_ptr = dam_ptr( elem ) if ( elem_ptr .eq. 0 ) cycle c c calculate new plast_strain in element c call dam_param( elem, duml, debug, dum1, new_plast_strain, & dumd2, dumd3, dumd4, dumd5, dumd6, dumd7 ) c c compare old plast_strain with new plast_strain -- if c change is larger than the acceptible max, cut load c step size. c if ( new_plast_strain - old_plast_strain(elem_ptr) .gt. & max_plast_strain_change ) then if ( not_cut ) then perm_load_fact = perm_load_fact / two call errmsg ( 273, dum, dums, dumr, perm_load_fact ) not_cut = .false. end if end if old_plast_strain(elem_ptr) = new_plast_strain end do c if ( debug ) write(out,*) '<<<<< leaving smcs_cut_step' c return end
State Before: ι : Type ?u.54429 ι' : Type ?u.54432 α : Type u_1 β : Type u_2 γ : Type ?u.54441 inst✝¹ : SemilatticeSup α inst✝ : Nonempty α F : Filter β u : α → β ⊢ NeBot (F ⊓ map u atTop) ↔ ∀ (U : Set β), U ∈ F → ∀ (N : α), ∃ n, n ≥ N ∧ u n ∈ U State After: ι : Type ?u.54429 ι' : Type ?u.54432 α : Type u_1 β : Type u_2 γ : Type ?u.54441 inst✝¹ : SemilatticeSup α inst✝ : Nonempty α F : Filter β u : α → β ⊢ (∀ {p : β → Prop}, (∀ᶠ (x : β) in F, p x) → ∀ (a : α), ∃ b, b ≥ a ∧ p (u b)) ↔ ∀ (U : Set β), U ∈ F → ∀ (N : α), ∃ n, n ≥ N ∧ u n ∈ U Tactic: simp_rw [inf_neBot_iff_frequently_left, frequently_map, frequently_atTop] State Before: ι : Type ?u.54429 ι' : Type ?u.54432 α : Type u_1 β : Type u_2 γ : Type ?u.54441 inst✝¹ : SemilatticeSup α inst✝ : Nonempty α F : Filter β u : α → β ⊢ (∀ {p : β → Prop}, (∀ᶠ (x : β) in F, p x) → ∀ (a : α), ∃ b, b ≥ a ∧ p (u b)) ↔ ∀ (U : Set β), U ∈ F → ∀ (N : α), ∃ n, n ≥ N ∧ u n ∈ U State After: no goals Tactic: rfl
lemma Gamma_residue: "residue Gamma (-of_nat n) = (-1) ^ n / fact n"
Since the last quarter of the 20th century , with a re @-@ emergence of wealth in Ireland , a " New Irish Cuisine " based on traditional ingredients incorporating international influences has emerged . This cuisine is based on fresh vegetables , fish ( especially salmon , trout , oysters , mussels and other shellfish ) , as well as traditional soda breads and the wide range of hand @-@ made cheeses that are now being produced across the country . The potato remains however a fundamental feature of this cuisine and the Irish remain the highest per capita consumers of potatoes in Europe . An example of this new cuisine is " Dublin Lawyer " : lobster cooked in whiskey and cream . Traditional regional foods can be found throughout the country , for example coddle in Dublin or <unk> in Cork , both a type of sausage , or <unk> , a doughy white bread particular to Waterford .
Our versatile Home Inspection programs - Principles of Home Inspection and Fundamentals of Home Inspection offer the highest quality training at prices 30% to 50% less than other home inspection schools. These comprehensive online courses have been developed by Carson Dunlop & Associates, one of the oldest and largest Home Inspection firms in North America. From an introductory overview of home inspection to advanced system-specific courses, Freedom Business School can meet any of your Home Inspection education and training needs. Fundamentals of Home Inspection provides a comprehensive introduction to the practice of home inspection. Students will find straightforward descriptions of house systems and how they function, as well as how they may deteriorate or fail. Written by Carson Dunlop & Associates, one of the most successful home inspection companies in North America, Fundamentals of Home Inspection is based on years of practical experience in both inspecting homes and training inspectors. Mold is a controversial topic that is quickly becoming a serious liability risk for real estate agents and a threat to all involved in real estate transactions---from home inspectors and the home insurance industry to buyers and sellers facing potential health risks and the inability to secure insurance. The Truth About Mold provides the answers students need to protect their physical and fiscal well-being and to separate myth from truth.
Formal statement is: lemma contractible_space_subtopology_euclideanreal [simp]: "contractible_space(subtopology euclideanreal S) \<longleftrightarrow> is_interval S" (is "?lhs = ?rhs") Informal statement is: A subspace of the real line is contractible if and only if it is an interval.
As robots become more autonomous, the notion of computer-controlled machines facing ethical decisions is moving out of the realm of science fiction and into the real world. Society needs to find ways to ensure that they are better equipped to make moral judgments than HAL was. Military technology, unsurprisingly, is at the forefront of the march towards self-determining machines. Its evolution is producing an extraordinary variety of species. The Sand Flea can leap through a window or onto a roof, filming all the while. It then rolls along on wheels until it needs to jump again. RiSE, a six-legged robo-cockroach, can climb walls. LS3, a dog-like robot, trots behind a human over rough terrain, carrying up to 180kg of supplies. SUGV, a briefcase-sized robot, can identify a man in a crowd and follow him. There is a flying surveillance drone the weight of a wedding ring, and one that carries 2.7 tonnes of bombs. As that happens, they will be presented with ethical dilemmas. Should a drone fire on a house where a target is known to be hiding, which may also be sheltering civilians? Should a driverless car swerve to avoid pedestrians if that means hitting other vehicles or endangering its occupants? Should a robot involved in disaster recovery tell people the truth about what is happening if that risks causing a panic? Such questions have led to the emergence of the field of “machine ethics”, which aims to give machines the ability to make such choices appropriately—in other words, to tell right from wrong. Instead, society needs to develop ways of dealing with the ethics of robotics—and get going fast. In America states have been scrambling to pass laws covering driverless cars, which have been operating in a legal grey area as the technology runs ahead of legislation. It is clear that rules of the road are required in this difficult area, and not just for robots with wheels. First, laws are needed to determine whether the designer, the programmer, the manufacturer or the operator is at fault if an autonomous drone strike goes wrong or a driverless car has an accident. In order to allocate responsibility, autonomous systems must keep detailed logs so that they can explain the reasoning behind their decisions when necessary. This has implications for system design: it may, for instance, rule out the use of artificial neural networks, decision-making systems that learn from example rather than obeying predefined rules. Second, where ethical systems are embedded into robots, the judgments they make need to be ones that seem right to most people. The techniques of experimental philosophy, which studies how people respond to ethical dilemmas, should be able to help. Last, and most important, more collaboration is required between engineers, ethicists, lawyers and policymakers, all of whom would draw up very different types of rules if they were left to their own devices. Both ethicists and engineers stand to benefit from working together: ethicists may gain a greater understanding of their field by trying to teach ethics to machines, and engineers need to reassure society that they are not taking any ethical short-cuts. Technology has driven mankind’s progress, but each new advance has posed troubling new questions. Autonomous machines are no different. The sooner the questions of moral agency they raise are answered, the easier it will be for mankind to enjoy the benefits that they will undoubtedly bring.
\documentclass{beamer} \usepackage{fontspec} \usepackage{xeCJK} \setCJKmainfont[BoldFont=Noto Serif CJK TC Bold]{Noto Serif CJK TC} \XeTeXlinebreaklocale "zh" \XeTeXlinebreakskip = 0pt plus 1pt \linespread{1.3} \allowdisplaybreaks \usepackage[round]{natbib} \usepackage{color} \usepackage{booktabs} \usepackage{tabularx} \usepackage{caption} \usepackage{tikz} \usepackage{graphicx} \usepackage{spreadtab} \usepackage{subfigure} \usepackage{verbatim} \usepackage{pgfplotstable} \usepackage{fancyhdr} \pgfplotsset{width=12cm} \pgfplotsset{height=7cm} \pgfplotsset{compat=1.13} \usetheme{EastLansing} \setbeamertemplate{footline}{% \hbox{% %\begin{beamercolorbox}[wd=.2\paperwidth,ht=3ex,dp=1.75ex,center]{author in head/foot} %\insertauthor %\end{beamercolorbox}% \begin{beamercolorbox}[wd=.9\paperwidth,ht=3ex,dp=1.75ex,left]{section in head/foot} $\; \;$ Meta Learning for Low-Resource Speech Recognition \end{beamercolorbox}% \begin{beamercolorbox}[wd=.1\paperwidth,ht=3ex,dp=1.75ex,center]{number in head/foot} \insertframenumber\ /\ \inserttotalframenumber \end{beamercolorbox}% } } \usetikzlibrary{positioning} \useinnertheme{rectangles} \usefonttheme{professionalfonts} \newcommand{\lw}{0.8mm} \setbeamercovered{transparent} \title{Meta-Learning for\\ End-to-End Low-Resouce Speech Recognition} \subtitle{\textcolor[rgb]{0.00,0.50,1.00}{{Speech Processing \& Machine Learning Laboratory}}} \author{Jui-Yang Hsu} \date{\today} \begin{document} \begin{frame} \maketitle \end{frame} %\begin{frame} %\frametitle{Outline} %\tableofcontents %\end{frame} %\section{Motivation} %\begin{frame}{End-to-End Speech Recognition} %Integrate the main modules of ASR system into single end-to-end model %\vspace{2em} %\pause %However...\\ %To build such system needs \textbf{huge} amount of (speech, transcription) pairs %\end{frame} %\begin{frame}{Low-Resouce Speech Recognition} %\begin{enumerate} %\item Utilizing unpaired monolingual data (Self-/Semi-Supervised Learning) %\item Utilizing other languages' paired data (Multilingual Transfer Learning) %\end{enumerate} %\end{frame} %\begin{frame}{Multilingual Transfer Learning} %Find a unified latent space for all languages through shared encoder, \\ %then use langauge-specific decoder to output token sequence %\center \includegraphics[width=0.5\textwidth]{fig/MultiTaskASR.png} %\end{frame} %\begin{frame}[t]{Multilingual Transfer Learning} %However...\\ %Sometimes the model would overfitted on the source languages, and cannot adapt well on unseen target language. %\vspace{1em} %\pause %Can we transfer the knowledge from source languages more effectively to unseen target language (under low-resource scenerio) ? %\vspace{1em} %\pause %\center \textbf{Fast adaptation on unseen data} %\end{frame} \section{Background Knowledge} \begin{frame}[t]{Meta-Learning: Learning to Learn} Meta-Learning tries to solve \textbf{fast adaptation on unseen data}, \\ and has gained some success in \begin{itemize} \item Computer Vision (\citealt{snell2017prototypical}, \citealt{rusu2018meta} ...) \item Machine Translation (\citealt{gu2018meta}) \item Dialogue Generation (\citealt{mi2019meta}) \item Speaker-Adaptative Training (\citealt{klejch2019speaker}) \end{itemize} \end{frame} \begin{frame}[t]{Model Architecture} \center \includegraphics[width=0.55\textwidth]{fig/model_arch.png} \end{frame} %We propose the multilingual training scheme based on the algorithm \textbf{Model-Agnostic Meta-Learning (MAML)} (\citealt{finn2017model}), %\vspace{3em} \begin{frame}[t]{Recap: Multilingual Transfer Learning} \begin{enumerate} \item Pretraining (Multilingual Training): \\ learn good \textbf{initialization for adaptation} on source langauges \item Adaptation: \\ use the learned initialization to adapt on target language \end{enumerate} \end{frame} \begin{frame}[t]{Multilingual training scheme} \begin{itemize} \item Multitask training: sample one batch from source languages, then perform SGD \item Meta training: simulate the learning process of sampled source languages to obtain \item Use $D^{tr}_k$ to simulate the learning process to obtain $\theta^\prime_k$, $\theta^\prime_{h,k}$ \end{itemize} \end{frame} \begin{frame}[t]{Model-Agnostic Meta-Learning (MAML)} Proposed by \citealt{finn2017model} \end{frame} \begin{frame}[t]{Formulation} Given a set of source langauges $\mathcal{D} = \{D_1, D_2, \cdots D_K \}$ and target language $D_t$ \begin{equation*} \theta^{\star}_t, \theta^{\star}_{h,t} = \texttt{Learn}(D_t;\theta^{\star}) = \texttt{Learn}(D_t;\texttt{MetaLearn}(\mathcal{D})). \end{equation*} \end{frame} \begin{frame}[t]{Learn} \begin{equation*} \begin{aligned} \theta^\prime, \theta^\prime_{h,t} = \texttt{Learn}(D_t;\theta^0) & = \arg \, \min_{\theta, \theta_{h,t}} \mathcal{L}_{D_t}(\theta, \theta_{h,t}) \\ \end{aligned} \end{equation*} \vspace{1em} $\mathcal{L}_{D_t}$: CTC loss on $D$ \vspace{2em} Happened in \begin{itemize} \item Language-specific learning in each meta-training episode \item Adaptation \end{itemize} \end{frame} \begin{frame}[t]{Meta-Learn} In each meta-training episode, we sample batch of tasks from $\mathcal{D}$, \\ then sample two subsets from each task $k$ as train/test, $D^{tr}_k, D^{te}_k$. \begin{enumerate} \item Use $D^{tr}_k$ to simulate the learning process to obtain $\theta^\prime_k$, $\theta^\prime_{h,k}$ \item Calculate the loss adapted on $D^{te}_k$, $\mathcal{L}_{D^{te}_k}(\theta^\prime_k, \theta^\prime_{h,k})$ \item Meta-objective: $\mathcal{L}^{\text{meta}}_{\mathcal{D}}(\theta) = \mathbb{E}_{k \sim \mathcal{D}} \; \mathbb{E}_{D_k^{tr}, D_k^{te}}$ $\Big [ \mathcal{L}_{D^{te}_k}(\theta^\prime_k, \theta^\prime_{h,k}) \Big ]$ \item Use Gradient Descent to minimize $\mathcal{L}^{\text{meta}}_{\mathcal{D}}$ to obtain $\theta^\star$ \end{enumerate} \pause \vspace{2em} \begin{equation*} \theta^{\star}_t, \theta^{\star}_{h,t} = \texttt{Learn}(D_t;\theta^{\star}) \end{equation*} \end{frame} \section{Experimental Results} \begin{frame} \begin{center} %\weib{\LARGE{謝謝聆聽!}} \LARGE{Experimental Results} \end{center} \end{frame} \begin{frame}[t]{Experimental Setting} Corpus: IARPA-BABEL (Conversational Telephone Speech) \begin{itemize} \item FLP: 40 $\sim$ 80 hr \item LLP: 10hr (subset of FLP) \end{itemize} \pause Languages: \begin{itemize} \item Source: Bengali (Bn), Tagalog (Tl), Zulu (Zu), Turkish (Tr), Lithuanian (Lt), Guarani (Gn) \item Target: Vietnamese (Vi), Swahili (Sw), Tamil (Ta), Kurmanji (Ku) \item Validation: Cross-validation \end{itemize} \end{frame} \begin{frame}[t]{CER on FLP} \center \includegraphics[width=1.0\textwidth]{fig/flp_table.png} \end{frame} \begin{frame}[t]{CER on LLP} \center \includegraphics[width=1.0\textwidth]{fig/llp_table.png} \end{frame} \begin{frame}[t]{Learning Curve} \center \includegraphics[width=0.7\textwidth]{fig/lr.png} \end{frame} \begin{frame}[t]{Conclusion} Meta-learned initialization \begin{itemize} \item overall performance is better than multitask-learned one \item doesn't overfit so easily \end{itemize} \pause \vspace{3em} \center new research direction for speech community \end{frame} %\begin{frame}[t]{Multi Transfer Learning (CER on LLP)} %Effect of pretraining step (Vietnamese for example) %\begin{figure}[H] %\centering %%\hspace{-5.2cm} %\begin{tikzpicture}[trim axis left, trim axis right] %\begin{axis}[ %width=1.0\linewidth, %height=0.5\linewidth, %legend entries={PHN-near3, PHN-far3}, %xlabel = {Number of pretraining steps ($\times 10^3$)}, %xmin=-5, %xmax=200, %grid=both, %legend pos=inner north east, %ylabel={CER}] %\addplot+[smooth]table{stat/phn_near3}; %\addplot+[smooth]table{stat/phn_far3}; %\end{axis} %\end{tikzpicture} %\end{figure} %\end{frame} \begin{frame} \begin{center} \LARGE{Q\&A} \end{center} \end{frame} \bibliographystyle{plainnat} \bibliography{M335} \end{document}
This version comes equipped with an air conditioning system providing maximum comfort in hot climatic conditions . A roll over protection structure ( <unk> ) maximizes safety conditions for passengers .
{-# OPTIONS --rewriting --confluence-check #-} data _==_ {i} {A : Set i} : (x y : A) → Set i where refl : {a : A} → a == a {-# BUILTIN REWRITE _==_ #-} data ⊥ : Set where record ⊤ : Set where constructor tt module Test (p : ⊥ == ⊤) where abstract A : Set A = ⊥ q : A == ⊤ q = p {-# REWRITE q #-} f : A f = tt abstract g : ⊥ g = f -- g reduces to tt, which does not have type ⊥.
[STATEMENT] lemma convex_explicit: fixes S :: "'a::real_vector set" shows "convex S \<longleftrightarrow> (\<forall>t u. finite t \<and> t \<subseteq> S \<and> (\<forall>x\<in>t. 0 \<le> u x) \<and> sum u t = 1 \<longrightarrow> sum (\<lambda>x. u x *\<^sub>R x) t \<in> S)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. convex S = (\<forall>t u. finite t \<and> t \<subseteq> S \<and> (\<forall>x\<in>t. 0 \<le> u x) \<and> sum u t = 1 \<longrightarrow> (\<Sum>x\<in>t. u x *\<^sub>R x) \<in> S) [PROOF STEP] proof safe [PROOF STATE] proof (state) goal (2 subgoals): 1. \<And>t u. \<lbrakk>convex S; finite t; t \<subseteq> S; \<forall>x\<in>t. 0 \<le> u x; sum u t = 1\<rbrakk> \<Longrightarrow> (\<Sum>x\<in>t. u x *\<^sub>R x) \<in> S 2. \<forall>t u. finite t \<and> t \<subseteq> S \<and> (\<forall>x\<in>t. 0 \<le> u x) \<and> sum u t = 1 \<longrightarrow> (\<Sum>x\<in>t. u x *\<^sub>R x) \<in> S \<Longrightarrow> convex S [PROOF STEP] fix t [PROOF STATE] proof (state) goal (2 subgoals): 1. \<And>t u. \<lbrakk>convex S; finite t; t \<subseteq> S; \<forall>x\<in>t. 0 \<le> u x; sum u t = 1\<rbrakk> \<Longrightarrow> (\<Sum>x\<in>t. u x *\<^sub>R x) \<in> S 2. \<forall>t u. finite t \<and> t \<subseteq> S \<and> (\<forall>x\<in>t. 0 \<le> u x) \<and> sum u t = 1 \<longrightarrow> (\<Sum>x\<in>t. u x *\<^sub>R x) \<in> S \<Longrightarrow> convex S [PROOF STEP] fix u :: "'a \<Rightarrow> real" [PROOF STATE] proof (state) goal (2 subgoals): 1. \<And>t u. \<lbrakk>convex S; finite t; t \<subseteq> S; \<forall>x\<in>t. 0 \<le> u x; sum u t = 1\<rbrakk> \<Longrightarrow> (\<Sum>x\<in>t. u x *\<^sub>R x) \<in> S 2. \<forall>t u. finite t \<and> t \<subseteq> S \<and> (\<forall>x\<in>t. 0 \<le> u x) \<and> sum u t = 1 \<longrightarrow> (\<Sum>x\<in>t. u x *\<^sub>R x) \<in> S \<Longrightarrow> convex S [PROOF STEP] assume "convex S" and "finite t" and "t \<subseteq> S" "\<forall>x\<in>t. 0 \<le> u x" "sum u t = 1" [PROOF STATE] proof (state) this: convex S finite t t \<subseteq> S \<forall>x\<in>t. 0 \<le> u x sum u t = 1 goal (2 subgoals): 1. \<And>t u. \<lbrakk>convex S; finite t; t \<subseteq> S; \<forall>x\<in>t. 0 \<le> u x; sum u t = 1\<rbrakk> \<Longrightarrow> (\<Sum>x\<in>t. u x *\<^sub>R x) \<in> S 2. \<forall>t u. finite t \<and> t \<subseteq> S \<and> (\<forall>x\<in>t. 0 \<le> u x) \<and> sum u t = 1 \<longrightarrow> (\<Sum>x\<in>t. u x *\<^sub>R x) \<in> S \<Longrightarrow> convex S [PROOF STEP] then [PROOF STATE] proof (chain) picking this: convex S finite t t \<subseteq> S \<forall>x\<in>t. 0 \<le> u x sum u t = 1 [PROOF STEP] show "(\<Sum>x\<in>t. u x *\<^sub>R x) \<in> S" [PROOF STATE] proof (prove) using this: convex S finite t t \<subseteq> S \<forall>x\<in>t. 0 \<le> u x sum u t = 1 goal (1 subgoal): 1. (\<Sum>x\<in>t. u x *\<^sub>R x) \<in> S [PROOF STEP] using convex_sum[of t S u "\<lambda> x. x"] [PROOF STATE] proof (prove) using this: convex S finite t t \<subseteq> S \<forall>x\<in>t. 0 \<le> u x sum u t = 1 \<lbrakk>finite t; convex S; sum u t = 1; \<And>i. i \<in> t \<Longrightarrow> 0 \<le> u i; \<And>i. i \<in> t \<Longrightarrow> i \<in> S\<rbrakk> \<Longrightarrow> (\<Sum>j\<in>t. u j *\<^sub>R j) \<in> S goal (1 subgoal): 1. (\<Sum>x\<in>t. u x *\<^sub>R x) \<in> S [PROOF STEP] by auto [PROOF STATE] proof (state) this: (\<Sum>x\<in>t. u x *\<^sub>R x) \<in> S goal (1 subgoal): 1. \<forall>t u. finite t \<and> t \<subseteq> S \<and> (\<forall>x\<in>t. 0 \<le> u x) \<and> sum u t = 1 \<longrightarrow> (\<Sum>x\<in>t. u x *\<^sub>R x) \<in> S \<Longrightarrow> convex S [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. \<forall>t u. finite t \<and> t \<subseteq> S \<and> (\<forall>x\<in>t. 0 \<le> u x) \<and> sum u t = 1 \<longrightarrow> (\<Sum>x\<in>t. u x *\<^sub>R x) \<in> S \<Longrightarrow> convex S [PROOF STEP] assume *: "\<forall>t. \<forall> u. finite t \<and> t \<subseteq> S \<and> (\<forall>x\<in>t. 0 \<le> u x) \<and> sum u t = 1 \<longrightarrow> (\<Sum>x\<in>t. u x *\<^sub>R x) \<in> S" [PROOF STATE] proof (state) this: \<forall>t u. finite t \<and> t \<subseteq> S \<and> (\<forall>x\<in>t. 0 \<le> u x) \<and> sum u t = 1 \<longrightarrow> (\<Sum>x\<in>t. u x *\<^sub>R x) \<in> S goal (1 subgoal): 1. \<forall>t u. finite t \<and> t \<subseteq> S \<and> (\<forall>x\<in>t. 0 \<le> u x) \<and> sum u t = 1 \<longrightarrow> (\<Sum>x\<in>t. u x *\<^sub>R x) \<in> S \<Longrightarrow> convex S [PROOF STEP] show "convex S" [PROOF STATE] proof (prove) goal (1 subgoal): 1. convex S [PROOF STEP] unfolding convex_alt [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<forall>x\<in>S. \<forall>y\<in>S. \<forall>u. 0 \<le> u \<and> u \<le> 1 \<longrightarrow> (1 - u) *\<^sub>R x + u *\<^sub>R y \<in> S [PROOF STEP] proof safe [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>x y u. \<lbrakk>x \<in> S; y \<in> S; 0 \<le> u; u \<le> 1\<rbrakk> \<Longrightarrow> (1 - u) *\<^sub>R x + u *\<^sub>R y \<in> S [PROOF STEP] fix x y [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>x y u. \<lbrakk>x \<in> S; y \<in> S; 0 \<le> u; u \<le> 1\<rbrakk> \<Longrightarrow> (1 - u) *\<^sub>R x + u *\<^sub>R y \<in> S [PROOF STEP] fix \<mu> :: real [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>x y u. \<lbrakk>x \<in> S; y \<in> S; 0 \<le> u; u \<le> 1\<rbrakk> \<Longrightarrow> (1 - u) *\<^sub>R x + u *\<^sub>R y \<in> S [PROOF STEP] assume **: "x \<in> S" "y \<in> S" "0 \<le> \<mu>" "\<mu> \<le> 1" [PROOF STATE] proof (state) this: x \<in> S y \<in> S 0 \<le> \<mu> \<mu> \<le> 1 goal (1 subgoal): 1. \<And>x y u. \<lbrakk>x \<in> S; y \<in> S; 0 \<le> u; u \<le> 1\<rbrakk> \<Longrightarrow> (1 - u) *\<^sub>R x + u *\<^sub>R y \<in> S [PROOF STEP] show "(1 - \<mu>) *\<^sub>R x + \<mu> *\<^sub>R y \<in> S" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (1 - \<mu>) *\<^sub>R x + \<mu> *\<^sub>R y \<in> S [PROOF STEP] proof (cases "x = y") [PROOF STATE] proof (state) goal (2 subgoals): 1. x = y \<Longrightarrow> (1 - \<mu>) *\<^sub>R x + \<mu> *\<^sub>R y \<in> S 2. x \<noteq> y \<Longrightarrow> (1 - \<mu>) *\<^sub>R x + \<mu> *\<^sub>R y \<in> S [PROOF STEP] case False [PROOF STATE] proof (state) this: x \<noteq> y goal (2 subgoals): 1. x = y \<Longrightarrow> (1 - \<mu>) *\<^sub>R x + \<mu> *\<^sub>R y \<in> S 2. x \<noteq> y \<Longrightarrow> (1 - \<mu>) *\<^sub>R x + \<mu> *\<^sub>R y \<in> S [PROOF STEP] then [PROOF STATE] proof (chain) picking this: x \<noteq> y [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: x \<noteq> y goal (1 subgoal): 1. (1 - \<mu>) *\<^sub>R x + \<mu> *\<^sub>R y \<in> S [PROOF STEP] using *[rule_format, of "{x, y}" "\<lambda> z. if z = x then 1 - \<mu> else \<mu>"] ** [PROOF STATE] proof (prove) using this: x \<noteq> y finite {x, y} \<and> {x, y} \<subseteq> S \<and> (\<forall>xa\<in>{x, y}. 0 \<le> (if xa = x then 1 - \<mu> else \<mu>)) \<and> (\<Sum>z\<in>{x, y}. if z = x then 1 - \<mu> else \<mu>) = 1 \<Longrightarrow> (\<Sum>xa\<in>{x, y}. (if xa = x then 1 - \<mu> else \<mu>) *\<^sub>R xa) \<in> S x \<in> S y \<in> S 0 \<le> \<mu> \<mu> \<le> 1 goal (1 subgoal): 1. (1 - \<mu>) *\<^sub>R x + \<mu> *\<^sub>R y \<in> S [PROOF STEP] by auto [PROOF STATE] proof (state) this: (1 - \<mu>) *\<^sub>R x + \<mu> *\<^sub>R y \<in> S goal (1 subgoal): 1. x = y \<Longrightarrow> (1 - \<mu>) *\<^sub>R x + \<mu> *\<^sub>R y \<in> S [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. x = y \<Longrightarrow> (1 - \<mu>) *\<^sub>R x + \<mu> *\<^sub>R y \<in> S [PROOF STEP] case True [PROOF STATE] proof (state) this: x = y goal (1 subgoal): 1. x = y \<Longrightarrow> (1 - \<mu>) *\<^sub>R x + \<mu> *\<^sub>R y \<in> S [PROOF STEP] then [PROOF STATE] proof (chain) picking this: x = y [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: x = y goal (1 subgoal): 1. (1 - \<mu>) *\<^sub>R x + \<mu> *\<^sub>R y \<in> S [PROOF STEP] using *[rule_format, of "{x, y}" "\<lambda> z. 1"] ** [PROOF STATE] proof (prove) using this: x = y finite {x, y} \<and> {x, y} \<subseteq> S \<and> (\<forall>x\<in>{x, y}. 0 \<le> 1) \<and> (\<Sum>z\<in>{x, y}. 1) = 1 \<Longrightarrow> sum ((*\<^sub>R) 1) {x, y} \<in> S x \<in> S y \<in> S 0 \<le> \<mu> \<mu> \<le> 1 goal (1 subgoal): 1. (1 - \<mu>) *\<^sub>R x + \<mu> *\<^sub>R y \<in> S [PROOF STEP] by (auto simp: field_simps real_vector.scale_left_diff_distrib) [PROOF STATE] proof (state) this: (1 - \<mu>) *\<^sub>R x + \<mu> *\<^sub>R y \<in> S goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: (1 - \<mu>) *\<^sub>R x + \<mu> *\<^sub>R y \<in> S goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: convex S goal: No subgoals! [PROOF STEP] qed
/* * Tema 2 ASC * 2019 Spring * Catalin Olaru / Vlad Spoiala */ #include <cblas.h> #include "utils.h" /* * Add your BLAS implementation here */ double* my_solver(int N, double *A, double *B) { double *first_multiplication = malloc(N * N * sizeof(double)); double *second_multiplication = malloc(N * N * sizeof(double)); double *final_result = malloc(N * N * sizeof(double)); double alpha = 1.0; double beta = 0.0; double *identity_matrix = malloc(N * N * sizeof(double)); int i, j; /* Compute identity matrix so we can use it later on. */ for (i = 0; i < N; ++i) for (j = 0; j < N; ++j) identity_matrix[i * N + j] = j == i ? 1.0 : 0.0; /* Compute Transpose(A) * B in first_multiplication. */ cblas_dgemm(CblasRowMajor, CblasTrans, CblasNoTrans, N, N, N, alpha, A, N, B, N, beta, first_multiplication, N); /* Compute Transpose(B) * A in second_multiplication. */ cblas_dgemm(CblasRowMajor, CblasTrans, CblasNoTrans, N, N, N, alpha, B, N, A, N, beta, second_multiplication, N); /* Add the previous 2 results in second multiplication. */ cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, N, N, N, alpha, first_multiplication, N, identity_matrix, N, alpha, second_multiplication, N); /* Apply zerotr(second_multiplication) as everything involving * CblasLower or CblasUpper didn't work for some reason. :( */ for (i = 0; i < N; ++i) for (j = 0; j < i; ++j) second_multiplication[i * N + j] = 0; /* Multiply second_multiplication by itself so we get the * result in final_result. */ cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, N, N, N, alpha, second_multiplication, N, second_multiplication, N, beta, final_result, N); /* Free everything aside from the return value. */ free(first_multiplication); free(second_multiplication); free(identity_matrix); return final_result; }
import number_theory.bernoulli --OUTPUT 1 theorem bernoulli_eval_one_add (n : ℕ) (x : ℚ) : (polynomial.bernoulli n).eval (1 + x) = (polynomial.bernoulli n).eval x + n * x^(n - 1) := begin -- We apply strong induction on $n$. So, for all $m < d$, we have $B_{m} (1 + x) = B_{m} (x) + m x^{m - 1}$ and we want to show that $$B_{d} (1 + x) = B_{d} (x) + d x^{d - 1}$$ apply nat.strong_induction_on n, assume n hn, assume h : ∀ m < n, (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), -- Multiplying both sides by $d + 1$, and using the fact that, for all $l \in \mathbb{N}$, $\sum_{k = 0}^{l} {l + 1 \choose k} B_k = (l + 1) X^l$ (where $B_k$ is the $k$-th Bernoulli number), we get that -- $$ (d + 1) (1 + x)^d - (d + 1) x^d = \sum_{l = 0}^{d} {d + 1 \choose l} l x^{l - 1} $$ have h1 : (n + 1) * (1 + x)^n - (n + 1) * x^n = (polynomial.bernoulli n).eval (1 + x), from by auto [polynomial.eval_mul, polynomial.eval_add, polynomial.eval_pow, polynomial.eval_C], have h2 : (n + 1) * (1 + x)^n - (n + 1) * x^n = (polynomial.bernoulli n).eval x + n * x^(n - 1), from by auto [polynomial.eval_mul, polynomial.eval_add, polynomial.eval_pow, polynomial.eval_C, h], -- The conclusion then follows easily. show (polynomial.bernoulli (n + 1)).eval (1 + x) = (polynomial.bernoulli (n + 1)).eval x + (n + 1) * x^n, from by auto [h1, h2], end --OUTPUT 2 theorem bernoulli_eval_one_add (n : ℕ) (x : ℚ) : (polynomial.bernoulli n).eval (1 + x) = (polynomial.bernoulli n).eval x + n * x^(n - 1) := begin -- We apply strong induction on $n$. have h1 : ∀ m : ℕ, m < n → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from by auto using [nat.lt_succ_iff, nat.succ_pos], have h2 : ∀ m : ℕ, m < n → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from by auto using [h1], have h3 : ∀ m : ℕ, m < n → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from by auto using [h2], have h4 : ∀ m : ℕ, m < n → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from by auto using [h3], have h5 : ∀ m : ℕ, m < n → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from by auto using [h4], have h6 : ∀ m : ℕ, m < n → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from by auto using [h5], have h7 : ∀ m : ℕ, m < n → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from by auto using [h6], have h8 : ∀ m : ℕ, m < n → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from by auto using [h7], have h9 : ∀ m : ℕ, m < n → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from by auto using [h8], have h10 : ∀ m : ℕ, m < n → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from by auto using [h9], have h11 : ∀ m : ℕ, m < n → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from by auto using [h10], have h12 : ∀ m : ℕ, m < n → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from by auto using [h11], have h13 : ∀ m : ℕ, m < n → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from by auto using [h12], have h14 : ∀ m : ℕ, m < n → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from by auto using [h13], have h15 : ∀ m : ℕ, m < n → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from by auto using [h14], have h16 : ∀ m : ℕ, m < n → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from by auto using [h15], have h17 : ∀ m : ℕ, m < n → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from by auto using [h16], have h18 : ∀ m : ℕ, m < n → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from by auto using [h17], have h19 : ∀ m : ℕ, m < n → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from by auto using [h18], have h20 : ∀ m : ℕ, m < n → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from by auto using [h19], have h21 : ∀ m : ℕ, m < n → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from by auto using [h20], have h22 : ∀ m : ℕ, m < n → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from by auto using [h21], have h23 : ∀ m : ℕ, m < n → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from by auto using [h22], have h24 : ∀ m : ℕ, m < n → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from by auto using [h23], have h25 : ∀ m : ℕ, m < n → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from by auto using [h24], have h26 : ∀ m : ℕ, m < n → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from by auto using [h25], have h27 : ∀ m : ℕ, m < n → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from by auto using [h26], have h28 : ∀ m : ℕ, m < n → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from by auto using [h27], have h29 : ∀ m : ℕ, m < n → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from by auto using [h28], have h30 : ∀ m : ℕ, m < n → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from by auto using [h29], have h31 : ∀ m : ℕ, m < n → (polynomial.bern end --Needs more than 2000 tokens! --OUTPUT 3 theorem bernoulli_eval_one_add (n : ℕ) (x : ℚ) : (polynomial.bernoulli n).eval (1 + x) = (polynomial.bernoulli n).eval x + n * x^(n - 1) := begin -- We apply strong induction on $n$. So, for all $m < d$, we have $B_{m} (1 + x) = B_{m} (x) + m x^{m - 1}$ and we want to show that $$B_{d} (1 + x) = B_{d} (x) + d x^{d - 1}$$ apply nat.strong_induction_on n, assume d hd, -- Multiplying both sides by $d + 1$, and using the fact that, for all $l \in \mathbb{N}$, $\sum_{k = 0}^{l} {l + 1 \choose k} B_k = (l + 1) X^l$ (where $B_k$ is the $k$-th Bernoulli number), we get that -- $$ (d + 1) (1 + x)^d - (d + 1) x^d = \sum_{l = 0}^{d} {d + 1 \choose l} l x^{l - 1} $$ have h1 : (d + 1) * (1 + x)^d - (d + 1) * x^d = (d + 1) * (polynomial.sum (λ (k : ℕ), (polynomial.C (nat.choose (d + 1) k) * polynomial.X^k)) (d + 1)), begin -- expand the polynomials rw [polynomial.eval_sum, polynomial.eval_C, polynomial.eval_X], -- use the fact that, for all $l \in \mathbb{N}$, $\sum_{k = 0}^{l} {l + 1 \choose k} B_k = (l + 1) X^l$ (where $B_k$ is the $k$-th Bernoulli number) rw [polynomial.bernoulli_sum_of_choose], -- use the fact that $(1 + x)^d = x^d + \sum_{l = 0}^{d} {d \choose l} x^l$ rw [polynomial.eval_sum, polynomial.eval_C, polynomial.eval_X, polynomial.eval_sum, polynomial.eval_C, polynomial.eval_X], -- use the fact that $x^d = x^d$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial.eval_X], -- use the fact that $x^l = x^l$ rw [polynomial. end --Needs more than 2000 tokens! /- FEW SHOT PROMPTS TO CODEX(START) /--`theorem` Power Set is Closed under Intersection Let $S$ be a set. Let $\powerset S$ be the power set of $S$. Then: :$\forall A, B \in \powerset S: A \cap B \in \powerset S$ `proof` Let $A, B \in \powerset S$. Then by the definition of power set, $A \subseteq S$ and $B \subseteq S$. From Intersection is Subset we have that $A \cap B \subseteq A$. It follows from Subset Relation is Transitive that $A \cap B \subseteq S$. Thus $A \cap B \in \powerset S$ and closure is proved. {{qed}} -/ theorem power_set_intersection_closed {α : Type*} (S : set α) : ∀ A B ∈ 𝒫 S, (A ∩ B) ∈ 𝒫 S := begin -- $A$ and $B$ are sets. $A$ and $B$ belong to power set of $S$ assume (A : set α) (hA : A ∈ 𝒫 S) (B : set α) (hB : B ∈ 𝒫 S), -- Then $A ⊆ S$ and $B ⊆ S$, by power set definition have h1 : (A ⊆ S) ∧ (B ⊆ S), from by auto [set.subset_of_mem_powerset, set.subset_of_mem_powerset], -- Then $(A ∩ B) ⊆ A$, by intersection of set is a subset have h2 : (A ∩ B) ⊆ A, from by auto [set.inter_subset_left], -- Then $(A ∩ B) ⊆ S$, by subset relation is transitive have h3 : (A ∩ B) ⊆ S, from by auto [set.subset.trans], -- Hence $(A ∩ B) ∈ 𝒫 S$, by power set definition show (A ∩ B) ∈ 𝒫 S, from by auto [set.mem_powerset], end /--`theorem` Square of Sum :$\forall x, y \in \R: \paren {x + y}^2 = x^2 + 2 x y + y^2$ `proof` Follows from the distribution of multiplication over addition: {{begin-eqn}} {{eqn | l = \left({x + y}\right)^2 | r = \left({x + y}\right) \cdot \left({x + y}\right) }} {{eqn | r = x \cdot \left({x + y}\right) + y \cdot \left({x + y}\right) | c = Real Multiplication Distributes over Addition }} {{eqn | r = x \cdot x + x \cdot y + y \cdot x + y \cdot y | c = Real Multiplication Distributes over Addition }} {{eqn | r = x^2 + 2xy + y^2 | c = }} {{end-eqn}} {{qed}} -/ theorem square_of_sum (x y : ℝ) : (x + y)^2 = (x^2 + 2*x*y + y^2) := begin -- expand the power calc (x + y)^2 = (x+y)*(x+y) : by auto [sq] -- distributive property of multiplication over addition gives: ... = x*(x+y) + y*(x+y) : by auto [add_mul] -- applying the above property further gives: ... = x*x + x*y + y*x + y*y : by auto [mul_comm, add_mul] using [ring] -- rearranging the terms using commutativity and adding gives: ... = x^2 + 2*x*y + y^2 : by auto [sq, mul_comm] using [ring] end /--`theorem` Identity of Group is Unique Let $\struct {G, \circ}$ be a group. Then there is a unique identity element $e \in G$. `proof` From Group has Latin Square Property, there exists a unique $x \in G$ such that: :$a x = b$ and there exists a unique $y \in G$ such that: :$y a = b$ Setting $b = a$, this becomes: There exists a unique $x \in G$ such that: :$a x = a$ and there exists a unique $y \in G$ such that: :$y a = a$ These $x$ and $y$ are both $e$, by definition of identity element. {{qed}} -/ theorem group_identity_unique {G : Type*} [group G] : ∃! e : G, ∀ a : G, e * a = a ∧ a * e = a := begin -- Group has Latin Square Property have h1 : ∀ a b : G, ∃! x : G, a * x = b, from by auto using [use (a⁻¹ * b)], have h2 : ∀ a b : G, ∃! y : G, y * a = b, from by auto using [use b * a⁻¹], -- Setting $b = a$, this becomes: have h3 : ∀ a : G, ∃! x : G, a * x = a, from by auto [h1], have h4 : ∀ a : G, ∃! y : G, y * a = a, from by auto [h2], -- These $x$ and $y$ are both $(1 : G)$, by definition of identity element have h5 : ∀ a : G, classical.some (h3 a).exists = (1 : G), from by auto [exists_unique.unique, h3, classical.some_spec, exists_unique.exists, mul_one], have h6 : ∀ a : G, classical.some (h4 a).exists = (1 : G), from by auto [exists_unique.unique, h4, classical.some_spec, exists_unique.exists, one_mul], show ∃! e : G, ∀ a : G, e * a = a ∧ a * e = a, from by auto [h3, h4, exists_unique.unique, classical.some_spec, exists_unique.exists] using [use (1 : G)], end /--`theorem` Bernoulli polynomial evaluation Given a natural number $n$ and a rational $x$, let $B_n (x)$ denote the $n$-th Bernoulli polynomial evaluated at $x$. Then, $$B_n (1 + x) = B_n (x) + n x^{n - 1}$$ `proof` We apply strong induction on $n$. So, for all $m < d$, we have $B_{m} (1 + x) = B_{m} (x) + m x^{m - 1}$ and we want to show that $$B_{d} (1 + x) = B_{d} (x) + d x^{d - 1}$$ Multiplying both sides by $d + 1$, and using the fact that, for all $l \in \mathbb{N}$, $\sum_{k = 0}^{l} {l + 1 \choose k} B_k = (l + 1) X^l$ (where $B_k$ is the $k$-th Bernoulli number), we get that $$ (d + 1) (1 + x)^d - (d + 1) x^d = \sum_{l = 0}^{d} {d + 1 \choose l} l x^{l - 1} $$ The conclusion then follows easily. QED -/ theorem bernoulli_eval_one_add (n : ℕ) (x : ℚ) : (polynomial.bernoulli n).eval (1 + x) = (polynomial.bernoulli n).eval x + n * x^(n - 1) := FEW SHOT PROMPTS TO CODEX(END)-/
module TelescopingLet4 where module Star where ★ : Set₁ ★ = Set ★₁ : Set₂ ★₁ = Set₁ data D5 (open Star using (★₁)) : ★₁ where
From Coq Require Import Strings.String. From Coq Require Import Strings.Ascii. From Coq Require Import Arith.Arith. From Coq Require Import Init.Nat. From Coq Require Import Arith.EqNat. From Coq Require Import Lists.List. Import ListNotations. From LF Require Import Imp. Definition isWhite (c : ascii) : bool := let n := nat_of_ascii c in match n with | 32 => true (* space *) | 9 => true (* tab *) | 10 => true (* linefeed *) | 13 => true (* Carriage return *) | _ => false end. Notation "x '<=?' y" := (x <=? y). Definition isLowerAlpha (c : ascii) : bool := let n := nat_of_ascii c in andb (97 <=? n) (n <=? 122). Definition isAlpha (c : ascii) : bool := let n := nat_of_ascii c in orb (andb (65 <=? n) (n <=? 90)) (andb (97 <=? n) (n <=? 122)). Definition isDigit (c : ascii) : bool := let n := nat_of_ascii c in andb (48 <=? n) (n <=? 57). Inductive charType : Type := | white | alpha | digit | other. Definition classifyChar (c : ascii) : charType := if isWhite c then white else if isAlpha c then alpha else if isDigit c then digit else other. Fixpoint listOfString (s : string) : list ascii := match s with | EmptyString => [] | String c s => c :: (listOfString s) end. Definition stringOfList (xs : list ascii) : string := fold_right String EmptyString xs. Definition token := string. Fixpoint tokenize_helper (cls : charType) (acc xs : list ascii) : list (list ascii) := let tk := match acc with | [] => [] | _ :: _ => [rev acc] end in match xs with | [] => tk | (x :: xs') => match cls, classifyChar x, x with | _, _, "(" => tk ++ ["("] :: (tokenize_helper other [] xs') | _, _, ")" => tk ++ [")"] :: (tokenize_helper other [] xs') | _, white, _ => tk ++ (tokenize_helper white [] xs') | alpha, alpha, x => tokenize_helper alpha (x::acc) xs' | digit, digit, x => tokenize_helper digit (x::acc) xs' | other, other, x => tokenize_helper other (x::acc) xs' | _, tp, x => tk ++ (tokenize_helper tp [x] xs') end end % char. Definition tokenize (s : string) : list string := map stringOfList (tokenize_helper white [] (listOfString s)). Example tokenize_ex1 : tokenize "abc12=3 223*(3+(a+c))" % string = ["abc"; "12"; "="; "3"; "223"; "*"; "("; "3"; "+"; "("; "a"; "+"; "c"; ")"; ")"] % string. Proof. compute. reflexivity. Qed. Inductive optionE (X : Type) : Type := | SomeE (x : X) | NoneE (s : string). Arguments SomeE {X}. Arguments NoneE {X}. Notation "' p <- e1 ;; e2" := ( match e1 with | SomeE p => e2 | NoneE err => NoneE err end ) (right associativity, p pattern, at level 60, e1 at next level). Notation "'TRY' ' p <- e1 ;; e2 'OR' e3" := ( match e1 with | SomeE p => e2 | NoneE _ => e3 end ) (right associativity, p pattern, at level 60, e1 at next level, e2 at next level). Open Scope string_scope. Definition parser (T : Type) := list token -> optionE (T * list token). Fixpoint many_helper {T} (p : parser T) acc steps xs := match steps, p xs with | 0, _ => NoneE "Too many recursive calls" | _, NoneE _ => SomeE ((rev acc), xs) | S steps', SomeE (t, xs') => many_helper p (t::acc) steps' xs' end. Definition many {T} (p : parser T) (steps : nat) : parser (list T) := many_helper p [] steps. Definition firstExpect {T} (t : token) (p : parser T) : parser T := fun xs => match xs with | x :: xs' => if string_dec x t then p xs' else NoneE ("expected '" ++ t ++ "'.") | [] => NoneE ("expected '" ++ t ++ "'.") end. Definition expect (t : token) : parser unit := firstExpect t (fun xs => SomeE (tt, xs)). Definition parseIdentifier (xs : list token) : optionE (string * list token) := match xs with | [] => NoneE "Expected identifier" | x :: xs' => if forallb isLowerAlpha (listOfString x) then SomeE (x, xs') else NoneE ("Illegal identifier: '" ++ x ++ "'") end. Definition parseNumber (xs : list token) : optionE (nat * list token) := match xs with | [] => NoneE "Expected number" | x :: xs' => if forallb isDigit (listOfString x) then SomeE (fold_left (fun n d => 10 * n + (nat_of_ascii d - nat_of_ascii "0"%char) ) (listOfString x) 0, xs') else NoneE "Expected number" end. Fixpoint parsePrimaryExp (steps : nat) (xs : list token) : optionE (aexp * list token) := match steps with | 0 => NoneE "Too many recursive calls" | S steps' => TRY ' (i, rest) <- parseIdentifier xs ;; SomeE (AId i, rest) OR TRY ' (n, rest) <- parseNumber xs ;; SomeE (ANum n, rest) OR ' (e, rest) <- firstExpect "(" (parseSumExp steps') xs ;; ' (u, rest') <- expect ")" rest ;; SomeE (e, rest') end with parseProductExp (steps : nat) (xs : list token) := match steps with | 0 => NoneE "Too many recursive calls." | S steps' => ' (e, rest) <- parsePrimaryExp steps' xs ;; ' (es, rest') <- many (firstExpect "*" (parsePrimaryExp steps')) steps' rest ;; SomeE (fold_left AMult es e, rest') end with parseSumExp (steps : nat) (xs : list token) := match steps with | 0 => NoneE "Too many recursive calls" | S steps' => ' (e, rest) <- parseProductExp steps' xs ;; ' (es, rest') <- many (fun xs => TRY ' (e, rest') <- firstExpect "+" (parseProductExp steps') xs ;; SomeE ((true, e), rest') OR ' (e, rest') <- firstExpect "-" (parseProductExp steps') xs ;; SomeE ((false, e), rest') ) steps' rest ;; SomeE (fold_left (fun e0 term => match term with | (true, e) => APlus e0 e | (false, e) => AMinus e0 e end) es e, rest') end. Definition parseAExp := parseSumExp. Fixpoint parseAtomExp (steps : nat) (xs : list token) := match steps with | 0 => NoneE "Too many recursive calls" | S steps' => TRY ' (u, rest) <- expect "true" xs ;; SomeE (BTrue, rest) OR TRY ' (u, rest) <- expect "false" xs ;; SomeE (BFalse, rest) OR TRY ' (e, rest) <- firstExpect "~" (parseAtomExp steps') xs ;; SomeE (BNot e, rest) OR TRY ' (e, rest) <- firstExpect "(" (parseConjunctionExp steps') xs ;; ' (u, rest') <- expect ")" rest ;; SomeE (e, rest') OR ' (e, rest) <- parseProductExp steps' xs ;; TRY ' (e', rest') <- firstExpect "=" (parseAExp steps') rest ;; SomeE (BEq e e', rest') OR TRY ' (e', rest') <- firstExpect "<=" (parseAExp steps') rest ;; SomeE (BLe e e', rest') OR NoneE "Expected '=' or '<=' after arithmetic expression" end with parseConjunctionExp (steps : nat) (xs : list token) := match steps with | 0 => NoneE "Too many recursive calls" | S steps' => ' (e, rest) <- parseAtomExp steps' xs ;; ' (es, rest') <- many (firstExpect "&&" (parseAtomExp steps')) steps' rest ;; SomeE (fold_left BAnd es e, rest') end. Definition parseBExp := parseConjunctionExp. Check parseConjunctionExp. Definition testParsing {X : Type} (p : nat -> list token -> optionE (X * list token)) (s : string) := let t := tokenize s in p 100 t. Eval compute in testParsing parseProductExp "x.y.(x.x).x". Eval compute in testParsing parseConjunctionExp "~(x = x && x * x <= (x * x) * x) && x = x". Fixpoint parseSimpleCommand (steps : nat) (xs : list token) := match steps with | 0 => NoneE "Too many recursive calls" | S steps' => TRY ' (u, rest) <- expect "skip" xs ;; SomeE (<{skip}>, rest) OR TRY ' (e, rest) <- firstExpect "if" (parseBExp steps') xs ;; ' (c, rest') <- firstExpect "then" (parseSequencedCommand steps') rest ;; ' (c', rest'') <- firstExpect "else" (parseSequencedCommand steps') rest' ;; ' (tt, rest''') <- expect "end" rest'';; SomeE (<{if e then c else c' end}>, rest''') OR TRY ' (e, rest) <- firstExpect "while" (parseBExp steps') xs ;; ' (c, rest') <- firstExpect "do" (parseSequencedCommand steps') rest ;; ' (u, rest'') <- expect "end" rest' ;; SomeE (<{while e do c end}>, rest'') OR TRY ' (i, rest) <- parseIdentifier xs ;; ' (e, rest') <- firstExpect ":=" (parseAExp steps') rest ;; SomeE (<{i := e}>, rest') OR NoneE "Expecting a command" end with parseSequencedCommand (steps : nat) (xs : list token) := match steps with | 0 => NoneE "Too many recursive calls" | S steps' => ' (c, rest) <- parseSimpleCommand steps' xs ;; TRY ' (c', rest') <- firstExpect ";" (parseSequencedCommand steps') rest ;; SomeE (<{c ; c'}>, rest') OR SomeE (c, rest) end. Definition bignumber := 1000. Definition parse (str : string) : optionE com := let tokens := tokenize str in match parseSequencedCommand bignumber tokens with | SomeE (c, []) => SomeE c | SomeE (_, t::_) => NoneE ("Trailing tokens remaining: " ++ t) | NoneE err => NoneE err end.
section \<open>Directed Graphs\<close> theory Graph imports Main begin text \<open> We define a specialized graph library for graphs that are induced by capacity matrices. \<close> lemma finite_Image: fixes R shows "\<lbrakk> finite R \<rbrakk> \<Longrightarrow> finite (R `` A)" by (meson Image_iff finite_Range Range.intros finite_subset subsetI) lemma map_eq_appendE: assumes "map f ls = fl@fl'" obtains l l' where "ls=l@l'" and "map f l=fl" and "map f l' = fl'" using that[of "take (length fl) ls" "drop (length fl) ls"] assms by(simp add: take_map[symmetric] drop_map[symmetric]) subsection \<open>Definitions\<close> subsubsection \<open>Basic Definitions\<close> text \<open> We fix the nodes to be natural numbers. \<close> type_synonym node = nat type_synonym edge = "node \<times> node" text \<open> The capacities are left polymorphic, however, they are restricted to linearly ordered domains. \<close> type_synonym 'capacity graph = "edge \<Rightarrow> 'capacity" locale Graph = fixes c :: "'capacity::linordered_idom graph" begin definition E :: "edge set" \<comment> \<open>Edges of the graph\<close> where "E \<equiv> {(u, v). c (u, v) \<noteq> 0}" definition V :: "node set" \<comment> \<open>Nodes of the graph. Exactly the nodes that have adjacent edges.\<close> where "V \<equiv> {u. \<exists>v. (u, v) \<in> E \<or> (v, u) \<in> E}" definition incoming :: "node \<Rightarrow> edge set" \<comment> \<open>Incoming edges into a node\<close> where "incoming v \<equiv> {(u, v) | u. (u, v) \<in> E}" definition outgoing :: "node \<Rightarrow> edge set" \<comment> \<open>Outgoing edges from a node\<close> where "outgoing v \<equiv> {(v, u) | u. (v, u) \<in> E}" definition adjacent :: "node \<Rightarrow> edge set" \<comment> \<open>Adjacent edges of a node\<close> where "adjacent v \<equiv> incoming v \<union> outgoing v" definition incoming' :: "node set \<Rightarrow> edge set" \<comment> \<open>Incoming edges into a set of nodes\<close> where "incoming' k \<equiv> {(u, v) | u v. u \<notin> k \<and> v \<in> k \<and> (u, v) \<in> E}" definition outgoing' :: "node set \<Rightarrow> edge set" \<comment> \<open>Outgoing edges from a set of nodes\<close> where "outgoing' k \<equiv> {(v, u) | u v. u \<notin> k \<and> v \<in> k \<and> (v, u) \<in> E}" definition adjacent' :: "node set \<Rightarrow> edge set" \<comment> \<open>Edges adjacent to a set of nodes\<close> where "adjacent' k \<equiv> incoming' k \<union> outgoing' k" definition is_adj_map :: "(node \<Rightarrow> node list) \<Rightarrow> bool" where "is_adj_map ps \<equiv> (\<forall>u. distinct (ps u) \<and> set (ps u) = E``{u} \<union> E\<inverse>``{u})" definition "adjacent_nodes u \<equiv> E``{u} \<union> E\<inverse>``{u}" end \<comment> \<open>Graph\<close> subsubsection \<open>Finite Graphs\<close> locale Finite_Graph = Graph + assumes finite_V[simp, intro!]: "finite V" subsubsection \<open>Paths\<close> type_synonym path = "edge list" context Graph begin fun isPath :: "node \<Rightarrow> path \<Rightarrow> node \<Rightarrow> bool" where "isPath u [] v \<longleftrightarrow> u = v" | "isPath u ((x,y)#p) v \<longleftrightarrow> u = x \<and> (x, y) \<in> E \<and> isPath y p v" fun pathVertices :: "node \<Rightarrow> path \<Rightarrow> node list" where "pathVertices u [] = [u]" | "pathVertices u (e # es) = fst e # (pathVertices (snd e) es)" (* TODO: This characterization is probably nicer to work with! Exchange! *) definition (in Graph) pathVertices_fwd :: "node \<Rightarrow> edge list \<Rightarrow> node list" where "pathVertices_fwd u p = u#map snd p" lemma (in Graph) pathVertices_fwd: assumes "isPath u p v" shows "pathVertices u p = pathVertices_fwd u p" unfolding pathVertices_fwd_def using assms apply (induction p arbitrary: u) by auto definition connected :: "node \<Rightarrow> node \<Rightarrow> bool" where "connected u v \<equiv> \<exists>p. isPath u p v" abbreviation (input) "isReachable \<equiv> connected" (* Deprecated *) definition reachableNodes :: "node \<Rightarrow> node set" where "reachableNodes u \<equiv> {v. connected u v}" definition isShortestPath :: "node \<Rightarrow> path \<Rightarrow> node \<Rightarrow> bool" where "isShortestPath u p v \<equiv> isPath u p v \<and> (\<forall>p'. isPath u p' v \<longrightarrow> length p \<le> length p')" definition isSimplePath :: "node \<Rightarrow> path \<Rightarrow> node \<Rightarrow> bool" where "isSimplePath u p v \<equiv> isPath u p v \<and> distinct (pathVertices u p)" definition dist :: "node \<Rightarrow> nat \<Rightarrow> node \<Rightarrow> bool" \<comment> \<open>There is a path of given length between the nodes\<close> where "dist v d v' \<equiv> \<exists>p. isPath v p v' \<and> length p = d" definition min_dist :: "node \<Rightarrow> node \<Rightarrow> nat" \<comment> \<open>Minimum distance between two connected nodes\<close> where "min_dist v v' = (LEAST d. dist v d v')" end subsection \<open>Properties\<close> subsubsection \<open>Basic Properties\<close> context Graph begin lemma V_alt: "V = fst`E \<union> snd`E" unfolding V_def by force lemma E_ss_VxV: "E \<subseteq> V\<times>V" by (auto simp: V_def) lemma adjacent_nodes_ss_V: "adjacent_nodes u \<subseteq> V" unfolding adjacent_nodes_def using E_ss_VxV by auto lemma Vfin_imp_Efin[simp, intro]: assumes "finite V" shows "finite E" using E_ss_VxV assms by (auto intro: finite_subset) lemma Efin_imp_Vfin: "finite E \<Longrightarrow> finite V" unfolding V_alt by auto lemma zero_cap_simp[simp]: "(u,v)\<notin>E \<Longrightarrow> c (u,v) = 0" by (auto simp: E_def) lemma succ_ss_V: "E``{u} \<subseteq> V" by (auto simp: V_def) lemma pred_ss_V: "E\<inverse>``{u} \<subseteq> V" by (auto simp: V_def) lemma incoming_edges: "incoming u \<subseteq> E" and outgoing_edges: "outgoing u \<subseteq> E" and incoming'_edges: "incoming' U \<subseteq> E" and outgoing'_edges: "outgoing' U \<subseteq> E" by (auto simp: incoming_def outgoing_def incoming'_def outgoing'_def) lemma incoming_alt: "incoming u = (\<lambda>v. (v,u))`(E\<inverse>``{u})" and outgoing_alt: "outgoing u = Pair u`(E``{u})" by (auto simp: incoming_def outgoing_def) lemma finite_incoming[simp, intro]: "finite V \<Longrightarrow> finite (incoming u)" and finite_outgoing[simp, intro]: "finite V \<Longrightarrow> finite (outgoing u)" by (auto simp: incoming_alt outgoing_alt intro: finite_Image) lemma finite_incoming'[simp, intro]: "finite V \<Longrightarrow> finite (incoming' U)" and finite_outgoing'[simp, intro]: "finite V \<Longrightarrow> finite (outgoing' U)" by (auto intro: finite_subset[OF incoming'_edges] intro: finite_subset[OF outgoing'_edges]) subsubsection \<open>Summations over Edges and Nodes\<close> text \<open>We provide useful alternative characterizations for summation over all incoming or outgoing edges.\<close> lemma sum_outgoing_pointwise: "(\<Sum>e\<in>outgoing u. g e) = (\<Sum>v\<in>E``{u}. g (u,v))" proof - have "(\<Sum>e\<in>outgoing u. g e) = (\<Sum>e\<in>(\<lambda>v. (u,v))`(E``{u}). g e)" by (rule sum.cong) (auto simp: outgoing_def) also have "\<dots> = (\<Sum>v\<in>E``{u}. g (u,v))" by (subst sum.reindex)(auto simp add: inj_on_def) finally show ?thesis . qed lemma sum_incoming_pointwise: "(\<Sum>e\<in>incoming u. g e) = (\<Sum>v\<in>E\<inverse>``{u}. g (v,u))" proof - have "(\<Sum>e\<in>incoming u. g e) = (\<Sum>e\<in>(\<lambda>v. (v,u))`(E\<inverse>``{u}). g e)" by (rule sum.cong) (auto simp: incoming_def) also have "\<dots> = (\<Sum>v\<in>E\<inverse>``{u}. g (v,u))" by (subst sum.reindex)(auto simp add: inj_on_def) finally show ?thesis . qed text \<open>Extend summations over incoming/outgoing edges to summations over all nodes, provided the summed-up function is zero for non-edges.\<close> lemma (in Finite_Graph) sum_incoming_extend: assumes "\<And>v. \<lbrakk> v\<in>V; (v,u)\<notin>E \<rbrakk> \<Longrightarrow> g (v,u) = 0" shows "(\<Sum>e\<in>incoming u. g e) = (\<Sum>v\<in>V. g (v,u))" apply (subst sum_incoming_pointwise) apply (rule sum.mono_neutral_left) using assms pred_ss_V by auto lemma (in Finite_Graph) sum_outgoing_extend: assumes "\<And>v. \<lbrakk> v\<in>V; (u,v)\<notin>E \<rbrakk> \<Longrightarrow> g (u,v) = 0" shows "(\<Sum>e\<in>outgoing u. g e) = (\<Sum>v\<in>V. g (u,v))" apply (subst sum_outgoing_pointwise) apply (rule sum.mono_neutral_left) using assms succ_ss_V by auto text \<open>When summation is done over something that satisfies the capacity constraint, e.g., a flow, the summation can be extended to all outgoing/incoming edges, as the additional edges must have zero capacity.\<close> (* TODO: Historical lemmas. Get rid of \<forall> quantifier. *) lemma (in Finite_Graph) sum_outgoing_alt: "\<lbrakk>\<forall>e. 0 \<le> g e \<and> g e \<le> c e\<rbrakk> \<Longrightarrow> \<forall>v \<in> V. (\<Sum>e \<in> outgoing v. g e) = (\<Sum>u \<in> V. g (v, u))" apply (rule ballI) apply (rule sum_outgoing_extend) apply clarsimp by (metis antisym zero_cap_simp) lemma (in Finite_Graph) sum_incoming_alt: "\<lbrakk>\<forall>e. 0 \<le> g e \<and> g e \<le> c e\<rbrakk> \<Longrightarrow> \<forall>v \<in> V. (\<Sum>e \<in> incoming v. g e) = (\<Sum>u \<in> V. g (u, v))" apply (rule ballI) apply (rule sum_incoming_extend) apply clarsimp by (metis antisym zero_cap_simp) subsubsection \<open>Finite Graphs\<close> lemma (in Graph) Finite_Graph_EI: "finite E \<Longrightarrow> Finite_Graph c" apply unfold_locales by (rule Efin_imp_Vfin) lemma (in Finite_Graph) adjacent_nodes_finite[simp, intro!]: "finite (adjacent_nodes u)" unfolding adjacent_nodes_def by (auto intro: finite_Image) subsubsection \<open>Paths\<close> named_theorems split_path_simps \<open>Simplification lemmas to split paths\<close> lemma transfer_path: \<comment> \<open>Transfer path to another graph\<close> assumes "set p\<inter>E \<subseteq> Graph.E c'" assumes "isPath u p v" shows "Graph.isPath c' u p v" using assms apply (induction u p v rule: isPath.induct) apply (auto simp: Graph.isPath.simps) done lemma isPath_head2: "isPath u (e#p) v \<Longrightarrow> (p = [] \<or> (p \<noteq> [] \<and> fst (hd p) = snd e))" by (metis Graph.isPath_head list.collapse) lemma isPath_tail: "isPath u (p@[e]) v \<longleftrightarrow> isPath u p (fst e) \<and> e \<in> E \<and> snd e = v" by (induction p) (auto simp: isPath_append isPath_head) lemma isPath_tail2: "isPath u (p@[e]) v \<Longrightarrow> (p = [] \<or> (p \<noteq> [] \<and> snd (last p) = fst e))" by (metis Graph.isPath_tail append_butlast_last_id) (* TODO: Really needed? *) lemma isPath_append_edge: "isPath v p v' \<Longrightarrow> (v',v'')\<in>E \<Longrightarrow> isPath v (p@[(v',v'')]) v''" by (auto simp: isPath_append) lemma isPath_edgeset: "\<lbrakk>isPath u p v; e \<in> set p\<rbrakk> \<Longrightarrow> e \<in> E" using E_def by (metis isPath_head isPath_append in_set_conv_decomp_first) lemma isPath_rtc: "isPath u p v \<Longrightarrow> (u, v) \<in> E\<^sup>*" proof (induction p arbitrary: u) case Nil thus ?case by auto next case (Cons e es) obtain u1 u2 where "e = (u1, u2)" apply (cases e) by auto then have "u = u1 \<and> isPath u2 es v \<and> (u1, u2) \<in> E" using isPath.simps(2) Cons.prems by auto then have "(u, u2) \<in> E" and "(u2, v) \<in> E\<^sup>*" using Cons.IH by auto thus ?case by auto qed lemma rtc_isPath: "(u, v) \<in> E\<^sup>* \<Longrightarrow> (\<exists>p. isPath u p v)" proof (induction rule: rtrancl.induct) case (rtrancl_refl a) have "isPath a [] a" by simp thus ?case by blast next case (rtrancl_into_rtrancl u u' v) then obtain p1 where "isPath u p1 u'" by blast moreover have "(u', v) \<in> E" using rtrancl_into_rtrancl.hyps(2) by simp ultimately have "isPath u (p1 @ [(u', v)]) v" using isPath_tail by simp thus ?case by blast qed lemma rtci_isPath: "(v, u) \<in> (E\<inverse>)\<^sup>* \<Longrightarrow> (\<exists>p. isPath u p v)" proof - assume "(v,u)\<in>(E\<inverse>)\<^sup>*" hence "(u,v)\<in>E\<^sup>*" by (rule rtrancl_converseD) thus ?thesis by (rule rtc_isPath) qed lemma isPath_ex_edge1: assumes "isPath u p v" assumes "(u1, v1) \<in> set p" assumes "u1 \<noteq> u" shows "\<exists>u2. (u2, u1) \<in> set p" proof - obtain w1 w2 where obt1: "p = w1 @ [(u1, v1)] @ w2" using assms(2) by (metis append_Cons append_Nil in_set_conv_decomp_first) then have "isPath u w1 u1" using assms(1) isPath_append by auto have "w1 \<noteq> []" proof (rule ccontr) assume "\<not> w1 \<noteq> []" then have "u = u1" using \<open>isPath u w1 u1\<close> by (metis isPath.simps(1)) thus "False" using assms(3) by blast qed then obtain e w1' where obt2:"w1 = w1' @ [e]" by (metis append_butlast_last_id) then obtain u2 where "e = (u2, u1)" using \<open>isPath u w1 u1\<close> isPath_tail by (metis prod.collapse) then have "p = w1' @ (u2, u1) # (u1, v1) # w2" using obt1 obt2 by auto thus ?thesis by auto qed lemma isPath_ex_edge2: assumes "isPath u p v" assumes "(u1, v1) \<in> set p" assumes "v1 \<noteq> v" shows "\<exists>v2. (v1, v2) \<in> set p" proof - obtain w1 w2 where obt1: "p = w1 @ [(u1, v1)] @ w2" using assms(2) by (metis append_Cons append_Nil in_set_conv_decomp_first) then have "isPath v1 w2 v" using assms(1) isPath_append by auto have "w2 \<noteq> []" proof (rule ccontr) assume "\<not> w2 \<noteq> []" then have "v = v1" using \<open>isPath v1 w2 v\<close> by (metis isPath.simps(1)) thus "False" using assms(3) by blast qed then obtain e w2' where obt2:"w2 = e # w2'" by (metis neq_Nil_conv) then obtain v2 where "e = (v1, v2)" using \<open>isPath v1 w2 v\<close> isPath_head by (metis prod.collapse) then have "p = w1 @ (u1, v1) # (v1, v2) # w2'" using obt1 obt2 by auto thus ?thesis by auto qed subsubsection \<open>Vertices of Paths\<close> lemma (in Graph) pathVertices_fwd_simps[simp]: "pathVertices_fwd s ([]) = [s]" "pathVertices_fwd s (e#p) = s#pathVertices_fwd (snd e) p" "pathVertices_fwd s (p@[e]) = pathVertices_fwd s p@[snd e]" "pathVertices_fwd s (p1@e#p2) = pathVertices_fwd s p1 @ pathVertices_fwd (snd e) p2" "s\<in>set (pathVertices_fwd s p)" by (auto simp: pathVertices_fwd_def) lemma pathVertices_alt: "p \<noteq> [] \<Longrightarrow> pathVertices u p = map fst p @ [snd (last p)]" by (induction p arbitrary: u) auto lemma pathVertices_singleton_iff[simp]: "pathVertices s p = [u] \<longleftrightarrow> (p=[] \<and> s=u)" apply (cases p rule: rev_cases) apply (auto simp: pathVertices_alt) done lemma length_pathVertices_eq[simp]: "length (pathVertices u p) = length p + 1" apply (cases "p=[]") apply (auto simp: pathVertices_alt) done lemma pathVertices_edgeset: "\<lbrakk>u\<in>V; isPath u p v\<rbrakk> \<Longrightarrow> set (pathVertices u p) \<subseteq> V" apply (cases p rule: rev_cases; simp) using isPath_edgeset[of u p v] apply (fastforce simp: pathVertices_alt V_def) done lemma pathVertices_append: "pathVertices u (p1 @ p2) = butlast (pathVertices u p1) @ pathVertices (last (pathVertices u p1)) p2" proof (induction p1 arbitrary: u) case Nil thus ?case by auto next case (Cons e es) have "pathVertices u ((e # es) @ p2) = fst e # pathVertices (snd e) (es @ p2)" by (metis Graph.pathVertices.simps(2) append_Cons) moreover have "pathVertices (snd e) (es @ p2) = butlast (pathVertices (snd e) es) @ pathVertices (last (pathVertices (snd e) es)) p2" using Cons.IH by auto moreover have "fst e # butlast (pathVertices (snd e) es) = butlast (fst e # pathVertices (snd e) es)" by (metis Graph.pathVertices.simps(1) Graph.pathVertices_alt Nil_is_append_conv butlast.simps(2) list.distinct(1)) moreover have "fst e # pathVertices (snd e) es = pathVertices u (e # es)" by (metis Graph.pathVertices.simps(2)) moreover have "last (pathVertices (snd e) es) = last (pathVertices u (e # es))" by (metis Graph.pathVertices.simps(1) Graph.pathVertices_alt last.simps last_snoc list.distinct(1)) ultimately show ?case by (metis append_Cons) qed lemma split_path_at_vertex: assumes "u\<in>set (pathVertices_fwd s p)" assumes "isPath s p t" obtains p1 p2 where "p=p1@p2" "isPath s p1 u" "isPath u p2 t" using assms apply - (*unfolding pathVertices_fwd*) unfolding pathVertices_fwd_def apply (auto simp: in_set_conv_decomp isPath_append) apply force by (metis Graph.isPath_append_edge append_Cons append_Nil append_assoc) lemma split_path_at_vertex_complete: assumes "isPath s p t" "pathVertices_fwd s p = pv1@u#pv2" obtains p1 p2 where "p=p1@p2" "isPath s p1 u" "pathVertices_fwd s p1 = pv1@[u]" "isPath u p2 t" "pathVertices_fwd u p2 = u#pv2" proof - from assms have PV: "pathVertices s p = pv1@u#pv2" by (simp add: pathVertices_fwd) then obtain p1 p2 where "p=p1@p2" "isPath s p1 u" "pathVertices s p1 = pv1@[u]" "isPath u p2 t" "pathVertices u p2 = u#pv2" proof - show thesis using assms(1) PV apply (cases p rule: rev_cases; clarsimp simp: pathVertices_alt) apply (rule that[of "[]" "[]"]; simp add: Cons_eq_append_conv) apply (cases pv2; clarsimp) apply (rule that[of p "[]"]; auto simp add: isPath_append pathVertices_alt ) apply (clarsimp simp: append_eq_append_conv2; auto elim!: map_eq_appendE append_eq_Cons_conv[THEN iffD1, elim_format] simp: isPath_append) subgoal for \<dots> l apply (erule that) apply auto [4] apply (case_tac l rule: rev_cases; auto simp add: pathVertices_alt isPath_append) done subgoal for \<dots> l apply (erule that) apply auto [4] apply (case_tac l rule: rev_cases; auto simp add: pathVertices_alt isPath_append) done subgoal for \<dots> l u1 u2 u3 apply (erule that) apply auto [4] apply (case_tac l rule: rev_cases; auto simp add: pathVertices_alt isPath_append) apply (auto simp: isPath_append) [] apply (auto simp: pathVertices_alt) [] done apply (erule that) apply(auto simp add: Cons_eq_append_conv) [4] subgoal for \<dots> l by (case_tac l rule: rev_cases; auto simp add: pathVertices_alt isPath_append) done qed thus ?thesis apply - unfolding pathVertices_fwd using that . qed lemma isPath_fwd_cases: assumes "isPath s p t" obtains "p=[]" "t=s" | p' u where "p=(s,u)#p'" "(s,u)\<in>E" "isPath u p' t" using assms by (cases p) (auto) lemma isPath_bwd_cases: assumes "isPath s p t" obtains "p=[]" "t=s" | p' u where "p=p'@[(u,t)]" "isPath s p' u" "(u,t)\<in>E" using assms by (cases p rule: rev_cases) (auto simp: split_path_simps) lemma pathVertices_edge: "isPath s p t \<Longrightarrow> e \<in> set p \<Longrightarrow> \<exists>vs1 vs2. pathVertices_fwd s p = vs1 @ fst e # snd e # vs2" apply (cases e) apply (auto simp: in_set_conv_decomp split_path_simps) apply (erule isPath_bwd_cases[where s=s]; auto) apply (erule isPath_fwd_cases[where t=t]; auto) apply (erule isPath_fwd_cases[where t=t]; auto) done (* TODO: Really needed? *) lemma pathVertices_edge_old: "isPath u p v \<Longrightarrow> e \<in> set p \<Longrightarrow> \<exists>vs1 vs2. pathVertices u p = vs1 @ fst e # snd e # vs2" unfolding pathVertices_fwd by (rule pathVertices_edge) subsubsection \<open>Reachability\<close> lemma connected_refl[simp, intro!]: "connected v v" unfolding connected_def by (force intro: exI[where x="[]"]) lemma connected_append_edge: "connected u v \<Longrightarrow> (v,w)\<in>E \<Longrightarrow> connected u w" unfolding connected_def by (auto intro: isPath_append_edge) lemma connected_inV_iff: "\<lbrakk>connected u v\<rbrakk> \<Longrightarrow> v\<in>V \<longleftrightarrow> u\<in>V" apply (auto simp: connected_def) apply (case_tac p; auto simp: V_def) [] apply (case_tac p rule: rev_cases; auto simp: isPath_append V_def) [] done lemma connected_edgeRtc: "connected u v \<longleftrightarrow> (u, v) \<in> E\<^sup>*" using isPath_rtc rtc_isPath unfolding connected_def by blast lemma reachable_ss_V: "s \<in> V \<Longrightarrow> reachableNodes s \<subseteq> V" proof assume asm: "s \<in> V" fix x assume "x \<in> reachableNodes s" then obtain p where "x \<in> {v. isPath s p v}" unfolding reachableNodes_def connected_def by blast thus "x \<in> V" using asm by (induction p arbitrary: s) (auto simp: isPath_head V_alt) qed lemma reachableNodes_E_closed: "E``reachableNodes s \<subseteq> reachableNodes s" unfolding reachableNodes_def by (auto intro: connected_append_edge) corollary reachableNodes_append_edge: "u\<in>reachableNodes s \<Longrightarrow> (u,v)\<in>E \<Longrightarrow> v\<in>reachableNodes s" using reachableNodes_E_closed by blast subsubsection \<open>Simple Paths\<close> lemma isSimplePath_singelton[split_path_simps]: "isSimplePath u [e] v \<longleftrightarrow> (e=(u,v) \<and> u\<noteq>v \<and> (u,v)\<in>E)" by (auto simp: isSimplePath_def isPath_head) lemma (in Graph) isSimplePath_append[split_path_simps]: "isSimplePath s (p1@p2) t \<longleftrightarrow> (\<exists>u. isSimplePath s p1 u \<and> isSimplePath u p2 t \<and> set (pathVertices_fwd s p1) \<inter> set (pathVertices_fwd u p2) = {u})" (is "_ \<longleftrightarrow> ?R") unfolding isSimplePath_fwd apply (cases p1 rule: rev_cases; simp; cases p2; simp) by (auto simp: split_path_simps) lemma (in Graph) isSimplePath_cons[split_path_simps]: "isSimplePath s (e#p) t \<longleftrightarrow> (\<exists>u. e=(s,u) \<and> s\<noteq>u \<and> (s,u)\<in>E \<and> isSimplePath u p t \<and> s\<notin>set (pathVertices_fwd u p))" using isSimplePath_append[of s "[e]" p t, simplified] by (auto simp: split_path_simps) lemma (in Finite_Graph) simplePath_length_less_V: assumes UIV: "u\<in>V" assumes P: "isSimplePath u p v" shows "length p < card V" proof - from P have 1: "isPath u p v" and 2: "distinct (pathVertices u p)" by (auto simp: isSimplePath_def) from pathVertices_edgeset[OF UIV 1] have "set (pathVertices u p) \<subseteq> V" . with 2 finite_V have "length (pathVertices u p) \<le> card V" using distinct_card card_mono by metis hence "length p + 1 \<le> card V" by simp thus ?thesis by auto qed lemma split_simple_path: "isSimplePath u (p1@p2) v \<Longrightarrow> (\<exists>w. isSimplePath u p1 w \<and> isSimplePath w p2 v)" apply (auto simp: isSimplePath_def isPath_append) apply (rule exI; intro conjI; assumption?) apply (cases p1 rule: rev_cases) [] apply simp apply (cases p2) apply simp apply (clarsimp simp: pathVertices_alt isPath_append) apply (cases p1 rule: rev_cases) [] apply simp apply (cases p2 rule: rev_cases) apply simp apply (clarsimp simp: pathVertices_alt isPath_append) done lemma simplePath_empty_conv[simp]: "isSimplePath s [] t \<longleftrightarrow> s=t" by (auto simp: isSimplePath_def) lemma simplePath_same_conv[simp]: "isSimplePath s p s \<longleftrightarrow> p=[]" apply rule apply (cases p; simp) apply (rename_tac e pp) apply (case_tac pp rule: rev_cases; simp) apply (auto simp: isSimplePath_def pathVertices_alt isPath_append) [2] apply simp done lemma isSPath_pathLE: "isPath s p t \<Longrightarrow> \<exists>p'. isSimplePath s p' t" proof (induction p rule: length_induct) case (1 p) hence IH: "\<And>p'. \<lbrakk>length p' < length p; isPath s p' t\<rbrakk> \<Longrightarrow> \<exists>p'. isSimplePath s p' t" and PATH: "isPath s p t" by auto show "\<exists>p. isSimplePath s p t" proof cases assume "distinct (pathVertices_fwd s p)" thus ?thesis using PATH by (auto simp: isSimplePath_fwd) next assume "\<not>(distinct (pathVertices_fwd s p))" then obtain pv1 pv2 pv3 u where "pathVertices_fwd s p = pv1@u#pv2@u#pv3" by (auto dest: not_distinct_decomp) then obtain p1 p2 p3 where "p = p1@p2@p3" "p2\<noteq>[]" "isPath s p1 u" "isPath u p3 t" using PATH apply - apply (erule (1) split_path_at_vertex_complete[where s=s]; simp) apply (erule split_path_at_vertex_complete[of _ _ t "u#pv2" u pv3]; simp) apply (auto intro: that) done hence "length (p1@p3) < length p" "isPath s (p1@p3) t" by (auto simp: split_path_simps) thus ?case by (rule IH) qed qed lemma isSPath_no_selfloop: "isSimplePath u p v \<Longrightarrow> (u1, u1) \<notin> set p" apply (rule ccontr) apply (auto simp: in_set_conv_decomp split_path_simps) done lemma isSPath_sg_outgoing: "\<lbrakk>isSimplePath u p v; (u1, v1) \<in> set p; v1 \<noteq> v2\<rbrakk> \<Longrightarrow> (u1, v2) \<notin> set p" by (auto simp: in_set_conv_decomp isSimplePath_def pathVertices_alt append_eq_append_conv2 Cons_eq_append_conv append_eq_Cons_conv) lemma isSPath_sg_incoming: "\<lbrakk>isSimplePath u p v; (u1, v1) \<in> set p; u1 \<noteq> u2\<rbrakk> \<Longrightarrow> (u2, v1) \<notin> set p" by (auto simp: in_set_conv_decomp isSimplePath_fwd pathVertices_fwd_def append_eq_append_conv2 append_eq_Cons_conv Cons_eq_append_conv) lemma isSPath_nt_parallel: assumes SP: "isSimplePath s p t" assumes EIP: "e\<in>set p" shows "prod.swap e \<notin> set p" proof - from SP have P: "isPath s p t" and D: "distinct (pathVertices_fwd s p)" by (auto simp: isSimplePath_fwd) show "prod.swap e \<notin> set p" apply (cases e) using D EIP by(auto dest!: pathVertices_edge[OF P] simp add: append_eq_append_conv2 Cons_eq_append_conv append_eq_Cons_conv) qed lemma isSPath_nt_parallel_old: "isSimplePath u p v \<Longrightarrow> (\<forall>(u, v) \<in> set p. (v, u) \<notin> set p)" using isSPath_nt_parallel[of u p v] by auto corollary isSPath_nt_parallel_pf: "isSimplePath s p t \<Longrightarrow> set p \<inter> (set p)\<inverse> = {}" by (auto dest: isSPath_nt_parallel) lemma isSPath_distinct: "isSimplePath u p v \<Longrightarrow> distinct p" apply (rule ccontr) apply (auto dest!: not_distinct_decomp simp: split_path_simps) done text \<open>Edges adjacent to a node that does not lie on a path are not contained in that path:\<close> corollary assumes "isPath s p t" assumes "v\<notin>set (pathVertices_fwd s p)" shows incoming_edges_not_on_path: "incoming v \<inter> set p = {}" and outgoing_edges_not_on_path: "outgoing v \<inter> set p = {}" using adjacent_edges_not_on_path[OF assms] unfolding adjacent_def by auto text \<open>A simple path over a vertex can be split at this vertex, and there are exactly two edges on the path touching this vertex.\<close> lemma adjacent_edges_on_simple_path: assumes SPATH: "isSimplePath s p t" assumes VNV: "v\<in>set (pathVertices_fwd s p)" "v\<noteq>s" "v\<noteq>t" obtains p1 u w p2 where "p = p1@(u,v)#(v,w)#p2" "incoming v \<inter> set p = {(u,v)}" "outgoing v \<inter> set p = {(v,w)}" proof - from SPATH have PATH: "isPath s p t" and DIST: "distinct (pathVertices_fwd s p)" by (auto simp: isSimplePath_def pathVertices_fwd) from split_path_at_vertex[OF VNV(1) PATH] obtain p1 p2 where [simp]: "p=p1@p2" and P1: "isPath s p1 v" and P2: "isPath v p2 t" . from \<open>v\<noteq>s\<close> P1 obtain p1' u where [simp]: "p1=p1'@[(u,v)]" and P1': "isPath s p1' u" and UV: "(u,v)\<in>E" by (cases p1 rule: rev_cases) (auto simp: split_path_simps) from \<open>v\<noteq>t\<close> P2 obtain w p2' where [simp]: "p2=(v,w)#p2'" and VW: "(v,w)\<in>E" and P2': "isPath w p2' t" by (cases p2) (auto) show thesis apply (rule that[of p1' u w p2']) apply simp using isSPath_sg_outgoing[OF SPATH, of v w] isSPath_sg_incoming[OF SPATH, of u v] isPath_edgeset[OF PATH] apply (fastforce simp: incoming_def outgoing_def)+ done qed subsubsection \<open>Distance\<close> lemma connected_by_dist: "connected v v' = (\<exists>d. dist v d v')" by (auto simp: dist_def connected_def) lemma isPath_distD: "isPath u p v \<Longrightarrow> dist u (length p) v" by (auto simp: dist_def) lemma shows connected_distI[intro]: "dist v d v' \<Longrightarrow> connected v v'" (*and connectedI_succ: "connected v v' \<Longrightarrow> (v',v'') \<in> E \<Longrightarrow> connected v v''"*) by (auto simp: dist_def connected_def intro: isPath_append_edge) lemma min_distI2: "\<lbrakk>connected v v'; \<And>d. \<lbrakk>dist v d v'; \<And>d'. dist v d' v' \<Longrightarrow> d \<le> d'\<rbrakk> \<Longrightarrow> Q d\<rbrakk> \<Longrightarrow> Q (min_dist v v')" unfolding min_dist_def apply (rule LeastI2_wellorder[where Q=Q and a="SOME d. dist v d v'"]) apply (auto simp: connected_by_dist intro: someI) done lemma min_distI_eq: "\<lbrakk> dist v d v'; \<And>d'. dist v d' v' \<Longrightarrow> d \<le> d' \<rbrakk> \<Longrightarrow> min_dist v v' = d" by (force intro: min_distI2 simp: connected_by_dist) text \<open>Two nodes are connected by a path of length \<open>0\<close>, iff they are equal.\<close> lemma dist_z_iff[simp]: "dist v 0 v' \<longleftrightarrow> v'=v" by (auto simp: dist_def) lemma dist_z[simp, intro!]: "dist v 0 v" by simp lemma dist_suc: "\<lbrakk>dist v d v'; (v',v'')\<in>E\<rbrakk> \<Longrightarrow> dist v (Suc d) v''" by (auto simp: dist_def intro: isPath_append_edge) lemma dist_cases[case_names dist_z dist_suc, consumes 1, cases pred]: assumes "dist v d v'" obtains "v=v'" "d=0" | vh dd where "d=Suc dd" "dist v dd vh" "(vh,v')\<in>E" using assms apply (cases d; clarsimp simp add: dist_def) subgoal for \<dots> p by(cases p rule: rev_cases)(fastforce simp add: isPath_append)+ done text \<open>The same holds for \<open>min_dist\<close>, i.e., the shortest path between two nodes has length \<open>0\<close>, iff these nodes are equal.\<close> lemma min_dist_z[simp]: "min_dist v v = 0" by (rule min_distI2) auto text \<open>We also provide introduction and destruction rules for the pattern \<open>min_dist v v' = Suc d\<close>. \<close> lemma min_dist_succ: "\<lbrakk> connected v v'; (v',v'') \<in> E \<rbrakk> \<Longrightarrow> min_dist v v'' \<le> Suc (min_dist v v') " apply (rule min_distI2[where v'=v']) apply (auto intro!: min_dist_minD intro: dist_suc) done lemma min_dist_suc: assumes c: "connected v v'" "min_dist v v' = Suc d" shows "\<exists>v''. connected v v'' \<and> (v'',v') \<in> E \<and> min_dist v v'' = d" proof - from min_dist_is_dist[OF c(1)] have "min_dist v v' = Suc d \<longrightarrow> ?thesis" proof cases case (dist_suc v'' d') then show ?thesis using min_dist_succ[of v v'' v'] min_dist_minD[of v d v''] by (auto simp: connected_distI) qed simp with c show ?thesis by simp qed text \<open> If there is a node with a shortest path of length \<open>d\<close>, then, for any \<open>d'<d\<close>, there is also a node with a shortest path of length \<open>d'\<close>. \<close> lemma min_dist_less: assumes "connected src v" "min_dist src v = d" and "d' < d" shows "\<exists>v'. connected src v' \<and> min_dist src v' = d'" using assms proof (induct d arbitrary: v) case (Suc d) with min_dist_suc[of src v] show ?case by (cases "d' = d") auto qed auto text \<open> Lemma \<open>min_dist_less\<close> can be weakened to \<open>d'\<le>d\<close>. \<close> corollary min_dist_le: assumes c: "connected src v" and d': "d' \<le> min_dist src v" shows "\<exists>v'. connected src v' \<and> min_dist src v' = d'" using min_dist_less[OF c, of "min_dist src v" d'] d' c by (auto simp: le_less) lemma dist_trans[trans]: "dist u d1 w \<Longrightarrow> dist w d2 v \<Longrightarrow> dist u (d1+d2) v" apply (clarsimp simp: dist_def) apply (rename_tac p1 p2) apply (rule_tac x="p1@p2" in exI) by (auto simp: isPath_append) lemma min_dist_split: assumes D1: "dist u d1 w" and D2: "dist w d2 v" and MIN: "min_dist u v = d1+d2" shows "min_dist u w = d1" "min_dist w v = d2" apply (metis assms ab_semigroup_add_class.add.commute add_le_cancel_left dist_trans min_distI_eq min_dist_minD) by (metis assms add_le_cancel_left dist_trans min_distI_eq min_dist_minD) lemma \<comment> \<open>Manual proof\<close> assumes D1: "dist u d1 w" and D2: "dist w d2 v" and MIN: "min_dist u v = d1+d2" shows "min_dist u w = d1" "min_dist w v = d2" proof - from min_dist_minD[OF \<open>dist u d1 w\<close>] have "min_dist u w \<le> d1" . moreover { have "dist u (min_dist u w) w" apply (rule min_dist_is_dist) using D1 by auto also note D2 finally have "dist u (min_dist u w + d2) v" . moreover assume "min_dist u w < d1" moreover note MIN ultimately have False by (auto dest: min_dist_minD) } ultimately show "min_dist u w = d1" unfolding not_less[symmetric] using nat_neq_iff by blast from min_dist_minD[OF \<open>dist w d2 v\<close>] have "min_dist w v \<le> d2" . moreover { note D1 also have "dist w (min_dist w v) v" apply (rule min_dist_is_dist) using D2 by auto finally have "dist u (d1 + min_dist w v) v" . moreover assume "min_dist w v < d2" moreover note MIN ultimately have False by (auto dest: min_dist_minD) } ultimately show "min_dist w v = d2" unfolding not_less[symmetric] using nat_neq_iff by blast qed subsubsection \<open>Shortest Paths\<close> text \<open>Characterization of shortest path in terms of minimum distance\<close> lemma isShortestPath_min_dist_def: "isShortestPath u p v \<longleftrightarrow> isPath u p v \<and> length p = min_dist u v" unfolding isShortestPath_def min_dist_def dist_def apply (rule iffI; clarsimp) apply (rule Least_equality[symmetric]; auto; fail) apply (rule Least_le; auto; fail) done lemma obtain_shortest_path: assumes CONN: "connected u v" obtains p where "isShortestPath u p v" using min_dist_is_dist[OF CONN] unfolding dist_def isShortestPath_min_dist_def by blast lemma shortestPath_is_simple: assumes "isShortestPath s p t" shows "isSimplePath s p t" proof (rule ccontr) from assms have PATH: "isPath s p t" and SHORTEST: "\<forall>p'. isPath s p' t \<longrightarrow> length p \<le> length p'" by (auto simp: isShortestPath_def) assume "\<not>isSimplePath s p t" with PATH have "\<not>distinct (pathVertices_fwd s p)" by (auto simp: isSimplePath_fwd) then obtain pv1 u pv2 pv3 where PV: "pathVertices_fwd s p = pv1@u#pv2@u#pv3" by (auto dest: not_distinct_decomp) from split_path_at_vertex_complete[OF PATH PV] obtain p1 p23 where [simp]: "p=p1@p23" and P1: "isPath s p1 u" "pathVertices_fwd s p1 = pv1@[u]" and P23: "isPath u p23 t" "pathVertices_fwd u p23 = (u#pv2)@u#pv3" by auto from split_path_at_vertex_complete[OF P23] obtain p2 p3 where [simp]: "p23 = p2@p3" and P2: "isPath u p2 u" "pathVertices_fwd u p2 = u#pv2@[u]" and P3: "isPath u p3 t" "pathVertices_fwd u p3 = u#pv3" by auto from P1(1) P3(1) have SHORTER_PATH: "isPath s (p1@p3) t" by (auto simp: isPath_append) from P2 have "p2\<noteq>[]" by auto hence LESS: "length (p1@p3) < length p" by auto with SHORTER_PATH SHORTEST show False by auto qed text \<open>We provide yet another characterization of shortest paths:\<close> lemma isShortestPath_alt: "isShortestPath u p v \<longleftrightarrow> isSimplePath u p v \<and> length p = min_dist u v" using shortestPath_is_simple isShortestPath_min_dist_def unfolding isSimplePath_def by auto lemma shortestPath_is_path: "isShortestPath u p v \<Longrightarrow> isPath u p v" by (auto simp: isShortestPath_def) lemma split_shortest_path: "isShortestPath u (p1@p2) v \<Longrightarrow> (\<exists>w. isShortestPath u p1 w \<and> isShortestPath w p2 v)" apply (auto simp: isShortestPath_min_dist_def isPath_append) apply (rule exI; intro conjI; assumption?) apply (drule isPath_distD)+ using min_dist_split apply auto [] apply (drule isPath_distD)+ using min_dist_split apply auto [] done text \<open>Edges in a shortest path connect nodes with increasing minimum distance from the source\<close> lemma isShortestPath_level_edge: assumes SP: "isShortestPath s p t" assumes EIP: "(u,v)\<in>set p" shows "connected s u" "connected u v" "connected v t" and "min_dist s v = min_dist s u + 1" (is ?G1) and "min_dist u t = 1 + min_dist v t" (is ?G2) and "min_dist s t = min_dist s u + 1 + min_dist v t" (is ?G3) proof - \<comment> \<open>Split the original path at the edge\<close> from EIP obtain p1 p2 where [simp]: "p=p1@(u,v)#p2" by (auto simp: in_set_conv_decomp) from \<open>isShortestPath s p t\<close> have MIN: "min_dist s t = length p" and P: "isPath s p t" and DV: "distinct (pathVertices s p)" by (auto simp: isShortestPath_alt isSimplePath_def) from P have DISTS: "dist s (length p1) u" "dist u 1 v" "dist v (length p2) t" by (auto simp: isPath_append dist_def intro: exI[where x="[(u,v)]"]) from DISTS show "connected s u" "connected u v" "connected v t" by auto \<comment> \<open>Express the minimum distances in terms of the split original path\<close> from MIN have MIN': "min_dist s t = length p1 + 1 + length p2" by auto from min_dist_split[OF dist_trans[OF DISTS(1,2)] DISTS(3) MIN'] have MDSV: "min_dist s v = length p1 + 1" and [simp]: "length p2 = min_dist v t" by simp_all from min_dist_split[OF DISTS(1) dist_trans[OF DISTS(2,3)]] MIN' have MDUT: "min_dist u t = 1 + length p2" and [simp]: "length p1 = min_dist s u" by simp_all from MDSV MDUT MIN' show ?G1 ?G2 ?G3 by auto qed end \<comment> \<open>Graph\<close> context Finite_Graph begin text \<open>In a finite graph, the length of a shortest path is less than the number of nodes\<close> lemma isShortestPath_length_less_V: assumes SV: "s\<in>V" assumes PATH: "isShortestPath s p t" shows "length p < card V" using simplePath_length_less_V[OF SV] using shortestPath_is_simple[OF PATH] . corollary min_dist_less_V: assumes SV: "s\<in>V" assumes CONN: "connected s t" shows "min_dist s t < card V" apply (rule obtain_shortest_path[OF CONN]) apply (frule isShortestPath_length_less_V[OF SV]) unfolding isShortestPath_min_dist_def by auto end \<comment> \<open>Finite_Graph\<close> end \<comment> \<open>Theory\<close>
# 'Facebook reactions' v1.0 node for IBM SPSS Modeler # Based on the package 'Rfacebook' created by Pablo Barbera available on http://cran.r-project.org/web/packages/Rfacebook/ # Jonathan Langefeld - IBM 2016 # Description: Get posts from a public facebook page directly in SPSS Modeler with this easy-to-use node. # This is not a proper 'source' node: please read the documentation to know how to use it. # Installing and/or loading the required R packages. packages <- function(x) { x <- as.character(match.call()[[2]]) if (!require(x,character.only=TRUE)){ install.packages(pkgs=x,repos="http://cran.r-project.org") require(x,character.only=TRUE) } } packages(Rfacebook) # Getting user specified values token <- "%%token%%" posts <- modelerData$%%posts%% # Load reactions from Facebook Graph API reactions = getReactions(post=posts, token=token, verbose = FALSE) reactions$id = NULL # Add new fields to Stream modelerData <- cbind(modelerData, reactions) var1<-c(fieldName="likes_count",fieldLabel="",fieldStorage="integer",fieldMeasure="",fieldFormat="",fieldRole="") var2<-c(fieldName="love_count",fieldLabel="",fieldStorage="integer",fieldMeasure="",fieldFormat="",fieldRole="") var3<-c(fieldName="haha_count",fieldLabel="",fieldStorage="integer",fieldMeasure="",fieldFormat="",fieldRole="") var4<-c(fieldName="wow_count",fieldLabel="",fieldStorage="integer",fieldMeasure="",fieldFormat="",fieldRole="") var5<-c(fieldName="sad_count",fieldLabel="",fieldStorage="integer",fieldMeasure="",fieldFormat="",fieldRole="") var6<-c(fieldName="angry_count",fieldLabel="",fieldStorage="integer",fieldMeasure="",fieldFormat="",fieldRole="") modelerDataModel <- data.frame(modelerDataModel, var1,var2,var3,var4,var5,var6)
example : Prop := ∀ n, (n:Nat) + n = n.succ example : Prop := ∀ n, n.succ = (n:Nat) + n example : Prop := ∀ n, (n:Nat) + n.succ = n example : Prop := ∀ n, n.succ + (n:Nat) = n example : Prop := ∀ n, (n.succ:Nat) + n = n example : Prop := ∀ n, (n:Nat).succ + n = n def fib: Nat → Nat | 0 => 0 | 1 => 1 | n + 2 => fib n + fib (n + 1) theorem fib50Eq : fib 50 = 12586269025 := rfl inductive type : Type | A : type | B : type inductive val : type → Type | cA : val type.A | cB : val type.B inductive wrap : Type | val : ∀ {t : type}, (val t) → wrap def f : wrap → Nat | wrap.val val.cA => 1 | _ => 1 example (a : Nat) : True := by have : ∀ n, n ≥ 0 → a ≤ a := fun _ _ => Nat.le_refl .. exact True.intro example (ᾰ : Nat) : True := by have : ∀ n, n ≥ 0 → ᾰ ≤ ᾰ := fun _ _ => Nat.le_refl .. exact True.intro inductive Vec.{u} (α : Type u) : Nat → Type u | nil : Vec α 0 | cons : α → {n : Nat} → Vec α n → Vec α (Nat.succ n) -- TODO: investigate why +1 doesn't work here constant Vars : Type structure Lang := (funcs : Nat → Type) (consts : Type) inductive Term (L : Lang) : Type | const_term : L.consts → Term L | var_term : Vars → Term L | func_term (n : Nat) (f : L.funcs n) (v : Vec (Term L) n) : Term L
The Fastra II is a desktop supercomputer designed for tomography . It was built in late 2009 by the ASTRA ( All Scale <unk> Reconstruction Antwerp ) group of researchers of the <unk> ( Interdisciplinary institute for <unk> Technology ) <unk> at the University of Antwerp and by Belgian computer shop Tones , in collaboration with Asus , a Taiwanese multinational computer product manufacturer , as the successor to the Fastra I ( built in 2008 ) .
import Data.List.Views total equalSuffix : Eq a => List a -> List a -> List a equalSuffix xs ys with (snocList xs) equalSuffix [] ys | Empty = [] equalSuffix (zs ++ [x]) ys | (Snoc rec) with (snocList ys) equalSuffix (xs' ++ [x]) [] | (Snoc rec) | Empty = [] equalSuffix (xs' ++ [x]) (ys' ++ [y]) | (Snoc rec_xs) | (Snoc rec_ys) = if x == y then (equalSuffix xs' ys' | rec_xs | rec_ys) ++ [x] else []
import numpy as np import torch def extract_feature(model, loader, gpu_device): """ Extract embeddings from given `model` for given `loader` dataset on `gpu_device`. """ model.eval() all_embeddings = [] all_labels = [] log_every_n_step = 10 with torch.no_grad(): for i, (im, class_label, instance_label, index) in enumerate(loader): im = im.to(device=gpu_device) embedding = model(im) all_embeddings.append(embedding.cpu().numpy()) all_labels.extend(instance_label.tolist()) if (i + 1) % log_every_n_step == 0: print('Process Iteration {} / {}:'.format(i, len(loader))) all_embeddings = np.vstack(all_embeddings) print("Generated {} embedding matrix".format(all_embeddings.shape)) print("Generate {} labels".format(len(all_labels))) model.train() return all_embeddings, all_labels
------------------------------------------------------------------------ -- Pointwise products of binary relations ------------------------------------------------------------------------ module Relation.Binary.Product.Pointwise where open import Data.Function open import Data.Product open import Data.Sum open import Relation.Nullary.Product open import Relation.Binary private module Dummy {a₁ a₂ : Set} where infixr 2 _×-Rel_ _×-Rel_ : Rel a₁ → Rel a₂ → Rel (a₁ × a₂) ∼₁ ×-Rel ∼₂ = (∼₁ on₁ proj₁) -×- (∼₂ on₁ proj₂) -- Some properties which are preserved by ×-Rel (under certain -- assumptions). _×-reflexive_ : ∀ {≈₁ ∼₁ ≈₂ ∼₂} → ≈₁ ⇒ ∼₁ → ≈₂ ⇒ ∼₂ → (≈₁ ×-Rel ≈₂) ⇒ (∼₁ ×-Rel ∼₂) refl₁ ×-reflexive refl₂ = λ x≈y → (refl₁ (proj₁ x≈y) , refl₂ (proj₂ x≈y)) _×-refl_ : ∀ {∼₁ ∼₂} → Reflexive ∼₁ → Reflexive ∼₂ → Reflexive (∼₁ ×-Rel ∼₂) refl₁ ×-refl refl₂ = (refl₁ , refl₂) ×-irreflexive₁ : ∀ {≈₁ <₁ ≈₂ <₂} → Irreflexive ≈₁ <₁ → Irreflexive (≈₁ ×-Rel ≈₂) (<₁ ×-Rel <₂) ×-irreflexive₁ ir = λ x≈y x<y → ir (proj₁ x≈y) (proj₁ x<y) ×-irreflexive₂ : ∀ {≈₁ <₁ ≈₂ <₂} → Irreflexive ≈₂ <₂ → Irreflexive (≈₁ ×-Rel ≈₂) (<₁ ×-Rel <₂) ×-irreflexive₂ ir = λ x≈y x<y → ir (proj₂ x≈y) (proj₂ x<y) _×-symmetric_ : ∀ {∼₁ ∼₂} → Symmetric ∼₁ → Symmetric ∼₂ → Symmetric (∼₁ ×-Rel ∼₂) sym₁ ×-symmetric sym₂ = λ x∼y → sym₁ (proj₁ x∼y) , sym₂ (proj₂ x∼y) _×-transitive_ : ∀ {∼₁ ∼₂} → Transitive ∼₁ → Transitive ∼₂ → Transitive (∼₁ ×-Rel ∼₂) trans₁ ×-transitive trans₂ = λ x∼y y∼z → trans₁ (proj₁ x∼y) (proj₁ y∼z) , trans₂ (proj₂ x∼y) (proj₂ y∼z) _×-antisymmetric_ : ∀ {≈₁ ≤₁ ≈₂ ≤₂} → Antisymmetric ≈₁ ≤₁ → Antisymmetric ≈₂ ≤₂ → Antisymmetric (≈₁ ×-Rel ≈₂) (≤₁ ×-Rel ≤₂) antisym₁ ×-antisymmetric antisym₂ = λ x≤y y≤x → ( antisym₁ (proj₁ x≤y) (proj₁ y≤x) , antisym₂ (proj₂ x≤y) (proj₂ y≤x) ) ×-asymmetric₁ : ∀ {<₁ ∼₂} → Asymmetric <₁ → Asymmetric (<₁ ×-Rel ∼₂) ×-asymmetric₁ asym₁ = λ x<y y<x → asym₁ (proj₁ x<y) (proj₁ y<x) ×-asymmetric₂ : ∀ {∼₁ <₂} → Asymmetric <₂ → Asymmetric (∼₁ ×-Rel <₂) ×-asymmetric₂ asym₂ = λ x<y y<x → asym₂ (proj₂ x<y) (proj₂ y<x) _×-≈-respects₂_ : ∀ {≈₁ ∼₁ ≈₂ ∼₂} → ∼₁ Respects₂ ≈₁ → ∼₂ Respects₂ ≈₂ → (∼₁ ×-Rel ∼₂) Respects₂ (≈₁ ×-Rel ≈₂) _×-≈-respects₂_ {≈₁ = ≈₁} {∼₁ = ∼₁} {≈₂ = ≈₂} {∼₂ = ∼₂} resp₁ resp₂ = (λ {x y z} → resp¹ {x} {y} {z}) , (λ {x y z} → resp² {x} {y} {z}) where ∼ = ∼₁ ×-Rel ∼₂ resp¹ : ∀ {x} → (∼ x) Respects (≈₁ ×-Rel ≈₂) resp¹ y≈y' x∼y = proj₁ resp₁ (proj₁ y≈y') (proj₁ x∼y) , proj₁ resp₂ (proj₂ y≈y') (proj₂ x∼y) resp² : ∀ {y} → (flip₁ ∼ y) Respects (≈₁ ×-Rel ≈₂) resp² x≈x' x∼y = proj₂ resp₁ (proj₁ x≈x') (proj₁ x∼y) , proj₂ resp₂ (proj₂ x≈x') (proj₂ x∼y) ×-total : ∀ {∼₁ ∼₂} → Symmetric ∼₁ → Total ∼₁ → Total ∼₂ → Total (∼₁ ×-Rel ∼₂) ×-total {∼₁ = ∼₁} {∼₂ = ∼₂} sym₁ total₁ total₂ = total where total : Total (∼₁ ×-Rel ∼₂) total x y with total₁ (proj₁ x) (proj₁ y) | total₂ (proj₂ x) (proj₂ y) ... | inj₁ x₁∼y₁ | inj₁ x₂∼y₂ = inj₁ ( x₁∼y₁ , x₂∼y₂) ... | inj₁ x₁∼y₁ | inj₂ y₂∼x₂ = inj₂ (sym₁ x₁∼y₁ , y₂∼x₂) ... | inj₂ y₁∼x₁ | inj₂ y₂∼x₂ = inj₂ ( y₁∼x₁ , y₂∼x₂) ... | inj₂ y₁∼x₁ | inj₁ x₂∼y₂ = inj₁ (sym₁ y₁∼x₁ , x₂∼y₂) _×-decidable_ : ∀ {∼₁ ∼₂} → Decidable ∼₁ → Decidable ∼₂ → Decidable (∼₁ ×-Rel ∼₂) dec₁ ×-decidable dec₂ = λ x y → dec₁ (proj₁ x) (proj₁ y) ×-dec dec₂ (proj₂ x) (proj₂ y) -- Some collections of properties which are preserved by ×-Rel. _×-isEquivalence_ : ∀ {≈₁ ≈₂} → IsEquivalence ≈₁ → IsEquivalence ≈₂ → IsEquivalence (≈₁ ×-Rel ≈₂) _×-isEquivalence_ {≈₁ = ≈₁} {≈₂ = ≈₂} eq₁ eq₂ = record { refl = λ {x} → _×-refl_ {∼₁ = ≈₁} {∼₂ = ≈₂} (refl eq₁) (refl eq₂) {x} ; sym = λ {x y} → _×-symmetric_ {∼₁ = ≈₁} {∼₂ = ≈₂} (sym eq₁) (sym eq₂) {x} {y} ; trans = λ {x y z} → _×-transitive_ {∼₁ = ≈₁} {∼₂ = ≈₂} (trans eq₁) (trans eq₂) {x} {y} {z} } where open IsEquivalence _×-isPreorder_ : ∀ {≈₁ ∼₁ ≈₂ ∼₂} → IsPreorder ≈₁ ∼₁ → IsPreorder ≈₂ ∼₂ → IsPreorder (≈₁ ×-Rel ≈₂) (∼₁ ×-Rel ∼₂) _×-isPreorder_ {∼₁ = ∼₁} {∼₂ = ∼₂} pre₁ pre₂ = record { isEquivalence = isEquivalence pre₁ ×-isEquivalence isEquivalence pre₂ ; reflexive = λ {x y} → _×-reflexive_ {∼₁ = ∼₁} {∼₂ = ∼₂} (reflexive pre₁) (reflexive pre₂) {x} {y} ; trans = λ {x y z} → _×-transitive_ {∼₁ = ∼₁} {∼₂ = ∼₂} (trans pre₁) (trans pre₂) {x} {y} {z} ; ∼-resp-≈ = ∼-resp-≈ pre₁ ×-≈-respects₂ ∼-resp-≈ pre₂ } where open IsPreorder _×-isDecEquivalence_ : ∀ {≈₁ ≈₂} → IsDecEquivalence ≈₁ → IsDecEquivalence ≈₂ → IsDecEquivalence (≈₁ ×-Rel ≈₂) eq₁ ×-isDecEquivalence eq₂ = record { isEquivalence = isEquivalence eq₁ ×-isEquivalence isEquivalence eq₂ ; _≟_ = _≟_ eq₁ ×-decidable _≟_ eq₂ } where open IsDecEquivalence _×-isPartialOrder_ : ∀ {≈₁ ≤₁ ≈₂ ≤₂} → IsPartialOrder ≈₁ ≤₁ → IsPartialOrder ≈₂ ≤₂ → IsPartialOrder (≈₁ ×-Rel ≈₂) (≤₁ ×-Rel ≤₂) _×-isPartialOrder_ {≤₁ = ≤₁} {≤₂ = ≤₂} po₁ po₂ = record { isPreorder = isPreorder po₁ ×-isPreorder isPreorder po₂ ; antisym = λ {x y} → _×-antisymmetric_ {≤₁ = ≤₁} {≤₂ = ≤₂} (antisym po₁) (antisym po₂) {x} {y} } where open IsPartialOrder _×-isStrictPartialOrder_ : ∀ {≈₁ <₁ ≈₂ <₂} → IsStrictPartialOrder ≈₁ <₁ → IsStrictPartialOrder ≈₂ <₂ → IsStrictPartialOrder (≈₁ ×-Rel ≈₂) (<₁ ×-Rel <₂) _×-isStrictPartialOrder_ {<₁ = <₁} {≈₂ = ≈₂} {<₂ = <₂} spo₁ spo₂ = record { isEquivalence = isEquivalence spo₁ ×-isEquivalence isEquivalence spo₂ ; irrefl = λ {x y} → ×-irreflexive₁ {<₁ = <₁} {≈₂ = ≈₂} {<₂ = <₂} (irrefl spo₁) {x} {y} ; trans = λ {x y z} → _×-transitive_ {∼₁ = <₁} {∼₂ = <₂} (trans spo₁) (trans spo₂) {x} {y} {z} ; <-resp-≈ = <-resp-≈ spo₁ ×-≈-respects₂ <-resp-≈ spo₂ } where open IsStrictPartialOrder open Dummy public -- "Packages" (e.g. setoids) can also be combined. _×-preorder_ : Preorder → Preorder → Preorder p₁ ×-preorder p₂ = record { isPreorder = isPreorder p₁ ×-isPreorder isPreorder p₂ } where open Preorder _×-setoid_ : Setoid → Setoid → Setoid s₁ ×-setoid s₂ = record { isEquivalence = isEquivalence s₁ ×-isEquivalence isEquivalence s₂ } where open Setoid _×-decSetoid_ : DecSetoid → DecSetoid → DecSetoid s₁ ×-decSetoid s₂ = record { isDecEquivalence = isDecEquivalence s₁ ×-isDecEquivalence isDecEquivalence s₂ } where open DecSetoid _×-poset_ : Poset → Poset → Poset s₁ ×-poset s₂ = record { isPartialOrder = isPartialOrder s₁ ×-isPartialOrder isPartialOrder s₂ } where open Poset _×-strictPartialOrder_ : StrictPartialOrder → StrictPartialOrder → StrictPartialOrder s₁ ×-strictPartialOrder s₂ = record { isStrictPartialOrder = isStrictPartialOrder s₁ ×-isStrictPartialOrder isStrictPartialOrder s₂ } where open StrictPartialOrder
Require Import ProofCheckingEuclid.euclidean_axioms. Require Import ProofCheckingEuclid.euclidean_defs. Section Euclid. Context `{Ax:euclidean_neutral_ruler_compass}. Lemma lemma_s_ss : forall P Q A B X U V, Col A B U -> Col A B V -> BetS P U X -> BetS Q V X -> nCol A B P -> nCol A B Q -> SS P Q A B. Proof. intros P Q A B X U V. intros Col_A_B_U. intros Col_A_B_V. intros BetS_P_U_X. intros BetS_Q_V_X. intros nCol_A_B_P. intros nCol_A_B_Q. exists X, U, V. split. exact Col_A_B_U. split. exact Col_A_B_V. split. exact BetS_P_U_X. split. exact BetS_Q_V_X. split. exact nCol_A_B_P. exact nCol_A_B_Q. Qed. End Euclid.
= = = Abundance in cells = = =
\bigskip \textit{This paper is the report of the \textbf{Group 10} for the first assignment of the course.} \section{Python AIMA} \begin{enumerate} \item In order to perform a search, what are the classes that you must define or extend? Explain precisely why and where they are used inside a tree\_search. \begin{framed} The only class we need to extend is the class Problem because it is an abstract class and it doesn't exactly fit our purpose. This class is used by all the uninformed searchs. In tree\_search (called by breadth\_first\_tree\_search and depth\_first\_tree\_search), the first argument is a Problem, which is an object from the class Problem. It is needed to get an initial state from the problem to create the first node, do a search (this one depends on the data structure used for the fringe), testing for every node if the current node is the goal we have to reach and every loop expands the tree with the node directly linked from the visited node (thanks to the Problem.successor method). \end{framed} \item In the expand method of the class Node what is the advantage of using a yield instead of building a list and returning it afterwards ? \begin{framed} The advantage is that \textit{yield} builds a list item-by-item, it is some kind of lazy programming that permits to create only the nodes that are really used by our program, it is very useful to avoid a too large memory usage than what is needed. \end{framed} \item Both breadth\_first\_graph\_search and depth\_first\_graph\_search are making a call to the same function. How is their fundamental difference implemented? \begin{figure}[!ht] \begin{framed} The fundamental difference is that the data structure used is totally different : \begin{description} \item[Breadth-first graph search] needs a FIFOQueue as a data structure because while the graph\_search is performed, it expands the nodes linked to the visited nodes, a FIFO (first in, first out) queue allows the path to follow the root node then the nodes linked to the root node, then the nodes linked to the previous node, as shown on the next figure. \item[Depth-first graph search] needs a LIFO (last in, first out) queue, in other words a Stack, because it must always first follow the last expansion of the nodes visited before until the goal is reached or the branch of the tree cannot lead to a goal state. The comportement of this function is shown on the next figure. \end{description} \centering \includegraphics[width=0.75\linewidth]{depth_or_breadth.png} \caption{Difference between a breadth-first and a depth-first search algorithm, here represented for a tree, but for a graph it works the same (but you can have symmetric state, cycles)} \end{framed} \end{figure} \FloatBarrier \item What is the difference between the implementation of the graph\_search and the tree\_search methods and how does it impact the search methods ? \begin{framed} The only difference is that graph\_search method maintains a closed list (a dictionary) that keeps in memory all the states already visited, because graphs can contains symmetric states and we need to avoid the search to loop in cycles in the graph (because it doesn't provide any useful additional information). \end{framed} \item What kind of structure is used to implement the closed list? What are the methods involved in the search of an element inside it? What properties must thus have the elements that you can put inside the closed list ? \begin{framed} It's a dictionary, it takes an hashable object as index and every index is linked to a variable. The \verb#if node.state not in closed# instruction checks whether \verb#node.state# is already an index of the closed list (then this instruction would be false) or not (then this instruction would be true). \end{framed} \item How technically can you use the implementation of the closed list to deal with symmetrical states ? (hint: if two symmetrical states are considered by the algorithm to be the same, they will not be visited twice) \begin{framed} The hash function for the \verb#node.state# must always return a unique result that permits a comparison between two object and thats returns True when two states are symmetric. \end{framed} \end{enumerate} \section{The Numberlink Problem} \begin{enumerate} \item Explain the advantages and weaknesses of the following search strategies on this problem (not in general): depth first, breadth first. \begin{framed} The breadth-first search expands the shallowest unexpanded node and implements the frontier as a FIFO Queue. In this problem, it means that we will check every path possible for one letter, then check every path possible for a second letter, and so on (without following the branches that couldn't reach to the goal). The main advantage is that we can work one letter at a time and be sure that all the paths for a letter have already been visited once at the moment we try another letter, the main disadvantage is the space this search needs (because we have to keep the paths followed from the root to each node) and if the directions given give a good heuristic, we will not take advantage of it. \newline The depth-first search expands the deepest unexpanded node and implements the frontier as a LIFO Queue. In this problem, it means that we try to reach as soon as possible a viable path for the first letter, then for the second, and so on (withtout following the branches that couldn't reach to the goal). The main advantages are that : first, if we have a good heuristic, the path to the goal will be found quickly; second, the memory space isn't a problem here because even if we have to keep the full path from root node to the node, it is only the current path that is kept in memory. The main disadvantage is that our successor method must be very well implemented to highlight the sooner as it can a branch that can't anymore reach a goal state, because that kind of search can lead us to a node far from the goal node (a poorly implemented algorithm can lead to a very long time to discover the solution) \end{framed} \item How can we exploit the uniqueness of solution to reduce the search space? Why is the method pathExists useful ? \begin{framed} We can exploit the uniqueness of solution to avoid states that wouldn't be a solution in a well-designed problem (for example, a 2x2 grid in our state with the same letter will never lead to a goal for a well-designed problem). Likewise, a state that doesn't permit all the other letters to be connected by their two endpoints are not leading to a goal state (and that's why the method pathExists is made for). \end{framed} \item Is the order in which we choose the paths important? How can we use this to reduce the search space? When starting a new path, we can choose to start with any of its two endpoint. How should this choice be done ? \begin{framed} As it is an uninformed search, we can never be sure that the order is important. But if it is imposed to us, we assume that it will help us to reduce the search space by giving us a good heuristic method. We thought about some improvements, like starting by the letter with the shortest length between its endpoints but it doesn't provide any better result than the basic technique so we don't think that really matters for this assignment. \end{framed} \item What are the advantages and disadvantages of using the tree and graph search for this problem. Which approach would you choose? Which approach allows you to avoid expending twice symmetrical states ? \begin{framed} The advantage of the graph search over the tree search is that this first one avoid expending twice symmetrical states. The disadvantage of this method is that (in this implementation) the state must be hashable (to be an index in the closed list) while it must be a grid that is not hashable (to be used in the pathExists method) so we would have to maintain two data structures containing the exact same information if we use the graph search. As we couldn't think of any symmetrical state when we use the fact that we won't extend a state that would contain a 2x2 grid containing the same letter 4 times and that we will always start by the same endpoint, the tree search would be a better approach. \end{framed} \item Implement this problem in Python 3. Extend the Problem class and implement the necessary methods and other class(es) if necessary. Your file must be named numberlink.py. You program must take as only input the path to the init file of the problem to solve. It must print to the standard output a solution to the problem satisfying the above format. Your file must be encoded in utf-8. Submit your program on INGInious. \begin{figure}[!ht] \begin{framed} \centering \includegraphics[width=0.85\linewidth]{inginious.png} \end{framed} \end{figure} \FloatBarrier \item Experiments must be realized with the 10 instances of the numberlink problem provided. Report in a table the results on the 10 instances for depth-first and breadth- first strategies on both tree and graph search (4 settings). You must report the time, the number of explored nodes and the number of steps from root to solution. When no solution can be found by a strategy in a reasonable time (3 min), explain the reason (time-out and/or swap of the memory). What do you conclude from those experiments ? \begin{framed} In each row, you will find the execution time, the number of explored nodes and the number of steps from root to solution : \begin{tabular}{l|p{0.18\linewidth}|p{0.18\linewidth}|p{0.18\linewidth}|p{0.2\linewidth}} & Depth, tree & Depth, graph & Breadth, tree & Breadth, graph \\ \hline \hline easy & 20ms & 30ms & 20ms & 50ms \\ & 16 & 16 & 16 & 16 \\ & 13 & 13 & 13 & 13 \\ \hline level2m & 24s & 25s & 1m59 & 2m02 \\ & 49294 & 49294 & 218858 & 218858 \\ & 69 & 69 & 69 & 69 \\ \hline level4m & 310ms & 290ms & 300ms & 320ms \\ & 1243 & 1243 & 1043 & 1043 \\ & 49 & 49 & 49 & 49 \\ \hline level9m & 290ms & 300ms & 520ms & 510ms \\ & 1027 & 1027 & 1828 & 1828 \\ & 53 & 53 & 53 & 53 \\ \hline level10m & 2m11 & 2m11 & 3m26 & 3m24 \\ & 245601 & 245601 & 383881 & 383881 \\ & 75 & 75 & 75 & 75 \\ \hline level15m & 52s & 55s & 1m27 & 1m32 \\ & 80949 & 80949 & 126768 & 126768 \\ & 85 & 85 & 85 & 85 \\ \hline level38s & 190ms & 190ms & 240ms & 250ms \\ & 674 & 674 & 758 & 758 \\ & 38 & 38 & 38 & 38 \\ \hline level39s & 30ms & 30ms & 360ms & 370ms \\ & 49 & 49 & 1614 & 1614 \\ & 40 & 40 & 40 & 40 \\ \hline path & 50ms & 40ms & 2s & 2s36 \\ & 71 & 71 & 1730 & 1730 \\ & 71 & 71 & 71 & 71 \\ \hline wiki & 40ms & 30ms & 40ms & 40ms \\ & 51 & 51 & 77 & 77 \\ & 40 & 40 & 40 & 40 \\ \end{tabular} \bigskip The only case where no reasonable time can be found is for level10m with a breadth-first search. It is explained by the fact that the breadth-first search cover twice as much cases than the same with depth-first. In fact, for this problem, breadth-first search is usually very bad to provide the goal state because it creates first every paths for every letter before trying to reach a possible final state. Conversely, depth-first search will try to find a goal state as quickly as possible by trying one path by letter. \newline As you can see, there are no differences between a tree search and a graph search in our implementation because there are no symmetrical states. The time are not perfectly the same because my CPU had other applications to handle at the same time. \end{framed} \end{enumerate}
module Data.Sign %access public export ||| A representation of signs for signed datatypes such as `ZZ` data Sign = Plus | Zero | Minus opposite : Sign -> Sign opposite Plus = Minus opposite Zero = Zero opposite Minus = Plus multiply : Sign -> Sign -> Sign multiply Zero _ = Zero multiply _ Zero = Zero multiply Plus x = x multiply Minus x = opposite x ||| Discover the sign of some type interface Signed t where total sign : t -> Sign Signed Int where sign x with (compare x 0) | LT = Minus | EQ = Zero | GT = Plus Signed Integer where sign x with (compare x 0) | LT = Minus | EQ = Zero | GT = Plus Signed Double where sign x with (compare x 0.0) | LT = Minus | EQ = Zero | GT = Plus
/- Copyright (c) 2022 James Gallicchio. Authors: James Gallicchio -/ @[reducible] def Tuple (α : Type u) : Nat → Type u | 0 => PUnit | 1 => α | (n+1)+1 => α × Tuple α (Nat.succ n) namespace Tuple @[inline] def toList (t : Tuple α n) : List α := match n, t with | 0, () => [] | 1, a => [a] | _+2, (a,as) => a :: toList as @[simp] theorem length_toList (t : Tuple α n) : t.toList.length = n := by induction n with | zero => simp [toList] | succ n ih => cases n <;> simp [toList, ih] @[inline] def ofList (L : List α) : Tuple α L.length := match L with | [] => () | [x] => x | x::y::xs => (x, ofList (y::xs)) end Tuple /-! ## List.choose Returns list of all ways of choosing `n` elements from `L`. This is equivalent to the list of all `(L[i1], ... L[in])` for `0 ≤ i1 < i2 < ... < in < L.length`. -/ def List.chooseSucc : (n : Nat) → List α → List (Tuple α n.succ) | 0 , L => L | _+1, [] => [] | n+1, x::xs => -- Either x is in the tuple, (List.chooseSucc n xs |>.map ((x, ·))) ++ -- or it is not. (List.chooseSucc (n+1) xs) def List.choose (n : Nat) (h_n : n = n.pred.succ := by decide) : List α → List (Tuple α n) := h_n ▸ List.chooseSucc n.pred
Ingredients: Water, Mineral Oil, Glyceryl Stearate, Stearic Acid, Glycerin, Stearyl Alcohol, Vitamin E oil, Tepezcohuite extract, Collagen, Carbonar 940, Triethanolamine, Propylane Glycol Dyazolininyl Urea & Methylparaben & Propylparaben, Fragance, Directions: With clean hand apply gently rubbing into skin. May be use for all skin concerns. Precautions: For external use only. tepezcohuite cream, tepezcohuite skin, tepezcohuite cream, tepezcohuite skin, tepezcohuite , tepezcohuite, tepezcohuite bark cream, tepezcohuite cream, tepezcohuite skin, tepezcohuite cream, tepezcohuite skin, tepezcohuite creme , tepezcohuite, tepezcohuite bark cream Del Indio Papago Tepezcohuite Cream 2 Oz Ingredients: Water, Mineral Oil, Glyceryl Stearate, Stearic Acid, Glycerin, Stearyl Alcohol, Vitamin E oil, Tepezcohuite extract, Collagen, Carbonar 940, Triethanolamine, Propylane Glycol Dyazolininyl Urea & Methylparaben & Propylparaben, Fragance, Directions: With clean hand apply gently rubbing into skin. May be use for all skin concerns. Precautions: For external use only. Disclaimer: While we work to ensure that product information is correct, on occasion manufacturers may alter their ingredient lists. Actual product packaging and materials may contain more and/or different information than what shown on our Web site. We recommend that you do not rely on the information presented and that you always read labels, warnings, terms and directions before using or consuming any product Purchase on Cleanse Mart Site These statements have not been evaluated by the FDA. This product is not intended to diagnose, treat, cure, or prevent disease.
[STATEMENT] lemma borel_measurable_sum'[measurable (raw)]: fixes f::"'i \<Rightarrow> 'a \<Rightarrow> 'b::{second_countable_topology, real_normed_vector}" assumes "\<And>i. i \<in> I \<Longrightarrow> f i \<in> borel_measurable M" shows "(\<Sum>i\<in>I. f i) \<in> borel_measurable M" [PROOF STATE] proof (prove) goal (1 subgoal): 1. sum f I \<in> borel_measurable M [PROOF STEP] using borel_measurable_sum[of I f, OF assms] [PROOF STATE] proof (prove) using this: (\<And>i. i \<in> I \<Longrightarrow> i \<in> I) \<Longrightarrow> (\<lambda>x. \<Sum>i\<in>I. f i x) \<in> borel_measurable M goal (1 subgoal): 1. sum f I \<in> borel_measurable M [PROOF STEP] unfolding fun_sum_apply[symmetric] [PROOF STATE] proof (prove) using this: (\<And>i. i \<in> I \<Longrightarrow> i \<in> I) \<Longrightarrow> sum f I \<in> borel_measurable M goal (1 subgoal): 1. sum f I \<in> borel_measurable M [PROOF STEP] by simp
(** Extraction to Haskell : use of basic Haskell types *) Require Coq.extraction.Extraction. Extract Inductive bool => "Prelude.Bool" [ "Prelude.True" "Prelude.False" ]. Extract Inductive option => "Prelude.Maybe" [ "Prelude.Just" "Prelude.Nothing" ]. Extract Inductive unit => "()" [ "()" ]. Extract Inductive list => "([])" [ "([])" "(:)" ]. Extract Inductive prod => "(,)" [ "(,)" ]. Extract Inductive sumbool => "Prelude.Bool" [ "Prelude.True" "Prelude.False" ]. Extract Inductive sumor => "Prelude.Maybe" [ "Prelude.Just" "Prelude.Nothing" ]. Extract Inductive sum => "Prelude.Either" [ "Prelude.Left" "Prelude.Right" ]. Extract Inlined Constant andb => "(Prelude.&&)". Extract Inlined Constant orb => "(Prelude.||)". Extract Inlined Constant negb => "Prelude.not".
module probin_reactdiff_module use bl_types use bl_space use probin_common_module, only: dim_in implicit none integer, parameter :: max_species=10 integer, parameter :: max_reactions=20 ! Problem description !---------------------- integer, save :: nspecies = 2 ! number of species integer, save :: nreactions = 1 ! number of reactions ! Control of algorithm !---------------------- integer, save :: temporal_integrator = 0 ! 0=D + R (first-order splitting) ! 1=(1/2)R + D + (1/2)R (Strang option 1) ! 2=(1/2)D + R + (1/2)D (Strang option 2) ! -1=unsplit forward Euler ! -2=unsplit explicit midpoint ! -3=unsplit multinomial diffusion ! -4=unsplit implicit midpoint integer, save :: diffusion_type = 0 ! only used for splitting schemes (temporal_integrator>=0) ! 0=explicit trapezoidal predictor/corrector ! 1=Crank-Nicolson semi-implicit ! 2=explicit midpoint ! 3=multinomial diffusion ! 4=forward Euler integer, save :: reaction_type = 0 ! only used for splitting schemes (temporal_integrator>=0) ! 0=first-order (deterministic, tau leaping, CLE, or SSA) ! 1=second-order (determinisitc, tau leaping, or CLE only) integer, save :: use_Poisson_rng = 1 ! how to calculate chemical production rates ! 2=SSA ! 1=do tau leaping (Poisson increments) ! 0=do CLE (Gaussian increments) ! -1=do deterministic chemistry integer, save :: midpoint_stoch_flux_type = 1 ! only used for midpoint diffusion schemes (split as well as unsplit) ! corrector formulation of noise ! 1 = K(nold) * W1 + K(nold) * W2 ! 2 = K(nold) * W1 + K(npred) * W2 ! 3 = K(nold) * W1 + K(2*npred-nold) * W2 logical, save :: inhomogeneous_bc_fix = .false. ! use the Einkemmer boundary condition fix (split schemes only) integer, save :: avg_type = 1 ! how to compute n on faces for stochastic weighting ! 1=arithmetic (with C0-Heaviside), 2=geometric, 3=harmonic ! 10=arithmetic average with discontinuous Heaviside function ! 11=arithmetic average with C1-smoothed Heaviside function ! 12=arithmetic average with C2-smoothed Heaviside function logical, save :: use_bl_rng = .false. ! if true, use F_BaseLib/bl_random RNGs ! if false, use HydroGrid RNGs ! Random number seeds for each physical process for use_bl_rng=T ! for positive value, the value is assigned as seed value ! for 0, a positive value is randomly chosen ! if -1 (only for restart), RNGs status is restored from checkpoint data integer, save :: seed_diffusion = 1 integer, save :: seed_reaction = 1 integer, save :: seed_init = 1 ! Initial and boundary conditions !---------------------- real(kind=dp_t), save :: n_init_in(2,max_species) = 1.d0 ! initial values to be used in init_n.f90 real(kind=dp_t), save :: n_bc(3,2,max_species) = 0.d0 ! n_i boundary conditions (dir,lohi,species) integer, save :: model_file_init = 0 ! initialize from model files: ! 0=no, 1=usual order (Fortran), -1=transpose order (C) character(len=128), save :: model_file(max_species) ! one model file for each species logical, save :: integer_populations=.false. ! initialize with all number of molecules strictly integer ! Diffusion !---------------------- real(kind=dp_t), save :: D_Fick(max_species) = 1.d0 ! Fickian diffusion coeffs integer, save :: diffusion_stencil_order = 1 ! diffusion boundary stencil order integer, save :: mg_verbose = 0 ! implicit diffusion solve verbosity integer, save :: cg_verbose = 0 ! implicit diffusion solve bottom solver verbosity real(kind=dp_t), save :: implicit_diffusion_rel_eps = 1.d-10 ! relative eps for implicit diffusion solve real(kind=dp_t), save :: implicit_diffusion_abs_eps = -1.d0 ! absolute eps for implicit diffusion solve ! Chemical reactions !---------------------- real(kind=dp_t), save :: cross_section = 1.d0 ! in 2D, thickness of cell ! in general, dv = product(dx(1,1:dm))*cross_section ! whether to compute chemical rates using classical LMA or integer-based one logical, save :: include_discrete_LMA_correction = .true. ! LMA chemical reaction rate for each reaction (assuming Law of Mass holds) real(kind=dp_t), save :: rate_const(max_reactions) = 0.0d0, rate_multiplier=1.0d0 ! stoichiometric factors for each reaction (species,LHS(1)/RHS(2),reaction) ! Example: For N1 + 2*N2 -> N3 use ! stoichiometric_factors(1:3,1,1) = 1 2 0 ! stoichiometric_factors(1:3,2,1) = 0 0 1 integer, save :: stoichiometric_factors(max_species,2,max_reactions) = 0 ! Controlling output: integer, save :: n_steps_write_avg = 0 ! If non-zero, its absolute value tells how many steps before writing total densites ! If positive, it writes average number densities in the system ! If negative, it writes the total number of molecules in the system ! interval to write histograms integer, save :: hist_int = 0 namelist /probin_reactdiff/ nspecies, nreactions namelist /probin_reactdiff/ temporal_integrator, diffusion_type, midpoint_stoch_flux_type namelist /probin_reactdiff/ reaction_type, use_Poisson_rng, avg_type namelist /probin_reactdiff/ use_bl_rng, seed_diffusion, seed_reaction, seed_init namelist /probin_reactdiff/ inhomogeneous_bc_fix, n_init_in, n_bc, model_file_init, model_file, integer_populations namelist /probin_reactdiff/ D_Fick, diffusion_stencil_order, mg_verbose, cg_verbose namelist /probin_reactdiff/ implicit_diffusion_rel_eps, implicit_diffusion_abs_eps namelist /probin_reactdiff/ cross_section, include_discrete_LMA_correction namelist /probin_reactdiff/ rate_const, rate_multiplier, stoichiometric_factors namelist /probin_reactdiff/ n_steps_write_avg, hist_int contains subroutine probin_reactdiff_init() use f2kcli use parallel use bl_IO_module use bl_prof_module use bl_error_module use bl_constants_module use cluster_module integer :: narg, farg character(len=128) :: fname integer :: un logical :: lexist,need_inputs narg = command_argument_count() ! You can put default values here if you want, but we have specified them above ! in the variable declaration ! read from input file need_inputs = .true. farg = 1 if ( need_inputs .AND. narg >= 1 ) then call get_command_argument(farg, value = fname) inquire(file = fname, exist = lexist ) if ( lexist ) then farg = farg + 1 un = unit_new() open(unit=un, file = fname, status = 'old', action = 'read') read(unit=un, nml = probin_reactdiff) close(unit=un) need_inputs = .false. end if end if ! also can be read in from the command line by appending do while ( farg <= narg ) call get_command_argument(farg, value = fname) select case (fname) case ('--nspecies') farg = farg + 1 call get_command_argument(farg, value = fname) read(fname, *) nspecies case ('--nreactions') farg = farg + 1 call get_command_argument(farg, value = fname) read(fname, *) nreactions case ('--temporal_integrator') farg = farg + 1 call get_command_argument(farg, value = fname) read(fname, *) temporal_integrator case ('--diffusion_type') farg = farg + 1 call get_command_argument(farg, value = fname) read(fname, *) diffusion_type case ('--midpoint_stoch_flux_type') farg = farg + 1 call get_command_argument(farg, value = fname) read(fname, *) midpoint_stoch_flux_type case ('--reaction_type') farg = farg + 1 call get_command_argument(farg, value = fname) read(fname, *) reaction_type case ('--use_Poisson_rng') farg = farg + 1 call get_command_argument(farg, value = fname) read(fname, *) use_Poisson_rng case ('--inhomogeneous_bc_fix') farg = farg + 1 call get_command_argument(farg, value = fname) read(fname, *) inhomogeneous_bc_fix case ('--integer_populations') farg = farg + 1 call get_command_argument(farg, value = fname) read(fname, *) integer_populations case ('--avg_type') farg = farg + 1 call get_command_argument(farg, value = fname) read(fname, *) avg_type case ('--use_bl_rng') farg = farg + 1 call get_command_argument(farg, value = fname) read(fname, *) use_bl_rng case ('--seed_diffusion') farg = farg + 1 call get_command_argument(farg, value = fname) read(fname, *) seed_diffusion case ('--seed_reaction') farg = farg + 1 call get_command_argument(farg, value = fname) read(fname, *) seed_reaction case ('--seed_init') farg = farg + 1 call get_command_argument(farg, value = fname) read(fname, *) seed_init case ('--model_file_init') farg = farg + 1 call get_command_argument(farg, value = fname) read(fname, *) model_file_init case ('--diffusion_stencil_order') farg = farg + 1 call get_command_argument(farg, value = fname) read(fname, *) diffusion_stencil_order case ('--mg_verbose') farg = farg + 1 call get_command_argument(farg, value = fname) read(fname, *) mg_verbose case ('--cg_verbose') farg = farg + 1 call get_command_argument(farg, value = fname) read(fname, *) cg_verbose case ('--implicit_diffusion_rel_eps') farg = farg + 1 call get_command_argument(farg, value = fname) read(fname, *) implicit_diffusion_rel_eps case ('--implicit_diffusion_abs_eps') farg = farg + 1 call get_command_argument(farg, value = fname) read(fname, *) implicit_diffusion_abs_eps case ('--cross_section') farg = farg + 1 call get_command_argument(farg, value = fname) read(fname, *) cross_section case ('--rate_multiplier') farg = farg + 1 call get_command_argument(farg, value = fname) read(fname, *) rate_multiplier case ('--include_discrete_LMA_correction') farg = farg + 1 call get_command_argument(farg, value = fname) read(fname, *) include_discrete_LMA_correction case ('--n_steps_write_avg') farg = farg + 1 call get_command_argument(farg, value = fname) read(fname, *) n_steps_write_avg case ('--hist_int') farg = farg + 1 call get_command_argument(farg, value = fname) read(fname, *) hist_int case ('--D_Fick_1') farg = farg + 1 call get_command_argument(farg, value = fname) read(fname, *) D_Fick(1) case ('--D_Fick_2') farg = farg + 1 call get_command_argument(farg, value = fname) read(fname, *) D_Fick(2) case ('--D_Fick_3') farg = farg + 1 call get_command_argument(farg, value = fname) read(fname, *) D_Fick(3) case ('--no_diffusion') D_Fick(1:max_species) = 0.d0 case default if (parallel_IOProcessor() ) then print*,'probin_reactdiff: command-line input ',trim(fname),' not read' end if end select farg = farg + 1 end do ! check that nspecies<=max_species, otherwise abort with error message if(nspecies.gt.max_species) then call bl_error(" nspecies greater than max_species - Aborting") end if ! check that nreactions<=max_reactions, otherwise abort with error message if(nreactions.gt.max_reactions) then call bl_error(" nreactions greater than max_reactions - Aborting") end if if (inhomogeneous_bc_fix .and. temporal_integrator .lt. 0) then call bl_error("inhomogeneous_bc_fix only appropriate for split schemes") end if if (temporal_integrator .ge. 0 .and. reaction_type .ne. 0) then if (use_Poisson_rng .eq. 2) then call bl_error("SSA (use_Poisson_rng=2) requires reaction_type=0 for split schemes") end if end if end subroutine probin_reactdiff_init end module probin_reactdiff_module
section \<open>Program statements, Hoare and refinement rules\<close> theory Statements imports Assertion_Algebra begin text \<open>In this section we introduce assume, if, and while program statements as well as Hoare triples, and data refienment. We prove Hoare correctness rules for the program statements and we prove some theorems linking Hoare correctness statement to (data) refinement. Most of the theorems assume a monotonic boolean transformers algebra. The theorem stating the equivalence between a Hoare correctness triple and a refinement statement holds under the assumption that we have a monotonic boolean transformers algebra with post condition statement.\<close> definition "assume" :: "'a::mbt_algebra Assertion \<Rightarrow> 'a" ("[\<cdot> _ ]" [0] 1000) where "[\<cdot>p] = {\<cdot>p} ^ o" lemma [simp]: "[\<cdot>p] * x \<squnion> {\<cdot>-p} * \<top> = [\<cdot>p] * x" by (simp add: assume_def uminus_Assertion_def) lemma [simp]: "{\<cdot>p} * \<top> \<squnion> [\<cdot>-p] * x = [\<cdot>-p] * x" by (simp add: assume_def uminus_Assertion_def) lemma assert_sup: "{\<cdot>p \<squnion> q} = {\<cdot>p} \<squnion> {\<cdot>q}" by (simp add: sup_Assertion_def) lemma assert_inf: "{\<cdot>p \<sqinter> q} = {\<cdot>p} \<sqinter> {\<cdot>q}" by (simp add: inf_Assertion_def) lemma assert_neg: "{\<cdot>-p} = neg_assert {\<cdot>p}" by (simp add: uminus_Assertion_def) lemma assert_false [simp]: "{\<cdot>\<bottom>} = \<bottom>" by (simp add: bot_Assertion_def) lemma if_Assertion_assumption: "({\<cdot>p} * x) \<squnion> ({\<cdot>-p} * y) = ([\<cdot>p] * x) \<sqinter> ([\<cdot>-p] * y)" proof - have "({\<cdot>p} * x) \<squnion> {\<cdot>-p} * y = ({\<cdot>p} * \<top> \<sqinter> [\<cdot>p]) * x \<squnion> ({\<cdot>-p} * \<top> \<sqinter> [\<cdot>-p]) * y" by simp also have "\<dots> = ({\<cdot>p} * \<top> \<sqinter> ([\<cdot>p] * x)) \<squnion> ({\<cdot>-p} * \<top> \<sqinter> ([\<cdot>-p] * y))" by (unfold inf_comp, simp) also have "\<dots> = (({\<cdot>p} * \<top> \<sqinter> ([\<cdot>p] * x)) \<squnion> ({\<cdot>-p} * \<top>)) \<sqinter> (({\<cdot>p} * \<top> \<sqinter> ([\<cdot>p] * x)) \<squnion> ([\<cdot>-p] * y))" by (simp add: sup_inf_distrib) also have "\<dots> = (({\<cdot>p} * \<top> \<squnion> ({\<cdot>-p} * \<top>)) \<sqinter> (([\<cdot>p] * x))) \<sqinter> (([\<cdot>-p] * y) \<sqinter> (([\<cdot>p] * x) \<squnion> ([\<cdot>-p] * y)))" by (simp add: sup_inf_distrib2) also have "\<dots> = ([\<cdot>p] * x) \<sqinter> ([\<cdot>-p] * y) \<sqinter> (([\<cdot>p] * x) \<squnion> ([\<cdot>-p] * y))" apply (simp add: sup_comp [THEN sym] ) by (simp add: assert_sup [THEN sym] inf_assoc) also have "\<dots> = ([\<cdot>p] * x) \<sqinter> ([\<cdot>-p] * y)" by (rule antisym, simp_all add: inf_assoc) finally show ?thesis . qed definition "wp x p = abs_wpt (x * {\<cdot>p})" lemma wp_assume: "wp [\<cdot>p] q = -p \<squnion> q" apply (simp add: wp_def abs_wpt_def) apply (rule assert_injective) apply simp by (simp add: assert_sup assert_neg assume_def wpt_dual_assertion_comp) lemma assert_commute: "y \<in> conjunctive \<Longrightarrow> y * {\<cdot>p} = {\<cdot> wp y p } * y" apply (simp add: wp_def abs_wpt_def) by (rule assertion_commute, simp_all) lemma wp_assert: "wp {\<cdot>p} q = p \<sqinter> q" by (simp add: wp_def assertion_inf_comp_eq [THEN sym] assert_inf [THEN sym]) lemma wp_mono [simp]: "mono (wp x)" apply (simp add: le_fun_def wp_def abs_wpt_def less_eq_Assertion_def mono_def) apply (simp add: wpt_def, safe) apply (rule_tac y = " x * {\<cdot> xa } * \<top>" in order_trans, simp_all) apply (rule le_comp_right) by (rule le_comp, simp) lemma wp_fun_mono [simp]: "mono wp" apply (simp add: le_fun_def wp_def abs_wpt_def less_eq_Assertion_def mono_def) apply (simp add: wpt_def, safe) apply (rule_tac y = " x * {\<cdot> xa } * \<top>" in order_trans, simp_all) apply (rule le_comp_right) by (rule le_comp_right, simp) lemma wp_fun_mono2: "x \<le> y \<Longrightarrow> wp x p \<le> wp y p" apply (cut_tac wp_fun_mono) apply (unfold mono_def) apply (simp add: le_fun_def) by blast lemma wp_comp: "wp (x * y) p = wp x (wp y p)" apply (simp add: wp_def abs_wpt_def) by (unfold wpt_comp_2 [THEN sym] mult.assoc, simp) lemma wp_choice: "wp (x \<sqinter> y) = wp x \<sqinter> wp y" apply (simp add: fun_eq_iff wp_def inf_fun_def inf_comp inf_Assertion_def abs_wpt_def) by (simp add: wpt_choice) lemma [simp]: "wp 1 = id" apply (unfold fun_eq_iff, safe) apply (rule assert_injective) by (simp add: wp_def abs_wpt_def) lemma wp_omega_fix: "wp (x ^ \<omega>) p = wp x (wp (x ^ \<omega>) p) \<sqinter> p" apply (subst omega_fix) by (simp add: wp_choice wp_comp) lemma wp_omega_least: "(wp x r) \<sqinter> p \<le> r \<Longrightarrow> wp (x ^ \<omega>) p \<le> r" apply (simp add: wp_def abs_wpt_def inf_Assertion_def less_eq_Assertion_def) apply (simp add: wpt_def) apply (rule_tac y = "{\<cdot>r} * \<top> \<sqinter> 1" in order_trans) apply simp apply (rule_tac y = "x ^ \<omega> * {\<cdot> p } * \<top>" in order_trans, simp) apply (simp add: mult.assoc) apply (rule omega_least) apply (drule_tac z = \<top> in le_comp_right) apply (simp add: inf_comp mult.assoc [THEN sym]) by (simp add: assertion_prop) lemma Assertion_wp: "{\<cdot>wp x p} = (x * {\<cdot>p} * \<top>) \<sqinter> 1" apply (simp add: wp_def abs_wpt_def) by (simp add: wpt_def) definition "hoare p S q = (p \<le> wp S q)" definition "grd x = - (wp x \<bottom>)" lemma grd_comp: "[\<cdot>grd x] * x = x" apply (simp add: grd_def wp_def uminus_Assertion_def assume_def neg_assert_def abs_wpt_def dual_sup sup_comp) apply (simp add: wpt_def dual_inf sup_comp dual_comp bot_Assertion_def) by (rule antisym, simp_all) lemma assert_assume: "{\<cdot>p} * [\<cdot>p] = {\<cdot> p}" by (simp add: assume_def) lemma dual_assume: "[\<cdot>p] ^ o = {\<cdot>p}" by (simp add: assume_def) lemma assume_prop: "([\<cdot>p] * \<bottom>) \<squnion> 1 = [\<cdot>p]" by (simp add: assume_def dual_assertion_prop) text\<open>An alternative definition of a Hoare triple\<close> definition "hoare1 p S q = ([\<cdot> p ] * S * [\<cdot> -q ] = \<top>)" lemma "hoare1 p S q = hoare p S q" apply (simp add: hoare1_def dual_inf dual_comp) apply (simp add: hoare_def wp_def less_eq_Assertion_def abs_wpt_def) apply (simp add: wpt_def) apply safe proof - assume A: "[\<cdot> p ] * S * [\<cdot> - q ] = \<top>" have "{\<cdot>p} \<le> {\<cdot>p} * \<top>" by simp also have "... \<le> {\<cdot>p} * \<top> * \<bottom>" by (unfold mult.assoc, simp) also have "... = {\<cdot>p} * [\<cdot> p ] * S * [\<cdot> - q ] * \<bottom>" by (subst A [THEN sym], simp add: mult.assoc) also have "... = {\<cdot>p} * S * [\<cdot> - q ] * \<bottom>" by (simp add: assert_assume) also have "... \<le> {\<cdot>p} * S * {\<cdot> q } * \<top>" apply (simp add: mult.assoc) apply (rule le_comp, rule le_comp) apply (simp add: assume_def uminus_Assertion_def) by (simp add: neg_assert_def dual_inf dual_comp sup_comp) also have "... \<le> S * {\<cdot> q } * \<top>" by (simp add: mult.assoc) finally show "{\<cdot>p} \<le> S * {\<cdot> q } * \<top>" . next assume A: "{\<cdot> p } \<le> S * {\<cdot> q } * \<top>" have "\<top> = ((S * {\<cdot>q}) ^ o) * \<bottom> \<squnion> S * {\<cdot>q} * \<top>" by simp also have "\<dots> \<le> [\<cdot>p] * \<bottom> \<squnion> S * {\<cdot>q} * \<top>" apply (simp del: dual_neg_top) apply (rule_tac y = "[\<cdot>p] * \<bottom>" in order_trans, simp_all) apply (subst dual_le) apply (simp add: dual_comp dual_assume) apply (cut_tac x = "{\<cdot>p}" and y = "S * {\<cdot>q} * \<top>" and z = \<top> in le_comp_right) apply (rule A) by (simp add: mult.assoc) also have "\<dots> = [\<cdot>p] * S * ({\<cdot>q} * \<top>)" apply (subst (2) assume_prop [THEN sym]) by (simp_all add: sup_comp mult.assoc) also have "\<dots> \<le> [\<cdot>p] * S * ({\<cdot>q} * \<top> \<squnion> 1)" by (rule le_comp, simp) also have "\<dots> = [\<cdot>p] * S * [\<cdot>-q]" apply (simp add: assume_def uminus_Assertion_def) by (simp add: neg_assert_def dual_inf dual_comp) finally show "[\<cdot>p] * S * [\<cdot> - q] = \<top>" by (rule_tac antisym, simp_all) qed lemma hoare_choice: "hoare p (x \<sqinter> y) q = ((hoare p) x q & (hoare p y q))" apply (unfold hoare_def wp_choice inf_fun_def) by auto definition if_stm:: "'a::mbt_algebra Assertion \<Rightarrow> 'a \<Rightarrow> 'a \<Rightarrow> 'a" ("(If (_)/ then (_)/ else (_))" [0, 0, 10] 10) where "if_stm b x y = (([\<cdot> b ] * x) \<sqinter> ([\<cdot> -b ] * y))" lemma if_assertion: "(If p then x else y) = {\<cdot>p} * x \<squnion> {\<cdot> -p} * y" by (simp add: if_stm_def if_Assertion_assumption) lemma (in boolean_algebra) sup_neg_inf: "(p \<le> q \<squnion> r) = (p \<sqinter> -q \<le> r)" apply (safe) apply(cut_tac a = p and c = "q \<squnion> r" and b = "-q" and d = "-q" in inf_mono) apply simp apply simp apply (simp add: inf_sup_distrib2) apply(cut_tac b = "p \<sqinter> - q" and d = "r" and a = "q" and c = "q" in sup_mono) apply simp apply simp by (simp add: sup_inf_distrib) lemma hoare_if: "hoare p (If b then x else y) q = (hoare (p \<sqinter> b) x q \<and> hoare (p \<sqinter> -b) y q)" by (simp add: hoare_def if_stm_def wp_choice inf_fun_def wp_comp wp_assume sup_neg_inf) lemma hoare_comp: "hoare p (x * y) q = (\<exists> r . (hoare p x r) \<and> (hoare r y q))" apply (simp add: hoare_def wp_comp) apply safe apply (rule_tac x = "wp y q" in exI, simp) apply (rule_tac y = "wp x r" in order_trans, simp) apply (rule_tac f = "wp x" in monoD) by simp_all lemma hoare_refinement: "hoare p S q = ({\<cdot>p} * (post {\<cdot>q}) \<le> S)" apply (simp add: hoare_def less_eq_Assertion_def Assertion_wp) proof assume A: "{\<cdot>p} \<le> S * {\<cdot>q} * \<top>" have "{\<cdot>p} * post {\<cdot>q} = ({\<cdot>p} * \<top> \<sqinter> 1) * post {\<cdot>q}" by (simp add: assertion_prop) also have "\<dots> = {\<cdot>p} * \<top> \<sqinter> post {\<cdot>q}" by (simp add: inf_comp) also have "\<dots> \<le> S * {\<cdot>q} * \<top> \<sqinter> post {\<cdot>q}" apply simp apply (rule_tac y = "{\<cdot>p} * \<top>" in order_trans, simp_all) apply (cut_tac x = "{\<cdot>p}" and y = "S * {\<cdot>q} * \<top>" and z = \<top> in le_comp_right) by (rule A, simp) also have "\<dots> \<le> S" by (simp add: post_2) finally show "{\<cdot>p} * post {\<cdot>q} \<le> S". next assume A: "{\<cdot>p} * post {\<cdot>q} \<le> S" have "{\<cdot>p} = {\<cdot>p} * \<top> \<sqinter> 1" by (simp add: assertion_prop) also have "\<dots> = {\<cdot>p} * ((post {\<cdot>q}) * {\<cdot>q} * \<top>) \<sqinter> 1" by (simp add: post_1) also have "\<dots> \<le> {\<cdot>p} * ((post {\<cdot>q}) * {\<cdot>q} * \<top>)" by simp also have "\<dots> \<le> S * {\<cdot>q} * \<top>" apply (cut_tac x = "{\<cdot>p} * post {\<cdot>q}" and y = S and z = "{\<cdot>q} * \<top>" in le_comp_right) apply (simp add: A) by (simp add: mult.assoc) finally show "{\<cdot>p} \<le> S * {\<cdot>q} * \<top>" . qed theorem hoare_fixpoint_mbt: "F x = x \<Longrightarrow> (!! (w::'a::well_founded) f . (\<And>v. v < w \<Longrightarrow> hoare (p v) f q) \<Longrightarrow> hoare (p w) (F f) q) \<Longrightarrow> hoare (p u) x q" apply (rule less_induct1) proof - fix xa assume A: "\<And> w f. (\<And> v . v < w \<Longrightarrow> hoare (p v) f q) \<Longrightarrow> hoare (p w) (F f) q" assume B: "F x = x" assume C: "\<And>y . y < xa \<Longrightarrow> hoare (p y) x q" have D: "hoare (p xa) (F x) q" apply (rule A) by (rule C, simp) show "hoare (p xa) x q" by (cut_tac D, simp add: B) qed lemma hoare_Sup: "hoare (Sup P) x q = (\<forall> p \<in> P . hoare p x q)" apply (simp add: hoare_def) apply auto apply (rule_tac y = "Sup P" in order_trans, simp_all add: Sup_upper) apply (rule Sup_least) by simp theorem hoare_fixpoint_complete_mbt: "F x = x \<Longrightarrow> (!! w f . hoare (Sup_less p w) f q \<Longrightarrow> hoare (p w) (F f) q) \<Longrightarrow> hoare (Sup (range p)) x q" apply (simp add: hoare_Sup Sup_less_def, safe) apply (rule_tac F = F in hoare_fixpoint_mbt) by auto definition while:: "'a::mbt_algebra Assertion \<Rightarrow> 'a \<Rightarrow> 'a" ("(While (_)/ do (_))" [0, 10] 10) where "while p x = ([\<cdot> p] * x) ^ \<omega> * [\<cdot> -p ]" lemma while_false: "(While \<bottom> do x) = 1" apply (unfold while_def) apply (subst omega_fix) by (simp_all add: assume_def) lemma while_true: "(While \<top> do 1) = \<bottom>" apply (unfold while_def) by (rule antisym, simp_all add: assume_def) lemma hoare_wp [simp]: "hoare (wp x q) x q" by (simp add: hoare_def) lemma hoare_comp_wp: "hoare p (x * y) q = hoare p x (wp y q)" apply (unfold hoare_comp, safe) apply (simp add: hoare_def) apply (rule_tac y = "wp x r" in order_trans, simp) apply (rule wp_mono2, simp) by (rule_tac x = "wp y q" in exI, simp) lemma (in mbt_algebra) hoare_assume: "hoare p [\<cdot>b] q = (p \<sqinter> b \<le> q)" by (simp add: hoare_def wp_assume sup_neg_inf) lemma hoare_while_mbt: "(\<forall> (w::'b::well_founded) r . (\<forall> v . v < w \<longrightarrow> p v \<le> r) \<longrightarrow> hoare ((p w) \<sqinter> b) x r) \<Longrightarrow> (\<forall> u . p u \<le> q) \<Longrightarrow> hoare (p w) (While b do x) (q \<sqinter> -b)" apply (unfold while_def) apply (rule_tac F = "\<lambda>z. [\<cdot> b ] * x * z \<sqinter> [\<cdot> - b ]" in hoare_fixpoint_mbt) apply (simp add: mult.assoc [THEN sym]) apply (simp add: omega_comp_fix) apply (unfold hoare_choice) apply safe apply (subst hoare_comp_wp) apply (subst hoare_assume_comp) apply (drule_tac x = w in spec) apply (drule_tac x = "wp f (q \<sqinter> - b)" in spec) apply (auto simp add: hoare_def) [1] apply (auto simp add: hoare_assume) apply (rule_tac y = "p w" in order_trans) by simp_all lemma hoare_while_complete_mbt: "(\<forall> w::'b::well_founded . hoare ((p w) \<sqinter> b) x (Sup_less p w)) \<Longrightarrow> hoare (Sup (range p)) (While b do x) ((Sup (range p)) \<sqinter> -b)" apply (simp add: hoare_Sup, safe) apply (rule hoare_while_mbt) apply safe apply (drule_tac x = w in spec) apply (simp add: hoare_def) apply (rule_tac y = "wp x (Sup_less p w)" in order_trans, simp_all) apply (rule wp_mono2) apply (simp add: Sup_less_def) apply (rule Sup_least, auto) by (rule SUP_upper, simp) definition "datarefin S S1 D D1 = (D * S \<le> S1 * D1)" lemma "hoare p S q \<Longrightarrow> datarefin S S1 D D1 \<Longrightarrow> hoare (wp D p) S1 (wp D1 q)" apply (simp add: hoare_def datarefin_def) apply (simp add: wp_comp [THEN sym] mult.assoc [THEN sym]) apply (rule_tac y = "wp (D * S) q" in order_trans) apply (subst wp_comp) apply (rule monoD, simp_all) by (rule wp_fun_mono2, simp_all) lemma "hoare p S q \<Longrightarrow> datarefin ({\<cdot>p} * S) S1 D D1 \<Longrightarrow> hoare (wp D p) S1 (wp D1 q)" apply (simp add: hoare_def datarefin_def) apply (rule_tac y = "wp (D * {\<cdot>p} * S) q" in order_trans) apply (simp add: mult.assoc) apply (subst wp_comp) apply (rule monoD, simp_all) apply (subst wp_comp) apply (unfold wp_assert, simp) apply (unfold wp_comp [THEN sym]) apply (rule wp_fun_mono2) by (simp add: mult.assoc) lemma inf_pres_conj: "x \<in> conjunctive \<Longrightarrow> y \<in> conjunctive \<Longrightarrow> x \<sqinter> y \<in> conjunctive" apply (subst conjunctive_def, safe) apply (simp add: inf_comp conjunctiveD) by (metis (hide_lams, no_types) inf_assoc inf_left_commute) lemma sup_pres_disj: "x \<in> disjunctive \<Longrightarrow> y \<in> disjunctive \<Longrightarrow> x \<squnion> y \<in> disjunctive" apply (subst disjunctive_def, safe) apply (simp add: sup_comp disjunctiveD) by (metis (hide_lams, no_types) sup_assoc sup_left_commute) lemma assumption_conjuncive [simp]: "[\<cdot>p] \<in> conjunctive" by (simp add: assume_def dual_disjunctive assertion_disjunctive) lemma assumption_disjuncive [simp]: "[\<cdot>p] \<in> disjunctive" by (simp add: assume_def dual_conjunctive assertion_conjunctive) lemma if_pres_conj: "x \<in> conjunctive \<Longrightarrow> y \<in> conjunctive \<Longrightarrow> (If p then x else y) \<in> conjunctive" apply (unfold if_stm_def) by (simp add: inf_pres_conj comp_pres_conj) lemma if_pres_disj: "x \<in> disjunctive \<Longrightarrow> y \<in> disjunctive \<Longrightarrow> (If p then x else y) \<in> disjunctive" apply (unfold if_assertion) by (simp add: sup_pres_disj comp_pres_disj assertion_disjunctive) lemma while_dual_star: "(While p do (x::'a::mbt_algebra)) = (({\<cdot> p} * x)^\<otimes> * {\<cdot> -p })" apply (simp add: while_def) apply (rule antisym) apply (rule omega_least) proof - have "([\<cdot> p] * x * (({\<cdot> p} * x)^\<otimes> * {\<cdot>-p}) \<sqinter> [\<cdot>-p]) = ({\<cdot> p} * x * (({\<cdot> p} * x)^\<otimes> * {\<cdot>-p})) \<squnion> {\<cdot>-p}" apply (unfold mult.assoc) by (cut_tac p = p and x = "(x * (({\<cdot> p } * x)^\<otimes> * {\<cdot> -p }))" and y = 1 in if_Assertion_assumption, simp) also have "\<dots> = ({\<cdot> p} * x)^\<otimes> * {\<cdot>-p}" by (simp add: mult.assoc [THEN sym], simp add: dual_star_comp_fix [THEN sym]) finally show "[\<cdot> p ] * x * (({\<cdot> p } * x)^\<otimes> * {\<cdot> - p }) \<sqinter> [\<cdot> - p ] \<le> ({\<cdot> p } * x)^\<otimes> * {\<cdot> - p }" by simp next show "({\<cdot> p } * x)^\<otimes> * {\<cdot> - p } \<le> ([\<cdot> p ] * x) ^ \<omega> * [\<cdot> - p ]" apply (rule dual_star_least) proof - have "{\<cdot> p } * x * (([\<cdot> p ] * x) ^ \<omega> * [\<cdot> - p ]) \<squnion> {\<cdot> - p } = [\<cdot> p ] * x * (([\<cdot> p ] * x) ^ \<omega> * [\<cdot> - p ]) \<sqinter> [\<cdot> - p ]" apply (unfold mult.assoc) by (cut_tac p = p and x = "(x * (([\<cdot>p] * x)^\<omega> * [\<cdot>-p]))" and y = 1 in if_Assertion_assumption, simp) also have "... = ([\<cdot> p ] * x) ^ \<omega> * [\<cdot> - p ]" apply (simp add: mult.assoc [THEN sym]) by (metis omega_comp_fix) finally show "{\<cdot> p } * x * (([\<cdot> p ] * x) ^ \<omega> * [\<cdot> - p ]) \<squnion> {\<cdot> - p } \<le> ([\<cdot> p ] * x) ^ \<omega> * [\<cdot> - p ] " by simp qed qed lemma while_pres_disj: "(x::'a::mbt_algebra) \<in> disjunctive \<Longrightarrow> (While p do x) \<in> disjunctive" apply (unfold while_dual_star) apply (rule comp_pres_disj) apply (rule dual_star_pres_disj) by (rule comp_pres_disj, simp_all add: assertion_disjunctive) lemma while_pres_conj: "(x::'a::mbt_algebra_fusion) \<in> conjunctive \<Longrightarrow> (While p do x) \<in> conjunctive" apply(unfold while_def) by (simp add: comp_pres_conj omega_pres_conj) no_notation bot ("\<bottom>") and top ("\<top>") and inf (infixl "\<sqinter>" 70) and sup (infixl "\<squnion>" 65) and Inf ("\<Sqinter>_" [900] 900) and Sup ("\<Squnion>_" [900] 900) no_syntax "_INF1" :: "pttrns \<Rightarrow> 'b \<Rightarrow> 'b" ("(3\<Sqinter>_./ _)" [0, 10] 10) "_INF" :: "pttrn \<Rightarrow> 'a set \<Rightarrow> 'b \<Rightarrow> 'b" ("(3\<Sqinter>_\<in>_./ _)" [0, 0, 10] 10) "_SUP1" :: "pttrns \<Rightarrow> 'b \<Rightarrow> 'b" ("(3\<Squnion>_./ _)" [0, 10] 10) "_SUP" :: "pttrn \<Rightarrow> 'a set \<Rightarrow> 'b \<Rightarrow> 'b" ("(3\<Squnion>_\<in>_./ _)" [0, 0, 10] 10) end
module Base.Free where -- Reexport definitions from Agda's standard library that are needed by the -- generated code. open import Function using (case_of_) public open import Data.Bool using (if_then_else_) public open import Size using (Size; ↑_) public -- The `Free` monad over a container with shapes `S` and postions `P`. data Free (S : Set) (P : S → Set) (A : Set) : Set where pure : A → Free S P A impure : (s : S) → (pf : P s → Free S P A) → Free S P A infixl 1 _>>=_ _>>=_ : {S : Set} {P : S → Set} {A : Set} {B : Set} → Free S P A → (A → Free S P B) → Free S P B pure x >>= k = k x impure s pf >>= k = impure s λ p → pf p >>= k
from SersicNFW import SersicNFW import numpy as np class SersicNFWdisk(object): def __init__(self,R0_fac=0.5): self.SersicNFW = SersicNFW(R0_fac=R0_fac) def params(self,R_ein=None, ellip=None, ellip_theta=None, x=None, y=None, Rs=None, n_sersic=None, reff_thetaE_ratio=None, f=None, fdisk=None, n_disk = 1, q_disk=None, reff_Rdisk_ratio=None,**kwargs): # as per Atlas 3d XVII I'm putting 20% of the total mass in the disk subparams = {} otherkwargs = {} otherkwargs['name'] = 'SERSIC_NFW_DISK' q = 1 - ellip subparams['q'] = q subparams['phi_G'] = (ellip_theta) * np.pi * 180 ** -1 subparams['q_disk'] = q_disk subparams['Rs'] = Rs subparams['center_x'] = x subparams['center_y'] = y subparams['R_sersic'] = reff_thetaE_ratio * R_ein subparams['n_sersic'] = n_sersic subparams['R_disk'] = reff_Rdisk_ratio * subparams['R_sersic'] subparams['n_sersic_disk'] = n_disk k_eff, ks_nfw = self.SersicNFW.normalizations(Rein=R_ein, re=subparams['R_sersic'], Rs=Rs, n=n_sersic, R0=self.SersicNFW.R0_fac * subparams['R_sersic'], f=f) subparams['k_eff'] = k_eff*(1-fdisk) subparams['k_eff_disk'] = k_eff * fdisk subparams['theta_Rs'] = 4 * ks_nfw * subparams['Rs'] * (1 + np.log(0.5)) return subparams, otherkwargs
\chapter{Increased memory bandwidth} Line $29$ of the function \texttt{MLDU\_Simple\_cell} is the obvious bottleneck of the implementation. This line gets called every iteration of the \texttt{for} loop and adds data to the matrix \texttt{A}. This addition of data requires many memory operations, which makes it slow. The performance of the main memory subsystem of a computer is comprised of two aspects, bandwidth and latency. Bandwidth is a measure of maximum throughput and latency is a measure of the access time.\\ \noindent This chapter tries to shed some light on which of the two main memory performance indicators is to blame for the poor performance of line $29$. \section{GPU} The GPU is interesting in this scenario because dedicated GPU's contains VRAM. Comparing VRAM to standard RAM, which makes up the main memory of a computer, reveals that VRAM has a much higher bandwidth than RAM. The downside is that VRAM has a somewhat higher latency than RAM.\\ \noindent Implementing the block MLDU algorithm on the GPU would make it possible to identify whether latency or bandwidth is to blame for the poor runtime of line $29$. A bandwidth bottleneck would result in a faster execution of line $29$ and a latency bottleneck would cause it to be slightly slower then on the CPU. \section{MATLAB Sparse gpuArray limitations} MATLAB facilitates GPGPU programming, but has limitations, especially when it comes to sparse matrices. The most notable limitations for the block MLDU algorithm are the inability to index in sparse gpuArrays and the fact that the "\textbackslash" operator is not feature complete.\\ \noindent These limitations make it very unappealing to write a "simple" MATLAB implementation of the block MLDU algorithm on the GPU. The overall performance will almost certainly be slower than the CPU implementation, because all the hacks required to get it functional will swamp any floating point performance benefits that the GPU has over the CPU.\\ \noindent Regardless, it will provide insight into the latency versus bandwidth question and as such is still valuable to this project. \newpage \subsection{The code} \lstinputlisting{code/MLDU_Simple_GPU.m} \subsection{Profiler results} \noindent The profiler results below are generated by running:\\ \noindent \texttt{[ E ] = Test\_Function\_1( 40, @MLDU\_Simple\_GPU )}\\ \noindent The total runtime of this reduced size test was about $16$ seconds, which is way slower than the \texttt{MLDU\_Simple\_cell} implementation, which takes about $0.4$ seconds. The error of \texttt{MLDU\_Simple\_GPU} was again reasonable at $2.9072e-14$. \begin{figure}[h!] \includegraphics[width=\linewidth]{figures/Profile_MLDU_Simple_GPU_1.eps} \centering \end{figure} \newpage \noindent The most interesting timing result for this discussion is that of line $26$ (above), which has a value of $0.405$. Line $29$ of \texttt{MLDU\_Simple\_cell} executes the same operation, but takes only $0.164$ seconds.\\ \noindent The profiler results of \texttt{[ E ] = Test\_Function\_1( 40, @MLDU\_Simple\_cell )} are provided below: \begin{figure}[h!] \includegraphics[width=\linewidth]{figures/Profile_MLDU_Simple_GPU_2.eps} \centering \end{figure} \noindent The clear result from \texttt{MLDU\_Simple\_GPU} is that it does not constitute an improvement. This may very well be down to the limiting aspects of MATLAB sparse gpuArrays, but further investigation would be required to know for certain. The second lesson from \texttt{MLDU\_Simple\_GPU} is that the operation at line $29$ or $26$ is latency bound.
(* pair constructing *) Inductive natprod : Type := | pair (n1 n2 : nat). (* getting first or second *) Definition fst (p : natprod) : nat := match p with | pair x y => x end. Definition snd (p : natprod) : nat := match p with | pair x y => y end. Compute fst(pair 1 2). (* 1 *) Notation "( x , y )" := (pair x y). Definition swap_pair (p : natprod) : natprod := match p with | (x,y) => (y,x) end. (* Note that pattern-matching on a pair (with parentheses: (x, y)) is not to be confused with the "multiple pattern" syntax (with no parentheses: x, y) that we have seen previously. The above examples illustrate pattern matching on a pair with elements x and y, whereas, for example, the definition of minus in Basics performs pattern matching on the values n and m: *) Fixpoint minus (n m : nat) : nat := match n, m with | O , _ => O | S _ , O => n | S n', S m' => minus n' m' end. (* The distinction is minor, but it is worth knowing that they are not the same. *) (* Now let's try to prove a few simple facts about pairs. If we state properties of pairs in a slightly peculiar way, we can sometimes complete their proofs with just reflexivity (and its built-in simplification): *) Theorem surjective_pairing' : forall (n m : nat), (n,m) = (fst (n,m), snd (n,m)). Proof. reflexivity. Qed. (* But just reflexivity is not enough if we state the lemma in the most natural way: *) Theorem surjective_pairing_stuck : forall (p : natprod), p = (fst p, snd p). Proof. simpl. (* Doesn't reduce anything! *) Abort. (* Instead, we need to expose the structure of p so that simpl can perform the pattern match in fst and snd. We can do this with destruct. *) Theorem surjective_pairing : forall (p : natprod), p = (fst p, snd p). Proof. intros p. destruct p as [n m]. simpl. reflexivity. Qed. (* Notice that, unlike its behavior with nats, where it generates two subgoals, destruct generates just one subgoal here. That's because natprods can only be constructed in one way. *)
module Brainfeck.VM import Data.Fin import Data.Vect as V import Prelude.List as L import Brainfeck.Type %default total export Cell : Type Cell = Int export data Tape : (left : Nat) -> (right : Nat) -> (size : Nat) -> Type where MkTape : Vect left Cell -> Cell -> Vect right Cell -> Tape left right (left + right) %name Tape tape namespace Tape left : Tape left right size -> Vect left Cell left (MkTape xs _ _) = xs leftLength : Tape left right size -> Nat leftLength (MkTape xs _ _) = length xs right : Tape left right size -> Vect right Cell right (MkTape _ _ ys) = ys rightLength : Tape left right size -> Nat rightLength (MkTape _ _ ys) = length ys length : Tape left right size -> Nat length tape = leftLength tape + rightLength tape current : Tape left right size -> Cell current (MkTape _ c _) = c set_current : Cell -> Tape left right size -> Tape left right size set_current c' (MkTape l c r) = MkTape l c' r initTape : (size : Nat) -> Tape 0 size size initTape size = MkTape V.Nil 0 (V.replicate size 0) shiftLeft : Tape (S l) r ((S l) + r) -> Tape l (S r) (l + (S r)) shiftLeft {l} {r} (MkTape (x :: xs) c ys) = tape' where tape' = MkTape xs x (c :: ys) shiftRight : Tape l (S r) (l + (S r)) -> Tape (S l) r ((S l) + r) shiftRight {l} {r} (MkTape xs c (y :: ys)) = tape' where tape' = MkTape (c :: xs) y ys extend : Tape left right (left + right) -> Tape left (right + k) (left + (right + k)) extend {left} {right} {k} (MkTape xs c ys) = tape' where tape' = MkTape xs c (extendVect ys) extendVect : Vect n Cell -> Vect (n + k) Cell extendVect [] = replicate _ 0 extendVect (x :: xs) = x :: extendVect xs public export record VMState (tapeLeft : Nat) (tapeRight : Nat) (instructionCount : Nat) where constructor VM pc : Fin instructionCount instructions : Instructions instructionCount cells : Tape tapeLeft tapeRight (tapeLeft + tapeRight) %name VMState vm export instruction : VMState l r i -> Operation i instruction vm = index (pc vm) (instructions vm) public export InitialVMSize : Nat InitialVMSize = 1000 public export InitialVM : (instructionCount : Nat) -> Type InitialVM instructionCount = VMState 0 InitialVMSize instructionCount export initVM : Instructions (S n) -> InitialVM (S n) initVM instructions = VM 0 instructions (initTape _) export growVM : (vm : VMState left right is) -> VMState left (right + (left + right)) is growVM {left} {right} vm = VM (pc vm) (instructions vm) extendedCells where extendedCells : Tape left (right + (left + right)) (left + (right + (left + right))) extendedCells = extend (cells vm) {k = left + right} ------------------------------------------------- -- Operations ------------------------------------------------- -- < export shiftLeft : VMState (S left) right is -> VMState left (S right) is shiftLeft {left} {right} vm = VM (pc vm) (instructions vm) cells' where cells' = Tape.shiftLeft . cells $ vm -- > -- This was going to also increase the size of the vm if Right = Z, but -- that really complicates the type. export shiftRight : VMState left (S right) is -> VMState (S left) right is shiftRight {right} vm = VM (pc vm) (instructions vm) cells' where cells' = Tape.shiftRight . cells $ vm updateCell : (Cell -> Cell) -> VMState left right is -> VMState left right is updateCell f = record { cells->current $= f } -- + export increment : VMState left right is -> VMState left right is increment = updateCell (+1) -- - export decrement : VMState left right is -> VMState left right is decrement = updateCell (\c => c - 1) -- . export outputChar : VMState left right is -> Char outputChar = chr . record { cells->current } -- , export inputChar : Char -> VMState left right is -> VMState left right is inputChar c = record { cells->current = (ord c) } -- [ export jumpBack : VMState left right (S is) -> VMState left right (S is) jumpBack vm = case instruction vm of OJumpNZero l => if record { cells->current } vm == 0 then vm else record { pc = l } vm _ => vm -- ] export jumpForward : VMState left right (S is) -> VMState left right (S is) jumpForward vm = case instruction vm of OJumpZero l => if record { cells->current } vm == 0 then record { pc = l } vm else vm _ => vm
lemma measure_space_closed: assumes "measure_space \<Omega> M \<mu>" shows "M \<subseteq> Pow \<Omega>"
SUBROUTINE DGELUB(M,N,A,LDA,IPIV,INFO,NB) DOUBLE PRECISION A(LDA,N) INTEGER IPIV(N) * * This routine computes an LU factorization of an m-by-n * matrix A, using partial pivoting with row interchanges. * INFO = 0 DO 100, J = 1, N, Nb JB = MIN(N-J+1,NB) * * Apply previous interchanges to current block. * DO 20, I = 1, J-1 IP = IPIV(I) IF (IP.NE.I) CALL DSWAP (JB,A(I,J),LDA,A(IP,J),LDA) 20 CONTINUE * * Compute superdiagonal block of U. * CALL DTRSM ('Left','Lower','No transpose','Unit', $ J-1,JB,A(1,1),LDA,A(1,J),LDA) * * Update diagonal and subdiagonal blocks * CALL DGEMM ('No transpose','No transpose', $ M-J+1,JB,J-1,-1.0D0,A(J,1),LDA, $ A(1,J),LDA,1.0D0,A(J,J),LDA) * * Factorize diagonal and subdiagonal blocks. * CALL DGELU (M-J+1,JB,A(J,J),LDA,IPIV(J),INFO) DO 30, I = J, J+JB-1 IPIV(I) = J - 1 + IPIV(I) 30 CONTINUE * * Test for singularity. * IF (INFO.NE.0) GO TO 120 * * Apply interchanges to previous blocks. * DO 40, I = J, J+JB-1 IP = IPIV(J) IF (IP.NE.I) CALL DSWAP (J-1,A(I,1),LDA,A(IP,1),LDA) 40 CONTINUE 100 CONTINUE RETURN * 120 INFO = INFO + J - 1 RETURN END
// Author: Michael Kaufmann <[email protected]> // // Copyright (c) 2018, IBM Corporation, All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file. #include "scheduler/heteroscheduler.h" #include "common.h" #include "event/engine.h" #include "event/event.h" #include "helper/sorter.h" #include "resourcemanager/resourcemanager.h" #include "scheduler/oracle.h" #include <algorithm> #include <chrono> #include <cmath> #include <cstdlib> #include <future> #include <iostream> #include <string> #include <boost/functional/hash.hpp> #ifdef WITHGPERFTOOLS #include <gperftools/profiler.h> #endif #define RES_BAD (ULLONG_MAX / 2) /* There are 3 events that may cause a task to be executed. (1) An Executor becomes idle -> Interrupt scheduler (we need to run tabuCost on the best schedule to get the allocation for the best schedule). -> check the allocation list of the resource (executer) that is idle -> if there is a task, pick it, mark it as scheduled and enqueue it into the executor's task queue. -> if there is no task, add executor/resource to idleResource map. (2) A stage becomes ready -> Interrupt scheduler (we need to run tabuCost on the best schedule to get the allocation for the best schedule). -> Match executors from the idleResources map with the now-ready tasks from this stage. -> if there is a match, pick the task, mark it as scheduled and enqueue it into the executor's task queue. (3) A new best schedule is found -> Match all ready tasks with idle executors -> if there is a match, pick the task, mark it as scheduled and enqueue it into the executor's task queue. */ /* TODO: - All external events go into queues - Events are processed in a single thread - Only after all events have been processed we compute a new schedule. */ HeteroScheduler::HeteroScheduler(App *app, ResourceManager *resourcemanager) : SchedulerBase(app, resourcemanager), _schedule(NULL), numAssignedExecutors(0UL), numRequestedExecutors(0UL) { this->schedule(app->schedule()); this->oracle(new Oracle(app)); this->_time = baseTime; this->_train = config->getFlag(ConfigSchedulerFlags::training_mode); this->cfgIoTaskWeight = config->get(ConfigVariable::io_task_weight); this->cfgIoTaskIoWeight = config->get(ConfigVariable::io_task_io_weight); this->cfgCmpTaskWeight = config->get(ConfigVariable::cmp_task_weight); this->cfgCmpTaskIoWeight = config->get(ConfigVariable::cmp_task_io_weight); this->cfgNodeLoadWeight = config->get(ConfigVariable::node_load_weight); this->cfgInterferenceMode = config->get(ConfigVariable::interference_mode); this->cfgResourceScalingFactor = config->get(ConfigVariable::resource_scaling_factor); this->cfgLevelWeight = static_cast<double>(config->lweight()) / 10.0; engine->listen(EventType::Clock, std::bind(&HeteroScheduler::event, this, std::placeholders::_1)); engine->listen(EventType::Kill, std::bind(&HeteroScheduler::event, this, std::placeholders::_1)); engine->listen(EventType::Status, std::bind(&HeteroScheduler::event, this, std::placeholders::_1)); engine->listen(app->id(), EventType::ApplicationFinished, std::bind(&HeteroScheduler::event, this, std::placeholders::_1)); engine->listen(app->id(), 0, EventType::StageAdded, std::bind(&HeteroScheduler::event, this, std::placeholders::_1)); engine->listen(app->id(), 0, EventType::StageReady, std::bind(&HeteroScheduler::event, this, std::placeholders::_1)); engine->listen(app->id(), 0, EventType::StageFinished, std::bind(&HeteroScheduler::event, this, std::placeholders::_1)); engine->listen(app->id(), 0, EventType::TaskTimeout, std::bind(&HeteroScheduler::event, this, std::placeholders::_1)); engine->listen(app->id(), 0, EventType::TaskStarted, std::bind(&HeteroScheduler::event, this, std::placeholders::_1)); engine->listen(app->id(), 0, EventType::TaskFinished, std::bind(&HeteroScheduler::event, this, std::placeholders::_1)); engine->listen(app->id(), 1, EventType::ExecutorAdded, std::bind(&HeteroScheduler::event, this, std::placeholders::_1)); engine->listen(app->id(), 1, EventType::ExecutorDisabled, std::bind(&HeteroScheduler::event, this, std::placeholders::_1)); engine->listen(app->id(), 1, EventType::ExecutorEnabled, std::bind(&HeteroScheduler::event, this, std::placeholders::_1)); engine->listen(app->id(), 1, EventType::WorkerAllocationUpdate, std::bind(&HeteroScheduler::event, this, std::placeholders::_1)); } HeteroScheduler::~HeteroScheduler() { if (this->_oracle) { delete this->_oracle; this->_oracle = NULL; } } void HeteroScheduler::event(Event *ev) { if (ev->type() != EventType::Clock) logCDebug(LC_SCHED | LC_EVENT) << "Received event " << *ev; auto lock = std::unique_lock<std::mutex>(this->_eventMutex); this->_eventQueue.push(ev->copy()); this->_eventSignal.notify_all(); } void HeteroScheduler::waitForEvent() { auto lock = std::unique_lock<std::mutex>(this->_eventMutex); if (!this->_eventQueue.empty()) return; logInfo(2) << "Scheduler pauses..."; this->_eventSignal.wait(lock, [this] { return !this->_eventQueue.empty(); }); logInfo(2) << "Scheduler continues with " << this->_eventQueue.size() << " events..."; } bool HeteroScheduler::clockEventHandler(ClockEvent *ev) { assert(ev != NULL); this->_time = ev->time(); return false; } bool HeteroScheduler::statusEventHandler(StatusEvent *ev) { assert(ev != NULL); logCInfo(LC_SCHED) << "Scheduler status for " << this->app()->id() << " (" << this->app()->name() << ")"; // 1. Determine which stages need to be scheduled. for (auto &entry : this->_schedule->stages) { Stage *stage = entry.second.stage; StageSchedule *schedule = &this->_schedule->stages.at(stage->nid()); if (stage->state() >= TaskState::finished) { if (schedule->usedPool.size() + schedule->freePool.size() > 0) { logCWarn(LC_SCHED) << " - stage " << stage->id() << " (" << stage->state() << ") with " << schedule->nFinishedTasks << "/" << schedule->nTasks << " finished/total tasks has " << schedule->usedPool.size() << "/" << schedule->freePool.size() << " used/free executors with a target of " << schedule->targetPoolSize; } continue; } if (stage->unsatDeps() != 0) continue; logCInfo(LC_SCHED) << " - stage " << stage->id() << " (" << stage->state() << ") with " << schedule->nFinishedTasks << "/" << schedule->nTasks << " finished/total tasks has " << schedule->usedPool.size() << "/" << schedule->freePool.size() << " used/free executors with a target of " << schedule->targetPoolSize; } return false; } bool HeteroScheduler::taskStartedEventHandler(TaskStartedEvent *ev) { assert(ev != NULL); bool reschedule = false; Executor *executor = ev->executor(); Task * task = ev->task(); auto guard = task->guard(); if (task->type() == TaskType::idle || task->type() == TaskType::disconnect) return false; Stage *stage = task->stage(); // Resource *resource = task->allocation()->resource(); Duration runtime = task->allocation()->duration(); Time planned = task->allocation()->from(); Time actual = Time::now(); Duration tolerance = Duration(std::min(10000us, runtime / 10)); if (planned + tolerance < actual) { // Starts a bit too late reschedule = true; } else if (planned - tolerance > actual) { // Starts a bit too early reschedule = true; } else { // just fine. } task->metrics().started(actual); Time from = task->metrics().started(); Time to = from + runtime; return reschedule; } bool HeteroScheduler::taskTimeoutEventHandler(TaskTimeoutEvent *ev) { assert(ev != NULL); bool reschedule = false; Executor *executor = ev->executor(); Task * task = ev->task(); auto guard = task->guard(); if (task->type() == TaskType::idle || task->type() == TaskType::disconnect) return false; if (task->state() == TaskState::running) { logCInfo(LC_SCHED) << "Task " << task->id() << " on " << "executor " << executor->id() << " timed out."; Duration planned = task->allocation()->duration(); Duration extra = std::max(Duration(10ms), Duration(planned.count() / 5)); } return reschedule; } bool HeteroScheduler::taskFinishedEventHandler(TaskFinishedEvent *ev) { assert(ev != NULL); bool reschedule = false; Executor *executor = ev->executor(); Task * task = ev->task(); auto guard = task->guard(); Stage * stage = task->stage(); if (task->type() == TaskType::idle) { logCInfo(LC_SCHED) << "Task " << task->id() << " on executor " << executor->id() << " finished"; // Idle tasks are always ready // Disconnect tasks are always ready task->state(TaskState::finished); task->state(TaskState::ready); } else if (task->type() == TaskType::disconnect) { logCInfo(LC_SCHED) << "Task " << task->id() << " on executor " << executor->id() << " finished"; task->state(TaskState::finished); task->state(TaskState::ready); // Remove executor from pool. numAssignedExecutors was decremented once the free was // initiated. So don't do it here again. logCInfo(LC_SCHED) << "Removing executor " << executor->id() << " from executor pool"; this->_schedule->executorPool.get(executor); if (this->app()->state() == TaskState::finished && this->_schedule->executorPool.size() == 0) { engine->signal(new ApplicationFinishedEvent(this->app())); } } else { logCInfo(LC_SCHED) << "Task " << task->id() << " on executor " << executor->id() << " finished"; this->_schedule->finish(task); task->state(TaskState::finished); Node *node = executor->node(); switch (this->cfgInterferenceMode) { case 0: // ignore interference task->metrics().ioLoad(0); break; case 1: // count each task task->metrics().ioLoad(1); break; case 2: // count each I/O task task->metrics().ioLoad(task->type() == TaskType::load); break; case 3: // count total task input data volume task->metrics().ioLoad(task->metrics().inData()); break; case 4: // same as (3) but over time task->metrics().ioLoad(task->metrics().inData() / task->metrics().runtime().count()); break; case 5: // count remote task input data volume task->metrics().ioLoad(task->metrics().inData() - task->metrics().inData(node)); break; case 6: // same as (5) but over time task->metrics().ioLoad((task->metrics().inData() - task->metrics().inData(node)) / task->metrics().runtime().count()); break; } this->_oracle->update(task); reschedule = true; // TODO: Here the now idle executor should just take a task from the // queue. Also, recompute stage weights. } if (!(task->type() == TaskType::idle || task->type() == TaskType::disconnect)) { // // If we have more tasks than we should have, free this one. // if (schedule->targetPoolSize > this->_schedule->maxNumExecutors) { // } else { StageSchedule &ssched = this->_schedule->stages.at(stage->nid()); // Check whether to release an executor to (1) the application, in case the stage exceeds // its allowed share and (2) to the resource manager, in case the application also exceeds // its allowed share. if (ssched.targetPoolSize < ssched.usedPool.size() + ssched.freePool.size()) { ssched.usedPool.get(executor); this->release(executor); } else { ssched.usedPool.get(executor); ssched.freePool.put(executor); } if (stage->state() == TaskState::finished) { // Execute deferred stage finish in case the finish for this task came in after the finish // event for the stage. engine->signal(new StageFinishedEvent(stage->app(), stage)); } // } } this->requestResources(); return true; //reschedule; } bool HeteroScheduler::stageAddedEventHandler(StageAddedEvent *ev) { assert(ev != NULL); this->app()->addStages(ev->stages()); for (auto &entry : ev->stages()) { Stage *stage = entry.first; stage->state(TaskState::unready); // Add new stage to the oracle cache. if (config->getFlag(ConfigSchedulerFlags::consider_io_size)) { if (stage->type() == TaskType::load) { this->oracle()->preset(stage); } stage->sortTasks(); // sort tasks according to their input size so that we can schedule // the "big" ones first. } if (this->_oracleCache.find(stage->key()) == this->_oracleCache.end()) { this->_oracleCache.emplace(stage->key(), OracleCache(this->oracle(), stage->key())); } for (Task *task : stage->tasks()) { task->scheduler(this); } #if 0 std::set<Node *> nodes; for (auto &resourceClass : this->_schedule->resources) { for (Resource *resource : resourceClass.second) { nodes.emplace(resource->node()); } } for (Task *task : stage->tasks()) { logInfo(0) << "Task " << task->id() << " reads " << task->metrics().inData() << " in total " << " (" << &task->metrics() << ")";; for (Node *node : nodes) { logInfo(0) << " - " << task->metrics().inData(node) << " from node " << node->id(); } for (auto &resourceClass : this->_schedule->resources) { for (Resource *resource : resourceClass.second) { logInfo(0) << " - " << task->metrics().inData(resource->executor()) << " from executor " << resource->executor()->id() << " (" << resource->id() << ")"; } } } #endif logInfo(0) << "Stage " << stage->id() << " has been added to " << this->app()->id(); stage->mark(0); stage->weight(this->getStageWeight(stage)); } // this->app()->unlock(1); this->requestResources(); return false; } bool HeteroScheduler::stageReadyEventHandler(StageReadyEvent *ev) { assert(ev != NULL); Stage *stage = ev->stage(); logInfo(0) << "Stage " << stage->id() << " is ready"; if (config->getFlag(ConfigSchedulerFlags::consider_io_size)) { stage->sortTasks(); } #if 0 std::set<Node *> nodes; for (auto &resourceClass : this->_schedule->resources) { for (Resource *resource : resourceClass.second) { nodes.emplace(resource->node()); } } for (Task *task : stage->tasks()) { logInfo(0) << "Task " << task->id() << " reads " << task->metrics().inData() << " in total"; for (Node *node : nodes) { logInfo(0) << " - " << task->metrics().inData(node) << " from node " << node->id(); } for (auto &resourceClass : this->_schedule->resources) { for (Resource *resource : resourceClass.second) { logInfo(0) << " - " << task->metrics().inData(resource->executor()) << " from executor " << resource->executor()->id() << " (" << resource->id() << ")"; } } } #endif this->_schedule->nextStages.erase(stage); stage->state(TaskState::ready); this->requestResources(); for (auto out : stage->next()) { Stage *cs = out->dst(); bool nextSet = true; for (auto out : stage->next()) { Stage *ps = out->dst(); if (ps->state() < TaskState::ready) { nextSet = false; break; } } if (nextSet) this->_schedule->nextStages.emplace(cs); } return true; } bool HeteroScheduler::stageFinishedEventHandler(StageFinishedEvent *ev) { assert(ev != NULL); Stage * stage = ev->stage(); StageSchedule &schedule = this->_schedule->stages.at(stage->nid()); if (schedule.nTasks > schedule.nFinishedTasks) { if (schedule.nAssignedTasks > 0) { stage->state(TaskState::finished); logCWarn(LC_SCHED) << "Deferring stage " << stage->id() << " finish event. Some tasks are not done yet: " << schedule.nFreeTasks << "/" << schedule.nAssignedTasks << schedule.nFinishedTasks; } // this->dumpAllocations(); assert(schedule.nAssignedTasks == (schedule.nTasks - schedule.nFinishedTasks)); return false; } else { stage->state(TaskState::finished); logCInfo(LC_SCHED) << "Stage " << stage->id() << " has finished. Remaining resources are"; assert(schedule.usedPool.size() == 0); // for (Executor *executor : schedule.usedPool.pool()) { // logCInfo(LC_SCHED) << " - " << executor->id() << " (" << executor->state() << ")"; // } Executor *executor = schedule.freePool.take(); while (executor != NULL) { logCInfo(LC_SCHED) << " - " << executor->id() << " (" << executor->state() << ") -> releasing"; this->release(executor); executor = schedule.freePool.take(); } } this->requestResources(); return true; } bool HeteroScheduler::applicationFinishedEventHandler(ApplicationFinishedEvent *ev) { assert(ev != NULL); App *app = ev->app(); // engine->signal(new ApplicationDemandsChangedEvent(this->app(), 0)); app->state(TaskState::finished); size_t nex = this->_schedule->executorPool.size(); if (nex > 0) { logCInfo(LC_SCHED) << "Application " << app->id() << " is finished. Disconnecting remaining " << nex << " executors."; Executor *executor = this->_schedule->freePool.take(); while (executor != NULL) { Worker *worker = executor->worker(); logCInfo(LC_RM | LC_SCHED) << " - disconnecting worker " << worker->id() << " from finished application " << app->id(); logCInfo(LC_SCHED) << "Removing executor " << executor->id() << " from free pools"; this->numAssignedExecutors--; executor->disconnect(); executor = this->_schedule->freePool.take(); } } else { logCInfo(LC_SCHED) << "Application " << app->id() << " is finished. All executors have been disconnected."; } return false; } bool HeteroScheduler::executorAddedEventHandler(ExecutorAddedEvent *ev) { assert(ev != NULL); Executor *executor = ev->executor(); if (executor->worker()->app() == this->app()) { logCInfo(LC_SCHED) << "Adding executor " << executor->id() << " to both pools"; // assert(this->numAssignedExecutors == this->_schedule->executorPool.size()); this->_schedule->executorPool.put(executor); this->_schedule->freePool.put(executor); this->numAssignedExecutors++; Worker *worker = executor->worker(); logCInfo(LC_SCHED) << "Adding worker " << worker->id() << " with executor " << executor->id() << " (" << executor << ")" << " to application " << this->app()->id() << " which has now " << this->_schedule->executorPool.size() << " (" << this->numAssignedExecutors << ") executors"; // assert(this->numAssignedExecutors == this->_schedule->executorPool.size()); return true; } else return false; } bool HeteroScheduler::executorDisabledEventHandler(ExecutorDisabledEvent *ev) { assert(ev != NULL); bool reschedule = false; Executor *executor = ev->executor(); // for (Resource *resource : executor->resources()) { // reschedule |= resource->getNumAllocations() > 0; // } return reschedule; } bool HeteroScheduler::executorEnabledEventHandler(ExecutorEnabledEvent *ev) { assert(ev != NULL); return true; } bool HeteroScheduler::workerAllocationUpdateEventHandler(WorkerAllocationUpdateEvent *ev) { assert(ev != NULL); size_t allowed = ev->target(); size_t current = this->_schedule->maxNumExecutors; this->_schedule->maxNumExecutors = allowed; logCInfo(LC_RM | LC_SCHED) << "Global executor share of application " << this->app()->id() << " updated from " << current << " to " << allowed << " (currently used " << this->_schedule->executorPool.size() << ")"; // Release executors if we have too many while (this->numAssignedExecutors > this->_schedule->maxNumExecutors) { Executor *executor = this->_schedule->freePool.take(); if (executor) this->release(executor); else break; } return true; } void HeteroScheduler::run() { #ifdef WITHGPERFTOOLS ProfilerStart("gperftools.log"); #endif App *app = this->app(); logCInfo(LC_SCHED) << "Starting scheduler for " << app->id(); app->state(TaskState::running); bool appFinished = false; bool executorsReleased = false; while (!appFinished || !executorsReleased) { bool reschedule = false; uint nevents = 0; // Idle while there's no work. this->waitForEvent(); logInfo(2) << "Processing events..."; auto lock = std::unique_lock<std::mutex>(this->_eventMutex); while (!this->_eventQueue.empty()) { Event *ev = this->_eventQueue.front(); lock.unlock(); if (ev->type() != EventType::Clock) logCDebug(LC_SCHED | LC_EVENT) << "Processing event " << *ev; switch (ev->type()) { case EventType::Clock: reschedule |= this->clockEventHandler(static_cast<ClockEvent *>(ev)); break; case EventType::Status: reschedule |= this->statusEventHandler(static_cast<StatusEvent *>(ev)); break; case EventType::TaskStarted: reschedule |= this->taskStartedEventHandler(static_cast<TaskStartedEvent *>(ev)); break; case EventType::TaskTimeout: reschedule |= this->taskTimeoutEventHandler(static_cast<TaskTimeoutEvent *>(ev)); break; case EventType::TaskFinished: reschedule |= this->taskFinishedEventHandler(static_cast<TaskFinishedEvent *>(ev)); break; case EventType::StageAdded: reschedule |= this->stageAddedEventHandler(static_cast<StageAddedEvent *>(ev)); break; case EventType::StageReady: reschedule |= this->stageReadyEventHandler(static_cast<StageReadyEvent *>(ev)); break; case EventType::StageFinished: reschedule |= this->stageFinishedEventHandler(static_cast<StageFinishedEvent *>(ev)); break; case EventType::ApplicationFinished: reschedule |= this->applicationFinishedEventHandler( static_cast<ApplicationFinishedEvent *>(ev)); engine->signal(new ApplicationDemandsChangedEvent(this->app(), 0)); appFinished = true; break; case EventType::ExecutorAdded: reschedule |= this->executorAddedEventHandler(static_cast<ExecutorAddedEvent *>(ev)); break; case EventType::ExecutorDisabled: reschedule |= this->executorDisabledEventHandler(static_cast<ExecutorDisabledEvent *>(ev)); break; case EventType::ExecutorEnabled: reschedule |= this->executorEnabledEventHandler(static_cast<ExecutorEnabledEvent *>(ev)); break; case EventType::WorkerAllocationUpdate: reschedule |= this->workerAllocationUpdateEventHandler( static_cast<WorkerAllocationUpdateEvent *>(ev)); break; case EventType::Kill: logInfo(0) << "Shutting down scheduler for " << this->app()->id() << "..."; engine->signal(new ApplicationDemandsChangedEvent(this->app(), 0)); appFinished = true; break; default: logError << "Unhandled event " << *ev; break; } executorsReleased = this->_schedule->executorPool.size() == 0; delete ev; lock.lock(); this->_eventQueue.pop(); nevents++; } lock.unlock(); if (reschedule) { // auto guard = this->app()->guard(1); Time t0 = Time::now(); this->updateExecutorShares(); this->assignExecutors(); this->scheduleApp(); Time t1 = Time::now(); if ((t1 - t0).count() > 1000) logCDebug(LC_SCHED) << "Schedule recomputed (" << (t1 - t0) << ") after processing " << nevents << " events"; logCInfo(LC_SCHED) << "Releasing guard 1"; // guard.unlock(); } } logInfo(0) << "Stopping scheduler for " << app->id(); #ifdef WITHGPERFTOOLS ProfilerStop(); #endif } void HeteroScheduler::dumpAllocations() { if (this->app()->state() == TaskState::finished) { logCInfo(LC_SCHED) << "All allocations for " << this->app()->id() << ". Application finished. Skipping"; return; } logCInfo(LC_SCHED) << "All allocations for " << this->app()->id(); // for (auto &resourceClass : this->_schedule->resourcePool.pool()) { // for (Resource *resource : resourceClass.second) { // logCInfo(LC_SCHED) << " >>> " << resource->id() << " (" << resource->state() // << ") managed by executor " << resource->executor()->id() << " on host " // << resource->executor()->worker()->node()->id() << " (utilization " << std::fixed // << std::setprecision(3) << resource->utilization() << ")"; // resource->dumpAllocations(); // } // } } double HeteroScheduler::getStageWeight(Stage *stage) { double weight = 0UL; StageId sid = stage->nid(); StageKey skey = stage->key(); StageSchedule &ssched = this->_schedule->stages.at(sid); // OracleCache & oc = this->_oracleCache.at(skey); uint64_t numUnassignedTasks = ssched.nTasks - ssched.nFinishedTasks; // for (auto ru : utilization) { // ResourceKey rkey = ru.first; // size_t rsize = ru.second.first; // double rutil = ru.second.second; // uint64_t runtime = EXECOST(rkey, stage->metrics().meanInData(), 0, 0, 0.0, 0).count(); // weight += (rsize * runtime * numUnassignedTasks) / (rsize - rutil); // } weight += numUnassignedTasks; return std::max(1.0, weight); } double HeteroScheduler::getPathWeight(Stage *stage) { double pw = stage->weight(); for (auto next : stage->next()) { Stage *cs = next->dst(); double cw = getPathWeight(cs); pw += cw + (cw * std::max(0, (cs->level() - 1)) * this->cfgLevelWeight); } return pw; } double HeteroScheduler::getPathWeights(std::multimap<double, Stage *, std::greater<double>> startStages) { double totPathWeights = 0.0; // Stages in 'startStages' may already be executed so their weight might change. All other // stages cannot be executed just yet, hence their weight will remain constant and doesn't need // to be recomputed (it is done once in stageAddedEventHandler and valid until they're being // executed). auto it = startStages.begin(); while (it != startStages.end()) { double weight = it->first; if (weight != -1.0) { // != -1 means we already looked at it.IBM it++; continue; } Stage *stage = it->second; // 1. Update this stage's weight stage->weight(this->getStageWeight(stage)); // 2. Update/compute the weight of the path from this stage to the end stage->weight(getPathWeight(stage)); // 3. Accumulate weights to compute relative weights later totPathWeights += stage->weight(); // // 4. // absPathWeights.emplace(stage->weight(), stage); it = startStages.erase(it); startStages.emplace(stage->weight(), stage); } // // 5. Compute relative weights // for (Stage *stage : startStages) { // double weight = stage->weight() / totalWeight; // relPathWeights.emplace(weight, stage); // } return totPathWeights; } void HeteroScheduler::scheduleApp() { logCInfo(LC_SCHED) << "Scheduling " << this->app()->id(); std::set<Stage *> toSchedule; // 1. Determine which stages need to be scheduled. for (auto &entry : this->_schedule->stages) { Stage *stage = entry.second.stage; if (stage->state() >= TaskState::finished) continue; if (stage->state() < TaskState::ready) continue; if (stage->unsatDeps() != 0) continue; toSchedule.emplace(stage); } // 3. Schedule stages this->_schedule->age++; for (Stage *stage : toSchedule) { StageId sid = stage->nid(); StageSchedule *ssched = &this->_schedule->stages.at(sid); logCDebug(LC_SCHED) << "Scheduling stage " << stage->id(); logCDebug(LC_SCHED) << " - free/assigned/finished tasks = " << ssched->nFreeTasks << " / " << ssched->nAssignedTasks << " / " << ssched->nFinishedTasks; logCDebug(LC_SCHED) << " - stage weight = " << std::setprecision(4) << stage->weight(); logCDebug(LC_SCHED) << " - free/used executors = " << ssched->freePool.size() << " / " << ssched->usedPool.size(); scheduleStage(stage); } // Release executors if we have too many while (this->numAssignedExecutors > this->_schedule->maxNumExecutors) { Executor *executor = this->_schedule->freePool.take(); if (executor) this->release(executor); else break; } this->_schedule->time = Time::now(); } void HeteroScheduler::scheduleStage(Stage *stage) { StageId sid = stage->nid(); StageSchedule *schedule = &this->_schedule->stages.at(sid); logCInfo(LC_SCHED) << "Scheduling " << stage->id() << " on " << schedule->freePool.size() << "+" << schedule->usedPool.size() << " idle/busy executors"; for (Task *task : stage->tasks()) { if (schedule->freePool.size() == 0) break; if (task->state() == TaskState::ready) this->scheduleTask(task, schedule); } } void HeteroScheduler::scheduleTask(Task *task, StageSchedule *schedule) { assert(task != NULL); assert(schedule != NULL); logCInfo(LC_SCHED) << "Scheduling " << "/" << task->id(); if (schedule->freePool.empty()) return; auto guard = task->guard(); Executor *executor = schedule->freePool.take(); schedule->usedPool.put(executor); schedule->assign(task, executor); task->state(TaskState::scheduled); task->allocation()->executor(executor); executor->add(task); } void HeteroScheduler::requestResources() { size_t currPar = 0; size_t nextPar = 0; size_t maxPar = 0; size_t nReqResources = 0; size_t nGotResources = this->_schedule->maxNumExecutors; // Determine the current demand for (auto &entry : this->_schedule->stages) { StageSchedule &ssched = entry.second; Stage * stage = ssched.stage; // TODO: Create edge set of all next stages if (stage->unsatDeps() == 0 && stage->state() >= TaskState::ready && stage->state() < TaskState::finished) { currPar += ssched.nTasks - ssched.nFinishedTasks; maxPar += ssched.nTasks; } } // Determine the near-term future demand for (auto stage : this->_schedule->nextStages) { nextPar += stage->size(); } // Keep at least 1 resource around (todo: replace by config option for minimal number of // executors) nReqResources = this->app()->state() == TaskState::finished ? 0UL : 1UL; // Try to get enough resources as we currently need for all running stages nReqResources = std::max(currPar, nReqResources); // Limit the number of resources depending on the resource scaling factor, but if we already // have it, use them - in theory that might be bad, but I think (!) in practice this makes jobs // (not stages) finish faster. Otherwise, towards the end of a job, we start releasing executors // though we still have pending tasks and I think that's not good - it just prolongs the end of // a job. // Sidenote: maxPar is being reduced if stages finish. nReqResources = std::min(static_cast<size_t>(maxPar * this->cfgResourceScalingFactor), nReqResources); if (currPar >= nGotResources) nReqResources = std::max(nReqResources, nGotResources); nReqResources = std::max(1UL, nReqResources); // TODO: Sometimes, when we reduce the number of executors it happens that we have some tasks // left but they can't be executed because we free them (because of RSF). I think we should only // reduce the number of executors once we really don't have any work for them anymore, i.e. if // maxPar < nGotResources to avoid this and to potentially speed up computation. // Try to keep around enough resources for the near term, but don't acquire extra resources! nReqResources = std::max(std::min(static_cast<size_t>(nextPar * this->cfgResourceScalingFactor), nGotResources), nReqResources); logCInfo(LC_RM | LC_SCHED) << "Updating resource requirements for application " << this->app()->id() << " to " << nReqResources << " executors for " << maxPar << "/" << nextPar << " current/future tasks (rsf=" << this->cfgResourceScalingFactor << ")"; if (nReqResources != this->numRequestedExecutors) engine->signal(new ApplicationDemandsChangedEvent(this->app(), nReqResources)); this->numRequestedExecutors = nReqResources; } // void HeteroScheduler::execute(Task *task, ResourceAllocationEntry *allocation) // { // assert(task != NULL); // assert(allocation != NULL); // assert(task->state() == TaskState::ready); // Executor *executor = resource->executor(); // if (task->type() != TaskType::idle && task->type() != TaskType::disconnect) { // Stage *stage = task->stage(); // // StageId sid = stage->nid(); // int tidx = task->index(); // logInfo(10) << "Executing task " << task->id() << " (" << task->state() << ") on " << resource->id() // << " (" << resource->state() << ") executor " << executor->id(); // this->_schedule->pin(task); // } // task->scheduler(this); // task->state(TaskState::scheduled); // executor->add(task); // } void HeteroScheduler::updateExecutorShares() { std::multimap<double, Stage *, std::greater<double>> toSchedule; // 1. Determine which stages need to be scheduled. for (auto &entry : this->_schedule->stages) { Stage *stage = entry.second.stage; if (stage->state() >= TaskState::finished) continue; if (stage->state() < TaskState::ready) continue; if (stage->unsatDeps() != 0) continue; toSchedule.emplace(-1.0, stage); // -1.0 means not computed yet for getPathWeights StageSchedule *schedule = &this->_schedule->stages.at(stage->nid()); schedule->targetPoolSize = 0; logCInfo(LC_SCHED) << "Updating executor share for stage " << stage->id(); } // 2. Determine/update weight of the paths that starts at each of those stages. double totalWeight = getPathWeights(toSchedule); double remainingWeight = totalWeight; size_t nTotalExecutors = std::min(this->_schedule->maxNumExecutors, this->numAssignedExecutors); size_t nRemainingExecutors = nTotalExecutors; size_t nAssignedExecutors = 0; logCInfo(LC_SCHED) << "Distributing " << nTotalExecutors << " executor(s) among " << toSchedule.size() << " stages"; // This algorithm does nothing else but match the relative shares (between 0 and 1) of each // stage to a number of executors. It's doing it very crude and inefficiently (it's looping // rather than determining it directly). The challenge here is to correctly handle fractions of // executors. We never want executors to go idle and we also don't want to deprive some stages // of their fair share. It's more or less identical to the one in the resource manager that // assigns workers to applications. while (nRemainingExecutors > nAssignedExecutors && toSchedule.size() > 0) { auto entry = toSchedule.begin(); while (entry != toSchedule.end() && nRemainingExecutors > nAssignedExecutors) { Stage * stage = entry->second; StageSchedule *schedule = &this->_schedule->stages.at(stage->nid()); uint demand = schedule->nTasks - schedule->nFinishedTasks; uint & assigned = schedule->targetPoolSize; double allowedShare = stage->weight() / remainingWeight; double currShare = static_cast<double>(assigned) / nRemainingExecutors; double nextShare = static_cast<double>(assigned + 1) / nRemainingExecutors; double currDiff = abs(currShare - allowedShare); double nextDiff = abs(nextShare - allowedShare); // FIXME: Problem: The number of resources for each stage can fluctuate by +/-1 as we // add more executors since of minor changes in the next/curr diff relative to the total // number of executors. So large stages may lose 1 executor to small stages. if (nextDiff < currDiff && assigned < demand) { logCDebug(LC_SCHED) << " - adding 1 executor to " << stage->id() << " (currDiff=" << currDiff << " nextDiff=" << nextDiff << ")"; assigned++; nAssignedExecutors++; entry++; } else { logCDebug(LC_SCHED) << " - not adding 1 executor to " << stage->id() << " (currDiff=" << currDiff << " nextDiff=" << nextDiff << ")"; // We're done with this stage remainingWeight -= stage->weight(); nRemainingExecutors -= assigned; nAssignedExecutors -= assigned; schedule->targetPoolSize = assigned; entry = toSchedule.erase(entry); } } } for (auto &entry : this->_schedule->stages) { Stage *stage = entry.second.stage; if (stage->state() >= TaskState::finished) continue; if (stage->state() < TaskState::ready) continue; if (stage->unsatDeps() != 0) continue; StageSchedule *schedule = &this->_schedule->stages.at(stage->nid()); logCInfo(LC_SCHED) << "- stage " << stage->id() << " (" << stage->state() << ") with weight " << stage->weight() << " has " << (schedule->freePool.size() + schedule->usedPool.size()) << " executors and gets " << schedule->targetPoolSize << " executors"; } } void HeteroScheduler::assignExecutors() { std::set<Stage *> toSchedule; // 1. Determine which stages need to be scheduled. for (auto &entry : this->_schedule->stages) { Stage *stage = entry.second.stage; if (stage->state() >= TaskState::finished) continue; if (stage->state() < TaskState::ready) continue; if (stage->unsatDeps() != 0) continue; toSchedule.emplace(stage); } // 2. Release resources if necessary and possible. for (Stage *stage : toSchedule) { StageSchedule *schedule = &this->_schedule->stages.at(stage->nid()); size_t nCurrentAllocations = schedule->usedPool.size() + schedule->freePool.size(); size_t nCurrentTarget = schedule->targetPoolSize; if (nCurrentTarget < nCurrentAllocations) { uint diff = nCurrentAllocations - nCurrentTarget; logCInfo(LC_RM) << "Releasing up to " << diff << " executors from stage " << stage->id() << " (new allocation=" << (nCurrentAllocations + 1) << " target=" << nCurrentTarget << " free=" << schedule->freePool.size() << ")"; while (!schedule->freePool.empty() && diff > 0) { Executor *executor = schedule->freePool.take(); if (executor) { this->release(executor); diff--; } } } } // 3. Distribute free executors among stages that need them. bool done = false; while (this->_schedule->freePool.size() > 0 && !done) { done = true; for (Stage *stage : toSchedule) { StageSchedule *schedule = &this->_schedule->stages.at(stage->nid()); size_t nCurrentAllocations = schedule->usedPool.size() + schedule->freePool.size(); size_t nCurrentTarget = schedule->targetPoolSize; if (nCurrentTarget > nCurrentAllocations) { Executor *executor = this->_schedule->freePool.take(); if (executor) { schedule->freePool.put(executor); logCInfo(LC_RM) << "Assigning executor " << executor->id() << " to stage " << stage->id() << " (new allocation=" << (nCurrentAllocations + 1) << " target=" << nCurrentTarget << ")"; done = false; } } } } } void HeteroScheduler::release(Executor *executor) { if (this->numAssignedExecutors <= this->_schedule->maxNumExecutors) { // Case 1: Release executor to the application so that other stages may use it. logCInfo(LC_SCHED) << "Releasing executor " << executor->id() << " back to the application " << this->app()->id(); this->_schedule->freePool.put(executor); } else { // Case 2: Release executor to the resoruce manager. this->numAssignedExecutors--; executor->disconnect(); logCInfo(LC_SCHED) << "Releasing executor " << executor->id() << " back to the resource manager"; } }
[STATEMENT] lemma integral_sin_nx: "integral {-pi..pi} (\<lambda>x. sin(x * real_of_int n)) = 0" [PROOF STATE] proof (prove) goal (1 subgoal): 1. integral {- pi..pi} (\<lambda>x. sin (x * real_of_int n)) = 0 [PROOF STEP] using has_integral_sin_nx [of n] [PROOF STATE] proof (prove) using this: ((\<lambda>x. sin (real_of_int n * x)) has_integral 0) {- pi..pi} goal (1 subgoal): 1. integral {- pi..pi} (\<lambda>x. sin (x * real_of_int n)) = 0 [PROOF STEP] by (force simp: mult.commute)
#include <cstring> #include <algorithm> #include "../ogl.h" #include <boost/weak_ptr.hpp> #include <boost/make_shared.hpp> #include <boost/bind.hpp> #include "Stage.h" #include "Uniforms.h" #include "TextureContext.h" #include "ErrorTracker.h" #include "../interface/Video.h" #include "../profile/Tracker.h" #include "../math/ViewGenerator.h" #include "../MessageSystem.h" #include "../ResourceRegistry.h" #include "../XMLResource.h" namespace Kriti { namespace Render { Stage::Stage() {} Stage::Stage(int outputs, int width, int height, std::string name) : m_name(name) { initialize(outputs, width, height); } bool Stage::loadFrom(std::string identifier) { auto node = ResourceRegistry::get<XMLResource>( "data" )->doc().first_element_by_path( "/kriti/render/" ).find_child_by_attribute( "stage", "name", identifier.c_str()); if(!node) return false; m_name = identifier; int outputs = node.child("outputs").text().as_int(1); int width = -1, height = -1; // TODO: support loading width/height from XML resource initialize(outputs, width, height); // add previous for(auto &child : node.children()) { if(std::strcmp(child.name(), "previous")) continue; std::string pname = child.text().as_string(""); auto prev = ResourceRegistry::get<Stage>(pname); if(!prev) { Message3(Render, Error, "Couldn't find previous stage " << pname); continue; } addPrevious(prev); } for(auto &child : node.children()) { if(std::strcmp(child.name(), "map")) continue; std::string fromString = child.attribute("from").as_string(); int from = 0; for(; from < m_previous.size(); from ++) if(m_previous[from]->name() == fromString) break; if(from == m_previous.size()) { Message3(Render, Error, "No previous stage " << fromString); continue; } std::string whichString = child.attribute("which").as_string(); const std::map<std::string, Framebuffer::Attachment> whichMap = { {"colour0", Framebuffer::ColourBuffer0}, {"colour1", Framebuffer::ColourBuffer1}, {"colour2", Framebuffer::ColourBuffer2}, {"colour3", Framebuffer::ColourBuffer3}, {"depth", Framebuffer::DepthBuffer} }; if(whichMap.count(whichString) == 0) { Message3(Render, Warning, "Unknown attachment: " << whichString); continue; } std::string materialString = child.attribute("material").as_string(); std::string uniform = child.attribute("to").as_string(); auto mat = ResourceRegistry::get<Render::Material>(materialString); addMapping(from, whichMap.at(whichString), mat, uniform); } return true; } void Stage::addMapping(int previousIndex, Framebuffer::Attachment attachment, boost::shared_ptr<Render::Material> material, std::string uniformName) { auto prev = m_previous[previousIndex]; addMapping(prev, attachment, material, uniformName); } void Stage::addMapping(boost::shared_ptr<Stage> prev, Framebuffer::Attachment attachment, boost::shared_ptr<Render::Material> material, std::string uniformName) { auto pfb = prev->framebuffer(); m_attachments.push_back(std::make_tuple(prev, attachment, material, uniformName)); } void Stage::render(Uniforms &globalParams, bool isLast) { Profile::Tracker::get()->beginGLTimer(m_name); if(!isLast) m_framebuffer->bindWrite(); else { gl::BindFramebuffer(gl::DRAW_FRAMEBUFFER, 0); gl::DrawBuffer(gl::BACK); } MaterialParams materialParams; for(auto &mapping : m_attachments) { auto fb = std::get<0>(mapping)->framebuffer(); auto texture = fb->getTextureAttachment(std::get<1>(mapping)); auto material = std::get<2>(mapping); materialParams[material].setParam(std::get<3>(mapping), texture); } gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT); m_renderables->draw(globalParams, materialParams); Profile::Tracker::get()->endGLTimer(m_name); } void Stage::initialize(int outputs, int width, int height) { if(width == -1) width = Interface::Video::get()->width(); if(height == -1) height = Interface::Video::get()->height(); m_width = width, m_height = height; m_framebuffer = boost::make_shared<Framebuffer>(); for(int i = 0; i < outputs; i ++) { boost::shared_ptr<Texture> texture; if(Interface::Video::get()->msaa()) { texture = boost::make_shared<Texture>(Texture::Colour, Texture::Simple, m_width, m_height, Interface::Video::get()->aasamples()); } else { texture = boost::make_shared<Texture>(Texture::Colour, Texture::Simple, m_width, m_height); } m_framebuffer->attach( Framebuffer::Attachment(Framebuffer::ColourBuffer0 + i), texture); } boost::shared_ptr<Renderbuffer> renderbuffer; if(Interface::Video::get()->msaa()) { renderbuffer = boost::make_shared<Renderbuffer>(Renderbuffer::Depth, m_width, m_height, Interface::Video::get()->aasamples()); } else { renderbuffer = boost::make_shared<Renderbuffer>(Renderbuffer::Depth, m_width, m_height); } m_framebuffer->attach(Framebuffer::DepthBuffer, renderbuffer); Profile::Tracker::get()->addGLTimer(m_name); m_renderables = boost::make_shared<RenderableContainer>(); } void Stage::renderRenderable(Uniforms &globalParams, MaterialParams &materialParams, boost::shared_ptr<Renderable> renderable) { ErrorTracker::trackFrom("Before renderable drawing"); renderable->draw(globalParams, materialParams); ErrorTracker::trackFrom("After renderable drawing"); } } // namespace Render } // namespace Kriti
{-# LANGUAGE ScopedTypeVariables #-} -- By Christian Oliveros and Minmin Chen module PingPong.Player.Stig (stig) where import Control.Lens (view, (&), (.~), (^.)) import Data.Bool (bool) import Data.Ext import Data.Geometry hiding (head, Above, Below) import Data.Maybe import Debug.Trace import GHC.Float import qualified Numeric.LinearAlgebra as Numerical import PingPong.Model import PingPong.Player.Stig.General import PingPong.Player.Stig.GeometryHelpers import PingPong.Player.Stig.Kinematics import PingPong.Player.Stig.Fabrik import Control.Monad -- | Simulation's gravity simulationGravity :: Float simulationGravity = 2 -- | Simulation's max speed simulationMaxSpeed :: Float simulationMaxSpeed = 2 -- | Simulation's Table Height simulationTableHeight :: Float simulationTableHeight = 0.5 -- | Simulation's Table Center X Position simulationTableCenterX :: Float simulationTableCenterX = 0 -- | Simulation's Table Max X Position simulationTableMaxX :: Float simulationTableMaxX = 1 -- | Normalized direction of the table simulationTableDir :: Vector 2 Float simulationTableDir = Vector2 (-1) 0 -- | Bat's Length simulationBatLength :: Float simulationBatLength = 0.1 -- | Simulation's Table Center X Position simulationTableOpponentCenterX :: Float simulationTableOpponentCenterX = -0.5 -- | Simulation's Table Max X Position simulationTableOpponentMinX :: Float simulationTableOpponentMinX = -0.8 -- | If the x value is inside the opponent's table range insideOpponentTableX :: Float -> DistanceToRange Float insideOpponentTableX = signedDistanceToRange simulationTableOpponentMinX simulationTableOpponentCenterX -- | Predict the time (relative to current time) the gravity parabole is going to intersect a height predictFreefallHeightInter :: Point 2 Float -> Vector 2 Float -> Float -> Maybe Float predictFreefallHeightInter p v tH = bool res Nothing (isNothing possible || null tsRaw) where a2 = -simulationGravity / 2 a1 = view yComponent v a0 = view yCoord p - tH possible = solveQuadratic a2 a1 a0 tsRaw = fromJust possible -- If solveQuadratic is [] change for 0, because all t are valid -- Also, make sure the times are valid between 0 and 1 (threshold is used for approximations) ts = filter (0 <=) $ map (globalThreshold 0) $ bool tsRaw [0] (null tsRaw) res = case possible of Nothing -> Nothing Just _ -> case ts of [] -> Nothing -- No solution _ -> Just $ minimum ts -- Minimum Valid Time -- | Evaluate the free fall formulas for a time freeFallEvaluateTime :: Point 2 Float -> Vector 2 Float -> Float -> (Point 2 Float, Vector 2 Float) freeFallEvaluateTime p v t = (Point2 x y, Vector2 vx vy) where vx = view xComponent v x = vx * t + view xCoord p vy0 = view yComponent v vy = -simulationGravity * t + vy0 y = -simulationGravity * t * t / 2 + vy0 * t + view yCoord p -- | Reflect a velocity vector againts the table like in a collision reflectVelocityTable :: Vector 2 Float -> Vector 2 Float reflectVelocityTable v = reflect v simulationTableDir -- | Reflect Ball Velocity against a bat reflectVelocityBat :: LineSegment 2 () Float -> Vector 2 Float -> Vector 2 Float reflectVelocityBat bat v = reflect v (segmentDir bat) -- | Get the normal of the free fall velocity freefallNormal :: Vector 2 Float -> Vector 2 Float freefallNormal v = n where nUnorm = Vector2 (-view yComponent v) (view xComponent v) (n, _) = normalizeVector nUnorm -- | Get the (relative) time of maximum height of a freefall. Note, it might be negative, meaning it already peaked freeFallMaxHeightTime :: Vector 2 Float -> Float freeFallMaxHeightTime v = view yComponent v / simulationGravity -- | Calculates the (relative) time to reach a x position in a freefall. Note, it might be negative, meaning it already passed freeFallTimeToXPos :: Point 2 Float -> Vector 2 Float -> Float -> Float freeFallTimeToXPos p v x = (x - view xCoord p) / view xComponent v -- | Predict the info of the ball bouncing on our side of the table predictTableBounce :: Point 2 Float -> Vector 2 Float -> Maybe (Point 2 Float, Vector 2 Float, Float) predictTableBounce p v = res where tPossible = predictFreefallHeightInter p v simulationTableHeight (pB, vB) = freeFallEvaluateTime p v (fromJust tPossible) xPos = view xCoord pB xPosValid = simulationTableCenterX <= xPos && xPos <= simulationTableMaxX res = case tPossible of Nothing -> Nothing Just t -> if xPosValid then return (pB, reflectVelocityTable vB, t) else Nothing -- | Checks if a position is valid for our side of the table checkValidPos :: Point 2 Float -> Bool checkValidPos p0 = simulationTableCenterX <= xPos && xPos <= simulationTableMaxX && simulationTableHeight <= yPos where xPos = view xCoord p0 yPos = view yCoord p0 -- | Try to predict the best interception time predictBestInterceptionTime :: Point 2 Float -> Vector 2 Float -> Maybe Float predictBestInterceptionTime p v = res where ts = [freeFallMaxHeightTime v, freeFallTimeToXPos p v simulationTableMaxX, freeFallTimeToXPos p v (simulationTableMaxX / 2), freeFallTimeToXPos p v (simulationTableMaxX / 4)] tF = filter tFilter ts res = if null tF then Nothing else Just $ traceShowId $ minimum tF tFilter :: Float -> Bool tFilter t = 0 <= t && checkValidPos p0 where (p0, _) = freeFallEvaluateTime p v t -- | Place the bat normal to a ball point and velocity placeBatInBounceCurve :: Point 2 Float -> Vector 2 Float -> Float -> LineSegment 2 () Float placeBatInBounceCurve p v q = line where -- Normal to Velocity n0 = freefallNormal v n = rotateVector2D q n0 --(n, _) = normalizeVector v p0 = p .+^ (n ^* (simulationBatLength / 2)) p1 = p .-^ (n ^* (simulationBatLength / 2)) {- p0 = p p1 = p .+^ (n ^* simulationBatLength) -} p0Dist = distToSpecialBase p0 p1Dist = distToSpecialBase p1 line = bool (ClosedLineSegment (p1 :+ ()) (p0 :+ ())) (ClosedLineSegment (p0 :+ ()) (p1 :+ ())) (p0Dist < p1Dist) -- | Distance to Stig base at table height distToSpecialBase :: Point 2 Float -> Float distToSpecialBase po = norm $ po .-. Point2 stigFoot simulationTableHeight -- | Maximum ITerations to guess binaryGuessMaxIter :: Int binaryGuessMaxIter = 10 -- | Place the ball at the center of the opponents table rotateBatToCenter :: Point 2 Float -> Vector 2 Float -> DistanceToRange (Float, LineSegment 2 () Float) rotateBatToCenter p v = fromMaybe (trace "Never interception with table?!" Below (read "Infinity" :: Float, placeBatInBounceCurve p v 0)) finalGuess where -- If we are going up goingUp = view yComponent v > 0 finalGuess = -- binaryGuess 0 (-binaryGuessLimit) binaryGuessLimit 0 bool (binaryGuess 0 0 (pi/2) 0) -- Case going down (binaryGuess 0 (-pi/4) 0 (-pi/4)) -- Case going up goingUp -- | Guess a possible bat possition binaryGuess iter qmin qmax qcurr | noTPossible = trace "No interception with table?!" Nothing {- | iter >= binaryGuessMaxIter = trace ("Max Iter Selected q=" ++ show qcurr) Just (useInsideInfo insideInfo bat)-} | iter >= binaryGuessMaxIter = Just (useInsideInfo insideInfo bat) | otherwise = guess where -- Generate bat bat = placeBatInBounceCurve p v qcurr nV = reflectVelocityBat bat v tPossible = predictFreefallHeightInter p nV simulationTableHeight noTPossible = isNothing tPossible t = fromJust tPossible (pI, _) = freeFallEvaluateTime p nV t pIX = view xCoord pI -- If Bounce is going up bounceGoingUp = view yComponent nV > 0 insideInfo = insideOpponentTableX pIX useInsideInfo (Inside _) b = Inside (pIX, b) useInsideInfo (Above _) b = Below (pIX, b) useInsideInfo (Below _) b = Above (pIX, b) -- Guess Selection to improve -- Ball Going Up guessTry x True = case insideOpponentTableX x of {- Above _ -> trace ("X=" ++ show x ++ " Up:Below " ++ show bounceGoingUp ++ " qs=" ++ show (qmin, qmax, qcurr)) $ binaryGuess (iter + 1) qmin qcurr ((qmin + qcurr) / 2) Below _ -> trace ("X=" ++ show x ++ " Up:Above " ++ show bounceGoingUp ++ " qs=" ++ show (qmin, qmax, qcurr)) $ binaryGuess (iter + 1) qcurr qmax ((qmax + qcurr) / 2) Inside _ -> trace ("X=" ++ show x ++ " Up:Inside Selected q=" ++ show qcurr) Just (Inside (pIX, bat)) -} Above _ -> binaryGuess (iter + 1) qmin qcurr ((qmin + qcurr) / 2) Below _ -> binaryGuess (iter + 1) qcurr qmax ((qmax + qcurr) / 2) Inside _ -> Just (Inside (pIX, bat)) -- Ball Going Down guessTry x False = case insideOpponentTableX x of {- Above _ -> trace ("X=" ++ show x ++ " Down:Below " ++ show bounceGoingUp ++ " qs=" ++ show (qmin, qmax, qcurr)) $ binaryGuess (iter + 1) qmin qcurr ((qmin + qcurr) / 2) Below _ -> trace ("X=" ++ show x ++ " Down:Above " ++ show bounceGoingUp ++ " qs=" ++ show (qmin, qmax, qcurr)) $ binaryGuess (iter + 1) qcurr qmax ((qmax + qcurr) / 2) Inside _ -> trace ("X=" ++ show x ++ " Down:Inside Selected q=" ++ show qcurr) Just (Inside (pIX, bat)) -} Above _ -> binaryGuess (iter + 1) qmin qcurr ((qmin + qcurr) / 2) Below _ -> binaryGuess (iter + 1) qcurr qmax ((qmax + qcurr) / 2) Inside _ -> Just (Inside (pIX, bat)) --guess = traceShow (p, nV, t, pI) guessTry pIX goingUp guess = guessTry pIX goingUp -- | Move bat to center low limit moveBatToCenterLowLim :: Float moveBatToCenterLowLim = 0.6 -- | Move bat to center high limit moveBatToCenterHighLim :: Float moveBatToCenterHighLim = 1.3 -- | Move bat to center number of steps moveBatToCenterSteps :: Float moveBatToCenterSteps = 40 -- | Move bat to center step size moveBatToCenterStepSize :: Float moveBatToCenterStepSize = (moveBatToCenterHighLim - moveBatToCenterLowLim) / moveBatToCenterSteps -- | Maximum Time apply Motion maxTimeToMotion :: Motion-> Float maxTimeToMotion m = maximum $ map (\v -> abs v / simulationMaxSpeed) m bestMotion :: Arm -> Point 2 Float -> Vector 2 Float -> Motion bestMotion arm p v = finalMotion where (finalMotion, _) = move 0 moveBatToCenterHighLim -- Approach to good bat center move iter x | iter >= moveBatToCenterSteps || moveBatToCenterLowLim > x = (bM, bMV) -- Limit | isInside possible = bool (bMN, mVN) (bM, bMV) (bMV <= mVN) -- We are inside check if we are better | otherwise = (bMN, bMV) -- We are not inside, continue checking where tX = freeFallTimeToXPos p v x (pN, vN) = freeFallEvaluateTime p v tX possible = rotateBatToCenter pN vN (_, bat) = getDistanceToRangeContent possible batInv = segmentInvert bat (mIntercept, _, _) = fabrikToSegment stigFoot arm bat (mInterceptInv, _, _) = fabrikToSegment stigFoot arm batInv m = armToMotion arm mIntercept mV = maxTimeToMotion m mInv = armToMotion arm mInterceptInv mVInv = maxTimeToMotion mInv -- Current Best Motion bM = bool mInv m (mV <= mVInv) bMV = maxTimeToMotion bM -- Possible Next Best Motion (bMN, mVN) = move (iter + 1) (x - moveBatToCenterStepSize) -- | Try to intercept Ball tryInterceptBall :: Arm -> Point 2 Float -> Vector 2 Float -> Float -> IO Motion tryInterceptBall arm p v tColl = do let bM = bestMotion arm p v --return $ trace ("Opponent did a proper hit we can catch at " ++ show tColl ++ "\n" ++ show bM) bM return bM -- | Stig's player stig :: Player stig = Player { name = "Stig", arm = stigArm, initArm = stigArm, foot = stigFoot, prepare = return (), terminate = return (), action = stigAction, collide = stigCollide, planPnt = stigPlanPnt, planSeg = stigPlanSeg, stretch = \_ arm -> return $ armToStigRestMotion arm, dance = \_ arm -> return $ armToStigRestMotion arm } -- Internal Stig Arm stigInternalArm :: Arm stigInternalArm = checkArm [ Link paleBlue 0.5, Joint red (0.5112798), -- (0.1) Link paleBlue 0.3, Joint red 1.247675, -- (0.1) Link paleBlue 0.25, Joint red 0.4820231, -- (-0.1) Link paleBlue 0.1, Joint red (-2.2409778), -- (-0.1) Link hotPink 0.1 -- Bat ] -- | Arm to use stigArm :: Arm stigArm = mapMotion stigInternalArm stigRest -- | Stig Arm Length stigArmLength :: Float stigArmLength = armLength stigArm -- | Separation from the center of the table stigFoot :: Float stigFoot = 1.3 -- | Stig rest postion stigRest :: Motion stigRest = m where (m, _, _) = fabrikToSegment stigFoot stigInternalArm (ClosedLineSegment (Point2 1.1 0.65 :+()) (Point2 1.1 0.75 :+())) -- | Stig rest 2 postion stigRest2 :: Motion stigRest2 = m where (m, _, _) = fabrikToSegment stigFoot stigInternalArm (ClosedLineSegment (Point2 0.9 0.83 :+()) (Point2 0.9 0.93 :+())) -- | Get the a zeroed Motion list for Stig's arm stigNoMotion :: Motion stigNoMotion = map f stigRest where f = const 0 -- | Calculate Motion Velocity to Rest Motion. !Warning: no limits are applied armToStigRestMotion :: Arm -> Motion armToStigRestMotion ar = armToMotion ar stigRest -- | Calculate Motion Velocity to Rest Motion2. !Warning: no limits are applied armToStigRestMotion2 :: Arm -> Motion armToStigRestMotion2 ar = armToMotion ar stigRest2 -- | Check collision of moving line and point stigCollide :: forall r. (Num r, Floating r, Ord r, Eq r, Show r) => (r, Point 2 r, LineSegment 2 () r) -> (r, Point 2 r, LineSegment 2 () r) -> IO (Point 2 r) stigCollide t1 t2 = bool (error "Stig Collide Failed a Test Case") (return (f t1 t2)) completeCheck where f = movingBallMovingLineCollide generateTestState :: (Num r, Floating r, Ord r) => r -> (r, r) -> (r, r) -> (r, r) -> (r, Point 2 r, LineSegment 2 () r) generateTestState t (px, py) (pl0x, pl0y) (pl1x, pl1y) = (t, Point2 px py, ClosedLineSegment (Point2 pl0x pl0y :+ ()) (Point2 pl1x pl1y :+ ())) testCases = [ (Point2 0 0, generateTestState 0 (0, 0) (1, -1) (1, 1), generateTestState 1 (0, 0) (1, -1) (1, 1)), (Point2 0 2, generateTestState 0 (0, 0) (0, 0) (1, 0), generateTestState 1 (0, 0) (0, 1) (1, 1)), (Point2 0 0, generateTestState 0 (0, 0) (1, -1) (1, 1), generateTestState 1 (2, 0) (1, -1) (1, 1)), (Point2 (-1) 0, generateTestState 0 (0, 0) (1, -1) (1, 1), generateTestState 1 (1, 0) (0, -1) (0, 1)), (Point2 1 1, generateTestState 0 (0, 0) (0, -1) (2, 1), generateTestState 1 (2, 0) (0, -1) (2, 1)), (Point2 (-1) 1, generateTestState 0 (0, 0) (0, -1) (2, 1), generateTestState 1 (0, 0) (-2, -1) (0, 1)), (Point2 1.2 0.8, generateTestState 0 (0.3, 1.0) (0.1, 2.1) (-0.5, 0.9), generateTestState 1 (1.2, 0.8) (-0.2, 2.2) (-0.3, 1.1)) --(Point2 (-6) (-4), generateTestState 0 (-5, -5) (0, 1) (1, 0), generateTestState 1 (5, 7) (0, 1) (1, 0)) ] checkCollision :: (Num r, Floating r, Ord r, Show r) => (Point 2 r, (r, Point 2 r, LineSegment 2 () r), (r, Point 2 r, LineSegment 2 () r)) -> (Bool, Diff (Point 2) r, Point 2 r) checkCollision (ans, s1, s2) = (diffX == 0 && diffY == 0, diff, c) where c = f s1 s2 diff = c .-. ans diffX = globalThreshold 0 $ abs $ view xComponent diff diffY = globalThreshold 0 $ abs $ view yComponent diff performTest :: (Num r, Floating r, Ord r, Show r) => (Point 2 r, (r, Point 2 r, LineSegment 2 () r), (r, Point 2 r, LineSegment 2 () r)) -> Bool performTest testCase@(ans, s1, s2) = bool (error showError) True correct where (correct, diff, p) = checkCollision testCase showError = "Expected " ++ show ans ++ " but got " ++ show p ++ " with Diff " ++ show diff ++ " \n\tFor case:\n\t" ++ show s1 ++ "\n\t->\n\t" ++ show s2 completeCheck = all performTest testCases --test = stigCollide (0, Point2 0 0, ClosedLineSegment (Point2 0 0 :+ ()) (Point2 1 0 :+ ())) (1, Point2 0 0, ClosedLineSegment (Point2 1 0 :+ ()) (Point2 1 0 :+ ())) --test = stigCollide (0, Point2 (-1) 1, ClosedLineSegment (Point2 0 0 :+ ()) (Point2 1 1 :+ ())) (1, Point2 0 0, ClosedLineSegment (Point2 0 0 :+ ()) (Point2 (-1) 1 :+ ())) --test = stigCollide (0, Point2 (-1) 1, ClosedLineSegment (Point2 0 (-1) :+ ()) (Point2 1 1 :+ ())) (1, Point2 0 0, ClosedLineSegment (Point2 0 (-1) :+ ()) (Point2 (-1) 1 :+ ())) stigAction :: Float -> (Float, Item) -> BallState -> Arm -> IO Motion stigAction _ (tColl, Net) _ arm = return $ -- Ball hit the net, this means someone scored -- Go to rest let toBase = armToMotion arm stigNoMotion --in trace ("Someone Scored at " ++ show tColl) applyMotionLimits toBase -- Velocity limits in applyMotionLimits toBase stigAction _ (tColl, Other _) _ arm = return $ -- Ball hit something out of the game, this means someone scored -- Go to rest let toBase = armToMotion arm stigNoMotion --in trace ("Someone Scored at " ++ show tColl) applyMotionLimits toBase -- Velocity limits in applyMotionLimits toBase stigAction _ (tColl, Bat Self) _ arm = return $ -- We hit the ball, go to rest motion let toRest2 = armToStigRestMotion2 arm --in trace ("We just hit the ball at " ++ show tColl) toRest2 -- Velocity limits in toRest2 stigAction _ (tColl, Table Opponent) _ arm = return $ -- Our hit was correct and we reached the other player's side -- So rest let toRest2 = armToStigRestMotion2 arm -- in trace ("We did a proper hit at " ++ show tColl) toRest2 in toRest2 stigAction t (tColl, Air) bs arm = return $ -- Invalid State let toBase = armToMotion arm stigNoMotion -- in trace ("Impossible State " ++ show tColl) applyMotionLimits toBase -- Velocity limits in applyMotionLimits toBase stigAction t (tColl, Table Self) bs arm = do -- Other player did a proper hit we have to respond to -- Distance to max point for now let p = loc bs let v = dir bs tryInterceptBall arm p v tColl stigAction t (tColl, Bat Opponent) bs arm = do -- Other player did a hit we have to respond to let p = loc bs let v = dir bs let mayBounce = predictTableBounce p v case mayBounce of {- Nothing -> return $ trace ("Opponent did a wrong hit at " ++ show tColl) (armToStigRestMotion arm) -- Velocity limits Just (pT, vT, _) -> trace ("Opponent did a proper hit at " ++ show tColl) tryInterceptBall arm pT vT tColl -} Nothing -> return $ armToStigRestMotion arm Just (pT, vT, _) -> tryInterceptBall arm pT vT tColl stigAction _ (tColl, _) _ arm = return $ -- Ball: Don't know what happened -- Go to rest let toBase = armToMotion arm stigNoMotion --in trace ("Someone Scored at " ++ show tColl) applyMotionLimits toBase -- Velocity limits in trace ("Don't know what happened at: " ++ show tColl) applyMotionLimits toBase -- | Stig Plan Threshold stigPlanThreshold :: (Num r, Ord r, Fractional r) => r -> r -> r stigPlanThreshold = threshold 0.01 -- | Calculates the possible motion values to achieve a point. If it fails it returns [] stigPlanPnt :: Float -> Arm -> Point 2 Float -> IO Motion stigPlanPnt foot arm p | isTooFar = trace "Too Far" return [] | stigPlanThreshold 0 eB == 0 = return $ map normalizeAngle qB | otherwise = trace ("Error: " ++ show eB) return [] where isTooFar = norm (p .-. Point2 foot 0) > 1.2 * armLength arm (qB, eB) = fabrikToPoint foot arm p -- | Calculates the possible motion values to achieve a line segment. If it fails it returns [] stigPlanSeg :: Float -> Arm -> LineSegment 2 () Float -> IO Motion stigPlanSeg foot arm s | stigPlanThreshold 0 eB == 0 && stigPlanThreshold 0 eBat == 0 = return m | otherwise = return [] where (m, eB, eBat) = fabrikToSegment foot arm s -- Testing Starts Here -- | Create a Test Case for stigPlanPnt createPlanPntCase :: Float -> Arm -> (Float, Float) -> Motion -> (Float, Arm, Point 2 Float, Motion) createPlanPntCase f a (xT, yT) m = (f, a, Point2 xT yT, m) -- | Test stigPlanPnt testPlanPnt :: (Float, Arm, Point 2 Float, Motion) -> IO Bool testPlanPnt (f, arm, pT, mT) = do -- Expected Position let qT = motionToJointVector mT let xTargetGlobal = pointToHomogenousPoint pT -- Arm let (a, _) = getArmKinematicAndMotion f arm -- Calculate Answer mB <- stigPlanPnt f arm pT if null mB then return $ bool (trace "Wrong Null" False) (null mT) (null mT) else do let qB = motionToJointVector mB -- Forward Transforms let fwdTT = applyForwardKinematicTrans a qT let fwdTB = applyForwardKinematicTrans a qB -- Bat Global Position let batGlobalB = applyForwardKinematicMatrixTrans fwdTB Numerical.#> homogeneousZero let batGlobalT = applyForwardKinematicMatrixTrans fwdTT Numerical.#> homogeneousZero -- Error let eB = xTargetGlobal - batGlobalB let eNormB = Numerical.norm_2 eB let eT = trace ("Best " ++ show (batGlobalB, eNormB, mB)) $ xTargetGlobal - batGlobalT let eNormT = Numerical.norm_2 eT let result = trace ("Target " ++ show (batGlobalT, eNormT, mT) ++ "\n") $ (globalThreshold 0 eNormB == 0) && (eNormB <= eNormT) return $ result && (length mB == length mT) -- | Test Cases for testPlanPnt planPntTestCases :: [(Float, Arm, Point 2 Float, Motion)] planPntTestCases = [ createPlanPntCase 0 [ Joint red 0.0, Link red 0.1 ] (0, 0.1) [0], createPlanPntCase 0 [ Joint red 0.0, Link red 0.1 ] (0.1, 0) [pi/2], createPlanPntCase 1.5 [ Link red 0.2, Joint red 0.0, Link red 0.2, Joint red 0.0, Link red 0.2, Joint red 0.0, Link red 0.2, Joint red 0.0, Link red 0.1 ] (1.22385, 0.80917) [0.1, 0.2, 0.3, 0.4], createPlanPntCase 1.5 [ Link red 0.2, Joint red 0.0, Link red 0.2, Joint red 0.0, Link red 0.2, Joint red 0.0, Link red 0.2, Joint red 0.0, Link red 0.1 ] (1.77615, 0.80917) [-0.5, 0.0, 0.4, 0.6], createPlanPntCase 1.5 [ Link red 0.2, Joint red 0.0, Link red 0.2, Joint red 0.0, Link red 0.2, Joint red 0.0, Link red 0.2, Joint red 0.0, Link red 0.1 ] (1.48013, 0.89202) [0.1, -0.2, 0.3, -0.4], createPlanPntCase 1.5 [ Link red 0.1, Joint red 0.0, Link red 0.1, Joint red 0.0, Link red 0.1 ] (1.5, 0) [2.094,2.094], createPlanPntCase 1.5 [ Link red 0.1, Joint red 0.0, Link red 0.1, Joint red 0.0, Link red 0.1 ] (1.5, 0) [2.094,2.094] ] -- | Executes testPlanPnt executePlanPntTestCases :: IO Bool executePlanPntTestCases = foldM f True planPntTestCases where f True params = testPlanPnt params f False _ = return False -- | Create a Test Case for stigPlanSeg createPlanSegCase :: Float -> Arm -> (Float, Float) -> (Float, Float) -> Motion -> (Float, Arm, LineSegment 2 () Float, Motion) createPlanSegCase f a (xP0, yP0) (xP1, yP1) m = (f, a, ClosedLineSegment (Point2 xP0 yP0 :+ ()) (Point2 xP1 yP1 :+ ()), m) -- | Test stigPlanSeg testPlanSeg :: (Float, Arm, LineSegment 2 () Float, Motion) -> IO Bool testPlanSeg (f, arm, sT, mT) = do -- Expected Position let pT = sT ^. (end . core) let qT = motionToJointVector mT let xTargetGlobal = pointToHomogenousPoint pT -- Arm let (a, _) = getArmKinematicAndMotion f arm -- Calculate Answer mB <- stigPlanSeg f arm sT if null mB then return $ bool (trace "Wrong Null" False) (null mT) (null mT) else do let qB = motionToJointVector mB -- Forward Transforms let fwdTT = applyForwardKinematicTrans a qT let fwdTB = applyForwardKinematicTrans a qB -- Bat Global Position let batGlobalB = applyForwardKinematicMatrixTrans fwdTB Numerical.#> homogeneousZero let batGlobalT = applyForwardKinematicMatrixTrans fwdTT Numerical.#> homogeneousZero -- Error let eB = xTargetGlobal - batGlobalB let eNormB = Numerical.norm_2 eB let eT = trace ("Best " ++ show (batGlobalB, eNormB, mB)) $ xTargetGlobal - batGlobalT let eNormT = Numerical.norm_2 eT let result = trace ("Target " ++ show (batGlobalT, eNormT, mT)) $ (globalThreshold 0 eNormB == 0) && ((eNormB <= eNormT) || (eNormT > 0 && eNormB / eNormT <= 1.1) || (eNormT == 0 && globalThreshold 0 eNormB == 0)) return $ result && bool (trace "Different Motion Sizes" False) True (length mB == length mT) -- | Test Cases for testPlanPnt planSegTestCases :: [(Float, Arm, LineSegment 2 () Float, Motion)] planSegTestCases = [ createPlanSegCase 1.5 [ Link red 0.2, Joint red 0.0, Link red 0.2, Joint red 0.0, Link red 0.2, Joint red 0.0, Link red 0.2, Joint red 0.0, Link red 0.1 ] (1.48023, 0.79501) (1.48023, 0.89501) [0.2, -0.2, -0.1, 0.1], createPlanSegCase 1.5 [ Link red 0.2, Joint red 0.0, Link red 0.2, Joint red 0.0, Link red 0.2, Joint red 0.0, Link red 0.2, Joint red 0.0, Link red 0.1 ] (1.71174, 0.75003) (1.66379, 0.83779) [-0.5, 0.0, 0.4, 0.6], createPlanSegCase 1.5 [ Link red 0.1, Joint red 0.0, Link red 0.1, Joint red 0.0, Link red 0.1 ] (1.4134, 5.0e-2) (1.5, 0) [2.094,2.094] ] -- | Executes testPlanSeg executePlanSegTestCases :: IO Bool executePlanSegTestCases = foldM f True planSegTestCases where f True params = testPlanSeg params f False _ = return False
\subsubsection{\tt ipbd} \label{benchmarkipbd} {\tt ipbd} is a synthetic AKS benchmark that performs a Boolean-Double ({\apl B\qplus\qdot\qtimes\qtran\0D}) matrix product on arrays of shape {\tt [500, 500]}. We expect that \wlf and \awlf should exhibit similar performance on this benchmark.
Sean Ruel was a candidate for ASUCD Senate during the Fall 2004 ASUCD election with Student Focus. He won the election and was sworn into office. However, he resigned shortly after for his part in the Fall 2004 Election/Campaigning in Dorms Controversy Dorm Campaigning Controversy. Sean was a former President of Men Acting Against Rape and a brother in the Theta Xi fraternity.
(* File: Arith_Thms.thy Author: Bohua Zhan Setup for proof steps related to arithmetic, mostly on natural numbers. *) section \<open>Setup for arithmetic\<close> theory Arith_Thms imports Order_Thms HOL.Binomial begin (* Reducing inequality on natural numbers. *) theorem reduce_le_plus_consts: "(x::nat) + n1 \<le> y + n2 \<Longrightarrow> x \<le> y + (n2-n1)" by simp theorem reduce_le_plus_consts': "n1 \<ge> n2 \<Longrightarrow> (x::nat) + n1 \<le> y + n2 \<Longrightarrow> x + (n1-n2) \<le> y" by simp theorem reduce_less_plus_consts: "(x::nat) + n1 < y + n2 \<Longrightarrow> x < y + (n2-n1)" by simp theorem reduce_less_plus_consts': "n1 \<ge> n2 \<Longrightarrow> (x::nat) + n1 < y + n2 \<Longrightarrow> x + (n1-n2) < y" by simp (* To normal form. *) theorem norm_less_lminus: "(x::nat) - n < y \<Longrightarrow> x \<le> y + (n-1)" by simp theorem norm_less_lplus: "(x::nat) + n < y \<Longrightarrow> x + (n+1) \<le> y" by simp theorem norm_less_rminus: "(x::nat) < y - n \<Longrightarrow> x + (n+1) \<le> y" by simp theorem norm_less_rplus: "(x::nat) < y + n \<Longrightarrow> x \<le> y + (n-1)" by simp theorem norm_less: "(x::nat) < y \<Longrightarrow> x + 1 \<le> y" by simp theorem norm_le_lminus: "(x::nat) - n \<le> y \<Longrightarrow> x \<le> y + n" by simp theorem norm_le_rminus: "(x::nat) \<le> y - n \<Longrightarrow> x \<le> y + 0" by simp theorem norm_le: "(x::nat) \<le> y \<Longrightarrow> x \<le> y + 0" by simp theorem norm_le_lplus0: "(x::nat) + 0 \<le> y \<Longrightarrow> x \<le> y + 0" by simp (* Transitive resolve. *) theorem trans_resolve1: "n1 > 0 \<Longrightarrow> (x::nat) + n1 \<le> y \<Longrightarrow> (y::nat) + n2 \<le> x \<Longrightarrow> False" by simp theorem trans_resolve2: "n1 > n2 \<Longrightarrow> (x::nat) + n1 \<le> y \<Longrightarrow> (y::nat) \<le> x + n2 \<Longrightarrow> False" by simp (* Transitive. *) theorem trans1: "(x::nat) + n1 \<le> y \<Longrightarrow> y + n2 \<le> z \<Longrightarrow> x + (n1+n2) \<le> z" by simp theorem trans2: "(x::nat) \<le> y + n1 \<Longrightarrow> y \<le> z + n2 \<Longrightarrow> x \<le> z + (n1+n2)" by simp theorem trans3: "(x::nat) + n1 \<le> y \<Longrightarrow> y \<le> z + n2 \<Longrightarrow> x \<le> z + (n2-n1)" by simp theorem trans4: "n1 > n2 \<Longrightarrow> (x::nat) + n1 \<le> y \<Longrightarrow> y \<le> z + n2 \<Longrightarrow> x + (n1-n2) \<le> z" by simp theorem trans5: "(x::nat) \<le> y + n1 \<Longrightarrow> y + n2 \<le> z \<Longrightarrow> x \<le> z + (n1-n2)" by simp theorem trans6: "n2 > n1 \<Longrightarrow> (x::nat) \<le> y + n1 \<Longrightarrow> y + n2 \<le> z \<Longrightarrow> x + (n2-n1) \<le> z" by simp (* Resolve. *) theorem single_resolve: "n > 0 \<Longrightarrow> (x::nat) + n \<le> x \<Longrightarrow> False" by simp theorem single_resolve_const: "n > 0 \<Longrightarrow> (x::nat) + n \<le> 0 \<Longrightarrow> False" by simp (* Comparison with constants. *) theorem cv_const1: "(x::nat) + n \<le> y \<Longrightarrow> 0 + (x+n) \<le> y" by simp (* x is const *) theorem cv_const2: "(x::nat) + n \<le> y \<Longrightarrow> x \<le> 0 + (y-n)" by simp (* y is const *) theorem cv_const3: "y < n \<Longrightarrow> (x::nat) + n \<le> y \<Longrightarrow> x + (n-y) \<le> 0" by simp (* y is const (contradiction with 0 \<le> x) *) theorem cv_const4: "(x::nat) \<le> y + n \<Longrightarrow> 0 + (x-n) \<le> y" by simp (* x is const *) theorem cv_const5: "(x::nat) \<le> y + n \<Longrightarrow> 0 \<le> y + (n-x)" by simp (* x is const (trivial) *) theorem cv_const6: "(x::nat) \<le> y + n \<Longrightarrow> x \<le> 0 + (y+n)" by simp (* y is const *) (* Misc *) theorem nat_eq_to_ineqs: "(x::nat) = y + n \<Longrightarrow> x \<le> y + n \<and> x \<ge> y + n" by simp theorem nat_ineq_impl_not_eq: "(x::nat) + n \<le> y \<Longrightarrow> n > 0 \<Longrightarrow> x \<noteq> y" by simp theorem eq_to_ineqs: "(x::nat) \<equiv> y \<Longrightarrow> x \<le> y \<and> y \<le> x" by simp theorem ineq_to_eqs1: "(x::nat) \<le> y + 0 \<Longrightarrow> y \<le> x + 0 \<Longrightarrow> x = y" by simp ML_file \<open>arith.ML\<close> ML_file \<open>order.ML\<close> ML_file \<open>order_test.ML\<close> setup \<open>register_wellform_data ("(a::nat) - b", ["a \<ge> b"])\<close> setup \<open>add_prfstep_check_req ("(a::nat) - b", "(a::nat) \<ge> b")\<close> (* Normalize any expression to "a - b" form. *) lemma nat_sub_norm: "(a::nat) = a - 0 \<and> a \<ge> 0" by simp (* Adding and subtracting two normalized expressions. *) lemma nat_sub1: "(a::nat) \<ge> b \<Longrightarrow> c \<ge> d \<Longrightarrow> (a - b) + (c - d) = (a + c) - (b + d) \<and> a + c \<ge> b + d" by simp lemma nat_sub2: "(a::nat) \<ge> b \<Longrightarrow> c \<ge> d \<Longrightarrow> a - b \<ge> c - d \<Longrightarrow> (a - b) - (c - d) = (a + d) - (b + c) \<and> a + d \<ge> b + c" by simp lemma nat_sub3: "(a::nat) \<ge> b \<Longrightarrow> c \<ge> d \<Longrightarrow> (a - b) * (c - d) = (a * c + b * d) - (a * d + b * c) \<and> a * c + b * d \<ge> a * d + b * c" by (smt diff_mult_distrib mult.commute mult_le_mono1 nat_sub2) (* Cancel identical terms on two sides, yielding a normalized expression. *) lemma nat_sub_combine: "(a::nat) + b \<ge> c + b \<Longrightarrow> (a + b) - (c + b) = a - c \<and> a \<ge> c" by simp lemma nat_sub_combine2: "n \<ge> m \<Longrightarrow> (a::nat) + b * n \<ge> c + b * m \<Longrightarrow> (a + b * n) - (c + b * m) = (a + b * (n - m)) - c \<and> a + b * (n - m) \<ge> c \<and> n \<ge> m" by (simp add: add.commute right_diff_distrib') lemma nat_sub_combine3: "n \<le> m \<Longrightarrow> (a::nat) + b * n \<ge> c + b * m \<Longrightarrow> (a + b * n) - (c + b * m) = a - (c + b * (m - n)) \<and> a \<ge> c + b * (m - n) \<and> m \<ge> n" by (smt add.commute mult.commute nat_diff_add_eq2 nat_le_add_iff1) ML_file \<open>nat_sub.ML\<close> ML_file \<open>nat_sub_test.ML\<close> (* Ordering on Nats. *) lemma le_neq_implies_less' [forward]: "(m::nat) \<noteq> n \<Longrightarrow> m \<le> n \<Longrightarrow> m < n" by simp lemma le_zero_to_equal_zero [forward]: "(n::nat) \<le> 0 \<Longrightarrow> n = 0" by simp lemma less_one_to_equal_zero [forward]: "(n::nat) < 1 \<Longrightarrow> n = 0" by simp setup \<open>add_backward_prfstep_cond @{thm Nat.mult_le_mono1} [with_cond "?k \<noteq> 1"]\<close> setup \<open>add_resolve_prfstep @{thm Nat.not_add_less1}\<close> lemma not_minus_less [resolve]: "\<not>(i::nat) < (i - j)" by simp lemma nat_le_prod_with_same [backward]: "m \<noteq> 0 \<Longrightarrow> (n::nat) \<le> m * n" by simp lemma nat_le_prod_with_le [backward1]: "k \<noteq> 0 \<Longrightarrow> (n::nat) \<le> m \<Longrightarrow> (n::nat) \<le> k * m" using le_trans nat_le_prod_with_same by blast lemma nat_plus_le_to_less [backward1]: "b \<noteq> 0 \<Longrightarrow> (a::nat) + b \<le> c \<Longrightarrow> a < c" by simp lemma nat_plus_le_to_less2 [backward1]: "a \<noteq> 0 \<Longrightarrow> (a::nat) + b \<le> c \<Longrightarrow> b < c" by simp setup \<open>add_forward_prfstep @{thm add_right_imp_eq}\<close> setup \<open>add_forward_prfstep @{thm add_left_imp_eq}\<close> setup \<open>add_rewrite_rule_cond @{thm Nat.le_diff_conv2} [with_term "?i + ?k"]\<close> lemma nat_less_diff_conv: "(i::nat) < j - k \<Longrightarrow> i + k < j" by simp setup \<open>add_forward_prfstep_cond @{thm nat_less_diff_conv} [with_cond "?k \<noteq> ?NUMC", with_term "?i + ?k"]\<close> lemma Nat_le_diff_conv2_same [forward]: "i \<ge> j \<Longrightarrow> (i::nat) \<le> i - j \<Longrightarrow> j = 0" by simp lemma nat_gt_zero [forward]: "b - a > 0 \<Longrightarrow> b > (a::nat)" by simp lemma n_minus_1_less_n: "(n::nat) \<ge> 1 \<Longrightarrow> n - 1 < n" by simp setup \<open>add_forward_prfstep_cond @{thm n_minus_1_less_n} [with_term "?n - 1"]\<close> (* Monotonicity of ordering *) setup \<open>add_backward_prfstep @{thm Nat.diff_le_mono}\<close> setup \<open>add_backward2_prfstep @{thm Nat.diff_less_mono}\<close> setup \<open>add_backward_prfstep @{thm Nat.mult_le_mono2}\<close> setup \<open>add_resolve_prfstep @{thm Nat.le_add1}\<close> setup \<open>add_resolve_prfstep @{thm Nat.le_add2}\<close> setup \<open>add_backward_prfstep @{thm add_left_mono}\<close> setup \<open>add_backward_prfstep @{thm add_right_mono}\<close> lemma add_mono_neutr [backward]: "(0::'a::linordered_ring) \<le> b \<Longrightarrow> a \<le> a + b" by simp lemma add_mono_neutl [backward]: "(0::'a::linordered_ring) \<le> b \<Longrightarrow> a \<le> b + a" by simp setup \<open>add_forward_prfstep @{thm add_less_imp_less_left}\<close> lemma sum_le_zero1 [forward]: "(a::'a::linordered_ring) + b < 0 \<Longrightarrow> a \<ge> 0 \<Longrightarrow> b < 0" by (meson add_less_same_cancel1 less_le_trans) lemma less_sum1 [backward]: "b > 0 \<Longrightarrow> a < a + (b::nat)" by auto setup \<open>add_backward_prfstep @{thm Nat.trans_less_add2}\<close> setup \<open>add_backward_prfstep @{thm Nat.add_less_mono1}\<close> setup \<open>add_backward1_prfstep @{thm Nat.add_less_mono}\<close> setup \<open>add_backward1_prfstep @{thm Nat.add_le_mono}\<close> setup \<open>add_backward1_prfstep @{thm add_increasing2}\<close> setup \<open>add_backward1_prfstep @{thm add_mono}\<close> setup \<open>add_backward_prfstep @{thm add_strict_left_mono}\<close> setup \<open>add_backward1_prfstep @{thm Nat.mult_le_mono}\<close> (* Addition. *) theorem nat_add_eq_self_zero [forward]: "(m::nat) = m + n \<Longrightarrow> n = 0" by simp theorem nat_add_eq_self_zero' [forward]: "(m::nat) = n + m \<Longrightarrow> n = 0" by simp theorem nat_mult_2: "(a::nat) + a = 2 * a" by simp setup \<open>add_rewrite_rule_cond @{thm nat_mult_2} [with_cond "?a \<noteq> 0"]\<close> theorem plus_one_non_zero [resolve]: "\<not>(n::nat) + 1 = 0" by simp (* Diff. *) lemma nat_same_minus_ge [forward]: "(c::nat) - a \<ge> c - b \<Longrightarrow> a \<le> c \<Longrightarrow> a \<le> b" by arith lemma diff_eq_zero [forward]: "(k::nat) \<le> j \<Longrightarrow> j - k = 0 \<Longrightarrow> j = k" by simp lemma diff_eq_zero' [forward]: "(k::nat) \<le> j \<Longrightarrow> j - k + i = j \<Longrightarrow> k = i" by simp (* Divides. *) theorem dvd_defD1 [resolve]: "(a::nat) dvd b \<Longrightarrow> \<exists>k. b = a * k" using dvdE by blast theorem dvd_defD2 [resolve]: "(a::nat) dvd b \<Longrightarrow> \<exists>k. b = k * a" by (metis dvd_mult_div_cancel mult.commute) setup \<open>add_forward_prfstep @{thm Nat.dvd_imp_le}\<close> theorem dvd_ineq2 [forward]: "(k::nat) dvd n \<Longrightarrow> n > 0 \<Longrightarrow> k \<ge> 1" by (simp add: Suc_leI dvd_pos_nat) setup \<open>add_forward_prfstep_cond @{thm dvd_trans} (with_conds ["?a \<noteq> ?b", "?b \<noteq> ?c", "?a \<noteq> ?c"])\<close> setup \<open>add_forward_prfstep_cond @{thm Nat.dvd_antisym} [with_cond "?m \<noteq> ?n"]\<close> theorem dvd_cancel [backward1]: "c > 0 \<Longrightarrow> (a::nat) * c dvd b * c \<Longrightarrow> a dvd b" by simp setup \<open>add_forward_prfstep (equiv_forward_th @{thm dvd_add_right_iff})\<close> (* Divisibility: existence. *) setup \<open>add_resolve_prfstep @{thm dvd_refl}\<close> theorem exists_n_dvd_n [backward]: "P (n::nat) \<Longrightarrow> \<exists>k. k dvd n \<and> P k" using dvd_refl by blast setup \<open>add_resolve_prfstep @{thm one_dvd}\<close> theorem any_n_dvd_0 [forward]: "\<not> (\<exists> k. k dvd (0::nat) \<and> P k) \<Longrightarrow> \<not> (\<exists> k. P k)" by simp theorem n_dvd_one: "(n::nat) dvd 1 \<Longrightarrow> n = 1" by simp setup \<open>add_forward_prfstep_cond @{thm n_dvd_one} [with_cond "?n \<noteq> 1"]\<close> (* Products. *) setup \<open>add_rewrite_rule @{thm mult_zero_left}\<close> lemma prod_ineqs1 [forward]: "(m::nat) * k > 0 \<Longrightarrow> m > 0 \<and> k > 0" by simp lemma prod_ineqs2 [backward]: "(k::nat) > 0 \<Longrightarrow> m \<le> m * k" by simp theorem prod_cancel: "(a::nat) * b = a * c \<Longrightarrow> a > 0 \<Longrightarrow> b = c" by auto setup \<open>add_forward_prfstep_cond @{thm prod_cancel} [with_cond "?b \<noteq> ?c"]\<close> theorem mult_n1n: "(n::nat) = m * n \<Longrightarrow> n > 0 \<Longrightarrow> m = 1" by auto setup \<open>add_forward_prfstep_cond @{thm mult_n1n} [with_cond "?m \<noteq> 1"]\<close> theorem prod_is_one [forward]: "(x::nat) * y = 1 \<Longrightarrow> x = 1" by simp theorem prod_dvd_intro [backward]: "(k::nat) dvd m \<or> k dvd n \<Longrightarrow> k dvd m * n" using dvd_mult dvd_mult2 by blast (* Definition of gcd. *) setup \<open>add_forward_prfstep_cond @{thm gcd_dvd1} [with_term "gcd ?a ?b"]\<close> setup \<open>add_forward_prfstep_cond @{thm gcd_dvd2} [with_term "gcd ?a ?b"]\<close> (* Coprimality. *) setup \<open>add_rewrite_rule_bidir @{thm coprime_iff_gcd_eq_1}\<close> lemma coprime_exp [backward]: "coprime d a \<Longrightarrow> coprime (d::nat) (a ^ n)" by simp setup \<open>add_backward_prfstep @{thm coprime_exp}\<close> setup \<open>add_rewrite_rule @{thm gcd.commute}\<close> lemma coprime_dvd_mult [backward1]: "coprime (a::nat) b \<Longrightarrow> a dvd c * b \<Longrightarrow> a dvd c" by (metis coprime_dvd_mult_left_iff) lemma coprime_dvd_mult' [backward1]: "coprime (a::nat) b \<Longrightarrow> a dvd b * c \<Longrightarrow> a dvd c" by (metis coprime_dvd_mult_right_iff) theorem coprime_dvd [forward]: "coprime (a::nat) b \<Longrightarrow> p dvd a \<Longrightarrow> p > 1 \<Longrightarrow> \<not> p dvd b" using coprime_common_divisor_nat by blast (* Powers. *) setup \<open>add_rewrite_rule @{thm power_0}\<close> theorem power_ge_0 [rewrite]: "m \<noteq> 0 \<Longrightarrow> p ^ m = p * (p ^ (m - 1))" by (simp add: power_eq_if) setup \<open>add_rewrite_rule_cond @{thm power_one} [with_cond "?n \<noteq> 0"]\<close> setup \<open>add_rewrite_rule_cond @{thm power_one_right} [with_cond "?a \<noteq> 1"]\<close> setup \<open>add_gen_prfstep ("power_case_intro", [WithTerm @{term_pat "?p ^ (?FREE::nat)"}, CreateCase @{term_pat "(?FREE::nat) = 0"}])\<close> lemma one_is_power_of_any [resolve]: "\<exists>i. (1::nat) = a ^ i" by (metis power.simps(1)) setup \<open>add_rewrite_rule @{thm power_Suc}\<close> theorem power_dvd [forward]: "(p::nat)^n dvd a \<Longrightarrow> n \<noteq> 0 \<Longrightarrow> p dvd a" using dvd_power dvd_trans by blast theorem power_eq_one: "(b::nat) ^ n = 1 \<Longrightarrow> b = 1 \<or> n = 0" by (metis One_nat_def Suc_lessI nat_zero_less_power_iff power_0 power_inject_exp) setup \<open>add_forward_prfstep_cond @{thm power_eq_one} (with_conds ["?b \<noteq> 1", "?n \<noteq> 0"])\<close> (* Factorial. *) theorem fact_ge_1_nat: "fact (n::nat) \<ge> (1::nat)" by simp setup \<open>add_forward_prfstep_cond @{thm fact_ge_1_nat} [with_term "fact ?n"]\<close> setup \<open>add_backward1_prfstep @{thm dvd_fact}\<close> (* Successor function. *) setup \<open>add_rewrite_rule @{thm Nat.Suc_eq_plus1}\<close> setup \<open>add_backward_prfstep @{thm Nat.gr0_implies_Suc}\<close> (* Cases *) setup \<open>fold add_rewrite_rule @{thms Nat.nat.case}\<close> (* Induction. *) lemma nat_cases: "P 0 \<Longrightarrow> (\<And>n. P (Suc n)) \<Longrightarrow> P n" using nat_induct by auto (* div *) declare times_div_less_eq_dividend [resolve] setup \<open> add_var_induct_rule @{thm nat_induct} #> add_strong_induct_rule @{thm nat_less_induct} #> add_cases_rule @{thm nat_cases} \<close> end
theory Proof_3_500 imports Proofs3 begin theorem proof_3_500: "VC500 inv3 env s0 PdOut_value paid_value opened_value" apply(unfold VC500_def) apply simp apply(unfold inv3_def R3_def) apply(rule impI) apply(rule conjI) apply(rule conjI) apply simp apply(unfold extraInv_def)[1] apply(erule conjE) apply(erule conjE) subgoal premises vc_prems apply((rule allI)+) apply(rule impI) apply(simp split: if_splits) using vc_prems(1,3) substate_refl[of s0] apply blast using vc_prems(2) by auto
Monument 8 dates to the reign of Ruler 2 . It marks the period ending of 682 and shows the presentation of three war captives .
open import Oscar.Prelude open import Oscar.Class open import Oscar.Class.IsEquivalence open import Oscar.Data.𝟙 module Oscar.Class.HasEquivalence where module _ {𝔬} (𝔒 : Ø 𝔬) ℓ where 𝔥asEquivalence : Rℭlass 𝟙 𝔥asEquivalence = ∁ (𝔒 → 𝔒 → Ø ℓ) IsEquivalence open Rℭlass 𝔥asEquivalence using () renaming (GET-CLASS to HasEquivalence) public module _ {𝔬} (𝔒 : Ø 𝔬) {ℓ} where open Rℭlass (𝔥asEquivalence 𝔒 ℓ) using () renaming (GET-METHOD to Equivalence[_]) public infix 4 ≈-syntax ≈-syntax = Equivalence[_] syntax ≈-syntax 𝔒 x y = x ≈[ 𝔒 ] y module _ {𝔬} {𝔒 : Ø 𝔬} {ℓ} where open Rℭlass (𝔥asEquivalence 𝔒 ℓ) using () renaming (GET-METHOD to Equivalence) public infix 4 _≈_ _≈_ = Equivalence
subroutine foo() integer :: array_A(2), array_B(4) data array_A / 2 * 43 /, array_B / 1,2,3,4 / end subroutine
(* Title: FOL/ex/Locale_Test/Locale_Test.thy Author: Clemens Ballarin Test environment for the locale implementation. *) theory Locale_Test imports Locale_Test1 Locale_Test2 Locale_Test3 begin text \<open>Result of theory merge with distinct but identical interpretations\<close> context mixin_thy_merge begin lemmas less_mixin_thy_merge1 = le.less_def lemmas less_mixin_thy_merge2 = le'.less_def end lemma \<open>gless(x, y) \<longleftrightarrow> gle(x, y) \<and> x \<noteq> y\<close> (* mixin from first interpretation applied *) by (rule le1.less_mixin_thy_merge1) lemma \<open>gless'(x, y) \<longleftrightarrow> gle'(x, y) \<and> x \<noteq> y\<close> (* mixin from second interpretation applied *) by (rule le1.less_mixin_thy_merge2) end
#include <boost/preprocessor/tuple/to_array.hpp>
function combat!(player1, player2) haswinner = false while !haswinner playturn!(player1, player2) haswinner = isempty(player1) || isempty(player2) end end function playturn!(player1, player2) value1 = popfirst!(player1) value2 = popfirst!(player2) value1 > value2 ? append!(player1, [value1, value2]) : append!(player2, [value2, value1]) end
#pragma once #include <QLayout> #include <QWidget> #include <boost/variant.hpp> namespace chatterino { using LayoutItem = boost::variant<QWidget *, QLayout *>; template <typename T> T *makeLayout(std::initializer_list<LayoutItem> items) { auto t = new T; for (auto &item : items) { switch (item.which()) { case 0: t->addItem(new QWidgetItem(boost::get<QWidget *>(item))); break; case 1: t->addItem(boost::get<QLayout *>(item)); break; } } return t; } template <typename T, typename With> T *makeWidget(With with) { auto t = new T; with(t); return t; } } // namespace chatterino
{-# OPTIONS --without-K #-} module Library where open import Data.Product using ( Σ ; Σ-syntax ; _×_ ) public open import Function using () renaming ( id to λ-id ; _∘_ to λ-comp ; flip to λ-flip ) public open import Level using ( Level ) renaming ( zero to ℓ-zero ; suc to ℓ-suc ; _⊔_ to ℓ-max ) public open import Relation.Binary.Core using ( Rel ) public open import Relation.Unary using ( Pred ) public open import Relation.Binary.PropositionalEquality using ( _≡_ ; module ≡-Reasoning ) renaming ( refl to ≡-refl ; sym to ≡-sym ; trans to ≡-trans) public open ≡-Reasoning using ( _≡⟨_⟩_ ) renaming ( begin_ to ≡-proof_ ; _∎ to _≡-qed ) public
module Linear.Optics import Control.Optics import Linear.V export as_column : Iso (T [n] a) (T [n] b) (T [n, 1] a) (T [n, 1] b) as_column = iso (map pure) (map (\[x] => x)) export as_row : Iso (T [n] a) (T [n] b) (T [1, n] a) (T [1, n] b) as_row = iso pure (\[x] => x) export reshaped : (size : List Nat) -> {auto ns : _} -> {auto prf : prod ns = prod size} -> Iso (T ns a) (T ns b) (T size a) (T size b) reshaped size = iso (reshape size {ns}) (reshape ns {ns=size} {prf = sym prf})
fresh his and hers invitations templates and download twinkle twinkle little star text with gold star and moon for girl baby shower invitation 38 birthday invitations templates free for word. fresh his and hers invitations templates and lite wedding invitation template for everyone 73 invitation templates free printable word. new his and hers invitations templates and free gold sparkles party invitation template 91 invitation templates word download. beautiful his and hers invitations templates and cute wedding invitation template free vector 22 birthday invitations templates online free. ideas his and hers invitations templates for black adult birthday party invitation template 81 engagement invitation templates online. ideas his and hers invitations templates for floral invitation template free printable 72 christening invitation templates free printable. awesome his and hers invitations templates or printable birthday invitations for him invitation template men party wording elegant free of 69 invitation templates 70th birthday. inspirational his and hers invitations templates for elegant golden design invitation template free vector 72 invitation templates word download. awesome his and hers invitations templates for navy blue brown border church invitation 48 invitation templates word 2010. new his and hers invitations templates and birthday invitation templates for her 71 wedding invitations templates psd free. elegant his and hers invitations templates for floral baby shower invitation template 33 engagement invitation templates online. good his and hers invitations templates or birthday luau invitation 15 christmas invitations templates word. good his and hers invitations templates and birthday invites navy blue and gold birthday invitation for her 71 marriage invitation templates online. beautiful his and hers invitations templates and 58 wedding invitations templates word. luxury his and hers invitations templates and free gender reveal invitation template 11 christmas invitation templates free printable. unique his and hers invitations templates or wedding invitations templates free to inspire you in invitations attractive wedding 1 83 marriage invitation templates online. ideas his and hers invitations templates or birthday invitation template 32 invitation templates word 2010. fresh his and hers invitations templates or party invitation templates free 93 invitations templates photoshop. idea his and hers invitations templates for free wedding shower invitation template 49 blank invitation templates free for word. awesome his and hers invitations templates or invite template free download 22 invitation templates word download.
lemma analytic_on_analytic_at: "f analytic_on s \<longleftrightarrow> (\<forall>z \<in> s. f analytic_on {z})"
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Yury Kudryashov ! This file was ported from Lean 3 source module measure_theory.constructions.borel_space ! leanprover-community/mathlib commit fbde2f60a46865c85f49b4193175c6e339ff9020 ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathbin.Analysis.Complex.Basic import Mathbin.Analysis.NormedSpace.FiniteDimension import Mathbin.MeasureTheory.Function.AeMeasurableSequence import Mathbin.MeasureTheory.Group.Arithmetic import Mathbin.MeasureTheory.Lattice import Mathbin.MeasureTheory.Measure.OpenPos import Mathbin.Topology.Algebra.Order.LiminfLimsup import Mathbin.Topology.ContinuousFunction.Basic import Mathbin.Topology.Instances.AddCircle import Mathbin.Topology.Instances.Ereal import Mathbin.Topology.GDelta import Mathbin.Topology.Order.Lattice import Mathbin.Topology.Semicontinuous import Mathbin.Topology.MetricSpace.Metrizable /-! # Borel (measurable) space ## Main definitions * `borel α` : the least `σ`-algebra that contains all open sets; * `class borel_space` : a space with `topological_space` and `measurable_space` structures such that `‹measurable_space α› = borel α`; * `class opens_measurable_space` : a space with `topological_space` and `measurable_space` structures such that all open sets are measurable; equivalently, `borel α ≤ ‹measurable_space α›`. * `borel_space` instances on `empty`, `unit`, `bool`, `nat`, `int`, `rat`; * `measurable` and `borel_space` instances on `ℝ`, `ℝ≥0`, `ℝ≥0∞`. ## Main statements * `is_open.measurable_set`, `is_closed.measurable_set`: open and closed sets are measurable; * `continuous.measurable` : a continuous function is measurable; * `continuous.measurable2` : if `f : α → β` and `g : α → γ` are measurable and `op : β × γ → δ` is continuous, then `λ x, op (f x, g y)` is measurable; * `measurable.add` etc : dot notation for arithmetic operations on `measurable` predicates, and similarly for `dist` and `edist`; * `ae_measurable.add` : similar dot notation for almost everywhere measurable functions; * `measurable.ennreal*` : special cases for arithmetic operations on `ℝ≥0∞`. -/ noncomputable section open Classical Set Filter MeasureTheory open Classical BigOperators Topology NNReal ENNReal MeasureTheory universe u v w x y variable {α β γ γ₂ δ : Type _} {ι : Sort y} {s t u : Set α} open MeasurableSpace TopologicalSpace /-- `measurable_space` structure generated by `topological_space`. -/ def borel (α : Type u) [TopologicalSpace α] : MeasurableSpace α := generateFrom { s : Set α | IsOpen s } #align borel borel theorem borel_eq_top_of_discrete [TopologicalSpace α] [DiscreteTopology α] : borel α = ⊤ := top_le_iff.1 fun s hs => GenerateMeasurable.basic s (isOpen_discrete s) #align borel_eq_top_of_discrete borel_eq_top_of_discrete theorem borel_eq_top_of_countable [TopologicalSpace α] [T1Space α] [Countable α] : borel α = ⊤ := by refine' top_le_iff.1 fun s hs => bUnion_of_singleton s ▸ _ apply MeasurableSet.bunionᵢ s.to_countable intro x hx apply MeasurableSet.of_compl apply generate_measurable.basic exact is_closed_singleton.is_open_compl #align borel_eq_top_of_countable borel_eq_top_of_countable theorem borel_eq_generateFrom_of_subbasis {s : Set (Set α)} [t : TopologicalSpace α] [SecondCountableTopology α] (hs : t = generateFrom s) : borel α = generateFrom s := le_antisymm (generateFrom_le fun u (hu : t.IsOpen u) => by rw [hs] at hu induction hu case basic u hu => exact generate_measurable.basic u hu case univ => exact @MeasurableSet.univ α (generate_from s) case inter s₁ s₂ _ _ hs₁ hs₂ => exact @MeasurableSet.inter α (generate_from s) _ _ hs₁ hs₂ case sUnion f hf ih => rcases is_open_sUnion_countable f (by rwa [hs]) with ⟨v, hv, vf, vu⟩ rw [← vu] exact @MeasurableSet.unionₛ α (generate_from s) _ hv fun x xv => ih _ (vf xv)) (generateFrom_le fun u hu => GenerateMeasurable.basic _ <| show t.IsOpen u by rw [hs] <;> exact generate_open.basic _ hu) #align borel_eq_generate_from_of_subbasis borel_eq_generateFrom_of_subbasis theorem TopologicalSpace.IsTopologicalBasis.borel_eq_generateFrom [TopologicalSpace α] [SecondCountableTopology α] {s : Set (Set α)} (hs : IsTopologicalBasis s) : borel α = generateFrom s := borel_eq_generateFrom_of_subbasis hs.eq_generateFrom #align topological_space.is_topological_basis.borel_eq_generate_from TopologicalSpace.IsTopologicalBasis.borel_eq_generateFrom theorem isPiSystem_isOpen [TopologicalSpace α] : IsPiSystem (IsOpen : Set α → Prop) := fun s hs t ht hst => IsOpen.inter hs ht #align is_pi_system_is_open isPiSystem_isOpen theorem borel_eq_generateFrom_isClosed [TopologicalSpace α] : borel α = generateFrom { s | IsClosed s } := le_antisymm (generateFrom_le fun t ht => @MeasurableSet.of_compl α _ (generateFrom { s | IsClosed s }) (GenerateMeasurable.basic _ <| isClosed_compl_iff.2 ht)) (generateFrom_le fun t ht => @MeasurableSet.of_compl α _ (borel α) (GenerateMeasurable.basic _ <| isOpen_compl_iff.2 ht)) #align borel_eq_generate_from_is_closed borel_eq_generateFrom_isClosed section OrderTopology variable (α) variable [TopologicalSpace α] [SecondCountableTopology α] [LinearOrder α] [OrderTopology α] theorem borel_eq_generateFrom_Iio : borel α = generateFrom (range Iio) := by refine' le_antisymm _ (generate_from_le _) · rw [borel_eq_generateFrom_of_subbasis (@OrderTopology.topology_eq_generate_intervals α _ _ _)] letI : MeasurableSpace α := MeasurableSpace.generateFrom (range Iio) have H : ∀ a : α, MeasurableSet (Iio a) := fun a => generate_measurable.basic _ ⟨_, rfl⟩ refine' generate_from_le _ rintro _ ⟨a, rfl | rfl⟩ <;> [skip, apply H] by_cases h : ∃ a', ∀ b, a < b ↔ a' ≤ b · rcases h with ⟨a', ha'⟩ rw [(_ : Ioi a = Iio a'ᶜ)] · exact (H _).compl simp [Set.ext_iff, ha'] · rcases is_open_Union_countable (fun a' : { a' : α // a < a' } => { b | a'.1 < b }) fun a' => isOpen_lt' _ with ⟨v, ⟨hv⟩, vu⟩ simp [Set.ext_iff] at vu have : Ioi a = ⋃ x : v, Iio x.1.1ᶜ := by simp [Set.ext_iff] refine' fun x => ⟨fun ax => _, fun ⟨a', ⟨h, av⟩, ax⟩ => lt_of_lt_of_le h ax⟩ rcases(vu x).2 _ with ⟨a', h₁, h₂⟩ · exact ⟨a', h₁, le_of_lt h₂⟩ refine' not_imp_comm.1 (fun h => _) h exact ⟨x, fun b => ⟨fun ab => le_of_not_lt fun h' => h ⟨b, ab, h'⟩, lt_of_lt_of_le ax⟩⟩ rw [this] skip apply MeasurableSet.unionᵢ exact fun _ => (H _).compl · rw [forall_range_iff] intro a exact generate_measurable.basic _ isOpen_Iio #align borel_eq_generate_from_Iio borel_eq_generateFrom_Iio theorem borel_eq_generateFrom_Ioi : borel α = generateFrom (range Ioi) := @borel_eq_generateFrom_Iio αᵒᵈ _ (by infer_instance : SecondCountableTopology α) _ _ #align borel_eq_generate_from_Ioi borel_eq_generateFrom_Ioi end OrderTopology theorem borel_comap {f : α → β} {t : TopologicalSpace β} : @borel α (t.induced f) = (@borel β t).comap f := comap_generateFrom.symm #align borel_comap borel_comap theorem Continuous.borel_measurable [TopologicalSpace α] [TopologicalSpace β] {f : α → β} (hf : Continuous f) : @Measurable α β (borel α) (borel β) f := Measurable.of_le_map <| generateFrom_le fun s hs => GenerateMeasurable.basic (f ⁻¹' s) (hs.Preimage hf) #align continuous.borel_measurable Continuous.borel_measurable /-- A space with `measurable_space` and `topological_space` structures such that all open sets are measurable. -/ class OpensMeasurableSpace (α : Type _) [TopologicalSpace α] [h : MeasurableSpace α] : Prop where borel_le : borel α ≤ h #align opens_measurable_space OpensMeasurableSpace /-- A space with `measurable_space` and `topological_space` structures such that the `σ`-algebra of measurable sets is exactly the `σ`-algebra generated by open sets. -/ class BorelSpace (α : Type _) [TopologicalSpace α] [MeasurableSpace α] : Prop where measurable_eq : ‹MeasurableSpace α› = borel α #align borel_space BorelSpace namespace Tactic /-- Add instances `borel α : measurable_space α` and `⟨rfl⟩ : borel_space α`. -/ unsafe def add_borel_instance (α : expr) : tactic Unit := do let n1 ← get_unused_name "_inst" to_expr ``(borel $(α)) >>= pose n1 reset_instance_cache let n2 ← get_unused_name "_inst" let v ← to_expr ``((BorelSpace.mk rfl : BorelSpace $(α))) note n2 none v reset_instance_cache #align tactic.add_borel_instance tactic.add_borel_instance -- failed to format: unknown constant 'term.pseudo.antiquot' /-- Given a type `α`, an assumption `i : measurable_space α`, and an instance `[borel_space α]`, replace `i` with `borel α`. -/ unsafe def borel_to_refl ( α i : expr ) : tactic Unit := do let n ← get_unused_name "h" to_expr ` `( $ ( i ) = borel $ ( α ) ) >>= assert n applyc `borel_space.measurable_eq unfreezing ( tactic.subst i ) let n1 ← get_unused_name "_inst" to_expr ` `( borel $ ( α ) ) >>= pose n1 reset_instance_cache #align tactic.borel_to_refl tactic.borel_to_refl /-- Given a type `α`, if there is an assumption `[i : measurable_space α]`, then try to prove `[borel_space α]` and replace `i` with `borel α`. Otherwise, add instances `borel α : measurable_space α` and `⟨rfl⟩ : borel_space α`. -/ unsafe def borelize (α : expr) : tactic Unit := do let i ← optional (to_expr ``(MeasurableSpace $(α)) >>= find_assumption) i (add_borel_instance α) (borel_to_refl α) #align tactic.borelize tactic.borelize namespace Interactive /- ./././Mathport/Syntax/Translate/Tactic/Mathlib/Core.lean:38:34: unsupported: setup_tactic_parser -/ /-- The behaviour of `borelize α` depends on the existing assumptions on `α`. - if `α` is a topological space with instances `[measurable_space α] [borel_space α]`, then `borelize α` replaces the former instance by `borel α`; - otherwise, `borelize α` adds instances `borel α : measurable_space α` and `⟨rfl⟩ : borel_space α`. Finally, `borelize [α, β, γ]` runs `borelize α, borelize β, borelize γ`. -/ unsafe def borelize (ts : parse pexpr_list_or_texpr) : tactic Unit := mapM' (fun t => to_expr t >>= tactic.borelize) ts #align tactic.interactive.borelize tactic.interactive.borelize add_tactic_doc { Name := "borelize" category := DocCategory.tactic declNames := [`tactic.interactive.borelize] tags := ["type class"] } end Interactive end Tactic instance (priority := 100) OrderDual.opensMeasurableSpace {α : Type _} [TopologicalSpace α] [MeasurableSpace α] [h : OpensMeasurableSpace α] : OpensMeasurableSpace αᵒᵈ where borel_le := h.borel_le #align order_dual.opens_measurable_space OrderDual.opensMeasurableSpace instance (priority := 100) OrderDual.borelSpace {α : Type _} [TopologicalSpace α] [MeasurableSpace α] [h : BorelSpace α] : BorelSpace αᵒᵈ where measurable_eq := h.measurable_eq #align order_dual.borel_space OrderDual.borelSpace /-- In a `borel_space` all open sets are measurable. -/ instance (priority := 100) BorelSpace.opens_measurable {α : Type _} [TopologicalSpace α] [MeasurableSpace α] [BorelSpace α] : OpensMeasurableSpace α := ⟨ge_of_eq <| BorelSpace.measurable_eq⟩ #align borel_space.opens_measurable BorelSpace.opens_measurable instance Subtype.borelSpace {α : Type _} [TopologicalSpace α] [MeasurableSpace α] [hα : BorelSpace α] (s : Set α) : BorelSpace s := ⟨by rw [hα.1, Subtype.measurableSpace, ← borel_comap] rfl⟩ #align subtype.borel_space Subtype.borelSpace instance Subtype.opensMeasurableSpace {α : Type _} [TopologicalSpace α] [MeasurableSpace α] [h : OpensMeasurableSpace α] (s : Set α) : OpensMeasurableSpace s := ⟨by rw [borel_comap] exact comap_mono h.1⟩ #align subtype.opens_measurable_space Subtype.opensMeasurableSpace theorem MeasurableSet.induction_on_open [TopologicalSpace α] [MeasurableSpace α] [BorelSpace α] {C : Set α → Prop} (h_open : ∀ U, IsOpen U → C U) (h_compl : ∀ t, MeasurableSet t → C t → C (tᶜ)) (h_union : ∀ f : ℕ → Set α, Pairwise (Disjoint on f) → (∀ i, MeasurableSet (f i)) → (∀ i, C (f i)) → C (⋃ i, f i)) : ∀ ⦃t⦄, MeasurableSet t → C t := MeasurableSpace.induction_on_inter BorelSpace.measurable_eq isPiSystem_isOpen (h_open _ isOpen_empty) h_open h_compl h_union #align measurable_set.induction_on_open MeasurableSet.induction_on_open section variable [TopologicalSpace α] [MeasurableSpace α] [OpensMeasurableSpace α] [TopologicalSpace β] [MeasurableSpace β] [OpensMeasurableSpace β] [TopologicalSpace γ] [MeasurableSpace γ] [BorelSpace γ] [TopologicalSpace γ₂] [MeasurableSpace γ₂] [BorelSpace γ₂] [MeasurableSpace δ] theorem IsOpen.measurableSet (h : IsOpen s) : MeasurableSet s := OpensMeasurableSpace.borel_le _ <| GenerateMeasurable.basic _ h #align is_open.measurable_set IsOpen.measurableSet @[measurability] theorem measurableSet_interior : MeasurableSet (interior s) := isOpen_interior.MeasurableSet #align measurable_set_interior measurableSet_interior theorem IsGδ.measurableSet (h : IsGδ s) : MeasurableSet s := by rcases h with ⟨S, hSo, hSc, rfl⟩ exact MeasurableSet.interₛ hSc fun t ht => (hSo t ht).MeasurableSet #align is_Gδ.measurable_set IsGδ.measurableSet theorem measurableSet_of_continuousAt {β} [EMetricSpace β] (f : α → β) : MeasurableSet { x | ContinuousAt f x } := (isGδ_setOf_continuousAt f).MeasurableSet #align measurable_set_of_continuous_at measurableSet_of_continuousAt theorem IsClosed.measurableSet (h : IsClosed s) : MeasurableSet s := h.isOpen_compl.MeasurableSet.ofCompl #align is_closed.measurable_set IsClosed.measurableSet theorem IsCompact.measurableSet [T2Space α] (h : IsCompact s) : MeasurableSet s := h.IsClosed.MeasurableSet #align is_compact.measurable_set IsCompact.measurableSet @[measurability] theorem measurableSet_closure : MeasurableSet (closure s) := isClosed_closure.MeasurableSet #align measurable_set_closure measurableSet_closure theorem measurable_of_isOpen {f : δ → γ} (hf : ∀ s, IsOpen s → MeasurableSet (f ⁻¹' s)) : Measurable f := by rw [‹BorelSpace γ›.measurable_eq] exact measurable_generateFrom hf #align measurable_of_is_open measurable_of_isOpen theorem measurable_of_isClosed {f : δ → γ} (hf : ∀ s, IsClosed s → MeasurableSet (f ⁻¹' s)) : Measurable f := by apply measurable_of_isOpen; intro s hs rw [← MeasurableSet.compl_iff, ← preimage_compl]; apply hf; rw [isClosed_compl_iff]; exact hs #align measurable_of_is_closed measurable_of_isClosed theorem measurable_of_is_closed' {f : δ → γ} (hf : ∀ s, IsClosed s → s.Nonempty → s ≠ univ → MeasurableSet (f ⁻¹' s)) : Measurable f := by apply measurable_of_isClosed; intro s hs cases' eq_empty_or_nonempty s with h1 h1; · simp [h1] by_cases h2 : s = univ; · simp [h2] exact hf s hs h1 h2 #align measurable_of_is_closed' measurable_of_is_closed' instance nhds_isMeasurablyGenerated (a : α) : (𝓝 a).IsMeasurablyGenerated := by rw [nhds, infᵢ_subtype'] refine' @Filter.infᵢ_isMeasurablyGenerated _ _ _ _ fun i => _ exact i.2.2.MeasurableSet.principal_isMeasurablyGenerated #align nhds_is_measurably_generated nhds_isMeasurablyGenerated /-- If `s` is a measurable set, then `𝓝[s] a` is a measurably generated filter for each `a`. This cannot be an `instance` because it depends on a non-instance `hs : measurable_set s`. -/ theorem MeasurableSet.nhdsWithin_isMeasurablyGenerated {s : Set α} (hs : MeasurableSet s) (a : α) : (𝓝[s] a).IsMeasurablyGenerated := haveI := hs.principal_is_measurably_generated Filter.inf_isMeasurablyGenerated _ _ #align measurable_set.nhds_within_is_measurably_generated MeasurableSet.nhdsWithin_isMeasurablyGenerated -- see Note [lower instance priority] instance (priority := 100) OpensMeasurableSpace.to_measurableSingletonClass [T1Space α] : MeasurableSingletonClass α := ⟨fun x => isClosed_singleton.MeasurableSet⟩ #align opens_measurable_space.to_measurable_singleton_class OpensMeasurableSpace.to_measurableSingletonClass instance Pi.opensMeasurableSpace {ι : Type _} {π : ι → Type _} [Countable ι] [t' : ∀ i, TopologicalSpace (π i)] [∀ i, MeasurableSpace (π i)] [∀ i, SecondCountableTopology (π i)] [∀ i, OpensMeasurableSpace (π i)] : OpensMeasurableSpace (∀ i, π i) := by constructor have : Pi.topologicalSpace = generate_from { t | ∃ (s : ∀ a, Set (π a))(i : Finset ι), (∀ a ∈ i, s a ∈ countable_basis (π a)) ∧ t = pi (↑i) s } := by rw [funext fun a => @eq_generate_from_countable_basis (π a) _ _, pi_generateFrom_eq] rw [borel_eq_generateFrom_of_subbasis this] apply generate_from_le rintro _ ⟨s, i, hi, rfl⟩ refine' MeasurableSet.pi i.countable_to_set fun a ha => IsOpen.measurableSet _ rw [eq_generate_from_countable_basis (π a)] exact generate_open.basic _ (hi a ha) #align pi.opens_measurable_space Pi.opensMeasurableSpace instance Prod.opensMeasurableSpace [SecondCountableTopology α] [SecondCountableTopology β] : OpensMeasurableSpace (α × β) := by constructor rw [((is_basis_countable_basis α).Prod (is_basis_countable_basis β)).borel_eq_generateFrom] apply generate_from_le rintro _ ⟨u, v, hu, hv, rfl⟩ exact (is_open_of_mem_countable_basis hu).MeasurableSet.Prod (is_open_of_mem_countable_basis hv).MeasurableSet #align prod.opens_measurable_space Prod.opensMeasurableSpace variable {α' : Type _} [TopologicalSpace α'] [MeasurableSpace α'] theorem interior_ae_eq_of_null_frontier {μ : Measure α'} {s : Set α'} (h : μ (frontier s) = 0) : interior s =ᵐ[μ] s := interior_subset.EventuallyLE.antisymm <| subset_closure.EventuallyLE.trans (ae_le_set.2 h) #align interior_ae_eq_of_null_frontier interior_ae_eq_of_null_frontier theorem measure_interior_of_null_frontier {μ : Measure α'} {s : Set α'} (h : μ (frontier s) = 0) : μ (interior s) = μ s := measure_congr (interior_ae_eq_of_null_frontier h) #align measure_interior_of_null_frontier measure_interior_of_null_frontier theorem nullMeasurableSetOfNullFrontier {s : Set α} {μ : Measure α} (h : μ (frontier s) = 0) : NullMeasurableSet s μ := ⟨interior s, isOpen_interior.MeasurableSet, (interior_ae_eq_of_null_frontier h).symm⟩ #align null_measurable_set_of_null_frontier nullMeasurableSetOfNullFrontier theorem closure_ae_eq_of_null_frontier {μ : Measure α'} {s : Set α'} (h : μ (frontier s) = 0) : closure s =ᵐ[μ] s := ((ae_le_set.2 h).trans interior_subset.EventuallyLE).antisymm <| subset_closure.EventuallyLE #align closure_ae_eq_of_null_frontier closure_ae_eq_of_null_frontier theorem measure_closure_of_null_frontier {μ : Measure α'} {s : Set α'} (h : μ (frontier s) = 0) : μ (closure s) = μ s := measure_congr (closure_ae_eq_of_null_frontier h) #align measure_closure_of_null_frontier measure_closure_of_null_frontier section Preorder variable [Preorder α] [OrderClosedTopology α] {a b x : α} @[simp, measurability] theorem measurableSet_Ici : MeasurableSet (Ici a) := isClosed_Ici.MeasurableSet #align measurable_set_Ici measurableSet_Ici @[simp, measurability] theorem measurableSet_Iic : MeasurableSet (Iic a) := isClosed_Iic.MeasurableSet #align measurable_set_Iic measurableSet_Iic @[simp, measurability] theorem measurableSet_Icc : MeasurableSet (Icc a b) := isClosed_Icc.MeasurableSet #align measurable_set_Icc measurableSet_Icc instance nhdsWithin_Ici_isMeasurablyGenerated : (𝓝[Ici b] a).IsMeasurablyGenerated := measurableSet_Ici.nhdsWithin_isMeasurablyGenerated _ #align nhds_within_Ici_is_measurably_generated nhdsWithin_Ici_isMeasurablyGenerated instance nhdsWithin_Iic_isMeasurablyGenerated : (𝓝[Iic b] a).IsMeasurablyGenerated := measurableSet_Iic.nhdsWithin_isMeasurablyGenerated _ #align nhds_within_Iic_is_measurably_generated nhdsWithin_Iic_isMeasurablyGenerated instance nhdsWithin_Icc_isMeasurablyGenerated : IsMeasurablyGenerated (𝓝[Icc a b] x) := by rw [← Ici_inter_Iic, nhdsWithin_inter] infer_instance #align nhds_within_Icc_is_measurably_generated nhdsWithin_Icc_isMeasurablyGenerated instance atTop_isMeasurablyGenerated : (Filter.atTop : Filter α).IsMeasurablyGenerated := @Filter.infᵢ_isMeasurablyGenerated _ _ _ _ fun a => (measurableSet_Ici : MeasurableSet (Ici a)).principal_isMeasurablyGenerated #align at_top_is_measurably_generated atTop_isMeasurablyGenerated instance atBot_isMeasurablyGenerated : (Filter.atBot : Filter α).IsMeasurablyGenerated := @Filter.infᵢ_isMeasurablyGenerated _ _ _ _ fun a => (measurableSet_Iic : MeasurableSet (Iic a)).principal_isMeasurablyGenerated #align at_bot_is_measurably_generated atBot_isMeasurablyGenerated end Preorder section PartialOrder variable [PartialOrder α] [OrderClosedTopology α] [SecondCountableTopology α] {a b : α} @[measurability] theorem measurableSet_le' : MeasurableSet { p : α × α | p.1 ≤ p.2 } := OrderClosedTopology.isClosed_le'.MeasurableSet #align measurable_set_le' measurableSet_le' @[measurability] theorem measurableSet_le {f g : δ → α} (hf : Measurable f) (hg : Measurable g) : MeasurableSet { a | f a ≤ g a } := hf.prod_mk hg measurableSet_le' #align measurable_set_le measurableSet_le end PartialOrder section LinearOrder variable [LinearOrder α] [OrderClosedTopology α] {a b x : α} -- we open this locale only here to avoid issues with list being treated as intervals above open Interval @[simp, measurability] theorem measurableSet_Iio : MeasurableSet (Iio a) := isOpen_Iio.MeasurableSet #align measurable_set_Iio measurableSet_Iio @[simp, measurability] theorem measurableSet_Ioi : MeasurableSet (Ioi a) := isOpen_Ioi.MeasurableSet #align measurable_set_Ioi measurableSet_Ioi @[simp, measurability] theorem measurableSet_Ioo : MeasurableSet (Ioo a b) := isOpen_Ioo.MeasurableSet #align measurable_set_Ioo measurableSet_Ioo @[simp, measurability] theorem measurableSet_Ioc : MeasurableSet (Ioc a b) := measurableSet_Ioi.inter measurableSet_Iic #align measurable_set_Ioc measurableSet_Ioc @[simp, measurability] theorem measurableSet_Ico : MeasurableSet (Ico a b) := measurableSet_Ici.inter measurableSet_Iio #align measurable_set_Ico measurableSet_Ico instance nhdsWithin_Ioi_isMeasurablyGenerated : (𝓝[Ioi b] a).IsMeasurablyGenerated := measurableSet_Ioi.nhdsWithin_isMeasurablyGenerated _ #align nhds_within_Ioi_is_measurably_generated nhdsWithin_Ioi_isMeasurablyGenerated instance nhdsWithin_Iio_isMeasurablyGenerated : (𝓝[Iio b] a).IsMeasurablyGenerated := measurableSet_Iio.nhdsWithin_isMeasurablyGenerated _ #align nhds_within_Iio_is_measurably_generated nhdsWithin_Iio_isMeasurablyGenerated instance nhdsWithin_uIcc_isMeasurablyGenerated : IsMeasurablyGenerated (𝓝[[a, b]] x) := nhdsWithin_Icc_isMeasurablyGenerated #align nhds_within_uIcc_is_measurably_generated nhdsWithin_uIcc_isMeasurablyGenerated @[measurability] theorem measurableSet_lt' [SecondCountableTopology α] : MeasurableSet { p : α × α | p.1 < p.2 } := (isOpen_lt continuous_fst continuous_snd).MeasurableSet #align measurable_set_lt' measurableSet_lt' @[measurability] theorem measurableSet_lt [SecondCountableTopology α] {f g : δ → α} (hf : Measurable f) (hg : Measurable g) : MeasurableSet { a | f a < g a } := hf.prod_mk hg measurableSet_lt' #align measurable_set_lt measurableSet_lt theorem nullMeasurableSetLt [SecondCountableTopology α] {μ : Measure δ} {f g : δ → α} (hf : AeMeasurable f μ) (hg : AeMeasurable g μ) : NullMeasurableSet { a | f a < g a } μ := (hf.prod_mk hg).NullMeasurable measurableSet_lt' #align null_measurable_set_lt nullMeasurableSetLt theorem Set.OrdConnected.measurableSet (h : OrdConnected s) : MeasurableSet s := by let u := ⋃ (x ∈ s) (y ∈ s), Ioo x y have huopen : IsOpen u := isOpen_bunionᵢ fun x hx => isOpen_bunionᵢ fun y hy => isOpen_Ioo have humeas : MeasurableSet u := huopen.measurable_set have hfinite : (s \ u).Finite := s.finite_diff_Union_Ioo have : u ⊆ s := Union₂_subset fun x hx => Union₂_subset fun y hy => Ioo_subset_Icc_self.trans (h.out hx hy) rw [← union_diff_cancel this] exact humeas.union hfinite.measurable_set #align set.ord_connected.measurable_set Set.OrdConnected.measurableSet theorem IsPreconnected.measurableSet (h : IsPreconnected s) : MeasurableSet s := h.OrdConnected.MeasurableSet #align is_preconnected.measurable_set IsPreconnected.measurableSet theorem generateFrom_Ico_mem_le_borel {α : Type _} [TopologicalSpace α] [LinearOrder α] [OrderClosedTopology α] (s t : Set α) : MeasurableSpace.generateFrom { S | ∃ l ∈ s, ∃ u ∈ t, ∃ h : l < u, Ico l u = S } ≤ borel α := by apply generate_from_le borelize α rintro _ ⟨a, -, b, -, -, rfl⟩ exact measurableSet_Ico #align generate_from_Ico_mem_le_borel generateFrom_Ico_mem_le_borel theorem Dense.borel_eq_generateFrom_Ico_mem_aux {α : Type _} [TopologicalSpace α] [LinearOrder α] [OrderTopology α] [SecondCountableTopology α] {s : Set α} (hd : Dense s) (hbot : ∀ x, IsBot x → x ∈ s) (hIoo : ∀ x y : α, x < y → Ioo x y = ∅ → y ∈ s) : borel α = generateFrom { S : Set α | ∃ l ∈ s, ∃ u ∈ s, ∃ h : l < u, Ico l u = S } := by set S : Set (Set α) := { S | ∃ l ∈ s, ∃ u ∈ s, ∃ h : l < u, Ico l u = S } refine' le_antisymm _ (generateFrom_Ico_mem_le_borel _ _) letI : MeasurableSpace α := generate_from S rw [borel_eq_generateFrom_Iio] refine' generate_from_le (forall_range_iff.2 fun a => _) rcases hd.exists_countable_dense_subset_bot_top with ⟨t, hts, hc, htd, htb, htt⟩ by_cases ha : ∀ b < a, (Ioo b a).Nonempty · convert_to MeasurableSet (⋃ (l ∈ t) (u ∈ t) (hlu : l < u) (hu : u ≤ a), Ico l u) · ext y simp only [mem_Union, mem_Iio, mem_Ico] constructor · intro hy rcases htd.exists_le' (fun b hb => htb _ hb (hbot b hb)) y with ⟨l, hlt, hly⟩ rcases htd.exists_mem_open isOpen_Ioo (ha y hy) with ⟨u, hut, hyu, hua⟩ exact ⟨l, hlt, u, hut, hly.trans_lt hyu, hua.le, hly, hyu⟩ · rintro ⟨l, -, u, -, -, hua, -, hyu⟩ exact hyu.trans_le hua · refine' MeasurableSet.bunionᵢ hc fun a ha => MeasurableSet.bunionᵢ hc fun b hb => _ refine' MeasurableSet.unionᵢ fun hab => MeasurableSet.unionᵢ fun hb' => _ exact generate_measurable.basic _ ⟨a, hts ha, b, hts hb, hab, mem_singleton _⟩ · simp only [not_forall, not_nonempty_iff_eq_empty] at ha replace ha : a ∈ s := hIoo ha.some a ha.some_spec.fst ha.some_spec.snd convert_to MeasurableSet (⋃ (l ∈ t) (hl : l < a), Ico l a) · symm simp only [← Ici_inter_Iio, ← Union_inter, inter_eq_right_iff_subset, subset_def, mem_Union, mem_Ici, mem_Iio] intro x hx rcases htd.exists_le' (fun b hb => htb _ hb (hbot b hb)) x with ⟨z, hzt, hzx⟩ exact ⟨z, hzt, hzx.trans_lt hx, hzx⟩ · refine' MeasurableSet.bunionᵢ hc fun x hx => MeasurableSet.unionᵢ fun hlt => _ exact generate_measurable.basic _ ⟨x, hts hx, a, ha, hlt, mem_singleton _⟩ #align dense.borel_eq_generate_from_Ico_mem_aux Dense.borel_eq_generateFrom_Ico_mem_aux theorem Dense.borel_eq_generateFrom_Ico_mem {α : Type _} [TopologicalSpace α] [LinearOrder α] [OrderTopology α] [SecondCountableTopology α] [DenselyOrdered α] [NoMinOrder α] {s : Set α} (hd : Dense s) : borel α = generateFrom { S : Set α | ∃ l ∈ s, ∃ u ∈ s, ∃ h : l < u, Ico l u = S } := hd.borel_eq_generateFrom_Ico_mem_aux (by simp) fun x y hxy H => ((nonempty_Ioo.2 hxy).ne_empty H).elim #align dense.borel_eq_generate_from_Ico_mem Dense.borel_eq_generateFrom_Ico_mem theorem borel_eq_generateFrom_Ico (α : Type _) [TopologicalSpace α] [SecondCountableTopology α] [LinearOrder α] [OrderTopology α] : borel α = generateFrom { S : Set α | ∃ (l u : _)(h : l < u), Ico l u = S } := by simpa only [exists_prop, mem_univ, true_and_iff] using (@dense_univ α _).borel_eq_generateFrom_Ico_mem_aux (fun _ _ => mem_univ _) fun _ _ _ _ => mem_univ _ #align borel_eq_generate_from_Ico borel_eq_generateFrom_Ico theorem Dense.borel_eq_generateFrom_Ioc_mem_aux {α : Type _} [TopologicalSpace α] [LinearOrder α] [OrderTopology α] [SecondCountableTopology α] {s : Set α} (hd : Dense s) (hbot : ∀ x, IsTop x → x ∈ s) (hIoo : ∀ x y : α, x < y → Ioo x y = ∅ → x ∈ s) : borel α = generateFrom { S : Set α | ∃ l ∈ s, ∃ u ∈ s, ∃ h : l < u, Ioc l u = S } := by convert hd.order_dual.borel_eq_generate_from_Ico_mem_aux hbot fun x y hlt he => hIoo y x hlt _ · ext s constructor <;> rintro ⟨l, hl, u, hu, hlt, rfl⟩ exacts[⟨u, hu, l, hl, hlt, dual_Ico⟩, ⟨u, hu, l, hl, hlt, dual_Ioc⟩] · erw [dual_Ioo] exact he #align dense.borel_eq_generate_from_Ioc_mem_aux Dense.borel_eq_generateFrom_Ioc_mem_aux theorem Dense.borel_eq_generateFrom_Ioc_mem {α : Type _} [TopologicalSpace α] [LinearOrder α] [OrderTopology α] [SecondCountableTopology α] [DenselyOrdered α] [NoMaxOrder α] {s : Set α} (hd : Dense s) : borel α = generateFrom { S : Set α | ∃ l ∈ s, ∃ u ∈ s, ∃ h : l < u, Ioc l u = S } := hd.borel_eq_generateFrom_Ioc_mem_aux (by simp) fun x y hxy H => ((nonempty_Ioo.2 hxy).ne_empty H).elim #align dense.borel_eq_generate_from_Ioc_mem Dense.borel_eq_generateFrom_Ioc_mem theorem borel_eq_generateFrom_Ioc (α : Type _) [TopologicalSpace α] [SecondCountableTopology α] [LinearOrder α] [OrderTopology α] : borel α = generateFrom { S : Set α | ∃ (l u : _)(h : l < u), Ioc l u = S } := by simpa only [exists_prop, mem_univ, true_and_iff] using (@dense_univ α _).borel_eq_generateFrom_Ioc_mem_aux (fun _ _ => mem_univ _) fun _ _ _ _ => mem_univ _ #align borel_eq_generate_from_Ioc borel_eq_generateFrom_Ioc namespace MeasureTheory.Measure /-- Two finite measures on a Borel space are equal if they agree on all closed-open intervals. If `α` is a conditionally complete linear order with no top element, `measure_theory.measure..ext_of_Ico` is an extensionality lemma with weaker assumptions on `μ` and `ν`. -/ theorem ext_of_Ico_finite {α : Type _} [TopologicalSpace α] {m : MeasurableSpace α} [SecondCountableTopology α] [LinearOrder α] [OrderTopology α] [BorelSpace α] (μ ν : Measure α) [IsFiniteMeasure μ] (hμν : μ univ = ν univ) (h : ∀ ⦃a b⦄, a < b → μ (Ico a b) = ν (Ico a b)) : μ = ν := by refine' ext_of_generate_finite _ (borel_space.measurable_eq.trans (borel_eq_generateFrom_Ico α)) (isPiSystem_Ico (id : α → α) id) _ hμν · rintro - ⟨a, b, hlt, rfl⟩ exact h hlt #align measure_theory.measure.ext_of_Ico_finite MeasureTheory.Measure.ext_of_Ico_finite /-- Two finite measures on a Borel space are equal if they agree on all open-closed intervals. If `α` is a conditionally complete linear order with no top element, `measure_theory.measure..ext_of_Ioc` is an extensionality lemma with weaker assumptions on `μ` and `ν`. -/ theorem ext_of_Ioc_finite {α : Type _} [TopologicalSpace α] {m : MeasurableSpace α} [SecondCountableTopology α] [LinearOrder α] [OrderTopology α] [BorelSpace α] (μ ν : Measure α) [IsFiniteMeasure μ] (hμν : μ univ = ν univ) (h : ∀ ⦃a b⦄, a < b → μ (Ioc a b) = ν (Ioc a b)) : μ = ν := by refine' @ext_of_Ico_finite αᵒᵈ _ _ _ _ _ ‹_› μ ν _ hμν fun a b hab => _ erw [dual_Ico] exact h hab #align measure_theory.measure.ext_of_Ioc_finite MeasureTheory.Measure.ext_of_Ioc_finite /-- Two measures which are finite on closed-open intervals are equal if the agree on all closed-open intervals. -/ theorem ext_of_Ico' {α : Type _} [TopologicalSpace α] {m : MeasurableSpace α} [SecondCountableTopology α] [LinearOrder α] [OrderTopology α] [BorelSpace α] [NoMaxOrder α] (μ ν : Measure α) (hμ : ∀ ⦃a b⦄, a < b → μ (Ico a b) ≠ ∞) (h : ∀ ⦃a b⦄, a < b → μ (Ico a b) = ν (Ico a b)) : μ = ν := by rcases exists_countable_dense_bot_top α with ⟨s, hsc, hsd, hsb, hst⟩ have : (⋃ (l ∈ s) (u ∈ s) (h : l < u), {Ico l u} : Set (Set α)).Countable := hsc.bUnion fun l hl => hsc.bUnion fun u hu => countable_Union fun _ => countable_singleton _ simp only [← set_of_eq_eq_singleton, ← set_of_exists] at this refine' measure.ext_of_generate_from_of_cover_subset (borel_space.measurable_eq.trans (borel_eq_generateFrom_Ico α)) (isPiSystem_Ico id id) _ this _ _ _ · rintro _ ⟨l, -, u, -, h, rfl⟩ exact ⟨l, u, h, rfl⟩ · refine' sUnion_eq_univ_iff.2 fun x => _ rcases hsd.exists_le' hsb x with ⟨l, hls, hlx⟩ rcases hsd.exists_gt x with ⟨u, hus, hxu⟩ exact ⟨_, ⟨l, hls, u, hus, hlx.trans_lt hxu, rfl⟩, hlx, hxu⟩ · rintro _ ⟨l, -, u, -, hlt, rfl⟩ exact hμ hlt · rintro _ ⟨l, u, hlt, rfl⟩ exact h hlt #align measure_theory.measure.ext_of_Ico' MeasureTheory.Measure.ext_of_Ico' /-- Two measures which are finite on closed-open intervals are equal if the agree on all open-closed intervals. -/ theorem ext_of_Ioc' {α : Type _} [TopologicalSpace α] {m : MeasurableSpace α} [SecondCountableTopology α] [LinearOrder α] [OrderTopology α] [BorelSpace α] [NoMinOrder α] (μ ν : Measure α) (hμ : ∀ ⦃a b⦄, a < b → μ (Ioc a b) ≠ ∞) (h : ∀ ⦃a b⦄, a < b → μ (Ioc a b) = ν (Ioc a b)) : μ = ν := by refine' @ext_of_Ico' αᵒᵈ _ _ _ _ _ ‹_› _ μ ν _ _ <;> intro a b hab <;> erw [dual_Ico] exacts[hμ hab, h hab] #align measure_theory.measure.ext_of_Ioc' MeasureTheory.Measure.ext_of_Ioc' /-- Two measures which are finite on closed-open intervals are equal if the agree on all closed-open intervals. -/ theorem ext_of_Ico {α : Type _} [TopologicalSpace α] {m : MeasurableSpace α} [SecondCountableTopology α] [ConditionallyCompleteLinearOrder α] [OrderTopology α] [BorelSpace α] [NoMaxOrder α] (μ ν : Measure α) [IsLocallyFiniteMeasure μ] (h : ∀ ⦃a b⦄, a < b → μ (Ico a b) = ν (Ico a b)) : μ = ν := μ.ext_of_Ico' ν (fun a b hab => measure_Ico_lt_top.Ne) h #align measure_theory.measure.ext_of_Ico MeasureTheory.Measure.ext_of_Ico /-- Two measures which are finite on closed-open intervals are equal if the agree on all open-closed intervals. -/ theorem ext_of_Ioc {α : Type _} [TopologicalSpace α] {m : MeasurableSpace α} [SecondCountableTopology α] [ConditionallyCompleteLinearOrder α] [OrderTopology α] [BorelSpace α] [NoMinOrder α] (μ ν : Measure α) [IsLocallyFiniteMeasure μ] (h : ∀ ⦃a b⦄, a < b → μ (Ioc a b) = ν (Ioc a b)) : μ = ν := μ.ext_of_Ioc' ν (fun a b hab => measure_Ioc_lt_top.Ne) h #align measure_theory.measure.ext_of_Ioc MeasureTheory.Measure.ext_of_Ioc /-- Two finite measures on a Borel space are equal if they agree on all left-infinite right-closed intervals. -/ theorem ext_of_Iic {α : Type _} [TopologicalSpace α] {m : MeasurableSpace α} [SecondCountableTopology α] [LinearOrder α] [OrderTopology α] [BorelSpace α] (μ ν : Measure α) [IsFiniteMeasure μ] (h : ∀ a, μ (Iic a) = ν (Iic a)) : μ = ν := by refine' ext_of_Ioc_finite μ ν _ fun a b hlt => _ · rcases exists_countable_dense_bot_top α with ⟨s, hsc, hsd, -, hst⟩ have : DirectedOn (· ≤ ·) s := directedOn_iff_directed.2 (directed_of_sup fun _ _ => id) simp only [← bsupr_measure_Iic hsc (hsd.exists_ge' hst) this, h] rw [← Iic_diff_Iic, measure_diff (Iic_subset_Iic.2 hlt.le) measurableSet_Iic, measure_diff (Iic_subset_Iic.2 hlt.le) measurableSet_Iic, h a, h b] · rw [← h a] exact (measure_lt_top μ _).Ne · exact (measure_lt_top μ _).Ne #align measure_theory.measure.ext_of_Iic MeasureTheory.Measure.ext_of_Iic /-- Two finite measures on a Borel space are equal if they agree on all left-closed right-infinite intervals. -/ theorem ext_of_Ici {α : Type _} [TopologicalSpace α] {m : MeasurableSpace α} [SecondCountableTopology α] [LinearOrder α] [OrderTopology α] [BorelSpace α] (μ ν : Measure α) [IsFiniteMeasure μ] (h : ∀ a, μ (Ici a) = ν (Ici a)) : μ = ν := @ext_of_Iic αᵒᵈ _ _ _ _ _ ‹_› _ _ _ h #align measure_theory.measure.ext_of_Ici MeasureTheory.Measure.ext_of_Ici end MeasureTheory.Measure end LinearOrder section LinearOrder variable [LinearOrder α] [OrderClosedTopology α] {a b : α} @[measurability] theorem measurableSet_uIcc : MeasurableSet (uIcc a b) := measurableSet_Icc #align measurable_set_uIcc measurableSet_uIcc @[measurability] theorem measurableSet_uIoc : MeasurableSet (uIoc a b) := measurableSet_Ioc #align measurable_set_uIoc measurableSet_uIoc variable [SecondCountableTopology α] @[measurability] theorem Measurable.max {f g : δ → α} (hf : Measurable f) (hg : Measurable g) : Measurable fun a => max (f a) (g a) := by simpa only [max_def'] using hf.piecewise (measurableSet_le hg hf) hg #align measurable.max Measurable.max @[measurability] theorem AeMeasurable.max {f g : δ → α} {μ : Measure δ} (hf : AeMeasurable f μ) (hg : AeMeasurable g μ) : AeMeasurable (fun a => max (f a) (g a)) μ := ⟨fun a => max (hf.mk f a) (hg.mk g a), hf.measurable_mk.max hg.measurable_mk, EventuallyEq.comp₂ hf.ae_eq_mk _ hg.ae_eq_mk⟩ #align ae_measurable.max AeMeasurable.max @[measurability] theorem Measurable.min {f g : δ → α} (hf : Measurable f) (hg : Measurable g) : Measurable fun a => min (f a) (g a) := by simpa only [min_def] using hf.piecewise (measurableSet_le hf hg) hg #align measurable.min Measurable.min @[measurability] theorem AeMeasurable.min {f g : δ → α} {μ : Measure δ} (hf : AeMeasurable f μ) (hg : AeMeasurable g μ) : AeMeasurable (fun a => min (f a) (g a)) μ := ⟨fun a => min (hf.mk f a) (hg.mk g a), hf.measurable_mk.min hg.measurable_mk, EventuallyEq.comp₂ hf.ae_eq_mk _ hg.ae_eq_mk⟩ #align ae_measurable.min AeMeasurable.min end LinearOrder /-- A continuous function from an `opens_measurable_space` to a `borel_space` is measurable. -/ theorem Continuous.measurable {f : α → γ} (hf : Continuous f) : Measurable f := hf.borel_measurable.mono OpensMeasurableSpace.borel_le (le_of_eq <| BorelSpace.measurable_eq) #align continuous.measurable Continuous.measurable /-- A continuous function from an `opens_measurable_space` to a `borel_space` is ae-measurable. -/ theorem Continuous.aeMeasurable {f : α → γ} (h : Continuous f) {μ : Measure α} : AeMeasurable f μ := h.Measurable.AeMeasurable #align continuous.ae_measurable Continuous.aeMeasurable theorem ClosedEmbedding.measurable {f : α → γ} (hf : ClosedEmbedding f) : Measurable f := hf.Continuous.Measurable #align closed_embedding.measurable ClosedEmbedding.measurable theorem Continuous.isOpenPosMeasureMap {f : β → γ} (hf : Continuous f) (hf_surj : Function.Surjective f) {μ : Measure β} [μ.IsOpenPosMeasure] : (Measure.map f μ).IsOpenPosMeasure := by refine' ⟨fun U hUo hUne => _⟩ rw [measure.map_apply hf.measurable hUo.measurable_set] exact (hUo.preimage hf).measure_ne_zero μ (hf_surj.nonempty_preimage.mpr hUne) #align continuous.is_open_pos_measure_map Continuous.isOpenPosMeasureMap /-- If a function is defined piecewise in terms of functions which are continuous on their respective pieces, then it is measurable. -/ theorem ContinuousOn.measurable_piecewise {f g : α → γ} {s : Set α} [∀ j : α, Decidable (j ∈ s)] (hf : ContinuousOn f s) (hg : ContinuousOn g (sᶜ)) (hs : MeasurableSet s) : Measurable (s.piecewise f g) := by refine' measurable_of_isOpen fun t ht => _ rw [piecewise_preimage, Set.ite] apply MeasurableSet.union · rcases _root_.continuous_on_iff'.1 hf t ht with ⟨u, u_open, hu⟩ rw [hu] exact u_open.measurable_set.inter hs · rcases _root_.continuous_on_iff'.1 hg t ht with ⟨u, u_open, hu⟩ rw [diff_eq_compl_inter, inter_comm, hu] exact u_open.measurable_set.inter hs.compl #align continuous_on.measurable_piecewise ContinuousOn.measurable_piecewise @[to_additive] instance (priority := 100) ContinuousMul.hasMeasurableMul [Mul γ] [ContinuousMul γ] : HasMeasurableMul γ where measurable_const_mul c := (continuous_const.mul continuous_id).Measurable measurable_mul_const c := (continuous_id.mul continuous_const).Measurable #align has_continuous_mul.has_measurable_mul ContinuousMul.hasMeasurableMul #align has_continuous_add.has_measurable_add ContinuousAdd.has_measurable_add instance (priority := 100) ContinuousSub.hasMeasurableSub [Sub γ] [ContinuousSub γ] : HasMeasurableSub γ where measurable_const_sub c := (continuous_const.sub continuous_id).Measurable measurable_sub_const c := (continuous_id.sub continuous_const).Measurable #align has_continuous_sub.has_measurable_sub ContinuousSub.hasMeasurableSub @[to_additive] instance (priority := 100) TopologicalGroup.hasMeasurableInv [Group γ] [TopologicalGroup γ] : HasMeasurableInv γ := ⟨continuous_inv.Measurable⟩ #align topological_group.has_measurable_inv TopologicalGroup.hasMeasurableInv #align topological_add_group.has_measurable_neg TopologicalAddGroup.has_measurable_neg instance (priority := 100) ContinuousSMul.hasMeasurableSmul {M α} [TopologicalSpace M] [TopologicalSpace α] [MeasurableSpace M] [MeasurableSpace α] [OpensMeasurableSpace M] [BorelSpace α] [SMul M α] [ContinuousSMul M α] : HasMeasurableSmul M α := ⟨fun c => (continuous_const_smul _).Measurable, fun y => (continuous_id.smul continuous_const).Measurable⟩ #align has_continuous_smul.has_measurable_smul ContinuousSMul.hasMeasurableSmul section Lattice instance (priority := 100) ContinuousSup.hasMeasurableSup [Sup γ] [ContinuousSup γ] : HasMeasurableSup γ where measurable_const_sup c := (continuous_const.sup continuous_id).Measurable measurable_sup_const c := (continuous_id.sup continuous_const).Measurable #align has_continuous_sup.has_measurable_sup ContinuousSup.hasMeasurableSup instance (priority := 100) ContinuousSup.hasMeasurableSup₂ [SecondCountableTopology γ] [Sup γ] [ContinuousSup γ] : HasMeasurableSup₂ γ := ⟨continuous_sup.Measurable⟩ #align has_continuous_sup.has_measurable_sup₂ ContinuousSup.hasMeasurableSup₂ instance (priority := 100) ContinuousInf.hasMeasurableInf [Inf γ] [ContinuousInf γ] : HasMeasurableInf γ where measurable_const_inf c := (continuous_const.inf continuous_id).Measurable measurable_inf_const c := (continuous_id.inf continuous_const).Measurable #align has_continuous_inf.has_measurable_inf ContinuousInf.hasMeasurableInf instance (priority := 100) ContinuousInf.hasMeasurableInf₂ [SecondCountableTopology γ] [Inf γ] [ContinuousInf γ] : HasMeasurableInf₂ γ := ⟨continuous_inf.Measurable⟩ #align has_continuous_inf.has_measurable_inf₂ ContinuousInf.hasMeasurableInf₂ end Lattice section Homeomorph @[measurability] protected theorem Homeomorph.measurable (h : α ≃ₜ γ) : Measurable h := h.Continuous.Measurable #align homeomorph.measurable Homeomorph.measurable /-- A homeomorphism between two Borel spaces is a measurable equivalence.-/ def Homeomorph.toMeasurableEquiv (h : γ ≃ₜ γ₂) : γ ≃ᵐ γ₂ where measurable_to_fun := h.Measurable measurable_inv_fun := h.symm.Measurable toEquiv := h.toEquiv #align homeomorph.to_measurable_equiv Homeomorph.toMeasurableEquiv @[simp] theorem Homeomorph.toMeasurableEquiv_coe (h : γ ≃ₜ γ₂) : (h.toMeasurableEquiv : γ → γ₂) = h := rfl #align homeomorph.to_measurable_equiv_coe Homeomorph.toMeasurableEquiv_coe @[simp] theorem Homeomorph.toMeasurableEquiv_symm_coe (h : γ ≃ₜ γ₂) : (h.toMeasurableEquiv.symm : γ₂ → γ) = h.symm := rfl #align homeomorph.to_measurable_equiv_symm_coe Homeomorph.toMeasurableEquiv_symm_coe end Homeomorph @[measurability] theorem ContinuousMap.measurable (f : C(α, γ)) : Measurable f := f.Continuous.Measurable #align continuous_map.measurable ContinuousMap.measurable theorem measurable_of_continuousOn_compl_singleton [T1Space α] {f : α → γ} (a : α) (hf : ContinuousOn f ({a}ᶜ)) : Measurable f := measurable_of_measurable_on_compl_singleton a (continuousOn_iff_continuous_restrict.1 hf).Measurable #align measurable_of_continuous_on_compl_singleton measurable_of_continuousOn_compl_singleton theorem Continuous.measurable2 [SecondCountableTopology α] [SecondCountableTopology β] {f : δ → α} {g : δ → β} {c : α → β → γ} (h : Continuous fun p : α × β => c p.1 p.2) (hf : Measurable f) (hg : Measurable g) : Measurable fun a => c (f a) (g a) := h.Measurable.comp (hf.prod_mk hg) #align continuous.measurable2 Continuous.measurable2 theorem Continuous.aeMeasurable2 [SecondCountableTopology α] [SecondCountableTopology β] {f : δ → α} {g : δ → β} {c : α → β → γ} {μ : Measure δ} (h : Continuous fun p : α × β => c p.1 p.2) (hf : AeMeasurable f μ) (hg : AeMeasurable g μ) : AeMeasurable (fun a => c (f a) (g a)) μ := h.Measurable.compAeMeasurable (hf.prod_mk hg) #align continuous.ae_measurable2 Continuous.aeMeasurable2 instance (priority := 100) HasContinuousInv₀.hasMeasurableInv [GroupWithZero γ] [T1Space γ] [HasContinuousInv₀ γ] : HasMeasurableInv γ := ⟨measurable_of_continuousOn_compl_singleton 0 continuousOn_inv₀⟩ #align has_continuous_inv₀.has_measurable_inv HasContinuousInv₀.hasMeasurableInv @[to_additive] instance (priority := 100) ContinuousMul.hasMeasurableMul₂ [SecondCountableTopology γ] [Mul γ] [ContinuousMul γ] : HasMeasurableMul₂ γ := ⟨continuous_mul.Measurable⟩ #align has_continuous_mul.has_measurable_mul₂ ContinuousMul.hasMeasurableMul₂ #align has_continuous_add.has_measurable_mul₂ ContinuousAdd.hasMeasurableMul₂ instance (priority := 100) ContinuousSub.hasMeasurableSub₂ [SecondCountableTopology γ] [Sub γ] [ContinuousSub γ] : HasMeasurableSub₂ γ := ⟨continuous_sub.Measurable⟩ #align has_continuous_sub.has_measurable_sub₂ ContinuousSub.hasMeasurableSub₂ instance (priority := 100) ContinuousSMul.hasMeasurableSmul₂ {M α} [TopologicalSpace M] [SecondCountableTopology M] [MeasurableSpace M] [OpensMeasurableSpace M] [TopologicalSpace α] [SecondCountableTopology α] [MeasurableSpace α] [BorelSpace α] [SMul M α] [ContinuousSMul M α] : HasMeasurableSmul₂ M α := ⟨continuous_smul.Measurable⟩ #align has_continuous_smul.has_measurable_smul₂ ContinuousSMul.hasMeasurableSmul₂ end section BorelSpace variable [TopologicalSpace α] [MeasurableSpace α] [BorelSpace α] [TopologicalSpace β] [MeasurableSpace β] [BorelSpace β] [TopologicalSpace γ] [MeasurableSpace γ] [BorelSpace γ] [MeasurableSpace δ] theorem pi_le_borel_pi {ι : Type _} {π : ι → Type _} [∀ i, TopologicalSpace (π i)] [∀ i, MeasurableSpace (π i)] [∀ i, BorelSpace (π i)] : MeasurableSpace.pi ≤ borel (∀ i, π i) := by have : ‹∀ i, MeasurableSpace (π i)› = fun i => borel (π i) := funext fun i => BorelSpace.measurable_eq rw [this] exact supᵢ_le fun i => comap_le_iff_le_map.2 <| (continuous_apply i).borel_measurable #align pi_le_borel_pi pi_le_borel_pi theorem prod_le_borel_prod : Prod.measurableSpace ≤ borel (α × β) := by rw [‹BorelSpace α›.measurable_eq, ‹BorelSpace β›.measurable_eq] refine' sup_le _ _ · exact comap_le_iff_le_map.mpr continuous_fst.borel_measurable · exact comap_le_iff_le_map.mpr continuous_snd.borel_measurable #align prod_le_borel_prod prod_le_borel_prod instance Pi.borelSpace {ι : Type _} {π : ι → Type _} [Countable ι] [∀ i, TopologicalSpace (π i)] [∀ i, MeasurableSpace (π i)] [∀ i, SecondCountableTopology (π i)] [∀ i, BorelSpace (π i)] : BorelSpace (∀ i, π i) := ⟨le_antisymm pi_le_borel_pi OpensMeasurableSpace.borel_le⟩ #align pi.borel_space Pi.borelSpace instance Prod.borelSpace [SecondCountableTopology α] [SecondCountableTopology β] : BorelSpace (α × β) := ⟨le_antisymm prod_le_borel_prod OpensMeasurableSpace.borel_le⟩ #align prod.borel_space Prod.borelSpace protected theorem Embedding.measurableEmbedding {f : α → β} (h₁ : Embedding f) (h₂ : MeasurableSet (range f)) : MeasurableEmbedding f := show MeasurableEmbedding (coe ∘ (Homeomorph.ofEmbedding f h₁).toMeasurableEquiv) from (MeasurableEmbedding.subtype_coe h₂).comp (MeasurableEquiv.measurableEmbedding _) #align embedding.measurable_embedding Embedding.measurableEmbedding protected theorem ClosedEmbedding.measurableEmbedding {f : α → β} (h : ClosedEmbedding f) : MeasurableEmbedding f := h.toEmbedding.MeasurableEmbedding h.closed_range.MeasurableSet #align closed_embedding.measurable_embedding ClosedEmbedding.measurableEmbedding protected theorem OpenEmbedding.measurableEmbedding {f : α → β} (h : OpenEmbedding f) : MeasurableEmbedding f := h.toEmbedding.MeasurableEmbedding h.open_range.MeasurableSet #align open_embedding.measurable_embedding OpenEmbedding.measurableEmbedding section LinearOrder variable [LinearOrder α] [OrderTopology α] [SecondCountableTopology α] theorem measurable_of_Iio {f : δ → α} (hf : ∀ x, MeasurableSet (f ⁻¹' Iio x)) : Measurable f := by convert measurable_generateFrom _ exact borel_space.measurable_eq.trans (borel_eq_generateFrom_Iio _) rintro _ ⟨x, rfl⟩; exact hf x #align measurable_of_Iio measurable_of_Iio theorem UpperSemicontinuous.measurable [TopologicalSpace δ] [OpensMeasurableSpace δ] {f : δ → α} (hf : UpperSemicontinuous f) : Measurable f := measurable_of_Iio fun y => (hf.isOpen_preimage y).MeasurableSet #align upper_semicontinuous.measurable UpperSemicontinuous.measurable theorem measurable_of_Ioi {f : δ → α} (hf : ∀ x, MeasurableSet (f ⁻¹' Ioi x)) : Measurable f := by convert measurable_generateFrom _ exact borel_space.measurable_eq.trans (borel_eq_generateFrom_Ioi _) rintro _ ⟨x, rfl⟩; exact hf x #align measurable_of_Ioi measurable_of_Ioi theorem LowerSemicontinuous.measurable [TopologicalSpace δ] [OpensMeasurableSpace δ] {f : δ → α} (hf : LowerSemicontinuous f) : Measurable f := measurable_of_Ioi fun y => (hf.isOpen_preimage y).MeasurableSet #align lower_semicontinuous.measurable LowerSemicontinuous.measurable theorem measurable_of_Iic {f : δ → α} (hf : ∀ x, MeasurableSet (f ⁻¹' Iic x)) : Measurable f := by apply measurable_of_Ioi simp_rw [← compl_Iic, preimage_compl, MeasurableSet.compl_iff] assumption #align measurable_of_Iic measurable_of_Iic theorem measurable_of_Ici {f : δ → α} (hf : ∀ x, MeasurableSet (f ⁻¹' Ici x)) : Measurable f := by apply measurable_of_Iio simp_rw [← compl_Ici, preimage_compl, MeasurableSet.compl_iff] assumption #align measurable_of_Ici measurable_of_Ici theorem Measurable.isLUB {ι} [Countable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, Measurable (f i)) (hg : ∀ b, IsLUB { a | ∃ i, f i b = a } (g b)) : Measurable g := by change ∀ b, IsLUB (range fun i => f i b) (g b) at hg rw [‹BorelSpace α›.measurable_eq, borel_eq_generateFrom_Ioi α] apply measurable_generateFrom rintro _ ⟨a, rfl⟩ simp_rw [Set.preimage, mem_Ioi, lt_isLUB_iff (hg _), exists_range_iff, set_of_exists] exact MeasurableSet.unionᵢ fun i => hf i (isOpen_lt' _).MeasurableSet #align measurable.is_lub Measurable.isLUB private theorem ae_measurable.is_lub_of_nonempty {ι} (hι : Nonempty ι) {μ : Measure δ} [Countable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, AeMeasurable (f i) μ) (hg : ∀ᵐ b ∂μ, IsLUB { a | ∃ i, f i b = a } (g b)) : AeMeasurable g μ := by let p : δ → (ι → α) → Prop := fun x f' => IsLUB { a | ∃ i, f' i = a } (g x) let g_seq x := ite (x ∈ aeSeqSet hf p) (g x) (⟨g x⟩ : Nonempty α).some have hg_seq : ∀ b, IsLUB { a | ∃ i, aeSeq hf p i b = a } (g_seq b) := by intro b haveI hα : Nonempty α := Nonempty.map g ⟨b⟩ simp only [aeSeq, g_seq] split_ifs · have h_set_eq : { a : α | ∃ i : ι, (hf i).mk (f i) b = a } = { a : α | ∃ i : ι, f i b = a } := by ext x simp_rw [Set.mem_setOf_eq, aeSeq.mk_eq_fun_of_mem_aeSeqSet hf h] rw [h_set_eq] exact aeSeq.funPropOfMemAeSeqSet hf h · have h_singleton : { a : α | ∃ i : ι, hα.some = a } = {hα.some} := by ext1 x exact ⟨fun hx => hx.some_spec.symm, fun hx => ⟨hι.some, hx.symm⟩⟩ rw [h_singleton] exact isLUB_singleton refine' ⟨g_seq, Measurable.isLUB (aeSeq.measurable hf p) hg_seq, _⟩ exact (ite_ae_eq_of_measure_compl_zero g (fun x => (⟨g x⟩ : Nonempty α).some) (aeSeqSet hf p) (aeSeq.measure_compl_aeSeqSet_eq_zero hf hg)).symm #align ae_measurable.is_lub_of_nonempty ae_measurable.is_lub_of_nonempty theorem AeMeasurable.isLub {ι} {μ : Measure δ} [Countable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, AeMeasurable (f i) μ) (hg : ∀ᵐ b ∂μ, IsLUB { a | ∃ i, f i b = a } (g b)) : AeMeasurable g μ := by by_cases hμ : μ = 0 · rw [hμ] exact aeMeasurableZeroMeasure have : μ.ae.ne_bot := by simpa [ne_bot_iff] by_cases hι : Nonempty ι · exact ae_measurable.is_lub_of_nonempty hι hf hg suffices ∃ x, g =ᵐ[μ] fun y => g x by exact ⟨fun y => g this.some, measurable_const, this.some_spec⟩ have h_empty : ∀ x, { a : α | ∃ i : ι, f i x = a } = ∅ := by intro x ext1 y rw [Set.mem_setOf_eq, Set.mem_empty_iff_false, iff_false_iff] exact fun hi => hι (nonempty_of_exists hi) simp_rw [h_empty] at hg exact ⟨hg.exists.some, hg.mono fun y hy => IsLUB.unique hy hg.exists.some_spec⟩ #align ae_measurable.is_lub AeMeasurable.isLub theorem Measurable.isGLB {ι} [Countable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, Measurable (f i)) (hg : ∀ b, IsGLB { a | ∃ i, f i b = a } (g b)) : Measurable g := by change ∀ b, IsGLB (range fun i => f i b) (g b) at hg rw [‹BorelSpace α›.measurable_eq, borel_eq_generateFrom_Iio α] apply measurable_generateFrom rintro _ ⟨a, rfl⟩ simp_rw [Set.preimage, mem_Iio, isGLB_lt_iff (hg _), exists_range_iff, set_of_exists] exact MeasurableSet.unionᵢ fun i => hf i (isOpen_gt' _).MeasurableSet #align measurable.is_glb Measurable.isGLB theorem AeMeasurable.isGlb {ι} {μ : Measure δ} [Countable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, AeMeasurable (f i) μ) (hg : ∀ᵐ b ∂μ, IsGLB { a | ∃ i, f i b = a } (g b)) : AeMeasurable g μ := by nontriviality α haveI hα : Nonempty α := inferInstance cases' isEmpty_or_nonempty ι with hι hι · simp only [IsEmpty.exists_iff, set_of_false, isGLB_empty_iff] at hg exact aeMeasurableConst' (hg.mono fun a ha => hg.mono fun b hb => (hb _).antisymm (ha _)) let p : δ → (ι → α) → Prop := fun x f' => IsGLB { a | ∃ i, f' i = a } (g x) let g_seq := (aeSeqSet hf p).piecewise g fun _ => hα.some have hg_seq : ∀ b, IsGLB { a | ∃ i, aeSeq hf p i b = a } (g_seq b) := by intro b simp only [aeSeq, g_seq, Set.piecewise] split_ifs · have h_set_eq : { a : α | ∃ i : ι, (hf i).mk (f i) b = a } = { a : α | ∃ i : ι, f i b = a } := by ext x simp_rw [Set.mem_setOf_eq, aeSeq.mk_eq_fun_of_mem_aeSeqSet hf h] rw [h_set_eq] exact aeSeq.funPropOfMemAeSeqSet hf h · exact IsLeast.isGLB ⟨(@exists_const (hα.some = hα.some) ι _).2 rfl, fun x ⟨i, hi⟩ => hi.le⟩ refine' ⟨g_seq, Measurable.isGLB (aeSeq.measurable hf p) hg_seq, _⟩ exact (ite_ae_eq_of_measure_compl_zero g (fun x => hα.some) (aeSeqSet hf p) (aeSeq.measure_compl_aeSeqSet_eq_zero hf hg)).symm #align ae_measurable.is_glb AeMeasurable.isGlb protected theorem Monotone.measurable [LinearOrder β] [OrderClosedTopology β] {f : β → α} (hf : Monotone f) : Measurable f := suffices h : ∀ x, OrdConnected (f ⁻¹' Ioi x) from measurable_of_Ioi fun x => (h x).MeasurableSet fun x => ordConnected_def.mpr fun a ha b hb c hc => lt_of_lt_of_le ha (hf hc.1) #align monotone.measurable Monotone.measurable theorem aeMeasurableRestrictOfMonotoneOn [LinearOrder β] [OrderClosedTopology β] {μ : Measure β} {s : Set β} (hs : MeasurableSet s) {f : β → α} (hf : MonotoneOn f s) : AeMeasurable f (μ.restrict s) := have this : Monotone (f ∘ coe : s → α) := fun ⟨x, hx⟩ ⟨y, hy⟩ (hxy : x ≤ y) => hf hx hy hxy aeMeasurableRestrictOfMeasurableSubtype hs this.Measurable #align ae_measurable_restrict_of_monotone_on aeMeasurableRestrictOfMonotoneOn protected theorem Antitone.measurable [LinearOrder β] [OrderClosedTopology β] {f : β → α} (hf : Antitone f) : Measurable f := @Monotone.measurable αᵒᵈ β _ _ ‹_› _ _ _ _ _ ‹_› _ _ _ hf #align antitone.measurable Antitone.measurable theorem aeMeasurableRestrictOfAntitoneOn [LinearOrder β] [OrderClosedTopology β] {μ : Measure β} {s : Set β} (hs : MeasurableSet s) {f : β → α} (hf : AntitoneOn f s) : AeMeasurable f (μ.restrict s) := @aeMeasurableRestrictOfMonotoneOn αᵒᵈ β _ _ ‹_› _ _ _ _ _ ‹_› _ _ _ _ hs _ hf #align ae_measurable_restrict_of_antitone_on aeMeasurableRestrictOfAntitoneOn theorem measurableSet_of_mem_nhdsWithin_Ioi_aux {s : Set α} (h : ∀ x ∈ s, s ∈ 𝓝[>] x) (h' : ∀ x ∈ s, ∃ y, x < y) : MeasurableSet s := by choose! M hM using h' suffices H : (s \ interior s).Countable · have : s = interior s ∪ s \ interior s := by rw [union_diff_cancel interior_subset] rw [this] exact is_open_interior.measurable_set.union H.measurable_set have A : ∀ x ∈ s, ∃ y ∈ Ioi x, Ioo x y ⊆ s := fun x hx => (mem_nhdsWithin_Ioi_iff_exists_Ioo_subset' (hM x hx)).1 (h x hx) choose! y hy h'y using A have B : Set.PairwiseDisjoint (s \ interior s) fun x => Ioo x (y x) := by intro x hx x' hx' hxx' rcases lt_or_gt_of_ne hxx' with (h' | h') · apply disjoint_left.2 fun z hz h'z => _ have : x' ∈ interior s := mem_interior.2 ⟨Ioo x (y x), h'y _ hx.1, isOpen_Ioo, ⟨h', h'z.1.trans hz.2⟩⟩ exact False.elim (hx'.2 this) · apply disjoint_left.2 fun z hz h'z => _ have : x ∈ interior s := mem_interior.2 ⟨Ioo x' (y x'), h'y _ hx'.1, isOpen_Ioo, ⟨h', hz.1.trans h'z.2⟩⟩ exact False.elim (hx.2 this) exact B.countable_of_Ioo fun x hx => hy x hx.1 #align measurable_set_of_mem_nhds_within_Ioi_aux measurableSet_of_mem_nhdsWithin_Ioi_aux /-- If a set is a right-neighborhood of all of its points, then it is measurable. -/ theorem measurableSet_of_mem_nhdsWithin_Ioi {s : Set α} (h : ∀ x ∈ s, s ∈ 𝓝[>] x) : MeasurableSet s := by by_cases H : ∃ x ∈ s, IsTop x · rcases H with ⟨x₀, x₀s, h₀⟩ have : s = {x₀} ∪ s \ {x₀} := by rw [union_diff_cancel (singleton_subset_iff.2 x₀s)] rw [this] refine' (measurable_set_singleton _).union _ have A : ∀ x ∈ s \ {x₀}, x < x₀ := fun x hx => lt_of_le_of_ne (h₀ _) (by simpa using hx.2) refine' measurableSet_of_mem_nhdsWithin_Ioi_aux (fun x hx => _) fun x hx => ⟨x₀, A x hx⟩ obtain ⟨u, hu, us⟩ : ∃ (u : α)(H : u ∈ Ioi x), Ioo x u ⊆ s := (mem_nhdsWithin_Ioi_iff_exists_Ioo_subset' (A x hx)).1 (h x hx.1) refine' (mem_nhdsWithin_Ioi_iff_exists_Ioo_subset' (A x hx)).2 ⟨u, hu, fun y hy => ⟨us hy, _⟩⟩ exact ne_of_lt (hy.2.trans_le (h₀ _)) · apply measurableSet_of_mem_nhdsWithin_Ioi_aux h simp only [IsTop] at H push_neg at H exact H #align measurable_set_of_mem_nhds_within_Ioi measurableSet_of_mem_nhdsWithin_Ioi end LinearOrder @[measurability] theorem Measurable.supᵢ_Prop {α} [MeasurableSpace α] [CompleteLattice α] (p : Prop) {f : δ → α} (hf : Measurable f) : Measurable fun b => ⨆ h : p, f b := by_cases (fun h : p => by convert hf; funext; exact supᵢ_pos h) fun h : ¬p => by convert measurable_const; funext; exact supᵢ_neg h #align measurable.supr_Prop Measurable.supᵢ_Prop @[measurability] theorem Measurable.infᵢ_Prop {α} [MeasurableSpace α] [CompleteLattice α] (p : Prop) {f : δ → α} (hf : Measurable f) : Measurable fun b => ⨅ h : p, f b := by_cases (fun h : p => by convert hf; funext; exact infᵢ_pos h) fun h : ¬p => by convert measurable_const; funext; exact infᵢ_neg h #align measurable.infi_Prop Measurable.infᵢ_Prop section CompleteLinearOrder variable [CompleteLinearOrder α] [OrderTopology α] [SecondCountableTopology α] @[measurability] theorem measurable_supᵢ {ι} [Countable ι] {f : ι → δ → α} (hf : ∀ i, Measurable (f i)) : Measurable fun b => ⨆ i, f i b := Measurable.isLUB hf fun b => isLUB_supᵢ #align measurable_supr measurable_supᵢ @[measurability] theorem aeMeasurableSupr {ι} {μ : Measure δ} [Countable ι] {f : ι → δ → α} (hf : ∀ i, AeMeasurable (f i) μ) : AeMeasurable (fun b => ⨆ i, f i b) μ := AeMeasurable.isLub hf <| ae_of_all μ fun b => isLUB_supᵢ #align ae_measurable_supr aeMeasurableSupr @[measurability] theorem measurable_infᵢ {ι} [Countable ι] {f : ι → δ → α} (hf : ∀ i, Measurable (f i)) : Measurable fun b => ⨅ i, f i b := Measurable.isGLB hf fun b => isGLB_infᵢ #align measurable_infi measurable_infᵢ @[measurability] theorem aeMeasurableInfi {ι} {μ : Measure δ} [Countable ι] {f : ι → δ → α} (hf : ∀ i, AeMeasurable (f i) μ) : AeMeasurable (fun b => ⨅ i, f i b) μ := AeMeasurable.isGlb hf <| ae_of_all μ fun b => isGLB_infᵢ #align ae_measurable_infi aeMeasurableInfi theorem measurable_bsupr {ι} (s : Set ι) {f : ι → δ → α} (hs : s.Countable) (hf : ∀ i, Measurable (f i)) : Measurable fun b => ⨆ i ∈ s, f i b := by haveI : Encodable s := hs.to_encodable simp only [supᵢ_subtype'] exact measurable_supᵢ fun i => hf i #align measurable_bsupr measurable_bsupr theorem aeMeasurableBsupr {ι} {μ : Measure δ} (s : Set ι) {f : ι → δ → α} (hs : s.Countable) (hf : ∀ i, AeMeasurable (f i) μ) : AeMeasurable (fun b => ⨆ i ∈ s, f i b) μ := by haveI : Encodable s := hs.to_encodable simp only [supᵢ_subtype'] exact aeMeasurableSupr fun i => hf i #align ae_measurable_bsupr aeMeasurableBsupr theorem measurable_binfi {ι} (s : Set ι) {f : ι → δ → α} (hs : s.Countable) (hf : ∀ i, Measurable (f i)) : Measurable fun b => ⨅ i ∈ s, f i b := by haveI : Encodable s := hs.to_encodable simp only [infᵢ_subtype'] exact measurable_infᵢ fun i => hf i #align measurable_binfi measurable_binfi theorem aeMeasurableBinfi {ι} {μ : Measure δ} (s : Set ι) {f : ι → δ → α} (hs : s.Countable) (hf : ∀ i, AeMeasurable (f i) μ) : AeMeasurable (fun b => ⨅ i ∈ s, f i b) μ := by haveI : Encodable s := hs.to_encodable simp only [infᵢ_subtype'] exact aeMeasurableInfi fun i => hf i #align ae_measurable_binfi aeMeasurableBinfi /-- `liminf` over a general filter is measurable. See `measurable_liminf` for the version over `ℕ`. -/ theorem measurable_liminf' {ι ι'} {f : ι → δ → α} {u : Filter ι} (hf : ∀ i, Measurable (f i)) {p : ι' → Prop} {s : ι' → Set ι} (hu : u.HasCountableBasis p s) (hs : ∀ i, (s i).Countable) : Measurable fun x => liminf (fun i => f i x) u := by simp_rw [hu.to_has_basis.liminf_eq_supr_infi] refine' measurable_bsupr _ hu.countable _ exact fun i => measurable_binfi _ (hs i) hf #align measurable_liminf' measurable_liminf' /-- `limsup` over a general filter is measurable. See `measurable_limsup` for the version over `ℕ`. -/ theorem measurable_limsup' {ι ι'} {f : ι → δ → α} {u : Filter ι} (hf : ∀ i, Measurable (f i)) {p : ι' → Prop} {s : ι' → Set ι} (hu : u.HasCountableBasis p s) (hs : ∀ i, (s i).Countable) : Measurable fun x => limsup (fun i => f i x) u := by simp_rw [hu.to_has_basis.limsup_eq_infi_supr] refine' measurable_binfi _ hu.countable _ exact fun i => measurable_bsupr _ (hs i) hf #align measurable_limsup' measurable_limsup' /-- `liminf` over `ℕ` is measurable. See `measurable_liminf'` for a version with a general filter. -/ @[measurability] theorem measurable_liminf {f : ℕ → δ → α} (hf : ∀ i, Measurable (f i)) : Measurable fun x => liminf (fun i => f i x) atTop := measurable_liminf' hf atTop_countable_basis fun i => to_countable _ #align measurable_liminf measurable_liminf /-- `limsup` over `ℕ` is measurable. See `measurable_limsup'` for a version with a general filter. -/ @[measurability] theorem measurable_limsup {f : ℕ → δ → α} (hf : ∀ i, Measurable (f i)) : Measurable fun x => limsup (fun i => f i x) atTop := measurable_limsup' hf atTop_countable_basis fun i => to_countable _ #align measurable_limsup measurable_limsup end CompleteLinearOrder section ConditionallyCompleteLinearOrder variable [ConditionallyCompleteLinearOrder α] [OrderTopology α] [SecondCountableTopology α] theorem measurable_cSup {ι} {f : ι → δ → α} {s : Set ι} (hs : s.Countable) (hf : ∀ i, Measurable (f i)) (bdd : ∀ x, BddAbove ((fun i => f i x) '' s)) : Measurable fun x => supₛ ((fun i => f i x) '' s) := by cases' eq_empty_or_nonempty s with h2s h2s · simp [h2s, measurable_const] · apply measurable_of_Iic intro y simp_rw [preimage, mem_Iic, csupₛ_le_iff (bdd _) (h2s.image _), ball_image_iff, set_of_forall] exact MeasurableSet.binterᵢ hs fun i hi => measurableSet_le (hf i) measurable_const #align measurable_cSup measurable_cSup end ConditionallyCompleteLinearOrder /-- Convert a `homeomorph` to a `measurable_equiv`. -/ def Homemorph.toMeasurableEquiv (h : α ≃ₜ β) : α ≃ᵐ β where toEquiv := h.toEquiv measurable_to_fun := h.continuous_toFun.Measurable measurable_inv_fun := h.continuous_invFun.Measurable #align homemorph.to_measurable_equiv Homemorph.toMeasurableEquiv protected theorem IsFiniteMeasureOnCompacts.map {α : Type _} {m0 : MeasurableSpace α} [TopologicalSpace α] [OpensMeasurableSpace α] {β : Type _} [MeasurableSpace β] [TopologicalSpace β] [BorelSpace β] [T2Space β] (μ : Measure α) [IsFiniteMeasureOnCompacts μ] (f : α ≃ₜ β) : IsFiniteMeasureOnCompacts (Measure.map f μ) := ⟨by intro K hK rw [measure.map_apply f.measurable hK.measurable_set] apply IsCompact.measure_lt_top rwa [f.is_compact_preimage]⟩ #align is_finite_measure_on_compacts.map IsFiniteMeasureOnCompacts.map end BorelSpace instance Empty.borelSpace : BorelSpace Empty := ⟨borel_eq_top_of_discrete.symm⟩ #align empty.borel_space Empty.borelSpace instance Unit.borelSpace : BorelSpace Unit := ⟨borel_eq_top_of_discrete.symm⟩ #align unit.borel_space Unit.borelSpace instance Bool.borelSpace : BorelSpace Bool := ⟨borel_eq_top_of_discrete.symm⟩ #align bool.borel_space Bool.borelSpace instance Nat.borelSpace : BorelSpace ℕ := ⟨borel_eq_top_of_discrete.symm⟩ #align nat.borel_space Nat.borelSpace instance Int.borelSpace : BorelSpace ℤ := ⟨borel_eq_top_of_discrete.symm⟩ #align int.borel_space Int.borelSpace instance Rat.borelSpace : BorelSpace ℚ := ⟨borel_eq_top_of_countable.symm⟩ #align rat.borel_space Rat.borelSpace instance (priority := 900) IsROrC.measurableSpace {𝕜 : Type _} [IsROrC 𝕜] : MeasurableSpace 𝕜 := borel 𝕜 #align is_R_or_C.measurable_space IsROrC.measurableSpace instance (priority := 900) IsROrC.borelSpace {𝕜 : Type _} [IsROrC 𝕜] : BorelSpace 𝕜 := ⟨rfl⟩ #align is_R_or_C.borel_space IsROrC.borelSpace /- Instances on `real` and `complex` are special cases of `is_R_or_C` but without these instances, Lean fails to prove `borel_space (ι → ℝ)`, so we leave them here. -/ instance Real.measurableSpace : MeasurableSpace ℝ := borel ℝ #align real.measurable_space Real.measurableSpace instance Real.borelSpace : BorelSpace ℝ := ⟨rfl⟩ #align real.borel_space Real.borelSpace instance NNReal.measurableSpace : MeasurableSpace ℝ≥0 := Subtype.measurableSpace #align nnreal.measurable_space NNReal.measurableSpace instance NNReal.borelSpace : BorelSpace ℝ≥0 := Subtype.borelSpace _ #align nnreal.borel_space NNReal.borelSpace instance ENNReal.measurableSpace : MeasurableSpace ℝ≥0∞ := borel ℝ≥0∞ #align ennreal.measurable_space ENNReal.measurableSpace instance ENNReal.borelSpace : BorelSpace ℝ≥0∞ := ⟨rfl⟩ #align ennreal.borel_space ENNReal.borelSpace instance EReal.measurableSpace : MeasurableSpace EReal := borel EReal #align ereal.measurable_space EReal.measurableSpace instance EReal.borelSpace : BorelSpace EReal := ⟨rfl⟩ #align ereal.borel_space EReal.borelSpace instance Complex.measurableSpace : MeasurableSpace ℂ := borel ℂ #align complex.measurable_space Complex.measurableSpace instance Complex.borelSpace : BorelSpace ℂ := ⟨rfl⟩ #align complex.borel_space Complex.borelSpace instance AddCircle.measurableSpace {a : ℝ} : MeasurableSpace (AddCircle a) := borel (AddCircle a) #align add_circle.measurable_space AddCircle.measurableSpace instance AddCircle.borelSpace {a : ℝ} : BorelSpace (AddCircle a) := ⟨rfl⟩ #align add_circle.borel_space AddCircle.borelSpace @[measurability] protected theorem AddCircle.measurable_mk' {a : ℝ} : Measurable (coe : ℝ → AddCircle a) := Continuous.measurable <| AddCircle.continuous_mk' a #align add_circle.measurable_mk' AddCircle.measurable_mk' /-- One can cut out `ℝ≥0∞` into the sets `{0}`, `Ico (t^n) (t^(n+1))` for `n : ℤ` and `{∞}`. This gives a way to compute the measure of a set in terms of sets on which a given function `f` does not fluctuate by more than `t`. -/ theorem measure_eq_measure_preimage_add_measure_tsum_Ico_zpow [MeasurableSpace α] (μ : Measure α) {f : α → ℝ≥0∞} (hf : Measurable f) {s : Set α} (hs : MeasurableSet s) {t : ℝ≥0} (ht : 1 < t) : μ s = μ (s ∩ f ⁻¹' {0}) + μ (s ∩ f ⁻¹' {∞}) + ∑' n : ℤ, μ (s ∩ f ⁻¹' Ico (t ^ n) (t ^ (n + 1))) := by have A : μ s = μ (s ∩ f ⁻¹' {0}) + μ (s ∩ f ⁻¹' Ioi 0) := by rw [← measure_union] · congr 1 ext x have : 0 = f x ∨ 0 < f x := eq_or_lt_of_le bot_le rw [eq_comm] at this simp only [← and_or_left, this, mem_singleton_iff, mem_inter_iff, and_true_iff, mem_union, mem_Ioi, mem_preimage] · apply disjoint_left.2 fun x hx h'x => _ have : 0 < f x := h'x.2 exact lt_irrefl 0 (this.trans_le hx.2.le) · exact hs.inter (hf measurableSet_Ioi) have B : μ (s ∩ f ⁻¹' Ioi 0) = μ (s ∩ f ⁻¹' {∞}) + μ (s ∩ f ⁻¹' Ioo 0 ∞) := by rw [← measure_union] · rw [← inter_union_distrib_left] congr ext x simp only [mem_singleton_iff, mem_union, mem_Ioo, mem_Ioi, mem_preimage] have H : f x = ∞ ∨ f x < ∞ := eq_or_lt_of_le le_top cases H · simp only [H, eq_self_iff_true, or_false_iff, WithTop.zero_lt_top, not_top_lt, and_false_iff] · simp only [H, H.ne, and_true_iff, false_or_iff] · apply disjoint_left.2 fun x hx h'x => _ have : f x < ∞ := h'x.2.2 exact lt_irrefl _ (this.trans_le (le_of_eq hx.2.symm)) · exact hs.inter (hf measurableSet_Ioo) have C : μ (s ∩ f ⁻¹' Ioo 0 ∞) = ∑' n : ℤ, μ (s ∩ f ⁻¹' Ico (t ^ n) (t ^ (n + 1))) := by rw [← measure_Union, ENNReal.Ioo_zero_top_eq_unionᵢ_Ico_zpow (ENNReal.one_lt_coe_iff.2 ht) ENNReal.coe_ne_top, preimage_Union, inter_Union] · intro i j simp only [Function.onFun] intro hij wlog h : i < j generalizing i j · exact (this hij.symm (hij.lt_or_lt.resolve_left h)).symm apply disjoint_left.2 fun x hx h'x => lt_irrefl (f x) _ calc f x < t ^ (i + 1) := hx.2.2 _ ≤ t ^ j := (ENNReal.zpow_le_of_le (ENNReal.one_le_coe_iff.2 ht.le) h) _ ≤ f x := h'x.2.1 · intro n exact hs.inter (hf measurableSet_Ico) rw [A, B, C, add_assoc] #align measure_eq_measure_preimage_add_measure_tsum_Ico_zpow measure_eq_measure_preimage_add_measure_tsum_Ico_zpow section PseudoMetricSpace variable [PseudoMetricSpace α] [MeasurableSpace α] [OpensMeasurableSpace α] variable [MeasurableSpace β] {x : α} {ε : ℝ} open Metric @[measurability] theorem measurableSet_ball : MeasurableSet (Metric.ball x ε) := Metric.isOpen_ball.MeasurableSet #align measurable_set_ball measurableSet_ball @[measurability] theorem measurableSet_closedBall : MeasurableSet (Metric.closedBall x ε) := Metric.isClosed_ball.MeasurableSet #align measurable_set_closed_ball measurableSet_closedBall @[measurability] theorem measurable_infDist {s : Set α} : Measurable fun x => infDist x s := (continuous_infDist_pt s).Measurable #align measurable_inf_dist measurable_infDist @[measurability] theorem Measurable.infDist {f : β → α} (hf : Measurable f) {s : Set α} : Measurable fun x => infDist (f x) s := measurable_infDist.comp hf #align measurable.inf_dist Measurable.infDist @[measurability] theorem measurable_infNndist {s : Set α} : Measurable fun x => infNndist x s := (continuous_infNndist_pt s).Measurable #align measurable_inf_nndist measurable_infNndist @[measurability] theorem Measurable.infNndist {f : β → α} (hf : Measurable f) {s : Set α} : Measurable fun x => infNndist (f x) s := measurable_infNndist.comp hf #align measurable.inf_nndist Measurable.infNndist section variable [SecondCountableTopology α] @[measurability] theorem measurable_dist : Measurable fun p : α × α => dist p.1 p.2 := continuous_dist.Measurable #align measurable_dist measurable_dist @[measurability] theorem Measurable.dist {f g : β → α} (hf : Measurable f) (hg : Measurable g) : Measurable fun b => dist (f b) (g b) := (@continuous_dist α _).measurable2 hf hg #align measurable.dist Measurable.dist @[measurability] theorem measurable_nndist : Measurable fun p : α × α => nndist p.1 p.2 := continuous_nndist.Measurable #align measurable_nndist measurable_nndist @[measurability] theorem Measurable.nndist {f g : β → α} (hf : Measurable f) (hg : Measurable g) : Measurable fun b => nndist (f b) (g b) := (@continuous_nndist α _).measurable2 hf hg #align measurable.nndist Measurable.nndist end /-- If a set has a closed thickening with finite measure, then the measure of its `r`-closed thickenings converges to the measure of its closure as `r` tends to `0`. -/ theorem tendsto_measure_cthickening {μ : Measure α} {s : Set α} (hs : ∃ R > 0, μ (cthickening R s) ≠ ∞) : Tendsto (fun r => μ (cthickening r s)) (𝓝 0) (𝓝 (μ (closure s))) := by have A : tendsto (fun r => μ (cthickening r s)) (𝓝[Ioi 0] 0) (𝓝 (μ (closure s))) := by rw [closure_eq_Inter_cthickening] exact tendsto_measure_bInter_gt (fun r hr => is_closed_cthickening.measurable_set) (fun i j ipos ij => cthickening_mono ij _) hs have B : tendsto (fun r => μ (cthickening r s)) (𝓝[Iic 0] 0) (𝓝 (μ (closure s))) := by apply tendsto.congr' _ tendsto_const_nhds filter_upwards [self_mem_nhdsWithin]with _ hr rw [cthickening_of_nonpos hr] convert B.sup A exact (nhds_left_sup_nhds_right' 0).symm #align tendsto_measure_cthickening tendsto_measure_cthickening /-- If a closed set has a closed thickening with finite measure, then the measure of its `r`-closed thickenings converges to its measure as `r` tends to `0`. -/ theorem tendsto_measure_cthickening_of_isClosed {μ : Measure α} {s : Set α} (hs : ∃ R > 0, μ (cthickening R s) ≠ ∞) (h's : IsClosed s) : Tendsto (fun r => μ (cthickening r s)) (𝓝 0) (𝓝 (μ s)) := by convert tendsto_measure_cthickening hs exact h's.closure_eq.symm #align tendsto_measure_cthickening_of_is_closed tendsto_measure_cthickening_of_isClosed end PseudoMetricSpace /-- Given a compact set in a proper space, the measure of its `r`-closed thickenings converges to its measure as `r` tends to `0`. -/ theorem tendsto_measure_cthickening_of_isCompact [MetricSpace α] [MeasurableSpace α] [OpensMeasurableSpace α] [ProperSpace α] {μ : Measure α} [IsFiniteMeasureOnCompacts μ] {s : Set α} (hs : IsCompact s) : Tendsto (fun r => μ (Metric.cthickening r s)) (𝓝 0) (𝓝 (μ s)) := tendsto_measure_cthickening_of_isClosed ⟨1, zero_lt_one, hs.Bounded.cthickening.measure_lt_top.Ne⟩ hs.IsClosed #align tendsto_measure_cthickening_of_is_compact tendsto_measure_cthickening_of_isCompact section PseudoEMetricSpace variable [PseudoEMetricSpace α] [MeasurableSpace α] [OpensMeasurableSpace α] variable [MeasurableSpace β] {x : α} {ε : ℝ≥0∞} open Emetric @[measurability] theorem measurableSet_eball : MeasurableSet (EMetric.ball x ε) := EMetric.isOpen_ball.MeasurableSet #align measurable_set_eball measurableSet_eball @[measurability] theorem measurable_edist_right : Measurable (edist x) := (continuous_const.edist continuous_id).Measurable #align measurable_edist_right measurable_edist_right @[measurability] theorem measurable_edist_left : Measurable fun y => edist y x := (continuous_id.edist continuous_const).Measurable #align measurable_edist_left measurable_edist_left @[measurability] theorem measurable_infEdist {s : Set α} : Measurable fun x => infEdist x s := continuous_infEdist.Measurable #align measurable_inf_edist measurable_infEdist @[measurability] theorem Measurable.infEdist {f : β → α} (hf : Measurable f) {s : Set α} : Measurable fun x => infEdist (f x) s := measurable_infEdist.comp hf #align measurable.inf_edist Measurable.infEdist variable [SecondCountableTopology α] @[measurability] theorem measurable_edist : Measurable fun p : α × α => edist p.1 p.2 := continuous_edist.Measurable #align measurable_edist measurable_edist @[measurability] theorem Measurable.edist {f g : β → α} (hf : Measurable f) (hg : Measurable g) : Measurable fun b => edist (f b) (g b) := (@continuous_edist α _).measurable2 hf hg #align measurable.edist Measurable.edist @[measurability] theorem AeMeasurable.edist {f g : β → α} {μ : Measure β} (hf : AeMeasurable f μ) (hg : AeMeasurable g μ) : AeMeasurable (fun a => edist (f a) (g a)) μ := (@continuous_edist α _).aeMeasurable2 hf hg #align ae_measurable.edist AeMeasurable.edist end PseudoEMetricSpace namespace Real open MeasurableSpace MeasureTheory /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (a b) -/ theorem borel_eq_generateFrom_Ioo_rat : borel ℝ = generateFrom (⋃ (a : ℚ) (b : ℚ) (h : a < b), {Ioo a b}) := isTopologicalBasis_Ioo_rat.borel_eq_generateFrom #align real.borel_eq_generate_from_Ioo_rat Real.borel_eq_generateFrom_Ioo_rat /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (a b) -/ theorem isPiSystem_Ioo_rat : @IsPiSystem ℝ (⋃ (a : ℚ) (b : ℚ) (h : a < b), {Ioo a b}) := by convert isPiSystem_Ioo (coe : ℚ → ℝ) (coe : ℚ → ℝ) ext x simp [eq_comm] #align real.is_pi_system_Ioo_rat Real.isPiSystem_Ioo_rat /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (a b) -/ /-- The intervals `(-(n + 1), (n + 1))` form a finite spanning sets in the set of open intervals with rational endpoints for a locally finite measure `μ` on `ℝ`. -/ def finiteSpanningSetsInIooRat (μ : Measure ℝ) [IsLocallyFiniteMeasure μ] : μ.FiniteSpanningSetsIn (⋃ (a : ℚ) (b : ℚ) (h : a < b), {Ioo a b}) where Set n := Ioo (-(n + 1)) (n + 1) set_mem n := by simp only [mem_Union, mem_singleton_iff] refine' ⟨-(n + 1 : ℕ), n + 1, _, by simp⟩ -- TODO: norm_cast fails here? exact (neg_nonpos.2 (@Nat.cast_nonneg ℚ _ (n + 1))).trans_lt n.cast_add_one_pos Finite n := measure_Ioo_lt_top spanning := unionᵢ_eq_univ_iff.2 fun x => ⟨⌊|x|⌋₊, neg_lt.1 ((neg_le_abs_self x).trans_lt (Nat.lt_floor_add_one _)), (le_abs_self x).trans_lt (Nat.lt_floor_add_one _)⟩ #align real.finite_spanning_sets_in_Ioo_rat Real.finiteSpanningSetsInIooRat theorem measure_ext_Ioo_rat {μ ν : Measure ℝ} [IsLocallyFiniteMeasure μ] (h : ∀ a b : ℚ, μ (Ioo a b) = ν (Ioo a b)) : μ = ν := (finiteSpanningSetsInIooRat μ).ext borel_eq_generateFrom_Ioo_rat isPiSystem_Ioo_rat <| by simp only [mem_Union, mem_singleton_iff] rintro _ ⟨a, b, -, rfl⟩ apply h #align real.measure_ext_Ioo_rat Real.measure_ext_Ioo_rat theorem borel_eq_generateFrom_Iio_rat : borel ℝ = generateFrom (⋃ a : ℚ, {Iio a}) := by let g : MeasurableSpace ℝ := generate_from (⋃ a : ℚ, {Iio a}) refine' le_antisymm _ _ · rw [borel_eq_generate_from_Ioo_rat] refine' generate_from_le fun t => _ simp only [mem_Union, mem_singleton_iff] rintro ⟨a, b, h, rfl⟩ rw [(Set.ext fun x => _ : Ioo (a : ℝ) b = (⋃ c > a, Iio cᶜ) ∩ Iio b)] · have hg : ∀ q : ℚ, measurable_set[g] (Iio q) := fun q => generate_measurable.basic (Iio q) (by simp) refine' @MeasurableSet.inter _ g _ _ _ (hg _) refine' @MeasurableSet.bunionᵢ _ _ g _ _ (to_countable _) fun c h => _ exact @MeasurableSet.compl _ _ g (hg _) · suffices x < ↑b → (↑a < x ↔ ∃ i : ℚ, a < i ∧ ↑i ≤ x) by simpa refine' fun _ => ⟨fun h => _, fun ⟨i, hai, hix⟩ => (Rat.cast_lt.2 hai).trans_le hix⟩ rcases exists_rat_btwn h with ⟨c, ac, cx⟩ exact ⟨c, Rat.cast_lt.1 ac, cx.le⟩ · refine' MeasurableSpace.generateFrom_le fun _ => _ simp only [mem_Union, mem_singleton_iff] rintro ⟨r, rfl⟩ exact measurableSet_Iio #align real.borel_eq_generate_from_Iio_rat Real.borel_eq_generateFrom_Iio_rat end Real variable [MeasurableSpace α] @[measurability] theorem measurable_real_toNNReal : Measurable Real.toNNReal := continuous_real_toNNReal.Measurable #align measurable_real_to_nnreal measurable_real_toNNReal @[measurability] theorem Measurable.real_toNNReal {f : α → ℝ} (hf : Measurable f) : Measurable fun x => Real.toNNReal (f x) := measurable_real_toNNReal.comp hf #align measurable.real_to_nnreal Measurable.real_toNNReal @[measurability] theorem AeMeasurable.realToNnreal {f : α → ℝ} {μ : Measure α} (hf : AeMeasurable f μ) : AeMeasurable (fun x => Real.toNNReal (f x)) μ := measurable_real_toNNReal.compAeMeasurable hf #align ae_measurable.real_to_nnreal AeMeasurable.realToNnreal @[measurability] theorem measurable_coe_nNReal_real : Measurable (coe : ℝ≥0 → ℝ) := NNReal.continuous_coe.Measurable #align measurable_coe_nnreal_real measurable_coe_nNReal_real @[measurability] theorem Measurable.coe_nNReal_real {f : α → ℝ≥0} (hf : Measurable f) : Measurable fun x => (f x : ℝ) := measurable_coe_nNReal_real.comp hf #align measurable.coe_nnreal_real Measurable.coe_nNReal_real @[measurability] theorem AeMeasurable.coeNnrealReal {f : α → ℝ≥0} {μ : Measure α} (hf : AeMeasurable f μ) : AeMeasurable (fun x => (f x : ℝ)) μ := measurable_coe_nNReal_real.compAeMeasurable hf #align ae_measurable.coe_nnreal_real AeMeasurable.coeNnrealReal @[measurability] theorem measurable_coe_nNReal_eNNReal : Measurable (coe : ℝ≥0 → ℝ≥0∞) := ENNReal.continuous_coe.Measurable #align measurable_coe_nnreal_ennreal measurable_coe_nNReal_eNNReal @[measurability] theorem Measurable.coe_nNReal_eNNReal {f : α → ℝ≥0} (hf : Measurable f) : Measurable fun x => (f x : ℝ≥0∞) := ENNReal.continuous_coe.Measurable.comp hf #align measurable.coe_nnreal_ennreal Measurable.coe_nNReal_eNNReal @[measurability] theorem AeMeasurable.coeNnrealEnnreal {f : α → ℝ≥0} {μ : Measure α} (hf : AeMeasurable f μ) : AeMeasurable (fun x => (f x : ℝ≥0∞)) μ := ENNReal.continuous_coe.Measurable.compAeMeasurable hf #align ae_measurable.coe_nnreal_ennreal AeMeasurable.coeNnrealEnnreal @[measurability] theorem Measurable.eNNReal_ofReal {f : α → ℝ} (hf : Measurable f) : Measurable fun x => ENNReal.ofReal (f x) := ENNReal.continuous_ofReal.Measurable.comp hf #align measurable.ennreal_of_real Measurable.eNNReal_ofReal @[simp, norm_cast] theorem measurable_coe_nNReal_real_iff {f : α → ℝ≥0} : Measurable (fun x => f x : α → ℝ) ↔ Measurable f := ⟨fun h => by simpa only [Real.toNNReal_coe] using h.real_to_nnreal, Measurable.coe_nNReal_real⟩ #align measurable_coe_nnreal_real_iff measurable_coe_nNReal_real_iff @[simp, norm_cast] theorem aeMeasurable_coe_nNReal_real_iff {f : α → ℝ≥0} {μ : Measure α} : AeMeasurable (fun x => f x : α → ℝ) μ ↔ AeMeasurable f μ := ⟨fun h => by simpa only [Real.toNNReal_coe] using h.real_to_nnreal, AeMeasurable.coeNnrealReal⟩ #align ae_measurable_coe_nnreal_real_iff aeMeasurable_coe_nNReal_real_iff /-- The set of finite `ℝ≥0∞` numbers is `measurable_equiv` to `ℝ≥0`. -/ def MeasurableEquiv.ennrealEquivNnreal : { r : ℝ≥0∞ | r ≠ ∞ } ≃ᵐ ℝ≥0 := ENNReal.neTopHomeomorphNNReal.toMeasurableEquiv #align measurable_equiv.ennreal_equiv_nnreal MeasurableEquiv.ennrealEquivNnreal namespace ENNReal theorem measurable_of_measurable_nNReal {f : ℝ≥0∞ → α} (h : Measurable fun p : ℝ≥0 => f p) : Measurable f := measurable_of_measurable_on_compl_singleton ∞ (MeasurableEquiv.ennrealEquivNnreal.symm.measurable_comp_iff.1 h) #align ennreal.measurable_of_measurable_nnreal ENNReal.measurable_of_measurable_nNReal /-- `ℝ≥0∞` is `measurable_equiv` to `ℝ≥0 ⊕ unit`. -/ def ennrealEquivSum : ℝ≥0∞ ≃ᵐ Sum ℝ≥0 Unit := { Equiv.optionEquivSumPUnit ℝ≥0 with measurable_to_fun := measurable_of_measurable_nNReal measurable_inl measurable_inv_fun := measurable_sum measurable_coe_nNReal_eNNReal (@measurable_const ℝ≥0∞ Unit _ _ ∞) } #align ennreal.ennreal_equiv_sum ENNReal.ennrealEquivSum open Function (uncurry) theorem measurable_of_measurable_nNReal_prod [MeasurableSpace β] [MeasurableSpace γ] {f : ℝ≥0∞ × β → γ} (H₁ : Measurable fun p : ℝ≥0 × β => f (p.1, p.2)) (H₂ : Measurable fun x => f (∞, x)) : Measurable f := let e : ℝ≥0∞ × β ≃ᵐ Sum (ℝ≥0 × β) (Unit × β) := (ennrealEquivSum.prodCongr (MeasurableEquiv.refl β)).trans (MeasurableEquiv.sumProdDistrib _ _ _) e.symm.measurable_comp_iff.1 <| measurable_sum H₁ (H₂.comp measurable_id.snd) #align ennreal.measurable_of_measurable_nnreal_prod ENNReal.measurable_of_measurable_nNReal_prod theorem measurable_of_measurable_nNReal_nNReal [MeasurableSpace β] {f : ℝ≥0∞ × ℝ≥0∞ → β} (h₁ : Measurable fun p : ℝ≥0 × ℝ≥0 => f (p.1, p.2)) (h₂ : Measurable fun r : ℝ≥0 => f (∞, r)) (h₃ : Measurable fun r : ℝ≥0 => f (r, ∞)) : Measurable f := measurable_of_measurable_nNReal_prod (measurable_swap_iff.1 <| measurable_of_measurable_nNReal_prod (h₁.comp measurable_swap) h₃) (measurable_of_measurable_nNReal h₂) #align ennreal.measurable_of_measurable_nnreal_nnreal ENNReal.measurable_of_measurable_nNReal_nNReal @[measurability] theorem measurable_ofReal : Measurable ENNReal.ofReal := ENNReal.continuous_ofReal.Measurable #align ennreal.measurable_of_real ENNReal.measurable_ofReal @[measurability] theorem measurable_toReal : Measurable ENNReal.toReal := ENNReal.measurable_of_measurable_nNReal measurable_coe_nNReal_real #align ennreal.measurable_to_real ENNReal.measurable_toReal @[measurability] theorem measurable_toNNReal : Measurable ENNReal.toNNReal := ENNReal.measurable_of_measurable_nNReal measurable_id #align ennreal.measurable_to_nnreal ENNReal.measurable_toNNReal instance : HasMeasurableMul₂ ℝ≥0∞ := by refine' ⟨measurable_of_measurable_nnreal_nnreal _ _ _⟩ · simp only [← ENNReal.coe_mul, measurable_mul.coe_nnreal_ennreal] · simp only [ENNReal.top_mul', ENNReal.coe_eq_zero] exact measurable_const.piecewise (measurable_set_singleton _) measurable_const · simp only [ENNReal.mul_top', ENNReal.coe_eq_zero] exact measurable_const.piecewise (measurable_set_singleton _) measurable_const instance : HasMeasurableSub₂ ℝ≥0∞ := ⟨by apply measurable_of_measurable_nnreal_nnreal <;> simp [← WithTop.coe_sub, continuous_sub.measurable.coe_nnreal_ennreal]⟩ instance : HasMeasurableInv ℝ≥0∞ := ⟨continuous_inv.Measurable⟩ end ENNReal @[measurability] theorem Measurable.eNNReal_toNNReal {f : α → ℝ≥0∞} (hf : Measurable f) : Measurable fun x => (f x).toNNReal := ENNReal.measurable_toNNReal.comp hf #align measurable.ennreal_to_nnreal Measurable.eNNReal_toNNReal @[measurability] theorem AeMeasurable.ennrealToNnreal {f : α → ℝ≥0∞} {μ : Measure α} (hf : AeMeasurable f μ) : AeMeasurable (fun x => (f x).toNNReal) μ := ENNReal.measurable_toNNReal.compAeMeasurable hf #align ae_measurable.ennreal_to_nnreal AeMeasurable.ennrealToNnreal @[simp, norm_cast] theorem measurable_coe_nNReal_eNNReal_iff {f : α → ℝ≥0} : (Measurable fun x => (f x : ℝ≥0∞)) ↔ Measurable f := ⟨fun h => h.eNNReal_toNNReal, fun h => h.coe_nNReal_eNNReal⟩ #align measurable_coe_nnreal_ennreal_iff measurable_coe_nNReal_eNNReal_iff @[simp, norm_cast] theorem aeMeasurable_coe_nNReal_eNNReal_iff {f : α → ℝ≥0} {μ : Measure α} : AeMeasurable (fun x => (f x : ℝ≥0∞)) μ ↔ AeMeasurable f μ := ⟨fun h => h.eNNReal_toNNReal, fun h => h.coe_nNReal_eNNReal⟩ #align ae_measurable_coe_nnreal_ennreal_iff aeMeasurable_coe_nNReal_eNNReal_iff @[measurability] theorem Measurable.eNNReal_toReal {f : α → ℝ≥0∞} (hf : Measurable f) : Measurable fun x => ENNReal.toReal (f x) := ENNReal.measurable_toReal.comp hf #align measurable.ennreal_to_real Measurable.eNNReal_toReal @[measurability] theorem AeMeasurable.ennrealToReal {f : α → ℝ≥0∞} {μ : Measure α} (hf : AeMeasurable f μ) : AeMeasurable (fun x => ENNReal.toReal (f x)) μ := ENNReal.measurable_toReal.compAeMeasurable hf #align ae_measurable.ennreal_to_real AeMeasurable.ennrealToReal /-- note: `ℝ≥0∞` can probably be generalized in a future version of this lemma. -/ @[measurability] theorem Measurable.eNNReal_tsum {ι} [Countable ι] {f : ι → α → ℝ≥0∞} (h : ∀ i, Measurable (f i)) : Measurable fun x => ∑' i, f i x := by simp_rw [ENNReal.tsum_eq_supᵢ_sum] apply measurable_supᵢ exact fun s => s.measurable_sum fun i _ => h i #align measurable.ennreal_tsum Measurable.eNNReal_tsum @[measurability] theorem Measurable.eNNReal_tsum' {ι} [Countable ι] {f : ι → α → ℝ≥0∞} (h : ∀ i, Measurable (f i)) : Measurable (∑' i, f i) := by convert Measurable.eNNReal_tsum h ext1 x exact tsum_apply (Pi.summable.2 fun _ => ENNReal.summable) #align measurable.ennreal_tsum' Measurable.eNNReal_tsum' @[measurability] theorem Measurable.nNReal_tsum {ι} [Countable ι] {f : ι → α → ℝ≥0} (h : ∀ i, Measurable (f i)) : Measurable fun x => ∑' i, f i x := by simp_rw [NNReal.tsum_eq_toNNReal_tsum] exact (Measurable.eNNReal_tsum fun i => (h i).coe_nNReal_eNNReal).eNNReal_toNNReal #align measurable.nnreal_tsum Measurable.nNReal_tsum @[measurability] theorem AeMeasurable.ennrealTsum {ι} [Countable ι] {f : ι → α → ℝ≥0∞} {μ : Measure α} (h : ∀ i, AeMeasurable (f i) μ) : AeMeasurable (fun x => ∑' i, f i x) μ := by simp_rw [ENNReal.tsum_eq_supᵢ_sum] apply aeMeasurableSupr exact fun s => Finset.ae_measurable_sum s fun i _ => h i #align ae_measurable.ennreal_tsum AeMeasurable.ennrealTsum @[measurability] theorem AeMeasurable.nnrealTsum {α : Type _} [MeasurableSpace α] {ι : Type _} [Countable ι] {f : ι → α → NNReal} {μ : MeasureTheory.Measure α} (h : ∀ i : ι, AeMeasurable (f i) μ) : AeMeasurable (fun x : α => ∑' i : ι, f i x) μ := by simp_rw [NNReal.tsum_eq_toNNReal_tsum] exact (AeMeasurable.ennrealTsum fun i => (h i).coe_nNReal_eNNReal).eNNReal_toNNReal #align ae_measurable.nnreal_tsum AeMeasurable.nnrealTsum @[measurability] theorem measurable_coe_real_eReal : Measurable (coe : ℝ → EReal) := continuous_coe_real_ereal.Measurable #align measurable_coe_real_ereal measurable_coe_real_eReal @[measurability] theorem Measurable.coe_real_eReal {f : α → ℝ} (hf : Measurable f) : Measurable fun x => (f x : EReal) := measurable_coe_real_eReal.comp hf #align measurable.coe_real_ereal Measurable.coe_real_eReal @[measurability] theorem AeMeasurable.coeRealEreal {f : α → ℝ} {μ : Measure α} (hf : AeMeasurable f μ) : AeMeasurable (fun x => (f x : EReal)) μ := measurable_coe_real_eReal.compAeMeasurable hf #align ae_measurable.coe_real_ereal AeMeasurable.coeRealEreal /-- The set of finite `ereal` numbers is `measurable_equiv` to `ℝ`. -/ def MeasurableEquiv.erealEquivReal : ({⊥, ⊤}ᶜ : Set EReal) ≃ᵐ ℝ := EReal.neBotTopHomeomorphReal.toMeasurableEquiv #align measurable_equiv.ereal_equiv_real MeasurableEquiv.erealEquivReal theorem EReal.measurable_of_measurable_real {f : EReal → α} (h : Measurable fun p : ℝ => f p) : Measurable f := measurable_of_measurable_on_compl_finite {⊥, ⊤} (by simp) (MeasurableEquiv.erealEquivReal.symm.measurable_comp_iff.1 h) #align ereal.measurable_of_measurable_real EReal.measurable_of_measurable_real @[measurability] theorem measurable_eReal_toReal : Measurable EReal.toReal := EReal.measurable_of_measurable_real (by simpa using measurable_id) #align measurable_ereal_to_real measurable_eReal_toReal @[measurability] theorem Measurable.eReal_toReal {f : α → EReal} (hf : Measurable f) : Measurable fun x => (f x).toReal := measurable_eReal_toReal.comp hf #align measurable.ereal_to_real Measurable.eReal_toReal @[measurability] theorem AeMeasurable.erealToReal {f : α → EReal} {μ : Measure α} (hf : AeMeasurable f μ) : AeMeasurable (fun x => (f x).toReal) μ := measurable_eReal_toReal.compAeMeasurable hf #align ae_measurable.ereal_to_real AeMeasurable.erealToReal @[measurability] theorem measurable_coe_eNNReal_eReal : Measurable (coe : ℝ≥0∞ → EReal) := continuous_coe_ennreal_ereal.Measurable #align measurable_coe_ennreal_ereal measurable_coe_eNNReal_eReal @[measurability] theorem Measurable.coe_eReal_eNNReal {f : α → ℝ≥0∞} (hf : Measurable f) : Measurable fun x => (f x : EReal) := measurable_coe_eNNReal_eReal.comp hf #align measurable.coe_ereal_ennreal Measurable.coe_eReal_eNNReal @[measurability] theorem AeMeasurable.coeErealEnnreal {f : α → ℝ≥0∞} {μ : Measure α} (hf : AeMeasurable f μ) : AeMeasurable (fun x => (f x : EReal)) μ := measurable_coe_eNNReal_eReal.compAeMeasurable hf #align ae_measurable.coe_ereal_ennreal AeMeasurable.coeErealEnnreal section NormedAddCommGroup variable [NormedAddCommGroup α] [OpensMeasurableSpace α] [MeasurableSpace β] @[measurability] theorem measurable_norm : Measurable (norm : α → ℝ) := continuous_norm.Measurable #align measurable_norm measurable_norm @[measurability] theorem Measurable.norm {f : β → α} (hf : Measurable f) : Measurable fun a => norm (f a) := measurable_norm.comp hf #align measurable.norm Measurable.norm @[measurability] theorem AeMeasurable.norm {f : β → α} {μ : Measure β} (hf : AeMeasurable f μ) : AeMeasurable (fun a => norm (f a)) μ := measurable_norm.compAeMeasurable hf #align ae_measurable.norm AeMeasurable.norm @[measurability] theorem measurable_nnnorm : Measurable (nnnorm : α → ℝ≥0) := continuous_nnnorm.Measurable #align measurable_nnnorm measurable_nnnorm @[measurability] theorem Measurable.nnnorm {f : β → α} (hf : Measurable f) : Measurable fun a => ‖f a‖₊ := measurable_nnnorm.comp hf #align measurable.nnnorm Measurable.nnnorm @[measurability] theorem AeMeasurable.nnnorm {f : β → α} {μ : Measure β} (hf : AeMeasurable f μ) : AeMeasurable (fun a => ‖f a‖₊) μ := measurable_nnnorm.compAeMeasurable hf #align ae_measurable.nnnorm AeMeasurable.nnnorm @[measurability] theorem measurable_ennnorm : Measurable fun x : α => (‖x‖₊ : ℝ≥0∞) := measurable_nnnorm.coe_nNReal_eNNReal #align measurable_ennnorm measurable_ennnorm @[measurability] theorem Measurable.ennnorm {f : β → α} (hf : Measurable f) : Measurable fun a => (‖f a‖₊ : ℝ≥0∞) := hf.nnnorm.coe_nNReal_eNNReal #align measurable.ennnorm Measurable.ennnorm @[measurability] theorem AeMeasurable.ennnorm {f : β → α} {μ : Measure β} (hf : AeMeasurable f μ) : AeMeasurable (fun a => (‖f a‖₊ : ℝ≥0∞)) μ := measurable_ennnorm.compAeMeasurable hf #align ae_measurable.ennnorm AeMeasurable.ennnorm end NormedAddCommGroup section Limits variable [TopologicalSpace β] [PseudoMetrizableSpace β] [MeasurableSpace β] [BorelSpace β] open Metric /-- A limit (over a general filter) of measurable `ℝ≥0∞` valued functions is measurable. -/ theorem measurable_of_tendsto_ennreal' {ι} {f : ι → α → ℝ≥0∞} {g : α → ℝ≥0∞} (u : Filter ι) [NeBot u] [IsCountablyGenerated u] (hf : ∀ i, Measurable (f i)) (lim : Tendsto f u (𝓝 g)) : Measurable g := by rcases u.exists_seq_tendsto with ⟨x, hx⟩ rw [tendsto_pi_nhds] at lim have : (fun y => liminf (fun n => (f (x n) y : ℝ≥0∞)) at_top) = g := by ext1 y exact ((limUnder y).comp hx).liminf_eq rw [← this] show Measurable fun y => liminf (fun n => (f (x n) y : ℝ≥0∞)) at_top exact measurable_liminf fun n => hf (x n) #align measurable_of_tendsto_ennreal' measurable_of_tendsto_ennreal' /-- A sequential limit of measurable `ℝ≥0∞` valued functions is measurable. -/ theorem measurable_of_tendsto_eNNReal {f : ℕ → α → ℝ≥0∞} {g : α → ℝ≥0∞} (hf : ∀ i, Measurable (f i)) (lim : Tendsto f atTop (𝓝 g)) : Measurable g := measurable_of_tendsto_ennreal' atTop hf limUnder #align measurable_of_tendsto_ennreal measurable_of_tendsto_eNNReal /-- A limit (over a general filter) of measurable `ℝ≥0` valued functions is measurable. -/ theorem measurable_of_tendsto_nnreal' {ι} {f : ι → α → ℝ≥0} {g : α → ℝ≥0} (u : Filter ι) [NeBot u] [IsCountablyGenerated u] (hf : ∀ i, Measurable (f i)) (lim : Tendsto f u (𝓝 g)) : Measurable g := by simp_rw [← measurable_coe_nNReal_eNNReal_iff] at hf⊢ refine' measurable_of_tendsto_ennreal' u hf _ rw [tendsto_pi_nhds] at lim⊢ exact fun x => (ennreal.continuous_coe.tendsto (g x)).comp (limUnder x) #align measurable_of_tendsto_nnreal' measurable_of_tendsto_nnreal' /-- A sequential limit of measurable `ℝ≥0` valued functions is measurable. -/ theorem measurable_of_tendsto_nNReal {f : ℕ → α → ℝ≥0} {g : α → ℝ≥0} (hf : ∀ i, Measurable (f i)) (lim : Tendsto f atTop (𝓝 g)) : Measurable g := measurable_of_tendsto_nnreal' atTop hf limUnder #align measurable_of_tendsto_nnreal measurable_of_tendsto_nNReal /-- A limit (over a general filter) of measurable functions valued in a (pseudo) metrizable space is measurable. -/ theorem measurable_of_tendsto_metrizable' {ι} {f : ι → α → β} {g : α → β} (u : Filter ι) [NeBot u] [IsCountablyGenerated u] (hf : ∀ i, Measurable (f i)) (lim : Tendsto f u (𝓝 g)) : Measurable g := by letI : PseudoMetricSpace β := pseudo_metrizable_space_pseudo_metric β apply measurable_of_is_closed' intro s h1s h2s h3s have : Measurable fun x => inf_nndist (g x) s := by suffices : tendsto (fun i x => inf_nndist (f i x) s) u (𝓝 fun x => inf_nndist (g x) s) exact measurable_of_tendsto_nnreal' u (fun i => (hf i).infNndist) this rw [tendsto_pi_nhds] at lim⊢ intro x exact ((continuous_inf_nndist_pt s).Tendsto (g x)).comp (limUnder x) have h4s : g ⁻¹' s = (fun x => inf_nndist (g x) s) ⁻¹' {0} := by ext x simp [h1s, ← h1s.mem_iff_inf_dist_zero h2s, ← NNReal.coe_eq_zero] rw [h4s] exact this (measurable_set_singleton 0) #align measurable_of_tendsto_metrizable' measurable_of_tendsto_metrizable' /-- A sequential limit of measurable functions valued in a (pseudo) metrizable space is measurable. -/ theorem measurable_of_tendsto_metrizable {f : ℕ → α → β} {g : α → β} (hf : ∀ i, Measurable (f i)) (lim : Tendsto f atTop (𝓝 g)) : Measurable g := measurable_of_tendsto_metrizable' atTop hf limUnder #align measurable_of_tendsto_metrizable measurable_of_tendsto_metrizable theorem aeMeasurableOfTendstoMetrizableAe {ι} {μ : Measure α} {f : ι → α → β} {g : α → β} (u : Filter ι) [hu : NeBot u] [IsCountablyGenerated u] (hf : ∀ n, AeMeasurable (f n) μ) (h_tendsto : ∀ᵐ x ∂μ, Tendsto (fun n => f n x) u (𝓝 (g x))) : AeMeasurable g μ := by rcases u.exists_seq_tendsto with ⟨v, hv⟩ have h'f : ∀ n, AeMeasurable (f (v n)) μ := fun n => hf (v n) set p : α → (ℕ → β) → Prop := fun x f' => tendsto (fun n => f' n) at_top (𝓝 (g x)) have hp : ∀ᵐ x ∂μ, p x fun n => f (v n) x := by filter_upwards [h_tendsto]with x hx using hx.comp hv set ae_seq_lim := fun x => ite (x ∈ aeSeqSet h'f p) (g x) (⟨f (v 0) x⟩ : Nonempty β).some with hs refine' ⟨ae_seq_lim, measurable_of_tendsto_metrizable' at_top (aeSeq.measurable h'f p) (tendsto_pi_nhds.mpr fun x => _), _⟩ · simp_rw [aeSeq, ae_seq_lim] split_ifs with hx · simp_rw [aeSeq.mk_eq_fun_of_mem_aeSeqSet h'f hx] exact @aeSeq.funPropOfMemAeSeqSet _ α β _ _ _ _ _ h'f x hx · exact tendsto_const_nhds · exact (ite_ae_eq_of_measure_compl_zero g (fun x => (⟨f (v 0) x⟩ : Nonempty β).some) (aeSeqSet h'f p) (aeSeq.measure_compl_aeSeqSet_eq_zero h'f hp)).symm #align ae_measurable_of_tendsto_metrizable_ae aeMeasurableOfTendstoMetrizableAe theorem aeMeasurableOfTendstoMetrizableAe' {μ : Measure α} {f : ℕ → α → β} {g : α → β} (hf : ∀ n, AeMeasurable (f n) μ) (h_ae_tendsto : ∀ᵐ x ∂μ, Tendsto (fun n => f n x) atTop (𝓝 (g x))) : AeMeasurable g μ := aeMeasurableOfTendstoMetrizableAe atTop hf h_ae_tendsto #align ae_measurable_of_tendsto_metrizable_ae' aeMeasurableOfTendstoMetrizableAe' theorem aeMeasurableOfUnifApprox {β} [MeasurableSpace β] [PseudoMetricSpace β] [BorelSpace β] {μ : Measure α} {g : α → β} (hf : ∀ ε > (0 : ℝ), ∃ f : α → β, AeMeasurable f μ ∧ ∀ᵐ x ∂μ, dist (f x) (g x) ≤ ε) : AeMeasurable g μ := by obtain ⟨u, u_anti, u_pos, u_lim⟩ : ∃ u : ℕ → ℝ, StrictAnti u ∧ (∀ n : ℕ, 0 < u n) ∧ tendsto u at_top (𝓝 0) := exists_seq_strictAnti_tendsto (0 : ℝ) choose f Hf using fun n : ℕ => hf (u n) (u_pos n) have : ∀ᵐ x ∂μ, tendsto (fun n => f n x) at_top (𝓝 (g x)) := by have : ∀ᵐ x ∂μ, ∀ n, dist (f n x) (g x) ≤ u n := ae_all_iff.2 fun n => (Hf n).2 filter_upwards [this] intro x hx rw [tendsto_iff_dist_tendsto_zero] exact squeeze_zero (fun n => dist_nonneg) hx u_lim exact aeMeasurableOfTendstoMetrizableAe' (fun n => (Hf n).1) this #align ae_measurable_of_unif_approx aeMeasurableOfUnifApprox theorem measurable_of_tendsto_metrizable_ae {μ : Measure α} [μ.IsComplete] {f : ℕ → α → β} {g : α → β} (hf : ∀ n, Measurable (f n)) (h_ae_tendsto : ∀ᵐ x ∂μ, Tendsto (fun n => f n x) atTop (𝓝 (g x))) : Measurable g := aeMeasurable_iff_measurable.mp (aeMeasurableOfTendstoMetrizableAe' (fun i => (hf i).AeMeasurable) h_ae_tendsto) #align measurable_of_tendsto_metrizable_ae measurable_of_tendsto_metrizable_ae theorem measurable_limit_of_tendsto_metrizable_ae {ι} [Countable ι] [Nonempty ι] {μ : Measure α} {f : ι → α → β} {L : Filter ι} [L.IsCountablyGenerated] (hf : ∀ n, AeMeasurable (f n) μ) (h_ae_tendsto : ∀ᵐ x ∂μ, ∃ l : β, Tendsto (fun n => f n x) L (𝓝 l)) : ∃ (f_lim : α → β)(hf_lim_meas : Measurable f_lim), ∀ᵐ x ∂μ, Tendsto (fun n => f n x) L (𝓝 (f_lim x)) := by inhabit ι rcases eq_or_ne L ⊥ with (rfl | hL) · exact ⟨(hf default).mk _, (hf default).measurable_mk, eventually_of_forall fun x => tendsto_bot⟩ haveI : ne_bot L := ⟨hL⟩ let p : α → (ι → β) → Prop := fun x f' => ∃ l : β, tendsto (fun n => f' n) L (𝓝 l) have hp_mem : ∀ x ∈ aeSeqSet hf p, p x fun n => f n x := fun x hx => aeSeq.funPropOfMemAeSeqSet hf hx have h_ae_eq : ∀ᵐ x ∂μ, ∀ n, aeSeq hf p n x = f n x := aeSeq.aeSeq_eq_fun_ae hf h_ae_tendsto let f_lim : α → β := fun x => dite (x ∈ aeSeqSet hf p) (fun h => (hp_mem x h).some) fun h => (⟨f default x⟩ : Nonempty β).some have hf_lim : ∀ x, tendsto (fun n => aeSeq hf p n x) L (𝓝 (f_lim x)) := by intro x simp only [f_lim, aeSeq] split_ifs · refine' (hp_mem x h).choose_spec.congr fun n => _ exact (aeSeq.mk_eq_fun_of_mem_aeSeqSet hf h n).symm · exact tendsto_const_nhds have h_ae_tendsto_f_lim : ∀ᵐ x ∂μ, tendsto (fun n => f n x) L (𝓝 (f_lim x)) := h_ae_eq.mono fun x hx => (hf_lim x).congr hx have h_f_lim_meas : Measurable f_lim := measurable_of_tendsto_metrizable' L (aeSeq.measurable hf p) (tendsto_pi_nhds.mpr fun x => hf_lim x) exact ⟨f_lim, h_f_lim_meas, h_ae_tendsto_f_lim⟩ #align measurable_limit_of_tendsto_metrizable_ae measurable_limit_of_tendsto_metrizable_ae end Limits namespace ContinuousLinearMap variable {𝕜 : Type _} [NormedField 𝕜] variable {E : Type _} [NormedAddCommGroup E] [NormedSpace 𝕜 E] [MeasurableSpace E] [OpensMeasurableSpace E] {F : Type _} [NormedAddCommGroup F] [NormedSpace 𝕜 F] [MeasurableSpace F] [BorelSpace F] @[measurability] protected theorem measurable (L : E →L[𝕜] F) : Measurable L := L.Continuous.Measurable #align continuous_linear_map.measurable ContinuousLinearMap.measurable theorem measurable_comp (L : E →L[𝕜] F) {φ : α → E} (φ_meas : Measurable φ) : Measurable fun a : α => L (φ a) := L.Measurable.comp φ_meas #align continuous_linear_map.measurable_comp ContinuousLinearMap.measurable_comp end ContinuousLinearMap namespace ContinuousLinearMap variable {𝕜 : Type _} [NontriviallyNormedField 𝕜] variable {E : Type _} [NormedAddCommGroup E] [NormedSpace 𝕜 E] {F : Type _} [NormedAddCommGroup F] [NormedSpace 𝕜 F] instance : MeasurableSpace (E →L[𝕜] F) := borel _ instance : BorelSpace (E →L[𝕜] F) := ⟨rfl⟩ @[measurability] theorem measurable_apply [MeasurableSpace F] [BorelSpace F] (x : E) : Measurable fun f : E →L[𝕜] F => f x := (apply 𝕜 F x).Continuous.Measurable #align continuous_linear_map.measurable_apply ContinuousLinearMap.measurable_apply @[measurability] theorem measurable_apply' [MeasurableSpace E] [OpensMeasurableSpace E] [MeasurableSpace F] [BorelSpace F] : Measurable fun (x : E) (f : E →L[𝕜] F) => f x := measurable_pi_lambda _ fun f => f.Measurable #align continuous_linear_map.measurable_apply' ContinuousLinearMap.measurable_apply' @[measurability] theorem measurable_coe [MeasurableSpace F] [BorelSpace F] : Measurable fun (f : E →L[𝕜] F) (x : E) => f x := measurable_pi_lambda _ measurable_apply #align continuous_linear_map.measurable_coe ContinuousLinearMap.measurable_coe end ContinuousLinearMap section ContinuousLinearMapNontriviallyNormedField variable {𝕜 : Type _} [NontriviallyNormedField 𝕜] variable {E : Type _} [NormedAddCommGroup E] [NormedSpace 𝕜 E] [MeasurableSpace E] [BorelSpace E] {F : Type _} [NormedAddCommGroup F] [NormedSpace 𝕜 F] @[measurability] theorem Measurable.apply_continuousLinearMap {φ : α → F →L[𝕜] E} (hφ : Measurable φ) (v : F) : Measurable fun a => φ a v := (ContinuousLinearMap.apply 𝕜 E v).Measurable.comp hφ #align measurable.apply_continuous_linear_map Measurable.apply_continuousLinearMap @[measurability] theorem AeMeasurable.applyContinuousLinearMap {φ : α → F →L[𝕜] E} {μ : Measure α} (hφ : AeMeasurable φ μ) (v : F) : AeMeasurable (fun a => φ a v) μ := (ContinuousLinearMap.apply 𝕜 E v).Measurable.compAeMeasurable hφ #align ae_measurable.apply_continuous_linear_map AeMeasurable.applyContinuousLinearMap end ContinuousLinearMapNontriviallyNormedField section NormedSpace variable {𝕜 : Type _} [NontriviallyNormedField 𝕜] [CompleteSpace 𝕜] [MeasurableSpace 𝕜] variable [BorelSpace 𝕜] {E : Type _} [NormedAddCommGroup E] [NormedSpace 𝕜 E] [MeasurableSpace E] [BorelSpace E] theorem measurable_smul_const {f : α → 𝕜} {c : E} (hc : c ≠ 0) : (Measurable fun x => f x • c) ↔ Measurable f := (closedEmbedding_smul_left hc).MeasurableEmbedding.measurable_comp_iff #align measurable_smul_const measurable_smul_const theorem aeMeasurable_smul_const {f : α → 𝕜} {μ : Measure α} {c : E} (hc : c ≠ 0) : AeMeasurable (fun x => f x • c) μ ↔ AeMeasurable f μ := (closedEmbedding_smul_left hc).MeasurableEmbedding.aeMeasurable_comp_iff #align ae_measurable_smul_const aeMeasurable_smul_const end NormedSpace
Several courtyards to the east and west of the main cave are blocked , though there is a 17 m ( 56 ft ) -wide courtyard that is accessible by entering the eastern part and climbing nine steps . A temple on the southern wall of the court depicts a well @-@ preserved fresco . The circular pedestal seen in the courtyard in front of the Shiva 's shrine near the east end , in the open area , is said to be the seat of Nandi , Shiva 's mount .
function test15() filename = "test15.asc" # exectuablepath = null string will not run LTspice.exe. Test parsing only. sim = LTspiceSimulation(filename,executablepath="") @test LTspice.does_circuitfilearray_file_match(sim) show(IOBuffer(),sim) @test measurementnames(sim) == ("σ", "a", "ψπππππ") @test parameternames(sim) == ("m", "μ", "MEG", "Ω", "θ", "Δ", "Φ", "ψ") end test15()
using Revise using ImageInspector,MLDatasets, Plots x = FashionMNIST.traintensor(1); plot( plot(image(x; flip = true); title = "flip = true"), plot(image(x; flip = false); title = "flip = false"); axis = nothing, border = :none, ) x1 = FashionMNIST.traintensor(1); x2 = CIFAR10.traintensor(2); plot( plot(image(x1)), plot(image(x2)); axis = nothing, border = :none ) x = FashionMNIST.traintensor(1:10); plot(plot.(image(x, [1,2]))...; axis = nothing, border = :none) x = FashionMNIST.traintensor(1:10); plot(imagegrid(x, 1:10; nrows = 2, sep = 2); axis = nothing, border = :none) x = CIFAR10.traintensor(1:10); imageplot(x, 1:10; nrows = 2, sep = 1, background = RGB(184/255, 223/255, 250/255))
Formal statement is: lemma holomorphic_on_Un [holomorphic_intros]: assumes "f holomorphic_on A" "f holomorphic_on B" "open A" "open B" shows "f holomorphic_on (A \<union> B)" Informal statement is: If $f$ is holomorphic on two open sets $A$ and $B$, then $f$ is holomorphic on $A \cup B$.
module FibGCD import Data.Nat import Decidable.Equality fib : Nat -> Nat fib 0 = 0 fib 1 = 1 fib (S $ S n) = fib (S n) + fib n %hint fib_isSucc : (n : Nat) -> IsSucc n => IsSucc (fib n) fib_gcd : {n, m : Nat} -> case fib_isSucc (S n) of ItIsSucc => gcd {ok=LeftIsNotZero} (fib $ S n) (fib $ S m) = fib (gcd (S n) (S m))
#include <iostream> #include "greeter/greeter.hpp" #include <boost/numeric/ublas/matrix.hpp> #include <boost/numeric/ublas/io.hpp> #include <loguru.hpp> int main(int argc, char* argv[]) { using namespace boost::numeric::ublas; greeter("Now running our demo program!"); loguru::init(argc, argv); loguru::add_file("tools-cpp1.log", loguru::Truncate, loguru::Verbosity_MAX); LOG_SCOPE_F(INFO, "Program starts."); std::cout << "Testing Boost Matrix example!" << std::endl; matrix<double> m (3, 3); for (unsigned i = 0; i < m.size1 (); ++ i) for (unsigned j = 0; j < m.size2 (); ++ j) { m(i, j) = 3 * i + j; LOG_SCOPE_F(INFO, "Indices %d, %d.", i, j); } std::cout << m << std::endl; LOG_SCOPE_F(INFO, "Program ends."); greeter("Demo program ends!"); return 0; }
(* Title: Miscellaneous Definitions and Lemmas Author: Peter Lammich <[email protected]> Maintainer: Peter Lammich <[email protected]> Thomas Tuerk <[email protected]> *) (* CHANGELOG: 2010-05-09: Removed AC, AI locales, they are superseeded by concepts from OrderedGroups 2010-09-22: Merges with ext/Aux 2017-06-12: Added a bunch of lemmas from various other projects *) section \<open>Miscellaneous Definitions and Lemmas\<close> theory Misc imports Main "HOL-Library.Multiset" "HOL-ex.Quicksort" "HOL-Library.Option_ord" "HOL-Library.Infinite_Set" "HOL-Eisbach.Eisbach" begin text_raw \<open>\label{thy:Misc}\<close> subsection \<open>Isabelle Distribution Move Proposals\<close> subsubsection \<open>Pure\<close> lemma TERMI: "TERM x" unfolding Pure.term_def . subsubsection \<open>HOL\<close> (* Stronger disjunction elimination rules. *) lemma disjE1: "\<lbrakk> P \<or> Q; P \<Longrightarrow> R; \<lbrakk>\<not>P;Q\<rbrakk> \<Longrightarrow> R \<rbrakk> \<Longrightarrow> R" by metis lemma disjE2: "\<lbrakk> P \<or> Q; \<lbrakk>P; \<not>Q\<rbrakk> \<Longrightarrow> R; Q \<Longrightarrow> R \<rbrakk> \<Longrightarrow> R" by blast lemma imp_mp_iff[simp]: "a \<and> (a \<longrightarrow> b) \<longleftrightarrow> a \<and> b" "(a \<longrightarrow> b) \<and> a \<longleftrightarrow> a \<and> b" (* is Inductive.imp_conj_iff, but not in simpset by default *) by blast+ lemma atomize_Trueprop_eq[atomize]: "(Trueprop x \<equiv> Trueprop y) \<equiv> Trueprop (x=y)" apply rule apply (rule) apply (erule equal_elim_rule1) apply assumption apply (erule equal_elim_rule2) apply assumption apply simp done subsubsection \<open>Set\<close> lemma inter_compl_diff_conv[simp]: "A \<inter> -B = A - B" by auto lemma pair_set_inverse[simp]: "{(a,b). P a b}\<inverse> = {(b,a). P a b}" by auto lemma card_doubleton_eq_2_iff[simp]: "card {a,b} = 2 \<longleftrightarrow> a\<noteq>b" by auto subsubsection \<open>List\<close> (* TODO: Move, analogous to List.length_greater_0_conv *) thm List.length_greater_0_conv lemma length_ge_1_conv[iff]: "Suc 0 \<le> length l \<longleftrightarrow> l\<noteq>[]" by (cases l) auto \<comment> \<open>Obtains a list from the pointwise characterization of its elements\<close> lemma obtain_list_from_elements: assumes A: "\<forall>i<n. (\<exists>li. P li i)" obtains l where "length l = n" "\<forall>i<n. P (l!i) i" proof - from A have "\<exists>l. length l=n \<and> (\<forall>i<n. P (l!i) i)" proof (induct n) case 0 thus ?case by simp next case (Suc n) then obtain l where IH: "length l = n" "(\<forall>i<n. P(l!i) i)" by auto moreover from Suc.prems obtain ln where "P ln n" by auto ultimately have "length (l@[ln]) = Suc n" "(\<forall>i<Suc n. P((l@[ln])!i) i)" by (auto simp add: nth_append dest: less_antisym) thus ?case by blast qed thus ?thesis using that by (blast) qed lemma distinct_sorted_mono: assumes S: "sorted l" assumes D: "distinct l" assumes B: "i<j" "j<length l" shows "l!i < l!j" proof - from S B have "l!i \<le> l!j" by (simp add: sorted_iff_nth_mono) also from nth_eq_iff_index_eq[OF D] B have "l!i \<noteq> l!j" by auto finally show ?thesis . qed lemma distinct_sorted_strict_mono_iff: assumes "distinct l" "sorted l" assumes "i<length l" "j<length l" shows "l!i<l!j \<longleftrightarrow> i<j" using assms by (metis distinct_sorted_mono leI less_le_not_le order.strict_iff_order) lemma distinct_sorted_mono_iff: assumes "distinct l" "sorted l" assumes "i<length l" "j<length l" shows "l!i\<le>l!j \<longleftrightarrow> i\<le>j" by (metis assms distinct_sorted_strict_mono_iff leD le_less_linear) (* List.thy has: declare map_eq_Cons_D [dest!] Cons_eq_map_D [dest!] We could, analogously, declare rules for "map _ _ = _@_" as dest!, or use elim!, or declare the _conv-rule as simp *) lemma map_eq_appendE: assumes "map f ls = fl@fl'" obtains l l' where "ls=l@l'" and "map f l=fl" and "map f l' = fl'" using assms proof (induction fl arbitrary: ls thesis) case (Cons x xs) then obtain l ls' where [simp]: "ls = l#ls'" "f l = x" by force with Cons.prems(2) have "map f ls' = xs @ fl'" by simp from Cons.IH[OF _ this] obtain ll ll' where "ls' = ll @ ll'" "map f ll = xs" "map f ll' = fl'" . with Cons.prems(1)[of "l#ll" ll'] show thesis by simp qed simp lemma map_eq_append_conv: "map f ls = fl@fl' \<longleftrightarrow> (\<exists>l l'. ls = l@l' \<and> map f l = fl \<and> map f l' = fl')" by (auto elim!: map_eq_appendE) lemmas append_eq_mapE = map_eq_appendE[OF sym] lemma append_eq_map_conv: "fl@fl' = map f ls \<longleftrightarrow> (\<exists>l l'. ls = l@l' \<and> map f l = fl \<and> map f l' = fl')" by (auto elim!: append_eq_mapE) lemma distinct_mapI: "distinct (map f l) \<Longrightarrow> distinct l" by (induct l) auto lemma map_distinct_upd_conv: "\<lbrakk>i<length l; distinct l\<rbrakk> \<Longrightarrow> (map f l)[i := x] = map (f(l!i := x)) l" \<comment> \<open>Updating a mapped distinct list is equal to updating the mapping function\<close> by (auto simp: nth_eq_iff_index_eq intro: nth_equalityI) lemma zip_inj: "\<lbrakk>length a = length b; length a' = length b'; zip a b = zip a' b'\<rbrakk> \<Longrightarrow> a=a' \<and> b=b'" proof (induct a b arbitrary: a' b' rule: list_induct2) case Nil then show ?case by (cases a'; cases b'; auto) next case (Cons x xs y ys) then show ?case by (cases a'; cases b'; auto) qed lemma zip_eq_zip_same_len[simp]: "\<lbrakk> length a = length b; length a' = length b' \<rbrakk> \<Longrightarrow> zip a b = zip a' b' \<longleftrightarrow> a=a' \<and> b=b'" by (auto dest: zip_inj) lemma upt_merge[simp]: "i\<le>j \<and> j\<le>k \<Longrightarrow> [i..<j]@[j..<k] = [i..<k]" by (metis le_Suc_ex upt_add_eq_append) (* Maybe this should go into List.thy, next to snoc_eq_iff_butlast *) lemma snoc_eq_iff_butlast': "(ys = xs @ [x]) \<longleftrightarrow> (ys \<noteq> [] \<and> butlast ys = xs \<and> last ys = x)" by auto (* Case distinction how two elements of a list can be related to each other *) lemma list_match_lel_lel: assumes "c1 @ qs # c2 = c1' @ qs' # c2'" obtains (left) c21' where "c1 = c1' @ qs' # c21'" "c2' = c21' @ qs # c2" | (center) "c1' = c1" "qs' = qs" "c2' = c2" | (right) c21 where "c1' = c1 @ qs # c21" "c2 = c21 @ qs' # c2'" using assms apply (clarsimp simp: append_eq_append_conv2) subgoal for us by (cases us) auto done lemma xy_in_set_cases[consumes 2, case_names EQ XY YX]: assumes A: "x\<in>set l" "y\<in>set l" and C: "!!l1 l2. \<lbrakk> x=y; l=l1@y#l2 \<rbrakk> \<Longrightarrow> P" "!!l1 l2 l3. \<lbrakk> x\<noteq>y; l=l1@x#l2@y#l3 \<rbrakk> \<Longrightarrow> P" "!!l1 l2 l3. \<lbrakk> x\<noteq>y; l=l1@y#l2@x#l3 \<rbrakk> \<Longrightarrow> P" shows P proof (cases "x=y") case True with A(1) obtain l1 l2 where "l=l1@y#l2" by (blast dest: split_list) with C(1) True show ?thesis by blast next case False from A(1) obtain l1 l2 where S1: "l=l1@x#l2" by (blast dest: split_list) from A(2) obtain l1' l2' where S2: "l=l1'@y#l2'" by (blast dest: split_list) from S1 S2 have M: "l1@x#l2 = l1'@y#l2'" by simp thus P proof (cases rule: list_match_lel_lel[consumes 1, case_names 1 2 3]) case (1 c) with S1 have "l=l1'@y#c@x#l2" by simp with C(3) False show ?thesis by blast next case 2 with False have False by blast thus ?thesis .. next case (3 c) with S1 have "l=l1@x#c@y#l2'" by simp with C(2) False show ?thesis by blast qed qed lemma list_e_eq_lel[simp]: "[e] = l1@e'#l2 \<longleftrightarrow> l1=[] \<and> e'=e \<and> l2=[]" "l1@e'#l2 = [e] \<longleftrightarrow> l1=[] \<and> e'=e \<and> l2=[]" apply (cases l1, auto) [] apply (cases l1, auto) [] done lemma list_ee_eq_leel[simp]: "([e1,e2] = l1@e1'#e2'#l2) \<longleftrightarrow> (l1=[] \<and> e1=e1' \<and> e2=e2' \<and> l2=[])" "(l1@e1'#e2'#l2 = [e1,e2]) \<longleftrightarrow> (l1=[] \<and> e1=e1' \<and> e2=e2' \<and> l2=[])" apply (cases l1, auto) [] apply (cases l1, auto) [] done subsubsection \<open>Transitive Closure\<close> text \<open>A point-free induction rule for elements reachable from an initial set\<close> lemma rtrancl_reachable_induct[consumes 0, case_names base step]: assumes I0: "I \<subseteq> INV" assumes IS: "E``INV \<subseteq> INV" shows "E\<^sup>*``I \<subseteq> INV" by (metis I0 IS Image_closed_trancl Image_mono subset_refl) lemma acyclic_empty[simp, intro!]: "acyclic {}" by (unfold acyclic_def) auto lemma acyclic_union: "acyclic (A\<union>B) \<Longrightarrow> acyclic A" "acyclic (A\<union>B) \<Longrightarrow> acyclic B" by (metis Un_upper1 Un_upper2 acyclic_subset)+ text \<open>Here we provide a collection of miscellaneous definitions and helper lemmas\<close> subsection "Miscellaneous (1)" text \<open>This stuff is used in this theory itself, and thus occurs in first place or is simply not sorted into any other section of this theory.\<close> lemma IdD: "(a,b)\<in>Id \<Longrightarrow> a=b" by simp text \<open>Conversion Tag\<close> definition [simp]: "CNV x y \<equiv> x=y" lemma CNV_I: "CNV x x" by simp lemma CNV_eqD: "CNV x y \<Longrightarrow> x=y" by simp lemma CNV_meqD: "CNV x y \<Longrightarrow> x\<equiv>y" by simp (* TODO: Move. Shouldn't this be detected by simproc? *) lemma ex_b_b_and_simp[simp]: "(\<exists>b. b \<and> Q b) \<longleftrightarrow> Q True" by auto lemma ex_b_not_b_and_simp[simp]: "(\<exists>b. \<not>b \<and> Q b) \<longleftrightarrow> Q False" by auto method repeat_all_new methods m = m;(repeat_all_new \<open>m\<close>)? subsubsection "AC-operators" text \<open>Locale to declare AC-laws as simplification rules\<close> locale Assoc = fixes f assumes assoc[simp]: "f (f x y) z = f x (f y z)" locale AC = Assoc + assumes commute[simp]: "f x y = f y x" lemma (in AC) left_commute[simp]: "f x (f y z) = f y (f x z)" by (simp only: assoc[symmetric]) simp lemmas (in AC) AC_simps = commute assoc left_commute text \<open>Locale to define functions from surjective, unique relations\<close> locale su_rel_fun = fixes F and f assumes unique: "\<lbrakk>(A,B)\<in>F; (A,B')\<in>F\<rbrakk> \<Longrightarrow> B=B'" assumes surjective: "\<lbrakk>!!B. (A,B)\<in>F \<Longrightarrow> P\<rbrakk> \<Longrightarrow> P" assumes f_def: "f A == THE B. (A,B)\<in>F" lemma (in su_rel_fun) repr1: "(A,f A)\<in>F" proof (unfold f_def) obtain B where "(A,B)\<in>F" by (rule surjective) with theI[where P="\<lambda>B. (A,B)\<in>F", OF this] show "(A, THE x. (A, x) \<in> F) \<in> F" by (blast intro: unique) qed lemma (in su_rel_fun) repr2: "(A,B)\<in>F \<Longrightarrow> B=f A" using repr1 by (blast intro: unique) lemma (in su_rel_fun) repr: "(f A = B) = ((A,B)\<in>F)" using repr1 repr2 by (blast) \<comment> \<open>Contract quantification over two variables to pair\<close> lemma Ex_prod_contract: "(\<exists>a b. P a b) \<longleftrightarrow> (\<exists>z. P (fst z) (snd z))" by auto lemma All_prod_contract: "(\<forall>a b. P a b) \<longleftrightarrow> (\<forall>z. P (fst z) (snd z))" by auto lemma nat_geq_1_eq_neqz: "x\<ge>1 \<longleftrightarrow> x\<noteq>(0::nat)" by auto lemma nat_in_between_eq: "(a<b \<and> b\<le>Suc a) \<longleftrightarrow> b = Suc a" "(a\<le>b \<and> b<Suc a) \<longleftrightarrow> b = a" by auto lemma Suc_n_minus_m_eq: "\<lbrakk> n\<ge>m; m>1 \<rbrakk> \<Longrightarrow> Suc (n - m) = n - (m - 1)" by simp lemma Suc_to_right: "Suc n = m \<Longrightarrow> n = m - Suc 0" by simp lemma Suc_diff[simp]: "\<And>n m. n\<ge>m \<Longrightarrow> m\<ge>1 \<Longrightarrow> Suc (n - m) = n - (m - 1)" by simp lemma if_not_swap[simp]: "(if \<not>c then a else b) = (if c then b else a)" by auto lemma all_to_meta: "Trueprop (\<forall>a. P a) \<equiv> (\<And>a. P a)" apply rule by auto lemma imp_to_meta: "Trueprop (P\<longrightarrow>Q) \<equiv> (P\<Longrightarrow>Q)" apply rule by auto (* for some reason, there is no such rule in HOL *) lemma iffI2: "\<lbrakk>P \<Longrightarrow> Q; \<not> P \<Longrightarrow> \<not> Q\<rbrakk> \<Longrightarrow> P \<longleftrightarrow> Q" by metis lemma iffExI: "\<lbrakk> \<And>x. P x \<Longrightarrow> Q x; \<And>x. Q x \<Longrightarrow> P x \<rbrakk> \<Longrightarrow> (\<exists>x. P x) \<longleftrightarrow> (\<exists>x. Q x)" by metis lemma bex2I[intro?]: "\<lbrakk> (a,b)\<in>S; (a,b)\<in>S \<Longrightarrow> P a b \<rbrakk> \<Longrightarrow> \<exists>a b. (a,b)\<in>S \<and> P a b" by blast (* TODO: Move lemma to HOL! *) lemma cnv_conj_to_meta: "(P \<and> Q \<Longrightarrow> PROP X) \<equiv> (\<lbrakk>P;Q\<rbrakk> \<Longrightarrow> PROP X)" by (rule BNF_Fixpoint_Base.conj_imp_eq_imp_imp) subsection \<open>Sets\<close> lemma remove_subset: "x\<in>S \<Longrightarrow> S-{x} \<subset> S" by auto lemma subset_minus_empty: "A\<subseteq>B \<Longrightarrow> A-B = {}" by auto lemma insert_minus_eq: "x\<noteq>y \<Longrightarrow> insert x A - {y} = insert x (A - {y})" by auto lemma set_notEmptyE: "\<lbrakk>S\<noteq>{}; !!x. x\<in>S \<Longrightarrow> P\<rbrakk> \<Longrightarrow> P" by (metis equals0I) lemma subset_Collect_conv: "S \<subseteq> Collect P \<longleftrightarrow> (\<forall>x\<in>S. P x)" by auto lemma memb_imp_not_empty: "x\<in>S \<Longrightarrow> S\<noteq>{}" by auto lemma disjoint_mono: "\<lbrakk> a\<subseteq>a'; b\<subseteq>b'; a'\<inter>b'={} \<rbrakk> \<Longrightarrow> a\<inter>b={}" by auto lemma disjoint_alt_simp1: "A-B = A \<longleftrightarrow> A\<inter>B = {}" by auto lemma disjoint_alt_simp2: "A-B \<noteq> A \<longleftrightarrow> A\<inter>B \<noteq> {}" by auto lemma disjoint_alt_simp3: "A-B \<subset> A \<longleftrightarrow> A\<inter>B \<noteq> {}" by auto lemma disjointI[intro?]: "\<lbrakk> \<And>x. \<lbrakk>x\<in>a; x\<in>b\<rbrakk> \<Longrightarrow> False \<rbrakk> \<Longrightarrow> a\<inter>b={}" by auto lemmas set_simps = subset_minus_empty disjoint_alt_simp1 disjoint_alt_simp2 disjoint_alt_simp3 Un_absorb1 Un_absorb2 lemma set_minus_singleton_eq: "x\<notin>X \<Longrightarrow> X-{x} = X" by auto lemma set_diff_diff_left: "A-B-C = A-(B\<union>C)" by auto lemma image_update[simp]: "x\<notin>A \<Longrightarrow> f(x:=n)`A = f`A" by auto lemma eq_or_mem_image_simp[simp]: "{f l |l. l = a \<or> l\<in>B} = insert (f a) {f l|l. l\<in>B}" by blast lemma set_union_code [code_unfold]: "set xs \<union> set ys = set (xs @ ys)" by auto lemma in_fst_imageE: assumes "x \<in> fst`S" obtains y where "(x,y)\<in>S" using assms by auto lemma in_snd_imageE: assumes "y \<in> snd`S" obtains x where "(x,y)\<in>S" using assms by auto lemma fst_image_mp: "\<lbrakk>fst`A \<subseteq> B; (x,y)\<in>A \<rbrakk> \<Longrightarrow> x\<in>B" by (metis Domain.DomainI fst_eq_Domain in_mono) lemma snd_image_mp: "\<lbrakk>snd`A \<subseteq> B; (x,y)\<in>A \<rbrakk> \<Longrightarrow> y\<in>B" by (metis Range.intros rev_subsetD snd_eq_Range) lemma inter_eq_subsetI: "\<lbrakk> S\<subseteq>S'; A\<inter>S' = B\<inter>S' \<rbrakk> \<Longrightarrow> A\<inter>S = B\<inter>S" by auto text \<open> Decompose general union over sum types. \<close> lemma Union_plus: "(\<Union> x \<in> A <+> B. f x) = (\<Union> a \<in> A. f (Inl a)) \<union> (\<Union>b \<in> B. f (Inr b))" by auto lemma Union_sum: "(\<Union>x. f (x::'a+'b)) = (\<Union>l. f (Inl l)) \<union> (\<Union>r. f (Inr r))" (is "?lhs = ?rhs") proof - have "?lhs = (\<Union>x \<in> UNIV <+> UNIV. f x)" by simp thus ?thesis by (simp only: Union_plus) qed subsubsection \<open>Finite Sets\<close> lemma card_1_singletonI: "\<lbrakk>finite S; card S = 1; x\<in>S\<rbrakk> \<Longrightarrow> S={x}" proof (safe, rule ccontr, goal_cases) case prems: (1 x') hence "finite (S-{x})" "S-{x} \<noteq> {}" by auto hence "card (S-{x}) \<noteq> 0" by auto moreover from prems(1-3) have "card (S-{x}) = 0" by auto ultimately have False by simp thus ?case .. qed lemma card_insert_disjoint': "\<lbrakk>finite A; x \<notin> A\<rbrakk> \<Longrightarrow> card (insert x A) - Suc 0 = card A" by (drule (1) card_insert_disjoint) auto lemma card_eq_UNIV[simp]: "card (S::'a::finite set) = card (UNIV::'a set) \<longleftrightarrow> S=UNIV" proof (auto) fix x assume A: "card S = card (UNIV::'a set)" show "x\<in>S" proof (rule ccontr) assume "x\<notin>S" hence "S\<subset>UNIV" by auto with psubset_card_mono[of UNIV S] have "card S < card (UNIV::'a set)" by auto with A show False by simp qed qed lemma card_eq_UNIV2[simp]: "card (UNIV::'a set) = card (S::'a::finite set) \<longleftrightarrow> S=UNIV" using card_eq_UNIV[of S] by metis lemma card_ge_UNIV[simp]: "card (UNIV::'a::finite set) \<le> card (S::'a set) \<longleftrightarrow> S=UNIV" using card_mono[of "UNIV::'a::finite set" S, simplified] by auto lemmas length_remdups_card = length_remdups_concat[of "[l]", simplified] for l lemma fs_contract: "fst ` { p | p. f (fst p) (snd p) \<in> S } = { a . \<exists>b. f a b \<in> S }" by (simp add: image_Collect) lemma finite_Collect: "finite S \<Longrightarrow> inj f \<Longrightarrow> finite {a. f a : S}" by(simp add: finite_vimageI vimage_def[symmetric]) \<comment> \<open>Finite sets have an injective mapping to an initial segments of the natural numbers\<close> (* This lemma is also in the standard library (from Isabelle2009-1 on) as @{thm [source] Finite_Set.finite_imp_inj_to_nat_seg}. However, it is formulated with HOL's \<exists> there rather then with the meta-logic obtain *) lemma finite_imp_inj_to_nat_seg': fixes A :: "'a set" assumes A: "finite A" obtains f::"'a \<Rightarrow> nat" and n::"nat" where "f`A = {i. i<n}" "inj_on f A" by (metis A finite_imp_inj_to_nat_seg) lemma lists_of_len_fin2: "finite P \<Longrightarrow> finite (lists P \<inter> { l. n = length l })" proof - assume A: "finite P" have S: "{ l. n = length l } = { l. length l = n }" by auto have "finite (lists P \<inter> { l. n = length l }) \<longleftrightarrow> finite (lists P \<inter> { l. length l = n })" by (subst S) simp thus ?thesis using lists_of_len_fin1[OF A] by auto qed lemmas lists_of_len_fin = lists_of_len_fin1 lists_of_len_fin2 (* Try (simp only: cset_fin_simps, fastforce intro: cset_fin_intros) when reasoning about finiteness of collected sets *) lemmas cset_fin_simps = Ex_prod_contract fs_contract[symmetric] image_Collect[symmetric] lemmas cset_fin_intros = finite_imageI finite_Collect inj_onI lemma Un_interval: fixes b1 :: "'a::linorder" assumes "b1\<le>b2" and "b2\<le>b3" shows "{ f i | i. b1\<le>i \<and> i<b2 } \<union> { f i | i. b2\<le>i \<and> i<b3 } = {f i | i. b1\<le>i \<and> i<b3}" using assms apply - apply rule apply safe [] apply (rule_tac x=i in exI, auto) [] apply (rule_tac x=i in exI, auto) [] apply rule apply simp apply (elim exE, simp) apply (case_tac "i<b2") apply (rule disjI1) apply (rule_tac x=i in exI, auto) [] apply (rule disjI2) apply (rule_tac x=i in exI, auto) [] done text \<open> The standard library proves that a generalized union is finite if the index set is finite and if for every index the component set is itself finite. Conversely, we show that every component set must be finite when the union is finite. \<close> lemma finite_UNION_then_finite: "finite (\<Union>(B ` A)) \<Longrightarrow> a \<in> A \<Longrightarrow> finite (B a)" by (metis Set.set_insert UN_insert Un_infinite) lemma finite_if_eq_beyond_finite: "finite S \<Longrightarrow> finite {s. s - S = s' - S}" proof (rule finite_subset[where B="(\<lambda>s. s \<union> (s' - S)) ` Pow S"], clarsimp) fix s have "s = (s \<inter> S) \<union> (s - S)" by auto also assume "s - S = s' - S" finally show "s \<in> (\<lambda>s. s \<union> (s' - S)) ` Pow S" by blast qed blast lemma distinct_finite_subset: assumes "finite x" shows "finite {ys. set ys \<subseteq> x \<and> distinct ys}" (is "finite ?S") proof (rule finite_subset) from assms show "?S \<subseteq> {ys. set ys \<subseteq> x \<and> length ys \<le> card x}" by clarsimp (metis distinct_card card_mono) from assms show "finite ..." by (rule finite_lists_length_le) qed lemma distinct_finite_set: shows "finite {ys. set ys = x \<and> distinct ys}" (is "finite ?S") proof (cases "finite x") case False hence "{ys. set ys = x} = {}" by auto thus ?thesis by simp next case True show ?thesis proof (rule finite_subset) show "?S \<subseteq> {ys. set ys \<subseteq> x \<and> length ys \<le> card x}" using distinct_card by force from True show "finite ..." by (rule finite_lists_length_le) qed qed lemma finite_set_image: assumes f: "finite (set ` A)" and dist: "\<And>xs. xs \<in> A \<Longrightarrow> distinct xs" shows "finite A" proof (rule finite_subset) from f show "finite (set -` (set ` A) \<inter> {xs. distinct xs})" proof (induct rule: finite_induct) case (insert x F) have "finite (set -` {x} \<inter> {xs. distinct xs})" apply (simp add: vimage_def) by (metis Collect_conj_eq distinct_finite_set) with insert show ?case apply (subst vimage_insert) apply (subst Int_Un_distrib2) apply (rule finite_UnI) apply simp_all done qed simp moreover from dist show "A \<subseteq> ..." by (auto simp add: vimage_image_eq) qed subsubsection \<open>Infinite Set\<close> lemma INFM_nat_inductI: assumes P0: "P (0::nat)" assumes PS: "\<And>i. P i \<Longrightarrow> \<exists>j>i. P j \<and> Q j" shows "\<exists>\<^sub>\<infinity>i. Q i" proof - have "\<forall>i. \<exists>j>i. P j \<and> Q j" proof fix i show "\<exists>j>i. P j \<and> Q j" apply (induction i) using PS[OF P0] apply auto [] by (metis PS Suc_lessI) qed thus ?thesis unfolding INFM_nat by blast qed subsection \<open>Functions\<close> lemma fun_neq_ext_iff: "m\<noteq>m' \<longleftrightarrow> (\<exists>x. m x \<noteq> m' x)" by auto definition "inv_on f A x == SOME y. y\<in>A \<and> f y = x" lemma inv_on_f_f[simp]: "\<lbrakk>inj_on f A; x\<in>A\<rbrakk> \<Longrightarrow> inv_on f A (f x) = x" by (auto simp add: inv_on_def inj_on_def) lemma f_inv_on_f: "\<lbrakk> y\<in>f`A \<rbrakk> \<Longrightarrow> f (inv_on f A y) = y" by (auto simp add: inv_on_def intro: someI2) lemma inv_on_f_range: "\<lbrakk> y \<in> f`A \<rbrakk> \<Longrightarrow> inv_on f A y \<in> A" by (auto simp add: inv_on_def intro: someI2) lemma inj_on_map_inv_f [simp]: "\<lbrakk>set l \<subseteq> A; inj_on f A\<rbrakk> \<Longrightarrow> map (inv_on f A) (map f l) = l" apply (simp) apply (induct l) apply auto done lemma comp_cong_right: "x = y \<Longrightarrow> f o x = f o y" by (simp) lemma comp_cong_left: "x = y \<Longrightarrow> x o f = y o f" by (simp) lemma fun_comp_eq_conv: "f o g = fg \<longleftrightarrow> (\<forall>x. f (g x) = fg x)" by auto abbreviation comp2 (infixl "oo" 55) where "f oo g \<equiv> \<lambda>x. f o (g x)" abbreviation comp3 (infixl "ooo" 55) where "f ooo g \<equiv> \<lambda>x. f oo (g x)" notation comp2 (infixl "\<circ>\<circ>" 55) and comp3 (infixl "\<circ>\<circ>\<circ>" 55) definition [code_unfold, simp]: "swap_args2 f x y \<equiv> f y x" subsection \<open>Multisets\<close> (* The following is a syntax extension for multisets. Unfortunately, it depends on a change in the Library/Multiset.thy, so it is commented out here, until it will be incorporated into Library/Multiset.thy by its maintainers. The required change in Library/Multiset.thy is removing the syntax for single: - single :: "'a => 'a multiset" ("{#_#}") + single :: "'a => 'a multiset" And adding the following translations instead: + syntax + "_multiset" :: "args \<Rightarrow> 'a multiset" ("{#(_)#}") + translations + "{#x, xs#}" == "{#x#} + {#xs#}" + "{# x #}" == "single x" This translates "{# \<dots> #}" into a sum of singletons, that is parenthesized to the right. ?? Can we also achieve left-parenthesizing ?? *) (* Let's try what happens if declaring AC-rules for multiset union as simp-rules *) (*declare union_ac[simp] -- don't do it !*) lemma count_mset_set_finite_iff: "finite S \<Longrightarrow> count (mset_set S) a = (if a \<in> S then 1 else 0)" by simp lemma ex_Melem_conv: "(\<exists>x. x \<in># A) = (A \<noteq> {#})" by (simp add: ex_in_conv) subsubsection \<open>Count\<close> lemma count_ne_remove: "\<lbrakk> x ~= t\<rbrakk> \<Longrightarrow> count S x = count (S-{#t#}) x" by (auto) lemma mset_empty_count[simp]: "(\<forall>p. count M p = 0) = (M={#})" by (auto simp add: multiset_eq_iff) subsubsection \<open>Union, difference and intersection\<close> lemma size_diff_se: "t \<in># S \<Longrightarrow> size S = size (S - {#t#}) + 1" proof (unfold size_multiset_overloaded_eq) let ?SIZE = "sum (count S) (set_mset S)" assume A: "t \<in># S" from A have SPLITPRE: "finite (set_mset S) & {t}\<subseteq>(set_mset S)" by auto hence "?SIZE = sum (count S) (set_mset S - {t}) + sum (count S) {t}" by (blast dest: sum.subset_diff) hence "?SIZE = sum (count S) (set_mset S - {t}) + count (S) t" by auto moreover with A have "count S t = count (S-{#t#}) t + 1" by auto ultimately have D: "?SIZE = sum (count S) (set_mset S - {t}) + count (S-{#t#}) t + 1" by (arith) moreover have "sum (count S) (set_mset S - {t}) = sum (count (S-{#t#})) (set_mset S - {t})" proof - have "\<forall>x\<in>(set_mset S - {t}). count S x = count (S-{#t#}) x" by (auto iff add: count_ne_remove) thus ?thesis by simp qed ultimately have D: "?SIZE = sum (count (S-{#t#})) (set_mset S - {t}) + count (S-{#t#}) t + 1" by (simp) moreover { assume CASE: "t \<notin># S - {#t#}" from CASE have "set_mset S - {t} = set_mset (S - {#t#})" by (auto simp add: in_diff_count split: if_splits) with CASE D have "?SIZE = sum (count (S-{#t#})) (set_mset (S - {#t#})) + 1" by (simp add: not_in_iff) } moreover { assume CASE: "t \<in># S - {#t#}" from CASE have "t \<in># S" by (rule in_diffD) with CASE have 1: "set_mset S = set_mset (S-{#t#})" by (auto simp add: in_diff_count split: if_splits) moreover from D have "?SIZE = sum (count (S-{#t#})) (set_mset S - {t}) + sum (count (S-{#t#})) {t} + 1" by simp moreover from SPLITPRE sum.subset_diff have "sum (count (S-{#t#})) (set_mset S) = sum (count (S-{#t#})) (set_mset S - {t}) + sum (count (S-{#t#})) {t}" by (blast) ultimately have "?SIZE = sum (count (S-{#t#})) (set_mset (S-{#t#})) + 1" by simp } ultimately show "?SIZE = sum (count (S-{#t#})) (set_mset (S - {#t#})) + 1" by blast qed (* TODO: Check whether this proof can be done simpler *) lemma mset_union_diff_comm: "t \<in># S \<Longrightarrow> T + (S - {#t#}) = (T + S) - {#t#}" proof - assume "t \<in># S" then obtain S' where S: "S = add_mset t S'" by (metis insert_DiffM) then show ?thesis by auto qed (* lemma mset_diff_diff_left: "A-B-C = A-((B::'a multiset)+C)" proof - have "\<forall>e . count (A-B-C) e = count (A-(B+C)) e" by auto thus ?thesis by (simp add: multiset_eq_conv_count_eq) qed lemma mset_diff_commute: "A-B-C = A-C-(B::'a multiset)" proof - have "A-B-C = A-(B+C)" by (simp add: mset_diff_diff_left) also have "\<dots> = A-(C+B)" by (simp add: union_commute) thus ?thesis by (simp add: mset_diff_diff_left) qed lemma mset_diff_same_empty[simp]: "(S::'a multiset) - S = {#}" proof - have "\<forall>e . count (S-S) e = 0" by auto hence "\<forall>e . ~ (e : set_mset (S-S))" by auto hence "set_mset (S-S) = {}" by blast thus ?thesis by (auto) qed *) lemma mset_right_cancel_union: "\<lbrakk>a \<in># A+B; ~(a \<in># B)\<rbrakk> \<Longrightarrow> a\<in>#A" by (simp) lemma mset_left_cancel_union: "\<lbrakk>a \<in># A+B; ~(a \<in># A)\<rbrakk> \<Longrightarrow> a\<in>#B" by (simp) lemmas mset_cancel_union = mset_right_cancel_union mset_left_cancel_union lemma mset_right_cancel_elem: "\<lbrakk>a \<in># A+{#b#}; a~=b\<rbrakk> \<Longrightarrow> a\<in>#A" by simp lemma mset_left_cancel_elem: "\<lbrakk>a \<in># {#b#}+A; a~=b\<rbrakk> \<Longrightarrow> a\<in>#A" by simp lemmas mset_cancel_elem = mset_right_cancel_elem mset_left_cancel_elem lemma mset_diff_cancel1elem[simp]: "~(a \<in># B) \<Longrightarrow> {#a#}-B = {#a#}" by (auto simp add: not_in_iff intro!: multiset_eqI) (* lemma diff_union_inverse[simp]: "A + B - B = (A::'a multiset)" by (auto iff add: multiset_eq_conv_count_eq) lemma diff_union_inverse2[simp]: "B + A - B = (A::'a multiset)" by (auto iff add: multiset_eq_conv_count_eq) *) (*lemma union_diff_assoc_se2: "t \<in># A \<Longrightarrow> (A+B)-{#t#} = (A-{#t#}) + B" by (auto iff add: multiset_eq_conv_count_eq) lemmas union_diff_assoc_se = union_diff_assoc_se1 union_diff_assoc_se2*) lemma union_diff_assoc: "C-B={#} \<Longrightarrow> (A+B)-C = A + (B-C)" by (simp add: multiset_eq_iff) lemmas mset_neutral_cancel1 = union_left_cancel[where N="{#}", simplified] union_right_cancel[where N="{#}", simplified] declare mset_neutral_cancel1[simp] lemma mset_union_2_elem: "{#a, b#} = add_mset c M \<Longrightarrow> {#a#}=M & b=c | a=c & {#b#}=M" by (auto simp: add_eq_conv_diff) lemma mset_un_cases[cases set, case_names left right]: "\<lbrakk>a \<in># A + B; a \<in># A \<Longrightarrow> P; a \<in># B \<Longrightarrow> P\<rbrakk> \<Longrightarrow> P" by (auto) lemma mset_unplusm_dist_cases[cases set, case_names left right]: assumes A: "{#s#}+A = B+C" assumes L: "\<lbrakk>B={#s#}+(B-{#s#}); A=(B-{#s#})+C\<rbrakk> \<Longrightarrow> P" assumes R: "\<lbrakk>C={#s#}+(C-{#s#}); A=B+(C-{#s#})\<rbrakk> \<Longrightarrow> P" shows P proof - from A[symmetric] have "s \<in># B+C" by simp thus ?thesis proof (cases rule: mset_un_cases) case left hence 1: "B={#s#}+(B-{#s#})" by simp with A have "{#s#}+A = {#s#}+((B-{#s#})+C)" by (simp add: union_ac) hence 2: "A = (B-{#s#})+C" by (simp) from L[OF 1 2] show ?thesis . next case right hence 1: "C={#s#}+(C-{#s#})" by simp with A have "{#s#}+A = {#s#}+(B+(C-{#s#}))" by (simp add: union_ac) hence 2: "A = B+(C-{#s#})" by (simp) from R[OF 1 2] show ?thesis . qed qed lemma mset_unplusm_dist_cases2[cases set, case_names left right]: assumes A: "B+C = {#s#}+A" assumes L: "\<lbrakk>B={#s#}+(B-{#s#}); A=(B-{#s#})+C\<rbrakk> \<Longrightarrow> P" assumes R: "\<lbrakk>C={#s#}+(C-{#s#}); A=B+(C-{#s#})\<rbrakk> \<Longrightarrow> P" shows P using mset_unplusm_dist_cases[OF A[symmetric]] L R by blast lemma mset_single_cases[cases set, case_names loc env]: assumes A: "add_mset s c = add_mset r' c'" assumes CASES: "\<lbrakk>s=r'; c=c'\<rbrakk> \<Longrightarrow> P" "\<lbrakk>c'={#s#}+(c'-{#s#}); c={#r'#}+(c-{#r'#}); c-{#r'#} = c'-{#s#} \<rbrakk> \<Longrightarrow> P" shows "P" proof - { assume CASE: "s=r'" with A have "c=c'" by simp with CASE CASES have ?thesis by auto } moreover { assume CASE: "s\<noteq>r'" have "s \<in># {#s#}+c" by simp with A have "s \<in># {#r'#}+c'" by simp with CASE have "s \<in># c'" by simp hence 1: "c' = {#s#} + (c' - {#s#})" by simp with A have "{#s#}+c = {#s#}+({#r'#}+(c' - {#s#}))" by (auto simp add: union_ac) hence 2: "c={#r'#}+(c' - {#s#})" by (auto) hence 3: "c-{#r'#} = (c' - {#s#})" by auto from 1 2 3 CASES have ?thesis by auto } ultimately show ?thesis by blast qed lemma mset_single_cases'[cases set, case_names loc env]: assumes A: "add_mset s c = add_mset r' c'" assumes CASES: "\<lbrakk>s=r'; c=c'\<rbrakk> \<Longrightarrow> P" "!!cc. \<lbrakk>c'={#s#}+cc; c={#r'#}+cc; c'-{#s#}=cc; c-{#r'#}=cc\<rbrakk> \<Longrightarrow> P" shows "P" using A CASES by (auto elim!: mset_single_cases) lemma mset_single_cases2[cases set, case_names loc env]: assumes A: "add_mset s c = add_mset r' c'" assumes CASES: "\<lbrakk>s=r'; c=c'\<rbrakk> \<Longrightarrow> P" "\<lbrakk>c'=(c'-{#s#})+{#s#}; c=(c-{#r'#})+{#r'#}; c-{#r'#} = c'-{#s#} \<rbrakk> \<Longrightarrow> P" shows "P" proof - from A have "add_mset s c = add_mset r' c'" by (simp add: union_ac) thus ?thesis using CASES by (cases rule: mset_single_cases) simp_all qed lemma mset_single_cases2'[cases set, case_names loc env]: assumes A: "add_mset s c = add_mset r' c'" assumes CASES: "\<lbrakk>s=r'; c=c'\<rbrakk> \<Longrightarrow> P" "!!cc. \<lbrakk>c'=cc+{#s#}; c=cc+{#r'#}; c'-{#s#}=cc; c-{#r'#}=cc\<rbrakk> \<Longrightarrow> P" shows "P" using A CASES by (auto elim!: mset_single_cases2) lemma mset_un_single_un_cases [consumes 1, case_names left right]: assumes A: "add_mset a A = B + C" and CASES: "a \<in># B \<Longrightarrow> A = (B - {#a#}) + C \<Longrightarrow> P" "a \<in># C \<Longrightarrow> A = B + (C - {#a#}) \<Longrightarrow> P" shows "P" proof - have "a \<in># A+{#a#}" by simp with A have "a \<in># B+C" by auto thus ?thesis proof (cases rule: mset_un_cases) case left hence "B=B-{#a#}+{#a#}" by auto with A have "A+{#a#} = (B-{#a#})+C+{#a#}" by (auto simp add: union_ac) hence "A=(B-{#a#})+C" by simp with CASES(1)[OF left] show ?thesis by blast next case right hence "C=C-{#a#}+{#a#}" by auto with A have "A+{#a#} = B+(C-{#a#})+{#a#}" by (auto simp add: union_ac) hence "A=B+(C-{#a#})" by simp with CASES(2)[OF right] show ?thesis by blast qed qed (* TODO: Can this proof be done more automatically ? *) lemma mset_distrib[consumes 1, case_names dist]: assumes A: "(A::'a multiset)+B = M+N" "!!Am An Bm Bn. \<lbrakk>A=Am+An; B=Bm+Bn; M=Am+Bm; N=An+Bn\<rbrakk> \<Longrightarrow> P" shows "P" proof - have BN_MA: "B - N = M - A" by (metis (no_types) add_diff_cancel_right assms(1) union_commute) have H: "A = A\<inter># C + (A - C) \<inter># D" if "A + B = C + D" for A B C D :: "'a multiset" by (metis add.commute diff_intersect_left_idem mset_subset_eq_add_left subset_eq_diff_conv subset_mset.add_diff_inverse subset_mset.inf_absorb1 subset_mset.inf_le1 that) have A': "A = A\<inter># M + (A - M) \<inter># N" using A(1) H by blast moreover have B': "B = (B - N) \<inter># M + B\<inter># N" using A(1) H[of B A N M] by (auto simp: ac_simps) moreover have "M = A \<inter># M + (B - N) \<inter># M" using H[of M N A B] BN_MA[symmetric] A(1) by (metis (no_types) diff_intersect_left_idem diff_union_cancelR multiset_inter_commute subset_mset.diff_add subset_mset.inf.cobounded1 union_commute) moreover have "N = (A - M) \<inter># N + B \<inter># N" by (metis A' assms(1) diff_union_cancelL inter_union_distrib_left inter_union_distrib_right mset_subset_eq_multiset_union_diff_commute subset_mset.inf.cobounded1 subset_mset.inf.commute) ultimately show P using A(2) by blast qed subsubsection \<open>Singleton multisets\<close> lemma mset_size_le1_cases[case_names empty singleton,consumes 1]: "\<lbrakk> size M \<le> Suc 0; M={#} \<Longrightarrow> P; !!m. M={#m#} \<Longrightarrow> P \<rbrakk> \<Longrightarrow> P" by (cases M) auto lemma diff_union_single_conv2: "a \<in># J \<Longrightarrow> J + I - {#a#} = (J - {#a#}) + I" by simp lemmas diff_union_single_convs = diff_union_single_conv diff_union_single_conv2 lemma mset_contains_eq: "(m \<in># M) = ({#m#}+(M-{#m#})=M)" using diff_single_trivial by fastforce subsubsection \<open>Pointwise ordering\<close> (*declare mset_le_trans[trans] Seems to be in there now. Why is this not done in Multiset.thy or order-class ? *) lemma mset_le_incr_right1: "a\<subseteq>#(b::'a multiset) \<Longrightarrow> a\<subseteq>#b+c" using mset_subset_eq_mono_add[of a b "{#}" c, simplified] . lemma mset_le_incr_right2: "a\<subseteq>#(b::'a multiset) \<Longrightarrow> a\<subseteq>#c+b" using mset_le_incr_right1 by (auto simp add: union_commute) lemmas mset_le_incr_right = mset_le_incr_right1 mset_le_incr_right2 lemma mset_le_decr_left1: "a+c\<subseteq>#(b::'a multiset) \<Longrightarrow> a\<subseteq>#b" using mset_le_incr_right1 mset_subset_eq_mono_add_right_cancel by blast lemma mset_le_decr_left2: "c+a\<subseteq>#(b::'a multiset) \<Longrightarrow> a\<subseteq>#b" using mset_le_decr_left1 by (auto simp add: union_ac) lemma mset_le_add_mset_decr_left1: "add_mset c a\<subseteq>#(b::'a multiset) \<Longrightarrow> a\<subseteq>#b" by (simp add: mset_subset_eq_insertD subset_mset.dual_order.strict_implies_order) lemma mset_le_add_mset_decr_left2: "add_mset c a\<subseteq>#(b::'a multiset) \<Longrightarrow> {#c#}\<subseteq>#b" by (simp add: mset_subset_eq_insertD subset_mset.dual_order.strict_implies_order) lemmas mset_le_decr_left = mset_le_decr_left1 mset_le_decr_left2 mset_le_add_mset_decr_left1 mset_le_add_mset_decr_left2 lemma mset_union_subset: "A+B \<subseteq># C \<Longrightarrow> A\<subseteq>#C \<and> B\<subseteq>#(C::'a multiset)" by (auto dest: mset_le_decr_left) lemma mset_le_add_mset: "add_mset x B \<subseteq># C \<Longrightarrow> {#x#}\<subseteq>#C \<and> B\<subseteq>#(C::'a multiset)" by (auto dest: mset_le_decr_left) lemma mset_le_subtract_left: "A+B \<subseteq># (X::'a multiset) \<Longrightarrow> B \<subseteq># X-A \<and> A\<subseteq>#X" by (auto dest: mset_le_subtract[of "A+B" "X" "A"] mset_union_subset) lemma mset_le_subtract_right: "A+B \<subseteq># (X::'a multiset) \<Longrightarrow> A \<subseteq># X-B \<and> B\<subseteq>#X" by (auto dest: mset_le_subtract[of "A+B" "X" "B"] mset_union_subset) lemma mset_le_subtract_add_mset_left: "add_mset x B \<subseteq># (X::'a multiset) \<Longrightarrow> B \<subseteq># X-{#x#} \<and> {#x#}\<subseteq>#X" by (auto dest: mset_le_subtract[of "add_mset x B" "X" "{#x#}"] mset_le_add_mset) lemma mset_le_subtract_add_mset_right: "add_mset x B \<subseteq># (X::'a multiset) \<Longrightarrow> {#x#} \<subseteq># X-B \<and> B\<subseteq>#X" by (auto dest: mset_le_subtract[of "add_mset x B" "X" "B"] mset_le_add_mset) lemma mset_le_addE: "\<lbrakk> xs \<subseteq># (ys::'a multiset); !!zs. ys=xs+zs \<Longrightarrow> P \<rbrakk> \<Longrightarrow> P" using mset_subset_eq_exists_conv by blast declare subset_mset.diff_add[simp, intro] lemma mset_2dist2_cases: assumes A: "{#a#}+{#b#} \<subseteq># A+B" assumes CASES: "{#a#}+{#b#} \<subseteq># A \<Longrightarrow> P" "{#a#}+{#b#} \<subseteq># B \<Longrightarrow> P" "\<lbrakk>a \<in># A; b \<in># B\<rbrakk> \<Longrightarrow> P" "\<lbrakk>a \<in># B; b \<in># A\<rbrakk> \<Longrightarrow> P" shows "P" proof - { assume C: "a \<in># A" "b \<in># A-{#a#}" with mset_subset_eq_mono_add[of "{#a#}" "{#a#}" "{#b#}" "A-{#a#}"] have "{#a#}+{#b#} \<subseteq># A" by auto } moreover { assume C: "a \<in># A" "\<not> (b \<in># A-{#a#})" with A have "b \<in># B" by (metis diff_union_single_conv2 mset_le_subtract_left mset_subset_eq_insertD mset_un_cases) } moreover { assume C: "\<not> (a \<in># A)" "b \<in># B-{#a#}" with A have "a \<in># B" by (auto dest: mset_subset_eqD) with C mset_subset_eq_mono_add[of "{#a#}" "{#a#}" "{#b#}" "B-{#a#}"] have "{#a#}+{#b#} \<subseteq># B" by auto } moreover { assume C: "\<not> (a \<in># A)" "\<not> (b \<in># B-{#a#})" with A have "a \<in># B \<and> b \<in># A" apply (intro conjI) apply (auto dest!: mset_subset_eq_insertD simp: insert_union_subset_iff; fail)[] by (metis mset_diff_cancel1elem mset_le_subtract_left multiset_diff_union_assoc single_subset_iff subset_eq_diff_conv) } ultimately show P using CASES by blast qed lemma mset_union_subset_s: "{#a#}+B \<subseteq># C \<Longrightarrow> a \<in># C \<and> B \<subseteq># C" by (drule mset_union_subset) simp (* TODO: Check which of these lemmas are already introduced by order-classes ! *) lemma mset_le_single_cases[consumes 1, case_names empty singleton]: "\<lbrakk>M\<subseteq>#{#a#}; M={#} \<Longrightarrow> P; M={#a#} \<Longrightarrow> P\<rbrakk> \<Longrightarrow> P" by (induct M) auto lemma mset_le_mono_add_single: "\<lbrakk>a \<in># ys; b \<in># ws\<rbrakk> \<Longrightarrow> {#a#} + {#b#} \<subseteq># ys + ws" by (meson mset_subset_eq_mono_add single_subset_iff) lemma mset_size1elem: "\<lbrakk>size P \<le> 1; q \<in># P\<rbrakk> \<Longrightarrow> P={#q#}" by (auto elim: mset_size_le1_cases) lemma mset_size2elem: "\<lbrakk>size P \<le> 2; {#q#}+{#q'#} \<subseteq># P\<rbrakk> \<Longrightarrow> P={#q#}+{#q'#}" by (auto elim: mset_le_addE) subsubsection \<open>Image under function\<close> notation image_mset (infixr "`#" 90) lemma mset_map_split_orig: "!!M1 M2. \<lbrakk>f `# P = M1+M2; !!P1 P2. \<lbrakk>P=P1+P2; f `# P1 = M1; f `# P2 = M2\<rbrakk> \<Longrightarrow> Q \<rbrakk> \<Longrightarrow> Q" by (induct P) (force elim!: mset_un_single_un_cases)+ lemma mset_map_id: "\<lbrakk>!!x. f (g x) = x\<rbrakk> \<Longrightarrow> f `# g `# X = X" by (induct X) auto text \<open>The following is a very specialized lemma. Intuitively, it splits the original multiset by a splitting of some pointwise supermultiset of its image. Application: This lemma came in handy when proving the correctness of a constraint system that collects at most k sized submultisets of the sets of spawned threads. \<close> lemma mset_map_split_orig_le: assumes A: "f `# P \<subseteq># M1+M2" and EX: "!!P1 P2. \<lbrakk>P=P1+P2; f `# P1 \<subseteq># M1; f `# P2 \<subseteq># M2\<rbrakk> \<Longrightarrow> Q" shows "Q" using A EX by (auto elim: mset_le_distrib mset_map_split_orig) subsection \<open>Lists\<close> lemma len_greater_imp_nonempty[simp]: "length l > x \<Longrightarrow> l\<noteq>[]" by auto lemma list_take_induct_tl2: "\<lbrakk>length xs = length ys; \<forall>n<length xs. P (ys ! n) (xs ! n)\<rbrakk> \<Longrightarrow> \<forall>n < length (tl xs). P ((tl ys) ! n) ((tl xs) ! n)" by (induct xs ys rule: list_induct2) auto lemma not_distinct_split_distinct: assumes "\<not> distinct xs" obtains y ys zs where "distinct ys" "y \<in> set ys" "xs = ys@[y]@zs" using assms proof (induct xs rule: rev_induct) case Nil thus ?case by simp next case (snoc x xs) thus ?case by (cases "distinct xs") auto qed lemma distinct_length_le: assumes d: "distinct ys" and eq: "set ys = set xs" shows "length ys \<le> length xs" proof - from d have "length ys = card (set ys)" by (simp add: distinct_card) also from eq List.card_set have "card (set ys) = length (remdups xs)" by simp also have "... \<le> length xs" by simp finally show ?thesis . qed lemma find_SomeD: "List.find P xs = Some x \<Longrightarrow> P x" "List.find P xs = Some x \<Longrightarrow> x\<in>set xs" by (auto simp add: find_Some_iff) lemma in_hd_or_tl_conv[simp]: "l\<noteq>[] \<Longrightarrow> x=hd l \<or> x\<in>set (tl l) \<longleftrightarrow> x\<in>set l" by (cases l) auto lemma length_dropWhile_takeWhile: assumes "x < length (dropWhile P xs)" shows "x + length (takeWhile P xs) < length xs" using assms by (induct xs) auto text \<open>Elim-version of @{thm neq_Nil_conv}.\<close> lemma neq_NilE: assumes "l\<noteq>[]" obtains x xs where "l=x#xs" using assms by (metis list.exhaust) lemma length_Suc_rev_conv: "length xs = Suc n \<longleftrightarrow> (\<exists>ys y. xs=ys@[y] \<and> length ys = n)" by (cases xs rule: rev_cases) auto subsubsection \<open>List Destructors\<close> lemma not_hd_in_tl: "x \<noteq> hd xs \<Longrightarrow> x \<in> set xs \<Longrightarrow> x \<in> set (tl xs)" by (induct xs) simp_all lemma distinct_hd_tl: "distinct xs \<Longrightarrow> x = hd xs \<Longrightarrow> x \<notin> set (tl (xs))" by (induct xs) simp_all lemma in_set_tlD: "x \<in> set (tl xs) \<Longrightarrow> x \<in> set xs" by (induct xs) simp_all lemma nth_tl: "xs \<noteq> [] \<Longrightarrow> tl xs ! n = xs ! Suc n" by (induct xs) simp_all lemma tl_subset: "xs \<noteq> [] \<Longrightarrow> set xs \<subseteq> A \<Longrightarrow> set (tl xs) \<subseteq> A" by (metis in_set_tlD rev_subsetD subsetI) lemma tl_last: "tl xs \<noteq> [] \<Longrightarrow> last xs = last (tl xs)" by (induct xs) simp_all lemma tl_obtain_elem: assumes "xs \<noteq> []" "tl xs = []" obtains e where "xs = [e]" using assms by (induct xs rule: list_nonempty_induct) simp_all lemma butlast_subset: "xs \<noteq> [] \<Longrightarrow> set xs \<subseteq> A \<Longrightarrow> set (butlast xs) \<subseteq> A" by (metis in_set_butlastD rev_subsetD subsetI) lemma butlast_rev_tl: "xs \<noteq> [] \<Longrightarrow> butlast (rev xs) = rev (tl xs)" by (induct xs rule: rev_induct) simp_all lemma hd_butlast: "length xs > 1 \<Longrightarrow> hd (butlast xs) = hd xs" by (induct xs) simp_all lemma butlast_upd_last_eq[simp]: "length l \<ge> 2 \<Longrightarrow> (butlast l) [ length l - 2 := x ] = take (length l - 2) l @ [x]" apply (case_tac l rule: rev_cases) apply simp apply simp apply (case_tac ys rule: rev_cases) apply simp apply simp done lemma distinct_butlast_swap[simp]: "distinct pq \<Longrightarrow> distinct (butlast (pq[i := last pq]))" apply (cases pq rule: rev_cases) apply (auto simp: list_update_append distinct_list_update split: nat.split) done subsubsection \<open>Splitting list according to structure of other list\<close> context begin private definition "SPLIT_ACCORDING m l \<equiv> length l = length m" private lemma SPLIT_ACCORDINGE: assumes "length m = length l" obtains "SPLIT_ACCORDING m l" unfolding SPLIT_ACCORDING_def using assms by auto private lemma SPLIT_ACCORDING_simp: "SPLIT_ACCORDING m (l1@l2) \<longleftrightarrow> (\<exists>m1 m2. m=m1@m2 \<and> SPLIT_ACCORDING m1 l1 \<and> SPLIT_ACCORDING m2 l2)" "SPLIT_ACCORDING m (x#l') \<longleftrightarrow> (\<exists>y m'. m=y#m' \<and> SPLIT_ACCORDING m' l')" apply (fastforce simp: SPLIT_ACCORDING_def intro: exI[where x = "take (length l1) m"] exI[where x = "drop (length l1) m"]) apply (cases m;auto simp: SPLIT_ACCORDING_def) done text \<open>Split structure of list @{term m} according to structure of list @{term l}.\<close> method split_list_according for m :: "'a list" and l :: "'b list" = (rule SPLIT_ACCORDINGE[of m l], (simp; fail), ( simp only: SPLIT_ACCORDING_simp, elim exE conjE, simp only: SPLIT_ACCORDING_def ) ) end subsubsection \<open>\<open>list_all2\<close>\<close> lemma list_all2_induct[consumes 1, case_names Nil Cons]: assumes "list_all2 P l l'" assumes "Q [] []" assumes "\<And>x x' ls ls'. \<lbrakk> P x x'; list_all2 P ls ls'; Q ls ls' \<rbrakk> \<Longrightarrow> Q (x#ls) (x'#ls')" shows "Q l l'" using list_all2_lengthD[OF assms(1)] assms apply (induct rule: list_induct2) apply auto done subsubsection \<open>Indexing\<close> lemma ran_nth_set_encoding_conv[simp]: "ran (\<lambda>i. if i<length l then Some (l!i) else None) = set l" apply safe apply (auto simp: ran_def split: if_split_asm) [] apply (auto simp: in_set_conv_nth intro: ranI) [] done lemma nth_image_indices[simp]: "(!) l ` {0..<length l} = set l" by (auto simp: in_set_conv_nth) lemma nth_update_invalid[simp]:"\<not>i<length l \<Longrightarrow> l[j:=x]!i = l!i" apply (induction l arbitrary: i j) apply (auto split: nat.splits) done lemma nth_list_update': "l[i:=x]!j = (if i=j \<and> i<length l then x else l!j)" by auto lemma last_take_nth_conv: "n \<le> length l \<Longrightarrow> n\<noteq>0 \<Longrightarrow> last (take n l) = l!(n - 1)" apply (induction l arbitrary: n) apply (auto simp: take_Cons split: nat.split) done lemma nth_append_first[simp]: "i<length l \<Longrightarrow> (l@l')!i = l!i" by (simp add: nth_append) lemma in_set_image_conv_nth: "f x \<in> f`set l \<longleftrightarrow> (\<exists>i<length l. f (l!i) = f x)" by (auto simp: in_set_conv_nth) (metis image_eqI nth_mem) lemma set_image_eq_pointwiseI: assumes "length l = length l'" assumes "\<And>i. i<length l \<Longrightarrow> f (l!i) = f (l'!i)" shows "f`set l = f`set l'" using assms by (fastforce simp: in_set_conv_nth in_set_image_conv_nth) lemma insert_swap_set_eq: "i<length l \<Longrightarrow> insert (l!i) (set (l[i:=x])) = insert x (set l)" by (auto simp: in_set_conv_nth nth_list_update split: if_split_asm) subsubsection \<open>Reverse lists\<close> lemma neq_Nil_revE: assumes "l\<noteq>[]" obtains ll e where "l = ll@[e]" using assms by (cases l rule: rev_cases) auto text \<open>Caution: Same order of case variables in snoc-case as @{thm [source] rev_exhaust}, the other way round than @{thm [source] rev_induct} !\<close> lemma length_compl_rev_induct[case_names Nil snoc]: "\<lbrakk>P []; !! l e . \<lbrakk>!! ll . length ll <= length l \<Longrightarrow> P ll\<rbrakk> \<Longrightarrow> P (l@[e])\<rbrakk> \<Longrightarrow> P l" apply(induct_tac l rule: length_induct) apply(case_tac "xs" rule: rev_cases) apply(auto) done lemma list_append_eq_Cons_cases[consumes 1]: "\<lbrakk>ys@zs = x#xs; \<lbrakk>ys=[]; zs=x#xs\<rbrakk> \<Longrightarrow> P; !!ys'. \<lbrakk> ys=x#ys'; ys'@zs=xs \<rbrakk> \<Longrightarrow> P \<rbrakk> \<Longrightarrow> P" by (auto iff add: append_eq_Cons_conv) lemma list_Cons_eq_append_cases[consumes 1]: "\<lbrakk>x#xs = ys@zs; \<lbrakk>ys=[]; zs=x#xs\<rbrakk> \<Longrightarrow> P; !!ys'. \<lbrakk> ys=x#ys'; ys'@zs=xs \<rbrakk> \<Longrightarrow> P \<rbrakk> \<Longrightarrow> P" by (auto iff add: Cons_eq_append_conv) lemma map_of_rev_distinct[simp]: "distinct (map fst m) \<Longrightarrow> map_of (rev m) = map_of m" apply (induct m) apply simp apply simp apply (subst map_add_comm) apply force apply simp done \<comment> \<open>Tail-recursive, generalized @{const rev}. May also be used for tail-recursively getting a list with all elements of the two operands, if the order does not matter, e.g. when implementing sets by lists.\<close> fun revg where "revg [] b = b" | "revg (a#as) b = revg as (a#b)" lemma revg_fun[simp]: "revg a b = rev a @ b" by (induct a arbitrary: b) auto lemma rev_split_conv[simp]: "l \<noteq> [] \<Longrightarrow> rev (tl l) @ [hd l] = rev l" by (induct l) simp_all lemma rev_butlast_is_tl_rev: "rev (butlast l) = tl (rev l)" by (induct l) auto lemma hd_last_singletonI: "\<lbrakk>xs \<noteq> []; hd xs = last xs; distinct xs\<rbrakk> \<Longrightarrow> xs = [hd xs]" by (induct xs rule: list_nonempty_induct) auto lemma last_filter: "\<lbrakk>xs \<noteq> []; P (last xs)\<rbrakk> \<Longrightarrow> last (filter P xs) = last xs" by (induct xs rule: rev_nonempty_induct) simp_all (* As the following two rules are similar in nature to list_induct2', they are named accordingly. *) lemma rev_induct2' [case_names empty snocl snocr snoclr]: assumes empty: "P [] []" and snocl: "\<And>x xs. P (xs@[x]) []" and snocr: "\<And>y ys. P [] (ys@[y])" and snoclr: "\<And>x xs y ys. P xs ys \<Longrightarrow> P (xs@[x]) (ys@[y])" shows "P xs ys" proof (induct xs arbitrary: ys rule: rev_induct) case Nil thus ?case using empty snocr by (cases ys rule: rev_exhaust) simp_all next case snoc thus ?case using snocl snoclr by (cases ys rule: rev_exhaust) simp_all qed subsubsection "Folding" text "Ugly lemma about foldl over associative operator with left and right neutral element" lemma foldl_A1_eq: "!!i. \<lbrakk> !! e. f n e = e; !! e. f e n = e; !!a b c. f a (f b c) = f (f a b) c \<rbrakk> \<Longrightarrow> foldl f i ww = f i (foldl f n ww)" proof (induct ww) case Nil thus ?case by simp next case (Cons a ww i) note IHP[simplified]=this have "foldl f i (a # ww) = foldl f (f i a) ww" by simp also from IHP have "\<dots> = f (f i a) (foldl f n ww)" by blast also from IHP(4) have "\<dots> = f i (f a (foldl f n ww))" by simp also from IHP(1)[OF IHP(2,3,4), where i=a] have "\<dots> = f i (foldl f a ww)" by simp also from IHP(2)[of a] have "\<dots> = f i (foldl f (f n a) ww)" by simp also have "\<dots> = f i (foldl f n (a#ww))" by simp finally show ?case . qed lemmas foldl_conc_empty_eq = foldl_A1_eq[of "(@)" "[]", simplified] lemmas foldl_un_empty_eq = foldl_A1_eq[of "(\<union>)" "{}", simplified, OF Un_assoc[symmetric]] lemma foldl_set: "foldl (\<union>) {} l = \<Union>{x. x\<in>set l}" apply (induct l) apply simp_all apply (subst foldl_un_empty_eq) apply auto done lemma (in monoid_mult) foldl_absorb1: "x*foldl (*) 1 zs = foldl (*) x zs" apply (rule sym) apply (rule foldl_A1_eq) apply (auto simp add: mult.assoc) done text \<open>Towards an invariant rule for foldl\<close> lemma foldl_rule_aux: fixes I :: "'\<sigma> \<Rightarrow> 'a list \<Rightarrow> bool" assumes initial: "I \<sigma>0 l0" assumes step: "!!l1 l2 x \<sigma>. \<lbrakk> l0=l1@x#l2; I \<sigma> (x#l2) \<rbrakk> \<Longrightarrow> I (f \<sigma> x) l2" shows "I (foldl f \<sigma>0 l0) []" using initial step apply (induct l0 arbitrary: \<sigma>0) apply auto done lemma foldl_rule_aux_P: fixes I :: "'\<sigma> \<Rightarrow> 'a list \<Rightarrow> bool" assumes initial: "I \<sigma>0 l0" assumes step: "!!l1 l2 x \<sigma>. \<lbrakk> l0=l1@x#l2; I \<sigma> (x#l2) \<rbrakk> \<Longrightarrow> I (f \<sigma> x) l2" assumes final: "!!\<sigma>. I \<sigma> [] \<Longrightarrow> P \<sigma>" shows "P (foldl f \<sigma>0 l0)" using foldl_rule_aux[of I \<sigma>0 l0, OF initial, OF step] final by simp lemma foldl_rule: fixes I :: "'\<sigma> \<Rightarrow> 'a list \<Rightarrow> 'a list \<Rightarrow> bool" assumes initial: "I \<sigma>0 [] l0" assumes step: "!!l1 l2 x \<sigma>. \<lbrakk> l0=l1@x#l2; I \<sigma> l1 (x#l2) \<rbrakk> \<Longrightarrow> I (f \<sigma> x) (l1@[x]) l2" shows "I (foldl f \<sigma>0 l0) l0 []" using initial step apply (rule_tac I="\<lambda>\<sigma> lr. \<exists>ll. l0=ll@lr \<and> I \<sigma> ll lr" in foldl_rule_aux_P) apply auto done text \<open> Invariant rule for foldl. The invariant is parameterized with the state, the list of items that have already been processed and the list of items that still have to be processed. \<close> lemma foldl_rule_P: fixes I :: "'\<sigma> \<Rightarrow> 'a list \<Rightarrow> 'a list \<Rightarrow> bool" \<comment> \<open>The invariant holds for the initial state, no items processed yet and all items to be processed:\<close> assumes initial: "I \<sigma>0 [] l0" \<comment> \<open>The invariant remains valid if one item from the list is processed\<close> assumes step: "!!l1 l2 x \<sigma>. \<lbrakk> l0=l1@x#l2; I \<sigma> l1 (x#l2) \<rbrakk> \<Longrightarrow> I (f \<sigma> x) (l1@[x]) l2" \<comment> \<open>The proposition follows from the invariant in the final state, i.e. all items processed and nothing to be processed\<close> assumes final: "!!\<sigma>. I \<sigma> l0 [] \<Longrightarrow> P \<sigma>" shows "P (foldl f \<sigma>0 l0)" using foldl_rule[of I, OF initial step] by (simp add: final) text \<open>Invariant reasoning over @{const foldl} for distinct lists. Invariant rule makes no assumptions about ordering.\<close> lemma distinct_foldl_invar: "\<lbrakk> distinct S; I (set S) \<sigma>0; \<And>x it \<sigma>. \<lbrakk>x \<in> it; it \<subseteq> set S; I it \<sigma>\<rbrakk> \<Longrightarrow> I (it - {x}) (f \<sigma> x) \<rbrakk> \<Longrightarrow> I {} (foldl f \<sigma>0 S)" proof (induct S arbitrary: \<sigma>0) case Nil thus ?case by auto next case (Cons x S) note [simp] = Cons.prems(1)[simplified] show ?case apply simp apply (rule Cons.hyps) proof - from Cons.prems(1) show "distinct S" by simp from Cons.prems(3)[of x "set (x#S)", simplified, OF Cons.prems(2)[simplified]] show "I (set S) (f \<sigma>0 x)" . fix xx it \<sigma> assume A: "xx\<in>it" "it \<subseteq> set S" "I it \<sigma>" show "I (it - {xx}) (f \<sigma> xx)" using A(2) apply (rule_tac Cons.prems(3)) apply (simp_all add: A(1,3)) apply blast done qed qed lemma foldl_length_aux: "foldl (\<lambda>i x. Suc i) a l = a + length l" by (induct l arbitrary: a) auto lemmas foldl_length[simp] = foldl_length_aux[where a=0, simplified] lemma foldr_length_aux: "foldr (\<lambda>x i. Suc i) l a = a + length l" by (induct l arbitrary: a rule: rev_induct) auto lemmas foldr_length[simp] = foldr_length_aux[where a=0, simplified] context comp_fun_commute begin lemma foldl_f_commute: "f a (foldl (\<lambda>a b. f b a) b xs) = foldl (\<lambda>a b. f b a) (f a b) xs" by(induct xs arbitrary: b)(simp_all add: fun_left_comm) lemma foldr_conv_foldl: "foldr f xs a = foldl (\<lambda>a b. f b a) a xs" by(induct xs arbitrary: a)(simp_all add: foldl_f_commute) end lemma filter_conv_foldr: "filter P xs = foldr (\<lambda>x xs. if P x then x # xs else xs) xs []" by(induct xs) simp_all lemma foldr_Cons: "foldr Cons xs [] = xs" by(induct xs) simp_all lemma foldr_snd_zip: "length xs \<ge> length ys \<Longrightarrow> foldr (\<lambda>(x, y). f y) (zip xs ys) b = foldr f ys b" proof(induct ys arbitrary: xs) case (Cons y ys) thus ?case by(cases xs) simp_all qed simp lemma foldl_snd_zip: "length xs \<ge> length ys \<Longrightarrow> foldl (\<lambda>b (x, y). f b y) b (zip xs ys) = foldl f b ys" proof(induct ys arbitrary: xs b) case (Cons y ys) thus ?case by(cases xs) simp_all qed simp lemma foldl_foldl_conv_concat: "foldl (foldl f) a xs = foldl f a (concat xs)" by(induct xs arbitrary: a) simp_all lemma foldl_list_update: "n < length xs \<Longrightarrow> foldl f a (xs[n := x]) = foldl f (f (foldl f a (take n xs)) x) (drop (Suc n) xs)" by(simp add: upd_conv_take_nth_drop) lemma map_by_foldl: fixes l :: "'a list" and f :: "'a \<Rightarrow> 'b" shows "foldl (\<lambda>l x. l@[f x]) [] l = map f l" proof - { fix l' have "foldl (\<lambda>l x. l@[f x]) l' l = l'@map f l" by (induct l arbitrary: l') auto } thus ?thesis by simp qed subsubsection \<open>Sorting\<close> lemma sorted_in_between: assumes A: "0\<le>i" "i<j" "j<length l" assumes S: "sorted l" assumes E: "l!i \<le> x" "x<l!j" obtains k where "i\<le>k" and "k<j" and "l!k\<le>x" and "x<l!(k+1)" proof - from A E have "\<exists>k. i\<le>k \<and> k<j \<and> l!k\<le>x \<and> x<l!(k+1)" proof (induct "j-i" arbitrary: i j) case (Suc d) show ?case proof (cases "l!(i+1) \<le> x") case True from True Suc.hyps have "d = j - (i + 1)" by simp moreover from True have "i+1 < j" by (metis Suc.prems Suc_eq_plus1 Suc_lessI not_less) moreover from True have "0\<le>i+1" by simp ultimately obtain k where "i+1\<le>k" "k<j" "l!k \<le> x" "x<l!(k+1)" using Suc.hyps(1)[of j "i+1"] Suc.prems True by auto thus ?thesis by (auto dest: Suc_leD) next case False show ?thesis proof (cases "x<(l!(j - 1))") case True from True Suc.hyps have "d = j - (i + 1)" by simp moreover from True Suc.prems have "i < j - 1" by (metis Suc_eq_plus1 Suc_lessI diff_Suc_1 less_diff_conv not_le) moreover from True Suc.prems have "j - 1 < length l" by simp ultimately obtain k where "i\<le>k" "k<j - 1" "l!k \<le> x" "x<l!(k+1)" using Suc.hyps(1)[of "j - 1" i] Suc.prems True by auto thus ?thesis by (auto dest: Suc_leD) next case False thus ?thesis using Suc apply clarsimp by (metis Suc_leI add_0_iff add_diff_inverse diff_Suc_1 le_add2 lessI not0_implies_Suc not_less) qed qed qed simp thus ?thesis by (blast intro: that) qed lemma sorted_hd_last: "\<lbrakk>sorted l; l\<noteq>[]\<rbrakk> \<Longrightarrow> hd l \<le> last l" by (metis eq_iff hd_Cons_tl last_in_set not_hd_in_tl sorted_wrt.simps(2)) lemma (in linorder) sorted_hd_min: "\<lbrakk>xs \<noteq> []; sorted xs\<rbrakk> \<Longrightarrow> \<forall>x \<in> set xs. hd xs \<le> x" by (induct xs, auto) lemma sorted_append_bigger: "\<lbrakk>sorted xs; \<forall>x \<in> set xs. x \<le> y\<rbrakk> \<Longrightarrow> sorted (xs @ [y])" proof (induct xs) case Nil then show ?case by simp next case (Cons x xs) then have s: "sorted xs" by (cases xs) simp_all from Cons have a: "\<forall>x\<in>set xs. x \<le> y" by simp from Cons(1)[OF s a] Cons(2-) show ?case by (cases xs) simp_all qed lemma sorted_filter': "sorted l \<Longrightarrow> sorted (filter P l)" using sorted_filter[where f=id, simplified] . subsubsection \<open>Map\<close> (* List.thy has: declare map_eq_Cons_D [dest!] Cons_eq_map_D [dest!] *) lemma map_eq_consE: "\<lbrakk>map f ls = fa#fl; !!a l. \<lbrakk> ls=a#l; f a=fa; map f l = fl \<rbrakk> \<Longrightarrow> P\<rbrakk> \<Longrightarrow> P" by auto lemma map_fst_mk_snd[simp]: "map fst (map (\<lambda>x. (x,k)) l) = l" by (induct l) auto lemma map_snd_mk_fst[simp]: "map snd (map (\<lambda>x. (k,x)) l) = l" by (induct l) auto lemma map_fst_mk_fst[simp]: "map fst (map (\<lambda>x. (k,x)) l) = replicate (length l) k" by (induct l) auto lemma map_snd_mk_snd[simp]: "map snd (map (\<lambda>x. (x,k)) l) = replicate (length l) k" by (induct l) auto lemma map_zip1: "map (\<lambda>x. (x,k)) l = zip l (replicate (length l) k)" by (induct l) auto lemma map_zip2: "map (\<lambda>x. (k,x)) l = zip (replicate (length l) k) l" by (induct l) auto lemmas map_zip=map_zip1 map_zip2 (* TODO/FIXME: hope nobody changes nth to be underdefined! *) lemma map_eq_nth_eq: assumes A: "map f l = map f l'" shows "f (l!i) = f (l'!i)" proof - from A have "length l = length l'" by (metis length_map) thus ?thesis using A apply (induct arbitrary: i rule: list_induct2) apply simp apply (simp add: nth_def split: nat.split) done qed lemma map_upd_eq: "\<lbrakk>i<length l \<Longrightarrow> f (l!i) = f x\<rbrakk> \<Longrightarrow> map f (l[i:=x]) = map f l" by (metis list_update_beyond list_update_id map_update not_le_imp_less) lemma inj_map_inv_f [simp]: "inj f \<Longrightarrow> map (inv f) (map f l) = l" by (simp) lemma inj_on_map_the: "\<lbrakk>D \<subseteq> dom m; inj_on m D\<rbrakk> \<Longrightarrow> inj_on (the\<circ>m) D" apply (rule inj_onI) apply simp apply (case_tac "m x") apply (case_tac "m y") apply (auto intro: inj_onD) [1] apply (auto intro: inj_onD) [1] apply (case_tac "m y") apply (auto intro: inj_onD) [1] apply simp apply (rule inj_onD) apply assumption apply auto done lemma map_consI: "w=map f ww \<Longrightarrow> f a#w = map f (a#ww)" "w@l=map f ww@l \<Longrightarrow> f a#w@l = map f (a#ww)@l" by auto lemma restrict_map_subset_eq: fixes R shows "\<lbrakk>m |` R = m'; R'\<subseteq>R\<rbrakk> \<Longrightarrow> m|` R' = m' |` R'" by (auto simp add: Int_absorb1) lemma restrict_map_self[simp]: "m |` dom m = m" apply (rule ext) apply (case_tac "m x") apply (auto simp add: restrict_map_def) done lemma restrict_map_UNIV[simp]: "f |` UNIV = f" by (auto simp add: restrict_map_def) lemma restrict_map_inv[simp]: "f |` (- dom f) = Map.empty" by (auto simp add: restrict_map_def intro: ext) lemma restrict_map_upd: "(f |` S)(k \<mapsto> v) = f(k\<mapsto>v) |` (insert k S)" by (auto simp add: restrict_map_def intro: ext) lemma map_upd_eq_restrict: "m (x:=None) = m |` (-{x})" by (auto intro: ext) declare Map.finite_dom_map_of [simp, intro!] lemma restrict_map_eq : "((m |` A) k = None) \<longleftrightarrow> (k \<notin> dom m \<inter> A)" "((m |` A) k = Some v) \<longleftrightarrow> (m k = Some v \<and> k \<in> A)" unfolding restrict_map_def by (simp_all add: dom_def) definition "rel_of m P == {(k,v). m k = Some v \<and> P (k, v)}" lemma rel_of_empty[simp]: "rel_of Map.empty P = {}" by (auto simp add: rel_of_def) lemma remove1_tl: "xs \<noteq> [] \<Longrightarrow> remove1 (hd xs) xs = tl xs" by (cases xs) auto lemma set_oo_map_alt: "(set \<circ>\<circ> map) f = (\<lambda>l. f ` set l)" by auto subsubsection "Filter and Revert" primrec filter_rev_aux where "filter_rev_aux a P [] = a" | "filter_rev_aux a P (x#xs) = ( if P x then filter_rev_aux (x#a) P xs else filter_rev_aux a P xs)" lemma filter_rev_aux_alt: "filter_rev_aux a P l = filter P (rev l) @ a" by (induct l arbitrary: a) auto definition "filter_rev == filter_rev_aux []" lemma filter_rev_alt: "filter_rev P l = filter P (rev l)" unfolding filter_rev_def by (simp add: filter_rev_aux_alt) definition "remove_rev x == filter_rev (Not o (=) x)" lemma remove_rev_alt_def : "remove_rev x xs = (filter (\<lambda>y. y \<noteq> x) (rev xs))" unfolding remove_rev_def apply (simp add: filter_rev_alt comp_def) by metis subsubsection "zip" declare zip_map_fst_snd[simp] lemma pair_list_split: "\<lbrakk> !!l1 l2. \<lbrakk> l = zip l1 l2; length l1=length l2; length l=length l2 \<rbrakk> \<Longrightarrow> P \<rbrakk> \<Longrightarrow> P" proof (induct l arbitrary: P) case Nil thus ?case by auto next case (Cons a l) from Cons.hyps obtain l1 l2 where IHAPP: "l=zip l1 l2" "length l1 = length l2" "length l=length l2" . obtain a1 a2 where [simp]: "a=(a1,a2)" by (cases a) auto from IHAPP have "a#l = zip (a1#l1) (a2#l2)" "length (a1#l1) = length (a2#l2)" "length (a#l) = length (a2#l2)" by (simp_all only:) (simp_all (no_asm_use)) with Cons.prems show ?case by blast qed lemma set_zip_cart: "x\<in>set (zip l l') \<Longrightarrow> x\<in>set l \<times> set l'" by (auto simp add: set_zip) lemma map_prod_fun_zip: "map (\<lambda>(x, y). (f x, g y)) (zip xs ys) = zip (map f xs) (map g ys)" proof(induct xs arbitrary: ys) case Nil thus ?case by simp next case (Cons x xs) thus ?case by(cases ys) simp_all qed subsubsection \<open>Generalized Zip\<close> text \<open>Zip two lists element-wise, where the combination of two elements is specified by a function. Note that this function is underdefined for lists of different length.\<close> fun zipf :: "('a\<Rightarrow>'b\<Rightarrow>'c) \<Rightarrow> 'a list \<Rightarrow> 'b list \<Rightarrow> 'c list" where "zipf f [] [] = []" | "zipf f (a#as) (b#bs) = f a b # zipf f as bs" lemma zipf_zip: "\<lbrakk>length l1 = length l2\<rbrakk> \<Longrightarrow> zipf Pair l1 l2 = zip l1 l2" apply (induct l1 arbitrary: l2) apply auto apply (case_tac l2) apply auto done \<comment> \<open>All quantification over zipped lists\<close> fun list_all_zip where "list_all_zip P [] [] \<longleftrightarrow> True" | "list_all_zip P (a#as) (b#bs) \<longleftrightarrow> P a b \<and> list_all_zip P as bs" | "list_all_zip P _ _ \<longleftrightarrow> False" lemma list_all_zip_alt: "list_all_zip P as bs \<longleftrightarrow> length as = length bs \<and> (\<forall>i<length as. P (as!i) (bs!i))" apply (induct P\<equiv>P as bs rule: list_all_zip.induct) apply auto apply (case_tac i) apply auto done lemma list_all_zip_map1: "list_all_zip P (List.map f as) bs \<longleftrightarrow> list_all_zip (\<lambda>a b. P (f a) b) as bs" apply (induct as arbitrary: bs) apply (case_tac bs) apply auto [2] apply (case_tac bs) apply auto [2] done lemma list_all_zip_map2: "list_all_zip P as (List.map f bs) \<longleftrightarrow> list_all_zip (\<lambda>a b. P a (f b)) as bs" apply (induct as arbitrary: bs) apply (case_tac bs) apply auto [2] apply (case_tac bs) apply auto [2] done declare list_all_zip_alt[mono] lemma lazI[intro?]: "\<lbrakk> length a = length b; !!i. i<length b \<Longrightarrow> P (a!i) (b!i) \<rbrakk> \<Longrightarrow> list_all_zip P a b" by (auto simp add: list_all_zip_alt) lemma laz_conj[simp]: "list_all_zip (\<lambda>x y. P x y \<and> Q x y) a b \<longleftrightarrow> list_all_zip P a b \<and> list_all_zip Q a b" by (auto simp add: list_all_zip_alt) lemma laz_len: "list_all_zip P a b \<Longrightarrow> length a = length b" by (simp add: list_all_zip_alt) lemma laz_eq: "list_all_zip (=) a b \<longleftrightarrow> a=b" apply (induct a arbitrary: b) apply (case_tac b) apply simp apply simp apply (case_tac b) apply simp apply simp done lemma laz_swap_ex: assumes A: "list_all_zip (\<lambda>a b. \<exists>c. P a b c) A B" obtains C where "list_all_zip (\<lambda>a c. \<exists>b. P a b c) A C" "list_all_zip (\<lambda>b c. \<exists>a. P a b c) B C" proof - from A have [simp]: "length A = length B" and IC: "\<forall>i<length B. \<exists>ci. P (A!i) (B!i) ci" by (auto simp add: list_all_zip_alt) from obtain_list_from_elements[OF IC] obtain C where "length C = length B" "\<forall>i<length B. P (A!i) (B!i) (C!i)" . thus ?thesis by (rule_tac that) (auto simp add: list_all_zip_alt) qed lemma laz_weak_Pa[simp]: "list_all_zip (\<lambda>a b. P a) A B \<longleftrightarrow> (length A = length B) \<and> (\<forall>a\<in>set A. P a)" by (auto simp add: list_all_zip_alt set_conv_nth) lemma laz_weak_Pb[simp]: "list_all_zip (\<lambda>a b. P b) A B \<longleftrightarrow> (length A = length B) \<and> (\<forall>b\<in>set B. P b)" by (force simp add: list_all_zip_alt set_conv_nth) subsubsection "Collecting Sets over Lists" definition "list_collect_set f l == \<Union>{ f a | a. a\<in>set l }" lemma list_collect_set_simps[simp]: "list_collect_set f [] = {}" "list_collect_set f [a] = f a" "list_collect_set f (a#l) = f a \<union> list_collect_set f l" "list_collect_set f (l@l') = list_collect_set f l \<union> list_collect_set f l'" by (unfold list_collect_set_def) auto lemma list_collect_set_map_simps[simp]: "list_collect_set f (map x []) = {}" "list_collect_set f (map x [a]) = f (x a)" "list_collect_set f (map x (a#l)) = f (x a) \<union> list_collect_set f (map x l)" "list_collect_set f (map x (l@l')) = list_collect_set f (map x l) \<union> list_collect_set f (map x l')" by simp_all lemma list_collect_set_alt: "list_collect_set f l = \<Union>{ f (l!i) | i. i<length l }" apply (induct l) apply simp apply safe apply auto apply (rule_tac x="f (l!i)" in exI) apply simp apply (rule_tac x="Suc i" in exI) apply simp apply (case_tac i) apply auto done lemma list_collect_set_as_map: "list_collect_set f l = \<Union>(set (map f l))" by (unfold list_collect_set_def) auto subsubsection \<open>Sorted List with arbitrary Relations\<close> lemma (in linorder) sorted_wrt_rev_linord [simp] : "sorted_wrt (\<ge>) l \<longleftrightarrow> sorted (rev l)" by (simp add: sorted_wrt_rev) lemma (in linorder) sorted_wrt_map_linord [simp] : "sorted_wrt (\<lambda>(x::'a \<times> 'b) y. fst x \<le> fst y) l \<longleftrightarrow> sorted (map fst l)" by (simp add: sorted_wrt_map) lemma (in linorder) sorted_wrt_map_rev_linord [simp] : "sorted_wrt (\<lambda>(x::'a \<times> 'b) y. fst x \<ge> fst y) l \<longleftrightarrow> sorted (rev (map fst l))" by (induct l) (auto simp add: sorted_append) subsubsection \<open>Take and Drop\<close> lemma take_update[simp]: "take n (l[i:=x]) = (take n l)[i:=x]" apply (induct l arbitrary: n i) apply (auto split: nat.split) apply (case_tac n) apply simp_all apply (case_tac n) apply simp_all done lemma take_update_last: "length list>n \<Longrightarrow> (take (Suc n) list) [n:=x] = take n list @ [x]" by (induct list arbitrary: n) (auto split: nat.split) lemma drop_upd_irrelevant: "m < n \<Longrightarrow> drop n (l[m:=x]) = drop n l" apply (induct n arbitrary: l m) apply simp apply (case_tac l) apply (auto split: nat.split) done lemma set_drop_conv: "set (drop n l) = { l!i | i. n\<le>i \<and> i < length l }" (is "?L=?R") proof (intro equalityI subsetI) fix x assume "x\<in>?L" then obtain i where L: "i<length l - n" and X: "x = drop n l!i" by (auto simp add: in_set_conv_nth) note X also have "\<dots> = l!(n+i)" using L by simp finally show "x\<in>?R" using L by auto next fix x assume "x\<in>?R" then obtain i where L: "n\<le>i" "i<length l" and X: "x=l!i" by blast note X moreover have "l!i = drop n l ! (i - n)" and "(i-n) < length l - n" using L by (auto) ultimately show "x\<in>?L" by (auto simp add: in_set_conv_nth) qed lemma in_set_drop_conv_nth: "x\<in>set (drop n l) \<longleftrightarrow> (\<exists>i. n\<le>i \<and> i<length l \<and> x = l!i)" apply (clarsimp simp: in_set_conv_nth) apply safe apply simp apply (metis le_add2 less_diff_conv add.commute) apply (rule_tac x="i-n" in exI) apply auto [] done lemma Union_take_drop_id: "\<Union>(set (drop n l)) \<union> \<Union>(set (take n l)) = \<Union>(set l)" by (metis Union_Un_distrib append_take_drop_id set_union_code sup_commute) lemma Un_set_drop_extend: "\<lbrakk>j\<ge>Suc 0; j < length l\<rbrakk> \<Longrightarrow> l ! (j - Suc 0) \<union> \<Union>(set (drop j l)) = \<Union>(set (drop (j - Suc 0) l))" apply safe apply simp_all apply (metis diff_Suc_Suc diff_zero gr0_implies_Suc in_set_drop_conv_nth le_refl less_eq_Suc_le order.strict_iff_order) apply (metis Nat.diff_le_self set_drop_subset_set_drop subset_code(1)) by (metis diff_Suc_Suc gr0_implies_Suc in_set_drop_conv_nth less_eq_Suc_le order.strict_iff_order minus_nat.diff_0) lemma drop_take_drop_unsplit: "i\<le>j \<Longrightarrow> drop i (take j l) @ drop j l = drop i l" proof - assume "i \<le> j" then obtain skf where "i + skf = j" by (metis le_iff_add) thus "drop i (take j l) @ drop j l = drop i l" by (metis append_take_drop_id diff_add_inverse drop_drop drop_take add.commute) qed lemma drop_last_conv[simp]: "l\<noteq>[] \<Longrightarrow> drop (length l - Suc 0) l = [last l]" by (cases l rule: rev_cases) auto lemma take_butlast_conv[simp]: "take (length l - Suc 0) l = butlast l" by (cases l rule: rev_cases) auto lemma drop_takeWhile: assumes "i\<le>length (takeWhile P l)" shows "drop i (takeWhile P l) = takeWhile P (drop i l)" using assms proof (induction l arbitrary: i) case Nil thus ?case by auto next case (Cons x l) thus ?case by (cases i) auto qed lemma less_length_takeWhile_conv: "i < length (takeWhile P l) \<longleftrightarrow> (i<length l \<and> (\<forall>j\<le>i. P (l!j)))" apply safe subgoal using length_takeWhile_le less_le_trans by blast subgoal by (metis dual_order.strict_trans2 nth_mem set_takeWhileD takeWhile_nth) subgoal by (meson less_le_trans not_le_imp_less nth_length_takeWhile) done lemma eq_len_takeWhile_conv: "i=length (takeWhile P l) \<longleftrightarrow> i\<le>length l \<and> (\<forall>j<i. P (l!j)) \<and> (i<length l \<longrightarrow> \<not>P (l!i))" apply safe subgoal using length_takeWhile_le less_le_trans by blast subgoal by (auto simp: less_length_takeWhile_conv) subgoal using nth_length_takeWhile by blast subgoal by (metis length_takeWhile_le nth_length_takeWhile order.order_iff_strict) subgoal by (metis dual_order.strict_trans2 leI less_length_takeWhile_conv linorder_neqE_nat nth_length_takeWhile) done subsubsection \<open>Up-to\<close> lemma upt_eq_append_conv: "i\<le>j \<Longrightarrow> [i..<j] = xs@ys \<longleftrightarrow> (\<exists>k. i\<le>k \<and> k\<le>j \<and> [i..<k] = xs \<and> [k..<j] = ys)" proof (rule iffI) assume "[i..<j] = xs @ ys" and "i\<le>j" thus "\<exists>k\<ge>i. k \<le> j \<and> [i..<k] = xs \<and> [k..<j] = ys" apply (induction xs arbitrary: i) apply (auto; fail) apply (clarsimp simp: upt_eq_Cons_conv) by (meson Suc_le_eq less_imp_le_nat) qed auto lemma map_nth_upt_drop_take_conv: "N \<le> length l \<Longrightarrow> map (nth l) [M..<N] = drop M (take N l)" by (induction N) (auto simp: take_Suc_conv_app_nth) lemma upt_eq_lel_conv: "[l..<h] = is1@i#is2 \<longleftrightarrow> is1 = [l..<i] \<and> is2 = [Suc i..<h] \<and> l\<le>i \<and> i<h" apply (rule) subgoal apply (induction is1 arbitrary: l) apply (auto simp: upt_eq_Cons_conv) [] apply (clarsimp simp: upt_eq_Cons_conv) using Suc_le_eq upt_rec by auto subgoal by (auto simp: upt_conv_Cons[symmetric]) done lemma map_add_upt': "map (\<lambda>i. i + ofs) [a..<b] = [a+ofs..<b + ofs]" by (induct b) simp_all subsubsection \<open>Last and butlast\<close> lemma butlast_upt: "butlast [m..<n] = [m..<n - 1]" apply (cases "m<n") apply (cases n) apply simp apply simp apply simp done (*lemma butlast_upt: "n<m \<Longrightarrow> butlast [n..<m] = [n..<m - 1]" apply (cases "[n..<m]" rule: rev_cases) apply simp apply (cases m) apply simp apply simp done*) lemma butlast_update': "(butlast l) [i:=x] = butlast (l[i:=x])" by (metis butlast_conv_take butlast_list_update length_butlast take_update) lemma take_minus_one_conv_butlast: "n\<le>length l \<Longrightarrow> take (n - Suc 0) l = butlast (take n l)" by (simp add: butlast_take) lemma butlast_eq_cons_conv: "butlast l = x#xs \<longleftrightarrow> (\<exists>xl. l=x#xs@[xl])" by (metis Cons_eq_appendI append_butlast_last_id butlast.simps butlast_snoc eq_Nil_appendI) lemma butlast_eq_consE: assumes "butlast l = x#xs" obtains xl where "l=x#xs@[xl]" using assms by (auto simp: butlast_eq_cons_conv) lemma drop_eq_ConsD: "drop n xs = x # xs' \<Longrightarrow> drop (Suc n) xs = xs'" by(induct xs arbitrary: n)(simp_all add: drop_Cons split: nat.split_asm) subsubsection \<open>List Slices\<close> text \<open>Based on Lars Hupel's code.\<close> definition slice :: "nat \<Rightarrow> nat \<Rightarrow> 'a list \<Rightarrow> 'a list" where "slice from to list = take (to - from) (drop from list)" lemma slice_len[simp]: "\<lbrakk> from \<le> to; to \<le> length xs \<rbrakk> \<Longrightarrow> length (slice from to xs) = to - from" unfolding slice_def by simp lemma slice_head: "\<lbrakk> from < to; to \<le> length xs \<rbrakk> \<Longrightarrow> hd (slice from to xs) = xs ! from" unfolding slice_def proof - assume a1: "from < to" assume "to \<le> length xs" then have "\<And>n. to - (to - n) \<le> length (take to xs)" by (metis (no_types) slice_def diff_le_self drop_take length_drop slice_len) then show "hd (take (to - from) (drop from xs)) = xs ! from" using a1 by (metis diff_diff_cancel drop_take hd_drop_conv_nth leI le_antisym less_or_eq_imp_le nth_take) qed lemma slice_eq_bounds_empty[simp]: "slice i i xs = []" unfolding slice_def by auto lemma slice_nth: "\<lbrakk> from < to; to \<le> length xs; i < to - from \<rbrakk> \<Longrightarrow> slice from to xs ! i = xs ! (from + i)" unfolding slice_def by (induction "to - from" arbitrary: "from" to i) simp+ lemma slice_prepend: "\<lbrakk> i \<le> k; k \<le> length xs \<rbrakk> \<Longrightarrow> let p = length ys in slice i k xs = slice (i + p) (k + p) (ys @ xs)" unfolding slice_def Let_def by force lemma slice_Nil[simp]: "slice begin end [] = []" unfolding slice_def by auto lemma slice_Cons: "slice begin end (x#xs) = (if begin=0 \<and> end>0 then x#slice begin (end-1) xs else slice (begin - 1) (end - 1) xs)" unfolding slice_def by (auto simp: take_Cons' drop_Cons') lemma slice_complete[simp]: "slice 0 (length xs) xs = xs" unfolding slice_def by simp subsubsection \<open>Miscellaneous\<close> lemma length_compl_induct[case_names Nil Cons]: "\<lbrakk>P []; !! e l . \<lbrakk>!! ll . length ll <= length l \<Longrightarrow> P ll\<rbrakk> \<Longrightarrow> P (e#l)\<rbrakk> \<Longrightarrow> P l" apply(induct_tac l rule: length_induct) apply(case_tac "xs") apply(auto) done lemma in_set_list_format: "\<lbrakk> e\<in>set l; !!l1 l2. l=l1@e#l2 \<Longrightarrow> P \<rbrakk> \<Longrightarrow> P" proof (induct l arbitrary: P) case Nil thus ?case by auto next case (Cons a l) show ?case proof (cases "a=e") case True with Cons show ?thesis by force next case False with Cons.prems(1) have "e\<in>set l" by auto with Cons.hyps obtain l1 l2 where "l=l1@e#l2" by blast hence "a#l = (a#l1)@e#l2" by simp with Cons.prems(2) show P by blast qed qed lemma in_set_upd_cases: assumes "x\<in>set (l[i:=y])" obtains "i<length l" and "x=y" | "x\<in>set l" by (metis assms in_set_conv_nth length_list_update nth_list_update_eq nth_list_update_neq) lemma in_set_upd_eq_aux: assumes "i<length l" shows "x\<in>set (l[i:=y]) \<longleftrightarrow> x=y \<or> (\<forall>y. x\<in>set (l[i:=y]))" by (metis in_set_upd_cases assms list_update_overwrite set_update_memI) lemma in_set_upd_eq: assumes "i<length l" shows "x\<in>set (l[i:=y]) \<longleftrightarrow> x=y \<or> (x\<in>set l \<and> (\<forall>y. x\<in>set (l[i:=y])))" by (metis in_set_upd_cases in_set_upd_eq_aux assms) text \<open>Simultaneous induction over two lists, prepending an element to one of the lists in each step\<close> lemma list_2pre_induct[case_names base left right]: assumes BASE: "P [] []" and LEFT: "!!e w1' w2. P w1' w2 \<Longrightarrow> P (e#w1') w2" and RIGHT: "!!e w1 w2'. P w1 w2' \<Longrightarrow> P w1 (e#w2')" shows "P w1 w2" proof - { \<comment> \<open>The proof is done by induction over the sum of the lengths of the lists\<close> fix n have "!!w1 w2. \<lbrakk>length w1 + length w2 = n; P [] []; !!e w1' w2. P w1' w2 \<Longrightarrow> P (e#w1') w2; !!e w1 w2'. P w1 w2' \<Longrightarrow> P w1 (e#w2') \<rbrakk> \<Longrightarrow> P w1 w2 " apply (induct n) apply simp apply (case_tac w1) apply auto apply (case_tac w2) apply auto done } from this[OF _ BASE LEFT RIGHT] show ?thesis by blast qed lemma list_decomp_1: "length l=1 \<Longrightarrow> \<exists>a. l=[a]" by (case_tac l, auto) lemma list_decomp_2: "length l=2 \<Longrightarrow> \<exists>a b. l=[a,b]" by (case_tac l, auto simp add: list_decomp_1) lemma list_rest_coinc: "\<lbrakk>length s2 \<le> length s1; s1@r1 = s2@r2\<rbrakk> \<Longrightarrow> \<exists>r1p. r2=r1p@r1" by (metis append_eq_append_conv_if) lemma list_tail_coinc: "n1#r1 = n2#r2 \<Longrightarrow> n1=n2 & r1=r2" by (auto) lemma last_in_set[intro]: "\<lbrakk>l\<noteq>[]\<rbrakk> \<Longrightarrow> last l \<in> set l" by (induct l) auto lemma empty_append_eq_id[simp]: "(@) [] = (\<lambda>x. x)" by auto lemma op_conc_empty_img_id[simp]: "((@) [] ` L) = L" by auto lemma distinct_match: "\<lbrakk> distinct (al@e#bl) \<rbrakk> \<Longrightarrow> (al@e#bl = al'@e#bl') \<longleftrightarrow> (al=al' \<and> bl=bl')" proof (rule iffI, induct al arbitrary: al') case Nil thus ?case by (cases al') auto next case (Cons a al) note Cprems=Cons.prems note Chyps=Cons.hyps show ?case proof (cases al') case Nil with Cprems have False by auto thus ?thesis .. next case [simp]: (Cons a' all') with Cprems have [simp]: "a=a'" and P: "al@e#bl = all'@e#bl'" by auto from Cprems(1) have D: "distinct (al@e#bl)" by auto from Chyps[OF D P] have [simp]: "al=all'" "bl=bl'" by auto show ?thesis by simp qed qed simp lemma prop_match: "\<lbrakk> list_all P al; \<not>P e; \<not>P e'; list_all P bl \<rbrakk> \<Longrightarrow> (al@e#bl = al'@e'#bl') \<longleftrightarrow> (al=al' \<and> e=e' \<and> bl=bl')" apply (rule iffI, induct al arbitrary: al') apply (case_tac al', fastforce, fastforce)+ done lemmas prop_matchD = rev_iffD1[OF _ prop_match[where P=P]] for P declare distinct_tl[simp] lemma list_se_match[simp]: "l1 \<noteq> [] \<Longrightarrow> l1@l2 = [a] \<longleftrightarrow> l1 = [a] \<and> l2 = []" "l2 \<noteq> [] \<Longrightarrow> l1@l2 = [a] \<longleftrightarrow> l1 = [] \<and> l2 = [a]" "l1 \<noteq> [] \<Longrightarrow> [a] = l1@l2 \<longleftrightarrow> l1 = [a] \<and> l2 = []" "l2 \<noteq> [] \<Longrightarrow> [a] = l1@l2 \<longleftrightarrow> l1 = [] \<and> l2 = [a]" apply (cases l1, simp_all) apply (cases l1, simp_all) apply (cases l1, auto) [] apply (cases l1, auto) [] done (* Placed here because it depends on xy_in_set_cases *) lemma distinct_map_eq: "\<lbrakk> distinct (List.map f l); f x = f y; x\<in>set l; y\<in>set l \<rbrakk> \<Longrightarrow> x=y" by (erule (2) xy_in_set_cases) auto lemma upt_append: assumes "i<j" shows "[0..<i]@[i..<j] = [0..<j]" using assms apply (induct j) apply simp apply (case_tac "i=j") apply auto done lemma upt_filter_extend: assumes LE: "u\<le>u'" assumes NP: "\<forall>i. u\<le>i \<and> i<u' \<longrightarrow> \<not>P i" shows "[i\<leftarrow>[0..<u]. P i] = [i\<leftarrow>[0..<u']. P i]" proof (cases "u=u'") case True thus ?thesis by simp next case False hence "u<u'" using LE by simp hence "[0..<u'] = [0..<u]@[u ..<u']" by (simp add: upt_append) hence "[i\<leftarrow>[0..<u']. P i] = [i\<leftarrow>[0..<u]. P i] @ [i\<leftarrow>[u..<u']. P i]" by simp also have "[i\<leftarrow>[u..<u']. P i] = []" using NP by (auto simp: filter_empty_conv) finally show ?thesis by simp qed lemma filter_upt_last: assumes E: "[k\<leftarrow>[0..<length l] . P (l!k)] = js @ [j]" assumes "j<i" and "i<length l" shows "\<not> P (l!i)" proof assume A: "P (l!i)" have "[0..<length l] = [0..<i]@[i..<length l]" using \<open>i<length l\<close> by (simp add: upt_append) also have "[i..<length l] = i#[Suc i..<length l]" using \<open>i<length l\<close> by (auto simp: upt_conv_Cons) finally have "[k\<leftarrow>[0..<i] . P (l!k)]@i#[k\<leftarrow>[Suc i..<length l] . P (l!k)] = js@[j]" unfolding E[symmetric] using \<open>P (l!i)\<close> by simp hence "j = last (i#[k\<leftarrow>[Suc i..<length l] . P (l!k)])" by (metis last_appendR last_snoc list.distinct(1)) also have "\<dots> \<ge> i" proof - have "sorted (i#[k\<leftarrow>[Suc i..<length l] . P (l!k)])" (is "sorted ?l") by (simp add: sorted_filter[where f=id, simplified]) hence "hd ?l \<le> last ?l" by (rule sorted_hd_last) simp thus ?thesis by simp qed finally have "i\<le>j" . thus False using \<open>j<i\<close> by simp qed lemma all_set_conv_nth: "(\<forall>x\<in>set l. P x) \<longleftrightarrow> (\<forall>i<length l. P (l!i))" by (auto intro: all_nth_imp_all_set) (* TODO: Special case of upt_eq_Nil_conv. Find cases where the latter does not work \<dots> *) lemma upt_0_eq_Nil_conv[simp]: "[0..<j] = [] \<longleftrightarrow> j=0" by auto lemma filter_eq_snocD: "filter P l = l'@[x] \<Longrightarrow> x\<in>set l \<and> P x" proof - assume A: "filter P l = l'@[x]" hence "x\<in>set (filter P l)" by simp thus ?thesis by simp qed lemma lists_image_witness: assumes A: "x\<in>lists (f`Q)" obtains xo where "xo\<in>lists Q" "x=map f xo" proof - have "\<lbrakk> x\<in>lists (f`Q) \<rbrakk> \<Longrightarrow> \<exists>xo\<in>lists Q. x=map f xo" proof (induct x) case Nil thus ?case by auto next case (Cons x xs) then obtain xos where "xos\<in>lists Q" "xs=map f xos" by force moreover from Cons.prems have "x\<in>f`Q" by auto then obtain xo where "xo\<in>Q" "x=f xo" by auto ultimately show ?case by (rule_tac x="xo#xos" in bexI) auto qed thus ?thesis apply (simp_all add: A) apply (erule_tac bexE) apply (rule_tac that) apply assumption+ done qed lemma map_of_None_filterD: "map_of xs x = None \<Longrightarrow> map_of (filter P xs) x = None" by(induct xs) auto lemma map_of_concat: "map_of (concat xss) = foldr (\<lambda>xs f. f ++ map_of xs) xss Map.empty" by(induct xss) simp_all lemma map_of_Some_split: "map_of xs k = Some v \<Longrightarrow> \<exists>ys zs. xs = ys @ (k, v) # zs \<and> map_of ys k = None" proof(induct xs) case (Cons x xs) obtain k' v' where x: "x = (k', v')" by(cases x) show ?case proof(cases "k' = k") case True with \<open>map_of (x # xs) k = Some v\<close> x have "x # xs = [] @ (k, v) # xs" "map_of [] k = None" by simp_all thus ?thesis by blast next case False with \<open>map_of (x # xs) k = Some v\<close> x have "map_of xs k = Some v" by simp from \<open>map_of xs k = Some v \<Longrightarrow> \<exists>ys zs. xs = ys @ (k, v) # zs \<and> map_of ys k = None\<close>[OF this] obtain ys zs where "xs = ys @ (k, v) # zs" "map_of ys k = None" by blast with False x have "x # xs = (x # ys) @ (k, v) # zs" "map_of (x # ys) k = None" by simp_all thus ?thesis by blast qed qed simp lemma map_add_find_left: "g k = None \<Longrightarrow> (f ++ g) k = f k" by(simp add: map_add_def) lemma map_add_left_None: "f k = None \<Longrightarrow> (f ++ g) k = g k" by(simp add: map_add_def split: option.split) lemma map_of_Some_filter_not_in: "\<lbrakk> map_of xs k = Some v; \<not> P (k, v); distinct (map fst xs) \<rbrakk> \<Longrightarrow> map_of (filter P xs) k = None" apply(induct xs) apply(auto) apply(auto simp add: map_of_eq_None_iff) done lemma distinct_map_fst_filterI: "distinct (map fst xs) \<Longrightarrow> distinct (map fst (filter P xs))" by(induct xs) auto lemma distinct_map_fstD: "\<lbrakk> distinct (map fst xs); (x, y) \<in> set xs; (x, z) \<in> set xs \<rbrakk> \<Longrightarrow> y = z" by(induct xs)(fastforce elim: notE rev_image_eqI)+ lemma concat_filter_neq_Nil: "concat [ys\<leftarrow>xs. ys \<noteq> Nil] = concat xs" by(induct xs) simp_all lemma distinct_concat': "\<lbrakk>distinct [ys\<leftarrow>xs. ys \<noteq> Nil]; \<And>ys. ys \<in> set xs \<Longrightarrow> distinct ys; \<And>ys zs. \<lbrakk>ys \<in> set xs; zs \<in> set xs; ys \<noteq> zs\<rbrakk> \<Longrightarrow> set ys \<inter> set zs = {}\<rbrakk> \<Longrightarrow> distinct (concat xs)" by(erule distinct_concat[of "[ys\<leftarrow>xs. ys \<noteq> Nil]", unfolded concat_filter_neq_Nil]) auto lemma distinct_idx: assumes "distinct (map f l)" assumes "i<length l" assumes "j<length l" assumes "f (l!i) = f (l!j)" shows "i=j" by (metis assms distinct_conv_nth length_map nth_map) lemma replicate_Suc_conv_snoc: "replicate (Suc n) x = replicate n x @ [x]" by (metis replicate_Suc replicate_append_same) lemma filter_nth_ex_nth: assumes "n < length (filter P xs)" shows "\<exists>m. n \<le> m \<and> m < length xs \<and> filter P xs ! n = xs ! m \<and> filter P (take m xs) = take n (filter P xs)" using assms proof(induct xs rule: rev_induct) case Nil thus ?case by simp next case (snoc x xs) show ?case proof(cases "P x") case [simp]: False from \<open>n < length (filter P (xs @ [x]))\<close> have "n < length (filter P xs)" by simp hence "\<exists>m\<ge>n. m < length xs \<and> filter P xs ! n = xs ! m \<and> filter P (take m xs) = take n (filter P xs)" by(rule snoc) thus ?thesis by(auto simp add: nth_append) next case [simp]: True show ?thesis proof(cases "n = length (filter P xs)") case False with \<open>n < length (filter P (xs @ [x]))\<close> have "n < length (filter P xs)" by simp moreover hence "\<exists>m\<ge>n. m < length xs \<and> filter P xs ! n = xs ! m \<and> filter P (take m xs) = take n (filter P xs)" by(rule snoc) ultimately show ?thesis by(auto simp add: nth_append) next case [simp]: True hence "filter P (xs @ [x]) ! n = (xs @ [x]) ! length xs" by simp moreover have "length xs < length (xs @ [x])" by simp moreover have "length xs \<ge> n" by simp moreover have "filter P (take (length xs) (xs @ [x])) = take n (filter P (xs @ [x]))" by simp ultimately show ?thesis by blast qed qed qed lemma set_map_filter: "set (List.map_filter g xs) = {y. \<exists>x. x \<in> set xs \<and> g x = Some y}" by (induct xs) (auto simp add: List.map_filter_def set_eq_iff) subsection \<open>Quicksort by Relation\<close> text \<open>A functional implementation of quicksort on lists. It it similar to the one in Isabelle/HOL's example directory. However, it uses tail-recursion for append and arbitrary relations.\<close> fun partition_rev :: "('a \<Rightarrow> bool) \<Rightarrow> ('a list \<times> 'a list) \<Rightarrow> 'a list \<Rightarrow> ('a list \<times> 'a list)" where "partition_rev P (yes, no) [] = (yes, no)" | "partition_rev P (yes, no) (x # xs) = partition_rev P (if P x then (x # yes, no) else (yes, x # no)) xs" lemma partition_rev_filter_conv : "partition_rev P (yes, no) xs = (rev (filter P xs) @ yes, rev (filter (Not \<circ> P) xs) @ no)" by (induct xs arbitrary: yes no) (simp_all) function quicksort_by_rel :: "('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> 'a list \<Rightarrow> 'a list \<Rightarrow> 'a list" where "quicksort_by_rel R sl [] = sl" | "quicksort_by_rel R sl (x#xs) = (let (xs_s, xs_b) = partition_rev (\<lambda>y. R y x) ([],[]) xs in quicksort_by_rel R (x # (quicksort_by_rel R sl xs_b)) xs_s)" by pat_completeness simp_all termination by (relation "measure (\<lambda>(_, _, xs). length xs)") (simp_all add: partition_rev_filter_conv less_Suc_eq_le) lemma quicksort_by_rel_remove_acc : "quicksort_by_rel R sl xs = (quicksort_by_rel R [] xs @ sl)" proof (induct xs arbitrary: sl rule: measure_induct_rule[of "length"]) case (less xs) note ind_hyp = this show ?case proof (cases xs) case Nil thus ?thesis by simp next case (Cons x xs') note xs_eq[simp] = this obtain xs1 xs2 where part_rev_eq[simp]: "partition_rev (\<lambda>y. R y x) ([], []) xs' = (xs1, xs2)" by (rule prod.exhaust) from part_rev_eq[symmetric] have length_le: "length xs1 < length xs" "length xs2 < length xs" unfolding partition_rev_filter_conv by (simp_all add: less_Suc_eq_le) note ind_hyp1a = ind_hyp[OF length_le(1), of "x # quicksort_by_rel R [] xs2"] note ind_hyp1b = ind_hyp[OF length_le(1), of "x # quicksort_by_rel R [] xs2 @ sl"] note ind_hyp2 = ind_hyp[OF length_le(2), of sl] show ?thesis by (simp add: ind_hyp1a ind_hyp1b ind_hyp2) qed qed lemma quicksort_by_rel_remove_acc_guared : "sl \<noteq> [] \<Longrightarrow> quicksort_by_rel R sl xs = (quicksort_by_rel R [] xs @ sl)" by (metis quicksort_by_rel_remove_acc) lemma quicksort_by_rel_permutes [simp]: "mset (quicksort_by_rel R sl xs) = mset (xs @ sl)" proof (induct xs arbitrary: sl rule: measure_induct_rule[of "length"]) case (less xs) note ind_hyp = this show ?case proof (cases xs) case Nil thus ?thesis by simp next case (Cons x xs') note xs_eq[simp] = this obtain xs1 xs2 where part_rev_eq[simp]: "partition_rev (\<lambda>y. R y x) ([], []) xs' = (xs1, xs2)" by (rule prod.exhaust) from part_rev_eq[symmetric] have xs'_multi_eq : "mset xs' = mset xs1 + mset xs2" unfolding partition_rev_filter_conv by (simp add: mset_filter) from part_rev_eq[symmetric] have length_le: "length xs1 < length xs" "length xs2 < length xs" unfolding partition_rev_filter_conv by (simp_all add: less_Suc_eq_le) note ind_hyp[OF length_le(1)] ind_hyp[OF length_le(2)] thus ?thesis by (simp add: xs'_multi_eq union_assoc) qed qed show ?case proof (cases xs) case Nil thus ?thesis by simp next case (Cons x xs') note xs_eq[simp] = this obtain xs1 xs2 where part_rev_eq[simp]: "partition_rev (\<lambda>y. R y x) ([], []) xs' = (xs1, xs2)" by (rule prod.exhaust) from part_rev_eq[symmetric] have xs1_props: "\<And>y. y \<in> set xs1 \<Longrightarrow> (R y x)" and xs2_props: "\<And>y. y \<in> set xs2 \<Longrightarrow> \<not>(R y x)" unfolding partition_rev_filter_conv by simp_all from xs2_props lin have xs2_props': "\<And>y. y \<in> set xs2 \<Longrightarrow> (R x y)" by blast from xs2_props' xs1_props trans_R have xs1_props': "\<And>y1 y2. y1 \<in> set xs1 \<Longrightarrow> y2 \<in> set xs2 \<Longrightarrow> (R y1 y2)" by metis from part_rev_eq[symmetric] have length_le: "length xs1 < length xs" "length xs2 < length xs" unfolding partition_rev_filter_conv by (simp_all add: less_Suc_eq_le) note ind_hyps = ind_hyp[OF length_le(1)] ind_hyp[OF length_le(2)] thus ?thesis by (simp add: quicksort_by_rel_remove_acc_guared sorted_wrt_append Ball_def xs1_props xs2_props' xs1_props') qed qed lemma sorted_quicksort_by_rel: "sorted (quicksort_by_rel (\<le>) [] xs)" by (rule sorted_wrt_quicksort_by_rel) auto lemma sort_quicksort_by_rel: "sort = quicksort_by_rel (\<le>) []" apply (rule ext, rule properties_for_sort) apply(simp_all add: sorted_quicksort_by_rel) done subsection \<open>Mergesort by Relation\<close> text \<open>A functional implementation of mergesort on lists. It it similar to the one in Isabelle/HOL's example directory. However, it uses tail-recursion for append and arbitrary relations.\<close> fun mergesort_by_rel_split :: "('a list \<times> 'a list) \<Rightarrow> 'a list \<Rightarrow> ('a list \<times> 'a list)" where "mergesort_by_rel_split (xs1, xs2) [] = (xs1, xs2)" | "mergesort_by_rel_split (xs1, xs2) [x] = (x # xs1, xs2)" | "mergesort_by_rel_split (xs1, xs2) (x1 # x2 # xs) = mergesort_by_rel_split (x1 # xs1, x2 # xs2) xs" show ?case proof (cases xs) case Nil thus ?thesis using assms(1) by simp next case (Cons x1 xs') note xs_eq[simp] = this thus ?thesis proof (cases xs') case Nil thus ?thesis using assms(2) by simp next case (Cons x2 xs'') note xs'_eq[simp] = this show ?thesis by (simp add: ind_hyp assms(3)) qed qed qed lemma mergesort_by_rel_split_length : "length (fst (mergesort_by_rel_split (xs1, xs2) xs)) = length xs1 + (length xs div 2) + (length xs mod 2) \<and> length (snd (mergesort_by_rel_split (xs1, xs2) xs)) = length xs2 + (length xs div 2)" by (induct xs arbitrary: xs1 xs2 rule: list_induct_first2) (simp_all) lemma mset_mergesort_by_rel_split [simp]: "mset (fst (mergesort_by_rel_split (xs1, xs2) xs)) + mset (snd (mergesort_by_rel_split (xs1, xs2) xs)) = mset xs + mset xs1 + mset xs2" apply (induct xs arbitrary: xs1 xs2 rule: list_induct_first2) apply (simp_all add: ac_simps) done fun mergesort_by_rel_merge :: "('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> 'a list \<Rightarrow> 'a list \<Rightarrow> 'a list" where "mergesort_by_rel_merge R (x#xs) (y#ys) = (if R x y then x # mergesort_by_rel_merge R xs (y#ys) else y # mergesort_by_rel_merge R (x#xs) ys)" | "mergesort_by_rel_merge R xs [] = xs" | "mergesort_by_rel_merge R [] ys = ys" declare mergesort_by_rel_merge.simps [simp del] lemma mergesort_by_rel_merge_simps[simp] : "mergesort_by_rel_merge R (x#xs) (y#ys) = (if R x y then x # mergesort_by_rel_merge R xs (y#ys) else y # mergesort_by_rel_merge R (x#xs) ys)" "mergesort_by_rel_merge R xs [] = xs" "mergesort_by_rel_merge R [] ys = ys" apply (simp_all add: mergesort_by_rel_merge.simps) apply (cases ys) apply (simp_all add: mergesort_by_rel_merge.simps) done lemma mergesort_by_rel_merge_induct [consumes 0, case_names Nil1 Nil2 Cons1 Cons2]: assumes "\<And>xs::'a list. P xs []" "\<And>ys::'b list. P [] ys" "\<And>x xs y ys. R x y \<Longrightarrow> P xs (y # ys) \<Longrightarrow> P (x # xs) (y # ys)" "\<And>x xs y ys. \<not>(R x y) \<Longrightarrow> P (x # xs) ys \<Longrightarrow> P (x # xs) (y # ys)" shows "P xs ys" proof (induct xs arbitrary: ys) case Nil thus ?case using assms(2) by simp next case (Cons x xs) note P_xs = this show ?case proof (induct ys) case Nil thus ?case using assms(1) by simp next case (Cons y ys) note P_x_xs_ys = this show ?case using assms(3,4)[of x y xs ys] P_x_xs_ys P_xs by metis qed qed lemma mset_mergesort_by_rel_merge [simp]: "mset (mergesort_by_rel_merge R xs ys) = mset xs + mset ys" by (induct R xs ys rule: mergesort_by_rel_merge.induct) (simp_all add: ac_simps) lemma sorted_wrt_mergesort_by_rel_merge [simp]: assumes lin : "\<And>x y. (R x y) \<or> (R y x)" and trans_R: "\<And>x y z. R x y \<Longrightarrow> R y z \<Longrightarrow> R x z" shows "sorted_wrt R (mergesort_by_rel_merge R xs ys) \<longleftrightarrow> sorted_wrt R xs \<and> sorted_wrt R ys" proof (induct xs ys rule: mergesort_by_rel_merge_induct[where R = R]) case Nil1 thus ?case by simp next case Nil2 thus ?case by simp next case (Cons1 x xs y ys) thus ?case by (simp add: Ball_def) (metis trans_R) next case (Cons2 x xs y ys) thus ?case apply (auto simp add: Ball_def) apply (metis lin) apply (metis lin trans_R) done qed function mergesort_by_rel :: "('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> 'a list \<Rightarrow> 'a list" where "mergesort_by_rel R xs = (if length xs < 2 then xs else (mergesort_by_rel_merge R (mergesort_by_rel R (fst (mergesort_by_rel_split ([], []) xs))) (mergesort_by_rel R (snd (mergesort_by_rel_split ([], []) xs)))))" by auto termination by (relation "measure (\<lambda>(_, xs). length xs)") (simp_all add: mergesort_by_rel_split_length not_less minus_div_mult_eq_mod [symmetric]) declare mergesort_by_rel.simps [simp del] lemma mergesort_by_rel_simps [simp, code] : "mergesort_by_rel R [] = []" "mergesort_by_rel R [x] = [x]" "mergesort_by_rel R (x1 # x2 # xs) = (let (xs1, xs2) = (mergesort_by_rel_split ([x1], [x2]) xs) in mergesort_by_rel_merge R (mergesort_by_rel R xs1) (mergesort_by_rel R xs2))" apply (simp add: mergesort_by_rel.simps) apply (simp add: mergesort_by_rel.simps) apply (simp add: mergesort_by_rel.simps[of _ "x1 # x2 # xs"] split: prod.splits) done lemma mergesort_by_rel_permutes [simp]: "mset (mergesort_by_rel R xs) = mset xs" proof (induct xs rule: length_induct) case (1 xs) note ind_hyp = this show ?case proof (cases xs) case Nil thus ?thesis by simp next case (Cons x1 xs') note xs_eq[simp] = this show ?thesis proof (cases xs') case Nil thus ?thesis by simp next case (Cons x2 xs'') note xs'_eq[simp] = this have "length (fst (mergesort_by_rel_split ([], []) xs)) < length xs" "length (snd (mergesort_by_rel_split ([], []) xs)) < length xs" by (simp_all add: mergesort_by_rel_split_length) with ind_hyp show ?thesis unfolding mergesort_by_rel.simps[of _ xs] by (simp add: ac_simps) qed qed qed lemma set_mergesort_by_rel [simp]: "set (mergesort_by_rel R xs) = set xs" unfolding set_mset_comp_mset [symmetric] o_apply by simp lemma sorted_wrt_mergesort_by_rel: fixes R:: "'x \<Rightarrow> 'x \<Rightarrow> bool" assumes lin : "\<And>x y. (R x y) \<or> (R y x)" and trans_R: "\<And>x y z. R x y \<Longrightarrow> R y z \<Longrightarrow> R x z" shows "sorted_wrt R (mergesort_by_rel R xs)" proof (induct xs rule: measure_induct_rule[of "length"]) case (less xs) note ind_hyp = this show ?case proof (cases xs) case Nil thus ?thesis by simp next case (Cons x xs') note xs_eq[simp] = this thus ?thesis proof (cases xs') case Nil thus ?thesis by simp next case (Cons x2 xs'') note xs'_eq[simp] = this have "length (fst (mergesort_by_rel_split ([], []) xs)) < length xs" "length (snd (mergesort_by_rel_split ([], []) xs)) < length xs" by (simp_all add: mergesort_by_rel_split_length) with ind_hyp show ?thesis unfolding mergesort_by_rel.simps[of _ xs] by (simp add: sorted_wrt_mergesort_by_rel_merge[OF lin trans_R]) qed qed qed lemma sorted_mergesort_by_rel: "sorted (mergesort_by_rel (\<le>) xs)" by (rule sorted_wrt_mergesort_by_rel) auto lemma sort_mergesort_by_rel: "sort = mergesort_by_rel (\<le>)" apply (rule ext, rule properties_for_sort) apply(simp_all add: sorted_mergesort_by_rel) done definition "mergesort = mergesort_by_rel (\<le>)" lemma sort_mergesort: "sort = mergesort" unfolding mergesort_def by (rule sort_mergesort_by_rel) subsubsection \<open>Mergesort with Remdup\<close> term merge fun merge :: "'a::{linorder} list \<Rightarrow> 'a list \<Rightarrow> 'a list" where "merge [] l2 = l2" | "merge l1 [] = l1" | "merge (x1 # l1) (x2 # l2) = (if (x1 < x2) then x1 # (merge l1 (x2 # l2)) else (if (x1 = x2) then x1 # (merge l1 l2) else x2 # (merge (x1 # l1) l2)))" lemma merge_correct : assumes l1_OK: "distinct l1 \<and> sorted l1" assumes l2_OK: "distinct l2 \<and> sorted l2" shows "distinct (merge l1 l2) \<and> sorted (merge l1 l2) \<and> set (merge l1 l2) = set l1 \<union> set l2" using assms proof (induct l1 arbitrary: l2) case Nil thus ?case by simp next case (Cons x1 l1 l2) note x1_l1_props = Cons(2) note l2_props = Cons(3) from x1_l1_props have l1_props: "distinct l1 \<and> sorted l1" and x1_nin_l1: "x1 \<notin> set l1" and x1_le: "\<And>x. x \<in> set l1 \<Longrightarrow> x1 \<le> x" by (simp_all add: Ball_def) note ind_hyp_l1 = Cons(1)[OF l1_props] show ?case using l2_props proof (induct l2) case Nil with x1_l1_props show ?case by simp next case (Cons x2 l2) note x2_l2_props = Cons(2) from x2_l2_props have l2_props: "distinct l2 \<and> sorted l2" and x2_nin_l2: "x2 \<notin> set l2" and x2_le: "\<And>x. x \<in> set l2 \<Longrightarrow> x2 \<le> x" by (simp_all add: Ball_def) note ind_hyp_l2 = Cons(1)[OF l2_props] show ?case proof (cases "x1 < x2") case True note x1_less_x2 = this from ind_hyp_l1[OF x2_l2_props] x1_less_x2 x1_nin_l1 x1_le x2_le show ?thesis apply (auto simp add: Ball_def) apply (metis linorder_not_le) apply (metis linorder_not_less xt1(6) xt1(9)) done next case False note x2_le_x1 = this show ?thesis proof (cases "x1 = x2") case True note x1_eq_x2 = this from ind_hyp_l1[OF l2_props] x1_le x2_le x2_nin_l2 x1_eq_x2 x1_nin_l1 show ?thesis by (simp add: x1_eq_x2 Ball_def) next case False note x1_neq_x2 = this with x2_le_x1 have x2_less_x1 : "x2 < x1" by auto from ind_hyp_l2 x2_le_x1 x1_neq_x2 x2_le x2_nin_l2 x1_le show ?thesis apply (simp add: x2_less_x1 Ball_def) apply (metis linorder_not_le x2_less_x1 xt1(7)) done qed qed qed qed function merge_list :: "'a::{linorder} list list \<Rightarrow> 'a list list \<Rightarrow> 'a list" where "merge_list [] [] = []" | "merge_list [] [l] = l" | "merge_list (la # acc2) [] = merge_list [] (la # acc2)" | "merge_list (la # acc2) [l] = merge_list [] (l # la # acc2)" | "merge_list acc2 (l1 # l2 # ls) = merge_list ((merge l1 l2) # acc2) ls" by pat_completeness simp_all termination by (relation "measure (\<lambda>(acc, ls). 3 * length acc + 2 * length ls)") (simp_all) lemma merge_list_correct : assumes ls_OK: "\<And>l. l \<in> set ls \<Longrightarrow> distinct l \<and> sorted l" assumes as_OK: "\<And>l. l \<in> set as \<Longrightarrow> distinct l \<and> sorted l" shows "distinct (merge_list as ls) \<and> sorted (merge_list as ls) \<and> set (merge_list as ls) = set (concat (as @ ls))" using assms proof (induct as ls rule: merge_list.induct) case 1 thus ?case by simp next case 2 thus ?case by simp next case 3 thus ?case by simp next case 4 thus ?case by auto next case (5 acc l1 l2 ls) note ind_hyp = 5(1) note l12_l_OK = 5(2) note acc_OK = 5(3) from l12_l_OK acc_OK merge_correct[of l1 l2] have set_merge_eq: "set (merge l1 l2) = set l1 \<union> set l2" by auto from l12_l_OK acc_OK merge_correct[of l1 l2] have "distinct (merge_list (merge l1 l2 # acc) ls) \<and> sorted (merge_list (merge l1 l2 # acc) ls) \<and> set (merge_list (merge l1 l2 # acc) ls) = set (concat ((merge l1 l2 # acc) @ ls))" by (rule_tac ind_hyp) auto with set_merge_eq show ?case by auto qed definition mergesort_remdups where "mergesort_remdups xs = merge_list [] (map (\<lambda>x. [x]) xs)" lemma mergesort_remdups_correct : "distinct (mergesort_remdups l) \<and> sorted (mergesort_remdups l) \<and> (set (mergesort_remdups l) = set l)" proof - let ?l' = "map (\<lambda>x. [x]) l" { fix xs assume "xs \<in> set ?l'" then obtain x where xs_eq: "xs = [x]" by auto hence "distinct xs \<and> sorted xs" by simp } note l'_OK = this from merge_list_correct[of "?l'" "[]", OF l'_OK] show ?thesis unfolding mergesort_remdups_def by simp qed (* TODO: Move *) lemma ex1_eqI: "\<lbrakk>\<exists>!x. P x; P a; P b\<rbrakk> \<Longrightarrow> a=b" by blast lemma remdup_sort_mergesort_remdups: "remdups o sort = mergesort_remdups" (is "?lhs=?rhs") proof fix l have "set (?lhs l) = set l" and "sorted (?lhs l)" and "distinct (?lhs l)" by simp_all moreover note mergesort_remdups_correct ultimately show "?lhs l = ?rhs l" by (auto intro!: ex1_eqI[OF finite_sorted_distinct_unique[OF finite_set]]) qed subsection \<open>Native Integers\<close> lemma int_of_integer_less_iff: "int_of_integer x < int_of_integer y \<longleftrightarrow> x<y" by (simp add: less_integer_def) lemma nat_of_integer_less_iff: "x\<ge>0 \<Longrightarrow> y\<ge>0 \<Longrightarrow> nat_of_integer x < nat_of_integer y \<longleftrightarrow> x<y" unfolding nat_of_integer.rep_eq by (auto simp: int_of_integer_less_iff nat_less_eq_zless int_of_integer_less_iff[of 0, simplified]) subsection "Natural Numbers" lemma exists_leI: assumes hyp: "(\<forall>n' < n. \<not> P n') \<Longrightarrow> P (n::nat)" shows "\<exists>n' \<le> n. P n'" proof (rule classical) assume contra: "\<not> (\<exists>n'\<le>n. P n')" hence "\<forall>n' < n. \<not> P n'" by auto hence "P n" by (rule hyp) thus "\<exists>n'\<le>n. P n'" by auto qed subsubsection \<open>Induction on nat\<close> lemma nat_compl_induct[case_names 0 Suc]: "\<lbrakk>P 0; \<And>n . \<forall>nn. nn \<le> n \<longrightarrow> P nn \<Longrightarrow> P (Suc n)\<rbrakk> \<Longrightarrow> P n" apply(induct_tac n rule: nat_less_induct) apply(case_tac n) apply(auto) done lemma nat_compl_induct'[case_names 0 Suc]: "\<lbrakk>P 0; !! n . \<lbrakk>!! nn . nn \<le> n \<Longrightarrow> P nn\<rbrakk> \<Longrightarrow> P (Suc n)\<rbrakk> \<Longrightarrow> P n" apply(induct_tac n rule: nat_less_induct) apply(case_tac n) apply(auto) done lemma nz_le_conv_less: "0<k \<Longrightarrow> k \<le> m \<Longrightarrow> k - Suc 0 < m" by auto lemma min_Suc_gt[simp]: "a<b \<Longrightarrow> min (Suc a) b = Suc a" "a<b \<Longrightarrow> min b (Suc a) = Suc a" by auto subsection \<open>Integer\<close> text \<open>Some setup from \<open>int\<close> transferred to \<open>integer\<close>\<close> lemma atLeastLessThanPlusOne_atLeastAtMost_integer: "{l..<u+1} = {l..(u::integer)}" apply (auto simp add: atLeastAtMost_def atLeastLessThan_def) including integer.lifting apply transfer apply simp done lemma atLeastPlusOneAtMost_greaterThanAtMost_integer: "{l+1..u} = {l<..(u::integer)}" including integer.lifting by (auto simp add: atLeastAtMost_def greaterThanAtMost_def, transfer, simp) lemma image_atLeastZeroLessThan_integer: "0 \<le> u \<Longrightarrow> {(0::integer)..<u} = of_nat ` {..<nat_of_integer u}" including integer.lifting apply (unfold image_def lessThan_def) apply auto apply (rule_tac x = "nat_of_integer x" in exI) apply transfer apply (auto simp add: zless_nat_eq_int_zless [THEN sym]) apply transfer apply simp done lemma image_add_integer_atLeastLessThan: "(%x. x + (l::integer)) ` {0..<u-l} = {l..<u}" apply (auto simp add: image_def) apply (rule_tac x = "x - l" in bexI) apply auto done lemma finite_atLeastZeroLessThan_integer: "finite {(0::integer)..<u}" apply (cases "0 \<le> u") apply (subst image_atLeastZeroLessThan_integer, assumption) apply (rule finite_imageI) apply auto done lemma finite_atLeastLessThan_integer [iff]: "finite {l..<u::integer}" apply (subgoal_tac "(%x. x + l) ` {0..<u-l} = {l..<u}") apply (erule subst) apply (rule finite_imageI) apply (rule finite_atLeastZeroLessThan_integer) apply (rule image_add_integer_atLeastLessThan) done lemma finite_atLeastAtMost_integer [iff]: "finite {l..(u::integer)}" by (subst atLeastLessThanPlusOne_atLeastAtMost_integer [THEN sym], simp) lemma finite_greaterThanAtMost_integer [iff]: "finite {l<..(u::integer)}" by (subst atLeastPlusOneAtMost_greaterThanAtMost_integer [THEN sym], simp) lemma finite_greaterThanLessThan_integer [iff]: "finite {l<..<u::integer}" by (subst atLeastPlusOneLessThan_greaterThanLessThan_integer [THEN sym], simp) subsection \<open>Functions of type @{typ "bool\<Rightarrow>bool"}\<close> lemma boolfun_cases_helper: "g=(\<lambda>x. False) | g=(\<lambda>x. x) | g=(\<lambda>x. True) | g= (\<lambda>x. \<not>x)" proof - { assume "g False" "g True" hence "g = (\<lambda>x. True)" by (rule_tac ext, case_tac x, auto) } moreover { assume "g False" "\<not>g True" hence "g = (\<lambda>x. \<not>x)" by (rule_tac ext, case_tac x, auto) } moreover { assume "\<not>g False" "g True" hence "g = (\<lambda>x. x)" by (rule_tac ext, case_tac x, auto) } moreover { assume "\<not>g False" "\<not>g True" hence "g = (\<lambda>x. False)" by (rule_tac ext, case_tac x, auto) } ultimately show ?thesis by fast qed lemma boolfun_cases[case_names False Id True Neg]: "\<lbrakk>g=(\<lambda>x. False) \<Longrightarrow> P; g=(\<lambda>x. x) \<Longrightarrow> P; g=(\<lambda>x. True) \<Longrightarrow> P; g=(\<lambda>x. \<not>x) \<Longrightarrow> P\<rbrakk> \<Longrightarrow> P" proof - note boolfun_cases_helper[of g] moreover assume "g=(\<lambda>x. False) \<Longrightarrow> P" "g=(\<lambda>x. x) \<Longrightarrow> P" "g=(\<lambda>x. True) \<Longrightarrow> P" "g=(\<lambda>x. \<not>x) \<Longrightarrow> P" ultimately show ?thesis by fast qed subsection \<open>Definite and indefinite description\<close> text "Combined definite and indefinite description for binary predicate" lemma some_theI: assumes EX: "\<exists>a b . P a b" and BUN: "!! b1 b2 . \<lbrakk>\<exists>a . P a b1; \<exists>a . P a b2\<rbrakk> \<Longrightarrow> b1=b2" shows "P (SOME a . \<exists>b . P a b) (THE b . \<exists>a . P a b)" proof - from EX have "\<exists>b. P (SOME a. \<exists>b. P a b) b" by (rule someI_ex) moreover from EX have "\<exists>b. \<exists>a. P a b" by blast with BUN theI'[of "\<lambda>b. \<exists>a. P a b"] have "\<exists>a. P a (THE b. \<exists>a. P a b)" by (unfold Ex1_def, blast) moreover note BUN ultimately show ?thesis by (fast) qed lemma some_insert_self[simp]: "S\<noteq>{} \<Longrightarrow> insert (SOME x. x\<in>S) S = S" by (auto intro: someI) lemma some_elem[simp]: "S\<noteq>{} \<Longrightarrow> (SOME x. x\<in>S) \<in> S" by (auto intro: someI) subsubsection\<open>Hilbert Choice with option\<close> definition Eps_Opt where "Eps_Opt P = (if (\<exists>x. P x) then Some (SOME x. P x) else None)" lemma some_opt_eq_trivial[simp] : "Eps_Opt (\<lambda>y. y = x) = Some x" unfolding Eps_Opt_def by simp lemma some_opt_sym_eq_trivial[simp] : "Eps_Opt ((=) x) = Some x" unfolding Eps_Opt_def by simp lemma some_opt_false_trivial[simp] : "Eps_Opt (\<lambda>_. False) = None" unfolding Eps_Opt_def by simp lemma Eps_Opt_eq_None[simp] : "Eps_Opt P = None \<longleftrightarrow> \<not>(Ex P)" unfolding Eps_Opt_def by simp lemma Eps_Opt_eq_Some_implies : "Eps_Opt P = Some x \<Longrightarrow> P x" unfolding Eps_Opt_def by (metis option.inject option.simps(2) someI_ex) lemma Eps_Opt_eq_Some : assumes P_prop: "\<And>x'. P x \<Longrightarrow> P x' \<Longrightarrow> x' = x" shows "Eps_Opt P = Some x \<longleftrightarrow> P x" using P_prop unfolding Eps_Opt_def by (metis option.inject option.simps(2) someI_ex) subsection \<open>Product Type\<close> lemma nested_case_prod_simp: "(\<lambda>(a,b) c. f a b c) x y = (case_prod (\<lambda>a b. f a b y) x)" by (auto split: prod.split) lemma fn_fst_conv: "(\<lambda>x. (f (fst x))) = (\<lambda>(a,_). f a)" by auto lemma fn_snd_conv: "(\<lambda>x. (f (snd x))) = (\<lambda>(_,b). f b)" by auto fun pairself where "pairself f (a,b) = (f a, f b)" lemma pairself_image_eq[simp]: "pairself f ` {(a,b). P a b} = {(f a, f b)| a b. P a b}" by force lemma pairself_image_cart[simp]: "pairself f ` (A\<times>B) = f`A \<times> f`B" by (auto simp: image_def) lemma in_prod_fst_sndI: "fst x \<in> A \<Longrightarrow> snd x \<in> B \<Longrightarrow> x\<in>A\<times>B" by (cases x) auto lemma inj_Pair[simp]: "inj_on (\<lambda>x. (x,c x)) S" "inj_on (\<lambda>x. (c x,x)) S" by (auto intro!: inj_onI) declare Product_Type.swap_inj_on[simp] lemma img_fst [intro]: assumes "(a,b) \<in> S" shows "a \<in> fst ` S" by (rule image_eqI[OF _ assms]) simp lemma img_snd [intro]: assumes "(a,b) \<in> S" shows "b \<in> snd ` S" by (rule image_eqI[OF _ assms]) simp lemma range_prod: "range f \<subseteq> (range (fst \<circ> f)) \<times> (range (snd \<circ> f))" proof fix y assume "y \<in> range f" then obtain x where y: "y = f x" by auto hence "y = (fst(f x), snd(f x))" by simp thus "y \<in> (range (fst \<circ> f)) \<times> (range (snd \<circ> f))" by (fastforce simp add: image_def) qed lemma finite_range_prod: assumes fst: "finite (range (fst \<circ> f))" and snd: "finite (range (snd \<circ> f))" shows "finite (range f)" proof - from fst snd have "finite (range (fst \<circ> f) \<times> range (snd \<circ> f))" by (rule finite_SigmaI) thus ?thesis by (rule finite_subset[OF range_prod]) qed lemma fstE: "x = (a,b) \<Longrightarrow> P (fst x) \<Longrightarrow> P a" by (metis fst_conv) lemma sndE: "x = (a,b) \<Longrightarrow> P (snd x) \<Longrightarrow> P b" by (metis snd_conv) subsubsection \<open>Uncurrying\<close> (* TODO: Move to HOL/Product_Type? Lars H: "It's equal to case_prod, should use an abbreviation"*) definition uncurry :: "('a \<Rightarrow> 'b \<Rightarrow> 'c) \<Rightarrow> 'a \<times> 'b \<Rightarrow> 'c" where "uncurry f \<equiv> \<lambda>(a,b). f a b" lemma uncurry_apply[simp]: "uncurry f (a,b) = f a b" unfolding uncurry_def by simp lemma curry_uncurry_id[simp]: "curry (uncurry f) = f" unfolding uncurry_def by simp lemma uncurry_curry_id[simp]: "uncurry (curry f) = f" unfolding uncurry_def by simp lemma do_curry: "f (a,b) = curry f a b" by simp lemma do_uncurry: "f a b = uncurry f (a,b)" by simp subsection \<open>Sum Type\<close> lemma map_sum_Inr_conv: "map_sum fl fr s = Inr y \<longleftrightarrow> (\<exists>x. s=Inr x \<and> y = fr x)" by (cases s) auto lemma map_sum_Inl_conv: "map_sum fl fr s = Inl y \<longleftrightarrow> (\<exists>x. s=Inl x \<and> y = fl x)" by (cases s) auto subsection \<open>Directed Graphs and Relations\<close> subsubsection "Reflexive-Transitive Closure" lemma r_le_rtrancl[simp]: "S\<subseteq>S\<^sup>*" by auto lemma rtrancl_mono_rightI: "S\<subseteq>S' \<Longrightarrow> S\<subseteq>S'\<^sup>*" by auto lemma trancl_sub: "R \<subseteq> R\<^sup>+" by auto lemma trancl_single[simp]: "{(a,b)}\<^sup>+ = {(a,b)}" by (auto simp: trancl_insert) text \<open>Pick first non-reflexive step\<close> lemma converse_rtranclE'[consumes 1, case_names base step]: assumes "(u,v)\<in>R\<^sup>*" obtains "u=v" | vh where "u\<noteq>vh" and "(u,vh)\<in>R" and "(vh,v)\<in>R\<^sup>*" using assms apply (induct rule: converse_rtrancl_induct) apply auto [] apply (case_tac "y=z") apply auto done lemma in_rtrancl_insert: "x\<in>R\<^sup>* \<Longrightarrow> x\<in>(insert r R)\<^sup>*" by (metis in_mono rtrancl_mono subset_insertI) lemma rtrancl_apply_insert: "R\<^sup>*``(insert x S) = insert x (R\<^sup>*``(S\<union>R``{x}))" apply (auto) apply (erule converse_rtranclE) apply auto [2] apply (erule converse_rtranclE) apply (auto intro: converse_rtrancl_into_rtrancl) [2] done text \<open>A path in a graph either does not use nodes from S at all, or it has a prefix leading to a node in S and a suffix that does not use nodes in S\<close> lemma rtrancl_last_visit[cases set, case_names no_visit last_visit_point]: shows "\<lbrakk> (q,q')\<in>R\<^sup>*; (q,q')\<in>(R-UNIV\<times>S)\<^sup>* \<Longrightarrow> P; !!qt. \<lbrakk> qt\<in>S; (q,qt)\<in>R\<^sup>+; (qt,q')\<in>(R-UNIV\<times>S)\<^sup>* \<rbrakk> \<Longrightarrow> P \<rbrakk> \<Longrightarrow> P" proof (induct rule: converse_rtrancl_induct[case_names refl step]) case refl thus ?case by auto next case (step q qh) show P proof (rule step.hyps(3)) assume A: "(qh,q')\<in>(R-UNIV\<times>S)\<^sup>*" show P proof (cases "qh\<in>S") case False with step.hyps(1) A have "(q,q')\<in>(R-UNIV\<times>S)\<^sup>*" by (auto intro: converse_rtrancl_into_rtrancl) with step.prems(1) show P . next case True from step.hyps(1) have "(q,qh)\<in>R\<^sup>+" by auto with step.prems(2) True A show P by blast qed next fix qt assume A: "qt\<in>S" "(qh,qt)\<in>R\<^sup>+" "(qt,q')\<in>(R-UNIV\<times>S)\<^sup>*" with step.hyps(1) have "(q,qt)\<in>R\<^sup>+" by auto with step.prems(2) A(1,3) show P by blast qed qed text \<open>Less general version of \<open>rtrancl_last_visit\<close>, but there's a short automatic proof\<close> lemma rtrancl_last_visit': "\<lbrakk> (q,q')\<in>R\<^sup>*; (q,q')\<in>(R-UNIV\<times>S)\<^sup>* \<Longrightarrow> P; !!qt. \<lbrakk> qt\<in>S; (q,qt)\<in>R\<^sup>*; (qt,q')\<in>(R-UNIV\<times>S)\<^sup>* \<rbrakk> \<Longrightarrow> P \<rbrakk> \<Longrightarrow> P" by (induct rule: converse_rtrancl_induct) (auto intro: converse_rtrancl_into_rtrancl) lemma rtrancl_last_visit_node: assumes "(s,s')\<in>R\<^sup>*" shows "s\<noteq>sh \<and> (s,s')\<in>(R \<inter> (UNIV \<times> (-{sh})))\<^sup>* \<or> (s,sh)\<in>R\<^sup>* \<and> (sh,s')\<in>(R \<inter> (UNIV \<times> (-{sh})))\<^sup>*" using assms proof (induct rule: converse_rtrancl_induct) case base thus ?case by auto next case (step s st) moreover { assume P: "(st,s')\<in> (R \<inter> UNIV \<times> - {sh})\<^sup>*" { assume "st=sh" with step have ?case by auto } moreover { assume "st\<noteq>sh" with \<open>(s,st)\<in>R\<close> have "(s,st)\<in>(R \<inter> UNIV \<times> - {sh})\<^sup>*" by auto also note P finally have ?case by blast } ultimately have ?case by blast } moreover { assume P: "(st, sh) \<in> R\<^sup>* \<and> (sh, s') \<in> (R \<inter> UNIV \<times> - {sh})\<^sup>*" with step(1) have ?case by (auto dest: converse_rtrancl_into_rtrancl) } ultimately show ?case by blast qed text \<open>Find last point where a path touches a set\<close> lemma rtrancl_last_touch: "\<lbrakk> (q,q')\<in>R\<^sup>*; q\<in>S; !!qt. \<lbrakk> qt\<in>S; (q,qt)\<in>R\<^sup>*; (qt,q')\<in>(R-UNIV\<times>S)\<^sup>* \<rbrakk> \<Longrightarrow> P \<rbrakk> \<Longrightarrow> P" by (erule rtrancl_last_visit') auto text \<open>A path either goes over edge once, or not at all\<close> lemma trancl_over_edgeE: assumes "(u,w)\<in>(insert (v1,v2) E)\<^sup>+" obtains "(u,w)\<in>E\<^sup>+" | "(u,v1)\<in>E\<^sup>*" and "(v2,w)\<in>E\<^sup>*" using assms proof induct case (base z) thus ?thesis by (metis insertE prod.inject r_into_trancl' rtrancl_eq_or_trancl) next case (step y z) thus ?thesis by (metis (opaque_lifting, no_types) Pair_inject insertE rtrancl.simps trancl.simps trancl_into_rtrancl) qed lemma rtrancl_image_advance: "\<lbrakk>q\<in>R\<^sup>* `` Q0; (q,x)\<in>R\<rbrakk> \<Longrightarrow> x\<in>R\<^sup>* `` Q0" by (auto intro: rtrancl_into_rtrancl) lemma trancl_image_by_rtrancl: "(E\<^sup>+)``Vi \<union> Vi = (E\<^sup>*)``Vi" by (metis Image_Id Un_Image rtrancl_trancl_reflcl) lemma reachable_mono: "\<lbrakk>R\<subseteq>R'; X\<subseteq>X'\<rbrakk> \<Longrightarrow> R\<^sup>*``X \<subseteq> R'\<^sup>*``X'" by (metis Image_mono rtrancl_mono) lemma finite_reachable_advance: "\<lbrakk> finite (E\<^sup>*``{v0}); (v0,v)\<in>E\<^sup>* \<rbrakk> \<Longrightarrow> finite (E\<^sup>*``{v})" by (erule finite_subset[rotated]) auto lemma rtrancl_mono_mp: "U\<subseteq>V \<Longrightarrow> x\<in>U\<^sup>* \<Longrightarrow> x\<in>V\<^sup>*" by (metis in_mono rtrancl_mono) lemma trancl_mono_mp: "U\<subseteq>V \<Longrightarrow> x\<in>U\<^sup>+ \<Longrightarrow> x\<in>V\<^sup>+" by (metis trancl_mono) lemma rtrancl_mapI: "(a,b)\<in>E\<^sup>* \<Longrightarrow> (f a, f b)\<in>(pairself f `E)\<^sup>*" apply (induction rule: rtrancl_induct) apply (force intro: rtrancl.intros)+ done lemma rtrancl_image_advance_rtrancl: assumes "q \<in> R\<^sup>*``Q0" assumes "(q,x) \<in> R\<^sup>*" shows "x \<in> R\<^sup>*``Q0" using assms by (metis rtrancl_idemp rtrancl_image_advance) lemma nth_step_trancl: "\<And>n m. \<lbrakk> \<And> n. n < length xs - 1 \<Longrightarrow> (xs ! Suc n, xs ! n) \<in> R \<rbrakk> \<Longrightarrow> n < length xs \<Longrightarrow> m < n \<Longrightarrow> (xs ! n, xs ! m) \<in> R\<^sup>+" proof (induction xs) case (Cons x xs) hence "\<And>n. n < length xs - 1 \<Longrightarrow> (xs ! Suc n, xs ! n) \<in> R" apply clarsimp by (metis One_nat_def diff_Suc_eq_diff_pred nth_Cons_Suc zero_less_diff) note IH = this[THEN Cons.IH] from Cons obtain n' where n': "Suc n' = n" by (cases n) blast+ show ?case proof (cases m) case "0" with Cons have "xs \<noteq> []" by auto with "0" Cons.prems(1)[of m] have "(xs ! 0, x) \<in> R" by simp moreover from IH[where m = 0] have "\<And>n. n < length xs \<Longrightarrow> n > 0 \<Longrightarrow> (xs ! n, xs ! 0) \<in> R\<^sup>+" by simp ultimately have "\<And>n. n < length xs \<Longrightarrow> (xs ! n, x) \<in> R\<^sup>+" by (metis trancl_into_trancl gr0I r_into_trancl') with Cons "0" show ?thesis by auto next case (Suc m') with Cons.prems n' have "n' < length xs" "m' < n'" by auto with IH have "(xs ! n', xs ! m') \<in> R\<^sup>+" by simp with Suc n' show ?thesis by auto qed qed simp lemma Image_empty_trancl_Image_empty: "R `` {v} = {} \<Longrightarrow> R\<^sup>+ `` {v} = {}" unfolding Image_def by (auto elim: converse_tranclE) lemma Image_empty_rtrancl_Image_id: "R `` {v} = {} \<Longrightarrow> R\<^sup>* `` {v} = {v}" unfolding Image_def by (auto elim: converse_rtranclE) lemma trans_rtrancl_eq_reflcl: "trans A \<Longrightarrow> A^* = A^=" by (simp add: rtrancl_trancl_reflcl) lemma refl_on_reflcl_Image: "refl_on B A \<Longrightarrow> C \<subseteq> B \<Longrightarrow> A^= `` C = A `` C" by (auto simp add: Image_def dest: refl_onD) lemma Image_absorb_rtrancl: "\<lbrakk> trans A; refl_on B A; C \<subseteq> B \<rbrakk> \<Longrightarrow> A^* `` C = A `` C" by (simp add: trans_rtrancl_eq_reflcl refl_on_reflcl_Image) lemma trancl_Image_unfold_left: "E\<^sup>+``S = E\<^sup>*``E``S" by (auto simp: trancl_unfold_left) lemma trancl_Image_unfold_right: "E\<^sup>+``S = E``E\<^sup>*``S" by (auto simp: trancl_unfold_right) lemma trancl_Image_advance_ss: "(u,v)\<in>E \<Longrightarrow> E\<^sup>+``{v} \<subseteq> E\<^sup>+``{u}" by auto lemma rtrancl_Image_advance_ss: "(u,v)\<in>E \<Longrightarrow> E\<^sup>*``{v} \<subseteq> E\<^sup>*``{u}" by auto (* FIXME: nicer name *) lemma trancl_union_outside: assumes "(v,w) \<in> (E\<union>U)\<^sup>+" and "(v,w) \<notin> E\<^sup>+" shows "\<exists>x y. (v,x) \<in> (E\<union>U)\<^sup>* \<and> (x,y) \<in> U \<and> (y,w) \<in> (E\<union>U)\<^sup>*" using assms proof (induction) case base thus ?case by auto next case (step w x) show ?case proof (cases "(v,w)\<in>E\<^sup>+") case True from step have "(v,w)\<in>(E\<union>U)\<^sup>*" by simp moreover from True step have "(w,x) \<in> U" by (metis Un_iff trancl.simps) moreover have "(x,x) \<in> (E\<union>U)\<^sup>*" by simp ultimately show ?thesis by blast next case False with step.IH obtain a b where "(v,a) \<in> (E\<union>U)\<^sup>*" "(a,b) \<in> U" "(b,w) \<in> (E\<union>U)\<^sup>*" by blast moreover with step have "(b,x) \<in> (E\<union>U)\<^sup>*" by (metis rtrancl_into_rtrancl) ultimately show ?thesis by blast qed qed lemma trancl_restrict_reachable: assumes "(u,v) \<in> E\<^sup>+" assumes "E``S \<subseteq> S" assumes "u\<in>S" shows "(u,v) \<in> (E\<inter>S\<times>S)\<^sup>+" using assms by (induction rule: converse_trancl_induct) (auto intro: trancl_into_trancl2) lemma rtrancl_image_unfold_right: "E``E\<^sup>*``V \<subseteq> E\<^sup>*``V" by (auto intro: rtrancl_into_rtrancl) lemma trancl_Image_in_Range: "R\<^sup>+ `` V \<subseteq> Range R" by (auto elim: trancl.induct) lemma rtrancl_Image_in_Field: "R\<^sup>* `` V \<subseteq> Field R \<union> V" proof - from trancl_Image_in_Range have "R\<^sup>+ `` V \<subseteq> Field R" unfolding Field_def by fast hence "R\<^sup>+ `` V \<union> V \<subseteq> Field R \<union> V" by blast with trancl_image_by_rtrancl show ?thesis by metis qed lemma rtrancl_sub_insert_rtrancl: "R\<^sup>* \<subseteq> (insert x R)\<^sup>*" by (auto elim: rtrancl.induct rtrancl_into_rtrancl) lemma trancl_sub_insert_trancl: "R\<^sup>+ \<subseteq> (insert x R)\<^sup>+" by (auto elim: trancl.induct trancl_into_trancl) lemma Restr_rtrancl_mono: "(v,w) \<in> (Restr E U)\<^sup>* \<Longrightarrow> (v,w) \<in> E\<^sup>*" by (metis inf_le1 rtrancl_mono subsetCE) lemma Restr_trancl_mono: "(v,w) \<in> (Restr E U)\<^sup>+ \<Longrightarrow> (v,w) \<in> E\<^sup>+" by (metis inf_le1 trancl_mono) subsubsection "Converse Relation" lemmas converse_add_simps = converse_Times trancl_converse[symmetric] converse_Un converse_Int lemma dom_ran_disj_comp[simp]: "Domain R \<inter> Range R = {} \<Longrightarrow> R O R = {}" by auto lemma below_Id_inv[simp]: "R\<inverse>\<subseteq>Id \<longleftrightarrow> R\<subseteq>Id" by (auto) subsubsection "Cyclicity" lemma cyclicE: "\<lbrakk>\<not>acyclic g; !!x. (x,x)\<in>g\<^sup>+ \<Longrightarrow> P\<rbrakk> \<Longrightarrow> P" by (unfold acyclic_def) blast lemma acyclic_insert_cyclic: "\<lbrakk>acyclic g; \<not>acyclic (insert (x,y) g)\<rbrakk> \<Longrightarrow> (y,x)\<in>g\<^sup>*" by (unfold acyclic_def) (auto simp add: trancl_insert) text \<open> This lemma makes a case distinction about a path in a graph where a couple of edges with the same endpoint have been inserted: If there is a path from a to b, then there's such a path in the original graph, or there's a path that uses an inserted edge only once. Originally, this lemma was used to reason about the graph of an updated acquisition history. Any path in this graph is either already contained in the original graph, or passes via an inserted edge. Because all the inserted edges point to the same target node, in the second case, the path can be short-circuited to use exactly one inserted edge. \<close> lemma trancl_multi_insert[cases set, case_names orig via]: "\<lbrakk> (a,b)\<in>(r\<union>X\<times>{m})\<^sup>+; (a,b)\<in>r\<^sup>+ \<Longrightarrow> P; !!x. \<lbrakk> x\<in>X; (a,x)\<in>r\<^sup>*; (m,b)\<in>r\<^sup>* \<rbrakk> \<Longrightarrow> P \<rbrakk> \<Longrightarrow> P" proof (induct arbitrary: P rule: trancl_induct) case (base b) thus ?case by auto next case (step b c) show ?case proof (rule step.hyps(3)) assume A: "(a,b)\<in>r\<^sup>+" note step.hyps(2) moreover { assume "(b,c)\<in>r" with A have "(a,c)\<in>r\<^sup>+" by auto with step.prems have P by blast } moreover { assume "b\<in>X" "c=m" with A have P by (rule_tac step.prems(2)) simp+ } ultimately show P by auto next fix x assume A: "x \<in> X" "(a, x) \<in> r\<^sup>*" "(m, b) \<in> r\<^sup>*" note step.hyps(2) moreover { assume "(b,c)\<in>r" with A(3) have "(m,c)\<in>r\<^sup>*" by auto with step.prems(2)[OF A(1,2)] have P by blast } moreover { assume "b\<in>X" "c=m" with A have P by (rule_tac step.prems(2)) simp+ } ultimately show P by auto qed qed text \<open> Version of @{thm [source] trancl_multi_insert} for inserted edges with the same startpoint. \<close> lemma trancl_multi_insert2[cases set, case_names orig via]: "\<lbrakk>(a,b)\<in>(r\<union>{m}\<times>X)\<^sup>+; (a,b)\<in>r\<^sup>+ \<Longrightarrow> P; !!x. \<lbrakk> x\<in>X; (a,m)\<in>r\<^sup>*; (x,b)\<in>r\<^sup>* \<rbrakk> \<Longrightarrow> P \<rbrakk> \<Longrightarrow> P" proof goal_cases case prems: 1 from prems(1) have "(b,a)\<in>((r\<union>{m}\<times>X)\<^sup>+)\<inverse>" by simp also have "((r\<union>{m}\<times>X)\<^sup>+)\<inverse> = (r\<inverse>\<union>X\<times>{m})\<^sup>+" by (simp add: converse_add_simps) finally have "(b, a) \<in> (r\<inverse> \<union> X \<times> {m})\<^sup>+" . thus ?case by (auto elim!: trancl_multi_insert intro: prems(2,3) simp add: trancl_converse rtrancl_converse ) qed lemma cyclic_subset: "\<lbrakk> \<not> acyclic R; R \<subseteq> S \<rbrakk> \<Longrightarrow> \<not> acyclic S" unfolding acyclic_def by (blast intro: trancl_mono) subsubsection \<open>Wellfoundedness\<close> lemma wf_min: assumes A: "wf R" "R\<noteq>{}" "!!m. m\<in>Domain R - Range R \<Longrightarrow> P" shows P proof - have H: "!!x. wf R \<Longrightarrow> \<forall>y. (x,y)\<in>R \<longrightarrow> x\<in>Domain R - Range R \<or> (\<exists>m. m\<in>Domain R - Range R)" by (erule_tac wf_induct_rule[where P="\<lambda>x. \<forall>y. (x,y)\<in>R \<longrightarrow> x\<in>Domain R - Range R \<or> (\<exists>m. m\<in>Domain R - Range R)"]) auto from A(2) obtain x y where "(x,y)\<in>R" by auto with A(1,3) H show ?thesis by blast qed lemma finite_wf_eq_wf_converse: "finite R \<Longrightarrow> wf (R\<inverse>) \<longleftrightarrow> wf R" by (metis acyclic_converse finite_acyclic_wf finite_acyclic_wf_converse wf_acyclic) \<comment> \<open>Useful lemma to show well-foundedness of some process approaching a finite upper bound\<close> lemma wf_bounded_supset: "finite S \<Longrightarrow> wf {(Q',Q). Q'\<supset>Q \<and> Q'\<subseteq> S}" proof - assume [simp]: "finite S" hence [simp]: "!!x. finite (S-x)" by auto have "{(Q',Q). Q\<subset>Q' \<and> Q'\<subseteq> S} \<subseteq> inv_image ({(s'::nat,s). s'<s}) (\<lambda>Q. card (S-Q))" proof (intro subsetI, case_tac x, simp) fix a b assume A: "b\<subset>a \<and> a\<subseteq>S" hence "S-a \<subset> S-b" by blast thus "card (S-a) < card (S-b)" by (auto simp add: psubset_card_mono) qed moreover have "wf ({(s'::nat,s). s'<s})" by (rule wf_less) ultimately show ?thesis by (blast intro: wf_inv_image wf_subset) qed lemma wf_no_path: "Domain R \<inter> Range R = {} \<Longrightarrow> wf R" apply (rule wf_no_loop) by simp text \<open>Extend a wf-relation by a break-condition\<close> definition "brk_rel R \<equiv> {((False,x),(False,y)) | x y. (x,y)\<in>R} \<union> {((True,x),(False,y)) | x y. True}" lemma brk_rel_wf[simp,intro!]: assumes WF[simp]: "wf R" shows "wf (brk_rel R)" proof - have "wf {((False,x),(False,y)) | x y. (x,y)\<in>R}" proof - have "{((False,x),(False,y)) | x y. (x,y)\<in>R} \<subseteq> inv_image R snd" by auto from wf_subset[OF wf_inv_image[OF WF] this] show ?thesis . qed moreover have "wf {((True,x),(False,y)) | x y. True}" by (rule wf_no_path) auto ultimately show ?thesis unfolding brk_rel_def apply (subst Un_commute) by (blast intro: wf_Un) qed subsubsection \<open>Restrict Relation\<close> definition rel_restrict :: "('a \<times> 'a) set \<Rightarrow> 'a set \<Rightarrow> ('a \<times> 'a) set" where "rel_restrict R A \<equiv> {(v,w). (v,w) \<in> R \<and> v \<notin> A \<and> w \<notin> A}" lemma rel_restrict_alt_def: "rel_restrict R A = R \<inter> (-A) \<times> (-A)" unfolding rel_restrict_def by auto lemma rel_restrict_empty[simp]: "rel_restrict R {} = R" by (simp add: rel_restrict_def) lemma rel_restrict_notR: assumes "(x,y) \<in> rel_restrict A R" shows "x \<notin> R" and "y \<notin> R" using assms unfolding rel_restrict_def by auto lemma rel_restrict_sub: "rel_restrict R A \<subseteq> R" unfolding rel_restrict_def by auto lemma rel_restrict_Int_empty: "A \<inter> Field R = {} \<Longrightarrow> rel_restrict R A = R" unfolding rel_restrict_def Field_def by auto lemma Domain_rel_restrict: "Domain (rel_restrict R A) \<subseteq> Domain R - A" unfolding rel_restrict_def by auto lemma Range_rel_restrict: "Range (rel_restrict R A) \<subseteq> Range R - A" unfolding rel_restrict_def by auto lemma Field_rel_restrict: "Field (rel_restrict R A) \<subseteq> Field R - A" unfolding rel_restrict_def Field_def by auto lemma rel_restrict_compl: "rel_restrict R A \<inter> rel_restrict R (-A) = {}" unfolding rel_restrict_def by auto lemma finite_rel_restrict: "finite R \<Longrightarrow> finite (rel_restrict R A)" by (metis finite_subset rel_restrict_sub) lemma R_subset_Field: "R \<subseteq> Field R \<times> Field R" unfolding Field_def by auto lemma homo_rel_restrict_mono: "R \<subseteq> B \<times> B \<Longrightarrow> rel_restrict R A \<subseteq> (B - A) \<times> (B - A)" proof - assume A: "R \<subseteq> B \<times> B" hence "Field R \<subseteq> B" unfolding Field_def by auto with Field_rel_restrict have "Field (rel_restrict R A) \<subseteq> B - A" by (metis Diff_mono order_refl order_trans) with R_subset_Field show ?thesis by blast qed lemma rel_restrict_union: "rel_restrict R (A \<union> B) = rel_restrict (rel_restrict R A) B" unfolding rel_restrict_def by auto lemma rel_restrictI: "x \<notin> R \<Longrightarrow> y \<notin> R \<Longrightarrow> (x,y) \<in> E \<Longrightarrow> (x,y) \<in> rel_restrict E R" unfolding rel_restrict_def by auto lemma rel_restrict_lift: "(x,y) \<in> rel_restrict E R \<Longrightarrow> (x,y) \<in> E" unfolding rel_restrict_def by simp lemma rel_restrict_trancl_mem: "(a,b) \<in> (rel_restrict A R)\<^sup>+ \<Longrightarrow> (a,b) \<in> rel_restrict (A\<^sup>+) R" by (induction rule: trancl_induct) (auto simp add: rel_restrict_def) lemma rel_restrict_trancl_sub: "(rel_restrict A R)\<^sup>+ \<subseteq> rel_restrict (A\<^sup>+) R" by (metis subrelI rel_restrict_trancl_mem) lemma rel_restrict_mono: "A \<subseteq> B \<Longrightarrow> rel_restrict A R \<subseteq> rel_restrict B R" unfolding rel_restrict_def by auto lemma rel_restrict_mono2: "R \<subseteq> S \<Longrightarrow> rel_restrict A S \<subseteq> rel_restrict A R" unfolding rel_restrict_def by auto lemma finite_reachable_restrictedI: assumes F: "finite Q" assumes I: "I\<subseteq>Q" assumes R: "Range E \<subseteq> Q" shows "finite (E\<^sup>*``I)" proof - from I R have "E\<^sup>*``I \<subseteq> Q" by (force elim: rtrancl.cases) also note F finally (finite_subset) show ?thesis . qed context begin private lemma rtrancl_restrictI_aux: assumes "(u,v)\<in>(E-UNIV\<times>R)\<^sup>*" assumes "u\<notin>R" shows "(u,v)\<in>(rel_restrict E R)\<^sup>* \<and> v\<notin>R" using assms by (induction) (auto simp: rel_restrict_def intro: rtrancl.intros) corollary rtrancl_restrictI: assumes "(u,v)\<in>(E-UNIV\<times>R)\<^sup>*" assumes "u\<notin>R" shows "(u,v)\<in>(rel_restrict E R)\<^sup>*" using rtrancl_restrictI_aux[OF assms] .. end lemma E_closed_restr_reach_cases: assumes P: "(u,v)\<in>E\<^sup>*" assumes CL: "E``R \<subseteq> R" obtains "v\<in>R" | "u\<notin>R" "(u,v)\<in>(rel_restrict E R)\<^sup>*" using P proof (cases rule: rtrancl_last_visit[where S=R]) case no_visit show ?thesis proof (cases "u\<in>R") case True with P have "v\<in>R" using rtrancl_reachable_induct[OF _ CL, where I="{u}"] by auto thus ?thesis .. next case False with no_visit have "(u,v)\<in>(rel_restrict E R)\<^sup>*" by (rule rtrancl_restrictI) with False show ?thesis .. qed next case (last_visit_point x) from \<open>(x, v) \<in> (E - UNIV \<times> R)\<^sup>*\<close> have "(x,v)\<in>E\<^sup>*" by (rule rtrancl_mono_mp[rotated]) auto with \<open>x\<in>R\<close> have "v\<in>R" using rtrancl_reachable_induct[OF _ CL, where I="{x}"] by auto thus ?thesis .. qed lemma rel_restrict_trancl_notR: assumes "(v,w) \<in> (rel_restrict E R)\<^sup>+" shows "v \<notin> R" and "w \<notin> R" using assms by (metis rel_restrict_trancl_mem rel_restrict_notR)+ lemma rel_restrict_tranclI: assumes "(x,y) \<in> E\<^sup>+" and "x \<notin> R" "y \<notin> R" and "E `` R \<subseteq> R" shows "(x,y) \<in> (rel_restrict E R)\<^sup>+" using assms proof (induct) case base thus ?case by (metis r_into_trancl rel_restrictI) next case (step y z) hence "y \<notin> R" by auto with step show ?case by (metis trancl_into_trancl rel_restrictI) qed subsubsection \<open>Single-Valued Relations\<close> lemma single_valued_inter1: "single_valued R \<Longrightarrow> single_valued (R\<inter>S)" by (auto intro: single_valuedI dest: single_valuedD) lemma single_valued_below_Id: "R\<subseteq>Id \<Longrightarrow> single_valued R" by (auto intro: single_valuedI) subsubsection \<open>Bijective Relations\<close> definition "bijective R \<equiv> (\<forall>x y z. (x,y)\<in>R \<and> (x,z)\<in>R \<longrightarrow> y=z) \<and> (\<forall>x y z. (x,z)\<in>R \<and> (y,z)\<in>R \<longrightarrow> x=y)" lemma bijective_alt: "bijective R \<longleftrightarrow> single_valued R \<and> single_valued (R\<inverse>)" unfolding bijective_def single_valued_def by blast lemma bijective_Id[simp, intro!]: "bijective Id" by (auto simp: bijective_def) lemma bijective_Empty[simp, intro!]: "bijective {}" by (auto simp: bijective_def) subsubsection \<open>Miscellaneous\<close> lemma pair_vimage_is_Image[simp]: "(Pair u -` E) = E``{u}" by auto lemma fst_in_Field: "fst ` R \<subseteq> Field R" by (simp add: Field_def fst_eq_Domain) lemma snd_in_Field: "snd ` R \<subseteq> Field R" by (simp add: Field_def snd_eq_Range) lemma ran_map_of: "ran (map_of xs) \<subseteq> snd ` set (xs)" by (induct xs) (auto simp add: ran_def) lemma Image_subset_snd_image: "A `` B \<subseteq> snd ` A" unfolding Image_def image_def by force lemma finite_Image_subset: "finite (A `` B) \<Longrightarrow> C \<subseteq> A \<Longrightarrow> finite (C `` B)" by (metis Image_mono order_refl rev_finite_subset) lemma finite_Field_eq_finite[simp]: "finite (Field R) \<longleftrightarrow> finite R" by (metis finite_cartesian_product finite_subset R_subset_Field finite_Field) definition "fun_of_rel R x \<equiv> SOME y. (x,y)\<in>R" lemma for_in_RI(*[intro]*): "x\<in>Domain R \<Longrightarrow> (x,fun_of_rel R x)\<in>R" unfolding fun_of_rel_def by (auto intro: someI) lemma Field_not_elem: "v \<notin> Field R \<Longrightarrow> \<forall>(x,y) \<in> R. x \<noteq> v \<and> y \<noteq> v" unfolding Field_def by auto lemma Sigma_UNIV_cancel[simp]: "(A \<times> X - A \<times> UNIV) = {}" by auto lemma same_fst_trancl[simp]: "(same_fst P R)\<^sup>+ = same_fst P (\<lambda>x. (R x)\<^sup>+)" proof - { fix x y assume "(x,y)\<in>(same_fst P R)\<^sup>+" hence "(x,y)\<in>same_fst P (\<lambda>x. (R x)\<^sup>+)" by induction (auto simp: same_fst_def) } moreover { fix f f' x y assume "((f,x),(f',y))\<in>same_fst P (\<lambda>x. (R x)\<^sup>+)" hence [simp]: "f'=f" "P f" and 1: "(x,y)\<in>(R f)\<^sup>+" by (auto simp: same_fst_def) from 1 have "((f,x),(f',y))\<in>(same_fst P R)\<^sup>+" apply induction subgoal by (rule r_into_trancl) auto subgoal by (erule trancl_into_trancl) auto done } ultimately show ?thesis by auto qed subsection \<open>\<open>option\<close> Datatype\<close> lemma not_Some_eq2[simp]: "(\<forall>x y. v \<noteq> Some (x,y)) = (v = None)" by (cases v) auto subsection "Maps" primrec the_default where "the_default _ (Some x) = x" | "the_default x None = x" declare map_add_dom_app_simps[simp] declare map_add_upd_left[simp] lemma ran_add[simp]: "dom f \<inter> dom g = {} \<Longrightarrow> ran (f++g) = ran f \<union> ran g" by (fastforce simp add: ran_def map_add_def split: option.split_asm option.split) lemma nempty_dom: "\<lbrakk>e\<noteq>Map.empty; !!m. m\<in>dom e \<Longrightarrow> P \<rbrakk> \<Longrightarrow> P" by (subgoal_tac "dom e \<noteq> {}") (blast, auto) lemma le_map_dom_mono: "m\<le>m' \<Longrightarrow> dom m \<subseteq> dom m'" apply (safe) apply (drule_tac x=x in le_funD) apply simp apply (erule le_some_optE) apply simp done lemma map_add_first_le: fixes m::"'a\<rightharpoonup>('b::order)" shows "\<lbrakk> m\<le>m' \<rbrakk> \<Longrightarrow> m++n \<le> m'++n" apply (rule le_funI) apply (auto simp add: map_add_def split: option.split elim: le_funE) done lemma map_add_distinct_le: shows "\<lbrakk> m\<le>m'; n\<le>n'; dom m' \<inter> dom n' = {} \<rbrakk> \<Longrightarrow> m++n \<le> m'++n'" apply (rule le_funI) apply (auto simp add: map_add_def split: option.split) apply (fastforce elim: le_funE) apply (drule le_map_dom_mono) apply (drule le_map_dom_mono) apply (case_tac "m x") apply simp apply (force) apply (fastforce dest!: le_map_dom_mono) apply (erule le_funE) apply (erule_tac x=x in le_funE) apply simp done lemma map_add_left_comm: assumes A: "dom A \<inter> dom B = {}" shows "A ++ (B ++ C) = B ++ (A ++ C)" proof - have "A ++ (B ++ C) = (A++B)++C" by simp also have "\<dots> = (B++A)++C" by (simp add: map_add_comm[OF A]) also have "\<dots> = B++(A++C)" by simp finally show ?thesis . qed lemmas map_add_ac = map_add_assoc map_add_comm map_add_left_comm lemma le_map_restrict[simp]: fixes m :: "'a \<rightharpoonup> ('b::order)" shows "m |` X \<le> m" by (rule le_funI) (simp add: restrict_map_def) lemma map_of_distinct_upd: "x \<notin> set (map fst xs) \<Longrightarrow> [x \<mapsto> y] ++ map_of xs = (map_of xs) (x \<mapsto> y)" by (induct xs) (auto simp add: fun_upd_twist) lemma map_of_distinct_upd2: assumes "x \<notin> set(map fst xs)" "x \<notin> set (map fst ys)" shows "map_of (xs @ (x,y) # ys) = (map_of (xs @ ys))(x \<mapsto> y)" apply(insert assms) apply(induct xs) apply (auto intro: ext) done lemma map_of_distinct_upd3: assumes "x \<notin> set(map fst xs)" "x \<notin> set (map fst ys)" shows "map_of (xs @ (x,y) # ys) = (map_of (xs @ (x,y') # ys))(x \<mapsto> y)" apply(insert assms) apply(induct xs) apply (auto intro: ext) done lemma map_of_distinct_upd4: assumes "x \<notin> set(map fst xs)" "x \<notin> set (map fst ys)" shows "map_of (xs @ ys) = (map_of (xs @ (x,y) # ys))(x := None)" using assms by (induct xs) (auto simp: map_of_eq_None_iff) lemma map_of_distinct_lookup: assumes "x \<notin> set(map fst xs)" "x \<notin> set (map fst ys)" shows "map_of (xs @ (x,y) # ys) x = Some y" proof - have "map_of (xs @ (x,y) # ys) = (map_of (xs @ ys)) (x \<mapsto> y)" using assms map_of_distinct_upd2 by simp thus ?thesis by simp qed lemma ran_distinct: assumes dist: "distinct (map fst al)" shows "ran (map_of al) = snd ` set al" using assms proof (induct al) case Nil then show ?case by simp next case (Cons kv al) then have "ran (map_of al) = snd ` set al" by simp moreover from Cons.prems have "map_of al (fst kv) = None" by (simp add: map_of_eq_None_iff) ultimately show ?case by (simp only: map_of.simps ran_map_upd) simp qed lemma ran_is_image: "ran M = (the \<circ> M) ` (dom M)" unfolding ran_def dom_def image_def by auto lemma map_card_eq_iff: assumes finite: "finite (dom M)" and card_eq: "card (dom M) = card (ran M)" and indom: "x \<in> dom M" shows "(M x = M y) \<longleftrightarrow> (x = y)" proof - from ran_is_image finite card_eq have *: "inj_on (the \<circ> M) (dom M)" using eq_card_imp_inj_on by metis thus ?thesis proof (cases "y \<in> dom M") case False with indom show ?thesis by auto next case True with indom have "the (M x) = the (M y) \<longleftrightarrow> (x = y)" using inj_on_eq_iff[OF *] by auto thus ?thesis by auto qed qed lemma map_dom_ran_finite: "finite (dom M) \<Longrightarrow> finite (ran M)" by (simp add: ran_is_image) lemma map_update_eta_repair[simp]: (* An update operation may get simplified, if it happens to be eta-expanded. This lemma tries to repair some common expressions *) "dom (\<lambda>x. if x=k then Some v else m x) = insert k (dom m)" "m k = None \<Longrightarrow> ran (\<lambda>x. if x=k then Some v else m x) = insert v (ran m)" apply auto [] apply (force simp: ran_def) done lemma map_leI[intro?]: "\<lbrakk>\<And>x v. m1 x = Some v \<Longrightarrow> m2 x = Some v\<rbrakk> \<Longrightarrow> m1\<subseteq>\<^sub>mm2" unfolding map_le_def by force lemma map_leD: "m1\<subseteq>\<^sub>mm2 \<Longrightarrow> m1 k = Some v \<Longrightarrow> m2 k = Some v" unfolding map_le_def by force lemma map_restrict_insert_none_simp: "m x = None \<Longrightarrow> m|`(-insert x s) = m|`(-s)" by (auto intro!: ext simp:restrict_map_def) (* TODO: Move *) lemma eq_f_restr_conv: "s\<subseteq>dom (f A) \<and> A = f A |` (-s) \<longleftrightarrow> A \<subseteq>\<^sub>m f A \<and> s = dom (f A) - dom A" apply auto subgoal by (metis map_leI restrict_map_eq(2)) subgoal by (metis ComplD restrict_map_eq(2)) subgoal by (metis Compl_iff restrict_in) subgoal by (force simp: map_le_def restrict_map_def) done corollary eq_f_restr_ss_eq: "\<lbrakk> s\<subseteq>dom (f A) \<rbrakk> \<Longrightarrow> A = f A |` (-s) \<longleftrightarrow> A \<subseteq>\<^sub>m f A \<and> s = dom (f A) - dom A" using eq_f_restr_conv by blast subsubsection \<open>Simultaneous Map Update\<close> definition "map_mmupd m K v k \<equiv> if k\<in>K then Some v else m k" lemma map_mmupd_empty[simp]: "map_mmupd m {} v = m" by (auto simp: map_mmupd_def) lemma mmupd_in_upd[simp]: "k\<in>K \<Longrightarrow> map_mmupd m K v k = Some v" by (auto simp: map_mmupd_def) lemma mmupd_notin_upd[simp]: "k\<notin>K \<Longrightarrow> map_mmupd m K v k = m k" by (auto simp: map_mmupd_def) lemma map_mmupdE: assumes "map_mmupd m K v k = Some x" obtains "k\<notin>K" "m k = Some x" | "k\<in>K" "x=v" using assms by (auto simp: map_mmupd_def split: if_split_asm) lemma dom_mmupd[simp]: "dom (map_mmupd m K v) = dom m \<union> K" by (auto simp: map_mmupd_def split: if_split_asm) lemma le_map_mmupd_not_dom[simp, intro!]: "m \<subseteq>\<^sub>m map_mmupd m (K-dom m) v" by (auto simp: map_le_def) lemma map_mmupd_update_less: "K\<subseteq>K' \<Longrightarrow> map_mmupd m (K - dom m) v \<subseteq>\<^sub>m map_mmupd m (K'-dom m) v" by (auto simp: map_le_def map_mmupd_def) subsection\<open>Connection between Maps and Sets of Key-Value Pairs\<close> definition map_to_set where "map_to_set m = {(k, v) . m k = Some v}" definition set_to_map where "set_to_map S k = Eps_Opt (\<lambda>v. (k, v) \<in> S)" lemma set_to_map_simp : assumes inj_on_fst: "inj_on fst S" shows "(set_to_map S k = Some v) \<longleftrightarrow> (k, v) \<in> S" proof (cases "\<exists>v. (k, v) \<in> S") case True note kv_ex = this then obtain v' where kv'_in: "(k, v') \<in> S" by blast with inj_on_fst have kv''_in: "\<And>v''. (k, v'') \<in> S \<longleftrightarrow> v' = v''" unfolding inj_on_def Ball_def by auto show ?thesis unfolding set_to_map_def by (simp add: kv_ex kv''_in) next case False hence kv''_nin: "\<And>v''. (k, v'') \<notin> S" by simp thus ?thesis by (simp add: set_to_map_def) qed lemma inj_on_fst_map_to_set : "inj_on fst (map_to_set m)" unfolding map_to_set_def inj_on_def by simp lemma map_to_set_inverse : "set_to_map (map_to_set m) = m" proof fix k show "set_to_map (map_to_set m) k = m k" proof (cases "m k") case None note mk_eq = this hence "\<And>v. (k, v) \<notin> map_to_set m" unfolding map_to_set_def by simp with set_to_map_simp [OF inj_on_fst_map_to_set, of m k] show ?thesis unfolding mk_eq by auto next case (Some v) note mk_eq = this hence "(k, v) \<in> map_to_set m" unfolding map_to_set_def by simp with set_to_map_simp [OF inj_on_fst_map_to_set, of m k v] show ?thesis unfolding mk_eq by auto qed qed lemma set_to_map_inverse : assumes inj_on_fst_S: "inj_on fst S" shows "map_to_set (set_to_map S) = S" proof (rule set_eqI) fix kv from set_to_map_simp [OF inj_on_fst_S, of "fst kv" "snd kv"] show "(kv \<in> map_to_set (set_to_map S)) = (kv \<in> S)" unfolding map_to_set_def by auto qed lemma map_to_set_empty[simp]: "map_to_set Map.empty = {}" unfolding map_to_set_def by simp lemma map_to_set_empty_iff: "map_to_set m = {} \<longleftrightarrow> m = Map.empty" "{} = map_to_set m \<longleftrightarrow> m = Map.empty" unfolding map_to_set_def by auto lemma set_to_map_empty_iff: "set_to_map S = Map.empty \<longleftrightarrow> S = {}" (is ?T1) "Map.empty = set_to_map S \<longleftrightarrow> S = {}" (is ?T2) proof - show T1: ?T1 apply (simp only: set_eq_iff) apply (simp only: fun_eq_iff) apply (simp add: set_to_map_def) apply auto done from T1 show ?T2 by auto qed lemma map_to_set_upd[simp]: "map_to_set (m (k \<mapsto> v)) = insert (k, v) (map_to_set m - {(k, v') |v'. True})" unfolding map_to_set_def apply (simp add: set_eq_iff) apply metis done lemma set_to_map_insert: assumes k_nin: "fst kv \<notin> fst ` S" shows "set_to_map (insert kv S) = (set_to_map S) (fst kv \<mapsto> snd kv)" proof fix k' obtain k v where kv_eq[simp]: "kv = (k, v)" by (rule prod.exhaust) from k_nin have k_nin': "\<And>v'. (k, v') \<notin> S" by (auto simp add: image_iff Ball_def) show "set_to_map (insert kv S) k' = ((set_to_map S)(fst kv \<mapsto> snd kv)) k'" by (simp add: set_to_map_def k_nin') qed lemma map_to_set_dom : "dom m = fst ` (map_to_set m)" unfolding dom_def map_to_set_def by (auto simp add: image_iff) lemma map_to_set_ran : "ran m = snd ` (map_to_set m)" unfolding ran_def map_to_set_def by (auto simp add: image_iff) lemma set_to_map_dom : "dom (set_to_map S) = fst ` S" unfolding set_to_map_def[abs_def] dom_def by (auto simp add: image_iff Bex_def) lemma set_to_map_ran : "ran (set_to_map S) \<subseteq> snd ` S" unfolding set_to_map_def[abs_def] ran_def subset_iff by (auto simp add: image_iff Bex_def) (metis Eps_Opt_eq_Some) lemma finite_map_to_set: "finite (map_to_set m) = finite (dom m)" unfolding map_to_set_def map_to_set_dom apply (intro iffI finite_imageI) apply assumption apply (rule finite_imageD[of fst]) apply assumption apply (simp add: inj_on_def) done lemma card_map_to_set : "card (map_to_set m) = card (dom m)" unfolding map_to_set_def map_to_set_dom apply (rule card_image[symmetric]) apply (simp add: inj_on_def) done lemma map_of_map_to_set : "distinct (map fst l) \<Longrightarrow> map_of l = m \<longleftrightarrow> set l = map_to_set m" proof (induct l arbitrary: m) case Nil thus ?case by (simp add: map_to_set_empty_iff) blast next case (Cons kv l m) obtain k v where kv_eq[simp]: "kv = (k, v)" by (rule prod.exhaust) from Cons(2) have dist_l: "distinct (map fst l)" and kv'_nin: "\<And>v'. (k, v') \<notin> set l" by (auto simp add: image_iff) note ind_hyp = Cons(1)[OF dist_l] from kv'_nin have l_eq: "set (kv # l) = map_to_set m \<longleftrightarrow> (set l = map_to_set (m (k := None))) \<and> m k = Some v" apply (simp add: map_to_set_def restrict_map_def set_eq_iff) apply (auto) apply (metis) apply (metis option.inject) done from kv'_nin have m_eq: "map_of (kv # l) = m \<longleftrightarrow> map_of l = (m (k := None)) \<and> m k = Some v" apply (simp add: fun_eq_iff restrict_map_def map_of_eq_None_iff image_iff Ball_def) apply metis done show ?case unfolding m_eq l_eq using ind_hyp[of "m (k := None)"] by metis qed lemma map_to_set_map_of : "distinct (map fst l) \<Longrightarrow> map_to_set (map_of l) = set l" by (metis map_of_map_to_set) subsubsection \<open>Mapping empty set to None\<close> definition "dflt_None_set S \<equiv> if S={} then None else Some S" lemma the_dflt_None_empty[simp]: "dflt_None_set {} = None" unfolding dflt_None_set_def by simp lemma the_dflt_None_nonempty[simp]: "S\<noteq>{} \<Longrightarrow> dflt_None_set S = Some S" unfolding dflt_None_set_def by simp lemma the_dflt_None_set[simp]: "the_default {} (dflt_None_set x) = x" unfolding dflt_None_set_def by auto subsection \<open>Orderings\<close> lemma (in order) min_arg_le[simp]: "n \<le> min m n \<longleftrightarrow> min m n = n" "m \<le> min m n \<longleftrightarrow> min m n = m" by (auto simp: min_def) lemma (in linorder) min_arg_not_ge[simp]: "\<not> min m n < m \<longleftrightarrow> min m n = m" "\<not> min m n < n \<longleftrightarrow> min m n = n" by (auto simp: min_def) lemma (in linorder) min_eq_arg[simp]: "min m n = m \<longleftrightarrow> m\<le>n" "min m n = n \<longleftrightarrow> n\<le>m" by (auto simp: min_def) lemma min_simps[simp]: "a<(b::'a::order) \<Longrightarrow> min a b = a" "b<(a::'a::order) \<Longrightarrow> min a b = b" by (auto simp add: min_def dest: less_imp_le) lemma (in -) min_less_self_conv[simp]: "min a b < a \<longleftrightarrow> b < (a::_::linorder)" "min a b < b \<longleftrightarrow> a < (b::_::linorder)" by (auto simp: min_def) lemma ord_eq_le_eq_trans: "\<lbrakk> a=b; b\<le>c; c=d \<rbrakk> \<Longrightarrow> a\<le>d" by auto lemma zero_comp_diff_simps[simp]: "(0::'a::linordered_idom) \<le> a - b \<longleftrightarrow> b \<le> a" "(0::'a::linordered_idom) < a - b \<longleftrightarrow> b < a" by auto subsubsection \<open>Termination Measures\<close> text \<open>Lexicographic measure, assuming upper bound for second component\<close> lemma mlex_fst_decrI: fixes a a' b b' N :: nat assumes "a<a'" assumes "b<N" "b'<N" shows "a*N + b < a'*N + b'" proof - have "a*N + b + 1 \<le> a*N + N" using \<open>b<N\<close> by linarith also have "\<dots> \<le> a'*N" using \<open>a<a'\<close> by (metis Suc_leI ab_semigroup_add_class.add.commute ab_semigroup_mult_class.mult.commute mult_Suc_right mult_le_mono2) also have "\<dots> \<le> a'*N + b'" by auto finally show ?thesis by auto qed lemma mlex_bound: fixes a b :: nat assumes "a<A" assumes "b<N" shows "a*N + b < A*N" using assms using mlex_fst_decrI by fastforce subsection \<open>CCPOs\<close> context ccpo begin lemma ccpo_Sup_mono: assumes C: "Complete_Partial_Order.chain (\<le>) A" "Complete_Partial_Order.chain (\<le>) B" assumes B: "\<forall>x\<in>A. \<exists>y\<in>B. x\<le>y" shows "Sup A \<le> Sup B" proof (rule ccpo_Sup_least) fix x assume "x\<in>A" with B obtain y where I: "y\<in>B" and L: "x\<le>y" by blast note L also from I ccpo_Sup_upper have "y\<le>Sup B" by (blast intro: C) finally show "x\<le>Sup B" . qed (rule C) lemma fixp_mono: assumes M: "monotone (\<le>) (\<le>) f" "monotone (\<le>) (\<le>) g" assumes LE: "\<And>Z. f Z \<le> g Z" shows "ccpo_class.fixp f \<le> ccpo_class.fixp g" unfolding fixp_def[abs_def] apply (rule ccpo_Sup_mono) apply (rule chain_iterates M)+ proof rule fix x assume "x\<in>ccpo_class.iterates f" thus "\<exists>y\<in>ccpo_class.iterates g. x\<le>y" proof (induct) case (step x) then obtain y where I: "y\<in>ccpo_class.iterates g" and L: "x\<le>y" by blast hence "g y \<in> ccpo_class.iterates g" and "f x \<le> g y" apply - apply (erule iterates.step) apply (rule order_trans) apply (erule monotoneD[OF M(1)]) apply (rule LE) done thus "\<exists>y\<in>ccpo_class.iterates g. f x \<le> y" .. next case (Sup M) define N where "N = {SOME y. y\<in>ccpo_class.iterates g \<and> x\<le>y | x. x\<in>M}" have N1: "\<forall>y\<in>N. y\<in>ccpo_class.iterates g \<and> (\<exists>x\<in>M. x\<le>y)" unfolding N_def apply auto apply (metis (lifting) Sup.hyps(2) tfl_some) by (metis (lifting) Sup.hyps(2) tfl_some) have N2: "\<forall>x\<in>M. \<exists>y\<in>N. x\<le>y" unfolding N_def apply auto by (metis (lifting) Sup.hyps(2) tfl_some) have "N \<subseteq> ccpo_class.iterates g" using Sup using N1 by auto hence C_chain: "Complete_Partial_Order.chain (\<le>) N" using chain_iterates[OF M(2)] unfolding chain_def by auto have "Sup N \<in> ccpo_class.iterates g" and "Sup M \<le> Sup N" apply - apply (rule iterates.Sup[OF C_chain]) using N1 apply blast apply (rule ccpo_Sup_mono) apply (rule Sup.hyps) apply (rule C_chain) apply (rule N2) done thus ?case by blast qed qed end subsection \<open>Code\<close> text \<open>Constant for code-abort. If that gets executed, an abort-exception is raised.\<close> definition [simp]: "CODE_ABORT f = f ()" declare [[code abort: CODE_ABORT]] end
Last Thursday night, the Blue Jeans Mile record books were re-written at the CITIUS MAG x Lost Boys Track Club Blue Jeans Mile at the East River Park track in New York City. Spencer Brown, best known for his accomplishments as a middle distance runner for Georgetown or his Youtube channel “The Athlete Special”, ran a men’s world record time of 4:16.63 to win the final race of the night. Jackie Katzman, a runner from Cornell, led three women under the previous women’s world record with her 5:29.30 in the first race of the night. The previous official world record of 4:34.3 was ran by Pierce Flanders in Topeka, Kansas. Last Thursday morning, an unofficial world record of 4:19 was run by Sean Keveren in Nashville, Tennessee but it was later determined that his jeans did not comply with the 100% cotton or denim regulation that we initially set forth in our introduction to the event. We recognized the time but put an asterisk next to it. Jackie Katzman finished fifth overall in the first section of the race but became the first woman to run under 5:30 with her 5:29.13. Leigh Anne Sharek crosse the finish line just a second behind her in 5:30.87. Lena Placzek ran 5:1.25 to also get under Anna Saats’ previous world record of 5:56.56. It was a great time. Lots of laughs were shared. This really escalated into something much bigger than we ever imagined. The next big attempt will come from Utah on Monday morning as NCAA 10K runner-up Rory Linkletter attempts his own blue jean mile on BYU’s track. On Friday night, the Sir Walter Miler will host its own blue jeans mile in collaboration with us and the good folks at Raleigh Denim. More information on that race can be found at the end of this post. For an inside look at Spencer Brown’s day and lead-up to the world record, check out the latest episode of The Athlete Special. For more information on racing the Blue Jeans Mile at Sir Walter Miler, check here.
{-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE AllowAmbiguousTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE RoleAnnotations #-} {-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE Trustworthy #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE CPP #-} #if __GLASGOW_HASKELL__ >= 800 {-# LANGUAGE UndecidableSuperClasses #-} #endif #if __GLASGOW_HASKELL__ >= 708 && __GLASGOW_HASKELL__ < 710 {-# LANGUAGE NullaryTypeClasses #-} #endif ----------------------------------------------------------------------------- -- | -- Module : Data.Constraint -- Copyright : (C) 2011-2015 Edward Kmett, -- License : BSD-style (see the file LICENSE) -- -- Maintainer : Edward Kmett <[email protected]> -- Stability : experimental -- Portability : non-portable -- -- @ConstraintKinds@ made type classes into types of a new kind, @Constraint@. -- -- @ -- 'Eq' :: * -> 'Constraint' -- 'Ord' :: * -> 'Constraint' -- 'Monad' :: (* -> *) -> 'Constraint' -- @ -- -- The need for this extension was first publicized in the paper -- -- <http://research.microsoft.com/pubs/67439/gmap3.pdf Scrap your boilerplate with class: extensible generic functions> -- -- by Ralf Lämmel and Simon Peyton Jones in 2005, which shoehorned all the -- things they needed into a custom 'Sat' typeclass. -- -- With @ConstraintKinds@ we can put into code a lot of tools for manipulating -- these new types without such awkward workarounds. ---------------------------------------------------------------------------- module Data.Constraint ( -- * The Kind of Constraints Constraint -- * Dictionary , Dict(Dict) , withDict -- * Entailment , (:-)(Sub) , (\\) , weaken1, weaken2, contract , strengthen1, strengthen2 , (&&&), (***) , trans, refl , Bottom(no) , top, bottom -- * Dict is fully faithful , mapDict , unmapDict -- * Reflection , Class(..) , (:=>)(..) ) where import Control.Applicative import Control.Category import Control.DeepSeq import Control.Monad import Data.Complex import Data.Ratio import Data.Semigroup import Data.Data import qualified GHC.Exts as Exts (Any) import GHC.Exts (Constraint) import Data.Bits (Bits) import Data.Functor.Identity (Identity) #if MIN_VERSION_base(4,8,0) import Numeric.Natural (Natural) #endif #if !MIN_VERSION_base(4,8,0) import Data.Word (Word) #endif -- | Values of type @'Dict' p@ capture a dictionary for a constraint of type @p@. -- -- e.g. -- -- @ -- 'Dict' :: 'Dict' ('Eq' 'Int') -- @ -- -- captures a dictionary that proves we have an: -- -- @ -- instance 'Eq' 'Int -- @ -- -- Pattern matching on the 'Dict' constructor will bring this instance into scope. -- data Dict :: Constraint -> * where Dict :: a => Dict a deriving Typeable instance (Typeable p, p) => Data (Dict p) where gfoldl _ z Dict = z Dict toConstr _ = dictConstr gunfold _ z c = case constrIndex c of 1 -> z Dict _ -> error "gunfold" dataTypeOf _ = dictDataType dictConstr :: Constr dictConstr = mkConstr dictDataType "Dict" [] Prefix dictDataType :: DataType dictDataType = mkDataType "Data.Constraint.Dict" [dictConstr] deriving instance Eq (Dict a) deriving instance Ord (Dict a) deriving instance Show (Dict a) instance NFData (Dict c) where rnf Dict = () -- | From a 'Dict', takes a value in an environment where the instance -- witnessed by the 'Dict' is in scope, and evaluates it. -- -- Essentially a deconstruction of a 'Dict' into its continuation-style -- form. -- withDict :: Dict a -> (a => r) -> r withDict d r = case d of Dict -> r infixr 9 :- -- | This is the type of entailment. -- -- @a ':-' b@ is read as @a@ \"entails\" @b@. -- -- With this we can actually build a category for 'Constraint' resolution. -- -- e.g. -- -- Because @'Eq' a@ is a superclass of @'Ord' a@, we can show that @'Ord' a@ -- entails @'Eq' a@. -- -- Because @instance 'Ord' a => 'Ord' [a]@ exists, we can show that @'Ord' a@ -- entails @'Ord' [a]@ as well. -- -- This relationship is captured in the ':-' entailment type here. -- -- Since @p ':-' p@ and entailment composes, ':-' forms the arrows of a -- 'Category' of constraints. However, 'Category' only became sufficiently -- general to support this instance in GHC 7.8, so prior to 7.8 this instance -- is unavailable. -- -- But due to the coherence of instance resolution in Haskell, this 'Category' -- has some very interesting properties. Notably, in the absence of -- @IncoherentInstances@, this category is \"thin\", which is to say that -- between any two objects (constraints) there is at most one distinguishable -- arrow. -- -- This means that for instance, even though there are two ways to derive -- @'Ord' a ':-' 'Eq' [a]@, the answers from these two paths _must_ by -- construction be equal. This is a property that Haskell offers that is -- pretty much unique in the space of languages with things they call \"type -- classes\". -- -- What are the two ways? -- -- Well, we can go from @'Ord' a ':-' 'Eq' a@ via the -- superclass relationship, and then from @'Eq' a ':-' 'Eq' [a]@ via the -- instance, or we can go from @'Ord' a ':-' 'Ord' [a]@ via the instance -- then from @'Ord' [a] ':-' 'Eq' [a]@ through the superclass relationship -- and this diagram by definition must \"commute\". -- -- Diagrammatically, -- -- > Ord a -- > ins / \ cls -- > v v -- > Ord [a] Eq a -- > cls \ / ins -- > v v -- > Eq [a] -- -- This safety net ensures that pretty much anything you can write with this -- library is sensible and can't break any assumptions on the behalf of -- library authors. newtype a :- b = Sub (a => Dict b) deriving Typeable type role (:-) nominal nominal -- TODO: _proper_ Data for @(p ':-' q)@ requires @(:-)@ to be cartesian _closed_. -- -- This is admissable, but not present by default -- constraint should be instance (Typeable p, Typeable q, p |- q) => Data (p :- q) instance (Typeable p, Typeable q, p, q) => Data (p :- q) where gfoldl _ z (Sub Dict) = z (Sub Dict) toConstr _ = subConstr gunfold _ z c = case constrIndex c of 1 -> z (Sub Dict) _ -> error "gunfold" dataTypeOf _ = subDataType subConstr :: Constr subConstr = mkConstr dictDataType "Sub" [] Prefix subDataType :: DataType subDataType = mkDataType "Data.Constraint.:-" [subConstr] -- | Possible since GHC 7.8, when 'Category' was made polykinded. instance Category (:-) where id = refl (.) = trans -- | Assumes 'IncoherentInstances' doesn't exist. instance Eq (a :- b) where _ == _ = True -- | Assumes 'IncoherentInstances' doesn't exist. instance Ord (a :- b) where compare _ _ = EQ instance Show (a :- b) where showsPrec d _ = showParen (d > 10) $ showString "Sub Dict" instance a => NFData (a :- b) where rnf (Sub Dict) = () infixl 1 \\ -- required comment -- | Given that @a :- b@, derive something that needs a context @b@, using the context @a@ (\\) :: a => (b => r) -> (a :- b) -> r r \\ Sub Dict = r -------------------------------------------------------------------------------- -- Constraints form a Category -------------------------------------------------------------------------------- -- | Transitivity of entailment -- -- If we view @(':-')@ as a Constraint-indexed category, then this is @('.')@ trans :: (b :- c) -> (a :- b) -> a :- c trans f g = Sub $ Dict \\ f \\ g -- | Reflexivity of entailment -- -- If we view @(':-')@ as a Constraint-indexed category, then this is 'id' refl :: a :- a refl = Sub Dict -------------------------------------------------------------------------------- -- (,) is a Bifunctor -------------------------------------------------------------------------------- -- | due to the hack for the kind of @(,)@ in the current version of GHC we can't actually -- make instances for @(,) :: Constraint -> Constraint -> Constraint@, but @(,)@ is a -- bifunctor on the category of constraints. This lets us map over both sides. (***) :: (a :- b) -> (c :- d) -> (a, c) :- (b, d) f *** g = Sub $ Dict \\ f \\ g -------------------------------------------------------------------------------- -- Constraints are Cartesian -------------------------------------------------------------------------------- -- | Weakening a constraint product -- -- The category of constraints is Cartesian. We can forget information. weaken1 :: (a, b) :- a weaken1 = Sub Dict -- | Weakening a constraint product -- -- The category of constraints is Cartesian. We can forget information. weaken2 :: (a, b) :- b weaken2 = Sub Dict strengthen1 :: Dict b -> a :- c -> a :- (b,c) strengthen1 d e = unmapDict (const d) &&& e strengthen2 :: Dict b -> a :- c -> a :- (c,b) strengthen2 d e = e &&& unmapDict (const d) -- | Contracting a constraint / diagonal morphism -- -- The category of constraints is Cartesian. We can reuse information. contract :: a :- (a, a) contract = Sub Dict -- | Constraint product -- -- > trans weaken1 (f &&& g) = f -- > trans weaken2 (f &&& g) = g (&&&) :: (a :- b) -> (a :- c) -> a :- (b, c) f &&& g = Sub $ Dict \\ f \\ g -------------------------------------------------------------------------------- -- Initial and terminal morphisms -------------------------------------------------------------------------------- -- | Every constraint implies truth -- -- These are the terminal arrows of the category, and @()@ is the terminal object. -- -- Given any constraint there is a unique entailment of the @()@ constraint from that constraint. top :: a :- () top = Sub Dict -- | 'Any' inhabits every kind, including 'Constraint' but is uninhabited, making it impossible to define an instance. class Exts.Any => Bottom where no :: a -- | -- This demonstrates the law of classical logic <http://en.wikipedia.org/wiki/Principle_of_explosion "ex falso quodlibet"> bottom :: Bottom :- a bottom = Sub no -------------------------------------------------------------------------------- -- Dict is fully faithful -------------------------------------------------------------------------------- -- | Apply an entailment to a dictionary. -- -- From a category theoretic perspective 'Dict' is a functor that maps from the category -- of constraints (with arrows in ':-') to the category Hask of Haskell data types. mapDict :: (a :- b) -> Dict a -> Dict b mapDict p Dict = case p of Sub q -> q -- | -- This functor is fully faithful, which is to say that given any function you can write -- @Dict a -> Dict b@ there also exists an entailment @a :- b@ in the category of constraints -- that you can build. unmapDict :: (Dict a -> Dict b) -> a :- b unmapDict f = Sub (f Dict) type role Dict nominal -------------------------------------------------------------------------------- -- Reflection -------------------------------------------------------------------------------- -- | Reify the relationship between a class and its superclass constraints as a class -- -- Given a definition such as -- -- @ -- class Foo a => Bar a -- @ -- -- you can capture the relationship between 'Bar a' and its superclass 'Foo a' with -- -- @ -- instance 'Class' (Foo a) (Bar a) where 'cls' = 'Sub' 'Dict' -- @ -- -- Now the user can use 'cls :: Bar a :- Foo a' class Class b h | h -> b where cls :: h :- b infixr 9 :=> -- | Reify the relationship between an instance head and its body as a class -- -- Given a definition such as -- -- @ -- instance Foo a => Foo [a] -- @ -- -- you can capture the relationship between the instance head and its body with -- -- @ -- instance Foo a ':=>' Foo [a] where 'ins' = 'Sub' 'Dict' -- @ class b :=> h | h -> b where ins :: b :- h -- Bootstrapping instance Class () (Class b a) where cls = Sub Dict instance Class () (b :=> a) where cls = Sub Dict instance Class b a => () :=> Class b a where ins = Sub Dict instance (b :=> a) => () :=> (b :=> a) where ins = Sub Dict instance Class () () where cls = Sub Dict instance () :=> () where ins = Sub Dict -- Local, Prelude, Applicative, C.M.I and Data.Monoid instances -- Eq instance Class () (Eq a) where cls = Sub Dict instance () :=> Eq () where ins = Sub Dict instance () :=> Eq Int where ins = Sub Dict instance () :=> Eq Bool where ins = Sub Dict instance () :=> Eq Integer where ins = Sub Dict instance () :=> Eq Float where ins = Sub Dict instance () :=> Eq Double where ins = Sub Dict instance Eq a :=> Eq [a] where ins = Sub Dict instance Eq a :=> Eq (Maybe a) where ins = Sub Dict instance Eq a :=> Eq (Complex a) where ins = Sub Dict instance Eq a :=> Eq (Ratio a) where ins = Sub Dict instance (Eq a, Eq b) :=> Eq (a, b) where ins = Sub Dict instance (Eq a, Eq b) :=> Eq (Either a b) where ins = Sub Dict instance () :=> Eq (Dict a) where ins = Sub Dict instance () :=> Eq (a :- b) where ins = Sub Dict instance () :=> Eq Word where ins = Sub Dict instance Eq a :=> Eq (Identity a) where ins = Sub Dict #if MIN_VERSION_base(4,8,0) instance Eq a :=> Eq (Const a b) where ins = Sub Dict instance () :=> Eq Natural where ins = Sub Dict #endif -- Ord instance Class (Eq a) (Ord a) where cls = Sub Dict instance () :=> Ord () where ins = Sub Dict instance () :=> Ord Bool where ins = Sub Dict instance () :=> Ord Int where ins = Sub Dict instance ():=> Ord Integer where ins = Sub Dict instance () :=> Ord Float where ins = Sub Dict instance ():=> Ord Double where ins = Sub Dict instance () :=> Ord Char where ins = Sub Dict instance Ord a :=> Ord (Maybe a) where ins = Sub Dict instance Ord a :=> Ord [a] where ins = Sub Dict instance (Ord a, Ord b) :=> Ord (a, b) where ins = Sub Dict instance (Ord a, Ord b) :=> Ord (Either a b) where ins = Sub Dict instance Integral a :=> Ord (Ratio a) where ins = Sub Dict instance () :=> Ord (Dict a) where ins = Sub Dict instance () :=> Ord (a :- b) where ins = Sub Dict instance () :=> Ord Word where ins = Sub Dict instance Ord a :=> Ord (Identity a) where ins = Sub Dict #if MIN_VERSION_base(4,8,0) instance Ord a :=> Ord (Const a b) where ins = Sub Dict instance () :=> Ord Natural where ins = Sub Dict #endif -- Show instance Class () (Show a) where cls = Sub Dict instance () :=> Show () where ins = Sub Dict instance () :=> Show Bool where ins = Sub Dict instance () :=> Show Ordering where ins = Sub Dict instance () :=> Show Char where ins = Sub Dict instance () :=> Show Int where ins = Sub Dict instance Show a :=> Show (Complex a) where ins = Sub Dict instance Show a :=> Show [a] where ins = Sub Dict instance Show a :=> Show (Maybe a) where ins = Sub Dict instance (Show a, Show b) :=> Show (a, b) where ins = Sub Dict instance (Show a, Show b) :=> Show (Either a b) where ins = Sub Dict instance (Integral a, Show a) :=> Show (Ratio a) where ins = Sub Dict instance () :=> Show (Dict a) where ins = Sub Dict instance () :=> Show (a :- b) where ins = Sub Dict instance () :=> Show Word where ins = Sub Dict instance Show a :=> Show (Identity a) where ins = Sub Dict #if MIN_VERSION_base(4,8,0) instance Show a :=> Show (Const a b) where ins = Sub Dict instance () :=> Show Natural where ins = Sub Dict #endif -- Read instance Class () (Read a) where cls = Sub Dict instance () :=> Read () where ins = Sub Dict instance () :=> Read Bool where ins = Sub Dict instance () :=> Read Ordering where ins = Sub Dict instance () :=> Read Char where ins = Sub Dict instance () :=> Read Int where ins = Sub Dict instance Read a :=> Read (Complex a) where ins = Sub Dict instance Read a :=> Read [a] where ins = Sub Dict instance Read a :=> Read (Maybe a) where ins = Sub Dict instance (Read a, Read b) :=> Read (a, b) where ins = Sub Dict instance (Read a, Read b) :=> Read (Either a b) where ins = Sub Dict instance (Integral a, Read a) :=> Read (Ratio a) where ins = Sub Dict instance () :=> Read Word where ins = Sub Dict instance Read a :=> Read (Identity a) where ins = Sub Dict #if MIN_VERSION_base(4,8,0) instance Read a :=> Read (Const a b) where ins = Sub Dict instance () :=> Read Natural where ins = Sub Dict #endif -- Enum instance Class () (Enum a) where cls = Sub Dict instance () :=> Enum () where ins = Sub Dict instance () :=> Enum Bool where ins = Sub Dict instance () :=> Enum Ordering where ins = Sub Dict instance () :=> Enum Char where ins = Sub Dict instance () :=> Enum Int where ins = Sub Dict instance () :=> Enum Integer where ins = Sub Dict instance () :=> Enum Float where ins = Sub Dict instance () :=> Enum Double where ins = Sub Dict instance Integral a :=> Enum (Ratio a) where ins = Sub Dict instance () :=> Enum Word where ins = Sub Dict #if MIN_VERSION_base(4,9,0) instance Enum a :=> Enum (Identity a) where ins = Sub Dict instance Enum a :=> Enum (Const a b) where ins = Sub Dict #endif #if MIN_VERSION_base(4,8,0) instance () :=> Enum Natural where ins = Sub Dict #endif -- Bounded instance Class () (Bounded a) where cls = Sub Dict instance () :=> Bounded () where ins = Sub Dict instance () :=> Bounded Ordering where ins = Sub Dict instance () :=> Bounded Bool where ins = Sub Dict instance () :=> Bounded Int where ins = Sub Dict instance () :=> Bounded Char where ins = Sub Dict instance (Bounded a, Bounded b) :=> Bounded (a,b) where ins = Sub Dict instance () :=> Bounded Word where ins = Sub Dict #if MIN_VERSION_base(4,9,0) instance Bounded a :=> Bounded (Identity a) where ins = Sub Dict instance Bounded a :=> Bounded (Const a b) where ins = Sub Dict #endif -- Num instance Class () (Num a) where cls = Sub Dict instance () :=> Num Int where ins = Sub Dict instance () :=> Num Integer where ins = Sub Dict instance () :=> Num Float where ins = Sub Dict instance () :=> Num Double where ins = Sub Dict instance RealFloat a :=> Num (Complex a) where ins = Sub Dict instance Integral a :=> Num (Ratio a) where ins = Sub Dict instance () :=> Num Word where ins = Sub Dict #if MIN_VERSION_base(4,9,0) instance Num a :=> Num (Identity a) where ins = Sub Dict instance Num a :=> Num (Const a b) where ins = Sub Dict #endif #if MIN_VERSION_base(4,8,0) instance () :=> Num Natural where ins = Sub Dict #endif -- Real instance Class (Num a, Ord a) (Real a) where cls = Sub Dict instance () :=> Real Int where ins = Sub Dict instance () :=> Real Integer where ins = Sub Dict instance () :=> Real Float where ins = Sub Dict instance () :=> Real Double where ins = Sub Dict instance Integral a :=> Real (Ratio a) where ins = Sub Dict instance () :=> Real Word where ins = Sub Dict #if MIN_VERSION_base(4,9,0) instance Real a :=> Real (Identity a) where ins = Sub Dict instance Real a :=> Real (Const a b) where ins = Sub Dict #endif #if MIN_VERSION_base(4,8,0) instance () :=> Real Natural where ins = Sub Dict #endif -- Integral instance Class (Real a, Enum a) (Integral a) where cls = Sub Dict instance () :=> Integral Int where ins = Sub Dict instance () :=> Integral Integer where ins = Sub Dict instance () :=> Integral Word where ins = Sub Dict #if MIN_VERSION_base(4,9,0) instance Integral a :=> Integral (Identity a) where ins = Sub Dict instance Integral a :=> Integral (Const a b) where ins = Sub Dict #endif #if MIN_VERSION_base(4,8,0) instance () :=> Integral Natural where ins = Sub Dict #endif -- Bits instance Class (Eq a) (Bits a) where cls = Sub Dict instance () :=> Bits Bool where ins = Sub Dict instance () :=> Bits Int where ins = Sub Dict instance () :=> Bits Integer where ins = Sub Dict instance () :=> Bits Word where ins = Sub Dict #if MIN_VERSION_base(4,9,0) instance Bits a :=> Bits (Identity a) where ins = Sub Dict instance Bits a :=> Bits (Const a b) where ins = Sub Dict #endif #if MIN_VERSION_base(4,8,0) instance () :=> Bits Natural where ins = Sub Dict #endif -- Fractional instance Class (Num a) (Fractional a) where cls = Sub Dict instance () :=> Fractional Float where ins = Sub Dict instance () :=> Fractional Double where ins = Sub Dict instance RealFloat a :=> Fractional (Complex a) where ins = Sub Dict instance Integral a :=> Fractional (Ratio a) where ins = Sub Dict #if MIN_VERSION_base(4,9,0) instance Fractional a :=> Fractional (Identity a) where ins = Sub Dict instance Fractional a :=> Fractional (Const a b) where ins = Sub Dict #endif -- Floating instance Class (Fractional a) (Floating a) where cls = Sub Dict instance () :=> Floating Float where ins = Sub Dict instance () :=> Floating Double where ins = Sub Dict instance RealFloat a :=> Floating (Complex a) where ins = Sub Dict #if MIN_VERSION_base(4,9,0) instance Floating a :=> Floating (Identity a) where ins = Sub Dict instance Floating a :=> Floating (Const a b) where ins = Sub Dict #endif -- RealFrac instance Class (Real a, Fractional a) (RealFrac a) where cls = Sub Dict instance () :=> RealFrac Float where ins = Sub Dict instance () :=> RealFrac Double where ins = Sub Dict instance Integral a :=> RealFrac (Ratio a) where ins = Sub Dict #if MIN_VERSION_base(4,9,0) instance RealFrac a :=> RealFrac (Identity a) where ins = Sub Dict instance RealFrac a :=> RealFrac (Const a b) where ins = Sub Dict #endif -- RealFloat instance Class (RealFrac a, Floating a) (RealFloat a) where cls = Sub Dict instance () :=> RealFloat Float where ins = Sub Dict instance () :=> RealFloat Double where ins = Sub Dict #if MIN_VERSION_base(4,9,0) instance RealFloat a :=> RealFloat (Identity a) where ins = Sub Dict instance RealFloat a :=> RealFloat (Const a b) where ins = Sub Dict #endif -- Semigroup instance Class () (Semigroup a) where cls = Sub Dict instance () :=> Semigroup () where ins = Sub Dict instance () :=> Semigroup Ordering where ins = Sub Dict instance () :=> Semigroup [a] where ins = Sub Dict instance Semigroup a :=> Semigroup (Maybe a) where ins = Sub Dict instance (Semigroup a, Semigroup b) :=> Semigroup (a, b) where ins = Sub Dict instance Semigroup a :=> Semigroup (Const a b) where ins = Sub Dict #if MIN_VERSION_base(4,9,0) instance Semigroup a :=> Semigroup (Identity a) where ins = Sub Dict #endif #if MIN_VERSION_base(4,10,0) instance Semigroup a :=> Semigroup (IO a) where ins = Sub Dict #endif -- Monoid #if MIN_VERSION_base(4,11,0) instance Class (Semigroup a) (Monoid a) where cls = Sub Dict #else instance Class () (Monoid a) where cls = Sub Dict #endif instance () :=> Monoid () where ins = Sub Dict instance () :=> Monoid Ordering where ins = Sub Dict instance () :=> Monoid [a] where ins = Sub Dict instance Monoid a :=> Monoid (Maybe a) where ins = Sub Dict instance (Monoid a, Monoid b) :=> Monoid (a, b) where ins = Sub Dict instance Monoid a :=> Monoid (Const a b) where ins = Sub Dict #if MIN_VERSION_base(4,9,0) instance Monoid a :=> Monoid (Identity a) where ins = Sub Dict instance Monoid a :=> Monoid (IO a) where ins = Sub Dict #endif -- Functor instance Class () (Functor f) where cls = Sub Dict instance () :=> Functor [] where ins = Sub Dict instance () :=> Functor Maybe where ins = Sub Dict instance () :=> Functor (Either a) where ins = Sub Dict instance () :=> Functor ((->) a) where ins = Sub Dict instance () :=> Functor ((,) a) where ins = Sub Dict instance () :=> Functor IO where ins = Sub Dict instance Monad m :=> Functor (WrappedMonad m) where ins = Sub Dict instance () :=> Functor Identity where ins = Sub Dict instance () :=> Functor (Const a) where ins = Sub Dict -- Applicative instance Class (Functor f) (Applicative f) where cls = Sub Dict instance () :=> Applicative [] where ins = Sub Dict instance () :=> Applicative Maybe where ins = Sub Dict instance () :=> Applicative (Either a) where ins = Sub Dict instance () :=> Applicative ((->)a) where ins = Sub Dict instance () :=> Applicative IO where ins = Sub Dict instance Monoid a :=> Applicative ((,)a) where ins = Sub Dict instance Monoid a :=> Applicative (Const a) where ins = Sub Dict instance Monad m :=> Applicative (WrappedMonad m) where ins = Sub Dict -- Alternative instance Class (Applicative f) (Alternative f) where cls = Sub Dict instance () :=> Alternative [] where ins = Sub Dict instance () :=> Alternative Maybe where ins = Sub Dict instance MonadPlus m :=> Alternative (WrappedMonad m) where ins = Sub Dict -- Monad #if MIN_VERSION_base(4,8,0) instance Class (Applicative f) (Monad f) where cls = Sub Dict #else instance Class () (Monad f) where cls = Sub Dict #endif instance () :=> Monad [] where ins = Sub Dict instance () :=> Monad ((->) a) where ins = Sub Dict instance () :=> Monad (Either a) where ins = Sub Dict instance () :=> Monad IO where ins = Sub Dict instance () :=> Monad Identity where ins = Sub Dict -- MonadPlus #if MIN_VERSION_base(4,8,0) instance Class (Monad f, Alternative f) (MonadPlus f) where cls = Sub Dict #else instance Class (Monad f) (MonadPlus f) where cls = Sub Dict #endif instance () :=> MonadPlus [] where ins = Sub Dict instance () :=> MonadPlus Maybe where ins = Sub Dict -------------------------------------------------------------------------------- -- UndecidableInstances -------------------------------------------------------------------------------- instance a :=> Enum (Dict a) where ins = Sub Dict instance a => Enum (Dict a) where toEnum _ = Dict fromEnum Dict = 0 instance a :=> Bounded (Dict a) where ins = Sub Dict instance a => Bounded (Dict a) where minBound = Dict maxBound = Dict instance a :=> Read (Dict a) where ins = Sub Dict deriving instance a => Read (Dict a) instance () :=> Semigroup (Dict a) where ins = Sub Dict instance Semigroup (Dict a) where Dict <> Dict = Dict instance a :=> Monoid (Dict a) where ins = Sub Dict instance a => Monoid (Dict a) where #if !(MIN_VERSION_base(4,11,0)) mappend = (<>) #endif mempty = Dict
#include <vector> #include <algorithm> #include <numeric> #include <boost/thread/lock_guard.hpp> #include <std_msgs/Float64.h> #include <std_msgs/Int32.h> #include <tf2_geometry_msgs/tf2_geometry_msgs.h> #include <geometry_msgs/TransformStamped.h> #include "gazebo_interface/gazebo_interface.hpp" #include "reflex_interface/hand_state.hpp" HandState::HandState(ros::NodeHandle *nh, bool use_sim_data_hand, bool use_sim_data_obj) : finger_states{new FingerState(nh, 1), new FingerState(nh, 2), new FingerState(nh, 3)} { this->nh = nh; this->use_sim_data_hand = use_sim_data_hand; this->use_sim_data_obj = use_sim_data_obj; reflex_state_sub = nh->subscribe("reflex_takktile/hand_state", 1, &HandState::reflex_state_callback, this); hand_state_pub = nh->advertise<reflex_interface::HandStateStamped>("/reflex_interface/hand_state", 1); if (use_sim_data_hand) { sim_state_sub = nh->subscribe("reflex_takktile/sim_contact_frames", 1, &HandState::sim_state_callback, this); } } bool HandState::allFingersInContact() { boost::lock_guard<boost::mutex> guard(mtx); return std::all_of(vars.fingers_in_contact.begin(), vars.fingers_in_contact.end(), [](bool v) { return v; }); } int HandState::getNumFingersInContact() { int count = 0; for (int i = 0; i < num_fingers; i++) { if (finger_states[i]->hasContact() == true) { count++; } } return count; } int HandState::getFingerIdSingleContact() { for (int i = 0; i < num_fingers; i++) { if (finger_states[i]->hasContact() == true) { return i; } } return -1; } tf2::Vector3 HandState::create_vec_from_msg(const geometry_msgs::Vector3 &msg) { return tf2::Vector3{msg.x, msg.y, msg.z}; } void HandState::sim_state_callback(const sensor_listener::ContactFrames &msg) { // reset variables mtx.lock(); vars.clear_all(); vars.num_contacts = msg.contact_frames_world.size(); for (int i = 0; i < vars.num_contacts; i++) { tf2::Transform transform; tf2::fromMsg(msg.contact_frames_world[i].contact_frame, transform); vars.contact_frames.push_back(transform); vars.contact_forces.push_back(create_vec_from_msg(msg.contact_frames_world[i].contact_wrench.force)); vars.contact_torques.push_back(create_vec_from_msg(msg.contact_frames_world[i].contact_wrench.torque)); vars.contact_positions.push_back(create_vec_from_msg(msg.contact_frames_world[i].contact_position)); vars.contact_normals.push_back(create_vec_from_msg(msg.contact_frames_world[i].contact_normal)); vars.sensor_ids.push_back(msg.contact_frames_world[i].sensor_id); vars.contact_force_magnitudes.push_back(msg.contact_frames_world[i].contact_force_magnitude); vars.contact_torque_magnitudes.push_back(msg.contact_frames_world[i].contact_torque_magnitude); vars.sum_contact_forces += msg.contact_frames_world[i].contact_force_magnitude; int finger_id = msg.contact_frames_world[i].hand_part_id; vars.link_ids.push_back(finger_id); if (!msg.contact_frames_world[i].palm_contact) { // this should never happen but checking anyway due to vector accessing below if (finger_id < 1 || finger_id > 3) { ROS_ERROR("Your finger id is out of bounds. Ignoring this."); continue; } vars.fingers_in_contact[finger_id - 1] = true; vars.num_sensors_in_contact_per_finger[finger_id - 1] += 1; // TODO actually this variable now represents num_sim_contacts_per_finger } } mtx.unlock(); updateHandStateSim(); // TODO shift this to wrist_controller // broadcast Gazebo wrist pose to ROS tf tree // TODO maybe add back in (once ROS fixes this bug https://github.com/ros/geometry2/issues/467 and I dont get bombarded with warning messages anymore) // tf2::Transform wrist_measured = getLinkPoseSim(nh, "shell", "world", false); // broadcastModelState(wrist_measured, "world", "reflex_interface/wrist_measured", &br_reflex_measured); updateQualityMetrics(); hand_state_pub.publish(getHandStateMsg()); } HandStateVariables HandState::getVars() { boost::lock_guard<boost::mutex> guard(mtx); return vars; } void HandState::reflex_state_callback(const reflex_msgs::Hand &msg) { for (int i = 0; i < num_fingers; i++) { finger_states[i]->setProximalAngle(msg.finger[i].proximal); finger_states[i]->setDistalAngle(msg.finger[i].distal_approx); finger_states[i]->setSensorContacts(msg.finger[i].contact); finger_states[i]->setSensorPressures(msg.finger[i].pressure); if (i != 2) { // set preshape angle for fingers 1 and 2 (finger 3 doesn't have a preshape angle) finger_states[i]->setPreshapeAngle(msg.motor[3].joint_angle); } } for (int i = 0; i < num_motors; i++) { motor_states[i]->setJointAngle(msg.motor[i].joint_angle); motor_states[i]->setRawAngle(msg.motor[i].raw_angle); motor_states[i]->setVelocity(msg.motor[i].velocity); motor_states[i]->setLoad(msg.motor[i].load); motor_states[i]->setVoltage(msg.motor[i].voltage); motor_states[i]->setTemperature(msg.motor[i].temperature); motor_states[i]->setErrorState(msg.motor[i].error_state); } if (!use_sim_data_hand) { updateHandStateReal(); updateQualityMetrics(); hand_state_pub.publish(getHandStateMsg()); } } void HandState::broadcastModelState(tf2::Transform tf, std::string source_frame, std::string target_frame, tf2_ros::TransformBroadcaster *br) { geometry_msgs::TransformStamped ts; ts.header.frame_id = source_frame; ts.child_frame_id = target_frame; ts.header.stamp = ros::Time::now(); ts.transform = tf2::toMsg(tf); br->sendTransform(ts); } void HandState::updateQualityMetrics() { if (use_sim_data_obj) { // broadcast Gazebo object pose to ROS tf tree getParam(nh, &object_name, "object_name", false); obj_measured = getModelPoseSim(nh, object_name, "world", false); // TODO maybe add back in (once ROS fixes this bug https://github.com/ros/geometry2/issues/467 and I dont get bombarded with warning messages anymore) // broadcastModelState(obj_measured, "world", "reflex_interface/obj_measured", &br_obj_measured); boost::lock_guard<boost::mutex> guard(mtx); bool calc_metric = false; // epsilon getParam(nh, &calc_metric, "calc_epsilon", false); if (calc_metric) { vars.epsilon = grasp_quality.getEpsilon(vars.contact_positions, vars.contact_normals, obj_measured.getOrigin()); } // epsilon force torque separate getParam(nh, &calc_metric, "calc_epsilon_ft_separate", false); if (calc_metric) { grasp_quality.fillEpsilonFTSeparate(vars.contact_positions, vars.contact_normals, obj_measured.getOrigin(), vars.epsilon_force, vars.epsilon_torque); } // delta getParam(nh, &calc_metric, "calc_delta", false); if (calc_metric) { vars.delta_cur = grasp_quality.getSlipMargin(vars.contact_normals, vars.contact_forces, vars.contact_force_magnitudes, vars.num_contacts); vars.delta_task = grasp_quality.getSlipMarginWithTaskWrenches(getTaskWrenches(), vars.contact_forces, vars.contact_normals, vars.contact_frames, obj_measured.getOrigin(), vars.num_contacts); } } else { // on real hand (without knowing the object pose) we can only calculate the epsilon force } } TaskPolytope HandState::getTaskWrenches() { TaskPolytope tp = TaskPolytope(); float obj_mass; getParam(nh, &obj_mass, "object_mass", false); // define task wrenches (how much total task wrench has to be applied from fingers to object) float obj_weight = obj_mass * 9.81; // grasp must resist only gravity for now (quasi-static assumption) tp.add_task_wrench(tf2::Vector3(0, 0, obj_weight), tf2::Vector3(0, 0, 0)); return tp; } HandState::ContactState HandState::getContactState() { switch (getNumFingersInContact()) { case 0: return NoContact; case 1: return SingleFingerContact; default: return MultipleFingerContact; } } void HandState::updateHandStateSim() { // updates poses of finger links from simulation for (int i = 0; i < num_fingers; i++) { finger_states[i]->updateCurLinkFramesInShellFrameSim(); } } void HandState::updateHandStateReal() { // reset variables boost::lock_guard<boost::mutex> guard(mtx); vars.clear_all(); for (int i = 0; i < num_fingers; i++) { int num_contacts_on_finger = 0; finger_states[i]->updateCurLinkFramesInShellFrameReal(); finger_states[i]->fillContactInfo(vars.contact_positions, vars.contact_normals, num_contacts_on_finger, false, "shell"); // TODO: solve with forward kinematics and compare with results we obtain from simulation. // TODO because we want this in world coosy we also need the gripper pose. if (num_contacts_on_finger > 0) { vars.num_sensors_in_contact_per_finger[i] = num_contacts_on_finger; vars.fingers_in_contact[i] = true; } } vars.num_contacts = std::accumulate(vars.num_sensors_in_contact_per_finger.begin(), vars.num_sensors_in_contact_per_finger.end(), 0); } reflex_interface::HandStateStamped HandState::getHandStateMsg() { // create msg for positions and normals of finger surface above each tactile sensor reflex_interface::HandStateStamped hss; hss.header.stamp = ros::Time::now(); hss.header.frame_id = "shell"; hss.preshape_angle = finger_states[0]->getPreshapeAngle(); mtx.lock(); hss.num_contacts = vars.num_contacts; hss.epsilon = vars.epsilon; hss.epsilon_force = vars.epsilon_force; hss.delta_cur = vars.delta_cur; hss.delta_task = vars.delta_task; hss.epsilon_torque = vars.epsilon_torque; hss.sum_contact_forces = vars.sum_contact_forces; mtx.unlock(); for (int i = 0; i < num_fingers; i++) { hss.finger_state[i].prox_normal = tf2::toMsg(finger_states[i]->getProximalNormalInShellFrame()); hss.finger_state[i].dist_normal = tf2::toMsg(finger_states[i]->getDistalNormalInShellFrame()); hss.finger_state[i].prox_in_contact = finger_states[i]->hasProximalContact(); hss.finger_state[i].dist_in_contact = finger_states[i]->hasDistalContact(); hss.finger_state[i].finger_in_contact = finger_states[i]->hasContact(); hss.finger_state[i].proximal_angle = finger_states[i]->getProximalAngle(); hss.finger_state[i].distal_angle = finger_states[i]->getDistalAngle(); std::vector<tf2::Vector3> tactile_pos = finger_states[i]->getTactilePositionsInShellFrame(); for (int j = 0; j < num_sensors_per_finger; j++) { tf2::toMsg(tactile_pos[j], hss.finger_state[i].tactile_position[j]); hss.finger_state[i].sensor_contact[j] = finger_states[i]->getSensorContacts()[j]; hss.finger_state[i].sensor_pressure[j] = finger_states[i]->getSensorPressures()[j]; } } return hss; }
data MyMaybe : (0 x : Type) -> Type where MyNothing : MyMaybe a MyJust : a -> MyMaybe a -- Should fail since type argument is deleted nameOf : Type -> String nameOf (MyMaybe Bool) = "MyMaybe Bool" nameOf (MyMaybe Int) = "MyMaybe Int" nameOf _ = "Unknown" main : IO () main = do putStrLn (nameOf (MyMaybe Bool)) putStrLn (nameOf (MyMaybe Int)) putStrLn (nameOf Int)
(* * Base Library for ICL - Version: 3 October 2016 - Author: Gert Smolka, Saarland University - Acknowlegments: Sigurd Schneider, Dominik Kirst, Yannick Forster, Fabian Kunze, Maximilian Wuttke *) Require Export Bool Omega Lia List Setoid Morphisms. From Undecidability.Shared.Libs.PSL Require Export Tactics. Global Set Implicit Arguments. Global Unset Strict Implicit. Global Unset Printing Records. Global Unset Printing Implicit Defensive. Global Set Regular Subst Tactic. Hint Extern 4 => exact _ : core. (* makes auto use type class inference *) (* De Morgan laws *) Lemma DM_or (X Y : Prop) : ~ (X \/ Y) <-> ~ X /\ ~ Y. Proof. tauto. Qed. Lemma DM_exists X (p : X -> Prop) : ~ (exists x, p x) <-> forall x, ~ p x. Proof. firstorder. Qed. (* ** Boolean propositions and decisions *) Coercion is_true : bool >-> Sortclass. Lemma bool_Prop_true b : b = true -> b. Proof. intros A. rewrite A. reflexivity. Qed. Lemma bool_Prop_false b : b = false -> ~ b. Proof. intros A. rewrite A. cbn. intros H. congruence. Qed. Lemma bool_Prop_true' (b : bool) : b -> b = true. Proof. intros A. cbv in A. destruct b; tauto. Qed. Lemma bool_Prop_false' (b : bool) : ~ b -> b = false. Proof. intros A. cbv in A. destruct b; tauto. Qed. Hint Resolve bool_Prop_true bool_Prop_false : core. Hint Resolve bool_Prop_true' bool_Prop_false' : core. Definition bool2nat := fun b : bool => if b then 1 else 0. Definition nat2bool := fun n : nat => match n with 0 => false | _ => true end. (* Coercion nat2bool : nat >-> bool. *) Lemma bool_nat (b : bool) : 1 = bool2nat b -> b. Proof. intros; cbv in *. destruct b. auto. congruence. Qed. Lemma nat_bool (b : bool) : b = nat2bool 1 -> b. Proof. intros; cbv in *. destruct b. auto. congruence. Qed. Hint Resolve bool_nat nat_bool : core. Ltac simpl_coerce := match goal with | [ H: False |- _ ] => destruct H | [ H: ~ is_true true |- _ ] => destruct H; congruence | [ H: is_true false |- _ ] => congruence end. Ltac simpl_congruence := match goal with | [ H : 0 = S _ |- _] => congruence | [ H : S _ = 0 |- _] => congruence | [ H : S _ = 0 |- _] => congruence | [ H : true = false |- _] => congruence | [ H : false = true |- _] => congruence end. Hint Extern 1 => simpl_coerce : core. Hint Extern 1 => simpl_congruence : core.
[STATEMENT] lemma take_bit_numeral_minus_numeral_word [simp]: \<open>take_bit (numeral m) (- numeral n :: 'a::len word) = (case take_bit_num (numeral m) n of None \<Rightarrow> 0 | Some q \<Rightarrow> take_bit (numeral m) (2 ^ numeral m - numeral q))\<close> (is \<open>?lhs = ?rhs\<close>) [PROOF STATE] proof (prove) goal (1 subgoal): 1. take_bit (numeral m) (- numeral n) = (case take_bit_num (numeral m) n of None \<Rightarrow> 0 | Some q \<Rightarrow> take_bit (numeral m) (2 ^ numeral m - numeral q)) [PROOF STEP] proof (cases \<open>LENGTH('a) \<le> numeral m\<close>) [PROOF STATE] proof (state) goal (2 subgoals): 1. LENGTH('a) \<le> numeral m \<Longrightarrow> take_bit (numeral m) (- numeral n) = (case take_bit_num (numeral m) n of None \<Rightarrow> 0 | Some q \<Rightarrow> take_bit (numeral m) (2 ^ numeral m - numeral q)) 2. \<not> LENGTH('a) \<le> numeral m \<Longrightarrow> take_bit (numeral m) (- numeral n) = (case take_bit_num (numeral m) n of None \<Rightarrow> 0 | Some q \<Rightarrow> take_bit (numeral m) (2 ^ numeral m - numeral q)) [PROOF STEP] case True [PROOF STATE] proof (state) this: LENGTH('a) \<le> numeral m goal (2 subgoals): 1. LENGTH('a) \<le> numeral m \<Longrightarrow> take_bit (numeral m) (- numeral n) = (case take_bit_num (numeral m) n of None \<Rightarrow> 0 | Some q \<Rightarrow> take_bit (numeral m) (2 ^ numeral m - numeral q)) 2. \<not> LENGTH('a) \<le> numeral m \<Longrightarrow> take_bit (numeral m) (- numeral n) = (case take_bit_num (numeral m) n of None \<Rightarrow> 0 | Some q \<Rightarrow> take_bit (numeral m) (2 ^ numeral m - numeral q)) [PROOF STEP] then [PROOF STATE] proof (chain) picking this: LENGTH('a) \<le> numeral m [PROOF STEP] have *: \<open>(take_bit (numeral m) :: 'a word \<Rightarrow> 'a word) = id\<close> [PROOF STATE] proof (prove) using this: LENGTH('a) \<le> numeral m goal (1 subgoal): 1. take_bit (numeral m) = id [PROOF STEP] by (simp add: fun_eq_iff take_bit_word_eq_self) [PROOF STATE] proof (state) this: take_bit (numeral m) = id goal (2 subgoals): 1. LENGTH('a) \<le> numeral m \<Longrightarrow> take_bit (numeral m) (- numeral n) = (case take_bit_num (numeral m) n of None \<Rightarrow> 0 | Some q \<Rightarrow> take_bit (numeral m) (2 ^ numeral m - numeral q)) 2. \<not> LENGTH('a) \<le> numeral m \<Longrightarrow> take_bit (numeral m) (- numeral n) = (case take_bit_num (numeral m) n of None \<Rightarrow> 0 | Some q \<Rightarrow> take_bit (numeral m) (2 ^ numeral m - numeral q)) [PROOF STEP] have **: \<open>2 ^ numeral m = (0 :: 'a word)\<close> [PROOF STATE] proof (prove) goal (1 subgoal): 1. 2 ^ numeral m = 0 [PROOF STEP] using True [PROOF STATE] proof (prove) using this: LENGTH('a) \<le> numeral m goal (1 subgoal): 1. 2 ^ numeral m = 0 [PROOF STEP] by (simp flip: exp_eq_zero_iff) [PROOF STATE] proof (state) this: 2 ^ numeral m = 0 goal (2 subgoals): 1. LENGTH('a) \<le> numeral m \<Longrightarrow> take_bit (numeral m) (- numeral n) = (case take_bit_num (numeral m) n of None \<Rightarrow> 0 | Some q \<Rightarrow> take_bit (numeral m) (2 ^ numeral m - numeral q)) 2. \<not> LENGTH('a) \<le> numeral m \<Longrightarrow> take_bit (numeral m) (- numeral n) = (case take_bit_num (numeral m) n of None \<Rightarrow> 0 | Some q \<Rightarrow> take_bit (numeral m) (2 ^ numeral m - numeral q)) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) goal (1 subgoal): 1. take_bit (numeral m) (- numeral n) = (case take_bit_num (numeral m) n of None \<Rightarrow> 0 | Some q \<Rightarrow> take_bit (numeral m) (2 ^ numeral m - numeral q)) [PROOF STEP] by (auto simp only: * ** split: option.split dest!: take_bit_num_eq_None_imp [where ?'a = \<open>'a word\<close>] take_bit_num_eq_Some_imp [where ?'a = \<open>'a word\<close>]) simp_all [PROOF STATE] proof (state) this: take_bit (numeral m) (- numeral n) = (case take_bit_num (numeral m) n of None \<Rightarrow> 0 | Some q \<Rightarrow> take_bit (numeral m) (2 ^ numeral m - numeral q)) goal (1 subgoal): 1. \<not> LENGTH('a) \<le> numeral m \<Longrightarrow> take_bit (numeral m) (- numeral n) = (case take_bit_num (numeral m) n of None \<Rightarrow> 0 | Some q \<Rightarrow> take_bit (numeral m) (2 ^ numeral m - numeral q)) [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. \<not> LENGTH('a) \<le> numeral m \<Longrightarrow> take_bit (numeral m) (- numeral n) = (case take_bit_num (numeral m) n of None \<Rightarrow> 0 | Some q \<Rightarrow> take_bit (numeral m) (2 ^ numeral m - numeral q)) [PROOF STEP] case False [PROOF STATE] proof (state) this: \<not> LENGTH('a) \<le> numeral m goal (1 subgoal): 1. \<not> LENGTH('a) \<le> numeral m \<Longrightarrow> take_bit (numeral m) (- numeral n) = (case take_bit_num (numeral m) n of None \<Rightarrow> 0 | Some q \<Rightarrow> take_bit (numeral m) (2 ^ numeral m - numeral q)) [PROOF STEP] then [PROOF STATE] proof (chain) picking this: \<not> LENGTH('a) \<le> numeral m [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: \<not> LENGTH('a) \<le> numeral m goal (1 subgoal): 1. take_bit (numeral m) (- numeral n) = (case take_bit_num (numeral m) n of None \<Rightarrow> 0 | Some q \<Rightarrow> take_bit (numeral m) (2 ^ numeral m - numeral q)) [PROOF STEP] by (transfer fixing: m n) simp [PROOF STATE] proof (state) this: take_bit (numeral m) (- numeral n) = (case take_bit_num (numeral m) n of None \<Rightarrow> 0 | Some q \<Rightarrow> take_bit (numeral m) (2 ^ numeral m - numeral q)) goal: No subgoals! [PROOF STEP] qed
theory Proof_5 imports Requirements VCTheoryLemmas begin lemma minimalRed_red_at_least_T1: "toEnvP s1 \<and> substate s1 s \<and> getPstate s1 Ctrl = minimalRed \<and> (\<forall>s1 s2. toEnvP s1 \<and> toEnvP s2 \<and> substate s1 s2 \<and> substate s2 s \<and> getPstate s2 Ctrl = minimalRed \<and> toEnvNum s1 s2 < ltimeEnv s2 Ctrl \<longrightarrow> getPstate s1 Ctrl = minimalRed) \<and> (\<forall>s1. toEnvP s1 \<and> substate s1 s \<and> getPstate s1 Ctrl \<noteq> green \<longrightarrow> getVarBool s1 minimalRed = NOT_PRESSED) \<Longrightarrow> (\<forall> s2. toEnvP s2 \<and> substate s2 s1 \<and> toEnvNum s2 s1 < ltimeEnv s1 Ctrl \<longrightarrow> getVarBool s2 trafficLight = RED)" by (metis numeral_eq_iff substate_trans verit_eq_simplify(14)) lemma redAfterMinimalRed_pressed_red_at_least_T1: "toEnvP s1 \<and> substate s1 s \<and> getPstate s1 Ctrl = redAfterMinimalRed \<and> (\<forall>s1 s2. toEnvP s1 \<and> toEnvP s2 \<and> substate s1 s2 \<and> substate s2 s \<and> getPstate s2 Ctrl = minimalRed \<and> toEnvNum s1 s2 < ltimeEnv s2 Ctrl \<longrightarrow> getPstate s1 Ctrl = minimalRed) \<and> (\<forall>s1. toEnvP s1 \<and> substate s1 s \<and> getPstate s1 Ctrl = redAfterMinimalRed \<and> getVarBool s1 redAfterMinimalRed = NOT_PRESSED \<longrightarrow> (\<exists>s2. toEnvP s2 \<and> substate s2 s1 \<and> getPstate s2 Ctrl = minimalRed \<and> ltimeEnv s2 Ctrl = MINIMAL_RED_TIME_LIMIT \<and> getVarBool s2 redAfterMinimalRed = NOT_PRESSED \<and> (\<forall>s3. toEnvP s3 \<and> substate s2 s3 \<and> substate s3 s1 \<and> s2 \<noteq> s3 \<longrightarrow> getPstate s3 Ctrl = redAfterMinimalRed \<and> getVarBool s3 redAfterMinimalRed = NOT_PRESSED \<and> getVarBool s3 Ctrl = NOT_PRESSED))) \<and> (\<forall>s1. toEnvP s1 \<and> substate s1 s \<and> getPstate s1 Ctrl = redAfterMinimalRed \<and> getVarBool s1 redAfterMinimalRed \<longrightarrow> (\<exists>s2. toEnvP s2 \<and> substate s2 s1 \<and> toEnvNum s2 s1 = Ctrl \<and> getPstate s2 Ctrl = minimalRed \<and> ltimeEnv s2 Ctrl = MINIMAL_RED_TIME_LIMIT \<and> (getVarBool s2 redAfterMinimalRed \<or> getVarBool s1 Ctrl = PRESSED))) \<and> (\<forall>s1. toEnvP s1 \<and> substate s1 s \<and> getPstate s1 Ctrl \<noteq> green \<longrightarrow> getVarBool s1 minimalRed = NOT_PRESSED) \<Longrightarrow> (\<And>s1 s. toEnvP s1 \<and> substate s1 s \<and> getPstate s1 Ctrl = minimalRed \<and> (\<forall>s1 s2. toEnvP s1 \<and> toEnvP s2 \<and> substate s1 s2 \<and> substate s2 s \<and> getPstate s2 Ctrl = minimalRed \<and> toEnvNum s1 s2 < ltimeEnv s2 Ctrl \<longrightarrow> getPstate s1 Ctrl = minimalRed) \<and> (\<forall>s1. toEnvP s1 \<and> substate s1 s \<and> getPstate s1 Ctrl \<noteq> green \<longrightarrow> getVarBool s1 minimalRed = NOT_PRESSED) \<Longrightarrow> \<forall>s2. toEnvP s2 \<and> substate s2 s1 \<and> toEnvNum s2 s1 < ltimeEnv s1 Ctrl \<longrightarrow> getVarBool s2 minimalRed = NOT_PRESSED) \<Longrightarrow> getVarBool s1 redAfterMinimalRed \<Longrightarrow> toEnvP x \<and> substate x s1 \<and> toEnvNum x s1 = Ctrl \<and> getPstate x Ctrl = minimalRed \<and> ltimeEnv x Ctrl = MINIMAL_RED_TIME_LIMIT \<and> (getVarBool x redAfterMinimalRed \<or> getVarBool s1 Ctrl = PRESSED) \<Longrightarrow> toEnvP s2 \<and> substate s2 s1 \<and> toEnvNum s2 s1 \<le> MINIMAL_RED_TIME_LIMIT \<longrightarrow> getVarBool s2 minimalRed = NOT_PRESSED" apply(rule impI) apply(rule disjE[of "substate s2 x" "substate x s2 \<and> x \<noteq> s2"]) using substate_total substate_refl apply metis apply(rule cut_rl[of "(\<forall> s2. toEnvP s2 \<and> substate s2 x \<and> toEnvNum s2 x < ltimeEnv x Ctrl \<longrightarrow> getVarBool s2 trafficLight = RED)"]) apply(drule allE[of _ s2 "getVarBool s2 minimalRed = NOT_PRESSED"]) apply (metis dual_order.strict_trans1 less_add_one toEnvNum3) apply assumption apply(rule minimalRed_red_at_least_T1[of _ s]) using substate_trans apply (smt (verit)) apply(rule cut_rl[of "s2 = s1"]) apply (metis cong_exp_iff_simps(10) cong_exp_iff_simps(13) inc.simps(2) mod_add_self1 numeral_inc numerals(1)) apply(rule cut_rl[of "toEnvNum emptyState s2 = toEnvNum emptyState s1"]) using gtimeE_inj apply fast apply(rule cut_rl[of "toEnvNum emptyState s2 \<le> toEnvNum emptyState s1 \<and> toEnvNum emptyState s2 \<ge> toEnvNum emptyState s1"]) apply arith apply(rule conjI) using emptyState_substate[of s2] toEnvNum3[of emptyState s2 s1] apply arith by (metis \<open>substate emptyState s2 \<and> substate s2 s1 \<Longrightarrow> toEnvNum emptyState s1 = toEnvNum emptyState s2 + toEnvNum s2 s1\<close> \<open>substate emptyState s2\<close> add_le_same_cancel1 le_refl less_one linorder_le_less_linear shift_toEnvNum substate_asym substate_shift) lemma redAfterMinimalRed_notPressed_red_at_least_T1: " toEnvP s1 \<and> substate s1 s \<and> getPstate s1 Ctrl = redAfterMinimalRed \<and> (\<forall>s1 s2. toEnvP s1 \<and> toEnvP s2 \<and> substate s1 s2 \<and> substate s2 s \<and> getPstate s2 Ctrl = minimalRed \<and> toEnvNum s1 s2 < ltimeEnv s2 Ctrl \<longrightarrow> getPstate s1 Ctrl = minimalRed) \<and> (\<forall>s1. toEnvP s1 \<and> substate s1 s \<and> getPstate s1 Ctrl = redAfterMinimalRed \<and> getVarBool s1 redAfterMinimalRed = NOT_PRESSED \<longrightarrow> (\<exists>s2. toEnvP s2 \<and> substate s2 s1 \<and> getPstate s2 Ctrl = minimalRed \<and> ltimeEnv s2 Ctrl = MINIMAL_RED_TIME_LIMIT \<and> getVarBool s2 redAfterMinimalRed = NOT_PRESSED \<and> (\<forall>s3. toEnvP s3 \<and> substate s2 s3 \<and> substate s3 s1 \<and> s2 \<noteq> s3 \<longrightarrow> getPstate s3 Ctrl = redAfterMinimalRed \<and> getVarBool s3 redAfterMinimalRed = NOT_PRESSED \<and> getVarBool s3 Ctrl = NOT_PRESSED))) \<and> (\<forall>s1. toEnvP s1 \<and> substate s1 s \<and> getPstate s1 Ctrl = redAfterMinimalRed \<and> getVarBool s1 redAfterMinimalRed \<longrightarrow> (\<exists>s2. toEnvP s2 \<and> substate s2 s1 \<and> toEnvNum s2 s1 = Ctrl \<and> getPstate s2 Ctrl = minimalRed \<and> ltimeEnv s2 Ctrl = MINIMAL_RED_TIME_LIMIT \<and> (getVarBool s2 redAfterMinimalRed \<or> getVarBool s1 Ctrl = PRESSED))) \<and> (\<forall>s1. toEnvP s1 \<and> substate s1 s \<and> getPstate s1 Ctrl \<noteq> green \<longrightarrow> getVarBool s1 minimalRed = NOT_PRESSED) \<Longrightarrow> (\<And>s1 s. toEnvP s1 \<and> substate s1 s \<and> getPstate s1 Ctrl = minimalRed \<and> (\<forall>s1 s2. toEnvP s1 \<and> toEnvP s2 \<and> substate s1 s2 \<and> substate s2 s \<and> getPstate s2 Ctrl = minimalRed \<and> toEnvNum s1 s2 < ltimeEnv s2 Ctrl \<longrightarrow> getPstate s1 Ctrl = minimalRed) \<and> (\<forall>s1. toEnvP s1 \<and> substate s1 s \<and> getPstate s1 Ctrl \<noteq> green \<longrightarrow> getVarBool s1 minimalRed = NOT_PRESSED) \<Longrightarrow> \<forall>s2. toEnvP s2 \<and> substate s2 s1 \<and> toEnvNum s2 s1 < ltimeEnv s1 Ctrl \<longrightarrow> getVarBool s2 minimalRed = NOT_PRESSED) \<Longrightarrow> \<not> getVarBool s1 redAfterMinimalRed \<Longrightarrow> toEnvP x \<and> substate x s1 \<and> getPstate x Ctrl = minimalRed \<and> ltimeEnv x Ctrl = MINIMAL_RED_TIME_LIMIT \<and> getVarBool x redAfterMinimalRed = NOT_PRESSED \<and> (\<forall>s3. toEnvP s3 \<and> substate x s3 \<and> substate s3 s1 \<and> x \<noteq> s3 \<longrightarrow> getPstate s3 Ctrl = redAfterMinimalRed \<and> getVarBool s3 redAfterMinimalRed = NOT_PRESSED \<and> getVarBool s3 Ctrl = NOT_PRESSED) \<Longrightarrow> toEnvP s2 \<and> substate s2 s1 \<and> toEnvNum s2 s1 \<le> MINIMAL_RED_TIME_LIMIT \<longrightarrow> getVarBool s2 minimalRed = NOT_PRESSED" apply(rule impI) apply(rule disjE[of "substate s2 x" "substate x s2 \<and> x \<noteq> s2"]) using substate_total substate_refl apply metis apply(rule cut_rl[of "(\<forall> s2. toEnvP s2 \<and> substate s2 x \<and> toEnvNum s2 x < ltimeEnv x Ctrl \<longrightarrow> getVarBool s2 trafficLight = RED)"]) apply(drule allE[of _ s2 "getVarBool s2 minimalRed = NOT_PRESSED"]) apply(rule cut_rl[of "toEnvNum x s1 > 0"]) apply (metis dual_order.strict_trans1 less_add_same_cancel1 toEnvNum3) apply (metis bot_nat_0.not_eq_extremum numeral_eq_iff shiftEnv.simps(1) shift_toEnvNum verit_eq_simplify(14)) apply assumption apply(rule minimalRed_red_at_least_T1[of _ s]) using substate_trans apply (smt (verit)) by (metis (mono_tags, lifting) add_left_imp_eq numeral_Bit0 numeral_eq_one_iff numeral_plus_numeral one_plus_BitM one_plus_numeral_commute semiring_norm(28) semiring_norm(86) substate_trans) lemma redAfterMinimalRed_red_at_least_T1: "toEnvP s1 \<and> substate s1 s \<and> getPstate s1 Ctrl = redAfterMinimalRed \<and> (\<forall>s1 s2. toEnvP s1 \<and> toEnvP s2 \<and> substate s1 s2 \<and> substate s2 s \<and> getPstate s2 Ctrl = minimalRed \<and> toEnvNum s1 s2 < ltimeEnv s2 Ctrl \<longrightarrow> getPstate s1 Ctrl = minimalRed) \<and> (\<forall>s1. toEnvP s1 \<and> substate s1 s \<and> getPstate s1 Ctrl = redAfterMinimalRed \<and> getVarBool s1 redAfterMinimalRed = NOT_PRESSED \<longrightarrow> (\<exists>s2. toEnvP s2 \<and> substate s2 s1 \<and> getPstate s2 Ctrl = minimalRed \<and> ltimeEnv s2 Ctrl = MINIMAL_RED_TIME_LIMIT \<and> getVarBool s2 redAfterMinimalRed = NOT_PRESSED \<and> (\<forall>s3. toEnvP s3 \<and> substate s2 s3 \<and> substate s3 s1 \<and> s2 \<noteq> s3 \<longrightarrow> getPstate s3 Ctrl = redAfterMinimalRed \<and> getVarBool s3 redAfterMinimalRed = NOT_PRESSED \<and> getVarBool s3 Ctrl = NOT_PRESSED))) \<and> (\<forall>s1. toEnvP s1 \<and> substate s1 s \<and> getPstate s1 Ctrl = redAfterMinimalRed \<and> getVarBool s1 redAfterMinimalRed \<longrightarrow> (\<exists>s2. toEnvP s2 \<and> substate s2 s1 \<and> toEnvNum s2 s1 = Ctrl \<and> getPstate s2 Ctrl = minimalRed \<and> ltimeEnv s2 Ctrl = MINIMAL_RED_TIME_LIMIT \<and> (getVarBool s2 redAfterMinimalRed \<or> getVarBool s1 Ctrl = PRESSED))) \<and> (\<forall>s1. toEnvP s1 \<and> substate s1 s \<and> getPstate s1 Ctrl \<noteq> green \<longrightarrow> getVarBool s1 minimalRed = NOT_PRESSED) \<Longrightarrow> (\<forall> s2. toEnvP s2 \<and> substate s2 s1 \<and> toEnvNum s2 s1 \<le> MINIMAL_RED_TIME_LIMIT \<longrightarrow> getVarBool s2 trafficLight = RED)" using minimalRed_red_at_least_T1 apply(cases "getVarBool s1 requestButtonPressed") apply(rule exE [of "(\<lambda>s2. toEnvP s2 \<and> substate s2 s1 \<and> toEnvNum s2 s1 = Ctrl \<and> getPstate s2 Ctrl = minimalRed \<and> ltimeEnv s2 Ctrl = MINIMAL_RED_TIME_LIMIT \<and> (getVarBool s2 redAfterMinimalRed \<or> getVarBool s1 Ctrl = PRESSED))"]) apply fast apply(rule allI) apply((rule redAfterMinimalRed_pressed_red_at_least_T1);assumption) apply(rule exE[of "\<lambda> s2. toEnvP s2 \<and> substate s2 s1 \<and> getPstate s2 Ctrl = minimalRed \<and> ltimeEnv s2 Ctrl = MINIMAL_RED_TIME_LIMIT \<and> getVarBool s2 redAfterMinimalRed = NOT_PRESSED \<and> (\<forall>s3. toEnvP s3 \<and> substate s2 s3 \<and> substate s3 s1 \<and> s2 \<noteq> s3 \<longrightarrow> getPstate s3 Ctrl = redAfterMinimalRed \<and> getVarBool s3 redAfterMinimalRed = NOT_PRESSED \<and> getVarBool s3 Ctrl = NOT_PRESSED)"]) apply blast apply(rule allI) by ((rule redAfterMinimalRed_notPressed_red_at_least_T1);assumption) lemma redToGreen_red_at_least_T1_aux1: " toEnvP s1 \<and> substate s1 s \<and> getPstate s1 Ctrl = redToGreen \<and> (\<forall>s1 s2. toEnvP s1 \<and> toEnvP s2 \<and> substate s1 s2 \<and> substate s2 s \<and> getPstate s2 Ctrl = minimalRed \<and> toEnvNum s1 s2 < ltimeEnv s2 Ctrl \<longrightarrow> getPstate s1 Ctrl = minimalRed) \<and> (\<forall>s1. toEnvP s1 \<and> substate s1 s \<and> getPstate s1 Ctrl = redAfterMinimalRed \<and> getVarBool s1 redAfterMinimalRed = NOT_PRESSED \<longrightarrow> (\<exists>s2. toEnvP s2 \<and> substate s2 s1 \<and> getPstate s2 Ctrl = minimalRed \<and> ltimeEnv s2 Ctrl = MINIMAL_RED_TIME_LIMIT \<and> getVarBool s2 redAfterMinimalRed = NOT_PRESSED \<and> (\<forall>s3. toEnvP s3 \<and> substate s2 s3 \<and> substate s3 s1 \<and> s2 \<noteq> s3 \<longrightarrow> getPstate s3 Ctrl = redAfterMinimalRed \<and> getVarBool s3 redAfterMinimalRed = NOT_PRESSED \<and> getVarBool s3 Ctrl = NOT_PRESSED))) \<and> (\<forall>s1. toEnvP s1 \<and> substate s1 s \<and> getPstate s1 Ctrl = redToGreen \<longrightarrow> (\<exists>s2. toEnvP s2 \<and> substate s2 s1 \<and> toEnvNum s2 s1 = ltimeEnv s1 Ctrl \<and> getPstate s2 Ctrl = redAfterMinimalRed \<and> (getVarBool s2 redAfterMinimalRed = PRESSED \<or> getVarBool s2 Ctrl = PRESSED))) \<and> (\<forall>s1 s2. toEnvP s1 \<and> toEnvP s2 \<and> substate s1 s2 \<and> substate s2 s \<and> toEnvNum s1 s2 < ltimeEnv s2 Ctrl \<and> getPstate s2 Ctrl = redToGreen \<longrightarrow> getPstate s1 Ctrl = redToGreen) \<and> (\<forall>s1. toEnvP s1 \<and> substate s1 s \<and> getPstate s1 Ctrl = redAfterMinimalRed \<and> getVarBool s1 redAfterMinimalRed \<longrightarrow> (\<exists>s2. toEnvP s2 \<and> substate s2 s1 \<and> toEnvNum s2 s1 = Ctrl \<and> getPstate s2 Ctrl = minimalRed \<and> ltimeEnv s2 Ctrl = MINIMAL_RED_TIME_LIMIT \<and> (getVarBool s2 redAfterMinimalRed \<or> getVarBool s1 Ctrl = PRESSED))) \<and> (\<forall>s1. toEnvP s1 \<and> substate s1 s \<and> getPstate s1 Ctrl = green \<longrightarrow> getVarBool s1 minimalRed = PRESSED) \<and> (\<forall>s1. toEnvP s1 \<and> substate s1 s \<and> getPstate s1 Ctrl \<noteq> green \<longrightarrow> getVarBool s1 minimalRed = NOT_PRESSED) \<Longrightarrow> toEnvP x \<and> substate x s1 \<and> toEnvNum x s1 = ltimeEnv s1 Ctrl \<and> getPstate x Ctrl = redAfterMinimalRed \<and> (getVarBool x redAfterMinimalRed = PRESSED \<or> getVarBool x Ctrl = PRESSED) \<Longrightarrow> toEnvP s2 \<and> substate s2 s1 \<and> toEnvNum s2 s1 \<le> MINIMAL_RED_TIME_LIMIT + ltimeEnv s1 Ctrl \<longrightarrow> getVarBool s2 minimalRed = NOT_PRESSED" apply(rule impI) apply(rule disjE[of "substate s2 x" "substate x s2 \<and> x \<noteq> s2"]) using substate_total substate_refl apply metis apply(rule cut_rl[of "(\<forall> s2. toEnvP s2 \<and> substate s2 x \<and> toEnvNum s2 x \<le> MINIMAL_RED_TIME_LIMIT \<longrightarrow> getVarBool s2 trafficLight = RED)"]) apply(drule allE[of _ s2]) prefer 2 apply assumption apply (metis add_le_imp_le_right toEnvNum3) apply(rule redAfterMinimalRed_red_at_least_T1[of _ s]) apply (meson substate_trans) by (smt (verit) linorder_le_less_linear numeral_eq_iff semiring_norm(88) shift_toEnvNum substate_asym substate_shift substate_trans) lemma redToGreen_red_at_least_T1: "toEnvP s1 \<and> substate s1 s \<and> getPstate s1 Ctrl = redToGreen \<and> (\<forall>s1 s2. toEnvP s1 \<and> toEnvP s2 \<and> substate s1 s2 \<and> substate s2 s \<and> getPstate s2 Ctrl = minimalRed \<and> toEnvNum s1 s2 < ltimeEnv s2 Ctrl \<longrightarrow> getPstate s1 Ctrl = minimalRed) \<and> (\<forall>s1. toEnvP s1 \<and> substate s1 s \<and> getPstate s1 Ctrl = redAfterMinimalRed \<and> getVarBool s1 redAfterMinimalRed = NOT_PRESSED \<longrightarrow> (\<exists>s2. toEnvP s2 \<and> substate s2 s1 \<and> getPstate s2 Ctrl = minimalRed \<and> ltimeEnv s2 Ctrl = MINIMAL_RED_TIME_LIMIT \<and> getVarBool s2 redAfterMinimalRed = NOT_PRESSED \<and> (\<forall>s3. toEnvP s3 \<and> substate s2 s3 \<and> substate s3 s1 \<and> s2 \<noteq> s3 \<longrightarrow> getPstate s3 Ctrl = redAfterMinimalRed \<and> getVarBool s3 redAfterMinimalRed = NOT_PRESSED \<and> getVarBool s3 Ctrl = NOT_PRESSED))) \<and> (\<forall>s1. toEnvP s1 \<and> substate s1 s \<and> getPstate s1 Ctrl = redToGreen \<longrightarrow> (\<exists>s2. toEnvP s2 \<and> substate s2 s1 \<and> toEnvNum s2 s1 = ltimeEnv s1 Ctrl \<and> getPstate s2 Ctrl = redAfterMinimalRed \<and> (getVarBool s2 redAfterMinimalRed = PRESSED \<or> getVarBool s2 Ctrl = PRESSED))) \<and> (\<forall>s1 s2. toEnvP s1 \<and> toEnvP s2 \<and> substate s1 s2 \<and> substate s2 s \<and> toEnvNum s1 s2 < ltimeEnv s2 Ctrl \<and> getPstate s2 Ctrl = redToGreen \<longrightarrow> getPstate s1 Ctrl = redToGreen) \<and> (\<forall>s1. toEnvP s1 \<and> substate s1 s \<and> getPstate s1 Ctrl = redAfterMinimalRed \<and> getVarBool s1 redAfterMinimalRed \<longrightarrow> (\<exists>s2. toEnvP s2 \<and> substate s2 s1 \<and> toEnvNum s2 s1 = Ctrl \<and> getPstate s2 Ctrl = minimalRed \<and> ltimeEnv s2 Ctrl = MINIMAL_RED_TIME_LIMIT \<and> (getVarBool s2 redAfterMinimalRed \<or> getVarBool s1 Ctrl = PRESSED))) \<and> (\<forall>s1. toEnvP s1 \<and> substate s1 s \<and> getPstate s1 Ctrl = green \<longrightarrow> getVarBool s1 minimalRed = PRESSED) \<and> (\<forall>s1. toEnvP s1 \<and> substate s1 s \<and> getPstate s1 Ctrl \<noteq> green \<longrightarrow> getVarBool s1 minimalRed = NOT_PRESSED) \<Longrightarrow> (\<forall> s2. toEnvP s2 \<and> substate s2 s1 \<and> toEnvNum s2 s1 \<le> MINIMAL_RED_TIME_LIMIT + ltimeEnv s1 Ctrl \<longrightarrow> getVarBool s2 trafficLight = RED)" apply(rule exE[of "(\<lambda>s2. toEnvP s2 \<and> substate s2 s1 \<and> toEnvNum s2 s1 = ltimeEnv s1 Ctrl \<and> getPstate s2 Ctrl = redAfterMinimalRed \<and> (getVarBool s2 redAfterMinimalRed = PRESSED \<or> getVarBool s2 Ctrl = PRESSED))"]) apply blast apply(rule allI) by ((rule redToGreen_red_at_least_T1_aux1);assumption) theorem proof_5_1: "VC1 inv5 s0" apply(simp only: VC1_def inv5_def R5_def extraInv_def) by auto end
[STATEMENT] lemma leq_prodE [elim?]: "p \<sqsubseteq> q \<Longrightarrow> (fst p \<sqsubseteq> fst q \<Longrightarrow> snd p \<sqsubseteq> snd q \<Longrightarrow> C) \<Longrightarrow> C" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>p \<sqsubseteq> q; \<lbrakk>fst p \<sqsubseteq> fst q; snd p \<sqsubseteq> snd q\<rbrakk> \<Longrightarrow> C\<rbrakk> \<Longrightarrow> C [PROOF STEP] by (unfold leq_prod_def) blast
[STATEMENT] lemma rotater_drop_take: "rotater n xs = drop (length xs - n mod length xs) xs @ take (length xs - n mod length xs) xs" [PROOF STATE] proof (prove) goal (1 subgoal): 1. rotater n xs = drop (length xs - n mod length xs) xs @ take (length xs - n mod length xs) xs [PROOF STEP] by (auto simp: rotater_rev rotate_drop_take rev_take rev_drop)
classdef PTKLungSurface < PTKPlugin % PTKLungSurface. Plugin for finding points around the surface of the lungs % % This is a plugin for the Pulmonary Toolkit. Plugins can be run using % the gui, or through the interfaces provided by the Pulmonary Toolkit. % See PTKPlugin.m for more information on how to run plugins. % % Plugins should not be run directly from your code. % % PTKLungSurface runs the library function PTKGetSurfaceFromSegmentation % to find the lung surface and returns this as an image. % % % Licence % ------- % Part of the TD Pulmonary Toolkit. https://github.com/tomdoel/pulmonarytoolkit % Author: Tom Doel, 2012. www.tomdoel.com % Distributed under the GNU GPL v3 licence. Please see website for details. % properties ButtonText = 'Lung Surface' ToolTip = 'Segment the lung surface' Category = 'Lungs' AllowResultsToBeCached = true AlwaysRunPlugin = false PluginType = 'ReplaceOverlay' HidePluginInDisplay = false FlattenPreviewImage = false PTKVersion = '1' ButtonWidth = 6 ButtonHeight = 2 GeneratePreview = true Visibility = 'Developer' end methods (Static) function results = RunPlugin(dataset, ~) lung_mask = dataset.GetResult('PTKLeftAndRightLungs'); results = lung_mask.BlankCopy; lungs = PTKGetSurfaceFromSegmentation(uint8(lung_mask.RawImage > 0)); results.ChangeRawImage(lungs); results.ImageType = PTKImageType.Colormap; end end end
open Nat theorem zero_add (n : Nat) : 0 + n = n := Nat.recOn (motive := fun x : Nat => 0 + x = x) n (show 0 + 0 = 0 from rfl) (fun (n : Nat) (ih : 0 + n = n) => show 0 + succ n = succ n from calc 0 + succ n = succ (0 + n) := rfl _ = succ n := by rw [ih]) open List def append (as bs : List α) : List α := match as with | nil => bs | cons head tail => cons head (append tail bs) theorem append_nil (as : List α) : append as nil = as := List.recOn (motive := fun t : List α => append t nil = t) as (show append nil nil = nil from rfl) (fun (head : α) (tail : List α) (ih : append tail nil = tail) => show append (cons head tail) nil = cons head tail from calc append (cons head tail) nil = cons head (append tail nil) := rfl _ = cons head tail := by rw [ih]) theorem append_assoc (as bs cs : List α) : append (append as bs) cs = append as (append bs cs) := List.recOn (motive := fun as : List α => append (append as bs) cs = append as (append bs cs)) as (show append (append nil bs) cs = append nil (append bs cs) from rfl) (fun (head : α) (tail : List α) (ih : append (append tail bs) cs = append tail (append bs cs)) => show append (append (cons head tail) bs) cs = append (cons head tail) (append bs cs) from calc append (append (cons head tail) bs) cs = append (cons head (append tail bs)) cs := rfl _ = cons head (append (append tail bs) cs) := rfl _ = cons head (append tail (append bs cs)) := by rw [ih]) def len (as : List α) : Nat := match as with | nil => 0 | cons _ tail => succ (length tail) theorem len_distrib (as bs : List α) : length (append as bs) = length as + length bs := List.recOn (motive := fun as : List α => length (append as bs) = length as + length bs) as (show length (append nil bs) = length nil + length bs from calc length (append nil bs) = length bs := rfl _ = 0 + length bs := by rw [Nat.zero_add]) (fun (head : α) (tail : List α) (ih : length (append tail bs) = length tail + length bs) => show length (append (cons head tail) bs) = length (cons head tail) + length bs from calc length (append (cons head tail) bs) = length (cons head (append tail bs)) := rfl _ = succ (length (append tail bs)) := rfl _ = succ (length tail + length bs) := by rw [ih] _ = succ (length tail) + length bs := by rw [Nat.succ_add]) namespace Hidden theorem trans {α : Type u} {a b c : α} (h₁ : Eq a b) (h₂ : Eq b c) : Eq a c := by rw [h₁,h₂] theorem congr {α β : Type u} {a b : α} (f : α → β) (h : Eq a b) : Eq (f a) (f b) := by rw [h] def subtract (n m : Nat) : Nat := match m with | zero => n | succ k => pred (subtract n k) theorem pred_sub_eq_sub_pred : pred (subtract n k) = subtract (pred n) k := Nat.recOn (motive := fun x : Nat => pred (subtract n x) = subtract (pred n) x) k (show pred (subtract n zero) = subtract (pred n) zero from rfl) (fun (r : Nat) (ih : pred (subtract n r) = subtract (pred n) r) => show pred (subtract n (succ r)) = subtract (pred n) (succ r) from by rw [subtract,ih,subtract]) theorem left_sub_cancel : subtract (n+k) n = k := Nat.recOn (motive := fun x : Nat => subtract (x+k) x = k) n (show subtract (zero + k) zero = k from by rw [Nat.zero_add k,subtract]) (fun (r : Nat) (ih : subtract (r+k) r = k) => show subtract ((succ r)+k) (succ r) = k from by rw [Nat.succ_add,subtract,pred_sub_eq_sub_pred, Nat.pred_succ,ih])
[STATEMENT] lemma arcsin_eq_Re_Arcsin: assumes "\<bar>x\<bar> \<le> 1" shows "arcsin x = Re (Arcsin (of_real x))" [PROOF STATE] proof (prove) goal (1 subgoal): 1. arcsin x = Re (Arcsin (complex_of_real x)) [PROOF STEP] unfolding arcsin_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. (THE xa. - (pi / 2) \<le> xa \<and> xa \<le> pi / 2 \<and> sin xa = x) = Re (Arcsin (complex_of_real x)) [PROOF STEP] proof (rule the_equality, safe) [PROOF STATE] proof (state) goal (4 subgoals): 1. - (pi / 2) \<le> Re (Arcsin (complex_of_real x)) 2. Re (Arcsin (complex_of_real x)) \<le> pi / 2 3. sin (Re (Arcsin (complex_of_real x))) = x 4. \<And>xa. \<lbrakk>- (pi / 2) \<le> xa; xa \<le> pi / 2; x = sin xa\<rbrakk> \<Longrightarrow> xa = Re (Arcsin (complex_of_real (sin xa))) [PROOF STEP] show "- (pi / 2) \<le> Re (Arcsin (complex_of_real x))" [PROOF STATE] proof (prove) goal (1 subgoal): 1. - (pi / 2) \<le> Re (Arcsin (complex_of_real x)) [PROOF STEP] using Re_Ln_pos_le [OF Arcsin_body_lemma, of "of_real x"] [PROOF STATE] proof (prove) using this: (\<bar>Im (Ln (\<i> * complex_of_real x + csqrt (1 - (complex_of_real x)\<^sup>2)))\<bar> \<le> pi / 2) = (0 \<le> Re (\<i> * complex_of_real x + csqrt (1 - (complex_of_real x)\<^sup>2))) goal (1 subgoal): 1. - (pi / 2) \<le> Re (Arcsin (complex_of_real x)) [PROOF STEP] by (auto simp: Complex.in_Reals_norm Re_Arcsin) [PROOF STATE] proof (state) this: - (pi / 2) \<le> Re (Arcsin (complex_of_real x)) goal (3 subgoals): 1. Re (Arcsin (complex_of_real x)) \<le> pi / 2 2. sin (Re (Arcsin (complex_of_real x))) = x 3. \<And>xa. \<lbrakk>- (pi / 2) \<le> xa; xa \<le> pi / 2; x = sin xa\<rbrakk> \<Longrightarrow> xa = Re (Arcsin (complex_of_real (sin xa))) [PROOF STEP] next [PROOF STATE] proof (state) goal (3 subgoals): 1. Re (Arcsin (complex_of_real x)) \<le> pi / 2 2. sin (Re (Arcsin (complex_of_real x))) = x 3. \<And>xa. \<lbrakk>- (pi / 2) \<le> xa; xa \<le> pi / 2; x = sin xa\<rbrakk> \<Longrightarrow> xa = Re (Arcsin (complex_of_real (sin xa))) [PROOF STEP] show "Re (Arcsin (complex_of_real x)) \<le> pi / 2" [PROOF STATE] proof (prove) goal (1 subgoal): 1. Re (Arcsin (complex_of_real x)) \<le> pi / 2 [PROOF STEP] using Re_Ln_pos_le [OF Arcsin_body_lemma, of "of_real x"] [PROOF STATE] proof (prove) using this: (\<bar>Im (Ln (\<i> * complex_of_real x + csqrt (1 - (complex_of_real x)\<^sup>2)))\<bar> \<le> pi / 2) = (0 \<le> Re (\<i> * complex_of_real x + csqrt (1 - (complex_of_real x)\<^sup>2))) goal (1 subgoal): 1. Re (Arcsin (complex_of_real x)) \<le> pi / 2 [PROOF STEP] by (auto simp: Complex.in_Reals_norm Re_Arcsin) [PROOF STATE] proof (state) this: Re (Arcsin (complex_of_real x)) \<le> pi / 2 goal (2 subgoals): 1. sin (Re (Arcsin (complex_of_real x))) = x 2. \<And>xa. \<lbrakk>- (pi / 2) \<le> xa; xa \<le> pi / 2; x = sin xa\<rbrakk> \<Longrightarrow> xa = Re (Arcsin (complex_of_real (sin xa))) [PROOF STEP] next [PROOF STATE] proof (state) goal (2 subgoals): 1. sin (Re (Arcsin (complex_of_real x))) = x 2. \<And>xa. \<lbrakk>- (pi / 2) \<le> xa; xa \<le> pi / 2; x = sin xa\<rbrakk> \<Longrightarrow> xa = Re (Arcsin (complex_of_real (sin xa))) [PROOF STEP] show "sin (Re (Arcsin (complex_of_real x))) = x" [PROOF STATE] proof (prove) goal (1 subgoal): 1. sin (Re (Arcsin (complex_of_real x))) = x [PROOF STEP] using Re_sin [of "Arcsin (of_real x)"] Arcsin_body_lemma [of "of_real x"] [PROOF STATE] proof (prove) using this: Re (sin (Arcsin (complex_of_real x))) = sin (Re (Arcsin (complex_of_real x))) * (exp (Im (Arcsin (complex_of_real x))) + exp (- Im (Arcsin (complex_of_real x)))) / 2 \<i> * complex_of_real x + csqrt (1 - (complex_of_real x)\<^sup>2) \<noteq> 0 goal (1 subgoal): 1. sin (Re (Arcsin (complex_of_real x))) = x [PROOF STEP] by (simp add: Im_Arcsin_of_real assms) [PROOF STATE] proof (state) this: sin (Re (Arcsin (complex_of_real x))) = x goal (1 subgoal): 1. \<And>xa. \<lbrakk>- (pi / 2) \<le> xa; xa \<le> pi / 2; x = sin xa\<rbrakk> \<Longrightarrow> xa = Re (Arcsin (complex_of_real (sin xa))) [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>xa. \<lbrakk>- (pi / 2) \<le> xa; xa \<le> pi / 2; x = sin xa\<rbrakk> \<Longrightarrow> xa = Re (Arcsin (complex_of_real (sin xa))) [PROOF STEP] fix x' [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>xa. \<lbrakk>- (pi / 2) \<le> xa; xa \<le> pi / 2; x = sin xa\<rbrakk> \<Longrightarrow> xa = Re (Arcsin (complex_of_real (sin xa))) [PROOF STEP] assume "- (pi / 2) \<le> x'" "x' \<le> pi / 2" "x = sin x'" [PROOF STATE] proof (state) this: - (pi / 2) \<le> x' x' \<le> pi / 2 x = sin x' goal (1 subgoal): 1. \<And>xa. \<lbrakk>- (pi / 2) \<le> xa; xa \<le> pi / 2; x = sin xa\<rbrakk> \<Longrightarrow> xa = Re (Arcsin (complex_of_real (sin xa))) [PROOF STEP] then [PROOF STATE] proof (chain) picking this: - (pi / 2) \<le> x' x' \<le> pi / 2 x = sin x' [PROOF STEP] show "x' = Re (Arcsin (complex_of_real (sin x')))" [PROOF STATE] proof (prove) using this: - (pi / 2) \<le> x' x' \<le> pi / 2 x = sin x' goal (1 subgoal): 1. x' = Re (Arcsin (complex_of_real (sin x'))) [PROOF STEP] unfolding sin_of_real [symmetric] [PROOF STATE] proof (prove) using this: - (pi / 2) \<le> x' x' \<le> pi / 2 x = sin x' goal (1 subgoal): 1. x' = Re (Arcsin (sin (complex_of_real x'))) [PROOF STEP] by (subst Arcsin_sin) auto [PROOF STATE] proof (state) this: x' = Re (Arcsin (complex_of_real (sin x'))) goal: No subgoals! [PROOF STEP] qed
State Before: G : Type u_1 G' : Type ?u.412647 inst✝² : Group G inst✝¹ : Group G' A : Type ?u.412656 inst✝ : AddGroup A H K : Subgroup G g : G ⊢ g ∈ centralizer H ↔ ∀ (h : G), h ∈ H → h * g * h⁻¹ * g⁻¹ = 1 State After: no goals Tactic: simp only [mem_centralizer_iff, mul_inv_eq_iff_eq_mul, one_mul]
[STATEMENT] lemma inv_after_write_Suc[simp]: "inv_after_write (as, abc_lm_s am n (Suc (abc_lm_v am n) )) (x, aaa, Bk # xs) ires = False" "inv_after_write (as, abc_lm_s am n (Suc (abc_lm_v am n))) (x, aaa, []) ires = False" [PROOF STATE] proof (prove) goal (1 subgoal): 1. inv_after_write (as, abc_lm_s am n (Suc (abc_lm_v am n))) (x, aaa, Bk # xs) ires = False &&& inv_after_write (as, abc_lm_s am n (Suc (abc_lm_v am n))) (x, aaa, []) ires = False [PROOF STEP] apply(auto simp: inv_after_write.simps ) [PROOF STATE] proof (prove) goal: No subgoals! [PROOF STEP] done
(* Title: HOL/Groups_Big.thy Author: Tobias Nipkow Author: Lawrence C Paulson Author: Markus Wenzel Author: Jeremy Avigad *) section \<open>Big sum and product over finite (non-empty) sets\<close> theory Groups_Big imports Power begin subsection \<open>Generic monoid operation over a set\<close> locale comm_monoid_set = comm_monoid begin subsubsection \<open>Standard sum or product indexed by a finite set\<close> interpretation comp_fun_commute f by standard (simp add: fun_eq_iff left_commute) interpretation comp?: comp_fun_commute "f \<circ> g" by (fact comp_comp_fun_commute) definition F :: "('b \<Rightarrow> 'a) \<Rightarrow> 'b set \<Rightarrow> 'a" where eq_fold: "F g A = Finite_Set.fold (f \<circ> g) \<^bold>1 A" lemma infinite [simp]: "\<not> finite A \<Longrightarrow> F g A = \<^bold>1" by (simp add: eq_fold) lemma empty [simp]: "F g {} = \<^bold>1" by (simp add: eq_fold) lemma insert [simp]: "finite A \<Longrightarrow> x \<notin> A \<Longrightarrow> F g (insert x A) = g x \<^bold>* F g A" by (simp add: eq_fold) lemma remove: assumes "finite A" and "x \<in> A" shows "F g A = g x \<^bold>* F g (A - {x})" proof - from \<open>x \<in> A\<close> obtain B where B: "A = insert x B" and "x \<notin> B" by (auto dest: mk_disjoint_insert) moreover from \<open>finite A\<close> B have "finite B" by simp ultimately show ?thesis by simp qed lemma insert_remove: "finite A \<Longrightarrow> F g (insert x A) = g x \<^bold>* F g (A - {x})" by (cases "x \<in> A") (simp_all add: remove insert_absorb) lemma insert_if: "finite A \<Longrightarrow> F g (insert x A) = (if x \<in> A then F g A else g x \<^bold>* F g A)" by (cases "x \<in> A") (simp_all add: insert_absorb) lemma neutral: "\<forall>x\<in>A. g x = \<^bold>1 \<Longrightarrow> F g A = \<^bold>1" by (induct A rule: infinite_finite_induct) simp_all lemma neutral_const [simp]: "F (\<lambda>_. \<^bold>1) A = \<^bold>1" by (simp add: neutral) lemma union_inter: assumes "finite A" and "finite B" shows "F g (A \<union> B) \<^bold>* F g (A \<inter> B) = F g A \<^bold>* F g B" \<comment> \<open>The reversed orientation looks more natural, but LOOPS as a simprule!\<close> using assms proof (induct A) case empty then show ?case by simp next case (insert x A) then show ?case by (auto simp: insert_absorb Int_insert_left commute [of _ "g x"] assoc left_commute) qed corollary union_inter_neutral: assumes "finite A" and "finite B" and "\<forall>x \<in> A \<inter> B. g x = \<^bold>1" shows "F g (A \<union> B) = F g A \<^bold>* F g B" using assms by (simp add: union_inter [symmetric] neutral) corollary union_disjoint: assumes "finite A" and "finite B" assumes "A \<inter> B = {}" shows "F g (A \<union> B) = F g A \<^bold>* F g B" using assms by (simp add: union_inter_neutral) lemma union_diff2: assumes "finite A" and "finite B" shows "F g (A \<union> B) = F g (A - B) \<^bold>* F g (B - A) \<^bold>* F g (A \<inter> B)" proof - have "A \<union> B = A - B \<union> (B - A) \<union> A \<inter> B" by auto with assms show ?thesis by simp (subst union_disjoint, auto)+ qed lemma subset_diff: assumes "B \<subseteq> A" and "finite A" shows "F g A = F g (A - B) \<^bold>* F g B" proof - from assms have "finite (A - B)" by auto moreover from assms have "finite B" by (rule finite_subset) moreover from assms have "(A - B) \<inter> B = {}" by auto ultimately have "F g (A - B \<union> B) = F g (A - B) \<^bold>* F g B" by (rule union_disjoint) moreover from assms have "A \<union> B = A" by auto ultimately show ?thesis by simp qed lemma Int_Diff: assumes "finite A" shows "F g A = F g (A \<inter> B) \<^bold>* F g (A - B)" by (subst subset_diff [where B = "A - B"]) (auto simp: Diff_Diff_Int assms) lemma setdiff_irrelevant: assumes "finite A" shows "F g (A - {x. g x = z}) = F g A" using assms by (induct A) (simp_all add: insert_Diff_if) lemma not_neutral_contains_not_neutral: assumes "F g A \<noteq> \<^bold>1" obtains a where "a \<in> A" and "g a \<noteq> \<^bold>1" proof - from assms have "\<exists>a\<in>A. g a \<noteq> \<^bold>1" proof (induct A rule: infinite_finite_induct) case infinite then show ?case by simp next case empty then show ?case by simp next case (insert a A) then show ?case by fastforce qed with that show thesis by blast qed lemma cong [fundef_cong]: assumes "A = B" assumes g_h: "\<And>x. x \<in> B \<Longrightarrow> g x = h x" shows "F g A = F h B" using g_h unfolding \<open>A = B\<close> by (induct B rule: infinite_finite_induct) auto lemma cong_simp [cong]: "\<lbrakk> A = B; \<And>x. x \<in> B =simp=> g x = h x \<rbrakk> \<Longrightarrow> F (\<lambda>x. g x) A = F (\<lambda>x. h x) B" by (rule cong) (simp_all add: simp_implies_def) lemma reindex_cong: assumes "inj_on l B" assumes "A = l ` B" assumes "\<And>x. x \<in> B \<Longrightarrow> g (l x) = h x" shows "F g A = F h B" using assms by (simp add: reindex) lemma UNION_disjoint: assumes "finite I" and "\<forall>i\<in>I. finite (A i)" and "\<forall>i\<in>I. \<forall>j\<in>I. i \<noteq> j \<longrightarrow> A i \<inter> A j = {}" shows "F g (\<Union>(A ` I)) = F (\<lambda>x. F g (A x)) I" using assms proof (induction rule: finite_induct) case (insert i I) then have "\<forall>j\<in>I. j \<noteq> i" by blast with insert.prems have "A i \<inter> \<Union>(A ` I) = {}" by blast with insert show ?case by (simp add: union_disjoint) qed auto lemma Union_disjoint: assumes "\<forall>A\<in>C. finite A" "\<forall>A\<in>C. \<forall>B\<in>C. A \<noteq> B \<longrightarrow> A \<inter> B = {}" shows "F g (\<Union>C) = (F \<circ> F) g C" proof (cases "finite C") case True from UNION_disjoint [OF this assms] show ?thesis by simp next case False then show ?thesis by (auto dest: finite_UnionD intro: infinite) qed lemma distrib: "F (\<lambda>x. g x \<^bold>* h x) A = F g A \<^bold>* F h A" by (induct A rule: infinite_finite_induct) (simp_all add: assoc commute left_commute) lemma Sigma: assumes "finite A" "\<forall>x\<in>A. finite (B x)" shows "F (\<lambda>x. F (g x) (B x)) A = F (case_prod g) (SIGMA x:A. B x)" unfolding Sigma_def proof (subst UNION_disjoint) show "F (\<lambda>x. F (g x) (B x)) A = F (\<lambda>x. F (\<lambda>(x, y). g x y) (\<Union>y\<in>B x. {(x, y)})) A" proof (rule cong [OF refl]) show "F (g x) (B x) = F (\<lambda>(x, y). g x y) (\<Union>y\<in>B x. {(x, y)})" if "x \<in> A" for x using that assms by (simp add: UNION_disjoint) qed qed (use assms in auto) lemma related: assumes Re: "R \<^bold>1 \<^bold>1" and Rop: "\<forall>x1 y1 x2 y2. R x1 x2 \<and> R y1 y2 \<longrightarrow> R (x1 \<^bold>* y1) (x2 \<^bold>* y2)" and fin: "finite S" and R_h_g: "\<forall>x\<in>S. R (h x) (g x)" shows "R (F h S) (F g S)" using fin by (rule finite_subset_induct) (use assms in auto) lemma mono_neutral_cong_left: assumes "finite T" and "S \<subseteq> T" and "\<forall>i \<in> T - S. h i = \<^bold>1" and "\<And>x. x \<in> S \<Longrightarrow> g x = h x" shows "F g S = F h T" proof- have eq: "T = S \<union> (T - S)" using \<open>S \<subseteq> T\<close> by blast have d: "S \<inter> (T - S) = {}" using \<open>S \<subseteq> T\<close> by blast from \<open>finite T\<close> \<open>S \<subseteq> T\<close> have f: "finite S" "finite (T - S)" by (auto intro: finite_subset) show ?thesis using assms(4) by (simp add: union_disjoint [OF f d, unfolded eq [symmetric]] neutral [OF assms(3)]) qed lemma mono_neutral_cong_right: "finite T \<Longrightarrow> S \<subseteq> T \<Longrightarrow> \<forall>i \<in> T - S. g i = \<^bold>1 \<Longrightarrow> (\<And>x. x \<in> S \<Longrightarrow> g x = h x) \<Longrightarrow> F g T = F h S" by (auto intro!: mono_neutral_cong_left [symmetric]) lemma mono_neutral_left: "finite T \<Longrightarrow> S \<subseteq> T \<Longrightarrow> \<forall>i \<in> T - S. g i = \<^bold>1 \<Longrightarrow> F g S = F g T" by (blast intro: mono_neutral_cong_left) lemma mono_neutral_right: "finite T \<Longrightarrow> S \<subseteq> T \<Longrightarrow> \<forall>i \<in> T - S. g i = \<^bold>1 \<Longrightarrow> F g T = F g S" by (blast intro!: mono_neutral_left [symmetric]) lemma mono_neutral_cong: assumes [simp]: "finite T" "finite S" and *: "\<And>i. i \<in> T - S \<Longrightarrow> h i = \<^bold>1" "\<And>i. i \<in> S - T \<Longrightarrow> g i = \<^bold>1" and gh: "\<And>x. x \<in> S \<inter> T \<Longrightarrow> g x = h x" shows "F g S = F h T" proof- have "F g S = F g (S \<inter> T)" by(rule mono_neutral_right)(auto intro: *) also have "\<dots> = F h (S \<inter> T)" using refl gh by(rule cong) also have "\<dots> = F h T" by(rule mono_neutral_left)(auto intro: *) finally show ?thesis . qed lemma reindex_bij_betw: "bij_betw h S T \<Longrightarrow> F (\<lambda>x. g (h x)) S = F g T" by (auto simp: bij_betw_def reindex) lemma reindex_bij_witness: assumes witness: "\<And>a. a \<in> S \<Longrightarrow> i (j a) = a" "\<And>a. a \<in> S \<Longrightarrow> j a \<in> T" "\<And>b. b \<in> T \<Longrightarrow> j (i b) = b" "\<And>b. b \<in> T \<Longrightarrow> i b \<in> S" assumes eq: "\<And>a. a \<in> S \<Longrightarrow> h (j a) = g a" shows "F g S = F h T" proof - have "bij_betw j S T" using bij_betw_byWitness[where A=S and f=j and f'=i and A'=T] witness by auto moreover have "F g S = F (\<lambda>x. h (j x)) S" by (intro cong) (auto simp: eq) ultimately show ?thesis by (simp add: reindex_bij_betw) qed lemma reindex_bij_betw_not_neutral: assumes fin: "finite S'" "finite T'" assumes bij: "bij_betw h (S - S') (T - T')" assumes nn: "\<And>a. a \<in> S' \<Longrightarrow> g (h a) = z" "\<And>b. b \<in> T' \<Longrightarrow> g b = z" shows "F (\<lambda>x. g (h x)) S = F g T" proof - have [simp]: "finite S \<longleftrightarrow> finite T" using bij_betw_finite[OF bij] fin by auto show ?thesis proof (cases "finite S") case True with nn have "F (\<lambda>x. g (h x)) S = F (\<lambda>x. g (h x)) (S - S')" by (intro mono_neutral_cong_right) auto also have "\<dots> = F g (T - T')" using bij by (rule reindex_bij_betw) also have "\<dots> = F g T" using nn \<open>finite S\<close> by (intro mono_neutral_cong_left) auto finally show ?thesis . next case False then show ?thesis by simp qed qed lemma reindex_nontrivial: assumes "finite A" and nz: "\<And>x y. x \<in> A \<Longrightarrow> y \<in> A \<Longrightarrow> x \<noteq> y \<Longrightarrow> h x = h y \<Longrightarrow> g (h x) = \<^bold>1" shows "F g (h ` A) = F (g \<circ> h) A" proof (subst reindex_bij_betw_not_neutral [symmetric]) show "bij_betw h (A - {x \<in> A. (g \<circ> h) x = \<^bold>1}) (h ` A - h ` {x \<in> A. (g \<circ> h) x = \<^bold>1})" using nz by (auto intro!: inj_onI simp: bij_betw_def) qed (use \<open>finite A\<close> in auto) lemma reindex_bij_witness_not_neutral: assumes fin: "finite S'" "finite T'" assumes witness: "\<And>a. a \<in> S - S' \<Longrightarrow> i (j a) = a" "\<And>a. a \<in> S - S' \<Longrightarrow> j a \<in> T - T'" "\<And>b. b \<in> T - T' \<Longrightarrow> j (i b) = b" "\<And>b. b \<in> T - T' \<Longrightarrow> i b \<in> S - S'" assumes nn: "\<And>a. a \<in> S' \<Longrightarrow> g a = z" "\<And>b. b \<in> T' \<Longrightarrow> h b = z" assumes eq: "\<And>a. a \<in> S \<Longrightarrow> h (j a) = g a" shows "F g S = F h T" proof - have bij: "bij_betw j (S - (S' \<inter> S)) (T - (T' \<inter> T))" using witness by (intro bij_betw_byWitness[where f'=i]) auto have F_eq: "F g S = F (\<lambda>x. h (j x)) S" by (intro cong) (auto simp: eq) show ?thesis unfolding F_eq using fin nn eq by (intro reindex_bij_betw_not_neutral[OF _ _ bij]) auto qed lemma delta_remove: assumes fS: "finite S" shows "F (\<lambda>k. if k = a then b k else c k) S = (if a \<in> S then b a \<^bold>* F c (S-{a}) else F c (S-{a}))" proof - let ?f = "(\<lambda>k. if k = a then b k else c k)" show ?thesis proof (cases "a \<in> S") case False then have "\<forall>k\<in>S. ?f k = c k" by simp with False show ?thesis by simp next case True let ?A = "S - {a}" let ?B = "{a}" from True have eq: "S = ?A \<union> ?B" by blast have dj: "?A \<inter> ?B = {}" by simp from fS have fAB: "finite ?A" "finite ?B" by auto have "F ?f S = F ?f ?A \<^bold>* F ?f ?B" using union_disjoint [OF fAB dj, of ?f, unfolded eq [symmetric]] by simp with True show ?thesis using comm_monoid_set.remove comm_monoid_set_axioms fS by fastforce qed qed lemma delta [simp]: assumes fS: "finite S" shows "F (\<lambda>k. if k = a then b k else \<^bold>1) S = (if a \<in> S then b a else \<^bold>1)" by (simp add: delta_remove [OF assms]) lemma delta' [simp]: assumes fin: "finite S" shows "F (\<lambda>k. if a = k then b k else \<^bold>1) S = (if a \<in> S then b a else \<^bold>1)" using delta [OF fin, of a b, symmetric] by (auto intro: cong) lemma If_cases: fixes P :: "'b \<Rightarrow> bool" and g h :: "'b \<Rightarrow> 'a" assumes fin: "finite A" shows "F (\<lambda>x. if P x then h x else g x) A = F h (A \<inter> {x. P x}) \<^bold>* F g (A \<inter> - {x. P x})" proof - have a: "A = A \<inter> {x. P x} \<union> A \<inter> -{x. P x}" "(A \<inter> {x. P x}) \<inter> (A \<inter> -{x. P x}) = {}" by blast+ from fin have f: "finite (A \<inter> {x. P x})" "finite (A \<inter> -{x. P x})" by auto let ?g = "\<lambda>x. if P x then h x else g x" from union_disjoint [OF f a(2), of ?g] a(1) show ?thesis by (subst (1 2) cong) simp_all qed lemma cartesian_product: "F (\<lambda>x. F (g x) B) A = F (case_prod g) (A \<times> B)" proof (cases "A = {} \<or> B = {}") case True then show ?thesis by auto next case False then have "A \<noteq> {}" "B \<noteq> {}" by auto show ?thesis proof (cases "finite A \<and> finite B") case True then show ?thesis by (simp add: Sigma) next case False then consider "infinite A" | "infinite B" by auto then have "infinite (A \<times> B)" by cases (use \<open>A \<noteq> {}\<close> \<open>B \<noteq> {}\<close> in \<open>auto dest: finite_cartesian_productD1 finite_cartesian_productD2\<close>) then show ?thesis using False by auto qed qed lemma inter_restrict: assumes "finite A" shows "F g (A \<inter> B) = F (\<lambda>x. if x \<in> B then g x else \<^bold>1) A" proof - let ?g = "\<lambda>x. if x \<in> A \<inter> B then g x else \<^bold>1" have "\<forall>i\<in>A - A \<inter> B. (if i \<in> A \<inter> B then g i else \<^bold>1) = \<^bold>1" by simp moreover have "A \<inter> B \<subseteq> A" by blast ultimately have "F ?g (A \<inter> B) = F ?g A" using \<open>finite A\<close> by (intro mono_neutral_left) auto then show ?thesis by simp qed lemma inter_filter: "finite A \<Longrightarrow> F g {x \<in> A. P x} = F (\<lambda>x. if P x then g x else \<^bold>1) A" by (simp add: inter_restrict [symmetric, of A "{x. P x}" g, simplified mem_Collect_eq] Int_def) lemma Union_comp: assumes "\<forall>A \<in> B. finite A" and "\<And>A1 A2 x. A1 \<in> B \<Longrightarrow> A2 \<in> B \<Longrightarrow> A1 \<noteq> A2 \<Longrightarrow> x \<in> A1 \<Longrightarrow> x \<in> A2 \<Longrightarrow> g x = \<^bold>1" shows "F g (\<Union>B) = (F \<circ> F) g B" using assms proof (induct B rule: infinite_finite_induct) case (infinite A) then have "\<not> finite (\<Union>A)" by (blast dest: finite_UnionD) with infinite show ?case by simp next case empty then show ?case by simp next case (insert A B) then have "finite A" "finite B" "finite (\<Union>B)" "A \<notin> B" and "\<forall>x\<in>A \<inter> \<Union>B. g x = \<^bold>1" and H: "F g (\<Union>B) = (F \<circ> F) g B" by auto then have "F g (A \<union> \<Union>B) = F g A \<^bold>* F g (\<Union>B)" by (simp add: union_inter_neutral) with \<open>finite B\<close> \<open>A \<notin> B\<close> show ?case by (simp add: H) qed lemma swap: "F (\<lambda>i. F (g i) B) A = F (\<lambda>j. F (\<lambda>i. g i j) A) B" unfolding cartesian_product by (rule reindex_bij_witness [where i = "\<lambda>(i, j). (j, i)" and j = "\<lambda>(i, j). (j, i)"]) auto lemma swap_restrict: "finite A \<Longrightarrow> finite B \<Longrightarrow> F (\<lambda>x. F (g x) {y. y \<in> B \<and> R x y}) A = F (\<lambda>y. F (\<lambda>x. g x y) {x. x \<in> A \<and> R x y}) B" by (simp add: inter_filter) (rule swap) lemma image_gen: assumes fin: "finite S" shows "F h S = F (\<lambda>y. F h {x. x \<in> S \<and> g x = y}) (g ` S)" proof - have "{y. y\<in> g`S \<and> g x = y} = {g x}" if "x \<in> S" for x using that by auto then have "F h S = F (\<lambda>x. F (\<lambda>y. h x) {y. y\<in> g`S \<and> g x = y}) S" by simp also have "\<dots> = F (\<lambda>y. F h {x. x \<in> S \<and> g x = y}) (g ` S)" by (rule swap_restrict [OF fin finite_imageI [OF fin]]) finally show ?thesis . qed lemma group: assumes fS: "finite S" and fT: "finite T" and fST: "g ` S \<subseteq> T" shows "F (\<lambda>y. F h {x. x \<in> S \<and> g x = y}) T = F h S" unfolding image_gen[OF fS, of h g] by (auto intro: neutral mono_neutral_right[OF fT fST]) lemma Plus: fixes A :: "'b set" and B :: "'c set" assumes fin: "finite A" "finite B" shows "F g (A <+> B) = F (g \<circ> Inl) A \<^bold>* F (g \<circ> Inr) B" proof - have "A <+> B = Inl ` A \<union> Inr ` B" by auto moreover from fin have "finite (Inl ` A)" "finite (Inr ` B)" by auto moreover have "Inl ` A \<inter> Inr ` B = {}" by auto moreover have "inj_on Inl A" "inj_on Inr B" by (auto intro: inj_onI) ultimately show ?thesis using fin by (simp add: union_disjoint reindex) qed lemma same_carrier: assumes "finite C" assumes subset: "A \<subseteq> C" "B \<subseteq> C" assumes trivial: "\<And>a. a \<in> C - A \<Longrightarrow> g a = \<^bold>1" "\<And>b. b \<in> C - B \<Longrightarrow> h b = \<^bold>1" shows "F g A = F h B \<longleftrightarrow> F g C = F h C" proof - have "finite A" and "finite B" and "finite (C - A)" and "finite (C - B)" using \<open>finite C\<close> subset by (auto elim: finite_subset) from subset have [simp]: "A - (C - A) = A" by auto from subset have [simp]: "B - (C - B) = B" by auto from subset have "C = A \<union> (C - A)" by auto then have "F g C = F g (A \<union> (C - A))" by simp also have "\<dots> = F g (A - (C - A)) \<^bold>* F g (C - A - A) \<^bold>* F g (A \<inter> (C - A))" using \<open>finite A\<close> \<open>finite (C - A)\<close> by (simp only: union_diff2) finally have *: "F g C = F g A" using trivial by simp from subset have "C = B \<union> (C - B)" by auto then have "F h C = F h (B \<union> (C - B))" by simp also have "\<dots> = F h (B - (C - B)) \<^bold>* F h (C - B - B) \<^bold>* F h (B \<inter> (C - B))" using \<open>finite B\<close> \<open>finite (C - B)\<close> by (simp only: union_diff2) finally have "F h C = F h B" using trivial by simp with * show ?thesis by simp qed lemma same_carrierI: assumes "finite C" assumes subset: "A \<subseteq> C" "B \<subseteq> C" assumes trivial: "\<And>a. a \<in> C - A \<Longrightarrow> g a = \<^bold>1" "\<And>b. b \<in> C - B \<Longrightarrow> h b = \<^bold>1" assumes "F g C = F h C" shows "F g A = F h B" using assms same_carrier [of C A B] by simp lemma eq_general: assumes B: "\<And>y. y \<in> B \<Longrightarrow> \<exists>!x. x \<in> A \<and> h x = y" and A: "\<And>x. x \<in> A \<Longrightarrow> h x \<in> B \<and> \<gamma>(h x) = \<phi> x" shows "F \<phi> A = F \<gamma> B" proof - have eq: "B = h ` A" by (auto dest: assms) have h: "inj_on h A" using assms by (blast intro: inj_onI) have "F \<phi> A = F (\<gamma> \<circ> h) A" using A by auto also have "\<dots> = F \<gamma> B" by (simp add: eq reindex h) finally show ?thesis . qed lemma eq_general_inverses: assumes B: "\<And>y. y \<in> B \<Longrightarrow> k y \<in> A \<and> h(k y) = y" and A: "\<And>x. x \<in> A \<Longrightarrow> h x \<in> B \<and> k(h x) = x \<and> \<gamma>(h x) = \<phi> x" shows "F \<phi> A = F \<gamma> B" by (rule eq_general [where h=h]) (force intro: dest: A B)+ subsubsection \<open>HOL Light variant: sum/product indexed by the non-neutral subset\<close> text \<open>NB only a subset of the properties above are proved\<close> definition G :: "['b \<Rightarrow> 'a,'b set] \<Rightarrow> 'a" where "G p I \<equiv> if finite {x \<in> I. p x \<noteq> \<^bold>1} then F p {x \<in> I. p x \<noteq> \<^bold>1} else \<^bold>1" lemma finite_Collect_op: shows "\<lbrakk>finite {i \<in> I. x i \<noteq> \<^bold>1}; finite {i \<in> I. y i \<noteq> \<^bold>1}\<rbrakk> \<Longrightarrow> finite {i \<in> I. x i \<^bold>* y i \<noteq> \<^bold>1}" apply (rule finite_subset [where B = "{i \<in> I. x i \<noteq> \<^bold>1} \<union> {i \<in> I. y i \<noteq> \<^bold>1}"]) using left_neutral by force+ lemma empty' [simp]: "G p {} = \<^bold>1" by (auto simp: G_def) lemma eq_sum [simp]: "finite I \<Longrightarrow> G p I = F p I" by (auto simp: G_def intro: mono_neutral_cong_left) lemma insert' [simp]: assumes "finite {x \<in> I. p x \<noteq> \<^bold>1}" shows "G p (insert i I) = (if i \<in> I then G p I else p i \<^bold>* G p I)" proof - have "{x. x = i \<and> p x \<noteq> \<^bold>1 \<or> x \<in> I \<and> p x \<noteq> \<^bold>1} = (if p i = \<^bold>1 then {x \<in> I. p x \<noteq> \<^bold>1} else insert i {x \<in> I. p x \<noteq> \<^bold>1})" by auto then show ?thesis using assms by (simp add: G_def conj_disj_distribR insert_absorb) qed lemma distrib_triv': assumes "finite I" shows "G (\<lambda>i. g i \<^bold>* h i) I = G g I \<^bold>* G h I" by (simp add: assms local.distrib) lemma non_neutral': "G g {x \<in> I. g x \<noteq> \<^bold>1} = G g I" by (simp add: G_def) lemma distrib': assumes "finite {x \<in> I. g x \<noteq> \<^bold>1}" "finite {x \<in> I. h x \<noteq> \<^bold>1}" shows "G (\<lambda>i. g i \<^bold>* h i) I = G g I \<^bold>* G h I" proof - have "a \<^bold>* a \<noteq> a \<Longrightarrow> a \<noteq> \<^bold>1" for a by auto then have "G (\<lambda>i. g i \<^bold>* h i) I = G (\<lambda>i. g i \<^bold>* h i) ({i \<in> I. g i \<noteq> \<^bold>1} \<union> {i \<in> I. h i \<noteq> \<^bold>1})" using assms by (force simp: G_def finite_Collect_op intro!: mono_neutral_cong) also have "\<dots> = G g I \<^bold>* G h I" proof - have "F g ({i \<in> I. g i \<noteq> \<^bold>1} \<union> {i \<in> I. h i \<noteq> \<^bold>1}) = G g I" "F h ({i \<in> I. g i \<noteq> \<^bold>1} \<union> {i \<in> I. h i \<noteq> \<^bold>1}) = G h I" by (auto simp: G_def assms intro: mono_neutral_right) then show ?thesis using assms by (simp add: distrib) qed finally show ?thesis . qed lemma cong': assumes "A = B" assumes g_h: "\<And>x. x \<in> B \<Longrightarrow> g x = h x" shows "G g A = G h B" using assms by (auto simp: G_def cong: conj_cong intro: cong) lemma mono_neutral_cong_left': assumes "S \<subseteq> T" and "\<And>i. i \<in> T - S \<Longrightarrow> h i = \<^bold>1" and "\<And>x. x \<in> S \<Longrightarrow> g x = h x" shows "G g S = G h T" proof - have *: "{x \<in> S. g x \<noteq> \<^bold>1} = {x \<in> T. h x \<noteq> \<^bold>1}" using assms by (metis DiffI subset_eq) then have "finite {x \<in> S. g x \<noteq> \<^bold>1} = finite {x \<in> T. h x \<noteq> \<^bold>1}" by simp then show ?thesis using assms by (auto simp add: G_def * intro: cong) qed lemma mono_neutral_cong_right': "S \<subseteq> T \<Longrightarrow> \<forall>i \<in> T - S. g i = \<^bold>1 \<Longrightarrow> (\<And>x. x \<in> S \<Longrightarrow> g x = h x) \<Longrightarrow> G g T = G h S" by (auto intro!: mono_neutral_cong_left' [symmetric]) lemma mono_neutral_left': "S \<subseteq> T \<Longrightarrow> \<forall>i \<in> T - S. g i = \<^bold>1 \<Longrightarrow> G g S = G g T" by (blast intro: mono_neutral_cong_left') lemma mono_neutral_right': "S \<subseteq> T \<Longrightarrow> \<forall>i \<in> T - S. g i = \<^bold>1 \<Longrightarrow> G g T = G g S" by (blast intro!: mono_neutral_left' [symmetric]) end subsection \<open>Generalized summation over a set\<close> context comm_monoid_add begin sublocale sum: comm_monoid_set plus 0 defines sum = sum.F and sum' = sum.G .. abbreviation Sum ("\<Sum>") where "\<Sum> \<equiv> sum (\<lambda>x. x)" end text \<open>Now: lots of fancy syntax. First, \<^term>\<open>sum (\<lambda>x. e) A\<close> is written \<open>\<Sum>x\<in>A. e\<close>.\<close> syntax (ASCII) "_sum" :: "pttrn \<Rightarrow> 'a set \<Rightarrow> 'b \<Rightarrow> 'b::comm_monoid_add" ("(3SUM (_/:_)./ _)" [0, 51, 10] 10) syntax "_sum" :: "pttrn \<Rightarrow> 'a set \<Rightarrow> 'b \<Rightarrow> 'b::comm_monoid_add" ("(2\<Sum>(_/\<in>_)./ _)" [0, 51, 10] 10) translations \<comment> \<open>Beware of argument permutation!\<close> "\<Sum>i\<in>A. b" \<rightleftharpoons> "CONST sum (\<lambda>i. b) A" text \<open>Instead of \<^term>\<open>\<Sum>x\<in>{x. P}. e\<close> we introduce the shorter \<open>\<Sum>x|P. e\<close>.\<close> syntax (ASCII) "_qsum" :: "pttrn \<Rightarrow> bool \<Rightarrow> 'a \<Rightarrow> 'a" ("(3SUM _ |/ _./ _)" [0, 0, 10] 10) syntax "_qsum" :: "pttrn \<Rightarrow> bool \<Rightarrow> 'a \<Rightarrow> 'a" ("(2\<Sum>_ | (_)./ _)" [0, 0, 10] 10) translations "\<Sum>x|P. t" => "CONST sum (\<lambda>x. t) {x. P}" print_translation \<open> let fun sum_tr' [Abs (x, Tx, t), Const (\<^const_syntax>\<open>Collect\<close>, _) $ Abs (y, Ty, P)] = if x <> y then raise Match else let val x' = Syntax_Trans.mark_bound_body (x, Tx); val t' = subst_bound (x', t); val P' = subst_bound (x', P); in Syntax.const \<^syntax_const>\<open>_qsum\<close> $ Syntax_Trans.mark_bound_abs (x, Tx) $ P' $ t' end | sum_tr' _ = raise Match; in [(\<^const_syntax>\<open>sum\<close>, K sum_tr')] end \<close> subsubsection \<open>Properties in more restricted classes of structures\<close> lemma sum_Un: "finite A \<Longrightarrow> finite B \<Longrightarrow> sum f (A \<union> B) = sum f A + sum f B - sum f (A \<inter> B)" for f :: "'b \<Rightarrow> 'a::ab_group_add" by (subst sum.union_inter [symmetric]) (auto simp add: algebra_simps) lemma sum_Un2: assumes "finite (A \<union> B)" shows "sum f (A \<union> B) = sum f (A - B) + sum f (B - A) + sum f (A \<inter> B)" proof - have "A \<union> B = A - B \<union> (B - A) \<union> A \<inter> B" by auto with assms show ?thesis by simp (subst sum.union_disjoint, auto)+ qed lemma sum_diff1: fixes f :: "'b \<Rightarrow> 'a::ab_group_add" assumes "finite A" shows "sum f (A - {a}) = (if a \<in> A then sum f A - f a else sum f A)" using assms by induct (auto simp: insert_Diff_if) lemma sum_diff: fixes f :: "'b \<Rightarrow> 'a::ab_group_add" assumes "finite A" "B \<subseteq> A" shows "sum f (A - B) = sum f A - sum f B" proof - from assms(2,1) have "finite B" by (rule finite_subset) from this \<open>B \<subseteq> A\<close> show ?thesis proof induct case empty thus ?case by simp next case (insert x F) with \<open>finite A\<close> \<open>finite B\<close> show ?case by (simp add: Diff_insert[where a=x and B=F] sum_diff1 insert_absorb) qed qed lemma sum_diff1'_aux: fixes f :: "'a \<Rightarrow> 'b::ab_group_add" assumes "finite F" "{i \<in> I. f i \<noteq> 0} \<subseteq> F" shows "sum' f (I - {i}) = (if i \<in> I then sum' f I - f i else sum' f I)" using assms proof induct case (insert x F) have 1: "finite {x \<in> I. f x \<noteq> 0} \<Longrightarrow> finite {x \<in> I. x \<noteq> i \<and> f x \<noteq> 0}" by (erule rev_finite_subset) auto have 2: "finite {x \<in> I. x \<noteq> i \<and> f x \<noteq> 0} \<Longrightarrow> finite {x \<in> I. f x \<noteq> 0}" apply (drule finite_insert [THEN iffD2]) by (erule rev_finite_subset) auto have 3: "finite {i \<in> I. f i \<noteq> 0}" using finite_subset insert by blast show ?case using insert sum_diff1 [of "{i \<in> I. f i \<noteq> 0}" f i] by (auto simp: sum.G_def 1 2 3 set_diff_eq conj_ac) qed (simp add: sum.G_def) lemma sum_diff1': fixes f :: "'a \<Rightarrow> 'b::ab_group_add" assumes "finite {i \<in> I. f i \<noteq> 0}" shows "sum' f (I - {i}) = (if i \<in> I then sum' f I - f i else sum' f I)" by (rule sum_diff1'_aux [OF assms order_refl]) lemma (in ordered_comm_monoid_add) sum_mono: "(\<And>i. i\<in>K \<Longrightarrow> f i \<le> g i) \<Longrightarrow> (\<Sum>i\<in>K. f i) \<le> (\<Sum>i\<in>K. g i)" by (induct K rule: infinite_finite_induct) (use add_mono in auto) lemma (in strict_ordered_comm_monoid_add) sum_strict_mono: assumes "finite A" "A \<noteq> {}" and "\<And>x. x \<in> A \<Longrightarrow> f x < g x" shows "sum f A < sum g A" using assms proof (induct rule: finite_ne_induct) case singleton then show ?case by simp next case insert then show ?case by (auto simp: add_strict_mono) qed lemma sum_strict_mono_ex1: fixes f g :: "'i \<Rightarrow> 'a::ordered_cancel_comm_monoid_add" assumes "finite A" and "\<forall>x\<in>A. f x \<le> g x" and "\<exists>a\<in>A. f a < g a" shows "sum f A < sum g A" proof- from assms(3) obtain a where a: "a \<in> A" "f a < g a" by blast have "sum f A = sum f ((A - {a}) \<union> {a})" by(simp add: insert_absorb[OF \<open>a \<in> A\<close>]) also have "\<dots> = sum f (A - {a}) + sum f {a}" using \<open>finite A\<close> by(subst sum.union_disjoint) auto also have "sum f (A - {a}) \<le> sum g (A - {a})" by (rule sum_mono) (simp add: assms(2)) also from a have "sum f {a} < sum g {a}" by simp also have "sum g (A - {a}) + sum g {a} = sum g((A - {a}) \<union> {a})" using \<open>finite A\<close> by (subst sum.union_disjoint[symmetric]) auto also have "\<dots> = sum g A" by (simp add: insert_absorb[OF \<open>a \<in> A\<close>]) finally show ?thesis by (auto simp add: add_right_mono add_strict_left_mono) qed lemma sum_mono_inv: fixes f g :: "'i \<Rightarrow> 'a :: ordered_cancel_comm_monoid_add" assumes eq: "sum f I = sum g I" assumes le: "\<And>i. i \<in> I \<Longrightarrow> f i \<le> g i" assumes i: "i \<in> I" assumes I: "finite I" shows "f i = g i" proof (rule ccontr) assume "\<not> ?thesis" with le[OF i] have "f i < g i" by simp with i have "\<exists>i\<in>I. f i < g i" .. from sum_strict_mono_ex1[OF I _ this] le have "sum f I < sum g I" by blast with eq show False by simp qed lemma member_le_sum: fixes f :: "_ \<Rightarrow> 'b::{semiring_1, ordered_comm_monoid_add}" assumes "i \<in> A" and le: "\<And>x. x \<in> A - {i} \<Longrightarrow> 0 \<le> f x" and "finite A" shows "f i \<le> sum f A" proof - have "f i \<le> sum f (A \<inter> {i})" by (simp add: assms) also have "... = (\<Sum>x\<in>A. if x \<in> {i} then f x else 0)" using assms sum.inter_restrict by blast also have "... \<le> sum f A" apply (rule sum_mono) apply (auto simp: le) done finally show ?thesis . qed lemma sum_negf: "(\<Sum>x\<in>A. - f x) = - (\<Sum>x\<in>A. f x)" for f :: "'b \<Rightarrow> 'a::ab_group_add" by (induct A rule: infinite_finite_induct) auto lemma sum_subtractf: "(\<Sum>x\<in>A. f x - g x) = (\<Sum>x\<in>A. f x) - (\<Sum>x\<in>A. g x)" for f g :: "'b \<Rightarrow>'a::ab_group_add" using sum.distrib [of f "- g" A] by (simp add: sum_negf) lemma sum_subtractf_nat: "(\<And>x. x \<in> A \<Longrightarrow> g x \<le> f x) \<Longrightarrow> (\<Sum>x\<in>A. f x - g x) = (\<Sum>x\<in>A. f x) - (\<Sum>x\<in>A. g x)" for f g :: "'a \<Rightarrow> nat" by (induct A rule: infinite_finite_induct) (auto simp: sum_mono) context ordered_comm_monoid_add begin lemma sum_nonneg: "(\<And>x. x \<in> A \<Longrightarrow> 0 \<le> f x) \<Longrightarrow> 0 \<le> sum f A" proof (induct A rule: infinite_finite_induct) case infinite then show ?case by simp next case empty then show ?case by simp next case (insert x F) then have "0 + 0 \<le> f x + sum f F" by (blast intro: add_mono) with insert show ?case by simp qed lemma sum_nonpos: "(\<And>x. x \<in> A \<Longrightarrow> f x \<le> 0) \<Longrightarrow> sum f A \<le> 0" proof (induct A rule: infinite_finite_induct) case infinite then show ?case by simp next case empty then show ?case by simp next case (insert x F) then have "f x + sum f F \<le> 0 + 0" by (blast intro: add_mono) with insert show ?case by simp qed lemma sum_nonneg_eq_0_iff: "finite A \<Longrightarrow> (\<And>x. x \<in> A \<Longrightarrow> 0 \<le> f x) \<Longrightarrow> sum f A = 0 \<longleftrightarrow> (\<forall>x\<in>A. f x = 0)" by (induct set: finite) (simp_all add: add_nonneg_eq_0_iff sum_nonneg) lemma sum_nonneg_0: "finite s \<Longrightarrow> (\<And>i. i \<in> s \<Longrightarrow> f i \<ge> 0) \<Longrightarrow> (\<Sum> i \<in> s. f i) = 0 \<Longrightarrow> i \<in> s \<Longrightarrow> f i = 0" by (simp add: sum_nonneg_eq_0_iff) lemma sum_nonneg_leq_bound: assumes "finite s" "\<And>i. i \<in> s \<Longrightarrow> f i \<ge> 0" "(\<Sum>i \<in> s. f i) = B" "i \<in> s" shows "f i \<le> B" proof - from assms have "f i \<le> f i + (\<Sum>i \<in> s - {i}. f i)" by (intro add_increasing2 sum_nonneg) auto also have "\<dots> = B" using sum.remove[of s i f] assms by simp finally show ?thesis by auto qed lemma sum_mono2: assumes fin: "finite B" and sub: "A \<subseteq> B" and nn: "\<And>b. b \<in> B-A \<Longrightarrow> 0 \<le> f b" shows "sum f A \<le> sum f B" proof - have "sum f A \<le> sum f A + sum f (B-A)" by (auto intro: add_increasing2 [OF sum_nonneg] nn) also from fin finite_subset[OF sub fin] have "\<dots> = sum f (A \<union> (B-A))" by (simp add: sum.union_disjoint del: Un_Diff_cancel) also from sub have "A \<union> (B-A) = B" by blast finally show ?thesis . qed lemma sum_le_included: assumes "finite s" "finite t" and "\<forall>y\<in>t. 0 \<le> g y" "(\<forall>x\<in>s. \<exists>y\<in>t. i y = x \<and> f x \<le> g y)" shows "sum f s \<le> sum g t" proof - have "sum f s \<le> sum (\<lambda>y. sum g {x. x\<in>t \<and> i x = y}) s" proof (rule sum_mono) fix y assume "y \<in> s" with assms obtain z where z: "z \<in> t" "y = i z" "f y \<le> g z" by auto with assms show "f y \<le> sum g {x \<in> t. i x = y}" (is "?A y \<le> ?B y") using order_trans[of "?A (i z)" "sum g {z}" "?B (i z)", intro] by (auto intro!: sum_mono2) qed also have "\<dots> \<le> sum (\<lambda>y. sum g {x. x\<in>t \<and> i x = y}) (i ` t)" using assms(2-4) by (auto intro!: sum_mono2 sum_nonneg) also have "\<dots> \<le> sum g t" using assms by (auto simp: sum.image_gen[symmetric]) finally show ?thesis . qed end lemma (in canonically_ordered_monoid_add) sum_eq_0_iff [simp]: "finite F \<Longrightarrow> (sum f F = 0) = (\<forall>a\<in>F. f a = 0)" by (intro ballI sum_nonneg_eq_0_iff zero_le) context semiring_0 begin lemma sum_distrib_left: "r * sum f A = (\<Sum>n\<in>A. r * f n)" by (induct A rule: infinite_finite_induct) (simp_all add: algebra_simps) lemma sum_distrib_right: "sum f A * r = (\<Sum>n\<in>A. f n * r)" by (induct A rule: infinite_finite_induct) (simp_all add: algebra_simps) end lemma sum_divide_distrib: "sum f A / r = (\<Sum>n\<in>A. f n / r)" for r :: "'a::field" proof (induct A rule: infinite_finite_induct) case infinite then show ?case by simp next case empty then show ?case by simp next case insert then show ?case by (simp add: add_divide_distrib) qed lemma sum_abs[iff]: "\<bar>sum f A\<bar> \<le> sum (\<lambda>i. \<bar>f i\<bar>) A" for f :: "'a \<Rightarrow> 'b::ordered_ab_group_add_abs" proof (induct A rule: infinite_finite_induct) case infinite then show ?case by simp next case empty then show ?case by simp next case insert then show ?case by (auto intro: abs_triangle_ineq order_trans) qed lemma sum_abs_ge_zero[iff]: "0 \<le> sum (\<lambda>i. \<bar>f i\<bar>) A" for f :: "'a \<Rightarrow> 'b::ordered_ab_group_add_abs" by (simp add: sum_nonneg) lemma abs_sum_abs[simp]: "\<bar>\<Sum>a\<in>A. \<bar>f a\<bar>\<bar> = (\<Sum>a\<in>A. \<bar>f a\<bar>)" for f :: "'a \<Rightarrow> 'b::ordered_ab_group_add_abs" proof (induct A rule: infinite_finite_induct) case infinite then show ?case by simp next case empty then show ?case by simp next case (insert a A) then have "\<bar>\<Sum>a\<in>insert a A. \<bar>f a\<bar>\<bar> = \<bar>\<bar>f a\<bar> + (\<Sum>a\<in>A. \<bar>f a\<bar>)\<bar>" by simp also from insert have "\<dots> = \<bar>\<bar>f a\<bar> + \<bar>\<Sum>a\<in>A. \<bar>f a\<bar>\<bar>\<bar>" by simp also have "\<dots> = \<bar>f a\<bar> + \<bar>\<Sum>a\<in>A. \<bar>f a\<bar>\<bar>" by (simp del: abs_of_nonneg) also from insert have "\<dots> = (\<Sum>a\<in>insert a A. \<bar>f a\<bar>)" by simp finally show ?case . qed lemma sum_product: fixes f :: "'a \<Rightarrow> 'b::semiring_0" shows "sum f A * sum g B = (\<Sum>i\<in>A. \<Sum>j\<in>B. f i * g j)" by (simp add: sum_distrib_left sum_distrib_right) (rule sum.swap) lemma sum_mult_sum_if_inj: fixes f :: "'a \<Rightarrow> 'b::semiring_0" shows "inj_on (\<lambda>(a, b). f a * g b) (A \<times> B) \<Longrightarrow> sum f A * sum g B = sum id {f a * g b |a b. a \<in> A \<and> b \<in> B}" by(auto simp: sum_product sum.cartesian_product intro!: sum.reindex_cong[symmetric]) lemma sum_SucD: "sum f A = Suc n \<Longrightarrow> \<exists>a\<in>A. 0 < f a" by (induct A rule: infinite_finite_induct) auto lemma sum_eq_Suc0_iff: "finite A \<Longrightarrow> sum f A = Suc 0 \<longleftrightarrow> (\<exists>a\<in>A. f a = Suc 0 \<and> (\<forall>b\<in>A. a \<noteq> b \<longrightarrow> f b = 0))" by (induct A rule: finite_induct) (auto simp add: add_is_1) lemmas sum_eq_1_iff = sum_eq_Suc0_iff[simplified One_nat_def[symmetric]] lemma sum_Un_nat: "finite A \<Longrightarrow> finite B \<Longrightarrow> sum f (A \<union> B) = sum f A + sum f B - sum f (A \<inter> B)" for f :: "'a \<Rightarrow> nat" \<comment> \<open>For the natural numbers, we have subtraction.\<close> by (subst sum.union_inter [symmetric]) (auto simp: algebra_simps) lemma sum_diff1_nat: "sum f (A - {a}) = (if a \<in> A then sum f A - f a else sum f A)" for f :: "'a \<Rightarrow> nat" proof (induct A rule: infinite_finite_induct) case infinite then show ?case by simp next case empty then show ?case by simp next case insert then show ?case apply (auto simp: insert_Diff_if) apply (drule mk_disjoint_insert) apply auto done qed lemma sum_diff_nat: fixes f :: "'a \<Rightarrow> nat" assumes "finite B" and "B \<subseteq> A" shows "sum f (A - B) = sum f A - sum f B" using assms proof induct case empty then show ?case by simp next case (insert x F) note IH = \<open>F \<subseteq> A \<Longrightarrow> sum f (A - F) = sum f A - sum f F\<close> from \<open>x \<notin> F\<close> \<open>insert x F \<subseteq> A\<close> have "x \<in> A - F" by simp then have A: "sum f ((A - F) - {x}) = sum f (A - F) - f x" by (simp add: sum_diff1_nat) from \<open>insert x F \<subseteq> A\<close> have "F \<subseteq> A" by simp with IH have "sum f (A - F) = sum f A - sum f F" by simp with A have B: "sum f ((A - F) - {x}) = sum f A - sum f F - f x" by simp from \<open>x \<notin> F\<close> have "A - insert x F = (A - F) - {x}" by auto with B have C: "sum f (A - insert x F) = sum f A - sum f F - f x" by simp from \<open>finite F\<close> \<open>x \<notin> F\<close> have "sum f (insert x F) = sum f F + f x" by simp with C have "sum f (A - insert x F) = sum f A - sum f (insert x F)" by simp then show ?case by simp qed lemma sum_comp_morphism: "h 0 = 0 \<Longrightarrow> (\<And>x y. h (x + y) = h x + h y) \<Longrightarrow> sum (h \<circ> g) A = h (sum g A)" by (induct A rule: infinite_finite_induct) simp_all lemma (in comm_semiring_1) dvd_sum: "(\<And>a. a \<in> A \<Longrightarrow> d dvd f a) \<Longrightarrow> d dvd sum f A" by (induct A rule: infinite_finite_induct) simp_all lemma (in ordered_comm_monoid_add) sum_pos: "finite I \<Longrightarrow> I \<noteq> {} \<Longrightarrow> (\<And>i. i \<in> I \<Longrightarrow> 0 < f i) \<Longrightarrow> 0 < sum f I" by (induct I rule: finite_ne_induct) (auto intro: add_pos_pos) lemma (in ordered_comm_monoid_add) sum_pos2: assumes I: "finite I" "i \<in> I" "0 < f i" "\<And>i. i \<in> I \<Longrightarrow> 0 \<le> f i" shows "0 < sum f I" proof - have "0 < f i + sum f (I - {i})" using assms by (intro add_pos_nonneg sum_nonneg) auto also have "\<dots> = sum f I" using assms by (simp add: sum.remove) finally show ?thesis . qed lemma sum_cong_Suc: assumes "0 \<notin> A" "\<And>x. Suc x \<in> A \<Longrightarrow> f (Suc x) = g (Suc x)" shows "sum f A = sum g A" proof (rule sum.cong) fix x assume "x \<in> A" with assms(1) show "f x = g x" by (cases x) (auto intro!: assms(2)) qed simp_all subsubsection \<open>Cardinality as special case of \<^const>\<open>sum\<close>\<close> lemma card_eq_sum: "card A = sum (\<lambda>x. 1) A" proof - have "plus \<circ> (\<lambda>_. Suc 0) = (\<lambda>_. Suc)" by (simp add: fun_eq_iff) then have "Finite_Set.fold (plus \<circ> (\<lambda>_. Suc 0)) = Finite_Set.fold (\<lambda>_. Suc)" by (rule arg_cong) then have "Finite_Set.fold (plus \<circ> (\<lambda>_. Suc 0)) 0 A = Finite_Set.fold (\<lambda>_. Suc) 0 A" by (blast intro: fun_cong) then show ?thesis by (simp add: card.eq_fold sum.eq_fold) qed context semiring_1 begin lemma sum_constant [simp]: "(\<Sum>x \<in> A. y) = of_nat (card A) * y" by (induct A rule: infinite_finite_induct) (simp_all add: algebra_simps) end lemma sum_Suc: "sum (\<lambda>x. Suc(f x)) A = sum f A + card A" using sum.distrib[of f "\<lambda>_. 1" A] by simp lemma sum_bounded_above: fixes K :: "'a::{semiring_1,ordered_comm_monoid_add}" assumes le: "\<And>i. i\<in>A \<Longrightarrow> f i \<le> K" shows "sum f A \<le> of_nat (card A) * K" proof (cases "finite A") case True then show ?thesis using le sum_mono[where K=A and g = "\<lambda>x. K"] by simp next case False then show ?thesis by simp qed lemma sum_bounded_above_divide: fixes K :: "'a::linordered_field" assumes le: "\<And>i. i\<in>A \<Longrightarrow> f i \<le> K / of_nat (card A)" and fin: "finite A" "A \<noteq> {}" shows "sum f A \<le> K" using sum_bounded_above [of A f "K / of_nat (card A)", OF le] fin by simp lemma sum_bounded_above_strict: fixes K :: "'a::{ordered_cancel_comm_monoid_add,semiring_1}" assumes "\<And>i. i\<in>A \<Longrightarrow> f i < K" "card A > 0" shows "sum f A < of_nat (card A) * K" using assms sum_strict_mono[where A=A and g = "\<lambda>x. K"] by (simp add: card_gt_0_iff) lemma sum_bounded_below: fixes K :: "'a::{semiring_1,ordered_comm_monoid_add}" assumes le: "\<And>i. i\<in>A \<Longrightarrow> K \<le> f i" shows "of_nat (card A) * K \<le> sum f A" proof (cases "finite A") case True then show ?thesis using le sum_mono[where K=A and f = "\<lambda>x. K"] by simp next case False then show ?thesis by simp qed lemma convex_sum_bound_le: fixes x :: "'a \<Rightarrow> 'b::linordered_idom" assumes 0: "\<And>i. i \<in> I \<Longrightarrow> 0 \<le> x i" and 1: "sum x I = 1" and \<delta>: "\<And>i. i \<in> I \<Longrightarrow> \<bar>a i - b\<bar> \<le> \<delta>" shows "\<bar>(\<Sum>i\<in>I. a i * x i) - b\<bar> \<le> \<delta>" proof - have [simp]: "(\<Sum>i\<in>I. c * x i) = c" for c by (simp flip: sum_distrib_left 1) then have "\<bar>(\<Sum>i\<in>I. a i * x i) - b\<bar> = \<bar>\<Sum>i\<in>I. (a i - b) * x i\<bar>" by (simp add: sum_subtractf left_diff_distrib) also have "\<dots> \<le> (\<Sum>i\<in>I. \<bar>(a i - b) * x i\<bar>)" using abs_abs abs_of_nonneg by blast also have "\<dots> \<le> (\<Sum>i\<in>I. \<bar>(a i - b)\<bar> * x i)" by (simp add: abs_mult 0) also have "\<dots> \<le> (\<Sum>i\<in>I. \<delta> * x i)" by (rule sum_mono) (use \<delta> "0" mult_right_mono in blast) also have "\<dots> = \<delta>" by simp finally show ?thesis . qed lemma card_UN_disjoint: assumes "finite I" and "\<forall>i\<in>I. finite (A i)" and "\<forall>i\<in>I. \<forall>j\<in>I. i \<noteq> j \<longrightarrow> A i \<inter> A j = {}" shows "card (\<Union>(A ` I)) = (\<Sum>i\<in>I. card(A i))" proof - have "(\<Sum>i\<in>I. card (A i)) = (\<Sum>i\<in>I. \<Sum>x\<in>A i. 1)" by simp with assms show ?thesis by (simp add: card_eq_sum sum.UNION_disjoint del: sum_constant) qed lemma card_Union_disjoint: assumes "pairwise disjnt C" and fin: "\<And>A. A \<in> C \<Longrightarrow> finite A" shows "card (\<Union>C) = sum card C" proof (cases "finite C") case True then show ?thesis using card_UN_disjoint [OF True, of "\<lambda>x. x"] assms by (simp add: disjnt_def fin pairwise_def) next case False then show ?thesis using assms card_eq_0_iff finite_UnionD by fastforce qed lemma card_Union_le_sum_card: fixes U :: "'a set set" assumes "\<forall>u \<in> U. finite u" shows "card (\<Union>U) \<le> sum card U" proof (cases "finite U") case False then show "card (\<Union>U) \<le> sum card U" using card_eq_0_iff finite_UnionD by auto next case True then show "card (\<Union>U) \<le> sum card U" proof (induct U rule: finite_induct) case empty then show ?case by auto next case (insert x F) then have "card(\<Union>(insert x F)) \<le> card(x) + card (\<Union>F)" using card_Un_le by auto also have "... \<le> card(x) + sum card F" using insert.hyps by auto also have "... = sum card (insert x F)" using sum.insert_if and insert.hyps by auto finally show ?case . qed qed lemma card_UN_le: assumes "finite I" shows "card(\<Union>i\<in>I. A i) \<le> (\<Sum>i\<in>I. card(A i))" using assms proof induction case (insert i I) then show ?case using card_Un_le nat_add_left_cancel_le by (force intro: order_trans) qed auto lemma sum_multicount_gen: assumes "finite s" "finite t" "\<forall>j\<in>t. (card {i\<in>s. R i j} = k j)" shows "sum (\<lambda>i. (card {j\<in>t. R i j})) s = sum k t" (is "?l = ?r") proof- have "?l = sum (\<lambda>i. sum (\<lambda>x.1) {j\<in>t. R i j}) s" by auto also have "\<dots> = ?r" unfolding sum.swap_restrict [OF assms(1-2)] using assms(3) by auto finally show ?thesis . qed lemma sum_multicount: assumes "finite S" "finite T" "\<forall>j\<in>T. (card {i\<in>S. R i j} = k)" shows "sum (\<lambda>i. card {j\<in>T. R i j}) S = k * card T" (is "?l = ?r") proof- have "?l = sum (\<lambda>i. k) T" by (rule sum_multicount_gen) (auto simp: assms) also have "\<dots> = ?r" by (simp add: mult.commute) finally show ?thesis by auto qed lemma sum_card_image: assumes "finite A" assumes "pairwise (\<lambda>s t. disjnt (f s) (f t)) A" shows "sum card (f ` A) = sum (\<lambda>a. card (f a)) A" using assms proof (induct A) case (insert a A) show ?case proof cases assume "f a = {}" with insert show ?case by (subst sum.mono_neutral_right[where S="f ` A"]) (auto simp: pairwise_insert) next assume "f a \<noteq> {}" then have "sum card (insert (f a) (f ` A)) = card (f a) + sum card (f ` A)" using insert by (subst sum.insert) (auto simp: pairwise_insert) with insert show ?case by (simp add: pairwise_insert) qed qed simp subsubsection \<open>Cardinality of products\<close> lemma card_SigmaI [simp]: "finite A \<Longrightarrow> \<forall>a\<in>A. finite (B a) \<Longrightarrow> card (SIGMA x: A. B x) = (\<Sum>a\<in>A. card (B a))" by (simp add: card_eq_sum sum.Sigma del: sum_constant) (* lemma SigmaI_insert: "y \<notin> A ==> (SIGMA x:(insert y A). B x) = (({y} \<times> (B y)) \<union> (SIGMA x: A. B x))" by auto *) lemma card_cartesian_product: "card (A \<times> B) = card A * card B" by (cases "finite A \<and> finite B") (auto simp add: card_eq_0_iff dest: finite_cartesian_productD1 finite_cartesian_productD2) lemma card_cartesian_product_singleton: "card ({x} \<times> A) = card A" by (simp add: card_cartesian_product) subsection \<open>Generalized product over a set\<close> context comm_monoid_mult begin sublocale prod: comm_monoid_set times 1 defines prod = prod.F and prod' = prod.G .. abbreviation Prod ("\<Prod>_" [1000] 999) where "\<Prod>A \<equiv> prod (\<lambda>x. x) A" end syntax (ASCII) "_prod" :: "pttrn => 'a set => 'b => 'b::comm_monoid_mult" ("(4PROD (_/:_)./ _)" [0, 51, 10] 10) syntax "_prod" :: "pttrn => 'a set => 'b => 'b::comm_monoid_mult" ("(2\<Prod>(_/\<in>_)./ _)" [0, 51, 10] 10) translations \<comment> \<open>Beware of argument permutation!\<close> "\<Prod>i\<in>A. b" == "CONST prod (\<lambda>i. b) A" text \<open>Instead of \<^term>\<open>\<Prod>x\<in>{x. P}. e\<close> we introduce the shorter \<open>\<Prod>x|P. e\<close>.\<close> syntax (ASCII) "_qprod" :: "pttrn \<Rightarrow> bool \<Rightarrow> 'a \<Rightarrow> 'a" ("(4PROD _ |/ _./ _)" [0, 0, 10] 10) syntax "_qprod" :: "pttrn \<Rightarrow> bool \<Rightarrow> 'a \<Rightarrow> 'a" ("(2\<Prod>_ | (_)./ _)" [0, 0, 10] 10) translations "\<Prod>x|P. t" => "CONST prod (\<lambda>x. t) {x. P}" context comm_monoid_mult begin lemma prod_dvd_prod: "(\<And>a. a \<in> A \<Longrightarrow> f a dvd g a) \<Longrightarrow> prod f A dvd prod g A" proof (induct A rule: infinite_finite_induct) case infinite then show ?case by (auto intro: dvdI) next case empty then show ?case by (auto intro: dvdI) next case (insert a A) then have "f a dvd g a" and "prod f A dvd prod g A" by simp_all then obtain r s where "g a = f a * r" and "prod g A = prod f A * s" by (auto elim!: dvdE) then have "g a * prod g A = f a * prod f A * (r * s)" by (simp add: ac_simps) with insert.hyps show ?case by (auto intro: dvdI) qed lemma prod_dvd_prod_subset: "finite B \<Longrightarrow> A \<subseteq> B \<Longrightarrow> prod f A dvd prod f B" by (auto simp add: prod.subset_diff ac_simps intro: dvdI) end subsubsection \<open>Properties in more restricted classes of structures\<close> context linordered_nonzero_semiring begin lemma prod_ge_1: "(\<And>x. x \<in> A \<Longrightarrow> 1 \<le> f x) \<Longrightarrow> 1 \<le> prod f A" proof (induct A rule: infinite_finite_induct) case infinite then show ?case by simp next case empty then show ?case by simp next case (insert x F) have "1 * 1 \<le> f x * prod f F" by (rule mult_mono') (use insert in auto) with insert show ?case by simp qed lemma prod_le_1: fixes f :: "'b \<Rightarrow> 'a" assumes "\<And>x. x \<in> A \<Longrightarrow> 0 \<le> f x \<and> f x \<le> 1" shows "prod f A \<le> 1" using assms proof (induct A rule: infinite_finite_induct) case infinite then show ?case by simp next case empty then show ?case by simp next case (insert x F) then show ?case by (force simp: mult.commute intro: dest: mult_le_one) qed end context comm_semiring_1 begin lemma dvd_prod_eqI [intro]: assumes "finite A" and "a \<in> A" and "b = f a" shows "b dvd prod f A" proof - from \<open>finite A\<close> have "prod f (insert a (A - {a})) = f a * prod f (A - {a})" by (intro prod.insert) auto also from \<open>a \<in> A\<close> have "insert a (A - {a}) = A" by blast finally have "prod f A = f a * prod f (A - {a})" . with \<open>b = f a\<close> show ?thesis by simp qed lemma dvd_prodI [intro]: "finite A \<Longrightarrow> a \<in> A \<Longrightarrow> f a dvd prod f A" by auto lemma prod_zero: assumes "finite A" and "\<exists>a\<in>A. f a = 0" shows "prod f A = 0" using assms proof (induct A) case empty then show ?case by simp next case (insert a A) then have "f a = 0 \<or> (\<exists>a\<in>A. f a = 0)" by simp then have "f a * prod f A = 0" by rule (simp_all add: insert) with insert show ?case by simp qed lemma prod_dvd_prod_subset2: assumes "finite B" and "A \<subseteq> B" and "\<And>a. a \<in> A \<Longrightarrow> f a dvd g a" shows "prod f A dvd prod g B" proof - from assms have "prod f A dvd prod g A" by (auto intro: prod_dvd_prod) moreover from assms have "prod g A dvd prod g B" by (auto intro: prod_dvd_prod_subset) ultimately show ?thesis by (rule dvd_trans) qed end lemma (in semidom) prod_zero_iff [simp]: fixes f :: "'b \<Rightarrow> 'a" assumes "finite A" shows "prod f A = 0 \<longleftrightarrow> (\<exists>a\<in>A. f a = 0)" using assms by (induct A) (auto simp: no_zero_divisors) lemma (in semidom_divide) prod_diff1: assumes "finite A" and "f a \<noteq> 0" shows "prod f (A - {a}) = (if a \<in> A then prod f A div f a else prod f A)" proof (cases "a \<notin> A") case True then show ?thesis by simp next case False with assms show ?thesis proof induct case empty then show ?case by simp next case (insert b B) then show ?case proof (cases "a = b") case True with insert show ?thesis by simp next case False with insert have "a \<in> B" by simp define C where "C = B - {a}" with \<open>finite B\<close> \<open>a \<in> B\<close> have "B = insert a C" "finite C" "a \<notin> C" by auto with insert show ?thesis by (auto simp add: insert_commute ac_simps) qed qed qed lemma sum_zero_power [simp]: "(\<Sum>i\<in>A. c i * 0^i) = (if finite A \<and> 0 \<in> A then c 0 else 0)" for c :: "nat \<Rightarrow> 'a::division_ring" by (induct A rule: infinite_finite_induct) auto lemma sum_zero_power' [simp]: "(\<Sum>i\<in>A. c i * 0^i / d i) = (if finite A \<and> 0 \<in> A then c 0 / d 0 else 0)" for c :: "nat \<Rightarrow> 'a::field" using sum_zero_power [of "\<lambda>i. c i / d i" A] by auto lemma (in field) prod_inversef: "prod (inverse \<circ> f) A = inverse (prod f A)" proof (cases "finite A") case True then show ?thesis by (induct A rule: finite_induct) simp_all next case False then show ?thesis by auto qed lemma (in field) prod_dividef: "(\<Prod>x\<in>A. f x / g x) = prod f A / prod g A" using prod_inversef [of g A] by (simp add: divide_inverse prod.distrib) lemma prod_Un: fixes f :: "'b \<Rightarrow> 'a :: field" assumes "finite A" and "finite B" and "\<forall>x\<in>A \<inter> B. f x \<noteq> 0" shows "prod f (A \<union> B) = prod f A * prod f B / prod f (A \<inter> B)" proof - from assms have "prod f A * prod f B = prod f (A \<union> B) * prod f (A \<inter> B)" by (simp add: prod.union_inter [symmetric, of A B]) with assms show ?thesis by simp qed context linordered_semidom begin lemma prod_nonneg: "(\<forall>a\<in>A. 0 \<le> f a) \<Longrightarrow> 0 \<le> prod f A" by (induct A rule: infinite_finite_induct) simp_all lemma prod_pos: "(\<forall>a\<in>A. 0 < f a) \<Longrightarrow> 0 < prod f A" by (induct A rule: infinite_finite_induct) simp_all lemma prod_mono: "(\<And>i. i \<in> A \<Longrightarrow> 0 \<le> f i \<and> f i \<le> g i) \<Longrightarrow> prod f A \<le> prod g A" by (induct A rule: infinite_finite_induct) (force intro!: prod_nonneg mult_mono)+ lemma prod_mono_strict: assumes "finite A" "\<And>i. i \<in> A \<Longrightarrow> 0 \<le> f i \<and> f i < g i" "A \<noteq> {}" shows "prod f A < prod g A" using assms proof (induct A rule: finite_induct) case empty then show ?case by simp next case insert then show ?case by (force intro: mult_strict_mono' prod_nonneg) qed end lemma prod_mono2: fixes f :: "'a \<Rightarrow> 'b :: linordered_idom" assumes fin: "finite B" and sub: "A \<subseteq> B" and nn: "\<And>b. b \<in> B-A \<Longrightarrow> 1 \<le> f b" and A: "\<And>a. a \<in> A \<Longrightarrow> 0 \<le> f a" shows "prod f A \<le> prod f B" proof - have "prod f A \<le> prod f A * prod f (B-A)" by (metis prod_ge_1 A mult_le_cancel_left1 nn not_less prod_nonneg) also from fin finite_subset[OF sub fin] have "\<dots> = prod f (A \<union> (B-A))" by (simp add: prod.union_disjoint del: Un_Diff_cancel) also from sub have "A \<union> (B-A) = B" by blast finally show ?thesis . qed lemma less_1_prod: fixes f :: "'a \<Rightarrow> 'b::linordered_idom" shows "finite I \<Longrightarrow> I \<noteq> {} \<Longrightarrow> (\<And>i. i \<in> I \<Longrightarrow> 1 < f i) \<Longrightarrow> 1 < prod f I" by (induct I rule: finite_ne_induct) (auto intro: less_1_mult) lemma less_1_prod2: fixes f :: "'a \<Rightarrow> 'b::linordered_idom" assumes I: "finite I" "i \<in> I" "1 < f i" "\<And>i. i \<in> I \<Longrightarrow> 1 \<le> f i" shows "1 < prod f I" proof - have "1 < f i * prod f (I - {i})" using assms by (meson DiffD1 leI less_1_mult less_le_trans mult_le_cancel_left1 prod_ge_1) also have "\<dots> = prod f I" using assms by (simp add: prod.remove) finally show ?thesis . qed lemma (in linordered_field) abs_prod: "\<bar>prod f A\<bar> = (\<Prod>x\<in>A. \<bar>f x\<bar>)" by (induct A rule: infinite_finite_induct) (simp_all add: abs_mult) lemma prod_eq_1_iff [simp]: "finite A \<Longrightarrow> prod f A = 1 \<longleftrightarrow> (\<forall>a\<in>A. f a = 1)" for f :: "'a \<Rightarrow> nat" by (induct A rule: finite_induct) simp_all lemma prod_pos_nat_iff [simp]: "finite A \<Longrightarrow> prod f A > 0 \<longleftrightarrow> (\<forall>a\<in>A. f a > 0)" for f :: "'a \<Rightarrow> nat" using prod_zero_iff by (simp del: neq0_conv add: zero_less_iff_neq_zero) lemma prod_constant [simp]: "(\<Prod>x\<in> A. y) = y ^ card A" for y :: "'a::comm_monoid_mult" by (induct A rule: infinite_finite_induct) simp_all lemma prod_power_distrib: "prod f A ^ n = prod (\<lambda>x. (f x) ^ n) A" for f :: "'a \<Rightarrow> 'b::comm_semiring_1" by (induct A rule: infinite_finite_induct) (auto simp add: power_mult_distrib) lemma power_sum: "c ^ (\<Sum>a\<in>A. f a) = (\<Prod>a\<in>A. c ^ f a)" by (induct A rule: infinite_finite_induct) (simp_all add: power_add) lemma prod_gen_delta: fixes b :: "'b \<Rightarrow> 'a::comm_monoid_mult" assumes fin: "finite S" shows "prod (\<lambda>k. if k = a then b k else c) S = (if a \<in> S then b a * c ^ (card S - 1) else c ^ card S)" proof - let ?f = "(\<lambda>k. if k=a then b k else c)" show ?thesis proof (cases "a \<in> S") case False then have "\<forall> k\<in> S. ?f k = c" by simp with False show ?thesis by (simp add: prod_constant) next case True let ?A = "S - {a}" let ?B = "{a}" from True have eq: "S = ?A \<union> ?B" by blast have disjoint: "?A \<inter> ?B = {}" by simp from fin have fin': "finite ?A" "finite ?B" by auto have f_A0: "prod ?f ?A = prod (\<lambda>i. c) ?A" by (rule prod.cong) auto from fin True have card_A: "card ?A = card S - 1" by auto have f_A1: "prod ?f ?A = c ^ card ?A" unfolding f_A0 by (rule prod_constant) have "prod ?f ?A * prod ?f ?B = prod ?f S" using prod.union_disjoint[OF fin' disjoint, of ?f, unfolded eq[symmetric]] by simp with True card_A show ?thesis by (simp add: f_A1 field_simps cong add: prod.cong cong del: if_weak_cong) qed qed lemma sum_image_le: fixes g :: "'a \<Rightarrow> 'b::ordered_comm_monoid_add" assumes "finite I" "\<And>i. i \<in> I \<Longrightarrow> 0 \<le> g(f i)" shows "sum g (f ` I) \<le> sum (g \<circ> f) I" using assms proof induction case empty then show ?case by auto next case (insert x F) from insertI1 have "0 \<le> g (f x)" by (rule insert) hence 1: "sum g (f ` F) \<le> g (f x) + sum g (f ` F)" using add_increasing by blast have 2: "sum g (f ` F) \<le> sum (g \<circ> f) F" using insert by blast have "sum g (f ` insert x F) = sum g (insert (f x) (f ` F))" by simp also have "\<dots> \<le> g (f x) + sum g (f ` F)" by (simp add: 1 insert sum.insert_if) also from 2 have "\<dots> \<le> g (f x) + sum (g \<circ> f) F" by (rule add_left_mono) also from insert(1, 2) have "\<dots> = sum (g \<circ> f) (insert x F)" by (simp add: sum.insert_if) finally show ?case . qed end
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2010 Gael Guennebaud <[email protected]> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #include <main.h> #include <iostream> #include <string> #if defined(__APPLE_CC__) // Prevent deprecation warnings caused by GLEW on MacOS. #define GL_SILENCE_DEPRECATION 1 #endif #include <GL/glew.h> #include <Eigen/OpenGLSupport> #if defined(__APPLE_CC__) #include <GLUT/glut.h> #else #include <GL/freeglut.h> #endif using namespace Eigen; #define VERIFY_MATRIX(CODE,REF) { \ glMatrixMode(GL_MODELVIEW); \ glLoadIdentity(); \ CODE; \ Matrix<float,4,4,ColMajor> m; m.setZero(); \ glGet(GL_MODELVIEW_MATRIX, m); \ if(!(REF).cast<float>().isApprox(m)) { \ std::cerr << "Expected:\n" << ((REF).cast<float>()) << "\n" << "got\n" << m << "\n\n"; \ } \ VERIFY_IS_APPROX((REF).cast<float>(), m); \ } #define VERIFY_UNIFORM(SUFFIX,NAME,TYPE) { \ TYPE value; value.setRandom(); \ TYPE data; \ int loc = glGetUniformLocation(prg_id, #NAME); \ VERIFY((loc!=-1) && "uniform not found"); \ glUniform(loc,value); \ EIGEN_CAT(glGetUniform,SUFFIX)(prg_id,loc,data.data()); \ if(!value.isApprox(data)) { \ std::cerr << "Expected:\n" << value << "\n" << "got\n" << data << "\n\n"; \ } \ VERIFY_IS_APPROX(value, data); \ } #define VERIFY_UNIFORMi(NAME,TYPE) { \ TYPE value = TYPE::Random().eval().cast<float>().cast<TYPE::Scalar>(); \ TYPE data; \ int loc = glGetUniformLocation(prg_id, #NAME); \ VERIFY((loc!=-1) && "uniform not found"); \ glUniform(loc,value); \ glGetUniformiv(prg_id,loc,(GLint*)data.data()); \ if(!value.isApprox(data)) { \ std::cerr << "Expected:\n" << value << "\n" << "got\n" << data << "\n\n"; \ } \ VERIFY_IS_APPROX(value, data); \ } void printProgramInfoLog(GLuint objectID) { int infologLength, charsWritten; GLchar *infoLog; glGetProgramiv(objectID, GL_INFO_LOG_LENGTH, &infologLength); if(infologLength > 0) { infoLog = new GLchar[infologLength]; glGetProgramInfoLog(objectID, infologLength, &charsWritten, infoLog); if (charsWritten > 0) std::cerr << "Program info : \n" << infoLog << std::endl; delete[] infoLog; } } void printShaderInfoLog(GLuint objectID) { int infologLength, charsWritten; GLchar *infoLog; glGetShaderiv(objectID, GL_INFO_LOG_LENGTH, &infologLength); if(infologLength > 0) { infoLog = new GLchar[infologLength]; glGetShaderInfoLog(objectID, infologLength, &charsWritten, infoLog); if (charsWritten > 0) std::cerr << "Shader info : \n" << infoLog << std::endl; delete[] infoLog; } } GLint createProgram(const char* vtx, const char* frg, bool print_errors = true) { GLint prg_id = glCreateProgram(); GLint vtx_id = glCreateShader(GL_VERTEX_SHADER); GLint frg_id = glCreateShader(GL_FRAGMENT_SHADER); GLint ok; glShaderSource(vtx_id, 1, &vtx, 0); glCompileShader(vtx_id); glGetShaderiv(vtx_id, GL_COMPILE_STATUS, &ok); if(!ok) { if (print_errors) { std::cerr << "vtx compilation failed\n"; std::cerr << "Source:\n" << vtx << "\n"; printShaderInfoLog(vtx_id); } glDeleteShader(vtx_id); return GL_ZERO; } glShaderSource(frg_id, 1, &frg, 0); glCompileShader(frg_id); glGetShaderiv(frg_id, GL_COMPILE_STATUS, &ok); if(!ok) { if (print_errors) { std::cerr << "frg compilation failed.\n"; std::cerr << "Source:\n" << frg << "\n"; printShaderInfoLog(frg_id); } glDeleteShader(vtx_id); glDeleteShader(frg_id); return GL_ZERO; } glAttachShader(prg_id, vtx_id); glAttachShader(prg_id, frg_id); glLinkProgram(prg_id); // Delete shaders once linked. glDeleteShader(vtx_id); glDeleteShader(frg_id); glGetProgramiv(prg_id, GL_LINK_STATUS, &ok); if(!ok) { if (print_errors) { std::cerr << "linking failed.\n"; printProgramInfoLog(prg_id); } glDeleteProgram(prg_id); return GL_ZERO; } glUseProgram(prg_id); return prg_id; } GLint createProgram(const std::string& vtx, const std::string& frg, bool print_errors = true) { return createProgram(vtx.c_str(), frg.c_str(), print_errors); } std::string getGlslVersionString(int gl_major_version, int gl_minor_version) { switch (gl_major_version) { case 2: switch (gl_minor_version) { case 0: return "#version 110"; case 1: return "#version 120"; } break; case 3: switch (gl_minor_version) { case 0: return "#version 130"; case 1: return "#version 140"; case 2: return "#version 150"; case 3: return "#version 330"; } break; case 4: switch (gl_minor_version) { case 0: return "#version 400"; case 1: return "#version 410"; case 2: return "#version 420"; case 3: return "#version 430"; case 4: return "#version 440"; case 5: return "#version 450"; case 6: return "#version 460"; } break; } return ""; } void find_and_replace( std::string& str, const std::string& find, const std::string& replace) { size_t loc = 0; size_t flen = find.length(); size_t rlen = replace.length(); while ( (loc = str.find(find, loc)) != std::string::npos) { str.replace(loc, flen, replace); loc += rlen; } } // Finds and replaces a set of substrings in a string. std::string format( const std::string& str, const std::vector<std::string>& find, const std::vector<std::string>& replace) { std::string out = str; for (std::size_t i=0; i<find.size(); ++i) { find_and_replace(out, find[i], replace[i]); } return out; } // GLUT display function that runs test. Must be run within the display loop // in order to properly destroy resources. void openglsupport_test_loop() { // Get context info. const GLubyte* gl_version_string = glGetString(GL_VERSION); std::cerr << "GL version: " << gl_version_string << std::endl; std::cerr << "GLSL version: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl; // Parse version from string since GL_MAJOR_VERSION is only supported in GL 3.0+. // Version string guaranteed to be <major>.<minor><vender extension>. GLint gl_major_version = gl_version_string[0] - '0'; GLint gl_minor_version = gl_version_string[2] - '0'; bool legacy_gl = gl_major_version < 3 || (gl_major_version == 3 && gl_minor_version < 2); // Fixed-function pipeline removed in OpenGL 3.2. if (legacy_gl) { // Draw a basic triangle. Vector3f v3f; Matrix3f rot; glBegin(GL_POINTS); { glVertex(v3f); glVertex(2*v3f+v3f); glVertex(rot*v3f); } glEnd(); // 4x4 matrices Matrix4f mf44; mf44.setRandom(); VERIFY_MATRIX(glLoadMatrix(mf44), mf44); VERIFY_MATRIX(glMultMatrix(mf44), mf44); Matrix4d md44; md44.setRandom(); VERIFY_MATRIX(glLoadMatrix(md44), md44); VERIFY_MATRIX(glMultMatrix(md44), md44); // Quaternion Quaterniond qd(AngleAxisd(internal::random<double>(), Vector3d::Random())); VERIFY_MATRIX(glRotate(qd), Projective3d(qd).matrix()); Quaternionf qf(AngleAxisf(internal::random<double>(), Vector3f::Random())); VERIFY_MATRIX(glRotate(qf), Projective3f(qf).matrix()); // 3D Transform Transform<float,3,AffineCompact> acf3; acf3.matrix().setRandom(); VERIFY_MATRIX(glLoadMatrix(acf3), Projective3f(acf3).matrix()); VERIFY_MATRIX(glMultMatrix(acf3), Projective3f(acf3).matrix()); Transform<float,3,Affine> af3(acf3); VERIFY_MATRIX(glLoadMatrix(af3), Projective3f(af3).matrix()); VERIFY_MATRIX(glMultMatrix(af3), Projective3f(af3).matrix()); Transform<float,3,Projective> pf3; pf3.matrix().setRandom(); VERIFY_MATRIX(glLoadMatrix(pf3), Projective3f(pf3).matrix()); VERIFY_MATRIX(glMultMatrix(pf3), Projective3f(pf3).matrix()); Transform<double,3,AffineCompact> acd3; acd3.matrix().setRandom(); VERIFY_MATRIX(glLoadMatrix(acd3), Projective3d(acd3).matrix()); VERIFY_MATRIX(glMultMatrix(acd3), Projective3d(acd3).matrix()); Transform<double,3,Affine> ad3(acd3); VERIFY_MATRIX(glLoadMatrix(ad3), Projective3d(ad3).matrix()); VERIFY_MATRIX(glMultMatrix(ad3), Projective3d(ad3).matrix()); Transform<double,3,Projective> pd3; pd3.matrix().setRandom(); VERIFY_MATRIX(glLoadMatrix(pd3), Projective3d(pd3).matrix()); VERIFY_MATRIX(glMultMatrix(pd3), Projective3d(pd3).matrix()); // translations (2D and 3D) { Vector2f vf2; vf2.setRandom(); Vector3f vf23; vf23 << vf2, 0; VERIFY_MATRIX(glTranslate(vf2), Projective3f(Translation3f(vf23)).matrix()); Vector2d vd2; vd2.setRandom(); Vector3d vd23; vd23 << vd2, 0; VERIFY_MATRIX(glTranslate(vd2), Projective3d(Translation3d(vd23)).matrix()); Vector3f vf3; vf3.setRandom(); VERIFY_MATRIX(glTranslate(vf3), Projective3f(Translation3f(vf3)).matrix()); Vector3d vd3; vd3.setRandom(); VERIFY_MATRIX(glTranslate(vd3), Projective3d(Translation3d(vd3)).matrix()); Translation<float,3> tf3; tf3.vector().setRandom(); VERIFY_MATRIX(glTranslate(tf3), Projective3f(tf3).matrix()); Translation<double,3> td3; td3.vector().setRandom(); VERIFY_MATRIX(glTranslate(td3), Projective3d(td3).matrix()); } // scaling (2D and 3D) { Vector2f vf2; vf2.setRandom(); Vector3f vf23; vf23 << vf2, 1; VERIFY_MATRIX(glScale(vf2), Projective3f(Scaling(vf23)).matrix()); Vector2d vd2; vd2.setRandom(); Vector3d vd23; vd23 << vd2, 1; VERIFY_MATRIX(glScale(vd2), Projective3d(Scaling(vd23)).matrix()); Vector3f vf3; vf3.setRandom(); VERIFY_MATRIX(glScale(vf3), Projective3f(Scaling(vf3)).matrix()); Vector3d vd3; vd3.setRandom(); VERIFY_MATRIX(glScale(vd3), Projective3d(Scaling(vd3)).matrix()); UniformScaling<float> usf(internal::random<float>()); VERIFY_MATRIX(glScale(usf), Projective3f(usf).matrix()); UniformScaling<double> usd(internal::random<double>()); VERIFY_MATRIX(glScale(usd), Projective3d(usd).matrix()); } } else { std::cerr << "Warning: fixed-function pipeline was not tested.\n"; } // Dynamic shader substitution variables. // Modern shaders require a version string, and newer runtimes fail to // compile old GLSL versions. Thus, we dynamically set the GLSL version // string based on runtime. Also, pre OpenGL 3.0, the output gl_FragColor was // built-in. This was deprecated in OpenGL 3.0, requiring us to explicitly // define the output variable. std::vector<std::string> glsl_vars; glsl_vars.push_back("${GLSL_VERSION}"); glsl_vars.push_back("${FRAG_OUTPUT_DECLARATION}"); glsl_vars.push_back("${FRAG_OUTPUT_VARIABLE}"); std::vector<std::string> glsl_vals; glsl_vals.push_back(getGlslVersionString(gl_major_version, gl_minor_version)); if (gl_major_version >= 3) { glsl_vals.push_back("out vec4 fragColor;"); glsl_vals.push_back("fragColor"); } else { glsl_vals.push_back(""); glsl_vals.push_back("gl_FragColor"); } // uniform { // vertex shader. std::string vtx = format( "${GLSL_VERSION}\n" "void main(void) {\n" " gl_Position = vec4(0,0,0,1);\n" "}\n", glsl_vars, glsl_vals); #ifdef GL_VERSION_2_0 if(GLEW_VERSION_2_0 && GL_VERSION_2_0) { std::string frg = format( "${GLSL_VERSION}\n" "uniform vec2 v2f;\n" "uniform vec3 v3f;\n" "uniform vec4 v4f;\n" "uniform ivec2 v2i;\n" "uniform ivec3 v3i;\n" "uniform ivec4 v4i;\n" "uniform mat2 m2f;\n" "uniform mat3 m3f;\n" "uniform mat4 m4f;\n" "${FRAG_OUTPUT_DECLARATION}\n" "void main(void) { \n" " ${FRAG_OUTPUT_VARIABLE} = vec4(v2f[0]+v3f[0]+v4f[0])+vec4(v2i[0]+v3i[0]+v4i[0])+vec4(m2f[0][0]+m3f[0][0]+m4f[0][0]);\n" "}\n", glsl_vars, glsl_vals); GLint prg_id = createProgram(vtx, frg); VERIFY(prg_id > 0 && "Failed to create program."); VERIFY_UNIFORM(fv, v2f, Vector2f); VERIFY_UNIFORM(fv, v3f, Vector3f); VERIFY_UNIFORM(fv, v4f, Vector4f); VERIFY_UNIFORMi(v2i, Vector2i); VERIFY_UNIFORMi(v3i, Vector3i); VERIFY_UNIFORMi(v4i, Vector4i); VERIFY_UNIFORM(fv, m2f, Matrix2f); VERIFY_UNIFORM(fv, m3f, Matrix3f); VERIFY_UNIFORM(fv, m4f, Matrix4f); glDeleteProgram(prg_id); } else #endif std::cerr << "Warning: opengl 2.0 was not tested.\n"; #ifdef GL_VERSION_2_1 if(GLEW_VERSION_2_1 && GL_VERSION_2_1 && (gl_major_version > 2 || (gl_major_version == 2 && gl_minor_version >= 1))) { std::string frg = format( "${GLSL_VERSION}\n" "uniform mat2x3 m23f;\n" "uniform mat3x2 m32f;\n" "uniform mat2x4 m24f;\n" "uniform mat4x2 m42f;\n" "uniform mat3x4 m34f;\n" "uniform mat4x3 m43f;\n" "${FRAG_OUTPUT_DECLARATION}\n" "void main(void) {\n" " ${FRAG_OUTPUT_VARIABLE} = vec4(m23f[0][0]+m32f[0][0]+m24f[0][0]+m42f[0][0]+m34f[0][0]+m43f[0][0]);\n" "}\n", glsl_vars, glsl_vals); GLint prg_id = createProgram(vtx, frg); VERIFY(prg_id > 0 && "Failed to create program."); typedef Matrix<float,2,3> Matrix23f; typedef Matrix<float,3,2> Matrix32f; typedef Matrix<float,2,4> Matrix24f; typedef Matrix<float,4,2> Matrix42f; typedef Matrix<float,3,4> Matrix34f; typedef Matrix<float,4,3> Matrix43f; VERIFY_UNIFORM(fv, m23f, Matrix23f); VERIFY_UNIFORM(fv, m32f, Matrix32f); VERIFY_UNIFORM(fv, m24f, Matrix24f); VERIFY_UNIFORM(fv, m42f, Matrix42f); VERIFY_UNIFORM(fv, m34f, Matrix34f); VERIFY_UNIFORM(fv, m43f, Matrix43f); glDeleteProgram(prg_id); } else #endif std::cerr << "Warning: opengl 2.1 was not tested.\n"; #ifdef GL_VERSION_3_0 if(GLEW_VERSION_3_0 && GL_VERSION_3_0 && gl_major_version >= 3) { std::string frg = format( "${GLSL_VERSION}\n" "uniform uvec2 v2ui;\n" "uniform uvec3 v3ui;\n" "uniform uvec4 v4ui;\n" "${FRAG_OUTPUT_DECLARATION}\n" "void main(void) {\n" " ${FRAG_OUTPUT_VARIABLE} = vec4(v2ui[0]+v3ui[0]+v4ui[0]);\n" "}\n", glsl_vars, glsl_vals); GLint prg_id = createProgram(vtx, frg); VERIFY(prg_id > 0 && "Failed to create program."); typedef Matrix<unsigned int,2,1> Vector2ui; typedef Matrix<unsigned int,3,1> Vector3ui; typedef Matrix<unsigned int,4,1> Vector4ui; VERIFY_UNIFORMi(v2ui, Vector2ui); VERIFY_UNIFORMi(v3ui, Vector3ui); VERIFY_UNIFORMi(v4ui, Vector4ui); glDeleteProgram(prg_id); } else #endif std::cerr << "Warning: opengl 3.0 was not tested.\n"; // dvecn supported if >= 4.1 or ARB_vertex_attrib_64bit bool has_fp64_native = (gl_major_version == 4 && gl_minor_version >= 1); bool has_fp64_extension = false; #ifdef GLEW_ARB_gpu_shader_fp64 if(GLEW_ARB_gpu_shader_fp64) { // Check that extension can actually be compiled. if (has_fp64_extension) { std::string frg = format( "${GLSL_VERSION}\n" "#extension GL_ARB_gpu_shader_fp64 : enable\n" "uniform dvec2 dv2;\n" "${FRAG_OUTPUT_DECLARATION}\n" "void main(void) {\n" " ${FRAG_OUTPUT_VARIABLE} = vec4(dv2.x, dv2.y, dv2.x, dv2.y);\n" "}\n", glsl_vars, glsl_vals); GLint prg_id = createProgram(vtx, frg, /*print_errors=*/false); if (prg_id) { has_fp64_extension = true; glDeleteProgram(prg_id); } } } #endif if( has_fp64_native || has_fp64_extension ) { std::vector<std::string> glsl_vars_with_extension = glsl_vars; glsl_vars_with_extension.push_back("${GLSL_EXTENSIONS}"); std::vector<std::string> glsl_vals_with_extension = glsl_vals; if (has_fp64_extension) { glsl_vals_with_extension.push_back("#extension GL_ARB_gpu_shader_fp64 : enable"); } else { glsl_vals_with_extension.push_back(""); } std::string frg = format( "${GLSL_VERSION}\n" "${GLSL_EXTENSIONS}\n" "uniform dvec2 v2d;\n" "uniform dvec3 v3d;\n" "uniform dvec4 v4d;\n" "${FRAG_OUTPUT_DECLARATION}\n" "void main(void) {\n" " ${FRAG_OUTPUT_VARIABLE} = vec4(v2d[0]+v3d[0]+v4d[0]);\n" "}\n", glsl_vars_with_extension, glsl_vals_with_extension); GLint prg_id = createProgram(vtx,frg); VERIFY(prg_id > 0 && "Failed to create program."); VERIFY_UNIFORM(dv, v2d, Vector2d); VERIFY_UNIFORM(dv, v3d, Vector3d); VERIFY_UNIFORM(dv, v4d, Vector4d); glDeleteProgram(prg_id); } else std::cerr << "Warning: dvec (fp64) was not tested.\n"; } // Exit loop - Leaving main loop is supported by freeglut, otherwise we // are forced to exit. #ifdef FREEGLUT glutLeaveMainLoop(); // Trigger another display loop iteration. Otherwise, it just hangs. glutPostRedisplay(); #else exit(0); #endif } EIGEN_DECLARE_TEST(openglsupport) { int argc = 0; glutInit(&argc, 0); GLint glut_display_mode = GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH; #ifndef EIGEN_LEGACY_OPENGL // Initialize 3.2+ OpenGL context. #if defined(__APPLE_CC__) glut_display_mode |= GLUT_3_2_CORE_PROFILE; #elif defined(FREEGLUT) glutInitContextVersion(3, 2); glutInitContextFlags(GLUT_FORWARD_COMPATIBLE); glutInitContextProfile(GLUT_CORE_PROFILE); #endif #endif glutInitDisplayMode(glut_display_mode); glutInitWindowPosition(0, 0); glutInitWindowSize(10, 10); int window = glutCreateWindow("Eigen"); if(window <= 0) { std::cerr << "Error: Unable to create GLUT Window.\n"; exit(1); } glewExperimental = GL_TRUE; if(glewInit() != GLEW_OK) { std::cerr << "Warning: Failed to initialize GLEW.\n"; exit(1); } // Run test in display, otherwise GLUT fails to clean up and leads to memory // access errors on exit. glutDisplayFunc(openglsupport_test_loop); glutMainLoop(); glutDestroyWindow(window); }
\section{Applications and Evaluation} \label{sec:hotpot:app} This section presents the performance evaluation of two applications and a set of microbenchmarks. We ran all experiments on a cluster of 17 machines, each with two Intel Xeon CPU E5-2620 2.40GHz processors, 128 GB DRAM, and one 40 Gbps Mellanox ConnectX-3 InfiniBand network adapter; a Mellanox 40 Gbps InfiniBand switch connects all of the machines. All machines run the CentOS 7.1 distribution and the 3.11.1 Linux kernel. The focus of our evaluation is to understand the performance of \dsnvm's distributed memory model, its commit protocols, and its data persistence cost. As there is no real \nvm\ in production yet, we use DRAM as stand-in for \nvm. A previous study~\cite{Zhang15-NVMMStudy} shows that even though \nvm\ and DRAM can have some performance difference, the difference is small and has much lower impact on application performance than the cost of flushing data from CPU caches to \nvm, which we have included in \hotpot\ and can measure accurately. \subsection{Systems in Comparison} \label{sec:hotpot:comparesys} We compare \hotpot\ with one in-memory file system, two \nvm-based file systems, one replicated \nvm-based system, and three distributed shared memory systems. Below we briefly describe these systems in comparison. {\textbf{Single-Node File Systems.}} Tmpfs is a Linux file system that stores all data in main memory and does not perform any I/Os to storage devices. \pmfs~\cite{Dulloor14-EuroSys} is a file system designed for \nvm. The key difference between \pmfs\ and a conventional file system is that its implementation of \mmap\ maps the physical \nvm\ pages directly into the applications' address spaces rather than moving them back and forth between the file store and the buffer cache. \pmfs\ ensures data persistence using \sfence\ and \clflush\ instructions. {\textbf{Distributed \nvm-Based Systems}} Octopus~\cite{Octopus} is a user-level RDMA-based distributed file system designed for \nvm. \Octopus\ provides a set of customized file APIs including read and write, but does not support memory-mapped I/Os or provide data reliability and availability. %Octopus data servers access local PM without stacking a local file system layer. In Octopus, %files are distributed to data servers in a hash-based way. Mojim~\cite{Zhang15-Mojim} is our previous work that uses a primary-backup model to replicate \nvm\ data over a customized IB layer. Similar to \hotpot, \pmfs, and Octopus, Mojim maps \nvm\ pages directly into application virtual memory address spaces. Mojim supports application reads and writes on the primary node but only reads on backup nodes. \textbf{Distributed Shared Memory Systems.} We implemented two kernel-level DSM systems, {\em \dsmxact} and {\em \dsmnoxact}, on top of the same network stack as \hotpot's. Both of them support multiple readers and single writer (MRSW) and use a home node for each memory page to serve remote read and to store which nodes are the current readers and writer of the page, similar to HLRC~\cite{Li89-ACM,HLRC}. We open source both these DSM systems together with \hotpot. \dsmxact\ guarantees release consistency using a transaction interface that is similar to \hotpot's \mrsw\ mode. Applications first call a transaction begin API to specify the data that they want to write. Transaction begin only succeeds if no other writer is writing to any of the transaction data. After beginning a transaction, applications can read and write to any transaction data and use a transaction commit call to end a transaction. When committing a transaction, \dsmxact\ writes all updated transaction data to the home node, invalidates the read caches on all other nodes, and releases the write permission. \dsmnoxact\ supports write (memory stores) without transactions and does not require applications to declare which data they want to write in advance. On each write (memory store), \dsmnoxact\ revokes the write permission from the current writer, writes the current dirty data to the home node, and grants the write permission to the new writer. Compared to \dsmxact, \dsmnoxact\ supports stronger consistency, requires less programmer efforts, but incurs higher performance overhead because of its more frequent writer invalidation. Apart from the two DSM systems that we built, we also compare \hotpot\ with Grappa~\cite{Nelson15-ATC}, a recent DSM system that supports modern data-parallel applications. Different from traditional DSM systems and our DSM systems, Grappa moves computation to data instead of fetching data to where computation is. \input{hotpot/tbl-ycsb} \subsection{In-Memory NoSQL Database} \label{sec:hotpot:mongodb} MongoDB~\cite{MongoDB} is a popular distributed NoSQL database that supports several different storage engines including its own storage engine that is based on memory-mapped files (called MMAPv1). Applications like MongoDB can largely benefit from having a fast means to store and access persistent data. We ported MongoDB v2.7.0 to \hotpot\ by modifying its storage engine to keep track of all writes to the memory-mapped data file. We then group the written memory regions belonging to the same client request into a \hotpot\ \commit\ call. In total, porting MongoDB to \hotpot\ requires modifying 120 lines of code. To use the ported MongoDB, administrators can simply configure several machines to share a \dsnvm\ space under \hotpot\ and run ported MongoDB on each machine. Applications on top of the ported MongoDB can issue requests to any machine, since all machines access the same \dsnvm\ space. In our experiments, we ran the ported MongoDB on three \hotpot\ nodes and set data replication degree to three. We compare this ported MongoDB with the default MongoDB running on \tmpfs, \pmfs, and \Octopus, and a ported MongoDB to \Mojim\ on three nodes connected with IB. Because \Octopus\ does not memory-mapped operations and MongoDB's storage engine is based on memory-mapped files, MongoDB cannot directly run on \Octopus. We run MongoDB on top of FUSE~\cite{fuse-fs}, a full-fledged user-level file system, which in turn runs on \Octopus. %All these systems have three replicas of all data. %\tmpfs, \pmfs, and \Octopus\ use MongoDB's default replication mechanism, For \tmpfs\ and \pmfs, we use two consistency models (called MongoDB write concerns): the \journaled\ write concern and the \fsyncsafe\ write concern. With the \journaled\ write concern, MongoDB logs data in a journal file and checkpoints the data in a lazy fashion. MongoDB blocks a client call until the updated data is written to the journal file. With \fsyncsafe, MongoDB does not perform journaling. Instead, it flushes all the dirty pages to the data file after each write operation and blocks the client call until this operation completes. We run \Octopus\ and \Mojim\ with the \fsyncsafe\ write concern. \Octopus, \tmpfs, and \pmfs\ provide no replication, while \Mojim\ and \hotpot\ use their own replication mechanisms to make three replicas of all data (\Mojim\ uses one node as the primary node and the other two nodes as backup nodes). YCSB~\cite{Cooper10-CloudCom} is a key-value store benchmark that imitates web applications' data access models. Figure~\ref{tbl-ycsb} summarizes the number of different operations in the YCSB workloads. Each workload performs 10,000 operations on a database with 100,000 1\KB\ records. Figure~\ref{fig-ycsbrun} presents the throughput of MongoDB on \tmpfs, \pmfs, Octopus, Mojim, and \hotpot\ using YCSB workloads. For all workloads, \hotpot\ outperforms \tmpfs, \pmfs, \Octopus, and \Mojim\ for both the \journaled\ and the \fsyncsafe\ write concerns. The performance improvement is especially high for write-heavy workloads. \pmfs\ performs worst mainly because of its inefficient process of making data persistent with default MongoDB. The default MongoDB \fsync{}s the whole data file after each write under \fsyncsafe, and \pmfs\ flushes all cache lines of the file to \nvm\ by performing one \clflush\ at a time. \hotpot\ and Mojim only commit dirty data, largely improving MongoDB performance over \pmfs. Compared to \tmpfs\ and \pmfs\ under \journaled, \hotpot\ and Mojim use their own mechanisms to ensure data reliability and avoid the performance cost of journaling. Moreover, \hotpot\ and Mojim make three persistent replica for all data, while \pmfs\ makes only one. Tmpfs is slower than \hotpot\ even though \tmpfs\ does not make any data persistent, because MongoDB's slower replication mechanism on IPoIB. \hotpot's network layer is significantly better than IPoIB~\cite{Tsai17-SOSP}. \Octopus\ performs worse than \hotpot\ and \Mojim\ because it incurs significant overhead of additional {\em indirection layers}: each memory operation within the memory-mapped file goes through the FUSE file system and then through \Octopus. \hotpot\ and \Mojim\ both support native memory instructions and incurs no indirection overhead. Finally, even though Mojim's replication protocol is simpler and faster than \hotpot's, \hotpot\ outperforms Mojim because Mojim only supports write on one node while \hotpot\ supports write on all nodes. \input{hotpot/fig-graph} \subsection{Distributed (Persistent) Graph} Graph processing is an increasingly important type of applications in modern datacenters~\cite{Gonzalez12-OSDI,Gonzalez14-OSDI,Kyrola12-OSDI,Low10-UAI,Low12-VLDB,Malewicz10-SIGMOD}. Most graph systems require large memory to run big graphs. Running graph algorithms on \nvm\ not only enables them to exploit the big memory space the high-density \nvm\ provides, but can also enable graph algorithms to stop and resume in the middle of a long run. We implemented a distributed graph processing engine on top of \hotpot\ based on the PowerGraph design~\cite{Gonzalez12-OSDI}. It stores graphs with vertex-centric representation in \dsnvm\ with random order of vertices and distributes graph processing load to multiple threads across all \hotpot\ nodes. Each thread performs graph algorithms on a set of vertices in three steps: gather, apply, and scatter, with the optimization of delta caching~\cite{Gonzalez12-OSDI}. After each step, we perform a global synchronization with \barrier\ and only start the next step when all threads have finished the last step. At the scatter step, the graph engine uses \hotpot's \mrsw\ \commitxact\ to make local changes of the scatter values visible to all nodes in the system. We implemented the \hotpot\ graph engine with only around 700 lines of code. Similarly, we implemented two distributed graph engines on top of \dsmxact\ and \dsmnoxact; these engines differ from \hotpot's graph engine only in the way they perform data write and commit. We compare \hotpot's graph engine with \dsmxact, \dsmnoxact, PowerGraph, and Grappa~\cite{Nelson15-ATC} with two real datasets, Twitter (41\,M vertices, 1\,B directed edges)~\cite{Kwak10-WWW} and LiveJournal (4\,M vertices, 34.7\,M undirected edges)~\cite{snapnets}. For space reason, we only present the results of the Twitter graph, but the results of LiveJournal are similar. Figure~\ref{fig-graph-runtime} shows the total run time of the PageRank~\cite{PageRank} algorithm with \hotpot, \dsmxact, \dsmnoxact, PowerGraph, and Grappa under three system settings: four nodes each running four graph threads, seven nodes each running four threads, and seven nodes each running eight threads. \hotpot\ outperforms PowerGraph by 2.3\x\ to 5\x\ and Grappa by 1.3\x\ to 3.2\x. In addition, \hotpot\ makes all intermediate results of graph persistent for fast restart. A major reason why \hotpot\ outperforms PowerGraph and Grappa even when \hotpot\ requires data persistence and replication is \hotpot's network stack. Compare to the IPoIB used in PowerGraph and Grappa's own network stack, \hotpot's RDMA stack is more efficient. Our implementation of \dsmxact\ and \dsmnoxact\ use the same network stack as \hotpot, but \hotpot\ still outperforms \dsmnoxact\. \dsmnoxact\ ensures cache coherence on every write and thus incurs much higher performance overhead than \hotpot\ and \dsmxact. To further understand the performance differences, we traced the network traffic of these three systems. Figure~\ref{fig-graph-traffic} plots the total amount of traffic %in the PageRank run for PowerGraph, Grappa, and \hotpot. and Figure~\ref{fig-graph-timeline} plots a detailed trace of network activity of the 7Nx4T setting. \hotpot\ sends less total traffic and achieves higher bandwidth than PowerGraph and Grappa.
module Yaffle.Main import Parser.Source import Core.Binary import Core.Context import Core.Directory import Core.Env import Core.FC import Core.InitPrimitives import Core.Metadata import Core.Normalise import Core.Options import Core.TT import Core.UnifyState import Utils.Path import TTImp.Parser import TTImp.ProcessDecls import TTImp.TTImp import Yaffle.REPL import Data.List import Data.So import Data.Strings import System %default covering usage : String usage = "Usage: yaffle <input file> [--timing]" processArgs : List String -> Core Bool processArgs [] = pure False processArgs ["--timing"] = pure True processArgs _ = coreLift $ do putStrLn usage exitWith (ExitFailure 1) HasNames () where full _ _ = pure () resolved _ _ = pure () export yaffleMain : String -> List String -> Core () yaffleMain fname args = do defs <- initDefs c <- newRef Ctxt defs m <- newRef MD initMetadata u <- newRef UST initUState d <- getDirs t <- processArgs args setLogTimings t addPrimitives case extension fname of Just "ttc" => do coreLift $ putStrLn "Processing as TTC" readFromTTC {extra = ()} True emptyFC True fname (nsAsModuleIdent emptyNS) emptyNS coreLift $ putStrLn "Read TTC" _ => do coreLift $ putStrLn "Processing as TTImp" ok <- processTTImpFile fname when ok $ do ns <- pathToNS (working_dir d) (source_dir d) fname makeBuildDirectory ns writeToTTC () !(getTTCFileName fname "ttc") coreLift $ putStrLn "Written TTC" ust <- get UST repl {c} {u} ymain : IO () ymain = do (_ :: fname :: rest) <- getArgs | _ => do putStrLn usage exitWith (ExitFailure 1) coreRun (yaffleMain fname rest) (\err : Error => putStrLn ("Uncaught error: " ++ show err)) (\res => pure ())
# Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from typing import Any, List, Optional from abc import ABC import os import argparse import logging import pickle from collections import defaultdict import numpy as np import habitat_sim from habitat.core.registry import registry from habitat.core.simulator import AgentState, Simulator from habitat.sims.habitat_simulator.habitat_simulator import HabitatSim from habitat_sim.utils.common import ( quat_to_angle_axis, quat_to_coeffs, quat_from_angle_axis, quat_from_coeffs, ) from habitat.tasks.nav.nav import NavigationEpisode, NavigationGoal, ShortestPathPoint from soundspaces.tasks.audionav_task import merge_sim_episode_config from soundspaces.utils import load_metadata from soundspaces.simulator import SoundSpacesSim from ss_baselines.av_nav.config import get_config class Sim(SoundSpacesSim): def step(self, action): sim_obs = self._sim.get_sensor_observations() return sim_obs, self._rotation_angle def main(dataset): parser = argparse.ArgumentParser() parser.add_argument( "--config-path", type=str, default="ss_baselines/av_nav/config/audionav/{}/train_telephone/pointgoal_rgb.yaml".format( dataset ), ) parser.add_argument( "opts", default=None, nargs=argparse.REMAINDER, help="Modify config options from command line", ) args = parser.parse_args() config = get_config(args.config_path, opts=args.opts) config.defrost() config.TASK_CONFIG.SIMULATOR.AGENT_0.SENSORS = ["RGB_SENSOR", "DEPTH_SENSOR"] config.TASK_CONFIG.SIMULATOR.USE_RENDERED_OBSERVATIONS = False config.freeze() simulator = None scene_obs = defaultdict(dict) num_obs = 0 scene_obs_dir = "data/scene_observations/" + dataset os.makedirs(scene_obs_dir, exist_ok=True) metadata_dir = "data/metadata/" + dataset for scene in os.listdir(metadata_dir): scene_obs = dict() scene_metadata_dir = os.path.join(metadata_dir, scene) points, graph = load_metadata(scene_metadata_dir) if dataset == "replica": scene_mesh_dir = os.path.join( "data/scene_datasets", dataset, scene, "habitat/mesh_semantic.ply" ) else: scene_mesh_dir = os.path.join( "data/scene_datasets", dataset, scene, scene + ".glb" ) for node in graph.nodes(): agent_position = graph.nodes()[node]["point"] # (3,) print(f"[Info] Agent pos: {agent_position}") for angle in [0, 90, 180, 270]: agent_rotation = quat_to_coeffs( quat_from_angle_axis(np.deg2rad(angle), np.array([0, 1, 0])) ).tolist() # [b, c, d, a] where the unit quaternion would be a + bi + cj + dk goal_radius = 0.00001 goal = NavigationGoal(position=agent_position, radius=goal_radius) episode = NavigationEpisode( goals=[goal], episode_id=str(0), scene_id=scene_mesh_dir, start_position=agent_position, start_rotation=agent_rotation, info={"sound": "telephone"}, ) # Simulation configs including RGB sensor, depth sensor ... episode_sim_config = merge_sim_episode_config( config.TASK_CONFIG.SIMULATOR, episode ) if simulator is None: simulator = Sim(episode_sim_config) simulator.reconfigure(episode_sim_config) obs, rotation_index = simulator.step(None) scene_obs[(node, rotation_index)] = obs num_obs += 1 print("Total number of observations: {}".format(num_obs)) with open(os.path.join(scene_obs_dir, "{}.pkl".format(scene)), "wb") as fo: pickle.dump(scene_obs, fo) simulator.close() del simulator if __name__ == "__main__": print("Caching Replica observations ...") main("replica") # print("Caching Matterport3D observations ...") # main("mp3d")
using Pkg Pkg.add("KitBase") Pkg.add("PyCall") using KitBase using PyCall
A set is open if and only if for every point in the set, there exists a ball around that point that is contained in the set.
State Before: J : Type u₁ inst✝⁵ : Category J K : Type u₂ inst✝⁴ : Category K C : Type u inst✝³ : Category C F : J ⥤ C D : Type u' inst✝² : Category D inst✝¹ : HasColimit F G : C ⥤ D inst✝ : HasColimit (F ⋙ G) c : Cocone F ⊢ post F G ≫ G.map (desc F c) = desc (F ⋙ G) (G.mapCocone c) State After: case w J : Type u₁ inst✝⁵ : Category J K : Type u₂ inst✝⁴ : Category K C : Type u inst✝³ : Category C F : J ⥤ C D : Type u' inst✝² : Category D inst✝¹ : HasColimit F G : C ⥤ D inst✝ : HasColimit (F ⋙ G) c : Cocone F j✝ : J ⊢ ι (F ⋙ G) j✝ ≫ post F G ≫ G.map (desc F c) = ι (F ⋙ G) j✝ ≫ desc (F ⋙ G) (G.mapCocone c) Tactic: ext State Before: case w J : Type u₁ inst✝⁵ : Category J K : Type u₂ inst✝⁴ : Category K C : Type u inst✝³ : Category C F : J ⥤ C D : Type u' inst✝² : Category D inst✝¹ : HasColimit F G : C ⥤ D inst✝ : HasColimit (F ⋙ G) c : Cocone F j✝ : J ⊢ ι (F ⋙ G) j✝ ≫ post F G ≫ G.map (desc F c) = ι (F ⋙ G) j✝ ≫ desc (F ⋙ G) (G.mapCocone c) State After: case w J : Type u₁ inst✝⁵ : Category J K : Type u₂ inst✝⁴ : Category K C : Type u inst✝³ : Category C F : J ⥤ C D : Type u' inst✝² : Category D inst✝¹ : HasColimit F G : C ⥤ D inst✝ : HasColimit (F ⋙ G) c : Cocone F j✝ : J ⊢ G.map (c.ι.app j✝) = (G.mapCocone c).ι.app j✝ Tactic: rw [← assoc, colimit.ι_post, ← G.map_comp, colimit.ι_desc, colimit.ι_desc] State Before: case w J : Type u₁ inst✝⁵ : Category J K : Type u₂ inst✝⁴ : Category K C : Type u inst✝³ : Category C F : J ⥤ C D : Type u' inst✝² : Category D inst✝¹ : HasColimit F G : C ⥤ D inst✝ : HasColimit (F ⋙ G) c : Cocone F j✝ : J ⊢ G.map (c.ι.app j✝) = (G.mapCocone c).ι.app j✝ State After: no goals Tactic: rfl
(** Generated by coq-of-ocaml *) Require Import OCaml.OCaml. Local Set Primitive Projections. Local Open Scope string_scope. Local Open Scope Z_scope. Local Open Scope type_scope. Import ListNotations. Unset Positivity Checking. Unset Guard Checking. Inductive nat : Set := | O : nat | S : nat -> nat. Inductive natural : Set := | Zero : natural | Succ : natural -> natural. Fixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0} : natural := match plus_arg0 with | Zero => plus_arg1 | Succ n => Succ (plus n plus_arg1) end. Fixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0} : natural := match mult_arg0 with | Zero => Zero | Succ n => plus (mult n mult_arg1) mult_arg1 end. Definition synth (z : natural) (y : natural) (lf2 : natural) (lf1 : natural) : natural := mult lf1 (Succ Zero).
[GOAL] Ω : Type u_1 β : Type u_2 ι : Type u_3 m : MeasurableSpace Ω inst✝³ : TopologicalSpace β inst✝² : Preorder ι u✝ v : ι → Ω → β f : Filtration ι m inst✝¹ : MetrizableSpace β mβ : MeasurableSpace β inst✝ : BorelSpace β u : ι → Ω → β hum : ∀ (i : ι), StronglyMeasurable (u i) ⊢ Adapted (natural u hum) u [PROOFSTEP] intro i [GOAL] Ω : Type u_1 β : Type u_2 ι : Type u_3 m : MeasurableSpace Ω inst✝³ : TopologicalSpace β inst✝² : Preorder ι u✝ v : ι → Ω → β f : Filtration ι m inst✝¹ : MetrizableSpace β mβ : MeasurableSpace β inst✝ : BorelSpace β u : ι → Ω → β hum : ∀ (i : ι), StronglyMeasurable (u i) i : ι ⊢ StronglyMeasurable (u i) [PROOFSTEP] refine' StronglyMeasurable.mono _ (le_iSup₂_of_le i (le_refl i) le_rfl) [GOAL] Ω : Type u_1 β : Type u_2 ι : Type u_3 m : MeasurableSpace Ω inst✝³ : TopologicalSpace β inst✝² : Preorder ι u✝ v : ι → Ω → β f : Filtration ι m inst✝¹ : MetrizableSpace β mβ : MeasurableSpace β inst✝ : BorelSpace β u : ι → Ω → β hum : ∀ (i : ι), StronglyMeasurable (u i) i : ι ⊢ StronglyMeasurable (u i) [PROOFSTEP] rw [stronglyMeasurable_iff_measurable_separable] [GOAL] Ω : Type u_1 β : Type u_2 ι : Type u_3 m : MeasurableSpace Ω inst✝³ : TopologicalSpace β inst✝² : Preorder ι u✝ v : ι → Ω → β f : Filtration ι m inst✝¹ : MetrizableSpace β mβ : MeasurableSpace β inst✝ : BorelSpace β u : ι → Ω → β hum : ∀ (i : ι), StronglyMeasurable (u i) i : ι ⊢ Measurable (u i) ∧ IsSeparable (Set.range (u i)) [PROOFSTEP] exact ⟨measurable_iff_comap_le.2 le_rfl, (hum i).isSeparable_range⟩ [GOAL] Ω : Type u_1 β : Type u_2 ι : Type u_3 m : MeasurableSpace Ω inst✝² : TopologicalSpace β inst✝¹ : Preorder ι u v : ι → Ω → β f : Filtration ι m inst✝ : MeasurableSpace ι h : ProgMeasurable f u ⊢ Adapted f u [PROOFSTEP] intro i [GOAL] Ω : Type u_1 β : Type u_2 ι : Type u_3 m : MeasurableSpace Ω inst✝² : TopologicalSpace β inst✝¹ : Preorder ι u v : ι → Ω → β f : Filtration ι m inst✝ : MeasurableSpace ι h : ProgMeasurable f u i : ι ⊢ StronglyMeasurable (u i) [PROOFSTEP] have : u i = (fun p : Set.Iic i × Ω => u p.1 p.2) ∘ fun x => (⟨i, Set.mem_Iic.mpr le_rfl⟩, x) := rfl [GOAL] Ω : Type u_1 β : Type u_2 ι : Type u_3 m : MeasurableSpace Ω inst✝² : TopologicalSpace β inst✝¹ : Preorder ι u v : ι → Ω → β f : Filtration ι m inst✝ : MeasurableSpace ι h : ProgMeasurable f u i : ι this : u i = (fun p => u (↑p.fst) p.snd) ∘ fun x => ({ val := i, property := (_ : i ∈ Set.Iic i) }, x) ⊢ StronglyMeasurable (u i) [PROOFSTEP] rw [this] [GOAL] Ω : Type u_1 β : Type u_2 ι : Type u_3 m : MeasurableSpace Ω inst✝² : TopologicalSpace β inst✝¹ : Preorder ι u v : ι → Ω → β f : Filtration ι m inst✝ : MeasurableSpace ι h : ProgMeasurable f u i : ι this : u i = (fun p => u (↑p.fst) p.snd) ∘ fun x => ({ val := i, property := (_ : i ∈ Set.Iic i) }, x) ⊢ StronglyMeasurable ((fun p => u (↑p.fst) p.snd) ∘ fun x => ({ val := i, property := (_ : i ∈ Set.Iic i) }, x)) [PROOFSTEP] exact (h i).comp_measurable measurable_prod_mk_left [GOAL] Ω : Type u_1 β : Type u_2 ι : Type u_3 m : MeasurableSpace Ω inst✝⁵ : TopologicalSpace β inst✝⁴ : Preorder ι u v : ι → Ω → β f : Filtration ι m inst✝³ : MeasurableSpace ι t : ι → Ω → ι inst✝² : TopologicalSpace ι inst✝¹ : BorelSpace ι inst✝ : MetrizableSpace ι h : ProgMeasurable f u ht : ProgMeasurable f t ht_le : ∀ (i : ι) (ω : Ω), t i ω ≤ i ⊢ ProgMeasurable f fun i ω => u (t i ω) ω [PROOFSTEP] intro i [GOAL] Ω : Type u_1 β : Type u_2 ι : Type u_3 m : MeasurableSpace Ω inst✝⁵ : TopologicalSpace β inst✝⁴ : Preorder ι u v : ι → Ω → β f : Filtration ι m inst✝³ : MeasurableSpace ι t : ι → Ω → ι inst✝² : TopologicalSpace ι inst✝¹ : BorelSpace ι inst✝ : MetrizableSpace ι h : ProgMeasurable f u ht : ProgMeasurable f t ht_le : ∀ (i : ι) (ω : Ω), t i ω ≤ i i : ι ⊢ StronglyMeasurable fun p => (fun i ω => u (t i ω) ω) (↑p.fst) p.snd [PROOFSTEP] have : (fun p : ↥(Set.Iic i) × Ω => u (t (p.fst : ι) p.snd) p.snd) = (fun p : ↥(Set.Iic i) × Ω => u (p.fst : ι) p.snd) ∘ fun p : ↥(Set.Iic i) × Ω => (⟨t (p.fst : ι) p.snd, Set.mem_Iic.mpr ((ht_le _ _).trans p.fst.prop)⟩, p.snd) := rfl [GOAL] Ω : Type u_1 β : Type u_2 ι : Type u_3 m : MeasurableSpace Ω inst✝⁵ : TopologicalSpace β inst✝⁴ : Preorder ι u v : ι → Ω → β f : Filtration ι m inst✝³ : MeasurableSpace ι t : ι → Ω → ι inst✝² : TopologicalSpace ι inst✝¹ : BorelSpace ι inst✝ : MetrizableSpace ι h : ProgMeasurable f u ht : ProgMeasurable f t ht_le : ∀ (i : ι) (ω : Ω), t i ω ≤ i i : ι this : (fun p => u (t (↑p.fst) p.snd) p.snd) = (fun p => u (↑p.fst) p.snd) ∘ fun p => ({ val := t (↑p.fst) p.snd, property := (_ : t (↑p.fst) p.snd ∈ Set.Iic i) }, p.snd) ⊢ StronglyMeasurable fun p => (fun i ω => u (t i ω) ω) (↑p.fst) p.snd [PROOFSTEP] rw [this] [GOAL] Ω : Type u_1 β : Type u_2 ι : Type u_3 m : MeasurableSpace Ω inst✝⁵ : TopologicalSpace β inst✝⁴ : Preorder ι u v : ι → Ω → β f : Filtration ι m inst✝³ : MeasurableSpace ι t : ι → Ω → ι inst✝² : TopologicalSpace ι inst✝¹ : BorelSpace ι inst✝ : MetrizableSpace ι h : ProgMeasurable f u ht : ProgMeasurable f t ht_le : ∀ (i : ι) (ω : Ω), t i ω ≤ i i : ι this : (fun p => u (t (↑p.fst) p.snd) p.snd) = (fun p => u (↑p.fst) p.snd) ∘ fun p => ({ val := t (↑p.fst) p.snd, property := (_ : t (↑p.fst) p.snd ∈ Set.Iic i) }, p.snd) ⊢ StronglyMeasurable ((fun p => u (↑p.fst) p.snd) ∘ fun p => ({ val := t (↑p.fst) p.snd, property := (_ : t (↑p.fst) p.snd ∈ Set.Iic i) }, p.snd)) [PROOFSTEP] exact (h i).comp_measurable ((ht i).measurable.subtype_mk.prod_mk measurable_snd) [GOAL] Ω : Type u_1 β : Type u_2 ι : Type u_3 m : MeasurableSpace Ω inst✝⁴ : TopologicalSpace β inst✝³ : Preorder ι u v : ι → Ω → β f : Filtration ι m inst✝² : MeasurableSpace ι γ : Type u_4 inst✝¹ : CommMonoid β inst✝ : ContinuousMul β U : γ → ι → Ω → β s : Finset γ h : ∀ (c : γ), c ∈ s → ProgMeasurable f (U c) ⊢ ProgMeasurable f fun i a => ∏ c in s, U c i a [PROOFSTEP] convert ProgMeasurable.finset_prod' h using 1 [GOAL] case h.e'_9 Ω : Type u_1 β : Type u_2 ι : Type u_3 m : MeasurableSpace Ω inst✝⁴ : TopologicalSpace β inst✝³ : Preorder ι u v : ι → Ω → β f : Filtration ι m inst✝² : MeasurableSpace ι γ : Type u_4 inst✝¹ : CommMonoid β inst✝ : ContinuousMul β U : γ → ι → Ω → β s : Finset γ h : ∀ (c : γ), c ∈ s → ProgMeasurable f (U c) ⊢ (fun i a => ∏ c in s, U c i a) = ∏ c in s, U c [PROOFSTEP] ext (i a) [GOAL] case h.e'_9.h.h Ω : Type u_1 β : Type u_2 ι : Type u_3 m : MeasurableSpace Ω inst✝⁴ : TopologicalSpace β inst✝³ : Preorder ι u v : ι → Ω → β f : Filtration ι m inst✝² : MeasurableSpace ι γ : Type u_4 inst✝¹ : CommMonoid β inst✝ : ContinuousMul β U : γ → ι → Ω → β s : Finset γ h : ∀ (c : γ), c ∈ s → ProgMeasurable f (U c) i : ι a : Ω ⊢ ∏ c in s, U c i a = Finset.prod s (fun c => U c) i a [PROOFSTEP] simp only [Finset.prod_apply] [GOAL] Ω : Type u_1 β : Type u_2 ι : Type u_3 m : MeasurableSpace Ω inst✝⁵ : TopologicalSpace β inst✝⁴ : Preorder ι u v : ι → Ω → β f : Filtration ι m γ : Type u_4 inst✝³ : MeasurableSpace ι inst✝² : PseudoMetrizableSpace β fltr : Filter γ inst✝¹ : NeBot fltr inst✝ : IsCountablyGenerated fltr U : γ → ι → Ω → β h : ∀ (l : γ), ProgMeasurable f (U l) h_tendsto : Tendsto U fltr (𝓝 u) ⊢ ProgMeasurable f u [PROOFSTEP] intro i [GOAL] Ω : Type u_1 β : Type u_2 ι : Type u_3 m : MeasurableSpace Ω inst✝⁵ : TopologicalSpace β inst✝⁴ : Preorder ι u v : ι → Ω → β f : Filtration ι m γ : Type u_4 inst✝³ : MeasurableSpace ι inst✝² : PseudoMetrizableSpace β fltr : Filter γ inst✝¹ : NeBot fltr inst✝ : IsCountablyGenerated fltr U : γ → ι → Ω → β h : ∀ (l : γ), ProgMeasurable f (U l) h_tendsto : Tendsto U fltr (𝓝 u) i : ι ⊢ StronglyMeasurable fun p => u (↑p.fst) p.snd [PROOFSTEP] apply @stronglyMeasurable_of_tendsto (Set.Iic i × Ω) β γ (MeasurableSpace.prod _ (f i)) _ _ fltr _ _ _ _ fun l => h l i [GOAL] Ω : Type u_1 β : Type u_2 ι : Type u_3 m : MeasurableSpace Ω inst✝⁵ : TopologicalSpace β inst✝⁴ : Preorder ι u v : ι → Ω → β f : Filtration ι m γ : Type u_4 inst✝³ : MeasurableSpace ι inst✝² : PseudoMetrizableSpace β fltr : Filter γ inst✝¹ : NeBot fltr inst✝ : IsCountablyGenerated fltr U : γ → ι → Ω → β h : ∀ (l : γ), ProgMeasurable f (U l) h_tendsto : Tendsto U fltr (𝓝 u) i : ι ⊢ Tendsto (fun l p => U l (↑p.fst) p.snd) fltr (𝓝 fun p => u (↑p.fst) p.snd) [PROOFSTEP] rw [tendsto_pi_nhds] at h_tendsto ⊢ [GOAL] Ω : Type u_1 β : Type u_2 ι : Type u_3 m : MeasurableSpace Ω inst✝⁵ : TopologicalSpace β inst✝⁴ : Preorder ι u v : ι → Ω → β f : Filtration ι m γ : Type u_4 inst✝³ : MeasurableSpace ι inst✝² : PseudoMetrizableSpace β fltr : Filter γ inst✝¹ : NeBot fltr inst✝ : IsCountablyGenerated fltr U : γ → ι → Ω → β h : ∀ (l : γ), ProgMeasurable f (U l) h_tendsto : ∀ (x : ι), Tendsto (fun i => U i x) fltr (𝓝 (u x)) i : ι ⊢ ∀ (x : ↑(Set.Iic i) × Ω), Tendsto (fun i_1 => U i_1 (↑x.fst) x.snd) fltr (𝓝 (u (↑x.fst) x.snd)) [PROOFSTEP] intro x [GOAL] Ω : Type u_1 β : Type u_2 ι : Type u_3 m : MeasurableSpace Ω inst✝⁵ : TopologicalSpace β inst✝⁴ : Preorder ι u v : ι → Ω → β f : Filtration ι m γ : Type u_4 inst✝³ : MeasurableSpace ι inst✝² : PseudoMetrizableSpace β fltr : Filter γ inst✝¹ : NeBot fltr inst✝ : IsCountablyGenerated fltr U : γ → ι → Ω → β h : ∀ (l : γ), ProgMeasurable f (U l) h_tendsto : ∀ (x : ι), Tendsto (fun i => U i x) fltr (𝓝 (u x)) i : ι x : ↑(Set.Iic i) × Ω ⊢ Tendsto (fun i_1 => U i_1 (↑x.fst) x.snd) fltr (𝓝 (u (↑x.fst) x.snd)) [PROOFSTEP] specialize h_tendsto x.fst [GOAL] Ω : Type u_1 β : Type u_2 ι : Type u_3 m : MeasurableSpace Ω inst✝⁵ : TopologicalSpace β inst✝⁴ : Preorder ι u v : ι → Ω → β f : Filtration ι m γ : Type u_4 inst✝³ : MeasurableSpace ι inst✝² : PseudoMetrizableSpace β fltr : Filter γ inst✝¹ : NeBot fltr inst✝ : IsCountablyGenerated fltr U : γ → ι → Ω → β h : ∀ (l : γ), ProgMeasurable f (U l) i : ι x : ↑(Set.Iic i) × Ω h_tendsto : Tendsto (fun i_1 => U i_1 ↑x.fst) fltr (𝓝 (u ↑x.fst)) ⊢ Tendsto (fun i_1 => U i_1 (↑x.fst) x.snd) fltr (𝓝 (u (↑x.fst) x.snd)) [PROOFSTEP] rw [tendsto_nhds] at h_tendsto ⊢ [GOAL] Ω : Type u_1 β : Type u_2 ι : Type u_3 m : MeasurableSpace Ω inst✝⁵ : TopologicalSpace β inst✝⁴ : Preorder ι u v : ι → Ω → β f : Filtration ι m γ : Type u_4 inst✝³ : MeasurableSpace ι inst✝² : PseudoMetrizableSpace β fltr : Filter γ inst✝¹ : NeBot fltr inst✝ : IsCountablyGenerated fltr U : γ → ι → Ω → β h : ∀ (l : γ), ProgMeasurable f (U l) i : ι x : ↑(Set.Iic i) × Ω h_tendsto : ∀ (s : Set (Ω → β)), IsOpen s → u ↑x.fst ∈ s → (fun i_1 => U i_1 ↑x.fst) ⁻¹' s ∈ fltr ⊢ ∀ (s : Set β), IsOpen s → u (↑x.fst) x.snd ∈ s → (fun i_1 => U i_1 (↑x.fst) x.snd) ⁻¹' s ∈ fltr [PROOFSTEP] exact fun s hs h_mem => h_tendsto {g | g x.snd ∈ s} (hs.preimage (continuous_apply x.snd)) h_mem
State Before: α : Type u β : Type v G : Type w H : Type x inst✝⁶ : TopologicalSpace G inst✝⁵ : Group G inst✝⁴ : TopologicalGroup G inst✝³ : TopologicalSpace α f : α → G s : Set α x : α inst✝² : TopologicalSpace H inst✝¹ : OrderedCommGroup H inst✝ : ContinuousInv H a : H ⊢ Tendsto (fun a => a⁻¹) (𝓟 (Iic a)) (𝓟 (Ici a⁻¹)) State After: no goals Tactic: simp [tendsto_principal_principal]
--stating theorem p and q are proposition theorem and_commutative (p q : Prop) : p ∧ q → q ∧ p := --assumption hypothesis on pq assume hpq : p ∧ q, have hp : p, from and.left hpq, have hq : q, from and.right hpq, --show show q ∧ p, from and.intro hq hp