Datasets:
AI4M
/

text
stringlengths
0
3.34M
context('Test Reading Config') test_that("Missing config generates warning.", { expect_warning(read_config('nonextant.yml'), "Config file not found:") }) test_that("Default config used for all when bad config is supplied", { result <- expect_warning(read_config('nonextant.yml')) expect_identical(result[['clc']], GOCC$DEFAULT_CFG) expect_identical(result[['hbpc']], GOCC$DEFAULT_CFG) expect_identical(result[['dementia']], GOCC$DEFAULT_CFG) })
module Issue2486.HaskellB where {-# FOREIGN GHC import qualified MAlonzo.Code.Issue2486.ImportB as B #-} {-# FOREIGN GHC data Test = Con B.BBool #-}
module Issue1494 where open import Issue1494.Helper module M (r : Record) where open Module r postulate A : Set a b : A Foo : a ≑ b Foo = {!!}
#include "VoDTopologyOracle.hpp" #include "Scheduler.hpp" #include "boost/random/normal_distribution.hpp" #include "UGCPopularity.hpp" #include <boost/lexical_cast.hpp> #include <initializer_list> #include <boost/random/mersenne_twister.hpp> // random generator extern boost::mt19937 gen; VoDTopologyOracle::VoDTopologyOracle(Topology* topo, po::variables_map vm, uint roundDuration) : TopologyOracle(topo, vm, roundDuration) { this->contentNum = vm["contents"].as<uint>(); this->popularity = new UGCPopularity(vm["rounds"].as<uint>(), vm["perturbations"].as<bool>()); } VoDTopologyOracle::~VoDTopologyOracle() { beforePeak.clear(); atPeak.clear(); afterPeak.clear(); } void VoDTopologyOracle::populateCatalog() { // normal distribution to generate content length in minutes boost::random::normal_distribution<> normDist(this->avgContentLength, this->devContentLength); Capacity size = 0; // generate content for (uint i = 0; i < contentNum; i++) { size = std::ceil(normDist(gen) * 60 * this->bitrate); ContentElement* content = new ContentElement(boost::lexical_cast<string > (i), 0, size, size); content->setPeakingRound(popularity->generatePeakRound()); if (content->getPeakingRound() == 0) this->atPeak.push_back(content); else this->beforePeak.push_back(content); this->addContent(content, 0); } } void VoDTopologyOracle::generateUserViewMap(Scheduler* scheduler) { uint totalViews = 0; if (!beforePeak.empty()) { totalViews += popularity->generateViews(beforePeak, BEFORE_PEAK); } if (!atPeak.empty()) { totalViews += popularity->generateViews(atPeak, AT_PEAK); } if (!afterPeak.empty()) { totalViews += popularity->generateViews(afterPeak, AFTER_PEAK); } uint totalPeers = topo->getNumCustomers(); double avgViewsPerPeer = (double) totalViews / (double) totalPeers; double avgHoursPerUserGen = avgViewsPerPeer * (this->avgContentLength / 60); if (avgHoursPerUserGen != this->avgHoursPerUser) { // scale content views to available customers std::cout << "Scaling views to ensure the average hours of view " "per peer per round is approximately " << this->avgHoursPerUser << " (current average: " << avgHoursPerUserGen << ")" << std::endl; double scale = this->avgHoursPerUser / avgHoursPerUserGen; totalViews = 0; BOOST_FOREACH(ContentElement* content, beforePeak) { if (content->getViewsThisRound() > 0) { content->setViewsThisRound(std::max(1, (int) std::floor(content->getViewsThisRound() * scale))); totalViews += content->getViewsThisRound(); } } BOOST_FOREACH(ContentElement* content, atPeak) { if (content->getViewsThisRound() > 0) { content->setViewsThisRound(std::max(1, (int) std::floor(content->getViewsThisRound() * scale))); totalViews += content->getViewsThisRound(); } } BOOST_FOREACH(ContentElement* content, afterPeak) { if (content->getViewsThisRound() > 0) { content->setViewsThisRound(std::max(1, (int) std::floor(content->getViewsThisRound() * scale))); totalViews += content->getViewsThisRound(); } } std::cout << "Total views after scaling: " << totalViews << ", avgViewsPerPeer: " << (double) totalViews / (double) totalPeers << std::endl; } // Views have been generated, now we need to map them to random users this->scheduleRequests(beforePeak, scheduler); this->scheduleRequests(atPeak, scheduler); this->scheduleRequests(afterPeak, scheduler); } // This method is not used in VoD simulations, remove it void VoDTopologyOracle::generateNewRequest(PonUser user, SimTime time, Scheduler* scheduler) { return; } void VoDTopologyOracle::updateCatalog(uint currentRound) { // move content that peaked last round to afterPeak afterPeak.splice(afterPeak.begin(), atPeak); // move content that peaks in the next round from beforePeak to atPeak std::list<ContentElement*>::iterator temp; std::list<ContentElement*>::iterator it = beforePeak.begin(); while (it != beforePeak.end()) { if ((*it)->getPeakingRound() == currentRound + 1) { temp = it; temp++; atPeak.splice(atPeak.end(), beforePeak, it); it = temp; } else it++; } } void VoDTopologyOracle::scheduleRequests(std::list<ContentElement*> list, Scheduler* scheduler) { boost::random::discrete_distribution<> hourDist(usrPctgByHour); boost::random::discrete_distribution<> dayDist(dayWeights); boost::random::uniform_int_distribution<> minSecDist(0, 3599); std::vector<Vertex> ponNodes = this->getTopology()->getPonNodes(); uint totUsers = topo->getNumCustomers(); std::set<uint> assignedUsers; uint randUser; PonUser randPonUser; BOOST_FOREACH (ContentElement* content, list) { // Newest implementation: ensures that a random value is computed exactly // viewsThisWeek times, no more. However this doesn't check that the // selected user does not have this content cached. After all, cached // content CAN be requested for a new view and that's part of the model. // Check that we are going to have enough users to be mapped to requests uint views = content->getViewsThisRound(); if (totUsers < views) { std::cout << "VoDTopologyOracle::serveRequests() - Not enough users to map all " << views << " requests for content " << content->getName() << ", truncating to " << totUsers << std::endl; content->setViewsThisRound(totUsers); } // Select random users to map requests for (uint j = totUsers - views; j < totUsers; j++) { boost::random::uniform_int_distribution<> userDist(0, j-1); randUser = userDist(gen); if (assignedUsers.insert(randUser).second == false) { randUser = j; auto rValue = assignedUsers.insert(randUser); assert(rValue.second == true); } /* this worked very well when all PONs had the same # of customers, now * we are forced to go through the following loop to map a planar integer * to the right PonUser, unless I can find a better way to deal with this. */ uint t(0), oldt(0), i(0); while (randUser >= t) { oldt = t; t += topo->getPonCustomers(ponNodes.at(i)); i++; } assert(topo->getPonCustomers(ponNodes.at(i - 1)) > randUser - oldt); randPonUser = std::make_pair(ponNodes.at(i - 1), randUser - oldt); // generate a random request time SimTime reqTime = dayDist(gen) * 86400 + // day hourDist(gen) * 3600 + // hour minSecDist(gen); // minutes and seconds // generate request // TODO: Add support for zapping in VoD too. Flow* req = new Flow(content, randPonUser, reqTime); scheduler->schedule(req); } assignedUsers.clear(); /* New implementation: roll over the amount of users and add those already * chosen to a set to avoid repetitions. Hopefully faster. // Check that we are going to have enough users to be mapped to requests // TODO: might want to do this even if views do not reach this value but // are numerous enough that rolling for a random unassigned user becomes a // significant time sink uint unavailableUsers = oracle->getSources(content).size(); if (totUsers - unavailableUsers <= content->getViewsThisRound()) { std::cout << "TestRun::serveRequests() - Not enough users to map all " << content->getViewsThisRound() << " requests for content " << content->getName() << ", truncating to " << totUsers - unavailableUsers << std::endl; content->setViewsThisRound(totUsers - unavailableUsers); // assign the views sequentially rather than randomly, as we know all // users are going to be involved anyway BOOST_FOREACH(Vertex v, ponNodes) { for (uint i = 0; i < ponCardinality; i++) { // check that this user has not the content in its cache if (oracle->checkIfCached(std::make_pair(v,i), content) == false) { // generate a random request time SimTime reqTime = dayDist(gen) * 86400 + // day hourDist(gen) * 3600 + // hour minSecDist(gen); // minutes and seconds // generate request Flow* req = new Flow(content, std::make_pair(v, i), reqTime); scheduler->schedule(req); } } } } else { // we've got more users than requests, roll randomly PonUser randPonUser; uint ponNodeIndex, userIndex; for (unsigned int i = 0; i < content->getViewsThisRound(); i++) { // choose a random new Pon node as the requester of the content; // checks that the user hasn't already requested that content this round // and that it is not caching it do { randUser = userDist(gen); ponNodeIndex = std::floor(randUser / ponCardinality); userIndex = randUser % ponCardinality; randPonUser = std::make_pair(ponNodes[ponNodeIndex],userIndex); } while (assignedUsers.insert(randUser).second != false && oracle->checkIfCached(randPonUser, content)); // generate a random request time SimTime reqTime = dayDist(gen) * 86400 + // day hourDist(gen) * 3600 + // hour minSecDist(gen); // minutes and seconds // generate request Flow* req = new Flow(content, randPonUser, reqTime); scheduler->schedule(req); } } assignedUsers.clear(); */ /* Old implementation - building a vector of all available PonUsers and removing them from the list as we select them. Terribly slow. // build a vector of all the available PonUsers std::vector<PonUser> availableUsers; BOOST_FOREACH(Vertex v, ponNodes) { for (unsigned int i = 0; i < ponCardinality; i++) { availableUsers.push_back(std::make_pair<unsigned int, unsigned int>(v,i)); } } for (unsigned int i = 0; i < content->getViewsThisRound(); i++) { // choose a random new Pon node as the requester of the content boost::uniform_int<unsigned int> uniDist(0, availableUsers.size()); unsigned int randUser = uniDist(gen); // generate a random request time SimTime reqTime = dayDist(gen) * 86400 + // day hourDist(gen) * 3600 + // hour minSecDist(gen); // minutes and seconds std::vector<PonUser>::iterator vIt = availableUsers.begin()+randUser; Request* req = new Request(reqTime, *vIt, content); scheduler->schedule(req); // erase the pon nodes from the available requesters (1 request // per node per content) availableUsers.erase(vIt); if (availableUsers.size() == 0) { // we ran out of requesters so we cannot allocate any more requests std::cout << "TestRun::execute() - not enough PON nodes to serve " "requests for content " << content->getName() << std::endl; break; } } */ } }
// Boost.Geometry (aka GGL, Generic Geometry Library) // Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands. // Copyright (c) 2008-2012 Bruno Lalande, Paris, France. // Copyright (c) 2009-2012 Mateusz Loskot, London, UK. // Copyright (c) 2014 Samuel Debionne, Grenoble, France. // Parts of Boost.Geometry are redesigned from Geodan's Geographic Library // (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands. // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_GEOMETRY_ALGORITHMS_ASSIGN_HPP #define BOOST_GEOMETRY_ALGORITHMS_ASSIGN_HPP #include <cstddef> #include <boost/concept/requires.hpp> #include <boost/concept_check.hpp> #include <boost/mpl/assert.hpp> #include <boost/mpl/if.hpp> #include <boost/numeric/conversion/bounds.hpp> #include <boost/numeric/conversion/cast.hpp> #include <boost/type_traits.hpp> #include <boost/geometry/algorithms/detail/assign_box_corners.hpp> #include <boost/geometry/algorithms/detail/assign_indexed_point.hpp> #include <boost/geometry/algorithms/detail/assign_values.hpp> #include <boost/geometry/algorithms/convert.hpp> #include <boost/geometry/algorithms/append.hpp> #include <boost/geometry/algorithms/clear.hpp> #include <boost/geometry/arithmetic/arithmetic.hpp> #include <boost/geometry/core/access.hpp> #include <boost/geometry/core/exterior_ring.hpp> #include <boost/geometry/core/tags.hpp> #include <boost/geometry/geometries/concepts/check.hpp> #include <boost/geometry/util/for_each_coordinate.hpp> #include <boost/variant/variant_fwd.hpp> namespace boost { namespace geometry { /*! \brief Assign a range of points to a linestring, ring or polygon \note The point-type of the range might be different from the point-type of the geometry \ingroup assign \tparam Geometry \tparam_geometry \tparam Range \tparam_range_point \param geometry \param_geometry \param range \param_range_point \qbk{ [heading Notes] [note Assign automatically clears the geometry before assigning (use append if you don't want that)] [heading Example] [assign_points] [assign_points_output] [heading See also] \* [link geometry.reference.algorithms.append append] } */ template <typename Geometry, typename Range> inline void assign_points(Geometry& geometry, Range const& range) { concept::check<Geometry>(); clear(geometry); geometry::append(geometry, range, -1, 0); } /*! \brief assign to a box inverse infinite \details The assign_inverse function initialize a 2D or 3D box with large coordinates, the min corner is very large, the max corner is very small. This is a convenient starting point to collect the minimum bounding box of a geometry. \ingroup assign \tparam Geometry \tparam_geometry \param geometry \param_geometry \qbk{ [heading Example] [assign_inverse] [assign_inverse_output] [heading See also] \* [link geometry.reference.algorithms.make.make_inverse make_inverse] } */ template <typename Geometry> inline void assign_inverse(Geometry& geometry) { concept::check<Geometry>(); dispatch::assign_inverse < typename tag<Geometry>::type, Geometry >::apply(geometry); } /*! \brief assign zero values to a box, point \ingroup assign \details The assign_zero function initializes a 2D or 3D point or box with coordinates of zero \tparam Geometry \tparam_geometry \param geometry \param_geometry */ template <typename Geometry> inline void assign_zero(Geometry& geometry) { concept::check<Geometry>(); dispatch::assign_zero < typename tag<Geometry>::type, Geometry >::apply(geometry); } /*! \brief Assign two coordinates to a geometry (usually a 2D point) \ingroup assign \tparam Geometry \tparam_geometry \tparam Type \tparam_numeric to specify the coordinates \param geometry \param_geometry \param c1 \param_x \param c2 \param_y \qbk{distinguish, 2 coordinate values} \qbk{ [heading Example] [assign_2d_point] [assign_2d_point_output] [heading See also] \* [link geometry.reference.algorithms.make.make_2_2_coordinate_values make] } */ template <typename Geometry, typename Type> inline void assign_values(Geometry& geometry, Type const& c1, Type const& c2) { concept::check<Geometry>(); dispatch::assign < typename tag<Geometry>::type, Geometry, geometry::dimension<Geometry>::type::value >::apply(geometry, c1, c2); } /*! \brief Assign three values to a geometry (usually a 3D point) \ingroup assign \tparam Geometry \tparam_geometry \tparam Type \tparam_numeric to specify the coordinates \param geometry \param_geometry \param c1 \param_x \param c2 \param_y \param c3 \param_z \qbk{distinguish, 3 coordinate values} \qbk{ [heading Example] [assign_3d_point] [assign_3d_point_output] [heading See also] \* [link geometry.reference.algorithms.make.make_3_3_coordinate_values make] } */ template <typename Geometry, typename Type> inline void assign_values(Geometry& geometry, Type const& c1, Type const& c2, Type const& c3) { concept::check<Geometry>(); dispatch::assign < typename tag<Geometry>::type, Geometry, geometry::dimension<Geometry>::type::value >::apply(geometry, c1, c2, c3); } /*! \brief Assign four values to a geometry (usually a box or segment) \ingroup assign \tparam Geometry \tparam_geometry \tparam Type \tparam_numeric to specify the coordinates \param geometry \param_geometry \param c1 First coordinate (usually x1) \param c2 Second coordinate (usually y1) \param c3 Third coordinate (usually x2) \param c4 Fourth coordinate (usually y2) \qbk{distinguish, 4 coordinate values} */ template <typename Geometry, typename Type> inline void assign_values(Geometry& geometry, Type const& c1, Type const& c2, Type const& c3, Type const& c4) { concept::check<Geometry>(); dispatch::assign < typename tag<Geometry>::type, Geometry, geometry::dimension<Geometry>::type::value >::apply(geometry, c1, c2, c3, c4); } namespace resolve_variant { template <typename Geometry1, typename Geometry2> struct assign { static inline void apply( Geometry1& geometry1, const Geometry2& geometry2) { concept::check<Geometry1>(); concept::check<Geometry2 const>(); concept::check_concepts_and_equal_dimensions<Geometry1, Geometry2 const>(); bool const same_point_order = point_order<Geometry1>::value == point_order<Geometry2>::value; bool const same_closure = closure<Geometry1>::value == closure<Geometry2>::value; BOOST_MPL_ASSERT_MSG ( same_point_order, ASSIGN_IS_NOT_SUPPORTED_FOR_DIFFERENT_POINT_ORDER , (types<Geometry1, Geometry2>) ); BOOST_MPL_ASSERT_MSG ( same_closure, ASSIGN_IS_NOT_SUPPORTED_FOR_DIFFERENT_CLOSURE , (types<Geometry1, Geometry2>) ); dispatch::convert<Geometry2, Geometry1>::apply(geometry2, geometry1); } }; template <BOOST_VARIANT_ENUM_PARAMS(typename T), typename Geometry2> struct assign<variant<BOOST_VARIANT_ENUM_PARAMS(T)>, Geometry2> { struct visitor: static_visitor<void> { Geometry2 const& m_geometry2; visitor(Geometry2 const& geometry2) : m_geometry2(geometry2) {} template <typename Geometry1> result_type operator()(Geometry1& geometry1) const { return assign < Geometry1, Geometry2 >::apply (geometry1, m_geometry2); } }; static inline void apply(variant<BOOST_VARIANT_ENUM_PARAMS(T)>& geometry1, Geometry2 const& geometry2) { return apply_visitor(visitor(geometry2), geometry1); } }; template <typename Geometry1, BOOST_VARIANT_ENUM_PARAMS(typename T)> struct assign<Geometry1, variant<BOOST_VARIANT_ENUM_PARAMS(T)> > { struct visitor: static_visitor<void> { Geometry1& m_geometry1; visitor(Geometry1 const& geometry1) : m_geometry1(geometry1) {} template <typename Geometry2> result_type operator()(Geometry2 const& geometry2) const { return assign < Geometry1, Geometry2 >::apply (m_geometry1, geometry2); } }; static inline void apply(Geometry1& geometry1, variant<BOOST_VARIANT_ENUM_PARAMS(T)> const& geometry2) { return apply_visitor(visitor(geometry1), geometry2); } }; template <BOOST_VARIANT_ENUM_PARAMS(typename A), BOOST_VARIANT_ENUM_PARAMS(typename B)> struct assign<variant<BOOST_VARIANT_ENUM_PARAMS(A)>, variant<BOOST_VARIANT_ENUM_PARAMS(B)> > { struct visitor: static_visitor<void> { template <typename Geometry1, typename Geometry2> result_type operator()( Geometry1& geometry1, Geometry2 const& geometry2) const { return assign < Geometry1, Geometry2 >::apply (geometry1, geometry2); } }; static inline void apply(variant<BOOST_VARIANT_ENUM_PARAMS(A)>& geometry1, variant<BOOST_VARIANT_ENUM_PARAMS(B)> const& geometry2) { return apply_visitor(visitor(), geometry1, geometry2); } }; } // namespace resolve_variant /*! \brief Assigns one geometry to another geometry \details The assign algorithm assigns one geometry, e.g. a BOX, to another geometry, e.g. a RING. This only works if it is possible and applicable. \ingroup assign \tparam Geometry1 \tparam_geometry \tparam Geometry2 \tparam_geometry \param geometry1 \param_geometry (target) \param geometry2 \param_geometry (source) \qbk{ [heading Example] [assign] [assign_output] [heading See also] \* [link geometry.reference.algorithms.convert convert] } */ template <typename Geometry1, typename Geometry2> inline void assign(Geometry1& geometry1, Geometry2 const& geometry2) { resolve_variant::assign<Geometry1, Geometry2>::apply(geometry1, geometry2); } }} // namespace boost::geometry #endif // BOOST_GEOMETRY_ALGORITHMS_ASSIGN_HPP
module Data.Int.Algebra import Control.Algebra %access public export --- ||| Return the smallest non-negative representative of the class of a modulo n. leastPositiveResidue : (Integral ty, Ord ty) => (a : ty) -> (b : ty) -> ty leastPositiveResidue a n = let r = a `mod` n in if r < 0 then r + n else r data Zn : (n : Nat) -> Type where MkZn : Int -> Zn n Semigroup (Zn n) where (MkZn x) <+> (MkZn y) = let z = x + y; i = fromNat n in MkZn $ if z < i then z else z - i Monoid (Zn n) where neutral = MkZn 0 Group (Zn n) where inverse (MkZn x) = MkZn (fromNat n - x) Eq (Zn n) where (MkZn x) == (MkZn y) = x == y DecEq (Zn n) where decEq x y = case x == y of True => Yes primitiveEq False => No primitiveNotEq where primitiveEq : x = y primitiveEq = really_believe_me (Refl {x}) primitiveNotEq : x = y -> Void primitiveNotEq prf = believe_me {b = Void} () Show (Zn n) where show (MkZn a) = show (leastPositiveResidue a (fromNat n))
{-# LANGUAGE AllowAmbiguousTypes, DataKinds, FlexibleInstances, FunctionalDependencies, QuantifiedConstraints, RankNTypes, TypeFamilies, TypeOperators #-} {-# OPTIONS_GHC -fconstraint-solver-iterations=16 #-} {-# OPTIONS_GHC -Wno-missing-methods #-} {-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-} {-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise #-} -- | Dual numbers and various operations on them, arithmetic and related -- to tensors (vectors, matrices and others). This is the high-level API, -- defined using the low-level API in "HordeAd.Core.DualClass". module HordeAd.Core.DualNumber ( module HordeAd.Core.DualNumber , IsScalar, HasDelta, DMode(..) , Domain0, Domain1, Domain2, DomainX, Domains -- an important re-export ) where import Prelude import qualified Data.Array.Convert import qualified Data.Array.Dynamic as OTB import qualified Data.Array.DynamicS as OT import Data.Array.Internal (valueOf) import Data.Array.Shape (DivRoundUp) import qualified Data.Array.Shaped as OSB import qualified Data.Array.ShapedS as OS import Data.List.Index (imap) import Data.MonoTraversable (MonoFunctor (omap)) import Data.Proxy (Proxy (Proxy)) import qualified Data.Strict.Vector as Data.Vector import qualified Data.Vector.Generic as V import GHC.TypeLits (KnownNat, type (+), type (-), type (<=)) import Numeric.LinearAlgebra (Matrix, Numeric, Vector) import qualified Numeric.LinearAlgebra as HM import HordeAd.Core.DualClass import HordeAd.Internal.Delta (CodeOut (..), Domain0, Domain1, Domain2, DomainX, Domains) -- * The main dual number types -- | Dual numbers with the second type argument being the primal component. data DualNumber (d :: DMode) a = D a (Dual d a) class (IsScalar d r, Monad m, Functor m, Applicative m) => DualMonad d r m | m -> d r where returnLet :: IsPrimalWithScalar d a r => DualNumber d a -> m (DualNumber d a) addParameters :: (Numeric r, Num (Vector r)) => Domains r -> Domains r -> Domains r addParameters (a0, a1, a2, aX) (b0, b1, b2, bX) = (a0 + b0, V.zipWith (+) a1 b1, V.zipWith (+) a2 b2, V.zipWith (+) aX bX) -- Dot product and sum respective ranks and sum it all. dotParameters :: Numeric r => Domains r -> Domains r -> r dotParameters (a0, a1, a2, aX) (b0, b1, b2, bX) = a0 HM.<.> b0 + V.sum (V.zipWith (HM.<.>) a1 b1) + V.sum (V.zipWith (HM.<.>) (V.map HM.flatten a2) (V.map HM.flatten b2)) + V.sum (V.zipWith (HM.<.>) (V.map OT.toVector aX) (V.map OT.toVector bX)) -- * General operations, for any tensor rank -- These instances are required by the @Real@ instance, which is required -- by @RealFloat@, which gives @atan2@. No idea what properties -- @Real@ requires here, so let it crash if it's really needed. instance Eq (DualNumber d a) where instance Ord (DualNumber d a) where -- These instances are dangerous due to possible subexpression copies -- leading to allocation explosion. Expressions should be wrapped in -- the monadic @returnLet@ whenever there is a possibility they can be -- used multiple times in a larger expression. instance (Num a, IsPrimal d a) => Num (DualNumber d a) where D u u' + D v v' = D (u + v) (dAdd u' v') D u u' - D v v' = D (u - v) (dAdd u' (dScale (-1) v')) D u u' * D v v' = D (u * v) (dAdd (dScale v u') (dScale u v')) negate (D v v') = D (negate v) (dScale (-1) v') abs (D v v') = D (abs v) (dScale (signum v) v') signum (D v _) = D (signum v) dZero fromInteger = constant . fromInteger instance (Real a, IsPrimal d a) => Real (DualNumber d a) where toRational = undefined -- TODO? instance (Fractional a, IsPrimal d a) => Fractional (DualNumber d a) where D u u' / D v v' = let recipSq = recip (v * v) in D (u / v) (dAdd (dScale (v * recipSq) u') (dScale (- u * recipSq) v')) recip (D v v') = let minusRecipSq = - recip (v * v) in D (recip v) (dScale minusRecipSq v') fromRational = constant . fromRational instance (Floating a, IsPrimal d a) => Floating (DualNumber d a) where pi = constant pi exp (D u u') = let expU = exp u in D expU (dScale expU u') log (D u u') = D (log u) (dScale (recip u) u') sqrt (D u u') = let sqrtU = sqrt u in D sqrtU (dScale (recip (sqrtU + sqrtU)) u') D u u' ** D v v' = D (u ** v) (dAdd (dScale (v * (u ** (v - 1))) u') (dScale ((u ** v) * log u) v')) logBase x y = log y / log x sin (D u u') = D (sin u) (dScale (cos u) u') cos (D u u') = D (cos u) (dScale (- (sin u)) u') tan (D u u') = let cosU = cos u in D (tan u) (dScale (recip (cosU * cosU)) u') asin (D u u') = D (asin u) (dScale (recip (sqrt (1 - u*u))) u') acos (D u u') = D (acos u) (dScale (- recip (sqrt (1 - u*u))) u') atan (D u u') = D (atan u) (dScale (recip (1 + u*u)) u') sinh (D u u') = D (sinh u) (dScale (cosh u) u') cosh (D u u') = D (cosh u) (dScale (sinh u) u') tanh (D u u') = let y = tanh u in D y (dScale (1 - y * y) u') asinh (D u u') = D (asinh u) (dScale (recip (sqrt (1 + u*u))) u') acosh (D u u') = D (acosh u) (dScale (recip (sqrt (u*u - 1))) u') atanh (D u u') = D (atanh u) (dScale (recip (1 - u*u)) u') instance (RealFrac a, IsPrimal d a) => RealFrac (DualNumber d a) where properFraction = undefined -- very low priority, since these are all extremely not continuous instance (RealFloat a, IsPrimal d a) => RealFloat (DualNumber d a) where atan2 (D u u') (D v v') = let t = 1 / (u * u + v * v) in D (atan2 u v) (dAdd (dScale (- u * t) v') (dScale (v * t) u')) -- we can be selective here and omit the other methods, -- most of which don't even have a differentiable codomain constant :: IsPrimal d a => a -> DualNumber d a constant a = D a dZero scale :: (Num a, IsPrimal d a) => a -> DualNumber d a -> DualNumber d a scale a (D u u') = D (a * u) (dScale a u') tanhAct :: (DualMonad d r m, IsPrimalAndHasFeatures d a r) => DualNumber d a -> m (DualNumber d a) tanhAct = returnLet . tanh logistic :: (Floating a, IsPrimal d a) => DualNumber d a -> DualNumber d a logistic (D u u') = let y = recip (1 + exp (- u)) in D y (dScale (y * (1 - y)) u') logisticAct :: (DualMonad d r m, IsPrimalAndHasFeatures d a r) => DualNumber d a -> m (DualNumber d a) logisticAct = returnLet . logistic -- Optimized and more clearly written @u ** 2@. square :: (Num a, IsPrimal d a) => DualNumber d a -> DualNumber d a square (D u u') = D (u * u) (dScale (2 * u) u') squaredDifference :: (Num a, IsPrimal d a) => a -> DualNumber d a -> DualNumber d a squaredDifference targ res = square $ res - constant targ lossSquared :: (DualMonad d r m, IsPrimalAndHasFeatures d a r) => a -> DualNumber d a -> m (DualNumber d a) lossSquared targ res = returnLet $ squaredDifference targ res reluAct :: (DualMonad d r m, IsPrimalAndHasFeatures d a r) => DualNumber d a -> m (DualNumber d a) reluAct v@(D u _) = do let oneIfGtZero = omap (\x -> if x > 0 then 1 else 0) u returnLet $ scale oneIfGtZero v reluLeakyAct :: (DualMonad d r m, IsPrimalAndHasFeatures d a r) => DualNumber d a -> m (DualNumber d a) reluLeakyAct v@(D u _) = do let oneIfGtZero = omap (\x -> if x > 0 then 1 else 0.01) u returnLet $ scale oneIfGtZero v -- * Operations resulting in a scalar sumElements0 :: IsScalar d r => DualNumber d (Vector r) -> DualNumber d r sumElements0 (D u u') = D (HM.sumElements u) (dSumElements0 u' (V.length u)) index0 :: IsScalar d r => DualNumber d (Vector r) -> Int -> DualNumber d r index0 (D u u') ix = D (u V.! ix) (dIndex0 u' ix (V.length u)) minimum0 :: IsScalar d r => DualNumber d (Vector r) -> DualNumber d r minimum0 (D u u') = D (HM.minElement u) (dIndex0 u' (HM.minIndex u) (V.length u)) maximum0 :: IsScalar d r => DualNumber d (Vector r) -> DualNumber d r maximum0 (D u u') = D (HM.maxElement u) (dIndex0 u' (HM.maxIndex u) (V.length u)) -- If @v'@ is a @Var1@, this is much faster due to the optimization -- in @Index0@. foldl'0 :: IsScalar d r => (DualNumber d r -> DualNumber d r -> DualNumber d r) -> DualNumber d r -> DualNumber d (Vector r) -> DualNumber d r foldl'0 f uu' (D v v') = let k = V.length v g !acc ix p = f (D p (dIndex0 v' ix k)) acc in V.ifoldl' g uu' v altSumElements0 :: IsScalar d r => DualNumber d (Vector r) -> DualNumber d r altSumElements0 = foldl'0 (+) 0 -- | Dot product. infixr 8 <.>! (<.>!) :: IsScalar d r => DualNumber d (Vector r) -> DualNumber d (Vector r) -> DualNumber d r (<.>!) (D u u') (D v v') = D (u HM.<.> v) (dAdd (dDot0 v u') (dDot0 u v')) -- | Dot product with a constant vector. infixr 8 <.>!! (<.>!!) :: IsScalar d r => DualNumber d (Vector r) -> Vector r -> DualNumber d r (<.>!!) (D u u') v = D (u HM.<.> v) (dDot0 v u') infixr 8 <.>$ (<.>$) :: (IsScalar d r, KnownNat n) => DualNumber d (OS.Array '[n] r) -> DualNumber d (OS.Array '[n] r) -> DualNumber d r (<.>$) d e = fromS1 d <.>! fromS1 e fromX0 :: IsScalar d r => DualNumber d (OT.Array r) -> DualNumber d r fromX0 (D u u') = D (OT.unScalar u) (dFromX0 u') fromS0 :: IsScalar d r => DualNumber d (OS.Array '[] r) -> DualNumber d r fromS0 (D u u') = D (OS.unScalar u) (dFromS0 u') sumElementsVectorOfDual :: IsScalar d r => Data.Vector.Vector (DualNumber d r) -> DualNumber d r sumElementsVectorOfDual = V.foldl' (+) 0 softMaxAct :: DualMonad d r m => Data.Vector.Vector (DualNumber d r) -> m (Data.Vector.Vector (DualNumber d r)) softMaxAct us = do expUs <- V.mapM (returnLet . exp) us let sumExpUs = sumElementsVectorOfDual expUs -- This has to be let-bound, because it's used many times below. recipSum <- returnLet $ recip sumExpUs V.mapM (\r -> returnLet $ r * recipSum) expUs -- In terms of hmatrix: @-(log res <.> targ)@. lossCrossEntropy :: forall d r m. DualMonad d r m => Vector r -> Data.Vector.Vector (DualNumber d r) -> m (DualNumber d r) lossCrossEntropy targ res = do let f :: DualNumber d r -> Int -> DualNumber d r -> DualNumber d r f !acc i d = acc + scale (targ V.! i) (log d) returnLet $ negate $ V.ifoldl' f 0 res -- In terms of hmatrix: @-(log res <.> targ)@. lossCrossEntropyV :: DualMonad d r m => Vector r -> DualNumber d (Vector r) -> m (DualNumber d r) lossCrossEntropyV targ res = returnLet $ negate $ log res <.>!! targ -- Note that this is equivalent to a composition of softMax and cross entropy -- only when @target@ is one-hot. Otherwise, results vary wildly. In our -- rendering of the MNIST data all labels are on-hot. lossSoftMaxCrossEntropyV :: DualMonad d r m => Vector r -> DualNumber d (Vector r) -> m (DualNumber d r) lossSoftMaxCrossEntropyV target (D u u') = do -- The following protects from underflows, overflows and exploding gradients -- and is required by the QuickCheck test in TestMnistCNN. -- See https://github.com/tensorflow/tensorflow/blob/5a566a7701381a5cf7f70fce397759483764e482/tensorflow/core/kernels/sparse_softmax_op.cc#L106 -- and https://github.com/tensorflow/tensorflow/blob/5a566a7701381a5cf7f70fce397759483764e482/tensorflow/core/kernels/xent_op.h let expU = exp (u - HM.scalar (HM.maxElement u)) sumExpU = HM.sumElements expU recipSum = recip sumExpU -- not exposed: softMaxU = HM.scaleRecip sumExpU expU softMaxU = HM.scale recipSum expU returnLet $ D (negate $ log softMaxU HM.<.> target) -- TODO: avoid: log . exp (dDot0 (softMaxU - target) u') -- * Operations resulting in a vector -- @1@ means rank one, so the dual component represents a vector. seq1 :: IsScalar d r => Data.Vector.Vector (DualNumber d r) -> DualNumber d (Vector r) seq1 v = D (V.convert $ V.map (\(D u _) -> u) v) -- I hope this fuses (dSeq1 $ V.map (\(D _ u') -> u') v) konst1 :: IsScalar d r => DualNumber d r -> Int -> DualNumber d (Vector r) konst1 (D u u') n = D (HM.konst u n) (dKonst1 u' n) append1 :: IsScalar d r => DualNumber d (Vector r) -> DualNumber d (Vector r) -> DualNumber d (Vector r) append1 (D u u') (D v v') = D (u V.++ v) (dAppend1 u' (V.length u) v') slice1 :: IsScalar d r => Int -> Int -> DualNumber d (Vector r) -> DualNumber d (Vector r) slice1 i n (D u u') = D (V.slice i n u) (dSlice1 i n u' (V.length u)) sumRows1 :: IsScalar d r => DualNumber d (Matrix r) -> DualNumber d (Vector r) sumRows1 (D u u') = D (V.fromList $ map HM.sumElements $ HM.toRows u) (dSumRows1 u' (HM.cols u)) sumColumns1 :: IsScalar d r => DualNumber d (Matrix r) -> DualNumber d (Vector r) sumColumns1 (D u u') = D (V.fromList $ map HM.sumElements $ HM.toColumns u) (dSumColumns1 u' (HM.rows u)) -- If @v'@ is a @Var1@, this is much faster due to the optimization -- in @Index0@. The detour through a boxed vector (list probably fuses away) -- is costly, but only matters if @f@ is cheap. map1 :: IsScalar d r => (DualNumber d r -> DualNumber d r) -> DualNumber d (Vector r) -> DualNumber d (Vector r) map1 f (D v v') = let k = V.length v g ix p = f $ D p (dIndex0 v' ix k) ds = imap g $ V.toList v in seq1 $ V.fromList ds -- | Dense matrix-vector product. infixr 8 #>! (#>!) :: IsScalar d r => DualNumber d (Matrix r) -> DualNumber d (Vector r) -> DualNumber d (Vector r) (#>!) (D u u') (D v v') = D (u HM.#> v) (dAdd (dMD_V1 u' v) (dM_VD1 u v')) -- | Dense matrix-vector product with a constant vector. infixr 8 #>!! (#>!!) :: IsScalar d r => DualNumber d (Matrix r) -> Vector r -> DualNumber d (Vector r) (#>!!) (D u u') v = D (u HM.#> v) (dMD_V1 u' v) fromX1 :: IsScalar d r => DualNumber d (OT.Array r) -> DualNumber d (Vector r) fromX1 (D u u') = D (OT.toVector u) (dFromX1 u') fromS1 :: forall len d r. (KnownNat len, IsScalar d r) => DualNumber d (OS.Array '[len] r) -> DualNumber d (Vector r) fromS1 (D u u') = D (OS.toVector u) (dFromS1 u') reverse1 :: IsScalar d r => DualNumber d (Vector r) -> DualNumber d (Vector r) reverse1 (D u u') = D (V.reverse u) (dReverse1 u') flatten1 :: IsScalar d r => DualNumber d (Matrix r) -> DualNumber d (Vector r) flatten1 (D u u') = let (rows, cols) = HM.size u in D (HM.flatten u) (dFlatten1 rows cols u') flattenX1 :: IsScalar d r => DualNumber d (OT.Array r) -> DualNumber d (Vector r) flattenX1 (D u u') = let sh = OT.shapeL u in D (OT.toVector u) (dFlattenX1 sh u') flattenS1 :: (IsScalar d r, OS.Shape sh) => DualNumber d (OS.Array sh r) -> DualNumber d (Vector r) flattenS1 (D u u') = D (OS.toVector u) (dFlattenS1 u') corr1 :: IsScalar d r => DualNumber d (Vector r) -> DualNumber d (Vector r) -> DualNumber d (Vector r) corr1 ker@(D u _) vv@(D v _) = case (V.length u, V.length v) of (0, lenV) -> konst1 0 lenV (lenK, lenV) -> if lenK <= lenV then vectorSlices2 lenK vv #>! ker else error $ "corr1: len kernel " ++ show lenK ++ " > len vector " ++ show lenV -- This is not optimally implemented: @append1@ is costly compared -- to a @mconcat@ counterpart and @z@ is used twice without -- assigning it to a variable. conv1 :: IsScalar d r => DualNumber d (Vector r) -> DualNumber d (Vector r) -> DualNumber d (Vector r) conv1 ker@(D u _) vv@(D v _) = let lenK = V.length u lenV = V.length v kerRev = reverse1 ker z = konst1 0 (lenK - 1) vvPadded = append1 z $ append1 vv z in if lenK == 0 then konst1 0 lenV else corr1 kerRev vvPadded -- No padding; remaining areas ignored. maxPool1 :: IsScalar d r => Int -> Int -> DualNumber d (Vector r) -> DualNumber d (Vector r) maxPool1 ksize stride v@(D u _) = let slices = [slice1 i ksize v | i <- [0, stride .. V.length u - ksize]] in seq1 $ V.fromList $ map maximum0 slices softMaxActV :: DualMonad d r m => DualNumber d (Vector r) -> m (DualNumber d (Vector r)) softMaxActV d@(D u _) = do expU <- returnLet $ exp d let sumExpU = sumElements0 expU -- This has to be let-bound, because it's used many times below. recipSum <- returnLet $ recip sumExpU returnLet $ konst1 recipSum (V.length u) * expU -- Note that this is equivalent to a composition of softMax and cross entropy -- only when @target@ is one-hot. Otherwise, results vary wildly. In our -- rendering of the MNIST data all labels are one-hot. lossSoftMaxCrossEntropyL :: DualMonad d r m => Matrix r -> DualNumber d (Matrix r) -> m (DualNumber d (Vector r)) lossSoftMaxCrossEntropyL target (D u u') = do let expU = exp (u - HM.scalar (HM.maxElement u)) -- vs exploding gradients sumExpU = V.fromList $ map HM.sumElements $ HM.toColumns expU recipSum = recip sumExpU softMaxU = HM.asRow recipSum * expU -- this @asRow@ is safe; multiplied at once scaled = D (negate $ log softMaxU * target) (dScale (softMaxU - target) u') returnLet $ sumColumns1 scaled -- * Operations resulting in a matrix -- @2@ means rank two, so the dual component represents a matrix. fromRows2 :: IsScalar d r => Data.Vector.Vector (DualNumber d (Vector r)) -> DualNumber d (Matrix r) fromRows2 v = D (HM.fromRows $ map (\(D u _) -> u) $ V.toList v) (dFromRows2 $ V.map (\(D _ u') -> u') v) fromColumns2 :: IsScalar d r => Data.Vector.Vector (DualNumber d (Vector r)) -> DualNumber d (Matrix r) fromColumns2 v = D (HM.fromRows $ map (\(D u _) -> u) $ V.toList v) (dFromColumns2 $ V.map (\(D _ u') -> u') v) konst2 :: IsScalar d r => DualNumber d r -> (Int, Int) -> DualNumber d (Matrix r) konst2 (D u u') sz = D (HM.konst u sz) (dKonst2 u' sz) transpose2 :: IsScalar d r => DualNumber d (Matrix r) -> DualNumber d (Matrix r) transpose2 (D u u') = D (HM.tr' u) (dTranspose2 u') -- | Dense matrix-matrix product. -- -- If @u@ is a m x n (number of rows x number of columns) matrix -- and @v@ is a n x p matrix then the result of @u <>! v@ is a m x p matrix. infixr 8 <>! (<>!) :: IsScalar d r => DualNumber d (Matrix r) -> DualNumber d (Matrix r) -> DualNumber d (Matrix r) (<>!) (D u u') (D v v') = D (u HM.<> v) (dAdd (dMD_M2 u' v) (dM_MD2 u v')) -- | Dense matrix-matrix product with a constant matrix. infixr 8 <>!! (<>!!) :: IsScalar d r => DualNumber d (Matrix r) -> Matrix r -> DualNumber d (Matrix r) (<>!!) (D u u') v = D (u HM.<> v) (dMD_M2 u' v) rowAppend2 :: IsScalar d r => DualNumber d (Matrix r) -> DualNumber d (Matrix r) -> DualNumber d (Matrix r) rowAppend2 (D u u') (D v v') = D (u HM.=== v) (dRowAppend2 u' (HM.rows u) v') columnAppend2 :: IsScalar d r => DualNumber d (Matrix r) -> DualNumber d (Matrix r) -> DualNumber d (Matrix r) columnAppend2 (D u u') (D v v') = D (u HM.||| v) (dColumnAppend2 u' (HM.cols u) v') rowSlice2 :: IsScalar d r => Int -> Int -> DualNumber d (Matrix r) -> DualNumber d (Matrix r) rowSlice2 i n (D u u') = D (HM.subMatrix (i, 0) (n, HM.cols u) u) (dRowSlice2 i n u' (HM.rows u)) columnSlice2 :: IsScalar d r => Int -> Int -> DualNumber d (Matrix r) -> DualNumber d (Matrix r) columnSlice2 i n (D u u') = D (HM.subMatrix (0, i) (HM.rows u, n) u) (dColumnSlice2 i n u' (HM.rows u)) asRow2 :: IsScalar d r => DualNumber d (Vector r) -> Int -> DualNumber d (Matrix r) asRow2 (D u u') n = D (HM.fromRows $ replicate n u) (dAsRow2 u') asColumn2 :: IsScalar d r => DualNumber d (Vector r) -> Int -> DualNumber d (Matrix r) asColumn2 (D u u') n = D (HM.fromColumns $ replicate n u) (dAsColumn2 u') fromX2 :: IsScalar d r => DualNumber d (OT.Array r) -> DualNumber d (Matrix r) fromX2 (D u u') = case OT.shapeL u of [_, cols] -> D (HM.reshape cols $ OT.toVector u) (dFromX2 u') dims -> error $ "fromX2: the tensor has wrong dimensions " ++ show dims fromS2 :: forall rows cols d r. (KnownNat rows, KnownNat cols, IsScalar d r) => DualNumber d (OS.Array '[rows, cols] r) -> DualNumber d (Matrix r) fromS2 (D u u') = D (HM.reshape (valueOf @cols) $ OS.toVector u) (dFromS2 u') flipud2 :: IsScalar d r => DualNumber d (Matrix r) -> DualNumber d (Matrix r) flipud2 (D u u') = D (HM.flipud u) (dFlipud2 u') fliprl2 :: IsScalar d r => DualNumber d (Matrix r) -> DualNumber d (Matrix r) fliprl2 (D u u') = D (HM.fliprl u) (dFliprl2 u') vectorSlices2 :: IsScalar d r => Int -> DualNumber d (Vector r) -> DualNumber d (Matrix r) vectorSlices2 n vv@(D v _) = fromRows2 $ V.fromList [slice1 i n vv | i <- [0 .. V.length v - n]] reshape2 :: IsScalar d r => Int -> DualNumber d (Vector r) -> DualNumber d (Matrix r) reshape2 cols (D u u') = D (HM.reshape cols u) (dReshape2 cols u') -- TODO: This has list of matrices result instead of a cube tensor. matrixSlices2 :: DualMonad d r m => Int -> DualNumber d (Matrix r) -> m [DualNumber d (Matrix r)] matrixSlices2 dr m@(D u _) = do let (rows, cols) = HM.size u n = dr * cols v <- returnLet $ flatten1 m -- used many times below let f k = returnLet $ reshape2 cols $ slice1 (k * cols) n v mapM f [0 .. rows - dr] -- Not optimal: matrix is constructed and destructed immediately, -- which is costly when evaluating delta expressions. The transposes -- may not be optimal, either. This goes down to individual deltas -- of scalars, which is horrible for performance. Unlike @corr1@ -- this uses the slow dot product instead of the fast matrix-vector -- (or matrix-matrix) multiplication. corr2 :: forall d r m. DualMonad d r m => DualNumber d (Matrix r) -> DualNumber d (Matrix r) -> m (DualNumber d (Matrix r)) corr2 ker@(D u _) m@(D v _) = do let (rowsK, colsK) = HM.size u (rowsM, colsM) = HM.size v rr = rowsM - rowsK + 1 rc = colsM - colsK + 1 if | rowsK <= 0 || colsK <= 0 -> error $ "corr2: empty kernel not handled: " ++ show (rowsK, colsK) | rr <= 0 || rc <= 0 -> error $ "corr2: dim kernel " ++ show (rowsK, colsK) ++ " > dim matrix " ++ show (rowsM, colsM) | otherwise -> do kerTransV <- returnLet $ flatten1 (transpose2 ker) let dotColSlices :: DualNumber d (Matrix r) -> m [DualNumber d r] dotColSlices tm = do ttm <- returnLet $ transpose2 tm colSlices <- matrixSlices2 colsK ttm let f :: DualNumber d (Matrix r) -> DualNumber d r f sm = kerTransV <.>! flatten1 sm return $ map f colSlices rowSlices <- matrixSlices2 rowsK m dotSlicesOfSlices <- mapM dotColSlices rowSlices returnLet $ reshape2 rc $ seq1 $ V.fromList $ concat dotSlicesOfSlices conv2 :: forall d r m. DualMonad d r m => DualNumber d (Matrix r) -> DualNumber d (Matrix r) -> m (DualNumber d (Matrix r)) conv2 ker@(D u _) m@(D v _) = do let (rowsK, colsK) = HM.size u (rowsM, colsM) = HM.size v if | rowsK <= 0 || colsK <= 0 -> returnLet $ konst2 0 (rowsM + rowsK - 1, colsM + colsK - 1) | otherwise -> do let zRow = konst2 0 (rowsK - 1, colsM) rowPadded = rowAppend2 zRow $ rowAppend2 m zRow zCol = konst2 0 (rowsM + 2 * (rowsK - 1), colsK - 1) padded = columnAppend2 zCol $ columnAppend2 rowPadded zCol corr2 (fliprl2 . flipud2 $ ker) padded conv2' :: IsScalar d r => DualNumber d (Matrix r) -> DualNumber d (Matrix r) -> DualNumber d (Matrix r) conv2' (D u u') (D v v') = D (HM.conv2 u v) (dAdd (dConv2 u v') (dConv2 v u')) -- A variant with limited padding, corresponding to SAME padding -- from Tensorflow. Data size does not change with this padding. -- It also performs convolution wrt flipped kernel (and so saves -- on flipping it here), which makes no practical difference when -- the kernel is initialized randomly. convSame2 :: forall d r m. DualMonad d r m => DualNumber d (Matrix r) -> DualNumber d (Matrix r) -> m (DualNumber d (Matrix r)) convSame2 ker@(D u _) m@(D v _) = do let (rowsK, colsK) = HM.size u (rowsM, colsM) = HM.size v if | rowsK <= 0 || colsK <= 0 -> returnLet $ konst2 0 (rowsM, colsM) | otherwise -> do let zRow = konst2 0 ((rowsK - 1) `div` 2, colsM) rowPadded = rowAppend2 zRow $ rowAppend2 m zRow zCol = konst2 0 (rowsM + rowsK - 1, (colsK - 1) `div` 2) padded = columnAppend2 zCol $ columnAppend2 rowPadded zCol corr2 ker padded -- No padding; remaining areas ignored. maxPool2 :: forall d r m. DualMonad d r m => Int -> Int -> DualNumber d (Matrix r) -> m (DualNumber d (Matrix r)) maxPool2 ksize stride m@(D u _) = do let (rows, cols) = HM.size u colsOut = cols `div` stride resultRows = [0, stride .. rows - ksize] resultCols = [0, stride .. cols - ksize] resultCoords = [(r, c) | r <- resultRows, c <- resultCols] v <- returnLet $ flatten1 m -- used many times below let getArea :: (Int, Int) -> DualNumber d (Vector r) getArea (r0, c0) = let getAreaAtRow r1 = append1 (slice1 (r1 * cols + c0) ksize v) in foldr getAreaAtRow (seq1 V.empty) [r0 .. r0 + ksize - 1] mins = map (maximum0 . getArea) resultCoords returnLet $ reshape2 colsOut $ seq1 $ V.fromList mins -- * Operations resulting in an arbitrary untyped tensor konstX :: IsScalar d r => DualNumber d r -> OT.ShapeL -> DualNumber d (OT.Array r) konstX (D u u') sh = D (OT.constant sh u) (dKonstX u' sh) appendX :: IsScalar d r => DualNumber d (OT.Array r) -> DualNumber d (OT.Array r) -> DualNumber d (OT.Array r) appendX (D u u') (D v v') = D (u `OT.append` v) (dAppendX u' (head $ OT.shapeL u) v') sliceX :: IsScalar d r => Int -> Int -> DualNumber d (OT.Array r) -> DualNumber d (OT.Array r) sliceX i n (D u u') = D (OT.slice [(i, n)] u) (dSliceX i n u' (head $ OT.shapeL u)) indexX :: IsScalar d r => DualNumber d (OT.Array r) -> Int -> DualNumber d (OT.Array r) indexX (D u u') ix = D (OT.index u ix) (dIndexX u' ix (head $ OT.shapeL u)) ravelFromListX :: IsScalar d r => [DualNumber d (OT.Array r)] -> DualNumber d (OT.Array r) ravelFromListX ld = let (lu, lu') = unzip $ map (\(D u u') -> (u, u')) ld sh = case lu of u : _ -> length lu : OT.shapeL u [] -> [] in D (OT.ravel $ OTB.fromList sh lu) (dRavelFromListX lu') unravelToListX :: IsScalar d r => DualNumber d (OT.Array r) -> [DualNumber d (OT.Array r)] unravelToListX (D v v') = case OT.shapeL v of k : _ -> let g ix p = D p (dIndexX v' ix k) in imap g $ OTB.toList $ OT.unravel v [] -> error "unravelToListX: wrong tensor dimensions" -- catch early mapX :: IsScalar d r => (DualNumber d (OT.Array r) -> DualNumber d (OT.Array r)) -> DualNumber d (OT.Array r) -> DualNumber d (OT.Array r) mapX f = ravelFromListX . map f . unravelToListX zipWithX :: IsScalar d r => (DualNumber d (OT.Array r) -> DualNumber d (OT.Array r) -> DualNumber d (OT.Array r)) -> DualNumber d (OT.Array r) -> DualNumber d (OT.Array r) -> DualNumber d (OT.Array r) zipWithX f d e = ravelFromListX $ zipWith f (unravelToListX d) (unravelToListX e) reshapeX :: IsScalar d r => OT.ShapeL -> DualNumber d (OT.Array r) -> DualNumber d (OT.Array r) reshapeX sh' (D u u') = D (OT.reshape sh' u) (dReshapeX (OT.shapeL u) sh' u') from0X :: IsScalar d r => DualNumber d r -> DualNumber d (OT.Array r) from0X (D u u') = D (OT.scalar u) (dFrom0X u') from1X :: IsScalar d r => DualNumber d (Vector r) -> DualNumber d (OT.Array r) from1X (D u u') = D (OT.fromVector [V.length u] u) (dFrom1X u') from2X :: IsScalar d r => DualNumber d (Matrix r) -> DualNumber d (OT.Array r) from2X (D u u') = D (OT.fromVector [HM.rows u, HM.cols u] $ HM.flatten u) (dFrom2X u' (HM.cols u)) fromSX :: forall sh d r. (IsScalar d r, OS.Shape sh) => DualNumber d (OS.Array sh r) -> DualNumber d (OT.Array r) fromSX (D u u') = D (Data.Array.Convert.convert u) (dFromSX u') -- * Operations resulting in an arbitrary fully typed Shaped tensor konstS :: (IsScalar d r, OS.Shape sh) => DualNumber d r -> DualNumber d (OS.Array sh r) konstS (D u u') = D (OS.constant u) (dKonstS u') appendS :: (KnownNat m, KnownNat n, IsScalar d r, OS.Shape sh) => DualNumber d (OS.Array (m ': sh) r) -> DualNumber d (OS.Array (n ': sh) r) -> DualNumber d (OS.Array ((m + n) ': sh) r) appendS (D u u') (D v v') = D (u `OS.append` v) (dAppendS u' v') sliceS :: forall i n k rest d r. (KnownNat i, KnownNat n, KnownNat k, IsScalar d r, OS.Shape rest) => DualNumber d (OS.Array (i + n + k ': rest) r) -> DualNumber d (OS.Array (n ': rest) r) sliceS (D u u') = D (OS.slice @'[ '(i, n) ] u) (dSliceS (Proxy :: Proxy i) Proxy u') indexS :: forall ix k rest d r. (KnownNat ix, KnownNat k, IsScalar d r, OS.Shape rest) => DualNumber d (OS.Array (ix + 1 + k ': rest) r) -> DualNumber d (OS.Array rest r) indexS (D u u') = D (OS.index u (valueOf @ix)) (dIndexS u' (Proxy :: Proxy ix)) ravelFromListS :: forall rest k d r. (KnownNat k, IsScalar d r, OS.Shape rest) => [DualNumber d (OS.Array rest r)] -> DualNumber d (OS.Array (k : rest) r) ravelFromListS ld = let (lu, lu') = unzip $ map (\(D u u') -> (u, u')) ld in D (OS.ravel $ OSB.fromList lu) (dRavelFromListS lu') unravelToListS :: forall k rest d r. (KnownNat k, IsScalar d r, OS.Shape rest) => DualNumber d (OS.Array (k : rest) r) -> [DualNumber d (OS.Array rest r)] unravelToListS (D v v') = -- @dIndexS@ is rigid, with type-level bound-checking, so we have to switch -- to @dIndexX@ for this function. let g ix p = D p (dFromXS $ dIndexX (dFromSX v') ix (valueOf @k)) in imap g $ OSB.toList $ OS.unravel v mapS :: forall k sh1 sh d r. (KnownNat k, IsScalar d r, OS.Shape sh, OS.Shape sh1) => (DualNumber d (OS.Array sh1 r) -> DualNumber d (OS.Array sh r)) -> DualNumber d (OS.Array (k : sh1) r) -> DualNumber d (OS.Array (k : sh) r) mapS f = ravelFromListS . map f . unravelToListS mapMS :: forall k sh1 sh d r m. (Monad m, KnownNat k, IsScalar d r, OS.Shape sh, OS.Shape sh1) => (DualNumber d (OS.Array sh1 r) -> m (DualNumber d (OS.Array sh r))) -> DualNumber d (OS.Array (k : sh1) r) -> m (DualNumber d (OS.Array (k : sh) r)) mapMS f d = do let ld = unravelToListS d ld2 <- mapM f ld return $! ravelFromListS ld2 zipWithS :: forall k sh1 sh2 sh d r. ( KnownNat k, IsScalar d r, OS.Shape sh, OS.Shape sh1, OS.Shape sh2) => (DualNumber d (OS.Array sh1 r) -> DualNumber d (OS.Array sh2 r) -> DualNumber d (OS.Array sh r)) -> DualNumber d (OS.Array (k : sh1) r) -> DualNumber d (OS.Array (k : sh2) r) -> DualNumber d (OS.Array (k : sh) r) zipWithS f d e = ravelFromListS $ zipWith f (unravelToListS d) (unravelToListS e) reshapeS :: (IsScalar d r, OS.Shape sh, OS.Shape sh', OS.Size sh ~ OS.Size sh') => DualNumber d (OS.Array sh r) -> DualNumber d (OS.Array sh' r) reshapeS (D u u') = D (OS.reshape u) (dReshapeS u') -- TODO: generalize as broadcast or stretch asRowS :: forall k n d r. (IsScalar d r, KnownNat k, KnownNat n) => DualNumber d (OS.Array '[k] r) -> DualNumber d (OS.Array '[n, k] r) asRowS d = from2S $ asRow2 (fromS1 d) (valueOf @n) asColumnS :: forall k n d r. (IsScalar d r, KnownNat k, KnownNat n) => DualNumber d (OS.Array '[k] r) -> DualNumber d (OS.Array '[k, n] r) asColumnS d = from2S $ asColumn2 (fromS1 d) (valueOf @n) from0S :: IsScalar d r => DualNumber d r -> DualNumber d (OS.Array '[] r) from0S (D u u') = D (OS.scalar u) (dFrom0S u') from1S :: (KnownNat n, IsScalar d r) => DualNumber d (Vector r) -> DualNumber d (OS.Array '[n] r) from1S (D u u') = D (OS.fromVector u) (dFrom1S u') from2S :: (KnownNat rows, KnownNat cols, IsScalar d r) => DualNumber d (Matrix r) -> DualNumber d (OS.Array '[rows, cols] r) from2S (D u u') = D (OS.fromVector $ HM.flatten u) (dFrom2S Proxy u') fromXS :: (IsScalar d r, OS.Shape sh) => DualNumber d (OT.Array r) -> DualNumber d (OS.Array sh r) fromXS (D u u') = D (Data.Array.Convert.convert u) (dFromXS u') -- TODO: generalize to arbitrary permutations of arbitrarily many ranks using https://hackage.haskell.org/package/orthotope/docs/Data-Array-ShapedS.html#v:transpose transpose2S :: (IsScalar d r, KnownNat rows, KnownNat cols) => DualNumber d (OS.Array '[rows, cols] r) -> DualNumber d (OS.Array '[cols, rows] r) transpose2S = from2S . transpose2 . fromS2 infixr 8 #>$ (#>$) :: (IsScalar d r, KnownNat rows, KnownNat cols) => DualNumber d (OS.Array '[rows, cols] r) -> DualNumber d (OS.Array '[cols] r) -> DualNumber d (OS.Array '[rows] r) (#>$) d e = from1S $ fromS2 d #>! fromS1 e infixr 8 <>$ (<>$) :: (IsScalar d r, KnownNat m, KnownNat n, KnownNat p) => DualNumber d (OS.Array '[m, n] r) -> DualNumber d (OS.Array '[n, p] r) -> DualNumber d (OS.Array '[m, p] r) (<>$) d e = from2S $ fromS2 d <>! fromS2 e conv2S :: forall d r kheight_minus_1 kwidth_minus_1 in_height in_width. ( KnownNat kheight_minus_1, KnownNat kwidth_minus_1 , KnownNat in_height, KnownNat in_width , IsScalar d r ) => DualNumber d (OS.Array '[kheight_minus_1 + 1, kwidth_minus_1 + 1] r) -> DualNumber d (OS.Array '[in_height, in_width] r) -> DualNumber d (OS.Array '[ in_height + kheight_minus_1 , in_width + kwidth_minus_1 ] r) conv2S ker x = from2S $ conv2' (fromS2 ker) (fromS2 x) -- Convolution of many matrices at once. Some of the names of dimensions -- are from https://www.tensorflow.org/api_docs/python/tf/nn/conv2d conv24 :: forall kheight_minus_1 kwidth_minus_1 out_channels in_height in_width batch_size in_channels d r. ( KnownNat kheight_minus_1, KnownNat kwidth_minus_1 , KnownNat out_channels, KnownNat in_height, KnownNat in_width , KnownNat batch_size, KnownNat in_channels , IsScalar d r ) => DualNumber d (OS.Array '[ out_channels, in_channels , kheight_minus_1 + 1, kwidth_minus_1 + 1 ] r) -> DualNumber d (OS.Array '[batch_size, in_channels, in_height, in_width] r) -> DualNumber d (OS.Array '[ batch_size, out_channels , in_height + kheight_minus_1 , in_width + kwidth_minus_1 ] r) conv24 ker = mapS conv23 where conv23 :: DualNumber d (OS.Array '[in_channels, in_height, in_width] r) -> DualNumber d (OS.Array '[ out_channels , in_height + kheight_minus_1 , in_width + kwidth_minus_1 ] r) conv23 x = mapS (convFilters x) ker convFilters :: DualNumber d (OS.Array '[in_channels, in_height, in_width] r) -> DualNumber d (OS.Array '[ in_channels , kheight_minus_1 + 1, kwidth_minus_1 + 1 ] r) -> DualNumber d (OS.Array '[ in_height + kheight_minus_1 , in_width + kwidth_minus_1 ] r) convFilters x ker1 = sumOutermost $ zipWithS conv2S ker1 x sumOutermost :: DualNumber d (OS.Array '[ in_channels , in_height + kheight_minus_1 , in_width + kwidth_minus_1 ] r) -> DualNumber d (OS.Array '[ in_height + kheight_minus_1 , in_width + kwidth_minus_1 ] r) sumOutermost = sum . unravelToListS -- slow; should go through Tensor2, or the Num instance should when possible maxPool24 :: forall ksize_minus_1 stride in_height in_width batch_size channels d r m. ( KnownNat ksize_minus_1, KnownNat stride , KnownNat in_height, KnownNat in_width , KnownNat batch_size, KnownNat channels , 1 <= stride , ksize_minus_1 <= in_height , ksize_minus_1 <= in_width , 1 <= in_height - ksize_minus_1 + stride , 1 <= in_width - ksize_minus_1 + stride , DualMonad d r m ) => DualNumber d (OS.Array '[batch_size, channels, in_height, in_width] r) -> m (DualNumber d (OS.Array '[ batch_size, channels , (in_height - ksize_minus_1) `DivRoundUp` stride , (in_width - ksize_minus_1) `DivRoundUp` stride ] r)) maxPool24 d = do res <- mapMS (mapMS (fmap from2S . maxPool2 (valueOf @ksize_minus_1 + 1) (valueOf @stride) . fromS2)) d returnLet res -- * Operations creating delayed/outlined derivatives -- | The version of the @D@ constructor lazy in the second argument. -- To be used as in -- -- > sinDelayed :: (Floating a, IsPrimal d a) => DualNumber d a -> DualNumber d a -- > sinDelayed (D u u') = delayD (sin u) (dScale (cos u) u') -- > -- > plusDelayed :: (Floating a, IsPrimal d a) -- > => DualNumber d a -> DualNumber d a -> DualNumber d a -- > plusDelayed (D u u') (D v v') = delayD (u + v) (dAdd u' v') -- > -- > x ** (sinDelayed x `plusDelayed` (id2 $ id2 $ id2 $ konst1 (sumElements0 x) 2)) -- -- The outlining is lost when serializing or logging, unlike with @Out@, -- @Outline0@, etc. -- -- Yet another incomparable variant that can't be serialized would be -- (illustrating with an example of a constructor at rank 0) -- -- > FromParams0 (Domains -> Delta0 r) -- -- that expects the initial parameters. But it's more troublesome -- than @Delay0@ both in implementation and usage. delayD :: IsPrimal d a => a -> Dual d a -> DualNumber d a delayD u ~u' = D u (dDelay u') -- | A wrapper type to delay/outline computation of the derivatives of the given -- primitive numeric function inside the dual component of the created dual -- number. The rule is that if all arguments of a function are wrapped -- in @Out@ then the function gets delayed. Inconsistent wrapping, -- e.g., only one of the arguments, leads to early type errors. -- -- To be used as in -- -- > x ** unOut (sin (Out x) + Out (id $ id $ id $ konst1 (sumElements0 x) 2)) -- -- which delays computing the dual component of sine and of addition -- (both in rank 1), but not of power, konst and sumElements. The last two -- can't be currently delayed, because only primitive numeric functions -- are supported (an attempt would not type-check). newtype Out a = Out {unOut :: a} deriving (Eq, Ord) returnOut :: (DualMonad d r m, IsPrimalWithScalar d a r) => Out (DualNumber d a) -> m (Out (DualNumber d a)) returnOut dOut = do dvar <- returnLet $ unOut dOut return $ Out dvar instance (Num a, IsPrimal 'DModeGradient a, HasVariables a) => Num (Out (DualNumber 'DModeGradient a)) where Out (D u u') + Out (D v v') = Out $ D (u + v) (dOutline PlusOut [u, v] [u', v']) Out (D u u') - Out (D v v') = Out $ D (u - v) (dOutline MinusOut [u, v] [u', v']) Out (D u u') * Out (D v v') = Out $ D (u * v) (dOutline TimesOut [u, v] [u', v']) negate (Out (D v v')) = Out $ D (negate v) (dOutline NegateOut [v] [v']) abs (Out (D v v')) = Out $ D (abs v) (dOutline AbsOut [v] [v']) signum (Out (D v v')) = Out $ D (signum v) (dOutline SignumOut [v] [v']) fromInteger = Out . constant . fromInteger instance (Real a, IsPrimal 'DModeGradient a, HasVariables a) => Real (Out (DualNumber 'DModeGradient a)) where toRational = undefined -- TODO? instance (Fractional a, IsPrimal 'DModeGradient a, HasVariables a) => Fractional (Out (DualNumber 'DModeGradient a)) where Out (D u u') / Out (D v v') = Out $ D (u / v) (dOutline DivideOut [u, v] [u', v']) recip (Out (D v v')) = Out $ D (recip v) (dOutline RecipOut [v] [v']) fromRational = Out . constant . fromRational instance (Floating a, IsPrimal 'DModeGradient a, HasVariables a) => Floating (Out (DualNumber 'DModeGradient a)) where pi = Out $ constant pi exp (Out (D u u')) = Out $ D (exp u) (dOutline ExpOut [u] [u']) log (Out (D u u')) = Out $ D (log u) (dOutline LogOut [u] [u']) sqrt (Out (D u u')) = Out $ D (sqrt u) (dOutline SqrtOut [u] [u']) Out (D u u') ** Out (D v v') = Out $ D (u ** v) (dOutline PowerOut [u, v] [u', v']) logBase (Out (D u u')) (Out (D v v')) = Out $ D (logBase u v) (dOutline LogBaseOut [u, v] [u', v']) sin (Out (D u u')) = Out $ D (sin u) (dOutline SinOut [u] [u']) cos (Out (D u u')) = Out $ D (cos u) (dOutline CosOut [u] [u']) tan (Out (D u u')) = Out $ D (tan u) (dOutline TanOut [u] [u']) asin (Out (D u u')) = Out $ D (asin u) (dOutline AsinOut [u] [u']) acos (Out (D u u')) = Out $ D (acos u) (dOutline AcosOut [u] [u']) atan (Out (D u u')) = Out $ D (atan u) (dOutline AtanOut [u] [u']) sinh (Out (D u u')) = Out $ D (sinh u) (dOutline SinhOut [u] [u']) cosh (Out (D u u')) = Out $ D (cosh u) (dOutline CoshOut [u] [u']) tanh (Out (D u u')) = Out $ D (tanh u) (dOutline TanhOut [u] [u']) asinh (Out (D u u')) = Out $ D (asinh u) (dOutline AsinhOut [u] [u']) acosh (Out (D u u')) = Out $ D (acosh u) (dOutline AcoshOut [u] [u']) atanh (Out (D u u')) = Out $ D (atanh u) (dOutline AtanhOut [u] [u']) instance (RealFrac a, IsPrimal 'DModeGradient a, HasVariables a) => RealFrac (Out (DualNumber 'DModeGradient a)) where properFraction = undefined -- very low priority, since these are all extremely not continuous instance (RealFloat a, IsPrimal 'DModeGradient a, HasVariables a) => RealFloat (Out (DualNumber 'DModeGradient a)) where atan2 (Out (D u u')) (Out (D v v')) = Out $ D (atan2 u v) (dOutline Atan2Out [u, v] [u', v']) -- we can be selective here and omit the other methods, -- most of which don't even have a differentiable codomain -- * Busywork to let the derivatives mode ignore all outlining -- | Note that this should apply only when @d@ is @'DModeDerivative@. -- However, GHC can't tell that @d@ has only two cases. Therefore, we need -- to overgeneralize these definitions and mark them with @OVERLAPPABLE@ -- or else GHC complains that not enough instances are given -- whenever type-checking code polymorphic on @d@. instance {-# OVERLAPPABLE #-} (Num a, IsPrimal d a) => Num (Out (DualNumber d a)) where Out d + Out e = Out (d + e) Out d - Out e = Out (d - e) Out d * Out e = Out (d * e) negate (Out e) = Out (negate e) abs (Out e) = Out (abs e) signum (Out e) = Out (signum e) fromInteger = Out . constant . fromInteger instance {-# OVERLAPPABLE #-} (Real a, IsPrimal d a) => Real (Out (DualNumber d a)) where toRational = undefined -- TODO? instance {-# OVERLAPPABLE #-} (Fractional a, IsPrimal d a) => Fractional (Out (DualNumber d a)) where Out d / Out e = Out (d / e) recip (Out e) = Out (recip e) fromRational = Out . constant . fromRational instance {-# OVERLAPPABLE #-} (Floating a, IsPrimal d a) => Floating (Out (DualNumber d a)) where pi = Out $ constant pi exp (Out d) = Out (exp d) log (Out d) = Out (log d) sqrt (Out d) = Out (sqrt d) Out d ** Out e = Out (d ** e) logBase (Out x) (Out y) = Out (logBase x y) sin (Out d) = Out (sin d) cos (Out d) = Out (cos d) tan (Out d) = Out (tan d) asin (Out d) = Out (asin d) acos (Out d) = Out (acos d) atan (Out d) = Out (atan d) sinh (Out d) = Out (sinh d) cosh (Out d) = Out (cosh d) tanh (Out d) = Out (tanh d) asinh (Out d) = Out (asinh d) acosh (Out d) = Out (acosh d) atanh (Out d) = Out (atanh d) instance {-# OVERLAPPABLE #-} (RealFrac a, IsPrimal d a) => RealFrac (Out (DualNumber d a)) where properFraction = undefined -- very low priority, since these are all extremely not continuous instance {-# OVERLAPPABLE #-} (RealFloat a, IsPrimal d a) => RealFloat (Out (DualNumber d a)) where atan2 (Out d) (Out e) = Out (atan2 d e)
```python from sympy import * init_printing() ``` # 1. SΓ­mbolos (*Symbols*) Variables de *Python* y *SymPy* ```python a = 'stuff' # variable Python ``` La funciΓ³n `symbols` crea una variable *SymPy* `x` que es asignada a la variable Python `x`. ```python x = symbols('x') x ``` Lo siguiente funciona tambiΓ©n, pero no se recomienda. La variable Python `crazy` se asigna a la variable *Sympy* `unrelated`. Por lo tanto, siempre es una buena idea nombrar sus variables igual que sus sΓ­mbolos. ```python crazy = symbols('unrelated') crazy ``` # 2. Inmutabilidad (*Immutability*) ```python x, y = symbols('x y') a = x + y + 1 a ``` ```python x = 3 ``` ΒΏQuΓ© es "` a` "ahora? ```python a ``` Ahora, ΒΏcΓ³mo puedo sustituir x por 3? ```python ?? ``` ΒΏQuΓ© es "` a` "ahora? ```python a ``` Las expresiones de *SymPy* son inmutables. Nunca cambian en el lugar. Por lo tanto, cada vez que haces `subs`, `simplify`, etc. *SymPy* crea una nueva expresiΓ³n. # 3. Signo de igual Comprobando la desigualdad matemΓ‘tica. ```python x = symbols('x') a = (x + 1)**2 a ``` ```python b = x**2 + 2*x + 1 ``` Ahora, vamos a verificar si `a` y` b` son iguales o no. ΒΏCuΓ‘l crees que serΓ‘ el resultado de lo siguiente? ```python a == b ``` ```python simplify(a - b) ``` Esa es la diferencia entre la igualdad estructural y matemΓ‘tica. #### Representando una igualdad simbΓ³lica, como por ejemplo: $$x^2 = y$$ ```python eq = Eq(x**2, y) ``` ```python eq.lhs ``` ```python eq.rhs ``` ```python solveset(eq, x) ``` # 4. Fracciones ```python acos(1/2) ``` Estamos buscando resultados simbΓ³licos, ΒΏverdad? ```python Rational(1, 2) ``` ```python acos(Rational(1, 2)) ``` ```python from fractions import Fraction Fraction(1, 2) ``` ```python acos(Fraction(1, 2)) ``` ```python type(sympify(Fraction(1, 2))) ``` # 5. Operador LΓ³gico (XOR) ```python x^2 ``` ```python sympify('x^2') ``` Si estΓ‘s haciendo lΓ³gica, y **no** quieres convertir el `XOR` al operador de potencia: ```python sympify('x^2', convert_xor=False) ```
variables x y z : β„€ example (x y z : β„•) : x * (y + z) = x * y + x * z := mul_add x y z example (x y z : β„•) : (x + y) * z = x * z + y * z := add_mul x y z example (x y z : β„•) : x + y + z = x + (y + z) := add_assoc x y z example (x y : β„•) : (x + y) * (x + y) = x * x + y * x + x * y + y * y := have h1 : (x + y) * (x + y) = (x + y) * x + (x + y) * y, from mul_add (x + y) x y, have h2 : (x + y) * (x + y) = x * x + y * x + (x * y + y * y), from add_mul x y x β–Έ add_mul x y y β–Έ h1, h2.trans (add_assoc (x * x + y * x) (x * y) (y * y)).symm
(******************************************************************************) (* Project: The Isabelle/UTP Proof System *) (* File: Positive_New.thy *) (* Authors: Simon Foster and Frank Zeyda *) (* Emails: [email protected] and [email protected] *) (******************************************************************************) (* LAST REVIEWED: 14 Sept 2017 *) section {* Positive Subtypes *} theory Positive_New imports Two Continuum "../axiomatic/theories/utils/Infinity" "~~/src/HOL/Library/Countable" begin text {* Move this instantiation to a more suitable place in the hierarchy. *} subclass (in infinite) two apply (intro_classes) apply (rule disjI1) apply (rule local.infinite_UNIV) done subsection {* Type Definition *} typedef (overloaded) 'a::"{zero, linorder}" pos = "{x::'a. x \<ge> 0}" apply (rule_tac x = "0" in exI) apply (clarsimp) done setup_lifting type_definition_pos subsection {* Instantiations *} instantiation pos :: ("{zero, linorder}") zero begin lift_definition zero_pos :: "'a pos" is "0 :: 'a" .. instance .. end instantiation pos :: ("{zero, linorder}") linorder begin lift_definition less_eq_pos :: "'a pos \<Rightarrow> 'a pos \<Rightarrow> bool" is "op \<le> :: 'a \<Rightarrow> 'a \<Rightarrow> bool" . lift_definition less_pos :: "'a pos \<Rightarrow> 'a pos \<Rightarrow> bool" is "op < :: 'a \<Rightarrow> 'a \<Rightarrow> bool" . instance apply (intro_classes; transfer) apply (auto) done end instance pos :: ("{zero, linorder, no_top}") no_top apply (intro_classes) apply (transfer) apply (clarsimp) apply (meson gt_ex less_imp_le order.strict_trans1) done instance pos :: ("{zero, linorder, no_top}") infinite apply (intro_classes) apply (rule notI) apply (subgoal_tac "\<forall>x::'a pos. x \<le> Max UNIV") using gt_ex leD apply (blast) apply (simp) done (*<*) (* Removed as clashing with the instantiation of @{class continuum}. *) (* instance pos :: ("{zero, linorder, countable}") countable apply (intro_classes) apply (rule_tac x = "to_nat o Rep_pos" in exI) apply (rule inj_comp) apply (clarsimp) apply (rule injI) apply (simp add: Rep_pos_inject) done *) (*>*) instantiation pos :: (linordered_semidom) linordered_semidom begin lift_definition one_pos :: "'a pos" is "1 :: 'a" by (simp) lift_definition plus_pos :: "'a pos \<Rightarrow> 'a pos \<Rightarrow> 'a pos" is "op +" by (simp) lift_definition minus_pos :: "'a pos \<Rightarrow> 'a pos \<Rightarrow> 'a pos" is "\<lambda>x y. if y \<le> x then x - y else 0" by (simp add: add_le_imp_le_diff) lift_definition times_pos :: "'a pos \<Rightarrow> 'a pos \<Rightarrow> 'a pos" is "op *" by (simp) instance apply (intro_classes; transfer; simp?) apply (simp add: add.assoc) apply (simp add: add.commute) apply (safe; clarsimp?) [1] apply (simp add: diff_diff_add) apply (metis add_left_mono le_add_diff_inverse) apply (simp add: add.commute add_le_imp_le_diff) apply (metis add_increasing2 antisym linear) apply (simp add: mult.assoc) apply (simp add: mult.commute) apply (simp add: comm_semiring_class.distrib) apply (simp add: mult_strict_left_mono) apply (safe; clarsimp?) [1] apply (simp add: right_diff_distrib') apply (simp add: mult_left_mono) using mult_left_le_imp_le apply (fastforce) apply (simp add: distrib_left) done end instantiation pos :: ("linordered_field") semidom_divide begin lift_definition divide_pos :: "'a pos \<Rightarrow> 'a pos \<Rightarrow> 'a pos" is "op div" by (simp) instance apply (intro_classes; transfer) apply (simp_all) done end subsection {* Continuum Closure *} lemma ge_num_infinite_if_no_top: "infinite {x::'a::{linorder, no_top}. n \<le> x}" apply (clarsimp) -- {* From the assumption that the set is finite. *} apply (subgoal_tac "\<exists>y::'a. Max {x. n \<le> x} < y") apply (clarsimp) apply (metis Max_ge leD mem_Collect_eq order.strict_implies_order order_refl order_trans) using gt_ex apply (blast) done lemma less_zero_ordLeq_ge_zero: "|{x::'a::{ordered_ab_group_add}. x < 0}| \<le>o |{x::'a. 0 \<le> x}|" apply (rule_tac f = "uminus" in surj_imp_ordLeq) apply (simp add: image_def) apply (clarsimp) apply (rule_tac x = "- x" in exI) apply (simp) done instance pos :: ("{zero, linorder, no_top}") two .. text {* The next theorem is not entirely trivial to prove! *} instance pos :: ("{linordered_ab_group_add, no_top, continuum}") continuum apply (intro_classes) apply (case_tac "countable (UNIV :: 'a set)") -- {* Subgoal 1 (Easy Case) *} apply (rule disjI1) apply (subgoal_tac "\<exists>to_nat::'a \<Rightarrow> nat. inj to_nat") -- {* Subgoal 1.1 *} apply (clarsimp) apply (thin_tac "countable UNIV") apply (rule_tac x = "to_nat o Rep_pos" in exI) apply (rule inj_comp) apply (assumption) apply (meson Positive_New.pos.Rep_pos_inject injI) -- {* Subgoal 1.2 *} apply (blast) -- {* Subgoal 2 (Difficult Case) *} apply (rule disjI2) apply (subst sym [OF equal_card_bij_betw]) apply (rule equal_card_intro) apply (subgoal_tac "|UNIV::'a pos set| =o |{x::'a. 0 \<le> x}|") -- {* Subgoal 2.1 *} apply (erule ordIso_transitive) apply (rule ordIso_symmetric) apply (subgoal_tac "|UNIV::nat set set| =o |UNIV::'a set|") -- {* Subgoal 2.1.1 *} apply (erule ordIso_transitive) apply (subgoal_tac "(UNIV::'a set) = {x.0 \<le> x} \<union> {x. x < 0}") -- {* Subgoal 2.1.1.1 *} apply (erule ssubst) apply (rule card_of_Un_infinite_simps(1)) apply (rule ge_num_infinite_if_no_top) apply (rule less_zero_ordLeq_ge_zero) -- {* Subgoal 2.1.1.2 *} apply (auto) -- {* Subgoal 2.1.2 *} apply (rule_tac f = "from_nat_set" in card_of_ordIsoI) apply (rule_tac bij_betwI'; clarsimp?) -- {* This is the only place where @{term "countable UNIV"} is needed. *} apply (metis bij_betw_imp_surj from_nat_set_def surj_f_inv_f to_nat_set_bij) apply (rule_tac x = "to_nat_set y" in exI) apply (clarsimp) -- {* Subgoal 2.2 *} apply (rule_tac f = "Rep_pos" in card_of_ordIsoI) apply (rule_tac bij_betwI'; clarsimp?) apply (simp add: Positive_New.pos.Rep_pos_inject) using Positive_New.pos.Rep_pos apply (blast) apply (rule_tac x = "Abs_pos y" in exI) apply (simp add: Positive_New.pos.Abs_pos_inverse) done end
(* Title: Atoms Author: Insa Stucke ([email protected]) *) theory Relation_Algebra_Atoms imports "$AFP/Relation_Algebra/Relation_Algebra" "$AFP/Relation_Algebra/Relation_Algebra_Functions" "~~/Relation_Algebra_Cardinalities/Relation_Algebra_Points" begin text{* Facts about atom are outsourced to this file. *} context relation_algebra_fin_points begin definition is_atom:: "'a \<Rightarrow> bool" where "is_atom x \<equiv> x\<noteq>0 \<and> x\<^sup>\<smile>;1;x \<le> 1' \<and> x;1;x\<^sup>\<smile> \<le> 1'" lemma topatoms: "\<Squnion> {p;q\<^sup>\<smile>|p q. is_point p \<and> is_point q} = 1" proof - have "1 = \<Squnion> {p|p. is_point p};(\<Squnion> {q|q. is_point q})\<^sup>\<smile>" using pointaxiom by auto also have "\<dots> = \<Squnion> {p|p. is_point p};(\<Squnion> {q\<^sup>\<smile>|q. is_point q})" using setsum_fun_add' finiteness by auto also have "\<dots> = \<Squnion> {p;q\<^sup>\<smile>|p q. is_point p \<and> is_point q}" using finiteness sum_sum_add_comp by blast finally show ?thesis by simp qed lemma pointssetcomp: "{x. \<exists> p q. p;q\<^sup>\<smile>=x \<and> is_point p \<and> is_point q} = {p;q\<^sup>\<smile>|p q. is_point p \<and> is_point q}" by blast lemma atompoint: assumes "is_atom x" shows "is_point (x;1)" proof - have a: "is_inj (x;1)" by (metis assms is_atom_def conv_contrav conv_one is_inj_def mult_assoc one_idem_mult) have b: "(x;1)\<noteq>0" using assms is_atom_def ss_p18 by auto have c: "is_vector (x;1)" by (simp add: comp_assoc is_vector_def) thus ?thesis by (simp add: a b is_point_def) qed lemma atompointcnv: assumes "is_atom x" shows "is_point (x\<^sup>\<smile>;1)" by (metis assms atompoint is_atom_def conv_invol conv_zero) lemma atompoints: assumes "is_atom x" shows "\<exists> p q. x=p;q\<^sup>\<smile> \<and> is_point p \<and> is_point q" proof - have hp: "is_point (x;1)" using atompoint assms by blast have hq: "is_point (x\<^sup>\<smile>;1)" using atompointcnv assms by blast have "x = (x;1);(x\<^sup>\<smile>;1)\<^sup>\<smile>" proof (rule antisym) show "x \<le> (x;1);(x\<^sup>\<smile>;1)\<^sup>\<smile>" by (metis conv_contrav conv_invol conv_one dedekind inf_top_left one_idem_mult) show "(x;1);(x\<^sup>\<smile>;1)\<^sup>\<smile> \<le> x" by (metis hq conv_invol conv_one dedekind_var_1 inf.absorb2 inf_top_right one_idem_mult point_cnv_map ss423 top_greatest) qed thus ?thesis using hp hq by blast qed lemma pointsatom: assumes "is_point p" and "is_point q" shows "is_atom (p;q\<^sup>\<smile>)" proof (unfold is_atom_def, intro conjI) show "(p;q\<^sup>\<smile>)\<noteq>0" by (simp add: assms comp_points) show "(p;q\<^sup>\<smile>)\<^sup>\<smile>;1;(p;q\<^sup>\<smile>) \<le> 1'" by (metis assms comp_assoc conv_contrav conv_invol is_inj_def is_point_def is_vector_def points_surj surj_tx) show "(p;q\<^sup>\<smile>);1;(p;q\<^sup>\<smile>)\<^sup>\<smile> \<le> 1'" by (metis assms conv_contrav conv_one is_inj_def is_point_def is_vector_def mult_assoc points_surj surj_tx) qed lemma atomeqpoints: "{x|x. is_atom x} = {x. \<exists> p q. p;q\<^sup>\<smile>=x \<and> is_point p \<and> is_point q}" proof (rule subset_antisym[OF subsetI subsetI]) show "\<And>x. x \<in> {x |x. is_atom x} \<Longrightarrow> x \<in> {x. \<exists>p q. p;q\<^sup>\<smile> = x \<and> is_point p \<and> is_point q}" using atompoints by fastforce next show "\<And>x. x \<in> {x. \<exists>p q. p;q\<^sup>\<smile> = x \<and> is_point p \<and> is_point q} \<Longrightarrow> x \<in> {x |x. is_atom x}" proof fix y::'a assume ypoints: "y \<in> {x. \<exists>p q. p;q\<^sup>\<smile> = x \<and> is_point p \<and> is_point q}" show "\<exists>x. y = x \<and> is_atom x" proof obtain p q where h1: "p;q\<^sup>\<smile> = y \<and> is_point p \<and> is_point q" using ypoints by blast have catom: "is_atom (p;q\<^sup>\<smile>)" using h1 pointsatom by blast show "y = y \<and> is_atom y" using catom h1 by blast qed qed qed lemma topatoms': "\<Squnion> {x|x. is_atom x} = 1" using atomeqpoints pointssetcomp topatoms by auto lemma atominj: assumes "is_atom x" shows "is_inj x" by (meson assms is_atom_def conv_galois_2 dual_order.trans is_inj_def maddux_20) lemma atompfun: assumes "is_atom x" shows "is_p_fun x" by (metis assms is_atom_def comp_assoc dual_order.trans is_p_fun_def maddux_21 mult_isol) lemma atomtrans: assumes "is_atom x" shows "is_trans x" proof (unfold is_trans_def) show "x;x \<le> x" proof - have "x;x \<le> x;1 \<cdot> 1;x" by (simp add: mult_isol_var) also have "\<dots> \<le> x;x\<^sup>\<smile>;1;x" by (metis inf_top.left_neutral modular_1_var mult.semigroup_axioms semigroup.assoc) also have "\<dots> \<le> x" using assms is_atom_def comp_assoc mult_isol by fastforce finally show ?thesis using dual_order.trans is_trans_def by blast qed qed lemma atomid: assumes "is_atom x" shows "x;x \<le> 1'" proof - have "x;x \<le> x;x \<cdot> x" using assms atomtrans inf_absorb1 is_trans_def by auto also have "\<dots> \<le> (x \<cdot> x;x\<^sup>\<smile>);(x \<cdot> x\<^sup>\<smile>;x)" using dedekind by blast also have "\<dots> \<le> x;x\<^sup>\<smile>;x\<^sup>\<smile>;x" by (metis comp_assoc inf.cobounded2 mult_isol_var) also have "\<dots> \<le> 1';x\<^sup>\<smile>;x" using assms atominj is_inj_def mult_isor by blast finally show ?thesis by (metis assms atompfun dual_order.trans is_p_fun_def mult_1_left) qed lemma atomdisj: assumes "is_atom x" and "is_atom y" and "x\<noteq>y" shows "x\<cdot>y \<le> 0" proof - obtain p q where h1: "p ; q\<^sup>\<smile> = x \<and> is_point p \<and> is_point q" using assms(1) atompoints by blast obtain r s where h2: "r ; s\<^sup>\<smile> = y \<and> is_point r \<and> is_point s" using assms(2) atompoints by blast have noteq: "p\<noteq>r \<or> q\<noteq>s" using assms(3) h1 h2 by blast have noteq: "p\<^sup>\<smile>;r \<le> 0 \<or> s\<^sup>\<smile>;q \<le> 0" using h1 h2 noteq pointcompbot by blast have "x\<cdot>y = p;q\<^sup>\<smile> \<cdot> r;s\<^sup>\<smile>" by (simp add: h1 h2) also have "\<dots> \<le> (p \<cdot> r;s\<^sup>\<smile>;q);(q\<^sup>\<smile> \<cdot> p\<^sup>\<smile>;r;s\<^sup>\<smile>)" by (metis comp_assoc conv_invol dedekind) also have "(p \<cdot> r;s\<^sup>\<smile>;q);(q\<^sup>\<smile> \<cdot> p\<^sup>\<smile>;r;s\<^sup>\<smile>) \<le> 0" using bot_unique mult_assoc noteq by fastforce finally show ?thesis by simp qed lemma pwd_points: "pairwise_disjoint {x |x.\<exists> p q. p;q\<^sup>\<smile>=x \<and> is_point p \<and> is_point q}" using atomdisj le_bot pointsatom pairwise_disjoint_def by auto lemma pwd_points_eq: "pairwise_disjoint {x |x.\<exists> p. p;p\<^sup>\<smile>=x \<and> is_point p}" proof - have a: "{x |x.\<exists> p. p;p\<^sup>\<smile>=x \<and> is_point p} \<subseteq> {x |x.\<exists> p q. p;q\<^sup>\<smile>=x \<and> is_point p \<and> is_point q}" by blast thus ?thesis using pwd_mon pwd_points by blast qed lemma atomsareatoms: assumes "is_point p" and "is_point q" and "is_point r" and "is_point s" and "p;q\<^sup>\<smile>=r;s\<^sup>\<smile>" shows "p=r \<and> q=s" proof (rule conjI) show "q = s" proof - have a: "p \<le> r;s\<^sup>\<smile>;q" by (metis assms comp_assoc maddux_20 pointcomptop) have b: "r;s\<^sup>\<smile>;q \<noteq> 0" by (metis a assms comp_assoc comp_points le_bot points_surj ss_p18 surj_tx) have c: "s\<^sup>\<smile>;q \<noteq> 0" using b annir comp_assoc by force thus ?thesis using assms c pointcompbot by blast qed next show "p=r" proof - have a: "p;q\<^sup>\<smile>=r;q\<^sup>\<smile>" by (metis assms is_point_def is_vector_def mult.semigroup_axioms points_surj surj_tx semigroup.assoc) thus ?thesis by (metis assms comp_assoc is_point_def is_vector_def pointcomptop) qed qed lemma fin_points: "finite {x |x. \<exists>p q. p;q\<^sup>\<smile> = x \<and> is_point p \<and> is_point q}" proof - have a: "{x |x. \<exists>p q. p;q\<^sup>\<smile> = x \<and> is_point p \<and> is_point q} = {p;q\<^sup>\<smile>|p q. is_point p \<and> is_point q}" by blast have b: " finite {p;q\<^sup>\<smile>|p q. is_point p \<and> is_point q}" by (metis atomeqpoints bot_unique is_atom_def pointssetcomp sum.infinite top_greatest topatoms' not_finite_existsD) thus ?thesis using a by auto qed lemma fin_atoms: "finite {x |x. is_atom x}" proof - have a: "{x |x. is_atom x} = {x |x. \<exists>p q. p;q\<^sup>\<smile> = x \<and> is_point p \<and> is_point q}" using atompoints pointsatom by blast thus ?thesis using a fin_points by auto qed lemma fin_atoms': "finite {x. is_atom x}" using fin_atoms by auto lemma fin_atoms_p: "finite {x |x. is_atom x \<and> P x}" by (simp add: Collect_mono fin_atoms') lemma atom_lattice_atom: assumes "is_atom x" and "y\<noteq>0" and "y \<le> x" shows "y = x" proof (rule univalent_antisym) show "is_p_fun x" by (simp add: assms atompfun) show "x; 1 \<le> y;1" by (metis assms atompoint comp_assoc inf_absorb2 is_vector_def mult_subdistr one_idem_mult point_lattice_atom ss_p18) show "y \<le> x" by (simp add: assms) qed lemma leq_atom_rel: assumes "is_atom x" and "y \<le> x" shows "y=x \<or> y \<le> 0" using assms atom_lattice_atom by fastforce lemma leq_atom_rel': assumes "is_atom x" shows "x \<le> y \<or> x \<cdot> y \<le> 0" by (metis assms leq_atom_rel inf.cobounded1 inf.orderI) lemma atomrel: assumes "is_atom x" shows "y \<cdot> x \<le> \<Squnion> {x|x. is_atom x \<and> x \<le> y}" proof - have a: "x \<le> y \<or> x \<cdot> y \<le> 0" by (simp add: assms leq_atom_rel') then have b: "y \<cdot> x \<le> \<Squnion>{x|x. is_atom x \<and> x \<le> y}" proof assume asm: "x \<cdot> y \<le> 0" show "y \<cdot> x \<le> \<Squnion>{x|x. is_atom x \<and> x \<le> y}" using asm antisym bot_least inf.commute by fastforce next assume asm: "x \<le> y" show "y \<cdot> x \<le> \<Squnion>{x|x. is_atom x \<and> x \<le> y}" proof (rule leq_sum_p) show "finite {x. is_atom x \<and> x \<le> y}" by (simp add: fin_atoms') next show "is_atom (y \<cdot> x) \<and> y \<cdot> x \<le> y" by (simp add: asm assms inf.absorb2) qed qed thus ?thesis by blast qed lemma atomaux: "\<Squnion> {y \<cdot> x|x. is_atom x} \<le> \<Squnion> {x|x. is_atom x \<and> x \<le> y}" proof (rule lub_sum_p) show "finite {x. is_atom x}" by (simp add: fin_atoms') next show "\<forall>x. is_atom x \<longrightarrow> y \<cdot> x \<le> \<Squnion> {x|x. is_atom x \<and> x \<le> y}" using atomrel by auto qed lemma relatoms: "\<Squnion> {x|x. is_atom x \<and> x \<le> y} = y" proof (rule antisym) show "\<Squnion>{x|x. is_atom x \<and> x \<le> y} \<le> y" by (metis (no_types, lifting) bot_least lub_sum sum.infinite mem_Collect_eq) next have "y = y \<cdot> \<Squnion> {x|x. is_atom x}" using topatoms' by auto also have "\<dots> = \<Squnion> {y \<cdot> x|x. is_atom x}" using fin_atoms sum_cap_distr_left by auto also have "\<dots> \<le> \<Squnion> {x|x. is_atom x \<and> x \<le> y}" using atomaux by blast finally show "y \<le> \<Squnion>{x|x. is_atom x \<and> x \<le> y}" using Collect_cong by auto qed definition is_partial_point:: "'a \<Rightarrow> bool" where "is_partial_point x \<equiv> is_atom x \<and> is_test x" lemma sumid_partial_points: "1' = \<Squnion> {x|x. is_partial_point x}" using relatoms is_partial_point_def is_test_def by auto lemma test_partial_points: assumes "is_test y" shows "y = \<Squnion> {x|x. is_partial_point x \<and> x \<le> y}" proof - have a: "{x|x. is_atom x \<and> x \<le> y} = {x|x. is_partial_point x \<and> x \<le> y}" using assms is_partial_point_def dual_order.trans is_test_def by blast thus ?thesis by (metis relatoms) qed lemma fin_partial_points_p: "finite {x |x. is_partial_point x \<and> P x}" using fin_atoms is_partial_point_def by auto lemma fin_partial_points_fun: "finite {f x |x. is_partial_point x \<and> P x}" using finite_image_set fin_partial_points_p by auto end end
\chapter{Command Summary} \label{a:cmdsum} \section{Operational Commands (page~\protect\pageref{sec:oper})}\label{sec:opsum} \cmdsum{\cmd{MASS} \param{nquad}, \optparam{density}\\ \cmd{PROPERTIES} \param{nquad} \optparam{density} } { calculates several mass properties of the body. } \cmdsum{\cmd{LOCATE} \cmd{\{NODES$|$ELEMENTS\}} \param{locate\_option} } { locates \cmd{NODES} or \cmd{ELEMENTS} that are a specified distance from a user-defined point, line, or plane. \begingroup\small \tabcolsep=3pt \begin{tabular}{*{3}{l} *{6}{l} *{2}{l} } LOCATE & NODES$|$ELEMENTS & POINT & $x_0$ & $y_0$ & $z_0$ & & & &distance &toler \\ LOCATE & NODES$|$ELEMENTS & LINE & $x_0$ & $y_0$ & $z_0$ & $x_1$ & $y_1$ & $z_1$ &distance &toler \\ LOCATE & NODES$|$ELEMENTS & PLANE & $x_0$ & $y_0$ & $z_0$ & $i$ & $j$ & $k$ &distance &toler \\ \end{tabular} \endgroup } \cmdsum{\cmd{CAVITY } \param{sset$_{1}$}, \param{sset$_{2}$}, \ldots, \param{sset$_n$}, \optparam{\cmd{CENTER}}, \optparam{xcen}, \optparam{ycen}, \optparam{zcen} } { calculates the volume of a cavity defined by the element sidesets \param{sset$_{1}$} to \param{sset$_n$}. } \cmdsum{\cmd{LIMITS} \optparam{\cmd{ALLTIMES}} } { determines the minimum, maximum, and range of the X, Y, and Z coordinates for each of the selected material blocks. } \cmdsum{\cmd{OVERLAP } \param{flag$_m$}, \param{flag$_s$} } { determines whether any of the nodes on the surface defined by the sideset \param{flag$_s$} penetrate the element faces on the surface defined by the sideset \param{flag$_m$}. } \cmdsum{\cmd{TIMESTEP} \param{wave\_speed} \optparam{damping\_fraction} } { estimates the maximum stable time step for an explicit transient dynamics finite element program. } \cmdsum{\cmd{GAP} \param{flag$_m$}, \param{flag$_s$}, \param{d$_{\max}$}, \optparam{\cmd{DISTANCE$|$NORMAL}} } { calculates the distance between nodes on the surfaces defined by the sideset flags \param{flag$_m$} and \param{flag$_s$}. } \newpage \section{Parameter Setting Commands (page~\protect\pageref{sec:param})} \cmdsum{\cmd{AXISYMMETRIC} } { the two-dimensional body is axisymmetric. } \cmdsum{\cmd{PLANAR} or \cmd{PLANE} } { the two-dimensional body described is planar or plane strain. } \cmdsum{\cmd{EXODUS} \optparam{\cmd{ON$|$OFF}} } { indicates that the operational commands should calculate values based on the undeformed geometry (\cmd{off}), or for every time step (\cmd{on}). } \cmdsum{\cmd{DENSITY } } { prompts the user for the density of each of the element blocks } \cmdsum{\cmd{SORT} \param{sort\_field} \optparam{sort\_order} } { orders the output of a \cmd{LOCATE} command according to \param{sort\_field} and \param{sort\_order}. } \cmdsum{\cmd{SELECT} \param{option} } { selects the materials or material blocks for the operational commands. } \cmdsum{\cmd{SELECT BLOCKS} \optparam{\cmd{ALL},} \param{block\_id$_{1}$}, \param{block\_id$_{2}$}, \ldots\ } { selects the element blocks. } \cmdsum{\cmd{SELECT MATERIALS} \optparam{\cmd{ALL},} \param{material\_id$_{1}$}, \param{material\_id$_{2}$}, \ldots\ } { selects the element blocks with the material number corresponding to \param{material\_id}. } \cmdsum{\cmd{TMIN} \param{tmin} } { sets the minimum selected time to \param{tmin}. } \cmdsum{\cmd{TMAX} \param{tmax} } { sets the maximum selected time to \param{tmax}. } \cmdsum{\cmd{DELTIME} \param{delt} } { sets the selected time interval to \param{delt}. } \cmdsum{\cmd{TIMES} \param{tmin} \cmd{TO} \param{tmax} \cmd{BY} \param{delt} } { sets \param{tmin}, \param{tmax}, and \param{delt} with a single command. } \section{Database Display Commands (page~\protect\pageref{cmd:display})} \cmdsum{\cmd{LIST} \param{option} } { displays the database information specified by \param{option}. \cenlinesbegin \cmd{LIST \{VARS$|$VARIABLES\}}\\ \cmd{LIST \{BLOCKS$|$MATERIALS\}}\\ \cmd{LIST \{NSETS$|$NODESETS\}}\\ \cmd{LIST \{SSETS$|$SIDESETS\}}\\ \cmd{LIST STEPS}\\ \cmd{LIST TIMES}\\ \cenlinesend } \cmdsum{\cmd{HELP} \param{command} } { displays information about a program command. } \section{Miscellaneous Commands (page~\protect\pageref{sec:misc})} \cmdsum{\cmd{ECHO} \optparam{\cmd{ON$|$OFF}} } { controls the output of results to the terminal. } \cmdsum{\cmd{PRINT} \optparam{\cmd{ON$|$OFF}} } { controls the output of results to the output file. } \cmdsum{\cmd{COMMENT } \optparam{\cmd{PAGE},} \param{ncom} } { prompts the user for \param{ncom} comment lines which are written to the output file. } \cmdsum{\cmd{EXIT } } { exits the program and closes all files. }
\documentclass{article} \usepackage[utf8]{inputenc} \usepackage{mathtools} % Required for display matrices. Extension on top of amsmath package. \usepackage{bm} % for rendering vectors correctly \usepackage{xcolor} \usepackage{amssymb} % for rendering dimension symbol R \usepackage[nocfg,notintoc]{nomencl} \makenomenclature \usepackage{booktabs} %\renewcommand{\arraystretch}{2.0} % affects matrices too. \usepackage[letterpaper, hmargin=0.8in]{geometry} \usepackage{fancyhdr} \pagestyle{fancy} % with this we ensure that the chapter and section % headings are in lowercase. %\renewcommand{\chaptermark}[1]{\markboth{#1}{}} \renewcommand{\sectionmark}[1]{% \markright{\thesection\ #1}} \fancyhf{} % delete current header and footer \fancyhead[L,R]{\bfseries\thepage} \fancyhead[LO]{\bfseries\rightmark} %\fancyhead[RE]{\bfseries\leftmark} \renewcommand{\headrulewidth}{0.5pt} \renewcommand{\footrulewidth}{0pt} \addtolength{\headheight}{0.5pt} % space for the rule \fancypagestyle{plain}{% \fancyhead{} % get rid of headers on plain pages \renewcommand{\headrulewidth}{0pt} % and the line } \usepackage{biblatex} \addbibresource{BackPropagationBasicMatrixOperations.bib} % hyperref package doesn't seem to be working. \renewcommand{\nomname}{} % We don't to use any word here. \newcommand{\transpose}[1]{#1^\top} \newcommand{\vecr}[1]{\bm{#1}} \newcommand{\matr}[1]{\mathbf{#1}} % undergraduate algebra version %\newcommand{\matr}[1]{#1} % pure math version %\newcommand{\matr}[1]{\bm{#1}} % ISO complying version \newcommand{\eqncomment}[1]{ \footnotesize \textcolor{gray}{ \begin{pmatrix*}[l] \text{#1} \end{pmatrix*} }} \newcommand{\longeqncomment}[2] {\footnotesize \textcolor{gray}{ \begin{pmatrix*}[l] \text{#1} \\ \text{#2} \end{pmatrix*} }} \title{CS231N: Backpropagation - Vector and Matrix Calculus} \author{ Ashish Jain \\ Stanford University \\ \texttt{[email protected]/[email protected]} } \date{\today} \begin{document} \pagestyle{empty} \maketitle \tableofcontents \newpage \pagestyle{fancy} \section{Introduction} \subsection{Intended Audience} This document is primarily targeted towards CS231N students who don't have a formal background in vector and matrix calculus. \subsection{Learning Goals} CS231N assignments have a heavy emphasis on vector and matrix calculus. Several different notation and layout conventions are popular in the literature which can be confusing and overwhelming for students just starting out with vector and matrix calculus. This document firmly aligns and sticks with the layout conventions for matrix calculus taught in CS231N lectures \cite{li_krishna_xu_2021}. This document hopes to bring the students who lack a formal background in vector and matrix calculus up to speed as well as serve as a reference while solving the various assignments. \subsection{Content} Through small non-trivial examples, we show how and why certain backpropagation operations reduce to the equations they reduce to for basic operations such as matrix multiplication, some element-wise operation on a matrix, element-wise operations between two matrices, reductions of a matrix to a vector and broadcasting of a vector to a matrix. The example matrices and vectors are deliberately kept small to ensure one can convince oneself or alternately verify on paper if the contents of this document are correct (please feel free to submit bugs or corrections). The examples considered while small are kept as general as possible throughout the derivations. Therefore, a motivated student can easily extend these examples to general proofs. Each section from section \ref{Matrix Multiplication} onward is written independently of each other, and therefore, you can directly jump to a section of your interest. \section{Nomenclature} \vspace{-2.5em} \nomenclature[N]{\(\vecr{x}\)}{Row or column vector} \nomenclature[N]{\(\matr{X}\)}{Two dimensional matrix} \nomenclature[N]{\(L\)}{Loss/Cost scalar} \nomenclature[N]{\(\mathbb{R}\)}{Real numbers} \nomenclature[O]{\(\mathrm{d}\text{Variable}\)}{$\frac{\partial L}{\partial \text{Variable}}$} \printnomenclature \section{Layout Convention} Given a vector $\vecr{y}$ where $\bm{y} \in \mathbb{R}^{m}$ and a vector $\bm{x}$ where $\bm{x} \in \mathbb{R}^{n}$, we are going to follow the \textbf{denominator layout} convention whereby $\frac{\partial y}{\partial x}$ is written as $n \times m$ matrix. This is in contrast to the \textbf{numerator layout} whereby $\frac{\partial y}{\partial x}$ is written as $m \times n$ matrix. For more details, please refer to the Wikipedia page \cite{wiki:Matrix_calculus}. For example, if $\bm{x} \in \mathbb{R}^{3}$ and $\bm{y} \in \mathbb{R}^{2}$ then: \begin{flalign} \frac{\partial \bm{y}}{\partial \bm{x}} &= \begin{bmatrix} \frac{\partial y_{1}}{\partial x_{1}} & \frac{\partial y_{2}}{\partial x_{1}} \\[0.5em] \frac{\partial y_{1}}{\partial x_{2}} & \frac{\partial y_{2}}{\partial x_{2}} \\[0.5em] \frac{\partial y_{1}}{\partial x_{3}} & \frac{\partial y_{2}}{\partial x_{3}} \\[0.5em] \end{bmatrix} & \longeqncomment{Denominator layout where layout is according to $\transpose{\vecr{y}}$ across axis 1 and $\vecr{x}$ across axis 0.}{In other words, the elements of $\vecr{y}$ are laid out in columns and the elements of $\vecr{x}$ are laid out in rows.} \nonumber \end{flalign} \section{Summary} \small \begin{tabular}{cllll} \toprule Index & Name & $\matr{Z}$/$\vecr{z}$ & $\frac{\partial L}{\partial \matr{X}}$/$\frac{\partial L}{\partial \vecr{x}}$ & $\frac{\partial L}{\partial \matr{Y}}$/$\frac{\partial L}{\partial \vecr{y}}$ \\[0.3em] \midrule 1 & Matrix Multiplication & $\matr{Z} = \matr{X}\matr{Y}$ & $\frac{\partial L}{\partial \matr{X}}=\frac{\partial L}{\partial \matr{Z}} \transpose{\matr{Y}}$ & $\frac{\partial L}{\partial \matr{Y}}=\transpose{\matr{X}} \frac{\partial L}{\partial \matr{Z}}$ \\[1em] 2 & Element-wise function & $\matr{Z} = g(\matr{X})$ & $\frac{\partial L}{\partial \matr{X}}=g'(\matr{X}) \circ \frac{\partial L}{\partial \matr{Z}}$ & \\[1em] 3 & Hadamard Product & $\matr{Z} = \matr{X} \circ \matr{Y}$ & $\frac{\partial L}{\partial \matr{X}}=\matr{Y} \circ \frac{\partial L}{\partial \matr{Z}}$ & $\frac{\partial L}{\partial \matr{Y}}=\matr{X} \circ \frac{\partial L}{\partial \matr{Z}}$ \\[1em] 4 & Matrix Addition & $\matr{Z} = \matr{X} + \matr{Y}$ & $\frac{\partial L}{\partial \matr{X}}=\frac{\partial L}{\partial \matr{Z}}$ & $\frac{\partial L}{\partial \matr{Y}}=\frac{\partial L}{\partial \matr{Z}}$\\[1em] 5 & Transpose & $\matr{Z} = \transpose{\matr{X}}$ & $\frac{\partial L}{\partial \matr{X}}=\transpose{\frac{\partial L}{\partial \matr{Z}}}$ & \\[1em] 6 & Sum along axis=0 & $\vecr{z}$ = \verb|np.sum(|${\matr{X}}$\verb|, axis=0)| & $\frac{\partial L}{\partial \matr{X}}=\mathbf{1}_{\text{rows}(\matr{X}),1} \frac{\partial L}{\partial \vecr{z}}$ & \\[1em] 7 & Sum along axis=1 & $\vecr{z}$ = \verb|np.sum(|${\matr{X}}$\verb|, axis=1)| & $\frac{\partial L}{\partial \matr{X}}=\frac{\partial L}{\partial \vecr{z}} \mathbf{1}_{1, \text{cols}(\matr{X})}$ & \\[1em] 8 & Broadcasting a column vector & $\matr{Z} = \vecr{x} \mathbf{1}_{1,\text{C}}$ & $\frac{\partial L}{\partial \vecr{x}}=\mathtt{np.sum(} \frac{\partial L}{\partial \matr{Z}} \mathtt{, axis=1)}$ & \\[1em] 9 & Broadcasting a row vector & $\matr{Z} = \mathbf{1}_{\text{R},1} \vecr{x}$ & $\frac{\partial L}{\partial \vecr{x}}=\mathtt{np.sum(} \frac{\partial L}{\partial \matr{Z}} \mathtt{, axis=0)}$ & \\[0.3em] \bottomrule \end{tabular} \normalsize \section{NumPy} \footnotesize \begin{tabular}{cllll} \toprule Index & Name & $\matr{Z}$/$\vecr{z}$ & \verb dX = $\frac{\partial L}{\partial \matr{X}}$/ \verb dx = $\frac{\partial L}{\partial \vecr{x}}$ & \verb dY = $\frac{\partial L}{\partial \matr{Y}}$/ \verb dy = $\frac{\partial L}{\partial \vecr{y}}$ \\[0.3em] \midrule 1 & Matrix Multiplication & \verb Z = \verb X@Y & \verb dX = \verb [email protected] & \verb dY = \verb X.T@dZ \\[0.7em] 2 & Element-wise function & \verb Z = \verb g(X) & \verb dX = \verb g'(X) *\verb dZ & \\[0.7em] 3 & Hadamard Product & \verb Z = \verb X*Y & \verb dX = \verb Y*dZ & \verb dY = \verb X*dZ \\[0.7em] 4 & Matrix Addition & \verb Z = \verb X+Y & \verb dX = \verb dZ & \verb dY = \verb dZ \\[0.7em] 5 & Transpose & \verb Z = \verb X.T & \verb dX = \verb dZ.T & \\[0.7em] 6 & Sum along axis=0 & \verb z = \verb|np.sum(X,axis=0)| & \verb dX = \verb|np.ones((X.shape[0],1))@dz| & \\[0.7em] 7 & Sum along axis=1 & \verb z = \verb|np.sum(X,axis=1)| & \verb dX = \verb|[email protected]((1,X.shape[1]))| & \\[0.7em] 8 & Broadcasting a column vector & \verb Z = \verb|x+np.zeros((1,C))| & \verb dx = \verb|np.sum(dZ,axis=1)| & \\[0.7em] 9 & Broadcasting a row vector & \verb Z = \verb|x+np.zeros((R,1))| & \verb dx = \verb|np.sum(dZ,axis=0)| & \\[0.3em] \bottomrule \end{tabular} \normalsize \section{Matrix Multiplication} \label{Matrix Multiplication} \subsection{Forward Pass} Let $\matr{X}$ be a $2 \times 3$ matrix, and let $\matr{Y}$ be a $3 \times 2$ matrix. Let $\matr{Z} = \matr{X}\matr{Y}$. \begin{flalign} \matr{X} &= \begin{bmatrix} x_{1,1} & x_{1,2} & x_{1,3} \\%[0.5em] x_{2,1} & x_{2,2} & x_{2,3} \\%[0.5em] \end{bmatrix} & \nonumber \end{flalign} \begin{flalign} \matr{Y} &= \begin{bmatrix} y_{1,1} & y_{1,2} \\%[0.5em] y_{2,1} & y_{2,2} \\%[0.5em] y_{3,1} & y_{3,2} \\%[0.5em] \end{bmatrix} & \nonumber \end{flalign} \vspace{1em} \noindent Given $\matr{Z} = \matr{X}\matr{Y}$, Z is a $2 \times 2$ matrix which can be expressed as: \begin{flalign} \matr{Z} &= \begin{bmatrix} z_{1,1} & z_{1,2}\\[0.5em] z_{2,1} & z_{2,2}\\[0.5em] \end{bmatrix} & \nonumber \\ &= \begin{bmatrix} x_{1,1}.y_{1,1} + x_{1,2}.y_{2,1} + x_{1,3}.y_{3,1} & x_{1,1}.y_{1,2} + x_{1,2}.y_{2,2} + x_{1,3}.y_{3,2}\\[0.5em] x_{2,1}.y_{1,1} + x_{2,2}.y_{2,1} + x_{2,3}.y_{3,1} & x_{2,1}.y_{1,2} + x_{2,2}.y_{2,2} + x_{2,3}.y_{3,2}\\[0.5em] \end{bmatrix} \nonumber \end{flalign} \subsection{Backward Pass} We are given $\frac{\partial L}{\partial \matr{Z}}$. It will be of shape $2 \times 2$. \begin{flalign} \frac{\partial L}{\partial \matr{Z}} &= \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} & \frac{\partial L}{\partial z_{1,2}} \\[0.5em] \frac{\partial L}{\partial z_{2,1}} & \frac{\partial L}{\partial z_{2,2}} \\[0.5em] \end{bmatrix} & \eqncomment{$\frac{\partial L}{\partial \matr{Z}}$ is the same shape as $\matr{Z}$ as $L$ is a scalar} \label{dZ_matrix_multiplication} \end{flalign} \noindent We need to compute $\frac{\partial L}{\partial \matr{X}}$ and $\frac{\partial L}{\partial \matr{Y}}$. Using chain rule, we get: \begin{flalign} \label{dX_matrix_multiplication} \frac{\partial L}{\partial \matr{X}} &= \frac{\partial \matr{Z}}{\partial \matr{X}}\frac{\partial L}{\partial \matr{Z}} & \end{flalign} \begin{flalign} \label{dY_matrix_multiplication} \frac{\partial L}{\partial \matr{Y}} &= \frac{\partial \matr{Z}}{\partial \matr{Y}}\frac{\partial L}{\partial \matr{Z}} & \end{flalign} \subsubsection{Computing $\frac{\partial L}{\partial \matr{X}}$} To compute $\frac{\partial L}{\partial \matr{X}}$, we need to compute $\frac{\partial \matr{Z}}{\partial \matr{X}}$. To make it easy for us to think about and capture the Jacobian in a two dimensional matrix (as opposed to a tensor), we will reshape matrices $\matr{X}$, $\matr{Y}$ and $\matr{Z}$ as column vectors, and compute Jacobians on them. Once we have computed the column vector corresponding to $\frac{\partial L}{\partial \matr{X}}$, we will reshape it back to a matrix with the same shape as $\matr{X}$. \begin{flalign} \frac{\partial \matr{Z}}{\partial \matr{X}} &= \begin{bmatrix} \frac{\partial z_{1,1}}{\partial x_{1,1}} & \frac{\partial z_{1,2}}{\partial x_{1,1}} & \frac{\partial z_{2,1}}{\partial x_{1,1}} & \frac{\partial z_{2,2}}{\partial x_{1,1}} \\[0.5em] \frac{\partial z_{1,1}}{\partial x_{1,2}} & \frac{\partial z_{1,2}}{\partial x_{1,2}} & \frac{\partial z_{2,1}}{\partial x_{1,2}} & \frac{\partial z_{2,2}}{\partial x_{1,2}} \\[0.5em] \frac{\partial z_{1,1}}{\partial x_{1,3}} & \frac{\partial z_{1,2}}{\partial x_{1,3}} & \frac{\partial z_{2,1}}{\partial x_{1,3}} & \frac{\partial z_{2,2}}{\partial x_{1,3}} \\[0.5em] \frac{\partial z_{1,1}}{\partial x_{2,1}} & \frac{\partial z_{1,2}}{\partial x_{2,1}} & \frac{\partial z_{2,1}}{\partial x_{2,1}} & \frac{\partial z_{2,2}}{\partial x_{2,1}} \\[0.5em] \frac{\partial z_{1,1}}{\partial x_{2,2}} & \frac{\partial z_{1,2}}{\partial x_{2,2}} & \frac{\partial z_{2,1}}{\partial x_{2,2}} & \frac{\partial z_{2,2}}{\partial x_{2,2}} \\[0.5em] \frac{\partial z_{1,1}}{\partial x_{2,3}} & \frac{\partial z_{1,2}}{\partial x_{2,3}} & \frac{\partial z_{2,1}}{\partial x_{2,3}} & \frac{\partial z_{2,2}}{\partial x_{2,3}} \\[0.5em] \end{bmatrix} & \eqncomment{$\matr{X}$, $\matr{Z}$ are being treated as column vectors. Therefore, $\frac{\partial \matr{Z}}{\partial \matr{X}}$ is of shape $6\times4$.} \nonumber \\ \label{dZbydX_matrix_multiplication} &= \begin{bmatrix} y_{1,1} & y_{1,2} & 0 & 0 \\[0.5em] y_{2,1} & y_{2,2} & 0 & 0 \\[0.5em] y_{3,1} & y_{3,2} & 0 & 0 \\[0.5em] 0 & 0 & y_{1,1} & y_{1,2} \\[0.5em] 0 & 0 & y_{2,1} & y_{2,2} \\[0.5em] 0 & 0 & y_{3,1} & y_{3,2} \\[0.5em] \end{bmatrix} \end{flalign} \noindent Now, $\frac{\partial L}{\partial \matr{Z}}$ in equation \ref{dZ_matrix_multiplication} expressed as a column vector will be: \begin{flalign} \label{dZAsColumnVector_matrix_multiplication} \frac{\partial L}{\partial \matr{Z}} &= \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} \\[0.7em] \frac{\partial L}{\partial z_{1,2}} \\[0.7em] \frac{\partial L}{\partial z_{2,1}} \\[0.7em] \frac{\partial L}{\partial z_{2,2}} \\[0.7em] \end{bmatrix} & \eqncomment{Reshaping $\frac{\partial L}{\partial \matr{Z}}$ from shape $2 \times 2$ to $4 \times 1$} \end{flalign} \noindent Plugging equations \ref{dZbydX_matrix_multiplication} and \ref{dZAsColumnVector_matrix_multiplication} into equation \ref{dX_matrix_multiplication}, we get: \begin{flalign} \frac{\partial L}{\partial \matr{X}} &= \frac{\partial \matr{Z}}{\partial \matr{X}}\frac{\partial L}{\partial \matr{Z}} & \nonumber \\ &= \begin{bmatrix} y_{1,1} & y_{1,2} & 0 & 0 \\[0.5em] y_{2,1} & y_{2,2} & 0 & 0 \\[0.5em] y_{3,1} & y_{3,2} & 0 & 0 \\[0.5em] 0 & 0 & y_{1,1} & y_{1,2} \\[0.5em] 0 & 0 & y_{2,1} & y_{2,2} \\[0.5em] 0 & 0 & y_{3,1} & y_{3,2} \\[0.5em] \end{bmatrix} \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} \\[0.7em] \frac{\partial L}{\partial z_{1,2}} \\[0.7em] \frac{\partial L}{\partial z_{2,1}} \\[0.7em] \frac{\partial L}{\partial z_{2,2}} \\[0.7em] \end{bmatrix} & \eqncomment{$\matr{X}$, $\matr{Z}$ and $\frac{\partial L}{\partial \matr{Z}}$ are being treated as column vectors} \nonumber \\ &= \begin{bmatrix} y_{1,1}.\frac{\partial L}{\partial z_{1,1}} + y_{1,2}.\frac{\partial L}{\partial z_{1,2}} \\[0.7em] y_{2,1}.\frac{\partial L}{\partial z_{1,1}} + y_{2,2}.\frac{\partial L}{\partial z_{1,2}} \\[0.7em] y_{3,1}.\frac{\partial L}{\partial z_{1,1}} + y_{3,2}.\frac{\partial L}{\partial z_{1,2}} \\[0.7em] y_{1,1}.\frac{\partial L}{\partial z_{2,1}} + y_{1,2}.\frac{\partial L}{\partial z_{2,2}} \\[0.7em] y_{2,1}.\frac{\partial L}{\partial z_{2,1}} + y_{2,2}.\frac{\partial L}{\partial z_{2,2}} \\[0.7em] y_{3,1}.\frac{\partial L}{\partial z_{2,1}} + y_{3,2}.\frac{\partial L}{\partial z_{2,2}} \\[0.7em] \end{bmatrix} \label{dXAsColumnVector_matrix_multiplication} \end{flalign} \noindent Reshaping column vector in equation \ref{dXAsColumnVector_matrix_multiplication} as a matrix of shape $\matr{X}$, we get: \begin{flalign} \frac{\partial L}{\partial \matr{X}} &= \begin{bmatrix} y_{1,1}.\frac{\partial L}{\partial z_{1,1}} + y_{1,2}.\frac{\partial L}{\partial z_{1,2}} & y_{2,1}.\frac{\partial L}{\partial z_{1,1}} + y_{2,2}.\frac{\partial L}{\partial z_{1,2}} & y_{3,1}.\frac{\partial L}{\partial z_{1,1}} + y_{3,2}.\frac{\partial L}{\partial z_{1,2}} \\[0.7em] y_{1,1}.\frac{\partial L}{\partial z_{2,1}} + y_{1,2}.\frac{\partial L}{\partial z_{2,2}} & y_{2,1}.\frac{\partial L}{\partial z_{2,1}} + y_{2,2}.\frac{\partial L}{\partial z_{2,2}} & y_{3,1}.\frac{\partial L}{\partial z_{2,1}} + y_{3,2}.\frac{\partial L}{\partial z_{2,2}} \\[0.7em] \end{bmatrix} \nonumber \\ &= \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} & \frac{\partial L}{\partial z_{1,2}} \\[0.7em] \frac{\partial L}{\partial z_{2,1}} & \frac{\partial L}{\partial z_{2,2}} \\[0.7em] \end{bmatrix} \begin{bmatrix} y_{1,1} & y_{2,1} & y_{3,1} \\%[0.5em] y_{1,2} & y_{2,2} & y_{3,2} \\%[0.5em] \end{bmatrix} & \eqncomment{Decomposing into a matmul operation} \nonumber \\ &= \underbrace{ \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} & \frac{\partial L}{\partial z_{1,2}} \\[0.7em] \frac{\partial L}{\partial z_{2,1}} & \frac{\partial L}{\partial z_{2,2}} \\[0.7em] \end{bmatrix}}_{\frac{\partial L}{\partial \matr{Z}}} \underbrace{ \transpose{\begin{bmatrix} y_{1,1} & y_{1,2} \\%[0.5em] y_{2,1} & y_{2,2} \\%[0.5em] y_{3,1} & y_{3,2} \\%[0.5em] \end{bmatrix}}}_{\transpose{\matr{Y}}} \nonumber \\ \label{dXFinal} &= \frac{\partial L}{\partial \matr{Z}} \transpose{\matr{Y}} \end{flalign} \subsubsection{Computing $\frac{\partial L}{\partial \matr{Y}}$} To compute $\frac{\partial L}{\partial \matr{Y}}$, we need to compute $\frac{\partial \matr{Z}}{\partial \matr{Y}}$. To make it easy for us to think about and capture the Jacobian in a two dimensional matrix (as opposed to a tensor), we will reshape matrices $\matr{X}$, $\matr{Y}$ and $\matr{Z}$ as column vectors, and compute Jacobians on them. Once we have computed the column vector corresponding to $\frac{\partial L}{\partial \matr{Y}}$, we will reshape it back to a matrix with the same shape as $\matr{Y}$. \begin{flalign} \frac{\partial \matr{Z}}{\partial \matr{Y}} &= \begin{bmatrix} \frac{\partial z_{1,1}}{\partial y_{1,1}} & \frac{\partial z_{1,2}}{\partial y_{1,1}} & \frac{\partial z_{2,1}}{\partial y_{1,1}} & \frac{\partial z_{2,2}}{\partial y_{1,1}} \\[0.5em] \frac{\partial z_{1,1}}{\partial y_{1,2}} & \frac{\partial z_{1,2}}{\partial y_{1,2}} & \frac{\partial z_{2,1}}{\partial y_{1,2}} & \frac{\partial z_{2,2}}{\partial y_{1,2}} \\[0.5em] \frac{\partial z_{1,1}}{\partial y_{2,1}} & \frac{\partial z_{1,2}}{\partial y_{2,1}} & \frac{\partial z_{2,1}}{\partial y_{2,1}} & \frac{\partial z_{2,2}}{\partial y_{2,1}} \\[0.5em] \frac{\partial z_{1,1}}{\partial y_{2,2}} & \frac{\partial z_{1,2}}{\partial y_{2,2}} & \frac{\partial z_{2,1}}{\partial y_{2,2}} & \frac{\partial z_{2,2}}{\partial y_{2,2}} \\[0.5em] \frac{\partial z_{1,1}}{\partial y_{3,1}} & \frac{\partial z_{1,2}}{\partial y_{3,1}} & \frac{\partial z_{2,1}}{\partial y_{3,1}} & \frac{\partial z_{2,2}}{\partial y_{3,1}} \\[0.5em] \frac{\partial z_{1,1}}{\partial y_{3,2}} & \frac{\partial z_{1,2}}{\partial y_{3,2}} & \frac{\partial z_{2,1}}{\partial y_{3,2}} & \frac{\partial z_{2,2}}{\partial y_{3,2}} \\[0.5em] \end{bmatrix} & \eqncomment{$\matr{Y}$, $\matr{Z}$ are being treated as column vectors. Therefore, $\frac{\partial \matr{Z}}{\partial \matr{Y}}$ is of shape $6\times4$.} \nonumber \\ &= \begin{bmatrix} x_{1,1} & 0 & x_{2,1} & 0 \\[0.5em] 0 & x_{1,1} & 0 & x_{2,1} \\[0.5em] x_{1,2} & 0 & x_{2,2} & 0 \\[0.5em] 0 & x_{1,2} & 0 & x_{2,2} \\[0.5em] x_{1,3} & 0 & x_{2,3} & 0 \\[0.5em] 0 & x_{1,3} & 0 & x_{2,3} \\[0.5em] \end{bmatrix} \label{dZbydY_matrix_multiplication} \end{flalign} \noindent Plugging equations \ref{dZbydY_matrix_multiplication} and \ref{dZAsColumnVector_matrix_multiplication} into equation \ref{dY_matrix_multiplication}, we get: \begin{flalign} \frac{\partial L}{\partial \matr{Y}} &= \begin{bmatrix} x_{1,1} & 0 & x_{2,1} & 0 \\[0.5em] 0 & x_{1,1} & 0 & x_{2,1} \\[0.5em] x_{1,2} & 0 & x_{2,2} & 0 \\[0.5em] 0 & x_{1,2} & 0 & x_{2,2} \\[0.5em] x_{1,3} & 0 & x_{2,3} & 0 \\[0.5em] 0 & x_{1,3} & 0 & x_{2,3} \\[0.5em] \end{bmatrix} \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} \\[0.7em] \frac{\partial L}{\partial z_{1,2}} \\[0.7em] \frac{\partial L}{\partial z_{2,1}} \\[0.7em] \frac{\partial L}{\partial z_{2,2}} \\[0.7em] \end{bmatrix} & \eqncomment{$\matr{Y}$, $\matr{Z}$ and $\frac{\partial L}{\partial \matr{Z}}$ are being treated as column vectors} \nonumber \\ &= \begin{bmatrix} x_{1,1}.\frac{\partial L}{\partial z_{1,1}} + x_{2,1}.\frac{\partial L}{\partial z_{2,1}} \\[0.7em] x_{1,1}.\frac{\partial L}{\partial z_{1,2}} + x_{2,1}.\frac{\partial L}{\partial z_{2,2}} \\[0.7em] x_{1,2}.\frac{\partial L}{\partial z_{1,1}} + x_{2,2}.\frac{\partial L}{\partial z_{2,1}} \\[0.7em] x_{1,2}.\frac{\partial L}{\partial z_{1,2}} + x_{2,2}.\frac{\partial L}{\partial z_{2,2}} \\[0.7em] x_{1,3}.\frac{\partial L}{\partial z_{1,1}} + x_{2,3}.\frac{\partial L}{\partial z_{2,1}} \\[0.7em] x_{1,3}.\frac{\partial L}{\partial z_{1,2}} + x_{2,3}.\frac{\partial L}{\partial z_{2,2}} \\[0.7em] \end{bmatrix} \label{dYAsColumnVector_matrix_multiplication} \end{flalign} \noindent Reshaping column vector in equation \ref{dYAsColumnVector_matrix_multiplication} as a matrix of shape $\matr{Y}$, we get: \begin{flalign} \frac{\partial L}{\partial \matr{Y}} &= \begin{bmatrix} x_{1,1}.\frac{\partial L}{\partial z_{1,1}} + x_{2,1}.\frac{\partial L}{\partial z_{2,1}} & x_{1,1}.\frac{\partial L}{\partial z_{1,2}} + x_{2,1}.\frac{\partial L}{\partial z_{2,2}} \\[0.7em] x_{1,2}.\frac{\partial L}{\partial z_{1,1}} + x_{2,2}.\frac{\partial L}{\partial z_{2,1}} & x_{1,2}.\frac{\partial L}{\partial z_{1,2}} + x_{2,2}.\frac{\partial L}{\partial z_{2,2}} \\[0.7em] x_{1,3}.\frac{\partial L}{\partial z_{1,1}} + x_{2,3}.\frac{\partial L}{\partial z_{2,1}} & x_{1,3}.\frac{\partial L}{\partial z_{1,2}} + x_{2,3}.\frac{\partial L}{\partial z_{2,2}} \\[0.7em] \end{bmatrix} \nonumber \\ &= \begin{bmatrix} x_{1,1} & x_{2,1} \\%[0.5em] x_{1,2} & x_{2,2} \\%[0.5em] x_{1,3} & x_{2,3} \\%[0.5em] \end{bmatrix} \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} & \frac{\partial L}{\partial z_{1,2}} \\[0.7em] \frac{\partial L}{\partial z_{2,1}} & \frac{\partial L}{\partial z_{2,2}} \\[0.7em] \end{bmatrix} & \eqncomment{Decomposing into a matmul operation} \nonumber \\ &= \underbrace{ \transpose{ \begin{bmatrix} x_{1,1} & x_{1,2} & x_{1,3} \\%[0.5em] x_{2,1} & x_{2,2} & x_{2,3} \\%[0.5em] \end{bmatrix}}}_{\transpose{\matr{X}}} \underbrace{ \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} & \frac{\partial L}{\partial z_{1,2}} \\[0.7em] \frac{\partial L}{\partial z_{2,1}} & \frac{\partial L}{\partial z_{2,2}} \\[0.7em] \end{bmatrix}}_{\frac{\partial L}{\partial \matr{Z}}} \nonumber \\ &= \transpose{\matr{X}} \frac{\partial L}{\partial \matr{Z}} \end{flalign} \section{Element-wise operation on a Matrix} \subsection{Forward Pass} Consider some function $g(x)$ which is applied element-wise on a matrix $\matr{X}$ of shape $3 \times 2$. Let $\matr{Z} = g(\matr{X})$. $\matr{Z}$ will be of shape $3 \times 2$. \begin{flalign} \matr{X} &= \begin{bmatrix} x_{1,1} & x_{1,2} \\%[0.5em] x_{2,1} & x_{2,2} \\%[0.5em] x_{3,1} & x_{3,2} \\%[0.5em] \end{bmatrix} & \nonumber \end{flalign} \noindent $\matr{Z}$ can be expressed as: \begin{flalign} \matr{Z} &= \begin{bmatrix} z_{1,1} & z_{1,2} \\%[0.5em] z_{2,1} & z_{2,2} \\%[0.5em] z_{3,1} & z_{3,2} \\%[0.5em] \end{bmatrix} & \nonumber \\ &= \begin{bmatrix} g(x_{1,1}) & g(x_{1,2}) \\[0.5em] g(x_{2,1}) & g(x_{2,2}) \\[0.5em] g(x_{3,1}) & g(x_{3,2}) \\[0.5em] \end{bmatrix} \nonumber \end{flalign} \subsection{Backward Pass} We have $\frac{\partial L}{\partial \matr{Z}}$ of shape $3 \times 2$. \begin{flalign} \frac{\partial L}{\partial \matr{Z}} &= \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} & \frac{\partial L}{\partial z_{1,2}} \\[0.5em] \frac{\partial L}{\partial z_{2,1}} & \frac{\partial L}{\partial z_{2,2}} \\[0.5em] \frac{\partial L}{\partial z_{3,1}} & \frac{\partial L}{\partial z_{3,2}} \\[0.5em] \end{bmatrix} & \eqncomment{$\frac{\partial L}{\partial \matr{Z}}$ is the same shape as $\matr{Z}$ as $L$ is a scalar} \label{dZ_elewise_single_matrix} \end{flalign} \noindent We now need to compute $\frac{\partial L}{\partial \matr{X}}$. Using chain rule, we get: \begin{flalign} \label{dX_elewise_single_matrix} \frac{\partial L}{\partial \matr{X}} &= \frac{\partial \matr{Z}}{\partial \matr{X}}\frac{\partial L}{\partial \matr{Z}} & \end{flalign} \subsubsection{Computing $\frac{\partial L}{\partial \matr{X}}$} To compute $\frac{\partial L}{\partial \matr{X}}$, we need to compute $\frac{\partial \matr{Z}}{\partial \matr{X}}$. To make it easy for us to think about and capture the Jacobian in a two dimensional matrix (as opposed to a tensor), we will reshape matrices $\matr{X}$ and $\matr{Z}$ as column vectors, and compute Jacobians on them. Once we have computed the column vector corresponding to $\frac{\partial L}{\partial \matr{X}}$, we will reshape it back to a matrix with the same shape as $\matr{X}$. \begin{flalign} \frac{\partial \matr{Z}}{\partial \matr{X}} &= \begin{bmatrix} \frac{\partial z_{1,1}}{\partial x_{1,1}} & \frac{\partial z_{1,2}}{\partial x_{1,1}} & \frac{\partial z_{2,1}}{\partial x_{1,1}} & \frac{\partial z_{2,2}}{\partial x_{1,1}} & \frac{\partial z_{3,1}}{\partial x_{1,1}} & \frac{\partial z_{3,2}}{\partial x_{1,1}}\\[0.7em] \frac{\partial z_{1,1}}{\partial x_{1,2}} & \frac{\partial z_{1,2}}{\partial x_{1,2}} & \frac{\partial z_{2,1}}{\partial x_{1,2}} & \frac{\partial z_{2,2}}{\partial x_{1,2}} & \frac{\partial z_{3,1}}{\partial x_{1,2}} & \frac{\partial z_{3,2}}{\partial x_{1,2}}\\[0.7em] \frac{\partial z_{1,1}}{\partial x_{2,1}} & \frac{\partial z_{1,2}}{\partial x_{2,1}} & \frac{\partial z_{2,1}}{\partial x_{2,1}} & \frac{\partial z_{2,2}}{\partial x_{2,1}} & \frac{\partial z_{3,1}}{\partial x_{2,1}} & \frac{\partial z_{3,2}}{\partial x_{2,1}}\\[0.7em] \frac{\partial z_{1,1}}{\partial x_{2,2}} & \frac{\partial z_{1,2}}{\partial x_{2,2}} & \frac{\partial z_{2,1}}{\partial x_{2,2}} & \frac{\partial z_{2,2}}{\partial x_{2,2}} & \frac{\partial z_{3,1}}{\partial x_{2,2}} & \frac{\partial z_{3,2}}{\partial x_{2,2}}\\[0.7em] \frac{\partial z_{1,1}}{\partial x_{3,1}} & \frac{\partial z_{1,2}}{\partial x_{3,1}} & \frac{\partial z_{2,1}}{\partial x_{3,1}} & \frac{\partial z_{2,2}}{\partial x_{3,1}} & \frac{\partial z_{3,1}}{\partial x_{3,1}} & \frac{\partial z_{3,2}}{\partial x_{3,1}}\\[0.7em] \frac{\partial z_{1,1}}{\partial x_{3,2}} & \frac{\partial z_{1,2}}{\partial x_{3,2}} & \frac{\partial z_{2,1}}{\partial x_{3,2}} & \frac{\partial z_{2,2}}{\partial x_{3,2}} & \frac{\partial z_{3,1}}{\partial x_{3,2}} & \frac{\partial z_{3,2}}{\partial x_{3,2}}\\[0.7em] \end{bmatrix} & \longeqncomment{$\matr{X}$, $\matr{Z}$ are being treated as column vectors.}{Therefore, $\frac{\partial \matr{Z}}{\partial \matr{X}}$ is of shape $6\times6$.} \nonumber \\ \label{dZbydX_elewise_single_matrix} &= \begin{bmatrix*}[c] g'(x_{1,1}) & 0 & 0 & 0 & 0 & 0 \\[0.0em] 0 & g'(x_{1,2}) & 0 & 0 & 0 & 0 \\[0.0em] 0 & 0 & g'(x_{2,1}) & 0 & 0 & 0 \\[0.0em] 0 & 0 & 0 & g'(x_{2,2}) & 0 & 0 \\[0.0em] 0 & 0 & 0 & 0 & g'(x_{3,1}) & 0 \\[0.0em] 0 & 0 & 0 & 0 & 0 & g'(x_{3,2}) \\[0.0em] \end{bmatrix*} \end{flalign} \noindent Now, $\frac{\partial L}{\partial \matr{Z}}$ in equation \ref{dZ_elewise_single_matrix} expressed as a column vector will be: \begin{flalign} \label{dZAsColumnVector_elewise_single_matrix} \frac{\partial L}{\partial \matr{Z}} &= \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} \\[0.7em] \frac{\partial L}{\partial z_{1,2}} \\[0.7em] \frac{\partial L}{\partial z_{2,1}} \\[0.7em] \frac{\partial L}{\partial z_{2,2}} \\[0.7em] \frac{\partial L}{\partial z_{3,1}} \\[0.7em] \frac{\partial L}{\partial z_{3,2}} \\[0.7em] \end{bmatrix} & \eqncomment{Reshaping $\frac{\partial L}{\partial \matr{Z}}$ from shape $3 \times 2$ to $6 \times 1$} \end{flalign} \noindent Plugging equations \ref{dZbydX_elewise_single_matrix} and \ref{dZAsColumnVector_elewise_single_matrix} into equation \ref{dX_elewise_single_matrix}, we get: \begin{flalign} \frac{\partial L}{\partial \matr{X}} &= \frac{\partial \matr{Z}}{\partial \matr{X}}\frac{\partial L}{\partial \matr{Z}} & \nonumber \\ &= \begin{bmatrix} g'(x_{1,1}) & 0 & 0 & 0 & 0 & 0 \\[0.5em] 0 & g'(x_{1,2}) & 0 & 0 & 0 & 0 \\[0.5em] 0 & 0 & g'(x_{2,1}) & 0 & 0 & 0 \\[0.5em] 0 & 0 & 0 & g'(x_{2,2}) & 0 & 0 \\[0.5em] 0 & 0 & 0 & 0 & g'(x_{3,1}) & 0 \\[0.5em] 0 & 0 & 0 & 0 & 0 & g'(x_{3,2}) \\[0.5em] \end{bmatrix} \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} \\[0.7em] \frac{\partial L}{\partial z_{1,2}} \\[0.7em] \frac{\partial L}{\partial z_{2,1}} \\[0.7em] \frac{\partial L}{\partial z_{2,2}} \\[0.7em] \frac{\partial L}{\partial z_{3,1}} \\[0.7em] \frac{\partial L}{\partial z_{3,2}} \\[0.7em] \end{bmatrix} & \longeqncomment{$\matr{X}$, $\matr{Z}$ and $\frac{\partial L}{\partial \matr{Z}}$ are being}{treated as column vectors.} \nonumber \\ &= \begin{bmatrix} g'(x_{1,1}).\frac{\partial L}{\partial z_{1,1}} \\[0.7em] g'(x_{1,2}).\frac{\partial L}{\partial z_{1,2}} \\[0.7em] g'(x_{2,1}).\frac{\partial L}{\partial z_{2,1}} \\[0.7em] g'(x_{2,2}).\frac{\partial L}{\partial z_{2,2}} \\[0.7em] g'(x_{3,1}).\frac{\partial L}{\partial z_{3,1}} \\[0.7em] g'(x_{3,2}).\frac{\partial L}{\partial z_{3,2}} \\[0.7em] \end{bmatrix} \label{dXAsColumnVector_elewise_single_matrix} \end{flalign} \noindent Note, we will be using $\circ$ to denote element-wise multiplication between matrices popularly known as Hadamard product. Also $g'(\matr{X})$ like $g(\matr{X})$ will be applied element-wise. \begin{flalign} g'(\matr{X}) &= \begin{bmatrix} g'(x_{1,1}) & g'(x_{1,2}) \\[0.5em] g'(x_{2,1}) & g'(x_{2,2}) \\[0.5em] g'(x_{3,1}) & g'(x_{3,2}) \\[0.5em] \end{bmatrix} & \nonumber \end{flalign} \noindent Now, reshaping column vector in equation \ref{dXAsColumnVector_elewise_single_matrix} as a matrix of shape $\matr{X}$, we get: \begin{flalign} \frac{\partial L}{\partial \matr{X}} &= \begin{bmatrix} g'(x_{1,1}).\frac{\partial L}{\partial z_{1,1}} & g'(x_{1,2}).\frac{\partial L}{\partial z_{1,2}} \\[0.7em] g'(x_{2,1}).\frac{\partial L}{\partial z_{2,1}} & g'(x_{2,2}).\frac{\partial L}{\partial z_{2,2}} \\[0.7em] g'(x_{3,1}).\frac{\partial L}{\partial z_{3,1}} & g'(x_{3,2}).\frac{\partial L}{\partial z_{3,2}} \\[0.7em] \end{bmatrix} \nonumber \\ &= \underbrace{ \begin{bmatrix} g'(x_{1,1}) & g'(x_{1,2}) \\[0.5em] g'(x_{2,1}) & g'(x_{2,2}) \\[0.5em] g'(x_{3,1}) & g'(x_{3,2}) \\[0.5em] \end{bmatrix}}_{g'(\matr{X})} \circ \underbrace{ \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} & \frac{\partial L}{\partial z_{1,2}} \\[0.5em] \frac{\partial L}{\partial z_{2,1}} & \frac{\partial L}{\partial z_{2,2}} \\[0.5em] \frac{\partial L}{\partial z_{3,1}} & \frac{\partial L}{\partial z_{3,2}} \\[0.5em] \end{bmatrix}}_{\frac{\partial L}{\partial \matr{Z}}} & \eqncomment{Decomposing into an element-wise multiplication between matrices.} \nonumber \\ &= g'(\matr{X}) \circ \frac{\partial L}{\partial \matr{Z}} \end{flalign} \section{Hadamard product} \subsection{Forward Pass} Let $\matr{X}$ be a $3 \times 2$ matrix, and let $\matr{Y}$ be a $3 \times 2$ matrix. Let $\matr{Z} = \matr{X} \circ \matr{Y}$ that is element-wise multiplication between $\matr{X}$ and $\matr{Y}$. \begin{flalign} \matr{X} &= \begin{bmatrix} x_{1,1} & x_{1,2} \\%[0.5em] x_{2,1} & x_{2,2} \\%[0.5em] x_{3,1} & x_{3,2} \\%[0.5em] \end{bmatrix} & \nonumber \end{flalign} \begin{flalign} \matr{Y} &= \begin{bmatrix} y_{1,1} & y_{1,2} \\%[0.5em] y_{2,1} & y_{2,2} \\%[0.5em] y_{3,1} & y_{3,2} \\%[0.5em] \end{bmatrix} & \nonumber \end{flalign} \noindent Given $\matr{Z} = \matr{X} \circ \matr{Y}$, $\matr{Z}$ is a $3 \times 2$ matrix which can be expressed as: \begin{flalign} \matr{Z} &= \begin{bmatrix} z_{1,1} & z_{1,2}\\[0.5em] z_{2,1} & z_{2,2}\\[0.5em] z_{3,1} & z_{3,2}\\[0.5em] \end{bmatrix} & \nonumber \\ &= \begin{bmatrix} x_{1,1}.y_{1,1} & x_{1,2}.y_{1,2} \\[0.5em] x_{2,1}.y_{2,1} & x_{2,2}.y_{2,2} \\[0.5em] x_{3,1}.y_{3,1} & x_{3,2}.y_{3,2} \\[0.5em] \end{bmatrix} \nonumber \end{flalign} \subsection{Backward Pass} We have $\frac{\partial L}{\partial \matr{Z}}$ of shape $3 \times 2$. \begin{flalign} \frac{\partial L}{\partial \matr{Z}} &= \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} & \frac{\partial L}{\partial z_{1,2}} \\[0.5em] \frac{\partial L}{\partial z_{2,1}} & \frac{\partial L}{\partial z_{2,2}} \\[0.5em] \frac{\partial L}{\partial z_{3,1}} & \frac{\partial L}{\partial z_{3,2}} \\[0.5em] \end{bmatrix} & \eqncomment{$\frac{\partial L}{\partial \matr{Z}}$ is the same shape as $\matr{Z}$ as $L$ is a scalar} \label{dZ_hadamard_product} \end{flalign} \noindent We now need to compute $\frac{\partial L}{\partial \matr{X}}$ and $\frac{\partial L}{\partial \matr{Y}}$. Using chain rule, we get: \begin{flalign} \label{dX_hadamard_product} \frac{\partial L}{\partial \matr{X}} &= \frac{\partial \matr{Z}}{\partial \matr{X}}\frac{\partial L}{\partial \matr{Z}} & \end{flalign} \begin{flalign} \label{dY_hadamard_product} \frac{\partial L}{\partial \matr{Y}} &= \frac{\partial \matr{Z}}{\partial \matr{Y}}\frac{\partial L}{\partial \matr{Z}} & \end{flalign} \subsubsection{Computing $\frac{\partial L}{\partial \matr{X}}$} To compute $\frac{\partial L}{\partial \matr{X}}$, we need to compute $\frac{\partial \matr{Z}}{\partial \matr{X}}$. To make it easy for us to think about and capture the Jacobian in a two dimensional matrix (as opposed to a tensor), we will reshape matrices $\matr{X}$, $\matr{Y}$ and $\matr{Z}$ as column vectors, and compute Jacobians on them. Once we have computed the column vector corresponding to $\frac{\partial L}{\partial \matr{X}}$, we will reshape it back to a matrix with the same shape as $\matr{X}$. \begin{flalign} \frac{\partial \matr{Z}}{\partial \matr{X}} &= \begin{bmatrix} \frac{\partial z_{1,1}}{\partial x_{1,1}} & \frac{\partial z_{1,2}}{\partial x_{1,1}} & \frac{\partial z_{2,1}}{\partial x_{1,1}} & \frac{\partial z_{2,2}}{\partial x_{1,1}} & \frac{\partial z_{3,1}}{\partial x_{1,1}} & \frac{\partial z_{3,2}}{\partial x_{1,1}}\\[0.7em] \frac{\partial z_{1,1}}{\partial x_{1,2}} & \frac{\partial z_{1,2}}{\partial x_{1,2}} & \frac{\partial z_{2,1}}{\partial x_{1,2}} & \frac{\partial z_{2,2}}{\partial x_{1,2}} & \frac{\partial z_{3,1}}{\partial x_{1,2}} & \frac{\partial z_{3,2}}{\partial x_{1,2}}\\[0.7em] \frac{\partial z_{1,1}}{\partial x_{2,1}} & \frac{\partial z_{1,2}}{\partial x_{2,1}} & \frac{\partial z_{2,1}}{\partial x_{2,1}} & \frac{\partial z_{2,2}}{\partial x_{2,1}} & \frac{\partial z_{3,1}}{\partial x_{2,1}} & \frac{\partial z_{3,2}}{\partial x_{2,1}}\\[0.7em] \frac{\partial z_{1,1}}{\partial x_{2,2}} & \frac{\partial z_{1,2}}{\partial x_{2,2}} & \frac{\partial z_{2,1}}{\partial x_{2,2}} & \frac{\partial z_{2,2}}{\partial x_{2,2}} & \frac{\partial z_{3,1}}{\partial x_{2,2}} & \frac{\partial z_{3,2}}{\partial x_{2,2}}\\[0.7em] \frac{\partial z_{1,1}}{\partial x_{3,1}} & \frac{\partial z_{1,2}}{\partial x_{3,1}} & \frac{\partial z_{2,1}}{\partial x_{3,1}} & \frac{\partial z_{2,2}}{\partial x_{3,1}} & \frac{\partial z_{3,1}}{\partial x_{3,1}} & \frac{\partial z_{3,2}}{\partial x_{3,1}}\\[0.7em] \frac{\partial z_{1,1}}{\partial x_{3,2}} & \frac{\partial z_{1,2}}{\partial x_{3,2}} & \frac{\partial z_{2,1}}{\partial x_{3,2}} & \frac{\partial z_{2,2}}{\partial x_{3,2}} & \frac{\partial z_{3,1}}{\partial x_{3,2}} & \frac{\partial z_{3,2}}{\partial x_{3,2}}\\[0.7em] \end{bmatrix} & \longeqncomment{$\matr{X}$, $\matr{Z}$ are being treated as column vectors.}{Therefore, $\frac{\partial \matr{Z}}{\partial \matr{X}}$ is of shape $6\times6$.} \nonumber \\ \label{dZbydX_hadamard_product} &= \begin{bmatrix} y_{1,1} & 0 & 0 & 0 & 0 & 0 \\[0.5em] 0 & y_{1,2} & 0 & 0 & 0 & 0 \\[0.5em] 0 & 0 & y_{2,1} & 0 & 0 & 0 \\[0.5em] 0 & 0 & 0 & y_{2,2} & 0 & 0 \\[0.5em] 0 & 0 & 0 & 0 & y_{3,1} & 0 \\[0.5em] 0 & 0 & 0 & 0 & 0 & y_{3,2} \\[0.5em] \end{bmatrix} \end{flalign} \noindent Now, $\frac{\partial L}{\partial \matr{Z}}$ in equation \ref{dZ_hadamard_product} expressed as a column vector will be: \begin{flalign} \label{dZAsColumnVector_hadamard_product} \frac{\partial L}{\partial \matr{Z}} &= \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} \\[0.7em] \frac{\partial L}{\partial z_{1,2}} \\[0.7em] \frac{\partial L}{\partial z_{2,1}} \\[0.7em] \frac{\partial L}{\partial z_{2,2}} \\[0.7em] \frac{\partial L}{\partial z_{3,1}} \\[0.7em] \frac{\partial L}{\partial z_{3,2}} \\[0.7em] \end{bmatrix} & \eqncomment{Reshaping $\frac{\partial L}{\partial \matr{Z}}$ from shape $3 \times 2$ to $6 \times 1$} \end{flalign} \noindent Plugging equations \ref{dZbydX_hadamard_product} and \ref{dZAsColumnVector_hadamard_product} into equation \ref{dX_hadamard_product}, we get: \begin{flalign} \frac{\partial L}{\partial \matr{X}} &= \frac{\partial \matr{Z}}{\partial \matr{X}}\frac{\partial L}{\partial \matr{Z}} & \nonumber \\ &= \begin{bmatrix} y_{1,1} & 0 & 0 & 0 & 0 & 0 \\[0.5em] 0 & y_{1,2} & 0 & 0 & 0 & 0 \\[0.5em] 0 & 0 & y_{2,1} & 0 & 0 & 0 \\[0.5em] 0 & 0 & 0 & y_{2,2} & 0 & 0 \\[0.5em] 0 & 0 & 0 & 0 & y_{3,1} & 0 \\[0.5em] 0 & 0 & 0 & 0 & 0 & y_{3,2} \\[0.5em] \end{bmatrix} \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} \\[0.7em] \frac{\partial L}{\partial z_{1,2}} \\[0.7em] \frac{\partial L}{\partial z_{2,1}} \\[0.7em] \frac{\partial L}{\partial z_{2,2}} \\[0.7em] \frac{\partial L}{\partial z_{3,1}} \\[0.7em] \frac{\partial L}{\partial z_{3,2}} \\[0.7em] \end{bmatrix} & \eqncomment{$\matr{X}$, $\matr{Z}$ and $\frac{\partial L}{\partial \matr{Z}}$ are being treated as column vectors} \nonumber \\ &= \begin{bmatrix} y_{1,1}.\frac{\partial L}{\partial z_{1,1}} \\[0.7em] y_{1,2}.\frac{\partial L}{\partial z_{1,2}} \\[0.7em] y_{2,1}.\frac{\partial L}{\partial z_{2,1}} \\[0.7em] y_{2,2}.\frac{\partial L}{\partial z_{2,2}} \\[0.7em] y_{3,1}.\frac{\partial L}{\partial z_{3,1}} \\[0.7em] y_{3,2}.\frac{\partial L}{\partial z_{3,2}} \\[0.7em] \end{bmatrix} \label{dXAsColumnVector_hadamard_product} \end{flalign} \noindent Reshaping column vector in equation \ref{dXAsColumnVector_hadamard_product} as a matrix of shape $\matr{X}$, we get: \begin{flalign} \frac{\partial L}{\partial \matr{X}} &= \begin{bmatrix} y_{1,1}.\frac{\partial L}{\partial z_{1,1}} & y_{1,2}.\frac{\partial L}{\partial z_{1,2}} \\[0.7em] y_{2,1}.\frac{\partial L}{\partial z_{2,1}} & y_{2,2}.\frac{\partial L}{\partial z_{2,2}} \\[0.7em] y_{3,1}.\frac{\partial L}{\partial z_{3,1}} & y_{3,2}.\frac{\partial L}{\partial z_{3,2}} \\[0.7em] \end{bmatrix} \nonumber \\ &= \underbrace{ \begin{bmatrix} y_{1,1} & y_{1,2} \\%[0.5em] y_{2,1} & y_{2,2} \\%[0.5em] y_{3,1} & y_{3,2} \\%[0.5em] \end{bmatrix}}_{\matr{Y}} \circ \underbrace{ \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} & \frac{\partial L}{\partial z_{1,2}} \\[0.5em] \frac{\partial L}{\partial z_{2,1}} & \frac{\partial L}{\partial z_{2,2}} \\[0.5em] \frac{\partial L}{\partial z_{3,1}} & \frac{\partial L}{\partial z_{3,2}} \\[0.5em] \end{bmatrix}}_{\frac{\partial L}{\partial \matr{Z}}} & \eqncomment{Decomposing into an element-wise multiplication between matrices.} \nonumber \\ &= \matr{Y} \circ \frac{\partial L}{\partial \matr{Z}} \end{flalign} \subsubsection{Computing $\frac{\partial L}{\partial \matr{Y}}$} To compute $\frac{\partial L}{\partial \matr{Y}}$, we need to compute $\frac{\partial \matr{Z}}{\partial \matr{Y}}$. To make it easy for us to think about and capture the Jacobian in a two dimensional matrix (as opposed to a tensor), we will reshape matrices $\matr{X}$, $\matr{Y}$ and $\matr{Z}$ as column vectors, and compute Jacobians on them. Once we have computed the column vector corresponding to $\frac{\partial L}{\partial \matr{Y}}$, we will reshape it back to a matrix with the same shape as $\matr{Y}$. \begin{flalign} \frac{\partial \matr{Z}}{\partial \matr{Y}} &= \begin{bmatrix} \frac{\partial z_{1,1}}{\partial y_{1,1}} & \frac{\partial z_{1,2}}{\partial y_{1,1}} & \frac{\partial z_{2,1}}{\partial y_{1,1}} & \frac{\partial z_{2,2}}{\partial y_{1,1}} & \frac{\partial z_{3,1}}{\partial y_{1,1}} & \frac{\partial z_{3,2}}{\partial y_{1,1}}\\[0.7em] \frac{\partial z_{1,1}}{\partial y_{1,2}} & \frac{\partial z_{1,2}}{\partial y_{1,2}} & \frac{\partial z_{2,1}}{\partial y_{1,2}} & \frac{\partial z_{2,2}}{\partial y_{1,2}} & \frac{\partial z_{3,1}}{\partial y_{1,2}} & \frac{\partial z_{3,2}}{\partial y_{1,2}}\\[0.7em] \frac{\partial z_{1,1}}{\partial y_{2,1}} & \frac{\partial z_{1,2}}{\partial y_{2,1}} & \frac{\partial z_{2,1}}{\partial y_{2,1}} & \frac{\partial z_{2,2}}{\partial y_{2,1}} & \frac{\partial z_{3,1}}{\partial y_{2,1}} & \frac{\partial z_{3,2}}{\partial y_{2,1}}\\[0.7em] \frac{\partial z_{1,1}}{\partial y_{2,2}} & \frac{\partial z_{1,2}}{\partial y_{2,2}} & \frac{\partial z_{2,1}}{\partial y_{2,2}} & \frac{\partial z_{2,2}}{\partial y_{2,2}} & \frac{\partial z_{3,1}}{\partial y_{2,2}} & \frac{\partial z_{3,2}}{\partial y_{2,2}}\\[0.7em] \frac{\partial z_{1,1}}{\partial y_{3,1}} & \frac{\partial z_{1,2}}{\partial y_{3,1}} & \frac{\partial z_{2,1}}{\partial y_{3,1}} & \frac{\partial z_{2,2}}{\partial y_{3,1}} & \frac{\partial z_{3,1}}{\partial y_{3,1}} & \frac{\partial z_{3,2}}{\partial y_{3,1}}\\[0.7em] \frac{\partial z_{1,1}}{\partial y_{3,2}} & \frac{\partial z_{1,2}}{\partial y_{3,2}} & \frac{\partial z_{2,1}}{\partial y_{3,2}} & \frac{\partial z_{2,2}}{\partial y_{3,2}} & \frac{\partial z_{3,1}}{\partial y_{3,2}} & \frac{\partial z_{3,2}}{\partial y_{3,2}}\\[0.7em] \end{bmatrix} & \longeqncomment{$\matr{Y}$, $\matr{Z}$ are being treated as column vectors.}{Therefore, $\frac{\partial \matr{Z}}{\partial \matr{Y}}$ is of shape $6\times6$.} \nonumber \\ \label{dZbydY_hadamard_product} &= \begin{bmatrix} x_{1,1} & 0 & 0 & 0 & 0 & 0 \\[0.5em] 0 & x_{1,2} & 0 & 0 & 0 & 0 \\[0.5em] 0 & 0 & x_{2,1} & 0 & 0 & 0 \\[0.5em] 0 & 0 & 0 & x_{2,2} & 0 & 0 \\[0.5em] 0 & 0 & 0 & 0 & x_{3,1} & 0 \\[0.5em] 0 & 0 & 0 & 0 & 0 & x_{3,2} \\[0.5em] \end{bmatrix} \end{flalign} \noindent Plugging equations \ref{dZbydY_hadamard_product} and \ref{dZAsColumnVector_hadamard_product} into equation \ref{dY_hadamard_product}, we get: \begin{flalign} \frac{\partial L}{\partial \matr{Y}} &= \frac{\partial \matr{Z}}{\partial \matr{Y}}\frac{\partial L}{\partial \matr{Z}} & \nonumber \\ &= \begin{bmatrix} x_{1,1} & 0 & 0 & 0 & 0 & 0 \\[0.5em] 0 & x_{1,2} & 0 & 0 & 0 & 0 \\[0.5em] 0 & 0 & x_{2,1} & 0 & 0 & 0 \\[0.5em] 0 & 0 & 0 & x_{2,2} & 0 & 0 \\[0.5em] 0 & 0 & 0 & 0 & x_{3,1} & 0 \\[0.5em] 0 & 0 & 0 & 0 & 0 & x_{3,2} \\[0.5em] \end{bmatrix} \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} \\[0.7em] \frac{\partial L}{\partial z_{1,2}} \\[0.7em] \frac{\partial L}{\partial z_{2,1}} \\[0.7em] \frac{\partial L}{\partial z_{2,2}} \\[0.7em] \frac{\partial L}{\partial z_{3,1}} \\[0.7em] \frac{\partial L}{\partial z_{3,2}} \\[0.7em] \end{bmatrix} & \eqncomment{$\matr{Y}$, $\matr{Z}$ and $\frac{\partial L}{\partial \matr{Z}}$ are being treated as column vectors} \nonumber \\ &= \begin{bmatrix} x_{1,1}.\frac{\partial L}{\partial z_{1,1}} \\[0.7em] x_{1,2}.\frac{\partial L}{\partial z_{1,2}} \\[0.7em] x_{2,1}.\frac{\partial L}{\partial z_{2,1}} \\[0.7em] x_{2,2}.\frac{\partial L}{\partial z_{2,2}} \\[0.7em] x_{3,1}.\frac{\partial L}{\partial z_{3,1}} \\[0.7em] x_{3,2}.\frac{\partial L}{\partial z_{3,2}} \\[0.7em] \end{bmatrix} \label{dYAsColumnVector_hadamard_product} \end{flalign} \noindent Now, reshaping column vector in equation \ref{dYAsColumnVector_hadamard_product} as a matrix of shape $\matr{Y}$, we get: \begin{flalign} \frac{\partial L}{\partial \matr{X}} &= \begin{bmatrix} x_{1,1}.\frac{\partial L}{\partial z_{1,1}} & x_{1,2}.\frac{\partial L}{\partial z_{1,2}} \\[0.7em] x_{2,1}.\frac{\partial L}{\partial z_{2,1}} & x_{2,2}.\frac{\partial L}{\partial z_{2,2}} \\[0.7em] x_{3,1}.\frac{\partial L}{\partial z_{3,1}} & x_{3,2}.\frac{\partial L}{\partial z_{3,2}} \\[0.7em] \end{bmatrix} \nonumber \\ &= \underbrace{ \begin{bmatrix} x_{1,1} & x_{1,2} \\%[0.5em] x_{2,1} & x_{2,2} \\%[0.5em] x_{3,1} & x_{3,2} \\%[0.5em] \end{bmatrix}}_{\matr{X}} \circ \underbrace{ \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} & \frac{\partial L}{\partial z_{1,2}} \\[0.5em] \frac{\partial L}{\partial z_{2,1}} & \frac{\partial L}{\partial z_{2,2}} \\[0.5em] \frac{\partial L}{\partial z_{3,1}} & \frac{\partial L}{\partial z_{3,2}} \\[0.5em] \end{bmatrix}}_{\frac{\partial L}{\partial \matr{Z}}} & \eqncomment{Decomposing into an element-wise multiplication between matrices.} \nonumber \\ &= \matr{X} \circ \frac{\partial L}{\partial \matr{Z}} \end{flalign} \section{Matrix Addition} \subsection{Forward Pass} Let $\matr{X}$ be a $3 \times 2$ matrix, and let $\matr{Y}$ be a $3 \times 2$ matrix. Let $\matr{Z} = \matr{X} + \matr{Y}$ that is element-wise addition between $\matr{X}$ and $\matr{Y}$. \begin{flalign} \matr{X} &= \begin{bmatrix} x_{1,1} & x_{1,2} \\%[0.5em] x_{2,1} & x_{2,2} \\%[0.5em] x_{3,1} & x_{3,2} \\%[0.5em] \end{bmatrix} & \nonumber \end{flalign} \begin{flalign} \matr{Y} &= \begin{bmatrix} y_{1,1} & y_{1,2} \\%[0.5em] y_{2,1} & y_{2,2} \\%[0.5em] y_{3,1} & y_{3,2} \\%[0.5em] \end{bmatrix} & \nonumber \end{flalign} \noindent Given $\matr{Z} = \matr{X} + \matr{Y}$, Z is a $3 \times 2$ matrix which can be expressed as: \begin{flalign} \matr{Z} &= \begin{bmatrix} z_{1,1} & z_{1,2}\\[0.5em] z_{2,1} & z_{2,2}\\[0.5em] z_{3,1} & z_{3,2}\\[0.5em] \end{bmatrix} & \nonumber \\ &= \begin{bmatrix} x_{1,1} + y_{1,1} & x_{1,2} + y_{1,2} \\[0.5em] x_{2,1} + y_{2,1} & x_{2,2} + y_{2,2} \\[0.5em] x_{3,1} + y_{3,1} & x_{3,2} + y_{3,2} \\[0.5em] \end{bmatrix} \nonumber \end{flalign} \subsection{Backward Pass} We have $\frac{\partial L}{\partial \matr{Z}}$ of shape $3 \times 2$. \begin{flalign} \frac{\partial L}{\partial \matr{Z}} &= \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} & \frac{\partial L}{\partial z_{1,2}} \\[0.5em] \frac{\partial L}{\partial z_{2,1}} & \frac{\partial L}{\partial z_{2,2}} \\[0.5em] \frac{\partial L}{\partial z_{3,1}} & \frac{\partial L}{\partial z_{3,2}} \\[0.5em] \end{bmatrix} & \eqncomment{$\frac{\partial L}{\partial \matr{Z}}$ is the same shape as $\matr{Z}$ as $L$ is a scalar} \label{dZ_matrix_addition} \end{flalign} \noindent We now need to compute $\frac{\partial L}{\partial \matr{X}}$ and $\frac{\partial L}{\partial \matr{Y}}$. Using chain rule, we get: \begin{flalign} \label{dX_matrix_addition} \frac{\partial L}{\partial \matr{X}} &= \frac{\partial \matr{Z}}{\partial \matr{X}}\frac{\partial L}{\partial \matr{Z}} & \end{flalign} \begin{flalign} \label{dY_matrix_addition} \frac{\partial L}{\partial \matr{Y}} &= \frac{\partial \matr{Z}}{\partial \matr{Y}}\frac{\partial L}{\partial \matr{Z}} & \end{flalign} \subsubsection{Computing $\frac{\partial L}{\partial \matr{X}}$} To compute $\frac{\partial L}{\partial \matr{X}}$, we need to compute $\frac{\partial \matr{Z}}{\partial \matr{X}}$. To make it easy for us to think about and capture the Jacobian in a two dimensional matrix (as opposed to a tensor), we will reshape matrices $\matr{X}$, $\matr{Y}$ and $\matr{Z}$ as column vectors, and compute Jacobians on them. Once we have computed the column vector corresponding to $\frac{\partial L}{\partial \matr{X}}$, we will reshape it back to a matrix with the same shape as $\matr{X}$. \begin{flalign} \frac{\partial \matr{Z}}{\partial \matr{X}} &= \begin{bmatrix} \frac{\partial z_{1,1}}{\partial x_{1,1}} & \frac{\partial z_{1,2}}{\partial x_{1,1}} & \frac{\partial z_{2,1}}{\partial x_{1,1}} & \frac{\partial z_{2,2}}{\partial x_{1,1}} & \frac{\partial z_{3,1}}{\partial x_{1,1}} & \frac{\partial z_{3,2}}{\partial x_{1,1}}\\[0.7em] \frac{\partial z_{1,1}}{\partial x_{1,2}} & \frac{\partial z_{1,2}}{\partial x_{1,2}} & \frac{\partial z_{2,1}}{\partial x_{1,2}} & \frac{\partial z_{2,2}}{\partial x_{1,2}} & \frac{\partial z_{3,1}}{\partial x_{1,2}} & \frac{\partial z_{3,2}}{\partial x_{1,2}}\\[0.7em] \frac{\partial z_{1,1}}{\partial x_{2,1}} & \frac{\partial z_{1,2}}{\partial x_{2,1}} & \frac{\partial z_{2,1}}{\partial x_{2,1}} & \frac{\partial z_{2,2}}{\partial x_{2,1}} & \frac{\partial z_{3,1}}{\partial x_{2,1}} & \frac{\partial z_{3,2}}{\partial x_{2,1}}\\[0.7em] \frac{\partial z_{1,1}}{\partial x_{2,2}} & \frac{\partial z_{1,2}}{\partial x_{2,2}} & \frac{\partial z_{2,1}}{\partial x_{2,2}} & \frac{\partial z_{2,2}}{\partial x_{2,2}} & \frac{\partial z_{3,1}}{\partial x_{2,2}} & \frac{\partial z_{3,2}}{\partial x_{2,2}}\\[0.7em] \frac{\partial z_{1,1}}{\partial x_{3,1}} & \frac{\partial z_{1,2}}{\partial x_{3,1}} & \frac{\partial z_{2,1}}{\partial x_{3,1}} & \frac{\partial z_{2,2}}{\partial x_{3,1}} & \frac{\partial z_{3,1}}{\partial x_{3,1}} & \frac{\partial z_{3,2}}{\partial x_{3,1}}\\[0.7em] \frac{\partial z_{1,1}}{\partial x_{3,2}} & \frac{\partial z_{1,2}}{\partial x_{3,2}} & \frac{\partial z_{2,1}}{\partial x_{3,2}} & \frac{\partial z_{2,2}}{\partial x_{3,2}} & \frac{\partial z_{3,1}}{\partial x_{3,2}} & \frac{\partial z_{3,2}}{\partial x_{3,2}}\\[0.7em] \end{bmatrix} & \longeqncomment{$\matr{X}$, $\matr{Z}$ are being treated as column vectors.}{Therefore, $\frac{\partial \matr{Z}}{\partial \matr{X}}$ is of shape $6\times6$.} \nonumber \\ \label{dZbydX_matrix_addition} &= \begin{bmatrix} 1 & 0 & 0 & 0 & 0 & 0 \\%[0.5em] 0 & 1 & 0 & 0 & 0 & 0 \\%[0.5em] 0 & 0 & 1 & 0 & 0 & 0 \\%[0.5em] 0 & 0 & 0 & 1 & 0 & 0 \\%[0.5em] 0 & 0 & 0 & 0 & 1 & 0 \\%[0.5em] 0 & 0 & 0 & 0 & 0 & 1 \\%[0.5em] \end{bmatrix} \end{flalign} \noindent Now, $\frac{\partial L}{\partial \matr{Z}}$ in equation \ref{dZ_matrix_addition} expressed as a column vector will be: \begin{flalign} \label{dZAsColumnVector_matrix_addition} \frac{\partial L}{\partial \matr{Z}} &= \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} \\[0.7em] \frac{\partial L}{\partial z_{1,2}} \\[0.7em] \frac{\partial L}{\partial z_{2,1}} \\[0.7em] \frac{\partial L}{\partial z_{2,2}} \\[0.7em] \frac{\partial L}{\partial z_{3,1}} \\[0.7em] \frac{\partial L}{\partial z_{3,2}} \\[0.7em] \end{bmatrix} & \eqncomment{Reshaping $\frac{\partial L}{\partial \matr{Z}}$ from shape $3 \times 2$ to $6 \times 1$} \end{flalign} \noindent Plugging equations \ref{dZbydX_matrix_addition} and \ref{dZAsColumnVector_matrix_addition} into equation \ref{dX_matrix_addition}, we get: \begin{flalign} \frac{\partial L}{\partial \matr{X}} &= \frac{\partial \matr{Z}}{\partial \matr{X}}\frac{\partial L}{\partial \matr{Z}} & \nonumber \\ &= \begin{bmatrix} 1 & 0 & 0 & 0 & 0 & 0 \\%[0.5em] 0 & 1 & 0 & 0 & 0 & 0 \\%[0.5em] 0 & 0 & 1 & 0 & 0 & 0 \\%[0.5em] 0 & 0 & 0 & 1 & 0 & 0 \\%[0.5em] 0 & 0 & 0 & 0 & 1 & 0 \\%[0.5em] 0 & 0 & 0 & 0 & 0 & 1 \\%[0.5em] \end{bmatrix} \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} \\[0.7em] \frac{\partial L}{\partial z_{1,2}} \\[0.7em] \frac{\partial L}{\partial z_{2,1}} \\[0.7em] \frac{\partial L}{\partial z_{2,2}} \\[0.7em] \frac{\partial L}{\partial z_{3,1}} \\[0.7em] \frac{\partial L}{\partial z_{3,2}} \\[0.7em] \end{bmatrix} & \eqncomment{$\matr{X}$, $\matr{Z}$ and $\frac{\partial L}{\partial \matr{Z}}$ are being treated as column vectors} \nonumber \\ &= \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} \\[0.7em] \frac{\partial L}{\partial z_{1,2}} \\[0.7em] \frac{\partial L}{\partial z_{2,1}} \\[0.7em] \frac{\partial L}{\partial z_{2,2}} \\[0.7em] \frac{\partial L}{\partial z_{3,1}} \\[0.7em] \frac{\partial L}{\partial z_{3,2}} \\[0.7em] \end{bmatrix} \label{dXAsColumnVector_matrix_addition} \end{flalign} \noindent Reshaping column vector in equation \ref{dXAsColumnVector_matrix_addition} as a matrix of shape $\matr{X}$, we get: \begin{flalign} \frac{\partial L}{\partial \matr{X}} &= \underbrace{ \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} & \frac{\partial L}{\partial z_{1,2}} \\[0.7em] \frac{\partial L}{\partial z_{2,1}} & \frac{\partial L}{\partial z_{2,2}} \\[0.7em] \frac{\partial L}{\partial z_{3,1}} & \frac{\partial L}{\partial z_{3,2}} \\[0.7em] \end{bmatrix}}_{\frac{\partial L}{\partial \matr{Z}}} & \nonumber \\ &= \frac{\partial L}{\partial \matr{Z}} \end{flalign} \subsubsection{Computing $\frac{\partial L}{\partial \matr{Y}}$} To compute $\frac{\partial L}{\partial \matr{Y}}$, we need to compute $\frac{\partial \matr{Z}}{\partial \matr{Y}}$. To make it easy for us to think about and capture the Jacobian in a two dimensional matrix (as opposed to a tensor), we will reshape matrices $\matr{X}$, $\matr{Y}$ and $\matr{Z}$ as column vectors, and compute Jacobians on them. Once we have computed the column vector corresponding to $\frac{\partial L}{\partial \matr{Y}}$, we will reshape it back to a matrix with the same shape as $\matr{Y}$. \begin{flalign} \frac{\partial \matr{Z}}{\partial \matr{Y}} &= \begin{bmatrix} \frac{\partial z_{1,1}}{\partial y_{1,1}} & \frac{\partial z_{1,2}}{\partial y_{1,1}} & \frac{\partial z_{2,1}}{\partial y_{1,1}} & \frac{\partial z_{2,2}}{\partial y_{1,1}} & \frac{\partial z_{3,1}}{\partial y_{1,1}} & \frac{\partial z_{3,2}}{\partial y_{1,1}}\\[0.7em] \frac{\partial z_{1,1}}{\partial y_{1,2}} & \frac{\partial z_{1,2}}{\partial y_{1,2}} & \frac{\partial z_{2,1}}{\partial y_{1,2}} & \frac{\partial z_{2,2}}{\partial y_{1,2}} & \frac{\partial z_{3,1}}{\partial y_{1,2}} & \frac{\partial z_{3,2}}{\partial y_{1,2}}\\[0.7em] \frac{\partial z_{1,1}}{\partial y_{2,1}} & \frac{\partial z_{1,2}}{\partial y_{2,1}} & \frac{\partial z_{2,1}}{\partial y_{2,1}} & \frac{\partial z_{2,2}}{\partial y_{2,1}} & \frac{\partial z_{3,1}}{\partial y_{2,1}} & \frac{\partial z_{3,2}}{\partial y_{2,1}}\\[0.7em] \frac{\partial z_{1,1}}{\partial y_{2,2}} & \frac{\partial z_{1,2}}{\partial y_{2,2}} & \frac{\partial z_{2,1}}{\partial y_{2,2}} & \frac{\partial z_{2,2}}{\partial y_{2,2}} & \frac{\partial z_{3,1}}{\partial y_{2,2}} & \frac{\partial z_{3,2}}{\partial y_{2,2}}\\[0.7em] \frac{\partial z_{1,1}}{\partial y_{3,1}} & \frac{\partial z_{1,2}}{\partial y_{3,1}} & \frac{\partial z_{2,1}}{\partial y_{3,1}} & \frac{\partial z_{2,2}}{\partial y_{3,1}} & \frac{\partial z_{3,1}}{\partial y_{3,1}} & \frac{\partial z_{3,2}}{\partial y_{3,1}}\\[0.7em] \frac{\partial z_{1,1}}{\partial y_{3,2}} & \frac{\partial z_{1,2}}{\partial y_{3,2}} & \frac{\partial z_{2,1}}{\partial y_{3,2}} & \frac{\partial z_{2,2}}{\partial y_{3,2}} & \frac{\partial z_{3,1}}{\partial y_{3,2}} & \frac{\partial z_{3,2}}{\partial y_{3,2}}\\[0.7em] \end{bmatrix} & \longeqncomment{$\matr{Y}$, $\matr{Z}$ are being treated as column vectors.}{Therefore, $\frac{\partial \matr{Z}}{\partial \matr{Y}}$ is of shape $6\times6$.} \nonumber \\ \label{dZbydY_matrix_addition} &= \begin{bmatrix} 1 & 0 & 0 & 0 & 0 & 0 \\%[0.5em] 0 & 1 & 0 & 0 & 0 & 0 \\%[0.5em] 0 & 0 & 1 & 0 & 0 & 0 \\%[0.5em] 0 & 0 & 0 & 1 & 0 & 0 \\%[0.5em] 0 & 0 & 0 & 0 & 1 & 0 \\%[0.5em] 0 & 0 & 0 & 0 & 0 & 1 \\%[0.5em] \end{bmatrix} \end{flalign} \noindent Plugging equations \ref{dZbydY_matrix_addition} and \ref{dZAsColumnVector_matrix_addition} into equation \ref{dY_matrix_addition}, we get: \begin{flalign} \frac{\partial L}{\partial \matr{Y}} &= \begin{bmatrix} 1 & 0 & 0 & 0 & 0 & 0 \\%[0.5em] 0 & 1 & 0 & 0 & 0 & 0 \\%[0.5em] 0 & 0 & 1 & 0 & 0 & 0 \\%[0.5em] 0 & 0 & 0 & 1 & 0 & 0 \\%[0.5em] 0 & 0 & 0 & 0 & 1 & 0 \\%[0.5em] 0 & 0 & 0 & 0 & 0 & 1 \\%[0.5em] \end{bmatrix} \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} \\[0.7em] \frac{\partial L}{\partial z_{1,2}} \\[0.7em] \frac{\partial L}{\partial z_{2,1}} \\[0.7em] \frac{\partial L}{\partial z_{2,2}} \\[0.7em] \frac{\partial L}{\partial z_{3,1}} \\[0.7em] \frac{\partial L}{\partial z_{3,2}} \\[0.7em] \end{bmatrix} & \eqncomment{$\matr{Y}$, $\matr{Z}$ and $\frac{\partial L}{\partial \matr{Z}}$ are being treated as column vectors} \nonumber \\ &= \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} \\[0.7em] \frac{\partial L}{\partial z_{1,2}} \\[0.7em] \frac{\partial L}{\partial z_{2,1}} \\[0.7em] \frac{\partial L}{\partial z_{2,2}} \\[0.7em] \frac{\partial L}{\partial z_{3,1}} \\[0.7em] \frac{\partial L}{\partial z_{3,2}} \\[0.7em] \end{bmatrix} \label{dYAsColumnVector_matrix_addition} \end{flalign} \noindent Reshaping column vector in equation \ref{dYAsColumnVector_matrix_addition} as a matrix of shape $\matr{Y}$, we get: \begin{flalign} \frac{\partial L}{\partial \matr{Y}} &= \underbrace{ \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} & \frac{\partial L}{\partial z_{1,2}} \\[0.7em] \frac{\partial L}{\partial z_{2,1}} & \frac{\partial L}{\partial z_{2,2}} \\[0.7em] \frac{\partial L}{\partial z_{3,1}} & \frac{\partial L}{\partial z_{3,2}} \\[0.7em] \end{bmatrix}}_{\frac{\partial L}{\partial \matr{Z}}} & \nonumber \\ &= \frac{\partial L}{\partial \matr{Z}} \end{flalign} \section{Transpose} \subsection{Forward Pass} Suppose we are given a matrix $\matr{X}$ of shape $3 \times 2$. Let $\matr{Z} = \transpose{\matr{X}}$. $\matr{Z}$ will be of shape $2 \times 3$. \begin{flalign} \matr{X} &= \begin{bmatrix} x_{1,1} & x_{1,2} \\%[0.5em] x_{2,1} & x_{2,2} \\%[0.5em] x_{3,1} & x_{3,2} \\%[0.5em] \end{bmatrix} & \nonumber \end{flalign} \noindent $\matr{Z}$ can be expressed as: \begin{flalign} \matr{Z} &= \begin{bmatrix} z_{1,1} & z_{1,2} & z_{1,3}\\%[0.5em] z_{2,1} & z_{2,2} & z_{2,3}\\%[0.5em] \end{bmatrix} & \nonumber \\ &= \begin{bmatrix} x_{1,1} & x_{2,1} & x_{3,1} \\%[0.5em] x_{1,2} & x_{2,2} & x_{3,2} \\%[0.5em] \end{bmatrix} \nonumber \end{flalign} \subsection{Backward Pass} We have $\frac{\partial L}{\partial \matr{Z}}$ of shape $2 \times 3$. \begin{flalign} \frac{\partial L}{\partial \matr{Z}} &= \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} & \frac{\partial L}{\partial z_{1,2}} & \frac{\partial L}{\partial z_{1,3}} \\[0.5em] \frac{\partial L}{\partial z_{2,1}} & \frac{\partial L}{\partial z_{2,2}} & \frac{\partial L}{\partial z_{2,3}} \\[0.5em] \end{bmatrix} & \eqncomment{$\frac{\partial L}{\partial \matr{Z}}$ is the same shape as $\matr{Z}$ as $L$ is a scalar} \label{dZ_transpose} \end{flalign} \noindent We now need to compute $\frac{\partial L}{\partial \matr{X}}$. Using chain rule, we get: \begin{flalign} \label{dX_transpose} \frac{\partial L}{\partial \matr{X}} &= \frac{\partial \matr{Z}}{\partial \matr{X}}\frac{\partial L}{\partial \matr{Z}} & \end{flalign} \subsubsection{Computing $\frac{\partial L}{\partial \matr{X}}$} To compute $\frac{\partial L}{\partial \matr{X}}$, we need to compute $\frac{\partial \matr{Z}}{\partial \matr{X}}$. To make it easy for us to think about and capture the Jacobian in a two dimensional matrix (as opposed to a tensor), we will reshape matrices $\matr{X}$ and $\matr{Z}$ as column vectors, and compute Jacobians on them. Once we have computed the column vector corresponding to $\frac{\partial L}{\partial \matr{X}}$, we will reshape it back to a matrix with the same shape as $\matr{X}$. \begin{flalign} \frac{\partial \matr{Z}}{\partial \matr{X}} &= \begin{bmatrix} \frac{\partial z_{1,1}}{\partial x_{1,1}} & \frac{\partial z_{1,2}}{\partial x_{1,1}} & \frac{\partial z_{1,3}}{\partial x_{1,1}} & \frac{\partial z_{2,1}}{\partial x_{1,1}} & \frac{\partial z_{2,2}}{\partial x_{1,1}} & \frac{\partial z_{3,3}}{\partial x_{1,1}}\\[0.7em] \frac{\partial z_{1,1}}{\partial x_{1,2}} & \frac{\partial z_{1,2}}{\partial x_{1,2}} & \frac{\partial z_{1,3}}{\partial x_{1,2}} & \frac{\partial z_{2,1}}{\partial x_{1,2}} & \frac{\partial z_{2,2}}{\partial x_{1,2}} & \frac{\partial z_{3,3}}{\partial x_{1,2}}\\[0.7em] \frac{\partial z_{1,1}}{\partial x_{2,1}} & \frac{\partial z_{1,2}}{\partial x_{2,1}} & \frac{\partial z_{1,3}}{\partial x_{2,1}} & \frac{\partial z_{2,1}}{\partial x_{2,1}} & \frac{\partial z_{2,2}}{\partial x_{2,1}} & \frac{\partial z_{3,3}}{\partial x_{2,1}}\\[0.7em] \frac{\partial z_{1,1}}{\partial x_{2,2}} & \frac{\partial z_{1,2}}{\partial x_{2,2}} & \frac{\partial z_{1,3}}{\partial x_{2,2}} & \frac{\partial z_{2,1}}{\partial x_{2,2}} & \frac{\partial z_{2,2}}{\partial x_{2,2}} & \frac{\partial z_{3,3}}{\partial x_{2,2}}\\[0.7em] \frac{\partial z_{1,1}}{\partial x_{3,1}} & \frac{\partial z_{1,2}}{\partial x_{3,1}} & \frac{\partial z_{1,3}}{\partial x_{3,1}} & \frac{\partial z_{2,1}}{\partial x_{3,1}} & \frac{\partial z_{2,2}}{\partial x_{3,1}} & \frac{\partial z_{3,3}}{\partial x_{3,1}}\\[0.7em] \frac{\partial z_{1,1}}{\partial x_{3,2}} & \frac{\partial z_{1,2}}{\partial x_{3,2}} & \frac{\partial z_{1,3}}{\partial x_{3,2}} & \frac{\partial z_{2,1}}{\partial x_{3,2}} & \frac{\partial z_{2,2}}{\partial x_{3,2}} & \frac{\partial z_{3,3}}{\partial x_{3,2}}\\[0.7em] \end{bmatrix} & \longeqncomment{$\matr{X}$, $\matr{Z}$ are being treated as column vectors.}{Therefore, $\frac{\partial \matr{Z}}{\partial \matr{X}}$ is of shape $6\times6$.} \nonumber \\ \label{dZbydX_transpose} &= \begin{bmatrix} 1 & 0 & 0 & 0 & 0 & 0 \\%[0.5em] 0 & 0 & 0 & 1 & 0 & 0 \\%[0.5em] 0 & 1 & 0 & 0 & 0 & 0 \\%[0.5em] 0 & 0 & 0 & 0 & 1 & 0 \\%[0.5em] 0 & 0 & 1 & 0 & 0 & 0 \\%[0.5em] 0 & 0 & 0 & 0 & 0 & 1 \\%[0.5em] \end{bmatrix} \end{flalign} \noindent Now, $\frac{\partial L}{\partial \matr{Z}}$ in equation \ref{dZ_transpose} expressed as a column vector will be: \begin{flalign} \label{dZAsColumnVector_transpose} \frac{\partial L}{\partial \matr{Z}} &= \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} \\[0.7em] \frac{\partial L}{\partial z_{1,2}} \\[0.7em] \frac{\partial L}{\partial z_{1,3}} \\[0.7em] \frac{\partial L}{\partial z_{2,1}} \\[0.7em] \frac{\partial L}{\partial z_{2,2}} \\[0.7em] \frac{\partial L}{\partial z_{2,3}} \\[0.7em] \end{bmatrix} & \eqncomment{Reshaping $\frac{\partial L}{\partial \matr{Z}}$ from shape $2 \times 3$ to $6 \times 1$} \end{flalign} \noindent Plugging equations \ref{dZbydX_transpose} and \ref{dZAsColumnVector_transpose} into equation \ref{dX_transpose}, we get: \begin{flalign} \frac{\partial L}{\partial \matr{X}} &= \frac{\partial \matr{Z}}{\partial \matr{X}}\frac{\partial L}{\partial \matr{Z}} & \nonumber \\ &= \begin{bmatrix} 1 & 0 & 0 & 0 & 0 & 0 \\%[0.5em] 0 & 0 & 0 & 1 & 0 & 0 \\%[0.5em] 0 & 1 & 0 & 0 & 0 & 0 \\%[0.5em] 0 & 0 & 0 & 0 & 1 & 0 \\%[0.5em] 0 & 0 & 1 & 0 & 0 & 0 \\%[0.5em] 0 & 0 & 0 & 0 & 0 & 1 \\%[0.5em] \end{bmatrix} \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} \\[0.7em] \frac{\partial L}{\partial z_{1,2}} \\[0.7em] \frac{\partial L}{\partial z_{1,3}} \\[0.7em] \frac{\partial L}{\partial z_{2,1}} \\[0.7em] \frac{\partial L}{\partial z_{2,2}} \\[0.7em] \frac{\partial L}{\partial z_{2,3}} \\[0.7em] \end{bmatrix} & \eqncomment{$\matr{X}$, $\matr{Z}$ and $\frac{\partial L}{\partial \matr{Z}}$ are being treated as column vectors} \nonumber \\ &= \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} \\[0.7em] \frac{\partial L}{\partial z_{2,1}} \\[0.7em] \frac{\partial L}{\partial z_{1,2}} \\[0.7em] \frac{\partial L}{\partial z_{2,2}} \\[0.7em] \frac{\partial L}{\partial z_{1,3}} \\[0.7em] \frac{\partial L}{\partial z_{2,3}} \\[0.7em] \end{bmatrix} \label{dXAsColumnVector_transpose} \end{flalign} \noindent Reshaping column vector in equation \ref{dXAsColumnVector_transpose} as a matrix of shape $\matr{X}$, we get: \begin{flalign} \frac{\partial L}{\partial \matr{X}} &= \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} & \frac{\partial L}{\partial z_{2,1}} \\[0.7em] \frac{\partial L}{\partial z_{1,2}} & \frac{\partial L}{\partial z_{2,2}} \\[0.7em] \frac{\partial L}{\partial z_{1,3}} & \frac{\partial L}{\partial z_{2,3}} \\[0.7em] \end{bmatrix} & \nonumber \\ &= \underbrace{ \transpose{ \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} & \frac{\partial L}{\partial z_{1,2}} & \frac{\partial L}{\partial z_{1,3}} \\[0.5em] \frac{\partial L}{\partial z_{2,1}} & \frac{\partial L}{\partial z_{2,2}} & \frac{\partial L}{\partial z_{2,3}} \\[0.5em] \end{bmatrix}}}_{\transpose{\frac{\partial L}{\partial \matr{Z}}}} \nonumber \\ &= \transpose{\frac{\partial L}{\partial \matr{Z}}} \end{flalign} \section{Sum along axis=0} \subsection{Forward Pass} Suppose we are given a matrix $\matr{X}$ of shape $3 \times 2$. Let $\vecr{z}$ = \verb|np.sum(|${\matr{X}}$\verb|, axis=0)|. $\vecr{z}$ will be of shape $1 \times 2$. \begin{flalign} \matr{X} &= \begin{bmatrix} x_{1,1} & x_{1,2} \\%[0.5em] x_{2,1} & x_{2,2} \\%[0.5em] x_{3,1} & x_{3,2} \\%[0.5em] \end{bmatrix} & \nonumber \end{flalign} \noindent $\vecr{z}$ can be expressed as: \begin{flalign} \vecr{z} &= \begin{bmatrix} z_{1,1} & z_{1,2} \\%[0.5em] \end{bmatrix} & \nonumber \\ &= \begin{bmatrix} x_{1,1} + x_{2,1} + x_{3,1} & x_{1,2} + x_{2,2} + x_{3,2} \\%[0.5em] \end{bmatrix} \nonumber \end{flalign} \subsection{Backward Pass} We have $\frac{\partial L}{\partial \vecr{z}}$ of shape $1 \times 2$. \begin{flalign} \frac{\partial L}{\partial \vecr{z}} &= \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} & \frac{\partial L}{\partial z_{1,2}} \\[0.3em] \end{bmatrix} & \eqncomment{$\frac{\partial L}{\partial \vecr{z}}$ is the same shape as $\vecr{z}$ as $L$ is a scalar} \label{dZ_sum_along_axis_0} \end{flalign} \noindent We now need to compute $\frac{\partial L}{\partial \matr{X}}$. Using chain rule, we get: \begin{flalign} \label{dX_sum_along_axis_0} \frac{\partial L}{\partial \matr{X}} &= \frac{\partial \vecr{z}}{\partial \matr{X}}\frac{\partial L}{\partial \vecr{z}} & \end{flalign} \subsubsection{Computing $\frac{\partial L}{\partial \matr{X}}$} To compute $\frac{\partial L}{\partial \matr{X}}$, we need to compute $\frac{\partial \vecr{z}}{\partial \matr{X}}$. To make it easy for us to think about and capture the Jacobian in a two dimensional matrix (as opposed to a tensor), we will reshape matrix $\matr{X}$ as well as vector $\vecr{z}$ as column vectors, and compute Jacobians on them. Once we have computed the column vector corresponding to $\frac{\partial L}{\partial \matr{X}}$, we will reshape it back to a matrix with the same shape as $\matr{X}$. \begin{flalign} \frac{\partial \vecr{z}}{\partial \matr{X}} &= \begin{bmatrix} \frac{\partial z_{1,1}}{\partial x_{1,1}} & \frac{\partial z_{1,2}}{\partial x_{1,1}} \\[0.7em] \frac{\partial z_{1,1}}{\partial x_{1,2}} & \frac{\partial z_{1,2}}{\partial x_{1,2}} \\[0.7em] \frac{\partial z_{1,1}}{\partial x_{2,1}} & \frac{\partial z_{1,2}}{\partial x_{2,1}} \\[0.7em] \frac{\partial z_{1,1}}{\partial x_{2,2}} & \frac{\partial z_{1,2}}{\partial x_{2,2}} \\[0.7em] \frac{\partial z_{1,1}}{\partial x_{3,1}} & \frac{\partial z_{1,2}}{\partial x_{3,1}} \\[0.7em] \frac{\partial z_{1,1}}{\partial x_{3,2}} & \frac{\partial z_{1,2}}{\partial x_{3,2}} \\[0.7em] \end{bmatrix} & \longeqncomment{$\matr{X}$, $\vecr{z}$ are being treated as column vectors.}{Therefore, $\frac{\partial \vecr{z}}{\partial \matr{X}}$ is of shape $6\times2$.} \nonumber \\ \label{dZbydX_sum_along_axis_0} &= \begin{bmatrix} 1 & 0 \\%[0.5em] 0 & 1 \\%[0.5em] 1 & 0 \\%[0.5em] 0 & 1 \\%[0.5em] 1 & 0 \\%[0.5em] 0 & 1 \\%[0.5em] \end{bmatrix} \end{flalign} \noindent Now, $\frac{\partial L}{\partial \vecr{z}}$ in equation \ref{dZ_sum_along_axis_0} expressed as a column vector will be: \begin{flalign} \label{dZAsColumnVector_sum_along_axis_0} \frac{\partial L}{\partial \vecr{z}} &= \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} \\[0.7em] \frac{\partial L}{\partial z_{1,2}} \\[0.7em] \end{bmatrix} & & \eqncomment{Reshaping $\frac{\partial L}{\partial \vecr{z}}$ from shape $1 \times 2$ to $2 \times 1$} \end{flalign} \noindent Plugging equations \ref{dZbydX_sum_along_axis_0} and \ref{dZAsColumnVector_sum_along_axis_0} into equation \ref{dX_sum_along_axis_0}, we get: \begin{flalign} \frac{\partial L}{\partial \matr{X}} &= \frac{\partial \vecr{z}}{\partial \matr{X}}\frac{\partial L}{\partial \vecr{z}} & \nonumber \\ &= \begin{bmatrix} 1 & 0 \\%[0.5em] 0 & 1 \\%[0.5em] 1 & 0 \\%[0.5em] 0 & 1 \\%[0.5em] 1 & 0 \\%[0.5em] 0 & 1 \\%[0.5em] \end{bmatrix} \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} \\[0.7em] \frac{\partial L}{\partial z_{1,2}} \\[0.7em] \end{bmatrix} & \eqncomment{$\matr{X}$, $\vecr{z}$ and $\frac{\partial L}{\partial \vecr{z}}$ are being treated as column vectors} \nonumber \\ &= \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} \\[0.7em] \frac{\partial L}{\partial z_{1,2}} \\[0.7em] \frac{\partial L}{\partial z_{1,1}} \\[0.7em] \frac{\partial L}{\partial z_{1,2}} \\[0.7em] \frac{\partial L}{\partial z_{1,1}} \\[0.7em] \frac{\partial L}{\partial z_{1,2}} \\[0.7em] \end{bmatrix} \label{dXAsColumnVector_sum_along_axis_0} \end{flalign} \noindent Reshaping column vector in equation \ref{dXAsColumnVector_sum_along_axis_0} as a matrix of shape $\matr{X}$, we get: \begin{flalign} \frac{\partial L}{\partial \matr{X}} &= \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} & \frac{\partial L}{\partial z_{1,2}} \\[0.7em] \frac{\partial L}{\partial z_{1,1}} & \frac{\partial L}{\partial z_{1,2}} \\[0.7em] \frac{\partial L}{\partial z_{1,1}} & \frac{\partial L}{\partial z_{1,2}} \\[0.7em] \end{bmatrix} \nonumber \\ &= \begin{bmatrix} 1 \\ 1 \\ 1 \\ \end{bmatrix} \underbrace{ \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} & \frac{\partial L}{\partial z_{1,2}} \\[0.3em] \end{bmatrix}}_{\frac{\partial L}{\partial \vecr{z}}} & \eqncomment{Decomposing into a matmul operation} \nonumber \\ &= \mathbf{1}_{3,1} \frac{\partial L}{\partial \vecr{z}} \nonumber & \eqncomment{We are using a bold 1 namely $\mathbf{1}$ to denote matrix of ones} \\ &= \mathbf{1}_{\text{rows}(\matr{X}),1} \frac{\partial L}{\partial \vecr{z}} & \eqncomment{Generalizing beyond our considered example} \end{flalign} \section{Sum along axis=1} \subsection{Forward Pass} Suppose we are given a matrix $\matr{X}$ of shape $3 \times 2$. Let $\vecr{z}$ = \verb|np.sum(|${\matr{X}}$\verb|, axis=1)|. $\vecr{z}$ will be of shape $3 \times 1$. \begin{flalign} \matr{X} &= \begin{bmatrix} x_{1,1} & x_{1,2} \\%[0.5em] x_{2,1} & x_{2,2} \\%[0.5em] x_{3,1} & x_{3,2} \\%[0.5em] \end{bmatrix} & \nonumber \end{flalign} \noindent $\vecr{z}$ can be expressed as: \begin{flalign} \vecr{z} &= \begin{bmatrix} z_{1,1} \\ z_{2,1} \\ z_{3,1} \\ \end{bmatrix} & \nonumber \\ &= \begin{bmatrix} x_{1,1} + x_{1,2} \\ x_{2,1} + x_{2,2} \\ x_{3,1} + x_{3,2} \\ \end{bmatrix} \nonumber \end{flalign} \subsection{Backward Pass} We have $\frac{\partial L}{\partial \vecr{z}}$ of shape $3 \times 1$. \begin{flalign} \frac{\partial L}{\partial \vecr{z}} &= \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} \\[0.7em] \frac{\partial L}{\partial z_{2,1}} \\[0.7em] \frac{\partial L}{\partial z_{3,1}} \\[0.7em] \end{bmatrix} & \eqncomment{$\frac{\partial L}{\partial \vecr{z}}$ is the same shape as $\vecr{z}$ as $L$ is a scalar} \label{dZAsColumnVector_sum_along_axis_1} \end{flalign} \noindent We now need to compute $\frac{\partial L}{\partial \matr{X}}$. Using chain rule, we get: \begin{flalign} \label{dX_sum_along_axis_1} \frac{\partial L}{\partial \matr{X}} &= \frac{\partial \vecr{z}}{\partial \matr{X}}\frac{\partial L}{\partial \vecr{z}} & \end{flalign} \subsubsection{Computing $\frac{\partial L}{\partial \matr{X}}$} To compute $\frac{\partial L}{\partial \matr{X}}$, we need to compute $\frac{\partial \vecr{z}}{\partial \matr{X}}$. To make it easy for us to think about and capture the Jacobian in a two dimensional matrix (as opposed to a tensor), we will reshape matrix $\matr{X}$ as a column vector, and compute Jacobians on the column vectors instead. Once we have computed the column vector corresponding to $\frac{\partial L}{\partial \matr{X}}$, we will reshape it back to a matrix with the same shape as $\matr{X}$. \begin{flalign} \frac{\partial \vecr{z}}{\partial \matr{X}} &= \begin{bmatrix} \frac{\partial z_{1,1}}{\partial x_{1,1}} & \frac{\partial z_{2,1}}{\partial x_{1,1}} & \frac{\partial z_{3,1}}{\partial x_{1,1}}\\[0.7em] \frac{\partial z_{1,1}}{\partial x_{1,2}} & \frac{\partial z_{2,1}}{\partial x_{1,2}} & \frac{\partial z_{3,1}}{\partial x_{1,2}} \\[0.7em] \frac{\partial z_{1,1}}{\partial x_{2,1}} & \frac{\partial z_{2,1}}{\partial x_{2,1}} & \frac{\partial z_{3,1}}{\partial x_{2,1}} \\[0.7em] \frac{\partial z_{1,1}}{\partial x_{2,2}} & \frac{\partial z_{2,1}}{\partial x_{2,2}} & \frac{\partial z_{3,1}}{\partial x_{2,2}} \\[0.7em] \frac{\partial z_{1,1}}{\partial x_{3,1}} & \frac{\partial z_{2,1}}{\partial x_{3,1}} & \frac{\partial z_{3,1}}{\partial x_{3,1}} \\[0.7em] \frac{\partial z_{1,1}}{\partial x_{3,2}} & \frac{\partial z_{2,1}}{\partial x_{3,2}} & \frac{\partial z_{3,1}}{\partial x_{3,2}} \\[0.7em] \end{bmatrix} & \longeqncomment{$\matr{X}$ is being treated as a column vector.}{Therefore, $\frac{\partial \vecr{z}}{\partial \matr{X}}$ is of shape $6\times3$.} \nonumber \\ \label{dZbydX_sum_along_axis_1} &= \begin{bmatrix} 1 & 0 & 0 \\%[0.5em] 1 & 0 & 0 \\%[0.5em] 0 & 1 & 0 \\%[0.5em] 0 & 1 & 0 \\%[0.5em] 0 & 0 & 1 \\%[0.5em] 0 & 0 & 1 \\%[0.5em] \end{bmatrix} \end{flalign} \noindent Plugging equations \ref{dZbydX_sum_along_axis_1} and \ref{dZAsColumnVector_sum_along_axis_1} into equation \ref{dX_sum_along_axis_1}, we get: \begin{flalign} \frac{\partial L}{\partial \matr{X}} &= \frac{\partial \vecr{z}}{\partial \matr{X}}\frac{\partial L}{\partial \vecr{z}} & \nonumber \\ &= \begin{bmatrix} 1 & 0 & 0 \\%[0.5em] 1 & 0 & 0 \\%[0.5em] 0 & 1 & 0 \\%[0.5em] 0 & 1 & 0 \\%[0.5em] 0 & 0 & 1 \\%[0.5em] 0 & 0 & 1 \\%[0.5em] \end{bmatrix} \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} \\[0.7em] \frac{\partial L}{\partial z_{2,1}} \\[0.7em] \frac{\partial L}{\partial z_{3,1}} \\[0.7em] \end{bmatrix} & \eqncomment{$\matr{X}$ and $\frac{\partial L}{\partial \vecr{z}}$ are being treated as column vectors} \nonumber \\ &= \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} \\[0.7em] \frac{\partial L}{\partial z_{1,1}} \\[0.7em] \frac{\partial L}{\partial z_{2,1}} \\[0.7em] \frac{\partial L}{\partial z_{2,1}} \\[0.7em] \frac{\partial L}{\partial z_{3,1}} \\[0.7em] \frac{\partial L}{\partial z_{3,1}} \\[0.7em] \end{bmatrix} \label{dXAsColumnVector_sum_along_axis_1} \end{flalign} \noindent Reshaping column vector in equation \ref{dXAsColumnVector_sum_along_axis_1} as a matrix of shape $\matr{X}$, we get: \begin{flalign} \frac{\partial L}{\partial \matr{X}} &= \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} & \frac{\partial L}{\partial z_{1,1}} \\[0.7em] \frac{\partial L}{\partial z_{2,1}} & \frac{\partial L}{\partial z_{2,1}} \\[0.7em] \frac{\partial L}{\partial z_{3,1}} & \frac{\partial L}{\partial z_{3,1}} \\[0.7em] \end{bmatrix} \nonumber \\ &= \underbrace{ \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} \\[0.7em] \frac{\partial L}{\partial z_{2,1}} \\[0.7em] \frac{\partial L}{\partial z_{3,1}} \\[0.7em] \end{bmatrix}}_{\frac{\partial L}{\partial \vecr{z}}} \begin{bmatrix} 1 & 1 \\%[0.3em] \end{bmatrix} & \eqncomment{Decomposing into a matmul operation} \nonumber \\ &= \frac{\partial L}{\partial \vecr{z}} \mathbf{1}_{1,2} & \eqncomment{We are using a bold 1 namely $\mathbf{1}$ to denote matrix of ones} \nonumber \\ &= \frac{\partial L}{\partial \vecr{z}} \mathbf{1}_{1, \text{cols}(\matr{X})} & \eqncomment{Generalizing beyond our considered example} \end{flalign} \section{Broadcasting a column vector} \subsection{Forward Pass} Suppose we are given a vector $\vecr{x}$ of shape $3 \times 1$. Let $\matr{Z} = \vecr{x} \mathbf{1}_{1,\text{C}}$ where $\mathbf{1}$ denotes a matrix of ones. $\matr{Z}$ will be of shape $3 \times \text{C}$. Let us suppose that C = 2. \begin{flalign} \vecr{x} &= \begin{bmatrix} x_{1,1} \\%[0.5em] x_{2,1} \\%[0.5em] x_{3,1} \\%[0.5em] \end{bmatrix} & \nonumber \end{flalign} \noindent $\matr{Z}$ can be expressed as: \begin{flalign} \matr{Z} &= \begin{bmatrix} z_{1,1} & z_{1,2} \\ z_{2,1} & z_{2,2} \\ z_{3,1} & z_{2,3} \\ \end{bmatrix} & \nonumber \\ &= \begin{bmatrix} x_{1,1} & x_{1,1} \\ x_{2,1} & x_{2,1} \\ x_{3,1} & x_{3,1} \\ \end{bmatrix} \nonumber \end{flalign} \subsection{Backward Pass} We have $\frac{\partial L}{\partial \matr{Z}}$ of shape $3 \times 2$. \begin{flalign} \frac{\partial L}{\partial \matr{Z}} &= \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} & \frac{\partial L}{\partial z_{1,2}} \\[0.7em] \frac{\partial L}{\partial z_{2,1}} & \frac{\partial L}{\partial z_{2,2}} \\[0.7em] \frac{\partial L}{\partial z_{3,1}} & \frac{\partial L}{\partial z_{3,2}} \\[0.7em] \end{bmatrix} \label{dZ_broadcast_column_vector} & \eqncomment{$\frac{\partial L}{\partial \vecr{z}}$ is the same shape as $\vecr{z}$ as $L$ is a scalar} \end{flalign} \noindent We now need to compute $\frac{\partial L}{\partial \vecr{x}}$. Using chain rule, we get: \begin{flalign} \label{dX_broadcast_column_vector} \frac{\partial L}{\partial \vecr{x}} &= \frac{\partial \matr{Z}}{\partial \vecr{x}}\frac{\partial L}{\partial \matr{Z}} & \end{flalign} \subsubsection{Computing $\frac{\partial L}{\partial \vecr{x}}$} To compute $\frac{\partial L}{\partial \vecr{x}}$, we need to compute $\frac{\partial \matr{Z}}{\partial \vecr{x}}$. To make it easy for us to think about and capture the Jacobian in a two dimensional matrix (as opposed to a tensor), we will reshape matrix $\matr{Z}$ as a column vector, and compute Jacobians on the column vectors instead. \begin{flalign} \frac{\partial \matr{Z}}{\partial \vecr{x}} &= \begin{bmatrix} \frac{\partial z_{1,1}}{\partial x_{1,1}} & \frac{\partial z_{1,2}}{\partial x_{1,1}} & \frac{\partial z_{2,1}}{\partial x_{1,1}} & \frac{\partial z_{2,2}}{\partial x_{1,1}} & \frac{\partial z_{3,1}}{\partial x_{1,1}} & \frac{\partial z_{3,2}}{\partial x_{1,1}} \\[0.7em] \frac{\partial z_{1,1}}{\partial x_{2,1}} & \frac{\partial z_{1,2}}{\partial x_{2,1}} & \frac{\partial z_{2,1}}{\partial x_{2,1}} & \frac{\partial z_{2,2}}{\partial x_{2,1}} & \frac{\partial z_{3,1}}{\partial x_{2,1}} & \frac{\partial z_{3,2}}{\partial x_{2,1}} \\[0.7em] \frac{\partial z_{1,1}}{\partial x_{3,1}} & \frac{\partial z_{1,2}}{\partial x_{3,1}} & \frac{\partial z_{2,1}}{\partial x_{3,1}} & \frac{\partial z_{2,2}}{\partial x_{3,1}} & \frac{\partial z_{3,1}}{\partial x_{3,1}} & \frac{\partial z_{3,2}}{\partial x_{3,1}} \\[0.7em] \end{bmatrix} & \longeqncomment{$\matr{Z}$ is being treated as a column vector.}{Therefore, $\frac{\partial \matr{Z}}{\partial \vecr{x}}$ is of shape $3\times6$.} \nonumber \\ \label{dZbydX_broadcast_column_vector} &= \begin{bmatrix} 1 & 1 & 0 & 0 & 0 & 0\\%[0.5em] 0 & 0 & 1 & 1 & 0 & 0\\%[0.5em] 0 & 0 & 0 & 0 & 1 & 1\\%[0.5em] \end{bmatrix} \end{flalign} \noindent Now, $\frac{\partial L}{\partial \matr{Z}}$ in equation \ref{dZ_broadcast_column_vector} expressed as a column vector will be: \begin{flalign} \label{dZAsColumnVector_broadcast_column_vector} \frac{\partial L}{\partial \matr{Z}} &= \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} \\[0.7em] \frac{\partial L}{\partial z_{1,2}} \\[0.7em] \frac{\partial L}{\partial z_{2,1}} \\[0.7em] \frac{\partial L}{\partial z_{2,2}} \\[0.7em] \frac{\partial L}{\partial z_{3,1}} \\[0.7em] \frac{\partial L}{\partial z_{3,2}} \\[0.7em] \end{bmatrix} & \eqncomment{Reshaping $\frac{\partial L}{\partial \matr{Z}}$ from shape $3 \times 2$ to $6 \times 1$} \end{flalign} \noindent Plugging equations \ref{dZbydX_broadcast_column_vector} and \ref{dZAsColumnVector_broadcast_column_vector} into equation \ref{dX_broadcast_column_vector}, we get: \begin{flalign} \frac{\partial L}{\partial \vecr{x}} &= \frac{\partial \matr{Z}}{\partial \vecr{x}}\frac{\partial L}{\partial \matr{Z}} & \nonumber \\ &= \begin{bmatrix} 1 & 1 & 0 & 0 & 0 & 0\\%[0.5em] 0 & 0 & 1 & 1 & 0 & 0\\%[0.5em] 0 & 0 & 0 & 0 & 1 & 1\\%[0.5em] \end{bmatrix} \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} \\[0.7em] \frac{\partial L}{\partial z_{1,2}} \\[0.7em] \frac{\partial L}{\partial z_{2,1}} \\[0.7em] \frac{\partial L}{\partial z_{2,2}} \\[0.7em] \frac{\partial L}{\partial z_{3,1}} \\[0.7em] \frac{\partial L}{\partial z_{3,2}} \\[0.7em] \end{bmatrix} & \eqncomment{$\matr{Z}$ and $\frac{\partial L}{\partial \matr{Z}}$ are being treated as column vectors} \nonumber \\ &= \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} + \frac{\partial L}{\partial z_{1,2}} \\[0.7em] \frac{\partial L}{\partial z_{2,1}} + \frac{\partial L}{\partial z_{2,2}} \\[0.7em] \frac{\partial L}{\partial z_{3,1}} + \frac{\partial L}{\partial z_{3,2}} \\[0.7em] \end{bmatrix} \nonumber \\ &= \underbrace{ \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} & \frac{\partial L}{\partial z_{1,2}} \\[0.7em] \frac{\partial L}{\partial z_{2,1}} & \frac{\partial L}{\partial z_{2,2}} \\[0.7em] \frac{\partial L}{\partial z_{3,1}} & \frac{\partial L}{\partial z_{3,2}} \\[0.7em] \end{bmatrix}}_{\frac{\partial L}{\partial \matr{Z}} } \begin{bmatrix} 1 \\ 1 \\ \end{bmatrix} & \eqncomment{Decomposing into a matmul operation} \nonumber \\ &= \frac{\partial L}{\partial \matr{Z}} \mathbf{1}_{\text{2},1} & \eqncomment{We are using a bold 1 namely $\mathbf{1}$ to denote matrix of ones} \nonumber \\ &= \frac{\partial L}{\partial \matr{Z}} \mathbf{1}_{\text{C},1} & \eqncomment{Generalizing beyond our considered example} \nonumber \\ &= \mathtt{np.sum(} \matr{Z} \mathtt{, axis=1)} & \eqncomment{Using $\mathtt{NumPy}$ notation for brevity} \end{flalign} \section{Broadcasting a row vector} \subsection{Forward Pass} Suppose we are given a vector $\vecr{x}$ of shape $1 \times 3$. Let $\matr{Z} = \mathbf{1}_{\text{R},1} \vecr{x}$ where $\mathbf{1}$ denotes a matrix of ones. $\matr{Z}$ will be of shape $\text{R} \times 3$. Let us suppose that R = 2. \begin{flalign} \vecr{x} &= \begin{bmatrix} x_{1,1} & x_{1,2} & x_{1,3} \\%[0.5em] \end{bmatrix} & \nonumber \end{flalign} \noindent $\matr{Z}$ can be expressed as: \begin{flalign} \matr{Z} &= \begin{bmatrix} z_{1,1} & z_{1,2} & z_{1,3} \\ z_{2,1} & z_{2,2} & z_{2,3} \\ \end{bmatrix} & \nonumber \\ &= \begin{bmatrix} x_{1,1} & x_{1,2} & x_{1,3} \\%[0.5em] x_{1,1} & x_{1,2} & x_{1,3} \\%[0.5em] \end{bmatrix} \nonumber \end{flalign} \subsection{Backward Pass} We have $\frac{\partial L}{\partial \matr{Z}}$ of shape $2 \times 3$. \begin{flalign} \frac{\partial L}{\partial \matr{Z}} &= \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} & \frac{\partial L}{\partial z_{1,2}} & \frac{\partial L}{\partial z_{1,3}}\\[0.7em] \frac{\partial L}{\partial z_{2,1}} & \frac{\partial L}{\partial z_{2,2}} & \frac{\partial L}{\partial z_{2,3}}\\[0.7em] \end{bmatrix} & \eqncomment{$\frac{\partial L}{\partial \vecr{z}}$ is the same shape as $\vecr{z}$ as $L$ is a scalar} \label{dZ_broadcast_row_vector} \end{flalign} \noindent We now need to compute $\frac{\partial L}{\partial \vecr{x}}$. Using chain rule, we get: \begin{flalign} \label{dX_broadcast_row_vector} \frac{\partial L}{\partial \vecr{x}} &= \frac{\partial \matr{Z}}{\partial \vecr{x}}\frac{\partial L}{\partial \matr{Z}} & \end{flalign} \subsubsection{Computing $\frac{\partial L}{\partial \vecr{x}}$} To compute $\frac{\partial L}{\partial \vecr{x}}$, we need to compute $\frac{\partial \matr{Z}}{\partial \vecr{x}}$. To make it easy for us to think about and capture the Jacobian in a two dimensional matrix (as opposed to a tensor), we will reshape matrix $\matr{Z}$ as well as vector $\vecr{x}$ as a column vector, and compute Jacobians on the column vectors instead. \begin{flalign} \frac{\partial \matr{Z}}{\partial \vecr{x}} &= \begin{bmatrix} \frac{\partial z_{1,1}}{\partial x_{1,1}} & \frac{\partial z_{1,2}}{\partial x_{1,1}} & \frac{\partial z_{1,3}}{\partial x_{1,1}} & \frac{\partial z_{2,1}}{\partial x_{1,1}} & \frac{\partial z_{2,2}}{\partial x_{1,1}} & \frac{\partial z_{2,3}}{\partial x_{1,1}} \\[0.7em] \frac{\partial z_{1,1}}{\partial x_{1,2}} & \frac{\partial z_{1,2}}{\partial x_{1,2}} & \frac{\partial z_{1,3}}{\partial x_{1,2}} & \frac{\partial z_{2,1}}{\partial x_{1,2}} & \frac{\partial z_{2,2}}{\partial x_{1,2}} & \frac{\partial z_{2,3}}{\partial x_{1,2}} \\[0.7em] \frac{\partial z_{1,1}}{\partial x_{1,3}} & \frac{\partial z_{1,2}}{\partial x_{1,3}} & \frac{\partial z_{1,3}}{\partial x_{1,3}} & \frac{\partial z_{2,1}}{\partial x_{1,3}} & \frac{\partial z_{2,2}}{\partial x_{1,3}} & \frac{\partial z_{2,3}}{\partial x_{1,3}} \\[0.7em] \end{bmatrix} & \longeqncomment{$\matr{Z}$ and $\vecr{x}$ are being treated as column vectors.}{Therefore, $\frac{\partial \matr{Z}}{\partial \vecr{x}}$ is of shape $3\times6$.} \nonumber \\ \label{dZbydX_broadcast_row_vector} &= \begin{bmatrix} 1 & 0 & 0 & 1 & 0 & 0\\%[0.5em] 0 & 1 & 0 & 0 & 1 & 0\\%[0.5em] 0 & 0 & 1 & 0 & 0 & 1\\%[0.5em] \end{bmatrix} \end{flalign} \noindent Now, $\frac{\partial L}{\partial \matr{Z}}$ in equation \ref{dZ_broadcast_row_vector} expressed as a column vector will be: \begin{flalign} \label{dZAsColumnVector_broadcast_row_vector} \frac{\partial L}{\partial \matr{Z}} &= \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} \\[0.7em] \frac{\partial L}{\partial z_{1,2}} \\[0.7em] \frac{\partial L}{\partial z_{1,3}} \\[0.7em] \frac{\partial L}{\partial z_{2,1}} \\[0.7em] \frac{\partial L}{\partial z_{2,2}} \\[0.7em] \frac{\partial L}{\partial z_{2,3}} \\[0.7em] \end{bmatrix} & \eqncomment{Reshaping $\frac{\partial L}{\partial \matr{Z}}$ from shape $2 \times 3$ to $6 \times 1$} \end{flalign} \noindent Plugging equations \ref{dZbydX_broadcast_row_vector} and \ref{dZAsColumnVector_broadcast_row_vector} into equation \ref{dX_broadcast_row_vector}, we get: \begin{flalign} \frac{\partial L}{\partial \vecr{x}} &= \frac{\partial \matr{Z}}{\partial \vecr{x}}\frac{\partial L}{\partial \matr{Z}} & \nonumber \\ &= \begin{bmatrix} 1 & 0 & 0 & 1 & 0 & 0\\%[0.5em] 0 & 1 & 0 & 0 & 1 & 0\\%[0.5em] 0 & 0 & 1 & 0 & 0 & 1\\%[0.5em] \end{bmatrix} \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} \\[0.7em] \frac{\partial L}{\partial z_{1,2}} \\[0.7em] \frac{\partial L}{\partial z_{1,3}} \\[0.7em] \frac{\partial L}{\partial z_{2,1}} \\[0.7em] \frac{\partial L}{\partial z_{2,2}} \\[0.7em] \frac{\partial L}{\partial z_{2,3}} \\[0.7em] \end{bmatrix} & \eqncomment{$\matr{Z}$, $\vecr{x}$ and $\frac{\partial L}{\partial \matr{Z}}$ are being treated as column vectors} \nonumber \\ &= \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} + \frac{\partial L}{\partial z_{2,1}} \\[0.7em] \frac{\partial L}{\partial z_{1,2}} + \frac{\partial L}{\partial z_{2,2}} \\[0.7em] \frac{\partial L}{\partial z_{1,3}} + \frac{\partial L}{\partial z_{2,3}} \\[0.7em] \end{bmatrix} \label{dXAsColumnVector_broadcast_row_vector} \end{flalign} \noindent Now reshaping $\frac{\partial L}{\partial \vecr{x}}$ from column vector of shape $3 \times 1$ in equation \ref{dXAsColumnVector_broadcast_row_vector} into row vector of shape $1 \times 3$ we get: \begin{flalign} \frac{\partial L}{\partial \vecr{x}} &= \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} + \frac{\partial L}{\partial z_{2,1}} & \frac{\partial L}{\partial z_{1,2}} + \frac{\partial L}{\partial z_{2,2}} & \frac{\partial L}{\partial z_{1,3}} + \frac{\partial L}{\partial z_{2,3}} \\[0.7em] \end{bmatrix} \nonumber \\ &= \begin{bmatrix} 1 & 1\\ \end{bmatrix} \underbrace{ \begin{bmatrix} \frac{\partial L}{\partial z_{1,1}} & \frac{\partial L}{\partial z_{1,2}} & \frac{\partial L}{\partial z_{1,3}}\\[0.7em] \frac{\partial L}{\partial z_{2,1}} & \frac{\partial L}{\partial z_{2,2}} & \frac{\partial L}{\partial z_{2,3}}\\[0.7em] \end{bmatrix}}_{\frac{\partial L}{\partial \matr{Z}}} & \eqncomment{Decomposing into a matmul operation} \nonumber \\ &= \mathbf{1}_{1, \text{2}} \frac{\partial L}{\partial \matr{Z}} & \eqncomment{We are using a bold 1 namely $\mathbf{1}$ to denote matrix of ones} \nonumber \\ &= \mathbf{1}_{1, \text{R}} \frac{\partial L}{\partial \matr{Z}} & \eqncomment{Generalizing beyond our considered example} \nonumber \\ &= \mathtt{np.sum(} \matr{Z} \mathtt{, axis=0)} & \eqncomment{Using $\mathtt{NumPy}$ notation for brevity} \end{flalign} \medskip \printbibliography \end{document}
Require Import bedrock2.NotationsCustomEntry. Import Syntax Syntax.Coercions BinInt String List List.ListNotations. Local Open Scope string_scope. Local Open Scope Z_scope. Local Open Scope list_scope. Definition memequal := func! (x,y,n) ~> r { r = $0; while n { r = r | (load1(x) ^ load1(y)); x = x + $1; y = y + $1; n = n - $1 }; r = r == $0 }. Require Import bedrock2.WeakestPrecondition bedrock2.Semantics bedrock2.ProgramLogic. Require Import coqutil.Word.Interface coqutil.Word.Bitwidth. Require Import coqutil.Map.Interface bedrock2.Map.SeparationLogic. Require Import bedrock2.ZnWords. Import Coq.Init.Byte coqutil.Byte. Local Notation string := String.string. (*Require Import bedrock2.ptsto_bytes.*) Local Notation "xs $@ a" := (Array.array ptsto (word.of_Z 1) a xs) (at level 10, format "xs $@ a"). Local Notation "m =* P" := ((P%sep) m) (at level 70, only parsing) (* experiment*). Section WithParameters. Context {width} {BW: Bitwidth width}. Context {word: word.word width} {mem: map.map word byte} {locals: map.map string word}. Context {ext_spec: ExtSpec}. Import ProgramLogic.Coercions. Global Instance spec_of_memequal : spec_of "memequal" := fnspec! "memequal" (x y n : word) / (xs ys : list byte) (Rx Ry : mem -> Prop) ~> r, { requires t m := m =* xs$@x * Rx /\ m =* ys$@y * Ry /\ length xs = n :>Z /\ length ys = n :>Z; ensures t' m' := m=m' /\ t=t' /\ (r = 0 :>Z \/ r = 1 :>Z) /\ (r = 1 :>Z <-> xs = ys) }. Context {word_ok: word.ok word} {mem_ok: map.ok mem} {locals_ok : map.ok locals} {env : map.map string (list string * list string * Syntax.cmd)} {env_ok : map.ok env} {ext_spec_ok : ext_spec.ok ext_spec}. Import coqutil.Tactics.letexists coqutil.Tactics.Tactics coqutil.Tactics.autoforward. Import coqutil.Word.Properties coqutil.Map.Properties. Local Ltac ZnWords := destruct width_cases; bedrock2.ZnWords.ZnWords. Lemma memequal_ok : program_logic_goal_for_function! memequal. Proof. repeat straightline. refine ((Loops.tailrec (HList.polymorphic_list.cons _ (HList.polymorphic_list.cons _ (HList.polymorphic_list.cons _ (HList.polymorphic_list.cons _ HList.polymorphic_list.nil)))) ["x";"y";"n";"r"]) (fun (v:nat) xs Rx ys Ry t m x y n r => PrimitivePair.pair.mk ( m =* xs$@x * Rx /\ m =* ys$@y * Ry /\ v=n :> Z /\ length xs = n :> Z /\ length ys = n :> Z ) (fun T M (X Y N R : word) => m = M /\ t = T /\ exists z, R = Z.lor r z :> Z /\ (z = 0 :>Z <-> xs = ys) )) lt _ _ _ _ _ _ _ _ _); (* TODO wrap this into a tactic with the previous refine *) cbn [HList.hlist.foralls HList.tuple.foralls HList.hlist.existss HList.tuple.existss HList.hlist.apply HList.tuple.apply HList.hlist List.repeat Datatypes.length HList.polymorphic_list.repeat HList.polymorphic_list.length PrimitivePair.pair._1 PrimitivePair.pair._2] in *. { cbv [Loops.enforce]; cbn. subst l l0. repeat (rewrite ?map.get_put_dec, ?map.get_remove_dec; cbn); split. { exact eq_refl. } { eapply map.map_ext; intros k. repeat (rewrite ?map.get_put_dec, ?map.get_remove_dec, ?map.get_empty; cbn -[String.eqb]). repeat (destruct String.eqb; trivial). } } { eapply Wf_nat.lt_wf. } { cbn; ssplit; eauto. } { intros ?v ?xs ?Rx ?ys ?Ry ?t ?m ?x ?y ?n ?r. repeat straightline. cbn in localsmap. eexists n0; split; cbv [expr expr_body localsmap get]. { rewrite ?Properties.map.get_put_dec. exists n0; cbn. auto. } split; cycle 1. { intros Ht; rewrite Ht in *. intuition idtac; destruct xs0, ys0; cbn in *; try discriminate; []. exists 0; intuition eauto. rewrite Z.lor_0_r. trivial. } intros Ht. destruct xs0 as [|hxs xs0] in *, ys0 as [|hys ys0] in *; cbn [length Array.array] in *; try (cbn in *; congruence); []; repeat straightline. eapply WeakestPreconditionProperties.dexpr_expr. repeat straightline. letexists; split. { rewrite ?Properties.map.get_put_dec; exact eq_refl. } repeat straightline. letexists; split. { rewrite ?Properties.map.get_put_dec; cbn. exact eq_refl. } repeat straightline. repeat straightline. repeat straightline. letexists; split. { rewrite ?Properties.map.get_put_dec; exact eq_refl. } repeat straightline. repeat straightline. eapply WeakestPreconditionProperties.dexpr_expr. letexists; split. { subst l. rewrite ?Properties.map.get_put_dec; cbn. exact eq_refl. } repeat straightline. eapply WeakestPreconditionProperties.dexpr_expr. letexists; split. { subst l l0. rewrite ?Properties.map.get_put_dec; cbn. exact eq_refl. } repeat straightline. eapply WeakestPreconditionProperties.dexpr_expr. letexists; split. { subst l l0 l1. rewrite ?Properties.map.get_put_dec; cbn. exact eq_refl. } repeat straightline. eexists _, _, _, _. split. { cbv [Loops.enforce l l0 l1 l2]; cbn. repeat (rewrite ?map.get_put_dec, ?map.get_remove_dec; cbn); split. { exact eq_refl. } { eapply map.map_ext; intros k. repeat (rewrite ?map.get_put_dec, ?map.get_remove_dec, ?map.get_empty; cbn -[String.eqb]). repeat (destruct String.eqb; trivial). } } eexists _, _, _, _, (length xs0); split; ssplit. { ecancel_assumption. } { ecancel_assumption. } { ZnWords. } { ZnWords. } { ZnWords. } split. { cbn in *; ZnWords. } intuition idtac; repeat straightline_cleanup. rewrite H10, word.unsigned_or_nowrap, <-Z.lor_assoc. eexists; split; trivial. transitivity (hxs = hys /\ xs0 = ys0); [|intuition congruence]. rewrite <-H11. rewrite Z.lor_eq_0_iff. eapply and_iff_compat_r. subst v0 v1. rewrite word.unsigned_xor_nowrap, Z.lxor_eq_0_iff. split; [|intros;subst;trivial]. intro HH. pose proof byte.unsigned_range hxs; pose proof byte.unsigned_range hys. eapply word.unsigned_inj in HH; eapply word.of_Z_inj_small in HH; try ZnWords. eapply byte.unsigned_inj in HH; trivial. } intuition idtac. case H6 as (?&?&?). subst. subst r. eapply WeakestPreconditionProperties.dexpr_expr. letexists; split; cbn. { rewrite ?Properties.map.get_put_dec; cbn; exact eq_refl. } eexists; split; cbn. { rewrite ?Properties.map.get_put_dec; cbn; exact eq_refl. } rewrite word.unsigned_of_Z_0, Z.lor_0_l in H5; subst x4 v. setoid_rewrite word.unsigned_eqb; setoid_rewrite word.unsigned_of_Z_0. eexists; ssplit; eauto; destr Z.eqb; autoforward with typeclass_instances in E; rewrite ?word.unsigned_of_Z_1, ?word.unsigned_of_Z_0; eauto. all : intuition eauto; discriminate. Qed. End WithParameters.
section \<open>Preliminaries\<close> theory Preliminaries imports Main HOL.Real "HOL-Library.FuncSet" begin lemma fact_approx_add: "fact (l + n) \<le> fact l * (real l + real n) ^ n" proof (induct n arbitrary: l) case (Suc n l) have "fact (l + Suc n) = (real l + Suc n) * fact (l + n)" by simp also have "\<dots> \<le> (real l + Suc n) * (fact l * (real l + real n) ^ n)" by (intro mult_left_mono[OF Suc], auto) also have "\<dots> = fact l * ((real l + Suc n) * (real l + real n) ^ n)" by simp also have "\<dots> \<le> fact l * ((real l + Suc n) * (real l + real (Suc n)) ^ n)" by (rule mult_left_mono, rule mult_left_mono, rule power_mono, auto) finally show ?case by simp qed simp lemma fact_approx_minus: assumes "k \<ge> n" shows "fact k \<le> fact (k - n) * (real k ^ n)" proof - define l where "l = k - n" from assms have k: "k = l + n" unfolding l_def by auto show ?thesis unfolding k using fact_approx_add[of l n] by simp qed lemma fact_approx_upper_add: assumes al: "a \<le> Suc l" shows "fact l * real a ^ n \<le> fact (l + n)" proof (induct n) case (Suc n) have "fact l * real a ^ (Suc n) = (fact l * real a ^ n) * real a" by simp also have "\<dots> \<le> fact (l + n) * real a" by (rule mult_right_mono[OF Suc], auto) also have "\<dots> \<le> fact (l + n) * real (Suc (l + n))" by (intro mult_left_mono, insert al, auto) also have "\<dots> = fact (Suc (l + n))" by simp finally show ?case by simp qed simp lemma fact_approx_upper_minus: assumes "n \<le> k" and "n + a \<le> Suc k" shows "fact (k - n) * real a ^ n \<le> fact k" proof - define l where "l = k - n" from assms have k: "k = l + n" unfolding l_def by auto show ?thesis using assms unfolding k apply simp apply (rule fact_approx_upper_add, insert assms, auto simp: l_def) done qed lemma choose_mono: "n \<le> m \<Longrightarrow> n choose k \<le> m choose k" unfolding binomial_def by (rule card_mono, auto) lemma div_mult_le: "(a div b) * c \<le> (a * c) div (b :: nat)" by (metis div_mult2_eq div_mult_mult2 mult.commute mult_0_right times_div_less_eq_dividend) lemma div_mult_pow_le: "(a div b)^n \<le> a^n div (b :: nat)^n" proof (cases "b = 0") case True thus ?thesis by (cases n, auto) next case b: False then obtain c d where a: "a = b * c + d" and id: "c = a div b" "d = a mod b" by auto have "(a div b)^n = c^n" unfolding id by simp also have "\<dots> = (b * c)^n div b^n" using b by (metis div_power dvd_triv_left nonzero_mult_div_cancel_left) also have "\<dots> \<le> (b * c + d)^n div b^n" by (rule div_le_mono, rule power_mono, auto) also have "\<dots> = a^n div b^n " unfolding a by simp finally show ?thesis . qed lemma choose_inj_right: assumes id: "(n choose l) = (k choose l)" and n0: "n choose l \<noteq> 0" and l0: "l \<noteq> 0" shows "n = k" proof (rule ccontr) assume nk: "n \<noteq> k" define m where "m = min n k" define M where "M = max n k" from nk have mM: "m < M" unfolding m_def M_def by auto let ?new = "insert (M - 1) {0..< l - 1}" let ?m = "{K \<in> Pow {0..<m}. card K = l}" let ?M = "{K \<in> Pow {0..<M}. card K = l}" from id n0 have lM :"l \<le> M" unfolding m_def M_def by auto from id have id: "(m choose l) = (M choose l)" unfolding m_def M_def by auto from this[unfolded binomial_def] have "card ?M < Suc (card ?m)" by auto also have "\<dots> = card (insert ?new ?m)" by (rule sym, rule card_insert_disjoint, force, insert mM, auto) also have "\<dots> \<le> card (insert ?new ?M)" by (rule card_mono, insert mM, auto) also have "insert ?new ?M = ?M" by (insert mM lM l0, auto) finally show False by simp qed end
Access and/or use of this Gilead website are subject to the terms and conditions set forth herein and all applicable laws, statutes, and/or regulations. Gilead will use reasonable efforts to include accurate and up-to-date information on this Gilead website, but all information is provided "AS IS." Gilead makes no warranties or representations as to the accuracy of information presented on this Gilead website and disclaims all warranties, conditions or representations, express or implied, including any warranties of merchantability, fitness for a particular purpose, and non-infringement to the fullest extent permitted by applicable law which may apply to the Website and any content on it. Neither Gilead nor any of its agents or affiliates shall be liable for any direct, incidental, consequential, indirect, or punitive damages arising out of user's access, use, or inability to use this Gilead website, use of or reliance on any content displayed on the Website or any errors or omissions in such content of this Gilead website. This Gilead website does not, and is not intended to, provide medical advice, nor does it provide instruction on the appropriate use of any product produced or supplied by Gilead, its affiliates, related companies, or its licensors or joint venture partners. The information presented on this Gilead website should not be interpreted or construed in any way as a replacement or substitution for medical advice provided by a doctor or healthcare provider. It is important that you discuss your treatment options and any questions that you may have with your doctor or healthcare provider. This Gilead website may contain information (including without limitation videos, abstracts, publications, postings, news and/or press releases), the content of which is accurate or current only as of the date of the particular information, video, abstract, publication, posting, news and/or press release, or posting. Gilead's websites may include hyperlinks to websites maintained or controlled by others. Gilead is not responsible for and does not routinely screen, approve, review or endorse the contents of or use of any of the products or services that may be offered at these websites. Such websites are accessed at the users’ own risk. You can contact us by post or by email.
#************************************************************************************** # Output_Interface.jl # =============== part of the GeoEfficiency.jl package. # # all the output either to the console or to the csv files is handled here. # #************************************************************************************** const resultsfolder = "results"; const resultdir = joinpath(datadir, resultsfolder); isdir(resultdir) || mkdir(resultdir) const resultdir_pnt = joinpath(resultdir, "Point"); isdir(resultdir_pnt) || mkdir(resultdir_pnt) const resultdir_nonPnt = joinpath(resultdir, "non-Point"); isdir(resultdir_nonPnt) || mkdir(resultdir_nonPnt) countDetectors = 1; """ calc(Detector::RadiationDetector = detectorFactory()) calculate the Geometrical Efficiency of the detector `Detector` and display it on the `console`. If no detector is supplied it ask for a detector from the `console`. Also prompt the user to input a source via the `console`. """ function calc(Detector::RadiationDetector = detectorFactory()) global countDetectors aPnt, srcRadius, srcLength = source() print_with_color(:yellow,"\n\<$(countDetectors)\> $(id(Detector))") println("\n - Source(", id(aPnt), ", srcRadius=",srcRadius, ", srcLength=", srcLength, ")") try println("\n - The Detector Geometrical Efficiency = ", geoEff(Detector, aPnt, srcRadius, srcLength)) catch err println(err) input("\n\t To Procced Press any Button") return nothing end #try countDetectors += 1 print_with_color(:red, repeat(" =",36),"\n\n") return nothing end #function """ calcN() calculate and display the Geometrical Efficiency. Prompt the user to input a `detector` and a `source` from the `console`. Prompt the user `repeatedly` until it exit (give a choice to use the same detector or a new detector). """ function calcN() Detector = detectorFactory() while (true) calc(Detector) res = input("""\n I- To continue make a choice: > using the same detector Press 'd'|'D' > using a new detector Press 'n'|'N'\n II- To quit just press return\n \n\tyour Choice: """, :blue)|> lowercase; if res == "n" Detector = detectorFactory() elseif res == "d" continue else break end #if end #while return nothing end #function function writecsv_head(fname::AbstractString, a, head=[]) open(fname, "w") do io writedlm(io, head, ',') writedlm(io, a, ',') end end """ batch() provide batch calculation of the Geometrical Efficiency based on the data provided from the csv files located in `$(datafolder)`. Results are saved on a `csv file` named after the detector located in `$(resultdir)`, also a log of the results are displayed on the `console`. Throw an error if the source location is inappropriate. \n***** """ function batch() batch(read_batch_info()...) end #function """ batch( Detector_info_array::Array{Float64,2}, srcHeights_array::Array{Float64,1}, srcRhos_array::Array{Float64,1}=[0.0], srcRadii_array::Array{Float64,1}=[0.0], srcLengths_array::Array{Float64,1}=[0.0], ispoint::Bool=true) provide batch calculation of the Geometricel efficiecny for each detector in the `Detector_info_array` after applying detectorFactory() to each raw. A set of sources is constructed of every valid combination of parameter in the `srcRhos_array`, `srcRadii_array`, `srcLengths_array` with conjunction with `ispoint`. If `ispoint` is true the source type is a point source and the parameters in srcRadii_array , srcLengths_array is completely ignored. If `ispoint` is false the parameters in srcRhos_array is completely ignored. Results are saved to a csv file named after the detector located in `$(resultdir)`, also a log of the results are displayed on the `console`. \n***** """ function batch( Detector_info_array::Array{Float64,2}, srcHeights_array::Array{Float64,1}, srcRhos_array::Array{Float64,1}=[0.0], srcRadii_array::Array{Float64,1}=[0.0], srcLengths_array::Array{Float64,1}=[0.0], ispoint::Bool=true) return batch( getDetectors(Detector_info_array), srcHeights_array, srcRhos_array, srcRadii_array, srcLengths_array, ispoint) end #function """ batch( Detector::RadiationDetector, srcHeights_array::Array{Float64,1}, srcRhos_array::Array{Float64,1}=[0.0], srcRadii_array::Array{Float64,1}=[0.0], srcLengths_array::Array{Float64,1}=[0.0], ispoint::Bool=true) provide batch calculation of the Geometricel efficiecny for the detector `Detector` . A set of sources is constructed of every valid combination of parameter in the `srcRhos_array`, `srcRadii_array`, `srcLengths_array` with conjunction with `ispoint`. If `ispoint` is true the source type is a point source and the parameters in srcRadii_array , srcLengths_array is completely ignored. If `ispoint` is false the parameters in srcRhos_array is completely ignored. Results are saved to a csv file named after the detector located in `$(resultdir)`, also a log of the results are displayed on the `console`. Return a tuple of the `detector array` and the `results array`. the `results array` has coloulmns `Height`, `Rho`, `GeoEfficiency` in the case of a point while coloulmns `AnchorHeight`, `AnchorRho`, `srcRadius`, `srcLength`, `GeoEfficiency` for non-point sources. \n***** """ function batch( Detector::RadiationDetector, srcHeights_array::Array{Float64,1}, srcRhos_array::Array{Float64,1}=[0.0], srcRadii_array::Array{Float64,1}=[0.0], srcLengths_array::Array{Float64,1}=[0.0], ispoint::Bool=true) return _batch(Val{ispoint}, Detector::RadiationDetector, srcHeights_array, srcRhos_array, srcRadii_array, srcLengths_array ) end #function """ batch( Detectors_array::Array{RadiationDetector,1}, srcHeights_array::Array{Float64,1}, srcRhos_array::Array{Float64,1}=[0.0], srcRadii_array::Array{Float64,1}=[0.0], srcLengths_array::Array{Float64,1}=[0.0], ispoint::Bool=true) provide batch calculation of the Geometricel efficiecny for each detector in the `Detectors_array`. A set of sources is constructed of every valid combination of parameter in the `srcRhos_array`, `srcRadii_array`, `srcLengths_array` with conjunction with `ispoint`. If `ispoint` is true the source type is a point source and the parameters in srcRadii_array , srcLengths_array is completely ignored. If `ispoint` is false the parameters in srcRhos_array is completely ignored. Results are saved to a csv file named after the detector located in `$(resultdir)`, also a log of the results are displayed on the `console`. \n***** """ function batch( Detectors_array::Array{RadiationDetector,1}, srcHeights_array::Array{Float64,1}, srcRhos_array::Array{Float64,1}=[0.0], srcRadii_array::Array{Float64,1}=[0.0], srcLengths_array::Array{Float64,1}=[0.0], ispoint::Bool=true) for Detector = Detectors_array batch(Detector, srcHeights_array, srcRhos_array, srcRadii_array, srcLengths_array, ispoint) end # Detectors_array input("\n\t the program had termiate, To Exit Press any Button") nothing end #function """ batch calclulation for point sources. """ function _batch(::Type{Val{true}}, Detector::RadiationDetector, srcHeights_array::Array{Float64,1}, srcRhos_array::Array{Float64,1}=[0.0], srcRadii_array::Array{Float64,1}=[0.0], srcLengths_array::Array{Float64,1}=[0.0] ) global countDetectors aPnt::Point = Point(0.0, 0.0) results::Array{Float64,2} = Array(Float64,(0,0)); out_results::Array{Float64,1} = Float64[]; cellLabel = "\n\<$(countDetectors)\>$(id(Detector))" for srcHeight = srcHeights_array aPnt.Height = srcHeight #setHeight!(aPnt, srcHeight) for srcRho = srcRhos_array aPnt.Rho = srcRho #setRho!(aPnt, srcRho) try x = geoEff(Detector, aPnt) push!(out_results, aPnt.Height, aPnt.Rho, x) catch err isa(err, AssertionError) && break rethrow() end #try print_with_color(:yellow,cellLabel) println("\n - Source: ", id(aPnt)) println("\n - The Detector Geometrical Efficiency = ", out_results[end]) print_with_color(:red, repeat(" =",36),"\n\n") end #for_Rho end #for_Height results = reshape(out_results, 3, Int(length(out_results)/3)) |> transpose println("INFO: Saving <$countDetectors> to '$(id(Detector)).csv'......") try writecsv_head(joinpath(resultdir_pnt, "$(id(Detector)).csv"), results, ["Height", "Rho", "GeoEfficiency"]') catch err warn("'.$(id(Detector)).csv': can't be created, results saved in an alternative file") writecsv_head(joinpath(resultdir_pnt, "_$(id(Detector)).csv"), results, ["Height", "Rho", "GeoEfficiency"]') end #try countDetectors += 1 return (Detector, results) end #function """ batch calclulation for non-point sources. """ function _batch(::Type{Val{false}}, Detector::RadiationDetector, srcHeights_array::Array{Float64,1}, srcRhos_array::Array{Float64,1}=[0.0], srcRadii_array::Array{Float64,1}=[0.0], srcLengths_array::Array{Float64,1}=[0.0]; ) global countDetectors aPnt::Point = Point(0.0, 0.0) results::Array{Float64,2} = Array(Float64,(0,0)); out_results::Array{Float64,1} = Float64[]; cellLabel = "\n\<$(countDetectors)\>$(id(Detector))" for srcHeight = srcHeights_array aPnt.Height = srcHeight #setHeight!(aPnt, srcHeight) for srcRho = srcRhos_array aPnt.Rho = srcRho #setRho!(aPnt, srcRho) for srcLength = srcLengths_array; for srcRadius = srcRadii_array try x = geoEff(Detector, aPnt, srcRadius , srcLength) push!(out_results, aPnt.Height, aPnt.Rho, srcRadius , srcLength, x) catch err isa(err, AssertionError) && @goto(Next_Height) rethrow() end #try print_with_color(:yellow,cellLabel) println("\n - Source[Anchor_", id(aPnt), ", srcRadius=",srcRadius, ", srcLength=", srcLength, "]") println("\n - The Detector Geometrical Efficiency = ", out_results[end]) print_with_color(:red, repeat(" =",36),"\n\n") end #for_srcRadius @label(Next_srcLength) end #for_srcLength end #for_Rho @label(Next_Height) end #for_Height results = reshape(out_results, 5, Int(length(out_results)/5)) |> transpose println("INFO: Saving <$countDetectors> to '$(id(Detector)).csv'......") try err writecsv_head(joinpath(resultdir_nonPnt, "$(id(Detector)).csv"), results, ["AnchorHeight", "AnchorRho", "srcRadius", "srcLength", "GeoEfficiency"]') catch warn("'$(id(Detector)).csv': can't be created, results saved in an alternative file") writecsv_head(joinpath(resultdir_nonPnt, "_$(id(Detector)).csv"), results, ["AnchorHeight", "AnchorRho", "srcRadius", "srcLength", "GeoEfficiency"]') end #try countDetectors += 1; return (Detector, results) end #function
# A collection of miscellanous lines you can run in your development of this # package. Nothing in here is exported or used anywhere else. Purely # helpers for development. This is just a scraps file. granatum.other = function () { library(devtools) # Check package devtools::check() # Update datasets # Saving datasets use_data(someData, overwrite = TRUE) install.packages("roxygen2") install.packages("testthat") install.packages("usethis") install.packages("covr") install.packages("DT") usethis::use_test("nodesDiffExp") devtools::test() granatum.codeCoverage() devtools::build_win() create("cats") devtools::release() # devtools::revdep_check() install.packages("granatum_0.1.0.tar.gz", repos = NULL, type ="source") } granatum.makeDoc = function (dataFrame, title = substitute(dataFrame)) { output = c(paste("#'", title), "#' @format data.frame", gsub("^","#'",capture.output(str(dataFrame))), dQuote(title)) cat(output, sep="\n") } granatum.codeCoverage = function () { library(covr) report() } # R CMD build . # R CMD check --as-cran granatum.tar.gz
(* Title: Sequents/LK/Quantifiers.thy Author: Lawrence C Paulson, Cambridge University Computer Laboratory Copyright 1992 University of Cambridge Classical sequent calculus: examples with quantifiers. *) theory Quantifiers imports "../LK" begin lemma "|- (ALL x. P) <-> P" by fast lemma "|- (ALL x y. P(x,y)) <-> (ALL y x. P(x,y))" by fast lemma "ALL u. P(u), ALL v. Q(v) |- ALL u v. P(u) & Q(v)" by fast text "Permutation of existential quantifier." lemma "|- (EX x y. P(x,y)) <-> (EX y x. P(x,y))" by fast lemma "|- (ALL x. P(x) & Q(x)) <-> (ALL x. P(x)) & (ALL x. Q(x))" by fast (*Converse is invalid*) lemma "|- (ALL x. P(x)) | (ALL x. Q(x)) --> (ALL x. P(x)|Q(x))" by fast text "Pushing ALL into an implication." lemma "|- (ALL x. P --> Q(x)) <-> (P --> (ALL x. Q(x)))" by fast lemma "|- (ALL x. P(x)-->Q) <-> ((EX x. P(x)) --> Q)" by fast lemma "|- (EX x. P) <-> P" by fast text "Distribution of EX over disjunction." lemma "|- (EX x. P(x) | Q(x)) <-> (EX x. P(x)) | (EX x. Q(x))" by fast (*Converse is invalid*) lemma "|- (EX x. P(x) & Q(x)) --> (EX x. P(x)) & (EX x. Q(x))" by fast text "Harder examples: classical theorems." lemma "|- (EX x. P-->Q(x)) <-> (P --> (EX x. Q(x)))" by fast lemma "|- (EX x. P(x)-->Q) <-> (ALL x. P(x)) --> Q" by fast lemma "|- (ALL x. P(x)) | Q <-> (ALL x. P(x) | Q)" by fast text "Basic test of quantifier reasoning" lemma "|- (EX y. ALL x. Q(x,y)) --> (ALL x. EX y. Q(x,y))" by fast lemma "|- (ALL x. Q(x)) --> (EX x. Q(x))" by fast text "The following are invalid!" (*INVALID*) lemma "|- (ALL x. EX y. Q(x,y)) --> (EX y. ALL x. Q(x,y))" apply fast? apply (rule _) oops (*INVALID*) lemma "|- (EX x. Q(x)) --> (ALL x. Q(x))" apply fast? apply (rule _) oops (*INVALID*) schematic_lemma "|- P(?a) --> (ALL x. P(x))" apply fast? apply (rule _) oops (*INVALID*) schematic_lemma "|- (P(?a) --> (ALL x. Q(x))) --> (ALL x. P(x) --> Q(x))" apply fast? apply (rule _) oops text "Back to things that are provable..." lemma "|- (ALL x. P(x)-->Q(x)) & (EX x. P(x)) --> (EX x. Q(x))" by fast (*An example of why exR should be delayed as long as possible*) lemma "|- (P--> (EX x. Q(x))) & P--> (EX x. Q(x))" by fast text "Solving for a Var" schematic_lemma "|- (ALL x. P(x)-->Q(f(x))) & (ALL x. Q(x)-->R(g(x))) & P(d) --> R(?a)" by fast text "Principia Mathematica *11.53" lemma "|- (ALL x y. P(x) --> Q(y)) <-> ((EX x. P(x)) --> (ALL y. Q(y)))" by fast text "Principia Mathematica *11.55" lemma "|- (EX x y. P(x) & Q(x,y)) <-> (EX x. P(x) & (EX y. Q(x,y)))" by fast text "Principia Mathematica *11.61" lemma "|- (EX y. ALL x. P(x) --> Q(x,y)) --> (ALL x. P(x) --> (EX y. Q(x,y)))" by fast (*21 August 88: loaded in 45.7 secs*) (*18 September 2005: loaded in 0.114 secs*) end
% --- [ Security Assessment ] -------------------------------------------------- \subsection{Security Assessment} \label{sec:ver_security_assessment} To assess the security of the decompiler pipeline, lets imagine a scenario in which users are given access to the implementation details and source code of the entire system and may provide arbitrary input to any of its components. A potential scenario could involve a web site which provides decompilation as a service and allows its users to interact with the various stages of the decompiler pipeline. The Retargetable Decompiler\footnote{Retargetable Decompiler: \url{https://retdec.com/}} provides such a service, except it only allows users to interact with the binary analysis stage of the pipeline (see section~\ref{sec:lit_review_binary_analysis}) and its source code is proprietary. The scope of this security assessment will be limited to the various components of the decompiler pipeline and their interaction. In particular security issues related to the operating system, network stack, web server and web site (e.g. SQL-injection and XSS vulnerabilities) of the decompilation service are intentionally excluded from the scope of the security assessment. The objective of an attacker may be to escalate their privileges in a system by exploiting it to execute actions not intended by design. Since the security of any system is only as strong as its weakest link, it is critical to identify and isolate likely targets for attacks. Projects which consist of or depend on large C or C\texttt{++} code bases may exhibit memory safety issues, such as buffer overflows or use-after-free vulnerabilities. These issues are considered low-hanging fruit for attackers and have a long history of successful exploitation~\cite{for_fun_and_profit}. Several modern programming languages (including Go) provide memory safety guarantees and may solve these issues by inserting bounds-checking for array accesses and using garbage collection for memory management. Code written in memory safe languages may still contain other security vulnerabilities caused by logic errors or insufficient validation, sanitation and parametrization of input (e.g. command injection and directory traversal vulnerabilities). The number of lines of code in a project may give an indication to the project's complexity and to some extent its potential attack surface. As summarised in table~\ref{tbl:loc_summary} every component, except \texttt{restructure}, of the decompiler pipeline depends on LLVM; the code base of which contains approximately 800~000 lines of C\texttt{++} source code. Even if only a portion of the code will be linked into the executables it is an interesting target for attacks. One thing to keep in mind is that there are several high-end users of the LLVM project (such as Apple, Intel, NVIDIA and Sony~\cite{llvm_users}) and it has a well established code reviewing process. Some of the LLVM developers are also very well educated in common security vulnerabilities and have developed the Clang Static Analyzer, which is a static source code analysis tool that locates bugs (such as buffer overflows and use-after-free issues) in C and C\texttt{++} programs~\cite{clang_analyzer}. The LLVM project may contain several security issues due to its size, but they are most likely difficult to discover since the low-hanging fruit have been caught already by the Clang Static Analyzer. Similarly, Google Protocol Buffers are used extensively by several companies and organisations and the likelihood of discovering a simple security vulnerability in its code base is low. \begin{table}[htbp] \begin{center} \resizebox{\textwidth}{!}{ \begin{tabular}{|l|l|l|l|} \hline \textbf{Project} & \textbf{Language} & \textbf{Lines} & \textbf{Dependencies} \\ \hline \multicolumn{4}{|l|}{\hspace{4ex} \textit{Front-end}} \\ \hline Dagger & C\texttt{++} & 2~000 & LLVM \\ Fracture & C\texttt{++} & 20~000 & LLVM \\ MC-Semantics & C\texttt{++} & 25~000 & LLVM and Google Protocol Buffers \\ \hline \multicolumn{4}{|l|}{\hspace{4ex} \textit{Middle-end}} \\ \hline ll2dot & Go & 500 & LLVM and dot \\ restructure & Go & 300 & graphs and dot \\ \hline \multicolumn{4}{|l|}{\hspace{4ex} \textit{Back-end}} \\ \hline ll2go & Go & 1~500 & LLVM and llvm (Go) \\ go-post & Go & 3~000 & - \\ \hline \multicolumn{4}{|l|}{\hspace{4ex} \textit{Dependencies}} \\ \hline LLVM & C\texttt{++} & 800~000 & - \\ Google Protocol Buffers & C\texttt{++} & 125~000 & - \\ dot & Go & 7~000 & - \\ llvm (Go) & Go & 5~000 & - \\ graphs & Go & 2~000 & - \\ \hline \end{tabular} } \end{center} \caption{A rough summary of each project specifying their programming language, total number of lines of code and dependencies.} \label{tbl:loc_summary} \end{table} There are still three potential targets which may contain memory related vulnerabilities, namely the front-end projects which translate binary executables, object code and shared libraries to LLVM IR. Insufficient validation during the parsing of headers (e.g. trusting the values of section header fields in ELF files) may lead to security vulnerabilities. The front-end projects rely extensively on parsing logic for the binary analysis stage (see section~\ref{sec:lit_review_binary_analysis}), and are therefore susceptible to security vulnerabilities. The security implications of various design decisions have been taken into consideration during the development process of the Go components. The Go runtime guarantees memory safety by inserting bounds-checking for array accesses and using garbage collection for memory management. Furthermore, the Go project focuses on addressing security issues at the language-level rather than relying on security through obscurity (e.g. address space layout randomization) to mitigate these issues at the OS-level, as further explained and justified by the quote of Russ Cox (who works on the Go compiler and runtime) presented in figure~\ref{fig:no_aslr}. \begin{figure}[htbp] \begin{quote} \textit{``Address space randomization is an OS-level workaround for a language-level problem, namely that simple C programs tend to be full of exploitable buffer overflows. Go fixes this at the language level, with bounds-checked arrays and slices and no dangling pointers, which makes the OS-level workaround much less important. In return, we receive the incredible debuggability of deterministic address space layout. I would not give that up lightly.''} \end{quote} \caption{Reply by Russ Cox to a discussion regarding ASLR, on the Go mailing list\protect\footnotemark.} \label{fig:no_aslr} \end{figure} \footnotetext{Secure Go binaries: \url{https://groups.google.com/d/msg/golang-nuts/Jd9tlNc6jUE/6dLasvOs4nIJ}} There is one know issue with the Go bindings for LLVM IR which may compromise the integrity of the output from the decompilation pipeline. The \texttt{ll2dot} and \texttt{ll2go} components require access to the names of unnamed basic blocks, but these names are not accessible from the API of the LLVM IR library as they are generated on the fly by the assembly printer. As a work around, the debug facilities of the LLVM IR library have been utilised to print the assembly to temporary files, which are parsed to gain access to the names of unnamed basic blocks. These temporary files may be tampered with, if not sufficiently protected by access permissions, which may compromise the integrity of the control flow analysis stage. A pure Go library for interacting with LLVM IR is being developed (see section~\ref{sec:impl_llvm_ir_library}) which will include native support for calculating the names of unnamed basic blocks, thus mitigating this security issue. To conclude, the security assessment was conducted to identify potential security issues and provide an intuition for the general security of the decompilation system. In scenarios such as the one described above (i.e. users may provide arbitrary input), it is advisable to further harden the decompilation system by utilizing defence in depth (i.e. several independent layers of security) and the principle of least privilege (e.g. use jails in FreeBSD and LXC in Linux).
1 FORMAT (1PE12.4, I10) 2 FORMAT (I12, /, ' Dates: ', 2 (2I3, I5)) end
[STATEMENT] lemma convert_obs_initial_simps [simp]: "\<lbrace>convert_obs_initial ta\<rbrace>\<^bsub>o\<^esub> = map NormalAction \<lbrace>ta\<rbrace>\<^bsub>o\<^esub>" "\<lbrace>convert_obs_initial ta\<rbrace>\<^bsub>l\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>l\<^esub>" "\<lbrace>convert_obs_initial ta\<rbrace>\<^bsub>t\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>t\<^esub>" "\<lbrace>convert_obs_initial ta\<rbrace>\<^bsub>c\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>c\<^esub>" "\<lbrace>convert_obs_initial ta\<rbrace>\<^bsub>w\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>w\<^esub>" "\<lbrace>convert_obs_initial ta\<rbrace>\<^bsub>i\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>i\<^esub>" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<lbrace>convert_obs_initial ta\<rbrace>\<^bsub>o\<^esub> = map NormalAction \<lbrace>ta\<rbrace>\<^bsub>o\<^esub> &&& \<lbrace>convert_obs_initial ta\<rbrace>\<^bsub>l\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>l\<^esub> &&& \<lbrace>convert_obs_initial ta\<rbrace>\<^bsub>t\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>t\<^esub>) &&& \<lbrace>convert_obs_initial ta\<rbrace>\<^bsub>c\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>c\<^esub> &&& \<lbrace>convert_obs_initial ta\<rbrace>\<^bsub>w\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>w\<^esub> &&& \<lbrace>convert_obs_initial ta\<rbrace>\<^bsub>i\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>i\<^esub> [PROOF STEP] by(simp_all add: convert_obs_initial_def)
[STATEMENT] theorem insert'_pres_valid: assumes "invar_vebt t n" shows "invar_vebt (insert' t x) n" [PROOF STATE] proof (prove) goal (1 subgoal): 1. invar_vebt (insert' t x) n [PROOF STEP] using assms [PROOF STATE] proof (prove) using this: invar_vebt t n goal (1 subgoal): 1. invar_vebt (insert' t x) n [PROOF STEP] apply cases [PROOF STATE] proof (prove) goal (5 subgoals): 1. \<And>a b. \<lbrakk>t = Leaf a b; n = Suc 0\<rbrakk> \<Longrightarrow> invar_vebt (insert' t x) n 2. \<And>treeList na summary m. \<lbrakk>t = Node None n treeList summary; \<forall>t\<in>set treeList. invar_vebt t na; invar_vebt summary m; length treeList = 2 ^ m; m = na; n = na + m; \<not> Ex (both_member_options summary); \<forall>t\<in>set treeList. \<not> Ex (both_member_options t)\<rbrakk> \<Longrightarrow> invar_vebt (insert' t x) n 3. \<And>treeList na summary m. \<lbrakk>t = Node None n treeList summary; \<forall>t\<in>set treeList. invar_vebt t na; invar_vebt summary m; length treeList = 2 ^ m; m = Suc na; n = na + m; \<not> Ex (both_member_options summary); \<forall>t\<in>set treeList. \<not> Ex (both_member_options t)\<rbrakk> \<Longrightarrow> invar_vebt (insert' t x) n 4. \<And>treeList na summary m mi ma. \<lbrakk>t = Node (Some (mi, ma)) n treeList summary; \<forall>t\<in>set treeList. invar_vebt t na; invar_vebt summary m; length treeList = 2 ^ m; m = na; n = na + m; \<forall>i<2 ^ m. Ex (both_member_options (treeList ! i)) = both_member_options summary i; mi = ma \<longrightarrow> (\<forall>t\<in>set treeList. \<not> Ex (both_member_options t)); mi \<le> ma; ma < 2 ^ n; mi \<noteq> ma \<longrightarrow> (\<forall>i<2 ^ m. (high ma na = i \<longrightarrow> both_member_options (treeList ! i) (low ma na)) \<and> (\<forall>x. high x na = i \<and> both_member_options (treeList ! i) (low x na) \<longrightarrow> mi < x \<and> x \<le> ma))\<rbrakk> \<Longrightarrow> invar_vebt (insert' t x) n 5. \<And>treeList na summary m mi ma. \<lbrakk>t = Node (Some (mi, ma)) n treeList summary; \<forall>t\<in>set treeList. invar_vebt t na; invar_vebt summary m; length treeList = 2 ^ m; m = Suc na; n = na + m; \<forall>i<2 ^ m. Ex (both_member_options (treeList ! i)) = both_member_options summary i; mi = ma \<longrightarrow> (\<forall>t\<in>set treeList. \<not> Ex (both_member_options t)); mi \<le> ma; ma < 2 ^ n; mi \<noteq> ma \<longrightarrow> (\<forall>i<2 ^ m. (high ma na = i \<longrightarrow> both_member_options (treeList ! i) (low ma na)) \<and> (\<forall>x. high x na = i \<and> both_member_options (treeList ! i) (low x na) \<longrightarrow> mi < x \<and> x \<le> ma))\<rbrakk> \<Longrightarrow> invar_vebt (insert' t x) n [PROOF STEP] apply (metis One_nat_def deg1Leaf insert'.simps(1) vebt_insert.simps(1)) [PROOF STATE] proof (prove) goal (4 subgoals): 1. \<And>treeList na summary m. \<lbrakk>t = Node None n treeList summary; \<forall>t\<in>set treeList. invar_vebt t na; invar_vebt summary m; length treeList = 2 ^ m; m = na; n = na + m; \<not> Ex (both_member_options summary); \<forall>t\<in>set treeList. \<not> Ex (both_member_options t)\<rbrakk> \<Longrightarrow> invar_vebt (insert' t x) n 2. \<And>treeList na summary m. \<lbrakk>t = Node None n treeList summary; \<forall>t\<in>set treeList. invar_vebt t na; invar_vebt summary m; length treeList = 2 ^ m; m = Suc na; n = na + m; \<not> Ex (both_member_options summary); \<forall>t\<in>set treeList. \<not> Ex (both_member_options t)\<rbrakk> \<Longrightarrow> invar_vebt (insert' t x) n 3. \<And>treeList na summary m mi ma. \<lbrakk>t = Node (Some (mi, ma)) n treeList summary; \<forall>t\<in>set treeList. invar_vebt t na; invar_vebt summary m; length treeList = 2 ^ m; m = na; n = na + m; \<forall>i<2 ^ m. Ex (both_member_options (treeList ! i)) = both_member_options summary i; mi = ma \<longrightarrow> (\<forall>t\<in>set treeList. \<not> Ex (both_member_options t)); mi \<le> ma; ma < 2 ^ n; mi \<noteq> ma \<longrightarrow> (\<forall>i<2 ^ m. (high ma na = i \<longrightarrow> both_member_options (treeList ! i) (low ma na)) \<and> (\<forall>x. high x na = i \<and> both_member_options (treeList ! i) (low x na) \<longrightarrow> mi < x \<and> x \<le> ma))\<rbrakk> \<Longrightarrow> invar_vebt (insert' t x) n 4. \<And>treeList na summary m mi ma. \<lbrakk>t = Node (Some (mi, ma)) n treeList summary; \<forall>t\<in>set treeList. invar_vebt t na; invar_vebt summary m; length treeList = 2 ^ m; m = Suc na; n = na + m; \<forall>i<2 ^ m. Ex (both_member_options (treeList ! i)) = both_member_options summary i; mi = ma \<longrightarrow> (\<forall>t\<in>set treeList. \<not> Ex (both_member_options t)); mi \<le> ma; ma < 2 ^ n; mi \<noteq> ma \<longrightarrow> (\<forall>i<2 ^ m. (high ma na = i \<longrightarrow> both_member_options (treeList ! i) (low ma na)) \<and> (\<forall>x. high x na = i \<and> both_member_options (treeList ! i) (low x na) \<longrightarrow> mi < x \<and> x \<le> ma))\<rbrakk> \<Longrightarrow> invar_vebt (insert' t x) n [PROOF STEP] apply (metis assms insert'.simps(2) leI valid_pres_insert)+ [PROOF STATE] proof (prove) goal: No subgoals! [PROOF STEP] done
If $y$ is a nonzero polynomial, then the remainder of $x$ divided by $y$ is $x \bmod y = x - b y$, where $b$ is the coefficient of the leading term of $x$ divided by the coefficient of the leading term of $y$.
function h = ne(f, g) %~= Not equal operator for CHEBFUN objects. % H = F ~= G, where F and/or G are CHEBFUN objects, constructs a logical % CHEBFUN H which is true (i.e., takes the value 1) where F ~= G, and false % (0) elsewhere. % % See also EQ, ROOTS. % Copyright 2017 by The University of Oxford and The Chebfun Developers. % See http://www.chebfun.org/ for Chebfun information. % Trivial empty case: if ( isempty(f) ) h = f; return elseif ( isempty(g) ) h = g; return end % Array-valued? if ( min(size(f)) > 1 || min(size(g)) > 1 ) error('CHEBFUN:CHEBFUN:ne:array', ... '~= does not support array-valued CHEBFUN objects.'); end % Call SIGN() to do the work: h = sign(f - g); % Get value in interior of each FUN by taking left-sided limit at the breaks: vals = get(h, 'rval-local'); % Set FUNs that are nonzero to FUNs which are identically 1: for k = 1:numel(h.funs) if ( vals(k) ~= 0 ) h.funs{k} = 1 + 0*h.funs{k}; end end % pointValues: ind = isnan(h.pointValues); h.pointValues = double(logical(h.pointValues(~ind))); % Tidy the result: h = merge(h); end
import combinatorics.simple_graph.clique import combinatorics.simple_graph.degree_sum import data.finset.basic import data.nat.basic import tactic.core import algebra.big_operators -- local imports import fedges import nbhd_res import clique_free_sets import misc_finset import multipartite import turanpartition import induced open finset nat turanpartition open_locale big_operators namespace simple_graph variables {t n : β„•} variables {Ξ± : Type*} (G H : simple_graph Ξ±)[fintype Ξ±][nonempty Ξ±][decidable_eq Ξ±][decidable_rel G.adj][decidable_rel H.adj] include G ---for any (t+2)-clique free set there is a partition into B, a (t+1)-clique free set and A\B -- such that e(A)+e(A\B) ≀ e(B) + |B|(|A|-|B|) lemma furedi_help : βˆ€A:finset Ξ±, G.clique_free_set A (t+2) β†’ βˆƒB:finset Ξ±, B βŠ† A ∧ G.clique_free_set B (t+1) ∧ βˆ‘v in A, G.deg_res v A + βˆ‘ v in (A\B), G.deg_res v (A\B) ≀ βˆ‘ v in B, G.deg_res v B + 2*B.card * (A\B).card:= begin cases nat.eq_zero_or_pos t with ht,{ intros A hA,rw ht at *, rw zero_add at *, ----- t = 0 need to check that βˆ… is not a 1-clique. refine βŸ¨βˆ…,⟨empty_subset A,(G.clique_free_empty (by norm_num: 0 <1)),_⟩⟩, rw [sdiff_empty, card_empty, mul_zero,zero_mul, sum_empty, zero_add,G.two_clique_free_sum hA]},{ ----- 0 < t case intros A hA, by_cases hnem: A.nonempty,{ obtain ⟨x,hxA,hxM⟩:=G.exists_max_res_deg_vertex hnem, -- get a vert x of max res deg in A set hBA:= (G.sub_res_nbhd_A x A), set B:=(G.nbhd_res x A) with hB,-- Let B be the res nbhd of the vertex x of max deg_A refine ⟨B, ⟨hBA,(G.t_clique_free hA hxA),_⟩⟩, rw [G.deg_res_add_sum hBA, G.sum_sdf hBA B, add_assoc], rw [G.sum_sdf hBA (A\B),G.bip_count hBA,← G.deg_res_add_sum hBA ], rw ← hB, rw ← add_assoc, ring_nf, apply add_le_add_left _ (βˆ‘ v in B, G.deg_res v B ), rw add_comm, rw add_assoc, nth_rewrite 1 add_comm, rw ← G.deg_res_add_sum hBA, ring_nf,rw mul_assoc, refine mul_le_mul' (by norm_num) _, apply le_trans (G.max_deg_res_sum_le (sdiff_subset A B)) _, rw [hxM,deg_res],}, {rw not_nonempty_iff_eq_empty at hnem, refine βŸ¨βˆ…,⟨empty_subset A,(G.clique_free_empty (by norm_num: 0 <t+1)),_⟩⟩, rw [sdiff_empty, card_empty, mul_zero,zero_mul, sum_empty, zero_add,hnem,sum_empty],}}, end -- Putting together the deg counts of G induced on a larger partition (M with C inserted). -- Counting degrees sums over the parts of the larger partition is what you expect -- ie e(G[M_0])+ .. +e(G[M_t])+e(G[C]) = e(G[M'_0])+...+e(G[M'_{t+1}]) lemma internal_count {M: multi_part Ξ±} {C : finset Ξ±} (h: disjoint M.A C): βˆ‘ i in range(M.t+1),βˆ‘ v in (M.P i), G.deg_res v (M.P i) + βˆ‘ v in C, G.deg_res v C = βˆ‘ i in range((insert M h).t+1), βˆ‘ v in ((insert M h).P i), G.deg_res v ((insert M h).P i):= begin simp [insert_t, insert_P,ite_not], have ru:range((M.t+1)+1)=range(M.t+1) βˆͺ {M.t+1},{ rw range_succ, rw union_comm, rw insert_eq _,}, have nm:(M.t+1)βˆ‰(range(M.t+1)):=not_mem_range_self, have rd: disjoint (range(M.t+1)) {M.t+1}:= disjoint_singleton_right.mpr nm, rw [ru,sum_union rd],simp only [sum_singleton, eq_self_iff_true, if_true], apply (add_left_inj _).mpr, apply sum_congr rfl, intros k hk, have nm:(M.t+1)βˆ‰(range(M.t+1)):=not_mem_range_self, have kne: kβ‰ M.t+1,{intro h',rw h' at hk, exact nm hk}, apply sum_congr, split_ifs,{contradiction},{refl},{ intros v hv,split_ifs,{contradiction},{refl}}, end -- Furedi's stability theorem: (t+2)-clique-free set A implies there is a (t+1)-partition of A -- such that edges in A + edges in parts (counted a second time) ≀ edges in the complete -- (t+1)-partite graph on same partition -- implies Turan once we have know how to maximize edges of a complete multi-partite graph theorem furedi : βˆ€A:finset Ξ±, G.clique_free_set A (t+2) β†’ βˆƒM:multi_part Ξ±, M.A=A ∧ M.t =t ∧ βˆ‘v in A, G.deg_res v A + βˆ‘ i in range(M.t+1),βˆ‘ v in (M.P i), G.deg_res v (M.P i) ≀ βˆ‘ v in A, (mp M).deg_res v A:= begin induction t with t ht, {rw zero_add, intros A ha, use (default_M A 0), refine ⟨rfl,rfl,_⟩, rw G.two_clique_free_sum ha, rw zero_add, unfold default_M, dsimp,simp, apply sum_le_sum, intros x hx, rw G.two_clique_free ha x hx,exact zero_le _ }, --- t.succ case {intros A ha, obtain⟨B,hBa,hBc,hBs⟩:=G.furedi_help A ha, have hAsd:=union_sdiff_of_subset hBa, obtain ⟨M,Ma,Mt,Ms⟩:=ht B hBc, have dAB:disjoint M.A (A\B), {rw Ma, exact disjoint_sdiff,}, set H: simple_graph Ξ±:= (mp (insert M dAB)), use (insert M dAB), refine ⟨_,_,_⟩,{ rw [insert_AB, Ma], exact union_sdiff_of_subset hBa}, {rwa [insert_t, Mt]},{ --- so we now have the new partition and "just" need to check the degree sum bound.. have mpc:=mp_count M dAB, rw [insert_AB, Ma , hAsd] at mpc, -- need to sort out the sum over parts in the larger graph rw ← mpc, rw ← G.internal_count dAB, linarith},}, end end simple_graph
# Factors # The term factor refers to a statistical data type used to store categorical variables. # The difference between a categorical variable and a continuous variable is that a categorical variable # can belong to a limited number of categories. A continuous variable, on the other hand, # can correspond to an infinite number of values. # Sex vector sex_vector <- c("Male", "Female", "Female", "Male", "Male") # Convert sex_vector to a factor - function will reduce the vector to a unique set factor_sex_vector <- factor(sex_vector) # Print out factor_sex_vector factor_sex_vector
theory Union_Find_Time imports "Imperative_HOL_Time.Sep_Time_Main" "../Sepreftime/Refine_Imperative_HOL/Sepref_Additional" Collections.Partial_Equivalence_Relation "HOL-Library.Code_Target_Numeral" "Imperative_HOL_Time.Asymptotics_1D" UnionFind_Intf begin notation timeCredit_assn ("$") text {* We implement a simple union-find data-structure based on an array. It uses path compression and a size-based union heuristics. *} subsection {* Abstract Union-Find on Lists *} text {* We first formulate union-find structures on lists, and later implement them using Imperative/HOL. This is a separation of proof concerns between proving the algorithmic idea correct and generating the verification conditions. *} subsubsection {* Representatives *} text {* We define a function that searches for the representative of an element. This function is only partially defined, as it does not terminate on all lists. We use the domain of this function to characterize valid union-find lists. *} function (domintros) rep_of where "rep_of l i = (if l!i = i then i else rep_of l (l!i))" by pat_completeness auto text {* A valid union-find structure only contains valid indexes, and the @{text "rep_of"} function terminates for all indexes. *} definition "ufa_invar l \<equiv> \<forall>i<length l. rep_of_dom (l,i) \<and> l!i<length l" lemma ufa_invarD: "\<lbrakk>ufa_invar l; i<length l\<rbrakk> \<Longrightarrow> rep_of_dom (l,i)" "\<lbrakk>ufa_invar l; i<length l\<rbrakk> \<Longrightarrow> l!i<length l" unfolding ufa_invar_def by auto text {* We derive the following equations for the @{text "rep-of"} function. *} lemma rep_of_refl: "l!i=i \<Longrightarrow> rep_of l i = i" apply (subst rep_of.psimps) apply (rule rep_of.domintros) apply (auto) done lemma rep_of_step: "\<lbrakk>ufa_invar l; i<length l; l!i\<noteq>i\<rbrakk> \<Longrightarrow> rep_of l i = rep_of l (l!i)" apply (subst rep_of.psimps) apply (auto dest: ufa_invarD) done lemmas rep_of_simps = rep_of_refl rep_of_step lemma rep_of_iff: "\<lbrakk>ufa_invar l; i<length l\<rbrakk> \<Longrightarrow> rep_of l i = (if l!i=i then i else rep_of l (l!i))" by (simp add: rep_of_simps) text {* We derive a custom induction rule, that is more suited to our purposes. *} lemma rep_of_induct[case_names base step, consumes 2]: assumes I: "ufa_invar l" assumes L: "i<length l" assumes BASE: "\<And>i. \<lbrakk> ufa_invar l; i<length l; l!i=i \<rbrakk> \<Longrightarrow> P l i" assumes STEP: "\<And>i. \<lbrakk> ufa_invar l; i<length l; l!i\<noteq>i; P l (l!i) \<rbrakk> \<Longrightarrow> P l i" shows "P l i" proof - from ufa_invarD[OF I L] have "ufa_invar l \<and> i<length l \<longrightarrow> P l i" apply (induct l\<equiv>l i rule: rep_of.pinduct) apply (auto intro: STEP BASE dest: ufa_invarD) done thus ?thesis using I L by simp qed text {* In the following, we define various properties of @{text "rep_of"}. *} lemma rep_of_min: "\<lbrakk> ufa_invar l; i<length l \<rbrakk> \<Longrightarrow> l!(rep_of l i) = rep_of l i" proof - have "\<lbrakk>rep_of_dom (l,i) \<rbrakk> \<Longrightarrow> l!(rep_of l i) = rep_of l i" apply (induct arbitrary: rule: rep_of.pinduct) apply (subst rep_of.psimps, assumption) apply (subst (2) rep_of.psimps, assumption) apply auto done thus "\<lbrakk> ufa_invar l; i<length l \<rbrakk> \<Longrightarrow> l!(rep_of l i) = rep_of l i" by (metis ufa_invarD(1)) qed lemma rep_of_bound: "\<lbrakk> ufa_invar l; i<length l \<rbrakk> \<Longrightarrow> rep_of l i < length l" apply (induct rule: rep_of_induct) apply (auto simp: rep_of_iff) done lemma rep_of_idem: "\<lbrakk> ufa_invar l; i<length l \<rbrakk> \<Longrightarrow> rep_of l (rep_of l i) = rep_of l i" by (auto simp: rep_of_min rep_of_refl) lemma rep_of_min_upd: "\<lbrakk> ufa_invar l; x<length l; i<length l \<rbrakk> \<Longrightarrow> rep_of (l[rep_of l x := rep_of l x]) i = rep_of l i" by (metis list_update_id rep_of_min) lemma rep_of_idx: "\<lbrakk>ufa_invar l; i<length l\<rbrakk> \<Longrightarrow> rep_of l (l!i) = rep_of l i" by (metis rep_of_step) subsubsection {* Abstraction to Partial Equivalence Relation *} definition ufa_\<alpha> :: "nat list \<Rightarrow> (nat\<times>nat) set" where "ufa_\<alpha> l \<equiv> {(x,y). x<length l \<and> y<length l \<and> rep_of l x = rep_of l y}" lemma ufa_\<alpha>_equiv[simp, intro!]: "part_equiv (ufa_\<alpha> l)" apply rule unfolding ufa_\<alpha>_def apply (rule symI) apply auto apply (rule transI) apply auto done lemma ufa_\<alpha>_lenD: "(x,y)\<in>ufa_\<alpha> l \<Longrightarrow> x<length l" "(x,y)\<in>ufa_\<alpha> l \<Longrightarrow> y<length l" unfolding ufa_\<alpha>_def by auto lemma ufa_\<alpha>_dom[simp]: "Domain (ufa_\<alpha> l) = {0..<length l}" unfolding ufa_\<alpha>_def by auto lemma ufa_\<alpha>_refl[simp]: "(i,i)\<in>ufa_\<alpha> l \<longleftrightarrow> i<length l" unfolding ufa_\<alpha>_def by simp lemma ufa_\<alpha>_len_eq: assumes "ufa_\<alpha> l = ufa_\<alpha> l'" shows "length l = length l'" by (metis assms le_antisym less_not_refl linorder_le_less_linear ufa_\<alpha>_refl) subsubsection {* Operations *} lemma ufa_init_invar: "ufa_invar [0..<n]" unfolding ufa_invar_def by (auto intro: rep_of.domintros) lemma ufa_init_correct: "ufa_\<alpha> [0..<n] = {(x,x) | x. x<n}" unfolding ufa_\<alpha>_def using ufa_init_invar[of n] apply (auto simp: rep_of_refl) done lemma ufa_find_correct: "\<lbrakk>ufa_invar l; x<length l; y<length l\<rbrakk> \<Longrightarrow> rep_of l x = rep_of l y \<longleftrightarrow> (x,y)\<in>ufa_\<alpha> l" unfolding ufa_\<alpha>_def by auto abbreviation "ufa_union l x y \<equiv> l[rep_of l x := rep_of l y]" lemma ufa_union_invar: assumes I: "ufa_invar l" assumes L: "x<length l" "y<length l" shows "ufa_invar (ufa_union l x y)" unfolding ufa_invar_def proof (intro allI impI, simp only: length_list_update) fix i assume A: "i<length l" with I have "rep_of_dom (l,i)" by (auto dest: ufa_invarD) have "ufa_union l x y ! i < length l" using I L A apply (cases "i=rep_of l x") apply (auto simp: rep_of_bound dest: ufa_invarD) done moreover have "rep_of_dom (ufa_union l x y, i)" using I A L proof (induct rule: rep_of_induct) case (base i) thus ?case apply - apply (rule rep_of.domintros) apply (cases "i=rep_of l x") apply auto apply (rule rep_of.domintros) apply (auto simp: rep_of_min) done next case (step i) from step.prems `ufa_invar l` `i<length l` `l!i\<noteq>i` have [simp]: "ufa_union l x y ! i = l!i" apply (auto simp: rep_of_min rep_of_bound nth_list_update) done from step show ?case apply - apply (rule rep_of.domintros) apply simp done qed ultimately show "rep_of_dom (ufa_union l x y, i) \<and> ufa_union l x y ! i < length l" by blast qed lemma ufa_union_aux: assumes I: "ufa_invar l" assumes L: "x<length l" "y<length l" assumes IL: "i<length l" shows "rep_of (ufa_union l x y) i = (if rep_of l i = rep_of l x then rep_of l y else rep_of l i)" using I IL proof (induct rule: rep_of_induct) case (base i) have [simp]: "rep_of l i = i" using `l!i=i` by (simp add: rep_of_refl) note [simp] = `ufa_invar l` `i<length l` show ?case proof (cases) assume A[simp]: "rep_of l x = i" have [simp]: "l[i := rep_of l y] ! i = rep_of l y" by (auto simp: rep_of_bound) show ?thesis proof (cases) assume [simp]: "rep_of l y = i" show ?thesis by (simp add: rep_of_refl) next assume A: "rep_of l y \<noteq> i" have [simp]: "rep_of (l[i := rep_of l y]) i = rep_of l y" apply (subst rep_of_step[OF ufa_union_invar[OF I L], simplified]) using A apply simp_all apply (subst rep_of_refl[where i="rep_of l y"]) using I L apply (simp_all add: rep_of_min) done show ?thesis by (simp add: rep_of_refl) qed next assume A: "rep_of l x \<noteq> i" hence "ufa_union l x y ! i = l!i" by (auto) also note `l!i=i` finally have "rep_of (ufa_union l x y) i = i" by (simp add: rep_of_refl) thus ?thesis using A by auto qed next case (step i) note [simp] = I L `i<length l` have "rep_of l x \<noteq> i" by (metis I L(1) rep_of_min `l!i\<noteq>i`) hence [simp]: "ufa_union l x y ! i = l!i" by (auto simp add: nth_list_update rep_of_bound `l!i\<noteq>i`) [] have "rep_of (ufa_union l x y) i = rep_of (ufa_union l x y) (l!i)" by (auto simp add: rep_of_iff[OF ufa_union_invar[OF I L]]) also note step.hyps(4) finally show ?case by (auto simp: rep_of_idx) qed lemma ufa_union_correct: "\<lbrakk> ufa_invar l; x<length l; y<length l \<rbrakk> \<Longrightarrow> ufa_\<alpha> (ufa_union l x y) = per_union (ufa_\<alpha> l) x y" unfolding ufa_\<alpha>_def per_union_def by (auto simp: ufa_union_aux split: if_split_asm ) lemma ufa_compress_aux: assumes I: "ufa_invar l" assumes L[simp]: "x<length l" shows "ufa_invar (l[x := rep_of l x])" and "\<forall>i<length l. rep_of (l[x := rep_of l x]) i = rep_of l i" proof - { fix i assume "i<length (l[x := rep_of l x])" hence IL: "i<length l" by simp have G1: "l[x := rep_of l x] ! i < length (l[x := rep_of l x])" using I IL by (auto dest: ufa_invarD[OF I] simp: nth_list_update rep_of_bound) from I IL have G2: "rep_of (l[x := rep_of l x]) i = rep_of l i \<and> rep_of_dom (l[x := rep_of l x], i)" proof (induct rule: rep_of_induct) case (base i) thus ?case apply (cases "x=i") apply (auto intro: rep_of.domintros simp: rep_of_refl) done next case (step i) hence D: "rep_of_dom (l[x := rep_of l x], i)" apply - apply (rule rep_of.domintros) apply (cases "x=i") apply (auto intro: rep_of.domintros simp: rep_of_min) done thus ?case apply simp using step apply - apply (subst rep_of.psimps[OF D]) apply (cases "x=i") apply (auto simp: rep_of_min rep_of_idx) apply (subst rep_of.psimps[where i="rep_of l i"]) apply (auto intro: rep_of.domintros simp: rep_of_min) done qed note G1 G2 } note G=this thus "\<forall>i<length l. rep_of (l[x := rep_of l x]) i = rep_of l i" by auto from G show "ufa_invar (l[x := rep_of l x])" by (auto simp: ufa_invar_def) qed lemma ufa_compress_invar: assumes I: "ufa_invar l" assumes L[simp]: "x<length l" shows "ufa_invar (l[x := rep_of l x])" using assms by (rule ufa_compress_aux) lemma ufa_compress_correct: assumes I: "ufa_invar l" assumes L[simp]: "x<length l" shows "ufa_\<alpha> (l[x := rep_of l x]) = ufa_\<alpha> l" by (auto simp: ufa_\<alpha>_def ufa_compress_aux[OF I]) subsubsection \<open>stuff about the height (by Max Haslbeck)\<close> function (domintros) height_of where "height_of l i = (if l!i = i then 0::nat else 1 + height_of l (l!i))" by pat_completeness auto print_theorems lemma height_of_dom_rep_of_dom[simp]: "height_of_dom (l, i) = rep_of_dom (l, i)" apply(rule) subgoal apply (induct arbitrary: rule: height_of.pinduct) apply (rule rep_of.domintros) by simp subgoal apply (induct arbitrary: rule: rep_of.pinduct) apply (rule height_of.domintros) by simp done lemma height_of_step: "ufa_invar l \<Longrightarrow> i < length l \<Longrightarrow> l ! i \<noteq> i \<Longrightarrow> height_of l i = Suc (height_of l (l ! i))" by (simp add: height_of.psimps ufa_invarD(1)) definition "h_of l i = Max {height_of l j|j. j<length l \<and> rep_of l j = i}" definition invar where "invar l sl = (length l = length sl \<and> sum (\<lambda>i. if l!i=i then sl !i else 0) {0..<length l} = length l \<and> (\<forall>i<length l. l!i=i \<longrightarrow> (2::nat) ^ h_of l i \<le> sl ! i))" lemma invar_sli_le_l: assumes "invar l sl" "ufa_invar l" "i<length l" shows "sl ! (rep_of l i) \<le> length l" proof - from assms(1) have a: "sum (\<lambda>i. if l!i=i then sl !i else 0) {0..<length l} = length l" and len: "length sl = length l" by(auto simp: invar_def) let ?r = "(rep_of l i)" from assms have "?r<length l" by(auto simp: rep_of_bound) then have f: "{0..<length l} = {?r} \<union> ({0..<length l}-{?r})" by auto have "sl ! (?r) \<le> sum (\<lambda>i. if l!i=i then sl !i else 0) ({0..<length l}-{?r}) + (if l!?r=?r then sl !?r else 0)" using assms by (auto simp: rep_of_min) also have "\<dots> = sum (\<lambda>i. if l!i=i then sl !i else 0) {0..<length l}" apply(subst (2) f) apply(subst sum_Un_nat) by simp_all also have "\<dots> = length l" using a by simp finally show "sl ! (rep_of l i) \<le> length l" . qed lemma h_rep: "ufa_invar l \<Longrightarrow> y<length l\<Longrightarrow> height_of l (rep_of l y) = 0" apply (subst height_of.psimps) subgoal by (simp add: rep_of_bound ufa_invarD(1) ufa_union_invar ) by (simp add: rep_of_min) lemma ufa_compress_compresses: "\<lbrakk>ufa_invar l; i<length l; j<length l\<rbrakk> \<Longrightarrow> height_of (l[j:=rep_of l j]) i \<le> height_of l i" proof (induct rule: rep_of_induct) case (base i) then show ?case apply(subst height_of.psimps) subgoal apply simp apply(rule ufa_invarD(1)) by(auto simp add: ufa_compress_invar) apply (auto simp add: rep_of_refl) by (metis nth_list_update' rep_of_iff) next case (step i) show ?case apply(subst height_of.psimps) subgoal using step by (simp add: ufa_invarD(1) ufa_compress_invar ) apply auto apply(subst (2) height_of.psimps) subgoal using step by (simp add: rep_of_bound ufa_invarD(1) ufa_compress_invar ) using step(1-3) apply auto apply(cases "i=j") subgoal apply simp apply(subst height_of.psimps) subgoal by (simp add: rep_of_bound ufa_compress_invar ufa_invarD(1)) using rep_of_min by auto subgoal apply simp apply(rule step(4)) using step by auto done qed lemma ufa_union_on_path_only_increases_by_one: "\<lbrakk>ufa_invar l; i<length l; x<length l; y<length l; rep_of l i = rep_of l x\<rbrakk> \<Longrightarrow> height_of (ufa_union l x y) i \<le> Suc (height_of l i)" proof (induct rule: rep_of_induct) case (base i) then show ?case apply(cases "i=rep_of l x") subgoal apply(subst height_of.psimps) subgoal by (simp add: ufa_invarD(1) ufa_union_invar ) apply simp apply (auto simp add: )[] apply(subst height_of.psimps) subgoal by (simp add: rep_of_bound ufa_invarD(1) ufa_union_invar) apply (auto simp: h_rep)[] by(simp add: rep_of_min) subgoal apply(subst height_of.psimps) subgoal apply simp by (simp add: ufa_invarD(1) ufa_union_invar) by simp done next case (step i) then have not: "i\<noteq>rep_of l x" using rep_of_min by blast show ?case apply(subst height_of.psimps) subgoal using step by (simp add: ufa_invarD(1) ufa_union_invar ) using not apply simp apply(subst (2) height_of.psimps) subgoal using step by (simp add: rep_of_bound ufa_invarD(1) ufa_union_invar ) apply simp apply safe apply(rule step(4)) using step by (auto simp add: rep_of_idx) qed lemma ufa_union_not_on_path_stays: "\<lbrakk>ufa_invar l; i<length l; x<length l; y<length l; rep_of l i \<noteq> rep_of l x\<rbrakk> \<Longrightarrow> height_of (ufa_union l x y) i = height_of l i" proof (induct rule: rep_of_induct) case (base i) then show ?case apply(cases "i=rep_of l x") subgoal by (auto simp add: h_rep rep_of_iff) subgoal apply(subst height_of.psimps) subgoal apply simp by (simp add: ufa_invarD(1) ufa_union_invar) apply auto apply(subst height_of.psimps) subgoal apply simp by (simp add: ufa_invarD(1) ufa_union_invar) by simp done next case (step i) then have not: "i\<noteq>rep_of l x" using rep_of_min by blast show ?case apply(subst height_of.psimps) subgoal using step by (simp add: ufa_invarD(1) ufa_union_invar ) using not step(1-3) apply auto apply(subst (2) height_of.psimps) subgoal using step by (simp add: rep_of_bound ufa_invarD(1) ufa_union_invar ) apply simp apply(rule step(4)) using step by (auto simp add: rep_of_idx) qed lemma ufa_union_on_path: "\<lbrakk>ufa_invar l; i<length l; x<length l; y<length l\<rbrakk> \<Longrightarrow> height_of (ufa_union l x y) i \<le> Suc (height_of l i)" proof (induct rule: rep_of_induct) case (base i) then show ?case apply(cases "i=rep_of l x") subgoal apply(subst height_of.psimps) subgoal by (simp add: ufa_invarD(1) ufa_union_invar ) apply (auto simp add: )[] apply(subst height_of.psimps) subgoal by (simp add: rep_of_bound ufa_invarD(1) ufa_union_invar) apply auto[] by(simp add: rep_of_min) subgoal apply(subst height_of.psimps) subgoal apply simp by (simp add: ufa_invarD(1) ufa_union_invar) by simp done next case (step i) then have not: "i\<noteq>rep_of l x" using rep_of_min by blast show ?case apply(subst height_of.psimps) subgoal using step by (simp add: ufa_invarD(1) ufa_union_invar ) using not apply simp apply(subst (2) height_of.psimps) subgoal using step by (simp add: rep_of_bound ufa_invarD(1) ufa_union_invar ) apply simp apply safe apply(rule step(4)) using step by auto qed lemma hel: "(\<And>x. x\<in>A \<Longrightarrow> f x \<le> g x) \<Longrightarrow> finite A \<Longrightarrow> Max (f ` A) \<le> Max (g ` A)" by (smt Max_ge_iff Max_in finite_imageI imageE image_eqI image_is_empty order_refl) lemma MAXIMUM_mono: "(\<And>x. x\<in>A \<Longrightarrow> f x \<le> g x) \<Longrightarrow> finite A \<Longrightarrow> A = B \<Longrightarrow> Max (f ` A) \<le> Max (g ` B)" using hel by blast lemma MAXIMUM_eq: "(\<And>x. x\<in>A \<Longrightarrow> f x = g x) \<Longrightarrow> finite A \<Longrightarrow> A = B \<Longrightarrow> Max (f ` A) = Max (g ` B)" apply(rule antisym) by (auto intro: MAXIMUM_mono) lemma h_of_alt: "h_of l i = Max ((height_of l) ` {j|j. j<length l \<and> rep_of l j = i})" unfolding h_of_def by (simp add: setcompr_eq_image) lemma h_of_compress: "ufa_invar l \<Longrightarrow> j < length l \<Longrightarrow> h_of (l[j:=rep_of l j]) i \<le> h_of l i" unfolding h_of_alt apply(rule MAXIMUM_mono) subgoal apply(rule ufa_compress_compresses) by auto by (auto simp add: ufa_compress_aux(2)) lemma h_of_uf_union_untouched: "ufa_invar l \<Longrightarrow> x < length l \<Longrightarrow> y < length l \<Longrightarrow> i < length l \<Longrightarrow> l!i = i \<Longrightarrow> i \<noteq> rep_of l x \<Longrightarrow> i \<noteq> rep_of l y \<Longrightarrow> h_of (ufa_union l x y) i = h_of l i" unfolding h_of_alt apply(rule MAXIMUM_eq) subgoal apply(rule ufa_union_not_on_path_stays) using ufa_union_aux by auto using ufa_union_aux by auto lemma Suc_h_of: assumes a: "i < length l " "rep_of l i = i" shows "Suc (h_of l i) = Max ((\<lambda>j. Suc (height_of l j)) ` {j|j. j<length l \<and> rep_of l j = i}) " unfolding h_of_alt apply(subst mono_Max_commute[where f=Suc]) subgoal by (simp add: mono_Suc) subgoal by simp subgoal using a by auto by (simp add: image_image) lemma MAXIMUM_Un: "finite A \<Longrightarrow> finite B \<Longrightarrow> A \<noteq> {} \<Longrightarrow> B \<noteq> {} \<Longrightarrow> Max (f` (A \<union> B) ) = max (Max (f`A)) (Max (f`B) )" apply(simp add: image_Un) apply(subst Max_Un) by auto lemma fixes A::nat shows "A\<le>A' \<Longrightarrow> B\<le>B' \<Longrightarrow> max A B \<le> max A' B'" by auto lemma h_of_uf_union_id: assumes "ufa_invar l "" x < length l "" y < length l "" i < length l " " rep_of l i = i" "i = rep_of l y" and neq: "rep_of l y = rep_of l x" shows "h_of (ufa_union l x y) i = h_of l i" using neq apply simp using assms by (metis list_update_id rep_of_min) lemma h_of_uf_union_touched: assumes "ufa_invar l "" x < length l "" y < length l "" i < length l " " rep_of l i = i" "i = rep_of l y" and neq: "rep_of l y \<noteq> rep_of l x" shows "h_of (ufa_union l x y) i \<le> max (h_of l (rep_of l y)) (Suc (h_of l (rep_of l x)))" proof - have *: "{j|j. j<length (ufa_union l x y) \<and> rep_of (ufa_union l x y) j = i} = {j|j. j<length (ufa_union l x y) \<and> rep_of (ufa_union l x y) j = i \<and> rep_of l j = rep_of l y} \<union> {j|j. j<length (ufa_union l x y) \<and> rep_of (ufa_union l x y) j = i \<and> rep_of l j = rep_of l x}" (is "_ = ?A \<union> ?B") apply auto using assms by (simp add: ufa_union_aux) have A: "?A = {j |j. j < length l \<and> rep_of l j = rep_of l y}" using ufa_union_aux assms by auto have B: "?B = {j |j. j < length l \<and> rep_of l j = rep_of l x}" using ufa_union_aux assms by auto have "h_of (ufa_union l x y) i = Max ( (height_of (ufa_union l x y)) `{j|j. j<length (ufa_union l x y) \<and> rep_of (ufa_union l x y) j = i})" unfolding h_of_alt by simp also have "\<dots> = Max ((height_of (ufa_union l x y))` (?A \<union> ?B) )" unfolding * by simp also have "\<dots> = max (Max ( (height_of (ufa_union l x y))`?A)) (Max ( (height_of (ufa_union l x y))`?B))" apply(subst MAXIMUM_Un) apply simp_all subgoal apply(rule exI[where x=y]) using assms by (simp add: ufa_union_aux) subgoal apply(rule exI[where x=x]) using assms by (simp add: ufa_union_aux) done also have "\<dots> \<le> max (Max ( (height_of l) ` ?A)) (Max ( (\<lambda>j. Suc (height_of l j)) `?B))" apply(rule max.mono) subgoal apply(rule MAXIMUM_mono) subgoal apply(rule order_eq_refl) apply(rule ufa_union_not_on_path_stays) using assms by auto by simp_all subgoal apply(rule MAXIMUM_mono) subgoal apply(rule ufa_union_on_path) using assms by auto apply simp by simp done also have "\<dots> \<le> max (h_of l (rep_of l y)) (Suc (h_of l (rep_of l x)))" apply(rule max.mono) subgoal unfolding h_of_alt A by simp subgoal apply(subst Suc_h_of) subgoal using assms by (auto simp: rep_of_min rep_of_bound rep_of_refl) subgoal using assms by (auto simp: rep_of_min rep_of_bound rep_of_refl) unfolding B by simp done finally show ?thesis . qed lemma height_of_le_h_of: "i < length l \<Longrightarrow> height_of l i \<le> h_of l (rep_of l i)" unfolding h_of_def apply(rule Max.coboundedI) apply simp apply(subst setcompr_eq_image) apply(rule imageI) by auto lemma height_of_ub: assumes "invar l sl" "ufa_invar l" "i<length l" shows "2 ^ (height_of l i) \<le> length l" proof - from assms(1) have "length l = length sl " and 2: "sum (\<lambda>i. if l!i=i then sl !i else 0) {0..<length l} = length l" and 3: "\<And>i. i<length l \<Longrightarrow> l!i=i \<Longrightarrow> (2::nat) ^ h_of l i \<le> sl ! i" unfolding invar_def by auto have *: "height_of l i \<le> h_of l (rep_of l i)" using assms by (auto intro: height_of_le_h_of) have "(2::nat) ^ (height_of l i) \<le> 2 ^ (h_of l (rep_of l i))" apply(rule power_increasing) apply(rule *) by simp also have "\<dots> \<le> sl ! (rep_of l i)" using 3 assms by(auto simp add: rep_of_bound rep_of_min ) also have "\<dots> \<le> length l" using assms by (auto simp: rep_of_bound intro: invar_sli_le_l) finally show ?thesis . qed subsection {* Implementation with Imperative/HOL *} text {* In this section, we implement the union-find data-structure with two arrays, one holding the next-pointers, and another one holding the size information. Note that we do not prove that the array for the size information contains any reasonable values, as the correctness of the algorithm is not affected by this. We leave it future work to also estimate the complexity of the algorithm. *} type_synonym uf = "nat array \<times> nat array" definition is_uf :: "(nat\<times>nat) set \<Rightarrow> uf \<Rightarrow> assn" where "is_uf R u \<equiv> case u of (s,p) \<Rightarrow> \<exists>\<^sub>Al szl. p\<mapsto>\<^sub>al * s\<mapsto>\<^sub>aszl * \<up>(ufa_invar l \<and> ufa_\<alpha> l = R \<and> length szl = length l \<and> invar l szl)" definition uf_init :: "nat \<Rightarrow> uf Heap" where "uf_init n \<equiv> do { l \<leftarrow> Array_Time.of_list [0..<n]; szl \<leftarrow> Array_Time.new n (1::nat); return (szl,l) }" lemma of_list_rule': "<$ (1 + n)> Array_Time.of_list [0..<n] <\<lambda>r. r \<mapsto>\<^sub>a [0..<n]>" using of_list_rule[of "[0..<n]"] by auto lemma height_of_init: "j<n \<Longrightarrow> height_of [0..<n] j = 0" by (simp add: height_of.psimps ufa_init_invar ufa_invarD(1)) lemma h_of_init: "i < n \<Longrightarrow> h_of [0..<n] i = 0" unfolding h_of_def apply auto apply(rule antisym) subgoal apply(rule Max.boundedI) apply simp using ufa_init_invar apply auto apply(rule exI[where x=i]) apply simp subgoal by (simp add: rep_of_refl) apply(rule height_of_init) by simp by simp lemma ufa_init_invar': "invar [0..<n] (replicate n (Suc 0))" unfolding invar_def apply auto using h_of_init by auto definition uf_init_time :: "nat \<Rightarrow> nat" where "uf_init_time n == (2*n+3)" lemma uf_init_bound[asym_bound]: "uf_init_time \<in> \<Theta>(\<lambda>n. n)" unfolding uf_init_time_def by auto2 lemma uf_init_rule: "<$(uf_init_time n)> uf_init n <is_uf {(i,i) |i. i<n}>\<^sub>t" unfolding uf_init_time_def uf_init_def is_uf_def[abs_def] by (sep_auto simp: ufa_init_correct ufa_init_invar ufa_init_invar' zero_time heap: of_list_rule') partial_function (heap_time) uf_rep_of :: "nat array \<Rightarrow> nat \<Rightarrow> nat Heap" where [code]: "uf_rep_of p i = do { n \<leftarrow> Array_Time.nth p i; if n=i then return i else uf_rep_of p n }" lemma uf_rep_of_rule: "\<lbrakk>ufa_invar l; i<length l\<rbrakk> \<Longrightarrow> <p\<mapsto>\<^sub>al * $(height_of l i + 2)> uf_rep_of p i <\<lambda>r. p\<mapsto>\<^sub>al * \<up>(r=rep_of l i)>\<^sub>t" apply (induct rule: rep_of_induct) apply (subst uf_rep_of.simps) apply (sep_auto simp: rep_of_refl) apply (subst uf_rep_of.simps) apply (sep_auto simp: rep_of_step height_of_step) done text {* We chose a non tail-recursive version here, as it is easier to prove. *} partial_function (heap_time) uf_compress :: "nat \<Rightarrow> nat \<Rightarrow> nat array \<Rightarrow> unit Heap" where [code]: "uf_compress i ci p = ( if i=ci then return () else do { ni\<leftarrow>Array_Time.nth p i; uf_compress ni ci p; Array_Time.upd i ci p; return () })" lemma compress_invar: assumes "invar l szl" "ufa_invar l" "i<length l" shows "invar (l[i := rep_of l i]) szl" using assms unfolding invar_def apply safe subgoal by simp subgoal apply simp by (smt nth_list_update_eq nth_list_update_neq rep_of_iff rep_of_min sum.ivl_cong) subgoal for i apply(rule order.trans) apply(rule power_increasing[where N="h_of l i"]) subgoal apply(rule h_of_compress) by auto apply simp apply simp by (metis nth_list_update_eq nth_list_update_neq rep_of_min) done lemma uf_compress_rule: "\<lbrakk> ufa_invar l; i<length l; ci=rep_of l i; invar l szl \<rbrakk> \<Longrightarrow> <p\<mapsto>\<^sub>al * $(1+height_of l i*3)> uf_compress i ci p <\<lambda>_. (\<exists>\<^sub>Al'. p\<mapsto>\<^sub>al' * \<up>(invar l' szl \<and> ufa_invar l' \<and> length l' = length l \<and> (\<forall>i<length l. rep_of l' i = rep_of l i)))>\<^sub>t" proof (induction rule: rep_of_induct) case (base i) thus ?case apply (subst uf_compress.simps) apply (sep_auto simp: rep_of_refl) done next case (step i) note SS = `ufa_invar l` `i<length l` `l!i\<noteq>i` `ci = rep_of l i` `invar l szl` have IH': "<p \<mapsto>\<^sub>a l * $ (1 + height_of l (l ! i) *3)> uf_compress (l ! i) (rep_of l i) p <\<lambda>_. (\<exists>\<^sub>Al'. p \<mapsto>\<^sub>a l' * \<up> (invar l' szl \<and>ufa_invar l' \<and> length l' = length l \<and> (\<forall>i<length l'. rep_of l i = rep_of l' i))) >\<^sub>t" apply(rule pre_rule[OF _ post_rule[OF step.IH[simplified SS rep_of_idx] ]] ) by (sep_auto simp add: rep_of_idx SS)+ show ?case apply (subst uf_compress.simps) apply (sep_auto simp: SS height_of_step heap: ) apply(sep_auto heap: IH') using SS apply (sep_auto ) subgoal using compress_invar by simp subgoal using ufa_compress_invar by fastforce subgoal by simp subgoal using ufa_compress_aux(2) by fastforce done qed definition uf_rep_of_c :: "nat array \<Rightarrow> nat \<Rightarrow> nat Heap" where "uf_rep_of_c p i \<equiv> do { ci\<leftarrow>uf_rep_of p i; uf_compress i ci p; return ci }" lemma uf_rep_of_c_rule: "\<lbrakk>ufa_invar l; i<length l; invar l szl\<rbrakk> \<Longrightarrow> <p\<mapsto>\<^sub>al * $(4+height_of l i*4)> uf_rep_of_c p i <\<lambda>r. (\<exists>\<^sub>Al'. p\<mapsto>\<^sub>al' * \<up>(r=rep_of l i \<and> ufa_invar l' \<and> invar l' szl \<and> length l' = length l \<and> (\<forall>i<length l. rep_of l' i = rep_of l i)))>\<^sub>t" unfolding uf_rep_of_c_def by (sep_auto heap: uf_compress_rule uf_rep_of_rule) thm height_of_ub definition height_ub :: "nat \<Rightarrow> nat" where "height_ub n = nat (ceiling (log 2 n))" lemma height_ub_bound[asym_bound]: "height_ub \<in> \<Theta>(\<lambda>n. ln n)" unfolding height_ub_def using abcd_lnx[of 0 1 1 0] by auto lemma height_ub: assumes "invar l sl" "ufa_invar l" "i<length l" shows "height_of l i \<le> height_ub (length l)" proof - from height_of_ub[OF assms] have "2 ^ height_of l i \<le> length l" . from le_log2_of_power[OF this] show ?thesis unfolding height_ub_def by linarith qed lemma uf_rep_of_c_rule_ub: assumes "ufa_invar l" "i<length l" "invar l szl" shows "<p\<mapsto>\<^sub>al * $(4+ height_ub (length l)*4)> uf_rep_of_c p i <\<lambda>r. (\<exists>\<^sub>Al'. p\<mapsto>\<^sub>al' * \<up>(r=rep_of l i \<and> ufa_invar l' \<and> invar l' szl \<and> length l' = length l \<and> (\<forall>i<length l. rep_of l' i = rep_of l i))) >\<^sub>t" proof - from assms height_ub have "height_of l i \<le> height_ub (length l)" by auto then obtain x where p: "height_ub (length l) = height_of l i + x" using le_Suc_ex by blast show ?thesis unfolding p using assms by(sep_auto heap: uf_rep_of_c_rule) qed definition uf_cmp :: "uf \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> bool Heap" where "uf_cmp u i j \<equiv> do { let (s,p)=u; n\<leftarrow>Array_Time.len p; if (i\<ge>n \<or> j\<ge>n) then return False else do { ci\<leftarrow>uf_rep_of_c p i; cj\<leftarrow>uf_rep_of_c p j; return (ci=cj) } }" lemma cnv_to_ufa_\<alpha>_eq: "\<lbrakk>(\<forall>i<length l. rep_of l' i = rep_of l i); length l = length l'\<rbrakk> \<Longrightarrow> (ufa_\<alpha> l = ufa_\<alpha> l')" unfolding ufa_\<alpha>_def by auto lemma " card (Domain (ufa_\<alpha> l)) = length l" by simp definition uf_cmp_time :: "nat \<Rightarrow> nat" where "uf_cmp_time n = 10+ height_ub n*8" lemma uf_cmp_time_bound[asym_bound]: "uf_cmp_time \<in> \<Theta>(\<lambda>n. ln n)" unfolding uf_cmp_time_def by auto2 lemma uf_cmp_rule: "<is_uf R u * $(uf_cmp_time (card (Domain R)))> uf_cmp u i j <\<lambda>r. is_uf R u * \<up>(r\<longleftrightarrow>(i,j)\<in>R)>\<^sub>t" unfolding uf_cmp_def is_uf_def uf_cmp_time_def apply (sep_auto heap: uf_rep_of_c_rule_ub length_rule dest: ufa_\<alpha>_lenD simp: not_le split: prod.split) (* problem here is, that timeframeinference does not work under equalities. length l' = length l is not used when infering the timeframe *) apply(rule fi_rule[OF uf_rep_of_c_rule_ub]) defer defer defer apply(simp only: mult.assoc) apply(rule match_first) apply simp apply(time_frame_inference) defer apply simp apply simp apply simp apply(sep_auto) apply (drule cnv_to_ufa_\<alpha>_eq, simp_all) apply (drule cnv_to_ufa_\<alpha>_eq, simp_all) apply (drule cnv_to_ufa_\<alpha>_eq, simp_all) apply (drule cnv_to_ufa_\<alpha>_eq, simp_all) apply (drule cnv_to_ufa_\<alpha>_eq, simp_all) apply (drule cnv_to_ufa_\<alpha>_eq, simp_all) apply (subst ufa_find_correct) by (auto simp add: ) definition uf_union :: "uf \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> uf Heap" where "uf_union u i j \<equiv> do { let (s,p)=u; ci \<leftarrow> uf_rep_of p i; cj \<leftarrow> uf_rep_of p j; if (ci=cj) then return (s,p) else do { si \<leftarrow> Array_Time.nth s ci; sj \<leftarrow> Array_Time.nth s cj; if si<sj then do { Array_Time.upd ci cj p; Array_Time.upd cj (si+sj) s; return (s,p) } else do { Array_Time.upd cj ci p; Array_Time.upd ci (si+sj) s; return (s,p) } } }" lemma uf_rep_of_rule_ub: assumes "ufa_invar l" "i<length l" "invar l szl" shows "<p\<mapsto>\<^sub>al * $(height_ub (length l) + 2)> uf_rep_of p i <\<lambda>r. p\<mapsto>\<^sub>al * \<up>(r=rep_of l i)>\<^sub>t" proof - from assms height_ub have "height_of l i \<le> height_ub (length l)" by auto then obtain x where p: "height_ub (length l) = height_of l i + x" using le_Suc_ex by blast show ?thesis unfolding p using assms by(sep_auto heap: uf_rep_of_rule) qed lemma 12: assumes "i < length l " "j < length l" "ufa_invar l " "(i, j) \<notin> ufa_\<alpha> l " and size: "szl ! rep_of l i < szl ! rep_of l j " and i: "invar l szl " shows "invar (ufa_union l i j) (szl[rep_of l j := szl ! rep_of l i + szl ! rep_of l j])" proof - let ?upd = "ufa_union l i j" from i have [simp]: "length szl = length l" unfolding invar_def by auto { fix a b and f :: "'a\<Rightarrow>nat" have r: "a\<noteq>b \<Longrightarrow> sum f {a,b} = f a + f b" by simp } note ff=this have *: "{0..<length l} = ({0..<length l}-{rep_of l j}) \<union> {rep_of l j}" using assms rep_of_bound by auto have **:"{0..<length l} = ({0..<length l}-{rep_of l i,rep_of l j}) \<union> {rep_of l i,rep_of l j}" using assms rep_of_bound by auto have ss: "(({0..<length l} - {rep_of l j}) \<inter> {ia. ?upd ! ia = ia}) = ({0..<length l}-{rep_of l i,rep_of l j}) \<inter> {ia. l ! ia = ia}" using assms by (auto simp: nth_list_update') have "(\<Sum>ia = 0..<length l. if ?upd ! ia = ia then szl[rep_of l j := szl ! rep_of l i + szl ! rep_of l j] ! ia else 0) = sum (\<lambda>ia. if ?upd ! ia = ia then szl[rep_of l j := szl ! rep_of l i + szl ! rep_of l j] ! ia else 0) ({0..<length l}-{rep_of l j}) + (szl ! rep_of l i + szl ! rep_of l j)" (is "?A = _") apply(subst *) apply(subst sum_Un_nat) apply simp apply simp apply simp apply safe subgoal using assms rep_of_bound using invar_def by fastforce subgoal using assms by (simp add: rep_of_min ufa_find_correct) subgoal using assms by (simp add: rep_of_min ufa_find_correct) done also have "\<dots> = sum (\<lambda>i. if l ! i = i then szl ! i else 0) ({0..<length l}-{rep_of l i,rep_of l j}) + (szl ! rep_of l i + szl ! rep_of l j)" (is "?L + _ = ?R + _") proof - have "?L = sum (\<lambda>ia. szl[rep_of l j := szl ! rep_of l i + szl ! rep_of l j] ! ia) (({0..<length l}-{rep_of l j})\<inter>{ia. ?upd ! ia = ia})" apply(subst sum.inter_restrict) by simp_all also have "\<dots> = sum (\<lambda>ia. szl[rep_of l j := szl ! rep_of l i + szl ! rep_of l j] ! ia) (({0..<length l}-{rep_of l i,rep_of l j}) \<inter> {ia. l ! ia = ia})" unfolding ss by simp also have "\<dots> = ?R" apply(subst sum.inter_restrict) apply simp apply auto apply(rule sum.cong) apply simp using assms by auto finally have "?L = ?R" . then show ?thesis by simp qed also have "\<dots> = (\<Sum>i = 0..<length l. if l ! i = i then szl ! i else 0)" apply(subst (2) **) apply(subst sum_Un_nat) apply simp apply simp apply simp apply(subst ff) using assms apply (auto simp: rep_of_min) done also from i have "\<dots> = length l" unfolding invar_def by auto finally have A: "?A = length l" . have max_distrib: "\<And>a b :: nat. (2::nat) ^ max a b = max (2 ^ a) (2 ^ b)" by (simp add: max_def) { assume a: "rep_of l j < length szl" "?upd ! rep_of l j = rep_of l j" from i have g: "\<And>i. i<length l \<Longrightarrow> l ! i = i \<Longrightarrow> 2 ^ h_of l i \<le> szl ! i" unfolding invar_def by metis have "(2::nat) ^ (max (h_of l (rep_of l j)) (Suc (h_of l (rep_of l i)))) \<le> max ( (szl ! (rep_of l j))) (2 * (szl ! (rep_of l i)))" apply(subst max_distrib) apply(rule max.mono) subgoal apply(rule g) using assms a by (auto simp: rep_of_min) subgoal apply(simp only: power.power_Suc) apply(rule mult_left_mono) apply(rule g) using assms a by (auto simp: rep_of_refl rep_of_min rep_of_bound) done also have "\<dots> \<le> szl ! rep_of l i + szl ! rep_of l j" using size by auto finally have "2 ^ max (h_of l (rep_of l j)) (Suc (h_of l (rep_of l i))) \<le> szl ! rep_of l i + szl ! rep_of l j" . } note absch = this show ?thesis unfolding invar_def apply safe subgoal using i[unfolded invar_def] by simp subgoal apply simp using A by simp subgoal for i apply(cases "i=rep_of l j") subgoal apply simp apply(rule order.trans) apply(rule power_increasing[OF h_of_uf_union_touched]) prefer 9 subgoal using absch by simp using assms by (auto simp: rep_of_idem) subgoal apply simp apply(subst h_of_uf_union_untouched) prefer 8 subgoal using i unfolding invar_def by (metis nth_list_update') using assms apply (auto simp: rep_of_idem ) by (metis nth_list_update') done done qed lemma 21: assumes "i < length l "" j < length l "" ufa_invar l " "(i, j) \<notin> ufa_\<alpha> l " and size: "\<not> szl ! rep_of l i < szl ! rep_of l j " and i: "invar l szl " shows "invar (ufa_union l j i) (szl[rep_of l i := szl ! rep_of l i + szl ! rep_of l j])" proof - let ?upd = "ufa_union l j i" from i have [simp]: "length szl = length l" unfolding invar_def by auto { fix a b and f :: "'a\<Rightarrow>nat" have r: "a\<noteq>b \<Longrightarrow> sum f {a,b} = f a + f b" by simp } note ff=this have *: "{0..<length l} = ({0..<length l}-{rep_of l i}) \<union> {rep_of l i}" using assms rep_of_bound by auto have **:"{0..<length l} = ({0..<length l}-{rep_of l i,rep_of l j}) \<union> {rep_of l i,rep_of l j}" using assms rep_of_bound by auto have ss: "(({0..<length l} - {rep_of l i}) \<inter> {ia. ?upd ! ia = ia}) = ({0..<length l}-{rep_of l i,rep_of l j}) \<inter> {ia. l ! ia = ia}" using assms by (auto simp: nth_list_update') have "(\<Sum>ia = 0..<length l. if ?upd ! ia = ia then szl[rep_of l i := szl ! rep_of l i + szl ! rep_of l j] ! ia else 0) = sum (\<lambda>ia. if ?upd ! ia = ia then szl[rep_of l i := szl ! rep_of l i + szl ! rep_of l j] ! ia else 0) ({0..<length l}-{rep_of l i}) + (szl ! rep_of l i + szl ! rep_of l j)" (is "?A = _") apply(subst *) apply(subst sum_Un_nat) apply simp apply simp apply simp apply safe subgoal using assms rep_of_bound using invar_def by fastforce subgoal using assms using rep_of_min ufa_find_correct by fastforce subgoal using assms using rep_of_min ufa_find_correct by fastforce done also have "\<dots> = sum (\<lambda>i. if l ! i = i then szl ! i else 0) ({0..<length l}-{rep_of l i,rep_of l j}) + (szl ! rep_of l i + szl ! rep_of l j)" (is "?L + _ = ?R + _") proof - have "?L = sum (\<lambda>ia. szl[rep_of l i := szl ! rep_of l i + szl ! rep_of l j] ! ia) (({0..<length l}-{rep_of l i})\<inter>{ia. ?upd ! ia = ia})" apply(subst sum.inter_restrict) by simp_all also have "\<dots> = sum (\<lambda>ia. szl[rep_of l i := szl ! rep_of l i + szl ! rep_of l j] ! ia) (({0..<length l}-{rep_of l i,rep_of l j}) \<inter> {ia. l ! ia = ia})" unfolding ss by simp also have "\<dots> = ?R" apply(subst sum.inter_restrict) apply simp apply auto apply(rule sum.cong) apply simp using assms by auto finally have "?L = ?R" . then show ?thesis by simp qed also have "\<dots> = (\<Sum>i = 0..<length l. if l ! i = i then szl ! i else 0)" apply(subst (2) **) apply(subst sum_Un_nat) apply simp apply simp apply simp apply(subst ff) using assms apply (auto simp: rep_of_min) using ufa_find_correct by blast also from i have "\<dots> = length l" unfolding invar_def by auto finally have A: "?A = length l" . have max_distrib: "\<And>a b :: nat. (2::nat) ^ max a b = max (2 ^ a) (2 ^ b)" by (simp add: max_def) { assume a: "rep_of l i < length szl" "?upd ! rep_of l i = rep_of l i" from i have g: "\<And>i. i<length l \<Longrightarrow> l ! i = i \<Longrightarrow> 2 ^ h_of l i \<le> szl ! i" unfolding invar_def by metis have "(2::nat) ^ (max (h_of l (rep_of l i)) (Suc (h_of l (rep_of l j)))) \<le> max ( (szl ! (rep_of l i))) (2 * (szl ! (rep_of l j)))" apply(subst max_distrib) apply(rule max.mono) subgoal apply(rule g) using assms a by (auto simp: rep_of_min) subgoal apply(simp only: power.power_Suc) apply(rule mult_left_mono) apply(rule g) using assms a by (auto simp: rep_of_refl rep_of_min rep_of_bound) done also have "\<dots> \<le> szl ! rep_of l i + szl ! rep_of l j" using size by auto finally have "2 ^ max (h_of l (rep_of l i)) (Suc (h_of l (rep_of l j))) \<le> szl ! rep_of l i + szl ! rep_of l j" . } note absch = this show ?thesis unfolding invar_def apply safe subgoal using i[unfolded invar_def] by simp subgoal apply simp using A by simp subgoal for e apply(cases "e=rep_of l i") subgoal apply simp apply(rule order.trans) apply(rule power_increasing[OF h_of_uf_union_touched]) prefer 9 subgoal using absch by simp using assms by (auto simp: rep_of_idem ufa_find_correct) subgoal apply simp apply(subst h_of_uf_union_untouched) prefer 8 subgoal using i unfolding invar_def by (metis nth_list_update') using assms apply (auto simp: rep_of_idem ) by (metis nth_list_update') done done qed lemma uf_union_rule': "\<lbrakk>i\<in>Domain R; j\<in> Domain R\<rbrakk> \<Longrightarrow> <is_uf R u * $(11+ height_ub (card (Domain R))*2)> uf_union u i j <is_uf (per_union R i j)>\<^sub>t" unfolding uf_union_def apply (cases u) apply (simp add: is_uf_def[abs_def]) apply(sep_auto heap: uf_rep_of_rule_ub) apply(simp add: ufa_\<alpha>_lenD) apply simp apply(sep_auto heap: uf_rep_of_rule_ub) apply(simp add: ufa_\<alpha>_lenD) apply simp apply (sep_auto simp: per_union_cmp ufa_\<alpha>_lenD ufa_find_correct rep_of_bound ufa_union_invar ufa_union_correct ) subgoal apply(drule ufa_\<alpha>_lenD) apply(drule ufa_\<alpha>_lenD) using 12 by blast apply (sep_auto simp: per_union_cmp ufa_\<alpha>_lenD ufa_find_correct rep_of_bound ufa_union_invar ufa_union_correct ) subgoal apply(drule ufa_\<alpha>_lenD) apply(drule ufa_\<alpha>_lenD) using 21 by blast done definition "uf_union_time n = 11+ height_ub n*2" lemma uf_union_time_bound[asym_bound]: "uf_union_time \<in> \<Theta>(\<lambda>n. ln n)" unfolding uf_union_time_def by auto2 lemma uf_union_rule: "\<lbrakk>i\<in>Domain R; j\<in> Domain R\<rbrakk> \<Longrightarrow> <is_uf R u * $(uf_union_time (card (Domain R)))> uf_union u i j <is_uf (per_union R i j)>\<^sub>t" unfolding uf_union_time_def using uf_union_rule' by auto interpretation UF_log: UnionFind_Impl is_uf uf_init uf_init_time uf_cmp uf_cmp_time uf_union uf_union_time proof (unfold_locales, goal_cases) case (1 t x' x) show ?case unfolding PR_CONST_def mop_per_init_def apply simp apply(rule extract_cost_otherway'[OF _ uf_init_rule, where Cost_lb="uf_init_time x"]) apply (sep_auto simp: per_init'_def hn_ctxt_def pure_def)+ using 1 by simp next case (2 t R' R a' a b' b) show ?case unfolding PR_CONST_def mop_per_compare_def apply simp apply(rule extract_cost_otherway'[OF _ uf_cmp_rule, where Cost_lb="(uf_cmp_time (card (Domain R')))"]) apply (sep_auto simp: per_init'_def hn_ctxt_def pure_def)+ using 2 by simp next case (3 t R' R a' a b' b) show ?case unfolding PR_CONST_def mop_per_union_def apply simp apply(rule extract_cost_otherway'[OF _ uf_union_rule, where Cost_lb="(uf_union_time (card (Domain R')))"]) apply (sep_auto simp: per_init'_def hn_ctxt_def pure_def)+ subgoal using 3 by simp apply (sep_auto simp: per_init'_def hn_ctxt_def pure_def)+ subgoal using 3 by simp apply (sep_auto simp: per_init'_def hn_ctxt_def pure_def invalid_assn_def)+ using 3 by simp qed end
df = CSV.File("config/min_max_adj.csv") |> DataFrame! const MINS = Array{Float64}(df[!, :min]) const MAXS = Array{Float64}(df[!, :adj_max]) const DIFF = MAXS .- MINS const ON_INP = .~(Bool.(df[!, :off])) function get_inputs(features::Array{Float64}) inputs = (features .- MINS) ./ DIFF inputs = min.(max.(inputs, -1.0), 1.0) inputs[ON_INP] end
x <- c(1,2,3,4,5,6) # Create ordered collection (vector) y <- x^2 # Square the elements of x print(y) # print (vector) y mean(y) # Calculate average (arithmetic mean) of (vector) y; result is scalar var(y) # Calculate sample variance lm_1<- lm(y ~ x) # Fit a linear regression model "y = f(x)" or "y = B0 + (B1 * x)" # store the results as lm_1 print(lm_1) # Print the model from the (linear model object) lm_1
{-# OPTIONS --safe --without-K #-} module Level where open import Agda.Primitive using (Level) renaming ( _βŠ”_ to _β„“βŠ”_ ; lzero to β„“zero ; lsuc to β„“suc ; Set to Type ) public variable a b c : Level A : Type a B : Type b C : Type c
From Coq Require Import ssreflect ssrfun ssrbool. Local Set Warnings "-notation-overridden". From mathcomp Require Export seq eqtype ssrnat. Theorem fold_union : forall (A: eqType) (l: seq A) f base P, (forall acc a, P (f acc a) = P acc || P a) -> P (foldl f base l) = P base || (has P l). Proof. move => A. elim => [ f base P HP /= | ]. by rewrite orbF. move => a l Hind f base P HP. rewrite /= Hind => //. by rewrite HP orbA. Qed. Theorem fold_intersection : forall (A: eqType) (l: seq A) f base P, (forall acc a, P (f acc a) = P acc && P a) -> P (foldl f base l) = (P base && all P l). Proof. move => A. elim => [ f base P HP | ]; first by rewrite andbT. move => a l Hind f base P HP. rewrite /= Hind => //. by rewrite HP andbA. Qed. Theorem sub_all_in: forall (T : eqType) (a1 a2 : pred T) (s: seq T), subpred (T:=T) (fun x => (x \in s) ==> a1 x) (fun x => (x \in s) ==> a2 x) -> all a1 s -> all a2 s. Proof. move => T a1 a2 s Hsubpred. move => /allP HIn1. apply /allP => x Hx_in. move => /(_ x) in Hsubpred. rewrite Hx_in in Hsubpred. rewrite !implyTb in Hsubpred; auto. Qed. Theorem zip_uniq : forall (A B: eqType) (a: A) (b: B) (s1: seq A) (s2: seq B), uniq s1 -> uniq (zip s1 s2). Proof. move => A B a b s1 s2. move => /uniqP Huniq. apply /(uniqP (a,b)) => x y Hx Hy. move => /(_ a x y) in Huniq. rewrite /in_mem /= in Hx, Hy, Huniq. move: (Hx) (Hy). rewrite !size_zip !leq_min => /andP[Hx1 Hx2] /andP[Hy1 Hy2]. move => /(_ Hx1 Hy1) in Huniq. rewrite !nth_zip_cond Hx Hy. move => [H1 H2]. by auto. Qed. Theorem index_uniq_zip : forall (A B: eqType) (a: A) (b: B) (s1: seq A) (s2: seq B), uniq s1 -> (a, b) \in (zip s1 s2) -> index (a, b) (zip s1 s2) = index a s1. Proof. move => A B a b s1 s2 Huniq Hin. move: (Hin) => Hin'. apply (nth_index (a,b)) in Hin'. rewrite nth_zip_cond in Hin'. rewrite -index_mem in Hin. rewrite Hin in Hin'. case: Hin' => [Hin' _]. rewrite -[in X in _ = X]Hin'. rewrite index_uniq => //. move: Hin. by rewrite size_zip leq_min => /andP[H1 H2]. Qed.
/* * This file belongs to the Galois project, a C++ library for exploiting parallelism. * The code is being released under the terms of the 3-Clause BSD License (a * copy is located in LICENSE.txt at the top-level directory). * * Copyright (C) 2018, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. */ #include <iostream> #include <limits> #include <cmath> #include "galois/DistGalois.h" #include "galois/gstl.h" #include "DistBenchStart.h" #include "galois/DReducible.h" #include "galois/AtomicWrapper.h" #include "galois/ArrayWrapper.h" #include "galois/runtime/Tracer.h" #include "galois/graphs/DistributedGraphLoader.h" #include <boost/serialization/vector.hpp> #include <boost/serialization/array.hpp> #include <boost/archive/binary_oarchive.hpp> #include <boost/archive/binary_iarchive.hpp> using namespace boost::archive; // For resilience #include "resilience.h" #ifdef __GALOIS_HET_CUDA__ #include "galois/cuda/cuda_device.h" #include "gen_cuda.h" struct CUDA_Context* cuda_ctx; #endif constexpr static const char* const regionname = "SGD"; /******************************************************************************/ /* Declaration of command line arguments */ /******************************************************************************/ namespace cll = llvm::cl; static cll::opt<unsigned int> maxIterations("maxIterations", cll::desc("Maximum iterations: Default 10000"), cll::init(10000)); static cll::opt<bool> bipartite( "bipartite", cll::desc("Is graph bipartite? if yes, it expects first N nodes to have " "edges."), cll::init(false)); static cll::opt<double> LEARNING_RATE("LEARNING_RATE", cll::desc("Learning rate (GAMMA): Default 0.00001"), cll::init(0.00001)); static cll::opt<double> LAMBDA("LAMBDA", cll::desc("LAMBDA: Default 0.0001"), cll::init(0.0001)); static cll::opt<double> DECAY_RATE("DECAY_RATE", cll::desc("Decay rate to be used in step size function " "(DECAY_RATE): Default 0.9"), cll::init(0.9)); static cll::opt<double> tolerance( "tolerance", cll::desc("rms normalized tolerance for convergence:Default 0.01"), cll::init(0.01)); /******************************************************************************/ /* Graph structure declarations + helper functions + other initialization */ /******************************************************************************/ #define LATENT_VECTOR_SIZE 20 // static const double LEARNING_RATE = 0.00001; // GAMMA, Purdue: 0.01 Intel: // 0.001 static const double DECAY_RATE = 0.9; // STEP_DEC, Purdue: 0.1 Intel: // 0.9 static const double LAMBDA = 0.0001; // Purdue: 1.0 Intel: 0.001 static const double MINVAL = -1e+100; static const double MAXVAL = 1e+100; const unsigned int infinity = std::numeric_limits<unsigned int>::max() / 4; struct NodeData { // galois::CopyableArray<galois::CopyableAtomic<double>, LATENT_VECTOR_SIZE> // residual_latent_vector; galois::CopyableArray<double, LATENT_VECTOR_SIZE> // latent_vector; std::vector<double> latent_vector; std::vector<galois::CopyableAtomic<double>> residual_latent_vector; template <class Archive> void serialize(Archive& ar, const unsigned int version) { ar& boost::serialization::make_array(latent_vector.data(), LATENT_VECTOR_SIZE); // ar & boost::serialization::make_array(residual_latent_vector.data(), // LATENT_VECTOR_SIZE); } }; galois::DynamicBitSet bitset_latent_vector; galois::DynamicBitSet bitset_residual_latent_vector; typedef galois::graphs::DistGraph<NodeData, double> Graph; // typedef galois::graphs::DistGraph<NodeData, uint32_t> Graph; typedef typename Graph::GraphNode GNode; #include "gen_sync.hh" // TODO: Set seed static double genRand() { // generate a random double in (-1,1) return 2.0 * ((double)std::rand() / (double)RAND_MAX) - 1.0; } static double genVal(uint32_t n) { return 2.0 * ((double)n / (double)RAND_MAX) - 1.0; } // Purdue learning function double getstep_size(unsigned int round) { return LEARNING_RATE * 1.5 / (1.0 + DECAY_RATE * pow(round + 1, 1.5)); } /** * Prediction of edge weight based on 2 latent vectors */ double calcPrediction(const NodeData& movie_data, const NodeData& user_data) { double pred = galois::innerProduct(movie_data.latent_vector, user_data.latent_vector, 0.0); double p = pred; pred = std::min(MAXVAL, pred); pred = std::max(MINVAL, pred); #ifndef NDEBUG if (p != pred) std::cerr << "clamped " << p << " to " << pred << "\n"; #endif return pred; } /******************************************************************************/ /* Algorithm structures */ /******************************************************************************/ struct InitializeGraph { Graph* graph; InitializeGraph(Graph* _graph) : graph(_graph) {} void static go(Graph& _graph) { auto& allNodes = _graph.allNodesRange(); #ifdef __GALOIS_HET_CUDA__ if (personality == GPU_CUDA) { std::string impl_str(_graph.get_run_identifier("InitializeGraph")); galois::StatTimer StatTimer_cuda(impl_str.c_str()); StatTimer_cuda.start(); InitializeGraph_cuda(*allNodes.begin(), *allNodes.end(), cuda_ctx); StatTimer_cuda.stop(); } else if (personality == CPU) #endif galois::do_all(galois::iterate(allNodes.begin(), allNodes.end()), InitializeGraph{&_graph}, galois::loopname("InitializeGraph")); // due to latent_vector being generated randomly, it should be sync'd // to 1 consistent version across all hosts _graph.sync<writeSource, readAny, Reduce_set_latent_vector, Broadcast_latent_vector>("InitializeGraph"); } void operator()(GNode src) const { NodeData& sdata = graph->getData(src); // resize vectors sdata.latent_vector.resize(LATENT_VECTOR_SIZE); sdata.residual_latent_vector.resize(LATENT_VECTOR_SIZE); for (int i = 0; i < LATENT_VECTOR_SIZE; i++) { sdata.latent_vector[i] = genVal(src); // randomly create latent vector sdata.residual_latent_vector[i] = 0; // randomly create latent vector #ifndef NDEBUG if (!std::isnormal(sdata.latent_vector[i])) galois::gDebug("GEN for ", i, " ", sdata.latent_vector[i]); #endif } } }; struct setMasterBitset { Graph* graph; setMasterBitset(Graph* _graph) : graph(_graph) {} void static go(Graph& _graph) { galois::do_all(galois::iterate(_graph.masterNodesRange().begin(), _graph.masterNodesRange().end()), setMasterBitset{&_graph}, galois::loopname("InitializeGraph_crashed_setMasterBiset")); } void operator()(GNode src) const { bitset_latent_vector.set(src); } }; struct InitializeGraph_crashed { Graph* graph; InitializeGraph_crashed(Graph* _graph) : graph(_graph) {} void static go(Graph& _graph) { setMasterBitset::go(_graph); auto& allNodes = _graph.allNodesRange(); #ifdef __GALOIS_HET_CUDA__ if (personality == GPU_CUDA) { std::string impl_str(_graph.get_run_identifier("InitializeGraph")); galois::StatTimer StatTimer_cuda(impl_str.c_str()); StatTimer_cuda.start(); InitializeGraph_cuda(*allNodes.begin(), *allNodes.end(), cuda_ctx); StatTimer_cuda.stop(); } else if (personality == CPU) #endif galois::do_all(galois::iterate(allNodes.begin(), allNodes.end()), InitializeGraph_crashed{&_graph}, galois::loopname("InitializeGraph_crashed")); _graph.sync<writeAny, readAny, Reduce_set_latent_vector, Broadcast_latent_vector, Bitset_latent_vector>( "InitializeGraph_crashed"); } void operator()(GNode src) const { NodeData& sdata = graph->getData(src); // resize vectors sdata.latent_vector.resize(LATENT_VECTOR_SIZE); sdata.residual_latent_vector.resize(LATENT_VECTOR_SIZE); for (int i = 0; i < LATENT_VECTOR_SIZE; i++) { sdata.latent_vector[i] = genVal(src); // randomly create latent vector sdata.residual_latent_vector[i] = 0; // randomly create latent vector #ifndef NDEBUG if (!std::isnormal(sdata.latent_vector[i])) galois::gDebug("GEN for ", i, " ", sdata.latent_vector[i]); #endif } } }; struct InitializeGraph_healthy { Graph* graph; InitializeGraph_healthy(Graph* _graph) : graph(_graph) {} void static go(Graph& _graph) { auto& allNodes = _graph.allNodesRange(); #ifdef __GALOIS_HET_CUDA__ if (personality == GPU_CUDA) { std::string impl_str(_graph.get_run_identifier("InitializeGraph")); galois::StatTimer StatTimer_cuda(impl_str.c_str()); StatTimer_cuda.start(); InitializeGraph_cuda(*allNodes.begin(), *allNodes.end(), cuda_ctx); StatTimer_cuda.stop(); } else if (personality == CPU) #endif galois::do_all(galois::iterate(allNodes.begin(), allNodes.end()), InitializeGraph_healthy{&_graph}, galois::loopname("InitializeGraph_healthy")); _graph.sync<writeAny, readAny, Reduce_set_latent_vector, Broadcast_latent_vector, Bitset_latent_vector>( "InitializeGraph_healthy"); } void operator()(GNode src) const { NodeData& sdata = graph->getData(src); for (int i = 0; i < LATENT_VECTOR_SIZE; i++) { sdata.residual_latent_vector[i] = 0; // randomly create latent vector } bitset_latent_vector.set(src); } }; /* Recovery to be called by resilience based fault tolerance * It is a NoOp */ struct recovery { Graph* graph; recovery(Graph* _graph) : graph(_graph) {} void static go(Graph& _graph) {} }; struct SGD_mergeResidual { Graph* graph; SGD_mergeResidual(Graph* _graph) : graph(_graph) {} void static go(Graph& _graph) { auto& allNodes = _graph.allNodesRange(); #ifdef __GALOIS_HET_CUDA__ if (personality == GPU_CUDA) { std::string impl_str("SGD_" + (_graph.get_run_identifier())); galois::StatTimer StatTimer_cuda(impl_str.c_str()); StatTimer_cuda.start(); int __retval = 0; SGD_all_cuda(__retval, cuda_ctx); // DGAccumulator_accum += __retval; StatTimer_cuda.stop(); } else if (personality == CPU) #endif galois::do_all( galois::iterate(allNodes.begin(), allNodes.end()), SGD_mergeResidual{&_graph}, galois::loopname(_graph.get_run_identifier("SGD_merge").c_str()), galois::steal(), galois::no_stats()); } void operator()(GNode src) const { NodeData& sdata = graph->getData(src); auto& latent_vector = sdata.latent_vector; auto& residual_latent_vector = sdata.residual_latent_vector; for (int i = 0; i < LATENT_VECTOR_SIZE; ++i) { latent_vector[i] += residual_latent_vector[i]; residual_latent_vector[i] = 0; #ifndef NDEBUG if (!std::isnormal(sdata.latent_vector[i])) galois::gDebug("GEN for ", i, " ", sdata.latent_vector[i]); #endif } } }; struct SGD { Graph* graph; double step_size; galois::DGAccumulator<double>& DGAccumulator_accum; SGD(Graph* _graph, double _step_size, galois::DGAccumulator<double>& _dga) : graph(_graph), step_size(_step_size), DGAccumulator_accum(_dga) {} void static go(Graph& _graph, galois::DGAccumulator<double>& dga) { unsigned _num_iterations = 0; unsigned _num_iterations_stepSize = 0; unsigned _num_iterations_checkpointed = 0; double rms_normalized = 0.0; double last = -1.0; double last_checkpointed = -1.0; auto& nodesWithEdges = _graph.allNodesWithEdgesRange(); do { // Checkpointing the all the node data if (enableFT && recoveryScheme == CP) { saveCheckpointToDisk(_num_iterations, _graph); // Saving other state variables if (_num_iterations % checkpointInterval == 0) { last_checkpointed = last; _num_iterations_checkpointed = _num_iterations; } } auto step_size = getstep_size(_num_iterations_stepSize); dga.reset(); galois::do_all(galois::iterate(nodesWithEdges), SGD(&_graph, step_size, dga), galois::loopname(_graph.get_run_identifier("SGD").c_str()), galois::steal(), galois::no_stats()); _graph.sync<writeDestination, readAny, Reduce_pair_wise_add_array_residual_latent_vector, Broadcast_residual_latent_vector, Bitset_residual_latent_vector>("SGD"); SGD_mergeResidual::go(_graph); /**************************CRASH SITE : start * *****************************************/ if (enableFT && (_num_iterations == crashIteration)) { crashSite<recovery, InitializeGraph_crashed, InitializeGraph_healthy>( _graph); ++_num_iterations; if (recoveryScheme == CP) { _num_iterations_stepSize = _num_iterations_checkpointed; last = last_checkpointed; } continue; } /**************************CRASH SITE : end * *****************************************/ // calculate root mean squared error // Divide by 2 since for symmetric graph it is counted twice double error = dga.reduce() / 2; rms_normalized = std::sqrt(error / _graph.globalSizeEdges()); double error_change = std::abs((last - error) / last); if (galois::runtime::getSystemNetworkInterface().ID == 0) { galois::gPrint("ITERATION : ", _num_iterations, "\n"); galois::gDebug("RMS Normalized : ", rms_normalized); galois::gPrint("RMS : ", rms_normalized, "\n"); galois::gPrint("abs(last - error/last) : ", error_change, "\n"); } if (error_change < tolerance) { break; } last = error; ++_num_iterations; ++_num_iterations_stepSize; } while ((_num_iterations < maxIterations)); if (galois::runtime::getSystemNetworkInterface().ID == 0) { galois::runtime::reportStat_Single( regionname, "NumIterations_" + std::to_string(_graph.get_run_num()), (unsigned long)_num_iterations); } } void operator()(GNode src) const { NodeData& sdata = graph->getData(src); auto& movie_node = sdata.latent_vector; auto& residual_movie_node = sdata.residual_latent_vector; for (auto jj = graph->edge_begin(src), ej = graph->edge_end(src); jj != ej; ++jj) { GNode dst = graph->getEdgeDst(jj); auto& ddata = graph->getData(dst); auto& user_node = ddata.latent_vector; auto& residual_user_node = ddata.residual_latent_vector; // auto& sdata_up = sdata.updates; double edge_rating = graph->getEdgeData(jj); // doGradientUpdate double old_dp = galois::innerProduct(user_node, movie_node, double(0)); double cur_error = edge_rating - old_dp; DGAccumulator_accum += (cur_error * cur_error); assert(cur_error < 10000 && cur_error > -10000); bool setBit = false; // update both vectors based on error derived from 2 previous vectors for (int i = 0; i < LATENT_VECTOR_SIZE; ++i) { double prevUser = user_node[i]; double prevMovie = movie_node[i]; // Only update the destination galois::atomicAdd( residual_user_node[i], double(step_size * (cur_error * prevMovie - LAMBDA * prevUser))); // galois::gPrint("val : ", residual_user_node[i], "\n"); assert(std::isnormal(residual_user_node[i])); if (!setBit && std::abs(residual_user_node[i]) > 0.1) setBit = true; // galois::atomicAdd(residual_movie_node[i], double(step_size * // (cur_error * prevUser - LAMBDA * prevMovie))); // assert(std::isnormal(residual_movie_node[i])); } if (setBit) bitset_residual_latent_vector.set(dst); } } }; /******************************************************************************/ /* Main */ /******************************************************************************/ constexpr static const char* const name = "SGD - Distributed Heterogeneous"; constexpr static const char* const desc = "SGD on Distributed Galois."; constexpr static const char* const url = 0; int main(int argc, char** argv) { galois::DistMemSys G; DistBenchStart(argc, argv, name, desc, url); const auto& net = galois::runtime::getSystemNetworkInterface(); if (net.ID == 0) { galois::runtime::reportParam(regionname, "Max Iterations", (unsigned long)maxIterations); galois::runtime::reportParam(regionname, "ENABLE_FT", (enableFT)); } galois::StatTimer StatTimer_total("TimerTotal", regionname); StatTimer_total.start(); #ifdef __GALOIS_HET_CUDA__ Graph* hg = distGraphInitialization<NodeData, double>(&cuda_ctx); #else Graph* hg = distGraphInitialization<NodeData, double>(); #endif // bitset comm setup bitset_latent_vector.resize(hg->size()); bitset_residual_latent_vector.resize(hg->size()); galois::gPrint("[", net.ID, "] InitializeGraph::go called\n"); galois::StatTimer StatTimer_init("TIMER_GRAPH_INIT", regionname); StatTimer_init.start(); InitializeGraph::go((*hg)); StatTimer_init.stop(); galois::runtime::getHostBarrier().wait(); // accumulators for use in operators galois::DGAccumulator<double> DGAccumulator_accum; // galois::DGAccumulator<uint64_t> DGAccumulator_sum; // galois::DGAccumulator<uint32_t> DGAccumulator_max; // galois::GReduceMax<uint32_t> m; for (auto run = 0; run < numRuns; ++run) { galois::gPrint("[", net.ID, "] SGD::go run ", run, " called\n"); std::string timer_str("Timer_" + std::to_string(run)); galois::StatTimer StatTimer_main(timer_str.c_str(), regionname); StatTimer_main.start(); SGD::go((*hg), DGAccumulator_accum); StatTimer_main.stop(); if ((run + 1) != numRuns) { #ifdef __GALOIS_HET_CUDA__ if (personality == GPU_CUDA) { // bitset_dist_current_reset_cuda(cuda_ctx); } else #endif bitset_latent_vector.reset(); bitset_residual_latent_vector.reset(); (*hg).set_num_run(run + 1); InitializeGraph::go((*hg)); galois::runtime::getHostBarrier().wait(); } } StatTimer_total.stop(); return 0; }
Formal statement is: lemma shows sets_lborel[simp, measurable_cong]: "sets lborel = sets borel" and space_lborel[simp]: "space lborel = space borel" and measurable_lborel1[simp]: "measurable M lborel = measurable M borel" and measurable_lborel2[simp]: "measurable lborel M = measurable borel M" Informal statement is: The Lebesgue measure on the real line is the same as the Borel measure on the real line.
!----------------------------------------------------------------------- !Main program string_matching !----------------------------------------------------------------------- program string_matching implicit none character(len=*), parameter :: fmt= '(I0)' write(*,fmt) starts("this","is") write(*,fmt) starts("theory","the") write(*,fmt) has("bananas","an") write(*,fmt) ends("banana","an") write(*,fmt) ends("banana","na") write(*,fmt) ends("brief","much longer") contains ! Determining if the first string starts with second string function starts(string1, string2) result(answer) implicit none character(len=*), intent(in) :: string1 character(len=*), intent(in) :: string2 integer :: answer answer = 0 if(len(string2)>len(string1)) return if(string1(1:len(string2))==string2) answer = 1 end function starts ! Determining if the first string contains the second string at any location function has(string1, string2) result(answer) implicit none character(len=*), intent(in) :: string1 character(len=*), intent(in) :: string2 character(len=:),allocatable :: temp integer :: answer, add character(len=*), parameter :: fmt= '(A6,X,I0)' answer = 0 add = 0 if(len(string2)>len(string1)) return answer = index(string1, string2) if(answer==0) return ! Print the location of the match for part 2 write(*,fmt) " at ", answer ! Handle multiple occurrences of a string for part 2. add = answer temp = string1(answer+1:) do while(answer>0) answer = index(temp, string2) add = add + answer if(answer>0) write(*,fmt) " at ", add ! deallocate(temp) temp = string1(add+1:) ! auto reallocation enddo answer = 1 end function has ! Determining if the first string ends with the second string function ends(string1, string2) result(answer) implicit none character(len=*), intent(in) :: string1 character(len=*), intent(in) :: string2 integer :: answer answer = 0 if(len(string2)>len(string1)) return if(string1(len(string1)-len(string2)+1:)==string2) answer = 1 end function ends end program string_matching
module TTImp.Elab.ImplicitBind -- Machinery needed for handling implicit name bindings (either pattern -- variables or unbound implicits as type variables) import Core.Context import Core.Context.Log import Core.Core import Core.Env import Core.Metadata import Core.Normalise import Core.Unify import Core.UnifyState import Core.TT import Core.Value import TTImp.Elab.Check import TTImp.Elab.Delayed import TTImp.TTImp import Data.List import Libraries.Data.NameMap %default covering -- Make a hole for an unbound implicit in the outer environment export mkOuterHole : {vars : _} -> {auto e : Ref EST (EState vars)} -> {auto c : Ref Ctxt Defs} -> {auto u : Ref UST UState} -> FC -> RigCount -> Name -> Env Term vars -> Maybe (Glued vars) -> Core (Term vars, Term vars) mkOuterHole loc rig n topenv (Just expty_in) = do est <- get EST let sub = subEnv est expected <- getTerm expty_in case shrinkTerm expected sub of -- Can't shrink so rely on unification with expected type later Nothing => mkOuterHole loc rig n topenv Nothing Just exp' => do let env = outerEnv est tm <- implBindVar loc rig env n exp' pure (embedSub sub tm, embedSub sub exp') mkOuterHole loc rig n topenv Nothing = do est <- get EST let sub = subEnv est let env = outerEnv est nm <- genName ("type_of_" ++ nameRoot n) ty <- metaVar loc erased env nm (TType loc) log "elab.implicits" 10 $ "Made metavariable for type of " ++ show n ++ ": " ++ show nm put EST (addBindIfUnsolved nm rig Explicit topenv (embedSub sub ty) (TType loc) est) tm <- implBindVar loc rig env n ty pure (embedSub sub tm, embedSub sub ty) -- Make a hole standing for the pattern variable, which we'll instantiate -- with a bound pattern variable later. -- Returns the hole term, its expected type (this is the type we'll use when -- we see the name later) and the type the binder will need to be when we -- instantiate it. export mkPatternHole : {vars' : _} -> {auto e : Ref EST (EState vars')} -> {auto c : Ref Ctxt Defs} -> {auto u : Ref UST UState} -> FC -> RigCount -> Name -> Env Term vars' -> BindMode -> Maybe (Glued vars') -> Core (Term vars', Term vars', Term vars') mkPatternHole loc rig n env (PI _) exp = do (tm, exp) <- mkOuterHole loc rig n env exp pure (tm, exp, exp) mkPatternHole {vars'} loc rig n topenv imode (Just expty_in) = do est <- get EST let sub = subEnv est let env = outerEnv est expected <- getTerm expty_in case bindInner topenv expected sub of Nothing => mkPatternHole loc rig n topenv imode Nothing Just exp' => do tm <- implBindVar loc rig env n exp' pure (apply loc (embedSub sub tm) (mkArgs sub), expected, embedSub sub exp') where mkArgs : {vs : _} -> SubVars newvars vs -> List (Term vs) mkArgs SubRefl = [] mkArgs (DropCons p) = Local loc Nothing 0 First :: map weaken (mkArgs p) mkArgs _ = [] -- This is for the specific situation where we're pattern matching on -- function types, which is realistically the only time we'll legitimately -- encounter a type variable under a binder bindInner : {vs : _} -> Env Term vs -> Term vs -> SubVars newvars vs -> Maybe (Term newvars) bindInner env ty SubRefl = Just ty bindInner {vs = x :: _} (b :: env) ty (DropCons p) = bindInner env (Bind loc x b ty) p bindInner _ _ _ = Nothing mkPatternHole loc rig n env _ _ = throw (GenericMsg loc ("Unknown type for pattern variable " ++ show n)) -- For any of the 'bindIfUnsolved' - these were added as holes during -- elaboration, but are as yet unsolved, so create a pattern variable for -- them and unify. -- (This is only when we're in a mode that allows unbound implicits) bindUnsolved : {vars : _} -> {auto c : Ref Ctxt Defs} -> {auto e : Ref EST (EState vars)} -> {auto u : Ref UST UState} -> FC -> ElabMode -> BindMode -> Core () bindUnsolved fc elabmode NONE = pure () bindUnsolved {vars} fc elabmode _ = do est <- get EST defs <- get Ctxt let bifs = bindIfUnsolved est log "elab.implicits" 5 $ "Bindable unsolved implicits: " ++ show (map fst bifs) traverse_ (mkImplicit defs (outerEnv est) (subEnv est)) (bindIfUnsolved est) where makeBoundVar : {outer, vs : _} -> Name -> RigCount -> PiInfo (Term vs) -> Env Term outer -> SubVars outer vs -> SubVars outer vars -> Term vs -> Core (Term vs) makeBoundVar n rig p env sub subvars expected = case shrinkTerm expected sub of Nothing => do tmn <- toFullNames expected throw (GenericMsg fc ("Can't bind implicit " ++ show n ++ " of type " ++ show tmn)) Just exp' => do impn <- genVarName (nameRoot n) tm <- metaVar fc rig env impn exp' est <- get EST let p' : PiInfo (Term vars) = forgetDef p put EST (record { toBind $= ((impn, NameBinding rig p' (embedSub subvars tm) (embedSub subvars exp')) ::) } est) pure (embedSub sub tm) mkImplicit : {outer : _} -> Defs -> Env Term outer -> SubVars outer vars -> (Name, RigCount, (vars' ** (Env Term vars', PiInfo (Term vars'), Term vars', Term vars', SubVars outer vars'))) -> Core () mkImplicit defs outerEnv subEnv (n, rig, (vs ** (env, p, tm, exp, sub))) = do Just (Hole _ _) <- lookupDefExact n (gamma defs) | _ => pure () bindtm <- makeBoundVar n rig p outerEnv sub subEnv !(normaliseHoles defs env exp) logTerm "elab.implicits" 5 ("Added unbound implicit") bindtm ignore $ unify (case elabmode of InLHS _ => inLHS _ => inTerm) fc env tm bindtm swapIsVarH : {idx : Nat} -> (0 p : IsVar nm idx (x :: y :: xs)) -> Var (y :: x :: xs) swapIsVarH First = MkVar (Later First) swapIsVarH (Later p) = swapP p -- it'd be nice to do this all at the top -- level, but that will need an improvement -- in erasability checking where swapP : forall name . {idx : _} -> (0 p : IsVar name idx (y :: xs)) -> Var (y :: x :: xs) swapP First = MkVar First swapP (Later x) = MkVar (Later (Later x)) swapIsVar : (vs : List Name) -> {idx : Nat} -> (0 p : IsVar nm idx (vs ++ x :: y :: xs)) -> Var (vs ++ y :: x :: xs) swapIsVar [] prf = swapIsVarH prf swapIsVar (x :: xs) First = MkVar First swapIsVar (x :: xs) (Later p) = let MkVar p' = swapIsVar xs p in MkVar (Later p') swapVars : {vs : List Name} -> Term (vs ++ x :: y :: ys) -> Term (vs ++ y :: x :: ys) swapVars (Local fc x idx p) = let MkVar p' = swapIsVar _ p in Local fc x _ p' swapVars (Ref fc x name) = Ref fc x name swapVars (Meta fc n i xs) = Meta fc n i (map swapVars xs) swapVars {vs} (Bind fc x b scope) = Bind fc x (map swapVars b) (swapVars {vs = x :: vs} scope) swapVars (App fc fn arg) = App fc (swapVars fn) (swapVars arg) swapVars (As fc s nm pat) = As fc s (swapVars nm) (swapVars pat) swapVars (TDelayed fc x tm) = TDelayed fc x (swapVars tm) swapVars (TDelay fc x ty tm) = TDelay fc x (swapVars ty) (swapVars tm) swapVars (TForce fc r tm) = TForce fc r (swapVars tm) swapVars (PrimVal fc c) = PrimVal fc c swapVars (Erased fc i) = Erased fc i swapVars (TType fc) = TType fc -- Push an explicit pi binder as far into a term as it'll go. That is, -- move it under implicit binders that don't depend on it, and stop -- when hitting any non-implicit binder push : {vs : _} -> FC -> (n : Name) -> Binder (Term vs) -> Term (n :: vs) -> Term vs push ofc n b tm@(Bind fc (PV x i) (Pi fc' c Implicit ty) sc) -- only push past 'PV's = case shrinkTerm ty (DropCons SubRefl) of Nothing => -- needs explicit pi, do nothing Bind ofc n b tm Just ty' => Bind fc (PV x i) (Pi fc' c Implicit ty') (push ofc n (map weaken b) (swapVars {vs = []} sc)) push ofc n b tm = Bind ofc n b tm -- Move any implicit arguments as far to the left as possible - this helps -- with curried applications -- We only do this for variables named 'PV', since they are the unbound -- implicits, and we don't want to move any given by the programmer liftImps : {vars : _} -> BindMode -> (Term vars, Term vars) -> (Term vars, Term vars) liftImps (PI _) (tm, TType fc) = (liftImps' tm, TType fc) where liftImps' : {vars : _} -> Term vars -> Term vars liftImps' (Bind fc (PV n i) b@(Pi _ _ Implicit _) sc) = Bind fc (PV n i) b (liftImps' sc) liftImps' (Bind fc n b@(Pi _ _ _ _) sc) = push fc n b (liftImps' sc) liftImps' tm = tm liftImps _ x = x -- Bind implicit arguments, returning the new term and its updated type bindImplVars : FC -> BindMode -> Defs -> Env Term vars -> List (Name, ImplBinding vars) -> Term vars -> Term vars -> (Term vars, Term vars) bindImplVars fc NONE gam env imps_in scope scty = (scope, scty) bindImplVars {vars} fc mode gam env imps_in scope scty = let imps = map (\ (x, bind) => (tidyName x, x, bind)) imps_in in getBinds imps None scope scty where -- Turn the pattern variable name into the user's original choice, -- now that there's no longer a risk of clash tidyName : Name -> Name tidyName (NS _ n) = tidyName n tidyName (PV n _) = tidyName n tidyName (Nested n inner) = tidyName inner tidyName n = n getBinds : (imps : List (Name, Name, ImplBinding vs)) -> Bounds new -> (tm : Term vs) -> (ty : Term vs) -> (Term (new ++ vs), Term (new ++ vs)) getBinds [] bs tm ty = (refsToLocals bs tm, refsToLocals bs ty) getBinds {new} ((n, metan, NameBinding c p _ bty) :: imps) bs tm ty = let (tm', ty') = getBinds imps (Add n metan bs) tm ty bty' = refsToLocals bs bty in case mode of PI c => (Bind fc _ (Pi fc c Implicit bty') tm', TType fc) _ => (Bind fc _ (PVar fc c (map (weakenNs (sizeOf bs)) p) bty') tm', Bind fc _ (PVTy fc c bty') ty') getBinds ((n, metan, AsBinding c _ _ bty bpat) :: imps) bs tm ty = let (tm', ty') = getBinds imps (Add n metan bs) tm ty bty' = refsToLocals bs bty bpat' = refsToLocals bs bpat in (Bind fc _ (PLet fc c bpat' bty') tm', Bind fc _ (PLet fc c bpat' bty') ty') normaliseHolesScope : {auto c : Ref Ctxt Defs} -> {vars : _} -> Defs -> Env Term vars -> Term vars -> Core (Term vars) normaliseHolesScope defs env (Bind fc n b sc) = pure $ Bind fc n b !(normaliseHolesScope defs -- use Lam because we don't want it reducing in the scope (Lam fc (multiplicity b) Explicit (binderType b) :: env) sc) normaliseHolesScope defs env tm = normaliseHoles defs env tm export bindImplicits : {auto c : Ref Ctxt Defs} -> {vars : _} -> FC -> BindMode -> Defs -> Env Term vars -> List (Name, ImplBinding vars) -> Term vars -> Term vars -> Core (Term vars, Term vars) bindImplicits fc NONE defs env hs tm ty = pure (tm, ty) bindImplicits {vars} fc mode defs env hs tm ty = do hs' <- traverse nHoles hs pure $ liftImps mode $ bindImplVars fc mode defs env hs' tm ty where nHoles : (Name, ImplBinding vars) -> Core (Name, ImplBinding vars) nHoles (n, NameBinding c p tm ty) = pure (n, NameBinding c p tm !(normaliseHolesScope defs env ty)) nHoles (n, AsBinding c p tm ty pat) = pure (n, AsBinding c p tm !(normaliseHolesScope defs env ty) pat) export implicitBind : {auto c : Ref Ctxt Defs} -> {auto u : Ref UST UState} -> Name -> Core () implicitBind n = do defs <- get Ctxt Just (Hole _ _) <- lookupDefExact n (gamma defs) | _ => pure () updateDef n (const (Just ImpBind)) removeHoleName n -- 'toBind' are the names which are to be implicitly bound (pattern bindings and -- unbound implicits). -- Return the names in the order they should be bound: i.e. respecting -- dependencies between types, and putting @-patterns last because their -- value is determined from the patterns export getToBind : {vars : _} -> {auto c : Ref Ctxt Defs} -> {auto e : Ref EST (EState vars)} -> {auto u : Ref UST UState} -> FC -> ElabMode -> BindMode -> Env Term vars -> (excepts : List Name) -> Core (List (Name, ImplBinding vars)) getToBind fc elabmode NONE env excepts = pure [] -- We should probably never get here, but for completeness... getToBind {vars} fc elabmode impmode env excepts = do solveConstraints (case elabmode of InLHS _ => inLHS _ => inTerm) Normal bindUnsolved fc elabmode impmode solveConstraints (case elabmode of InLHS _ => inLHS _ => inTerm) Normal defs <- get Ctxt est <- get EST let tob = reverse $ filter (\x => not (fst x `elem` excepts)) $ toBind est -- Make sure all the hole names are normalised in the implicitly -- bound types, because otherwise we'll bind them too res <- normImps defs [] tob let hnames = map fst res -- Return then in dependency order let res' = depSort hnames res log "elab.implicits" 10 $ "Bound names: " ++ show res log "elab.implicits" 10 $ "Sorted: " ++ show res' pure res' where normBindingTy : Defs -> ImplBinding vars -> Core (ImplBinding vars) normBindingTy defs (NameBinding c p tm ty) = pure $ NameBinding c p tm !(normaliseHoles defs env ty) normBindingTy defs (AsBinding c p tm ty pat) = pure $ AsBinding c p tm !(normaliseHoles defs env ty) !(normaliseHoles defs env pat) normImps : Defs -> List Name -> List (Name, ImplBinding vars) -> Core (List (Name, ImplBinding vars)) normImps defs ns [] = pure [] normImps defs ns ((PV n i, bty) :: ts) = do logTermNF "elab.implicits" 10 ("Implicit pattern var " ++ show (PV n i)) env (bindingType bty) if PV n i `elem` ns then normImps defs ns ts else do rest <- normImps defs (PV n i :: ns) ts pure ((PV n i, !(normBindingTy defs bty)) :: rest) normImps defs ns ((n, bty) :: ts) = do tmnf <- normaliseHoles defs env (bindingTerm bty) logTerm "elab.implicits" 10 ("Normalising implicit " ++ show n) tmnf case getFnArgs tmnf of -- n reduces to another hole, n', so treat it as that as long -- as it isn't already done (Meta _ n' i margs, args) => do hole <- isCurrentHole i if hole && not (n' `elem` ns) then do rest <- normImps defs (n' :: ns) ts btynf <- normBindingTy defs bty pure ((n', btynf) :: rest) else normImps defs ns ts _ => -- Unified to something concrete, so drop it normImps defs ns ts -- Insert the hole/binding pair into the list before the first thing -- which refers to it insert : (Name, ImplBinding vars) -> List Name -> List Name -> List (Name, ImplBinding vars) -> List (Name, ImplBinding vars) insert h ns sofar [] = [h] insert (hn, bty) ns sofar ((hn', bty') :: rest) = let used = filter (\n => elem n ns) (keys (bindingMetas bty')) in -- 'used' is to make sure we're only worrying about metavariables -- introduced in *this* expression (there may be others unresolved -- from elsewhere, for type inference purposes) if hn `elem` used then (hn, bty) :: (hn', bty') :: rest else (hn', bty') :: insert (hn, bty) ns (hn' :: sofar) rest -- Sort the list of implicits so that each binding is inserted *after* -- all the things it depends on (assumes no cycles) depSort : List Name -> List (Name, ImplBinding vars) -> List (Name, ImplBinding vars) depSort hnames [] = [] depSort hnames (h :: hs) = insert h hnames [] (depSort hnames hs) export checkBindVar : {vars : _} -> {auto c : Ref Ctxt Defs} -> {auto m : Ref MD Metadata} -> {auto u : Ref UST UState} -> {auto e : Ref EST (EState vars)} -> RigCount -> ElabInfo -> NestedNames vars -> Env Term vars -> FC -> UserName -> -- username is base of the pattern name Maybe (Glued vars) -> Core (Term vars, Glued vars) checkBindVar rig elabinfo nest env fc str topexp = do let elabmode = elabMode elabinfo -- In types, don't rebind if the name is already in scope; -- Below, return True if we don't need to implicitly bind the name let False = case implicitMode elabinfo of PI _ => maybe False (const True) (defined (UN str) env) _ => False | _ => check rig elabinfo nest env (IVar fc (UN str)) topexp est <- get EST let n = PV (UN str) (defining est) noteLHSPatVar elabmode (UN str) notePatVar n est <- get EST whenJust (isConcreteFC fc) $ \nfc => do log "ide-mode.highlight" 7 $ "getNameType is adding Bound: " ++ show n addSemanticDecorations [(nfc, Bound, Just n)] case lookup n (boundNames est) of Nothing => do (tm, exp, bty) <- mkPatternHole fc rig n env (implicitMode elabinfo) topexp -- In PI mode, it's invertible like any other pi bound thing case implicitMode elabinfo of PI _ => setInvertible fc n _ => pure () log "elab.implicits" 5 $ "Added Bound implicit " ++ show (n, (rig, tm, exp, bty)) est <- get EST put EST (record { boundNames $= ((n, NameBinding rig Explicit tm exp) ::), toBind $= ((n, NameBinding rig Explicit tm bty) :: ) } est) log "metadata.names" 7 $ "checkBindVar is adding ↓" addNameType fc (UN str) env exp addNameLoc fc (UN str) checkExp rig elabinfo env fc tm (gnf env exp) topexp Just bty => do -- Check rig is consistent with the one in bty, and -- update if necessary combine (UN str) rig (bindingRig bty) let tm = bindingTerm bty let ty = bindingType bty log "metadata.names" 7 $ "checkBindVar is adding ↓" addNameType fc (UN str) env ty addNameLoc fc (UN str) checkExp rig elabinfo env fc tm (gnf env ty) topexp where updateRig : Name -> RigCount -> List (Name, ImplBinding vars) -> List (Name, ImplBinding vars) updateRig n c [] = [] updateRig n c ((bn, r) :: bs) = if n == bn then case r of NameBinding _ p tm ty => (bn, NameBinding c p tm ty) :: bs AsBinding _ p tm ty pat => (bn, AsBinding c p tm ty pat) :: bs else (bn, r) :: updateRig n c bs -- Two variables are incompatble if at least one of them appears in a linear position -- and their sum is bigger than 1 isIncompatible : RigCount -> RigCount -> Bool isIncompatible l r = (isLinear l || isLinear r) && linear < l |+| r combine : Name -> RigCount -> RigCount -> Core () combine n l r = when (isIncompatible l r) (throw (LinearUsed fc 2 n)) checkPolyConstraint : {auto c : Ref Ctxt Defs} -> PolyConstraint -> Core () checkPolyConstraint (MkPolyConstraint fc env arg x y) = do defs <- get Ctxt -- If 'x' is a metavariable and 'y' is concrete, that means we've -- ended up putting something too concrete in for a polymorphic -- argument xnf <- continueNF defs env x case xnf of NApp _ (NMeta _ _ _) _ => do ynf <- continueNF defs env y if !(concrete defs env ynf) then do empty <- clearDefs defs throw (MatchTooSpecific fc env arg) else pure () _ => pure () checkPolyConstraint _ = pure () solvePolyConstraint : {auto c : Ref Ctxt Defs} -> {auto u : Ref UST UState} -> PolyConstraint -> Core () solvePolyConstraint (MkPolyConstraint fc env arg x y) = do defs <- get Ctxt -- If the LHS of the constraint isn't a metavariable, we can solve -- the constraint case !(continueNF defs env x) of xnf@(NApp _ (NMeta _ _ _) _) => pure () t => do res <- unify inLHS fc env t !(continueNF defs env y) -- If there's any constraints, it just means we didn't -- solve anything and it won't help the check pure () export checkBindHere : {vars : _} -> {auto c : Ref Ctxt Defs} -> {auto m : Ref MD Metadata} -> {auto u : Ref UST UState} -> {auto e : Ref EST (EState vars)} -> RigCount -> ElabInfo -> NestedNames vars -> Env Term vars -> FC -> BindMode -> RawImp -> Maybe (Glued vars) -> Core (Term vars, Glued vars) checkBindHere rig elabinfo nest env fc bindmode tm exp = do est <- get EST let oldenv = outerEnv est let oldsub = subEnv est let oldbif = bindIfUnsolved est let dontbind = map fst (toBind est) -- Set the binding environment in the elab state - unbound -- implicits should have access to whatever is in scope here put EST (updateEnv env SubRefl [] est) constart <- getNextEntry (tmv, tmt) <- check rig (record { implicitMode = bindmode, bindingVars = True } elabinfo) nest env tm exp let solvemode = case elabMode elabinfo of InLHS c => inLHS _ => inTerm solveConstraints solvemode Normal ust <- get UST catch (retryDelayed solvemode (delayedElab ust)) (\err => do ust <- get UST put UST (record { delayedElab = [] } ust) throw err) -- Check all the patterns standing for polymorphic variables are -- indeed polymorphic ust <- get UST let cons = polyConstraints ust put UST (record { polyConstraints = [] } ust) traverse_ solvePolyConstraint cons traverse_ checkPolyConstraint cons solveConstraintsAfter constart (case elabMode elabinfo of InLHS c => inLHS _ => inTerm) Defaults checkDots -- Check dot patterns unifying with the claimed thing -- before binding names logTerm "elab.implicits" 5 "Binding names" tmv logTermNF "elab.implicits" 5 "Normalised" env tmv argImps <- getToBind fc (elabMode elabinfo) bindmode env dontbind clearToBind dontbind est <- get EST put EST (updateEnv oldenv oldsub oldbif (record { boundNames = [] } est)) ty <- getTerm tmt defs <- get Ctxt (bv, bt) <- bindImplicits fc bindmode defs env argImps !(normaliseHoles defs env tmv) !(normaliseHoles defs env ty) traverse_ implicitBind (map fst argImps) checkExp rig elabinfo env fc bv (gnf env bt) exp
-- expressions data SourcePos = SP String Nat Nat Show SourcePos where show (SP x k j) = x ++ ":" ++ (show k) ++ "," ++ (show j) one : Nat one = unsafePerformIO $ do putStrLn "ALEX" pure 3 data Name = Name' String Show Name where show (Name' x) = x Eq Name where (==) (Name' x) (Name' y) = x == y data Expr = Var Name -- x | Pi Name Expr Expr -- (Ξ  ((x A)) B) | Lambda Name Expr -- (Ξ» (x) b) | App Expr Expr -- (rator rand) | Sigma Name Expr Expr -- (Ξ£ ((x A)) D) | Cons Expr Expr -- (cons a d) | Car Expr -- (car e) | Cdr Expr -- (cdr e) | Nat -- Nat | Zero -- zero | Add1 Expr -- (add1 e) | IndNat Expr Expr Expr Expr -- (ind-nat tgt mot base step) | Equal Expr Expr Expr -- (= A from to) | Same -- Same | Replace Expr Expr Expr -- (replace tgt mot base) | Trivial -- Trivial | Sole -- sole | Absurd -- Absurd | IndAbsurd Expr Expr -- (ind-Absurd tgt mot) | Atom -- Atom | Tick String -- 'a | U -- U | The Expr Expr -- (the t e) | SrcPos SourcePos Expr Show Expr where Eq Expr where Namespace : Type Namespace = List (Name, Integer) %name Namespace ns1, ns2, ns3 -- alpha equivalence aEquivHelper : (i : Integer) -> Namespace -> Expr -> Namespace -> Expr -> Bool aEquivHelper i ns1 (Var x) ns2 (Var y) = case (lookup x ns1, lookup y ns2) of (Nothing, Nothing) => x == y (Just j, Just k) => i == j _ => False aEquivHelper i ns1 (Pi x a1 r1) ns2 (Pi y a2 r2) = aEquivHelper i ns1 a1 ns2 a2 && aEquivHelper (i+1) ((x, i) :: ns1) r1 ((y, i) :: ns2) r2 aEquivHelper i ns1 (Lambda x body1) ns2 (Lambda y body2) = aEquivHelper (i+1) ((x, i) :: ns1) body1 ((y, i) :: ns2) body2 aEquivHelper i ns1 (App rator1 rand1) ns2 (App rator2 rand2) = aEquivHelper i ns1 rator1 ns2 rator2 && aEquivHelper i ns1 rand1 ns2 rand2 aEquivHelper i ns1 (Sigma x a1 d1) ns2 (Sigma y a2 d2) = aEquivHelper i ns1 a1 ns2 a2 && aEquivHelper (i+1) ((x, i) :: ns1) d1 ((y, i) :: ns2) d2 aEquivHelper i ns1 (Cons car1 cdr1) ns2 (Cons car2 cdr2) = aEquivHelper i ns1 car1 ns2 car2 && aEquivHelper i ns1 cdr1 ns2 cdr2 aEquivHelper i ns1 (Car pair1) ns2 (Car pair2) = aEquivHelper i ns1 pair1 ns2 pair2 aEquivHelper i ns1 (Cdr pair1) ns2 (Cdr pair2) = aEquivHelper i ns1 pair1 ns2 pair2 aEquivHelper _ _ Nat _ Nat = True aEquivHelper _ _ Zero _ Zero = True aEquivHelper i ns1 (Add1 e1) ns2 (Add1 e2) = aEquivHelper i ns1 e1 ns2 e2 aEquivHelper i ns1 (IndNat tgt1 mot1 base1 step1) ns2 (IndNat tgt2 mot2 base2 step2) = aEquivHelper i ns1 tgt1 ns2 tgt2 && aEquivHelper i ns1 mot1 ns2 mot2 && aEquivHelper i ns1 base1 ns2 base2 && aEquivHelper i ns1 step1 ns2 step2 aEquivHelper i ns1 (Equal ty1 from1 to1) ns2 (Equal ty2 from2 to2) = aEquivHelper i ns1 ty1 ns2 ty2 && aEquivHelper i ns1 from1 ns2 from2 && aEquivHelper i ns1 to1 ns2 to2 aEquivHelper _ _ Same _ Same = True aEquivHelper i ns1 (Replace tgt1 mot1 base1) ns2 (Replace tgt2 mot2 base2) = aEquivHelper i ns1 tgt1 ns2 tgt2 && aEquivHelper i ns1 mot1 ns2 mot2 && aEquivHelper i ns1 base1 ns2 base2 aEquivHelper _ _ Trivial _ Trivial = True aEquivHelper _ _ Sole _ Sole = True aEquivHelper _ _ Absurd _ Absurd = True aEquivHelper _ _ Atom _ Atom = True aEquivHelper _ _ U _ Atom = True aEquivHelper i ns1 (IndAbsurd tgt1 mot1) ns2 (IndAbsurd tgt2 mot2) = aEquivHelper i ns1 tgt1 ns2 tgt2 && aEquivHelper i ns1 mot1 ns2 mot2 aEquivHelper i ns1 (Tick a1) ns2 (Tick a2) = a1 == a2 aEquivHelper _ _ (The Absurd _) _ (The Absurd _) = True aEquivHelper i ns1 (The t1 e1) ns2 (The t2 e2) = aEquivHelper i ns1 t1 ns2 t2 && aEquivHelper i ns1 e1 ns2 e2 aEquivHelper i ns1 (SrcPos str1 e1) ns2 (SrcPos str2 e2) = aEquivHelper i ns1 e1 ns2 e2 aEquivHelper _ _ _ _ _ = False aEquiv : Expr -> Expr -> Bool aEquiv e1 e2 = aEquivHelper 0 [] e1 [] e2 mutual data Neutral = NVar Name | NApp Neutral Normal | NCar Neutral | NCdr Neutral | NIndNat Neutral Normal Normal Normal | NReplace Neutral Normal Normal | NIndAbsurd Neutral Normal data Normal = Normal' Ty Value Env : Type -- Now a type alias Env = List (Name,Value) %name Env env, env1, env2 record Closure where constructor MkClosure closureEnv : Env closureName : Name closureBody : Expr Ty : Type Ty = Value -- Values data Value = VPi Ty Closure | VLambda Closure | VSigma Ty Closure | VPair Value Value | VNat | VZero | VAdd1 Value | VEq Ty Value Value | VSame | VTrivial | VSole | VAbsurd | VAtom | VTick String | VU | VNeutral Ty Neutral extendEnv : Env -> Name -> Value -> Env extendEnv env x v = ((x, v) :: env) -- definitions and dependent types data CtxEntry = Def Ty Value | IsA Ty Ctx : Type Ctx = List (Name, CtxEntry) %name Ctx ctx, ctx1, ctx2 initCtx : Ctx initCtx = [] ctxNames : Ctx -> List Name ctxNames ctx = map fst ctx extendCtx : Ctx -> Name -> Ty -> Ctx extendCtx ctx x t = (x, (IsA t)) :: ctx define : Ctx -> Name -> Ty -> Value -> Ctx define ctx x t v = (x, Def t v) :: ctx mkEnv : Ctx -> Env mkEnv [] = [] mkEnv ((x, e) :: ctx) = let env = mkEnv ctx in (case e of (Def _ v) => (x, v) :: env (IsA t) => let v = VNeutral t (NVar x) in (x, v) :: env) -- evaluator mutual data Error = MissingValue String | CarError | CdrError | ApplyError | IndAbsurdError | DoReplaceError | DoIndNatError | ReadBackTypedError | ErrorMessage String partial evalClosure : Closure -> Value -> Either Error Value evalClosure (MkClosure env x e) v = eval (extendEnv env x v) e evalVar : Env -> Name -> Either Error Value evalVar [] x = Left (MissingValue (show x ++ " not found in env")) evalVar ((y, v) :: env) x = case x == y of True => Right v False => evalVar env x partial eval : Env -> Expr -> Either Error Value eval env (Var x) = evalVar env x eval env (Pi x dom ran) = do dom' <- eval env dom Right (VPi dom' (MkClosure env x ran)) eval env (Lambda x body) = Right (VLambda (MkClosure env x body)) eval env (App rator rand) = do rator' <- eval env rator rand' <- eval env rand doApply rator' rand' eval env (Sigma x carType cdrType) = do carType' <- eval env carType Right (VSigma carType' (MkClosure env x cdrType)) eval env (Cons a d) = do a' <- eval env a d' <- eval env d Right (VPair a' d') eval env (Car e) = do e' <- eval env e doCar e' eval env (Cdr e) = do e' <- eval env e doCdr e' eval env Nat = Right VNat eval env Zero = Right VZero eval env (Add1 e) = do e' <- eval env e Right (VAdd1 e') eval env (IndNat tgt mot base step) = do tgt' <- eval env tgt mot' <- eval env mot base' <- eval env base step' <- eval env step doIndNat tgt' mot' base' step' eval env (Equal ty from to) = do ty' <- eval env ty from' <- eval env from to' <- eval env to Right (VEq ty' from' to') eval env Same = Right VSame eval env (Replace tgt mot base) = do tgt' <- eval env tgt mot' <- eval env mot base' <- eval env base doReplace tgt' mot' base' eval env Trivial = Right VTrivial eval env Sole = Right VSole eval env Absurd = Right VAbsurd eval env (IndAbsurd tgt mot) = do tgt' <- eval env tgt mot' <- eval env mot doIndAbsurd tgt' mot' eval env Atom = Right VAtom eval env (Tick x) = Right (VTick x) eval env U = Right VU eval env (The ty e) = eval env e eval env (SrcPos _ e) = eval env e -- eliminators doCar : Value -> Either Error Value doCar (VPair v1 v2) = Right v1 doCar (VNeutral (VSigma aT dT) neu) = Right (VNeutral aT (NCar neu)) doCar _ = Left CarError partial doCdr : Value -> Either Error Value doCdr (VPair v1 v2) = Right v2 doCdr v@(VNeutral (VSigma aT dT) neu) = do v' <- doCar v cl' <- evalClosure dT v' Right (VNeutral cl' (NCdr neu)) doCdr _ = Left CdrError partial doApply : Value -> Value -> Either Error Value doApply (VLambda closure) arg = evalClosure closure arg doApply (VNeutral (VPi dom ran) neu) arg = do arg' <- evalClosure ran arg Right (VNeutral arg' (NApp neu (Normal' dom arg))) doApply _ _ = Left ApplyError doIndAbsurd : Value -> Value -> Either Error Value doIndAbsurd (VNeutral VAbsurd neu) mot = Right (VNeutral mot (NIndAbsurd neu (Normal' VU mot))) doIndAbsurd _ _ = Left IndAbsurdError partial doReplace : Value -> Value -> Value -> Either Error Value doReplace VSame mot base = Right base doReplace (VNeutral (VEq ty from to) neu) mot base = do v' <- doApply mot to baseT' <- doApply mot from Right (VNeutral v' (NReplace neu (Normal' motT mot) (Normal' baseT' base))) where motT = VPi ty (MkClosure ([]) (Name' "x") U) doReplace _ _ _ = Left DoReplaceError partial indNatStepType : Value -> Either Error Value indNatStepType mot = eval [(Name' "mot", mot)] (Pi (Name' "n-1") Nat (Pi (Name' "almost") (App (Var (Name' "mot")) (Var (Name' "n-1"))) (App (Var (Name' "mot")) (Add1 (Var (Name' "n-1")))))) partial doIndNat : Value -> Value -> Value -> Value -> Either Error Value doIndNat VZero mot base step = Right base doIndNat (VAdd1 v) mot base step = do rator' <- (doApply step v) rand' <- (doIndNat v mot base step) doApply rator' rand' doIndNat tgt@(VNeutral VNat neu) mot base step = do a' <- (doApply mot tgt) b' <- (doApply mot VZero) c' <- (indNatStepType mot) Right (VNeutral a' (NIndNat neu (Normal' (VPi VNat (MkClosure [] (Name' "k") U)) mot) (Normal' b' base) (Normal' c' step))) doIndNat _ _ _ _ = Left DoIndNatError -- fresh names nextName : Name -> Name nextName (Name' x) = Name' ((show x) ++ "'") -- could possibly fail for a list like [n', n'', n'] freshen : List Name -> Name -> Name freshen [] n = n freshen (x :: used) n = case x == n of False => freshen used n True => freshen used (nextName n) -- reading back mutual partial readBackNeutral : Ctx -> Neutral -> Either Error Expr readBackNeutral ctx (NVar x) = Right (Var x) readBackNeutral ctx (NApp neu arg) = do neu' <- readBackNeutral ctx neu arg' <- readBackNormal ctx arg Right (App neu' arg') readBackNeutral ctx (NCar neu) = do car <- readBackNeutral ctx neu Right (Car car) readBackNeutral ctx (NCdr neu) = do cdr <- readBackNeutral ctx neu Right (Cdr cdr) readBackNeutral ctx (NIndNat neu mot base step) = do neu' <- readBackNeutral ctx neu mot' <- readBackNormal ctx mot base' <- readBackNormal ctx base step' <- readBackNormal ctx step Right (IndNat neu' mot' base' step') readBackNeutral ctx (NReplace neu mot base) = do neu' <- readBackNeutral ctx neu mot' <- readBackNormal ctx mot base' <- readBackNormal ctx base Right (Replace neu' mot' base') readBackNeutral ctx (NIndAbsurd neu mot) = do neu' <- readBackNeutral ctx neu mot' <- readBackNormal ctx mot Right (IndAbsurd (The Absurd neu') mot') partial readBackTyped : Ctx -> Ty -> Value -> Either Error Expr readBackTyped ctx VNat VZero = Right Zero readBackTyped ctx VNat (VAdd1 v) = do n <- (readBackTyped ctx VNat v) Right (Add1 n) readBackTyped ctx (VPi dom ran) fun = let x = freshen (ctxNames ctx) (closureName ran) xVal = VNeutral dom (NVar x) ctx' = extendCtx ctx x dom in do ty' <- evalClosure ran xVal v' <- doApply fun xVal body <- readBackTyped ctx' ty' ty' Right (Lambda x body) readBackTyped ctx (VSigma aT dT) pair = do carVal <- doCar pair car <- readBackTyped ctx aT carVal cdrT <- evalClosure dT carVal cdrVal <- doCdr pair cdr <- readBackTyped ctx cdrT cdrVal Right (Cons car cdr) readBackTyped ctx VAbsurd (VNeutral VAbsurd neu) = do a <- readBackNeutral ctx neu Right (The Absurd a) readBackTyped ctx (VEq _ _ _) VSame = Right Same readBackTyped ctx VAtom (VTick x) = Right (Tick x) readBackTyped ctx VU VNat = Right Nat readBackTyped ctx VU VAtom = Right Atom readBackTyped ctx VU VTrivial = Right Trivial readBackTyped ctx VU VAbsurd = Right Absurd readBackTyped ctx VU (VEq t from to) = do a <- readBackTyped ctx VU t b <- readBackTyped ctx t from c <- readBackTyped ctx t to Right (Equal a b c) readBackTyped ctx VU (VSigma aT dT) = let x = freshen (ctxNames ctx) (closureName dT) in do a <- readBackTyped ctx VU aT body <- evalClosure dT (VNeutral aT (NVar x)) d <- readBackTyped (extendCtx ctx x aT) VU body Right (Sigma x a d) readBackTyped ctx VU (VPi aT bT) = let x = freshen (ctxNames ctx) (closureName bT) in do a <- readBackTyped ctx VU aT body <- evalClosure bT (VNeutral aT (NVar x)) b <- readBackTyped (extendCtx ctx x aT) VU body Right (Pi x a b) readBackTyped ctx VU VU = Right U readBackTyped ctx t (VNeutral t' neu) = readBackNeutral ctx neu readBackTyped _ otherT otherE = Left ReadBackTypedError partial readBackNormal : Ctx -> Normal -> Either Error Expr readBackNormal ctx (Normal' t v) = readBackTyped ctx t v -- helpers lookupType : Ctx -> Name -> Either Error Ty -- didn't use message type lookupType [] x = Left (ErrorMessage "unbound variable: ") -- TODO ++ show x lookupType ((y, e) :: ctx) x = (case x == y of False => lookupType ctx x True => (case e of (Def t _) => Right t (IsA t) => Right t)) unexpected : Ctx -> String -> Value -> Either Error a isPi : Ctx -> Value -> Either Error (Ty, Closure) isPi _ (VPi a b) = Right (a, b) isPi ctx other = unexpected ctx "Not a Pi type" other isSigma : Ctx -> Value -> Either Error (Ty, Closure) isSigma _ (VSigma a b) = Right (a, b) isSigma ctx other = unexpected ctx "Not a Sigma type" other isNat : Ctx -> Value -> Either Error () isNat _ VNat = Right () isNat ctx other = unexpected ctx "Not Nat" other isEqual : Ctx -> Value -> Either Error (Ty, Value, Value) isEqual _ (VEq ty from to) = Right (ty, from, to) isEqual ctx other = unexpected ctx "Not an equality type" other isAbsurd : Ctx -> Value -> Either Error () isAbsurd _ VAbsurd = Right () isAbsurd ctx other = unexpected ctx "Not Absurd: " other isTrivial : Ctx -> Value -> Either Error () isTrivial _ VTrivial = Right () isTrivial ctx other = unexpected ctx "Not Trivial" other isAtom : Ctx -> Value -> Either Error () isAtom _ VAtom = Right () isAtom ctx other = unexpected ctx "Not Atom" other -- checking/synthesis mutual partial check : Ctx -> Expr -> Ty -> Either Error () check ctx (Lambda x body) t = ?check_rhs_3 check ctx (Cons a d) t = ?check_rhs_6 check ctx Zero t = isNat ctx t check ctx (Add1 n) t = do isNat ctx t check ctx n VNat check ctx Same t = do (t, from, to) <- isEqual ctx t convert ctx t from to check ctx Sole t = isTrivial ctx t check ctx (Tick x) t = isAtom ctx t check ctx other t = do t' <- synth ctx other convert ctx VU t' t convert : Ctx -> Ty -> Value -> Value -> Either Error () partial synth : Ctx -> Expr -> Either Error Ty synth ctx (Var x) = lookupType ctx x synth ctx (Pi x a b) = do check ctx a VU v <- eval (mkEnv ctx) a check (extendCtx ctx x v) b VU Right VU synth ctx (App rator rand) = do funTy <- synth ctx rator (a, b) <- isPi ctx funTy check ctx rand a body <- eval (mkEnv ctx) rand evalClosure b body synth ctx (Sigma x a b) = do check ctx a VU a' <- eval (mkEnv ctx) a check (extendCtx ctx x a') b VU Right VU synth ctx (Car e) = do t <- synth ctx e (aT, dT) <- isSigma ctx t Right aT synth ctx (Cdr e) = do t <- synth ctx e (aT, dT) <- isSigma ctx t e' <- eval (mkEnv ctx) e body <- doCar e' evalClosure dT body synth ctx Nat = Right VU synth ctx (IndNat tgt mot base step) = do t <- synth ctx tgt tgtV <- eval (mkEnv ctx) tgt motTy <- eval (mkEnv []) (Pi (Name' "x") Nat U) check ctx mot motTy motV <- eval (mkEnv ctx) mot z' <- doApply motV VZero check ctx base z' m' <- indNatStepType motV check ctx step m' doApply motV tgtV synth ctx (Equal ty from to) = do check ctx ty VU tyV <- eval (mkEnv ctx) ty check ctx from tyV check ctx to tyV Right VU synth ctx (Replace tgt mot base) = do t <- synth ctx tgt (ty, from, to) <- isEqual ctx t motTy <- eval ([(Name' "ty", ty)]) (Pi (Name' "x") (Var (Name' "ty")) U) check ctx mot motTy motV <- eval (mkEnv ctx) mot fromV <- doApply motV from check ctx base fromV doApply motV to synth ctx Trivial = Right VU synth ctx Absurd = Right VU synth ctx (IndAbsurd tgt mot) = do t <- synth ctx tgt isAbsurd ctx t check ctx mot VU eval (mkEnv ctx) mot synth ctx Atom = Right VU synth ctx U = Right VU synth ctx (The ty expr) = do check ctx ty VU tyV <- eval (mkEnv ctx) ty check ctx expr tyV Right tyV synth ctx other = Left (ErrorMessage "Unable to synthesize a type for ") -- ++ show other
------------------------------------------------------------------------ -- The Agda standard library -- -- Properties related to negation ------------------------------------------------------------------------ {-# OPTIONS --without-K --safe #-} module Relation.Nullary.Negation where open import Category.Monad open import Data.Bool.Base using (Bool; false; true; if_then_else_) open import Data.Empty open import Data.Product as Prod open import Data.Sum as Sum using (_⊎_; inj₁; injβ‚‚; [_,_]) open import Function open import Level open import Relation.Nullary open import Relation.Unary contradiction : βˆ€ {p w} {P : Set p} {Whatever : Set w} β†’ P β†’ Β¬ P β†’ Whatever contradiction p Β¬p = βŠ₯-elim (Β¬p p) contraposition : βˆ€ {p q} {P : Set p} {Q : Set q} β†’ (P β†’ Q) β†’ Β¬ Q β†’ Β¬ P contraposition f Β¬q p = contradiction (f p) Β¬q -- Note also the following use of flip: private note : βˆ€ {p q} {P : Set p} {Q : Set q} β†’ (P β†’ Β¬ Q) β†’ Q β†’ Β¬ P note = flip -- If we can decide P, then we can decide its negation. Β¬? : βˆ€ {p} {P : Set p} β†’ Dec P β†’ Dec (Β¬ P) Β¬? (yes p) = no (Ξ» Β¬p β†’ Β¬p p) Β¬? (no Β¬p) = yes Β¬p ------------------------------------------------------------------------ -- Quantifier juggling βˆƒβŸΆΒ¬βˆ€Β¬ : βˆ€ {a p} {A : Set a} {P : A β†’ Set p} β†’ βˆƒ P β†’ Β¬ (βˆ€ x β†’ Β¬ P x) βˆƒβŸΆΒ¬βˆ€Β¬ = flip uncurry βˆ€βŸΆΒ¬βˆƒΒ¬ : βˆ€ {a p} {A : Set a} {P : A β†’ Set p} β†’ (βˆ€ x β†’ P x) β†’ Β¬ βˆƒ Ξ» x β†’ Β¬ P x βˆ€βŸΆΒ¬βˆƒΒ¬ βˆ€xPx (x , Β¬Px) = Β¬Px (βˆ€xPx x) Β¬βˆƒβŸΆβˆ€Β¬ : βˆ€ {a p} {A : Set a} {P : A β†’ Set p} β†’ Β¬ βˆƒ (Ξ» x β†’ P x) β†’ βˆ€ x β†’ Β¬ P x Β¬βˆƒβŸΆβˆ€Β¬ = curry βˆ€Β¬βŸΆΒ¬βˆƒ : βˆ€ {a p} {A : Set a} {P : A β†’ Set p} β†’ (βˆ€ x β†’ Β¬ P x) β†’ Β¬ βˆƒ (Ξ» x β†’ P x) βˆ€Β¬βŸΆΒ¬βˆƒ = uncurry βˆƒΒ¬βŸΆΒ¬βˆ€ : βˆ€ {a p} {A : Set a} {P : A β†’ Set p} β†’ βˆƒ (Ξ» x β†’ Β¬ P x) β†’ Β¬ (βˆ€ x β†’ P x) βˆƒΒ¬βŸΆΒ¬βˆ€ = flip βˆ€βŸΆΒ¬βˆƒΒ¬ ------------------------------------------------------------------------ -- Double-negation ¬¬-map : βˆ€ {p q} {P : Set p} {Q : Set q} β†’ (P β†’ Q) β†’ Β¬ Β¬ P β†’ Β¬ Β¬ Q ¬¬-map f = contraposition (contraposition f) -- Stability under double-negation. Stable : βˆ€ {β„“} β†’ Set β„“ β†’ Set β„“ Stable P = Β¬ Β¬ P β†’ P -- Everything is stable in the double-negation monad. stable : βˆ€ {p} {P : Set p} β†’ Β¬ Β¬ Stable P stable Β¬[¬¬pβ†’p] = Β¬[¬¬pβ†’p] (Ξ» ¬¬p β†’ βŠ₯-elim (¬¬p (Β¬[¬¬pβ†’p] ∘ const))) -- Negated predicates are stable. negated-stable : βˆ€ {p} {P : Set p} β†’ Stable (Β¬ P) negated-stable ¬¬¬P P = ¬¬¬P (Ξ» Β¬P β†’ Β¬P P) -- Decidable predicates are stable. decidable-stable : βˆ€ {p} {P : Set p} β†’ Dec P β†’ Stable P decidable-stable (yes p) ¬¬p = p decidable-stable (no Β¬p) ¬¬p = βŠ₯-elim (¬¬p Β¬p) Β¬-drop-Dec : βˆ€ {p} {P : Set p} β†’ Dec (Β¬ Β¬ P) β†’ Dec (Β¬ P) Β¬-drop-Dec (yes ¬¬p) = no ¬¬p Β¬-drop-Dec (no ¬¬¬p) = yes (negated-stable ¬¬¬p) -- Double-negation is a monad (if we assume that all elements of Β¬ Β¬ P -- are equal). ¬¬-Monad : βˆ€ {p} β†’ RawMonad (Ξ» (P : Set p) β†’ Β¬ Β¬ P) ¬¬-Monad = record { return = contradiction ; _>>=_ = Ξ» x f β†’ negated-stable (¬¬-map f x) } ¬¬-push : βˆ€ {p q} {P : Set p} {Q : P β†’ Set q} β†’ Β¬ Β¬ ((x : P) β†’ Q x) β†’ (x : P) β†’ Β¬ Β¬ Q x ¬¬-push ¬¬P⟢Q P Β¬Q = ¬¬P⟢Q (Ξ» P⟢Q β†’ Β¬Q (P⟢Q P)) -- A double-negation-translated variant of excluded middle (or: every -- nullary relation is decidable in the double-negation monad). excluded-middle : βˆ€ {p} {P : Set p} β†’ Β¬ Β¬ Dec P excluded-middle Β¬h = Β¬h (no (Ξ» p β†’ Β¬h (yes p))) -- If Whatever is instantiated with ¬ ¬ something, then this function -- is call with current continuation in the double-negation monad, or, -- if you will, a double-negation translation of Peirce's law. -- -- In order to prove ¬ ¬ P one can assume ¬ P and prove βŠ₯. However, -- sometimes it is nice to avoid leaving the double-negation monad; in -- that case this function can be used (with Whatever instantiated to -- βŠ₯). call/cc : βˆ€ {w p} {Whatever : Set w} {P : Set p} β†’ ((P β†’ Whatever) β†’ Β¬ Β¬ P) β†’ Β¬ Β¬ P call/cc hyp Β¬p = hyp (Ξ» p β†’ βŠ₯-elim (Β¬p p)) Β¬p -- The "independence of premise" rule, in the double-negation monad. -- It is assumed that the index set (Q) is inhabited. independence-of-premise : βˆ€ {p q r} {P : Set p} {Q : Set q} {R : Q β†’ Set r} β†’ Q β†’ (P β†’ Ξ£ Q R) β†’ Β¬ Β¬ (Ξ£[ x ∈ Q ] (P β†’ R x)) independence-of-premise {P = P} q f = ¬¬-map helper excluded-middle where helper : Dec P β†’ _ helper (yes p) = Prod.map id const (f p) helper (no Β¬p) = (q , βŠ₯-elim βˆ˜β€² Β¬p) -- The independence of premise rule for binary sums. independence-of-premise-⊎ : βˆ€ {p q r} {P : Set p} {Q : Set q} {R : Set r} β†’ (P β†’ Q ⊎ R) β†’ Β¬ Β¬ ((P β†’ Q) ⊎ (P β†’ R)) independence-of-premise-⊎ {P = P} f = ¬¬-map helper excluded-middle where helper : Dec P β†’ _ helper (yes p) = Sum.map const const (f p) helper (no Β¬p) = inj₁ (βŠ₯-elim βˆ˜β€² Β¬p) private -- Note that independence-of-premise-⊎ is a consequence of -- independence-of-premise (for simplicity it is assumed that Q and -- R have the same type here): corollary : βˆ€ {p β„“} {P : Set p} {Q R : Set β„“} β†’ (P β†’ Q ⊎ R) β†’ Β¬ Β¬ ((P β†’ Q) ⊎ (P β†’ R)) corollary {P = P} {Q} {R} f = ¬¬-map helper (independence-of-premise true ([ _,_ true , _,_ false ] βˆ˜β€² f)) where helper : βˆƒ (Ξ» b β†’ P β†’ if b then Q else R) β†’ (P β†’ Q) ⊎ (P β†’ R) helper (true , f) = inj₁ f helper (false , f) = injβ‚‚ f ------------------------------------------------------------------------ -- DEPRECATED NAMES ------------------------------------------------------------------------ -- Please use the new names as continuing support for the old names is -- not guaranteed. -- Version 1.0 Excluded-Middle : (β„“ : Level) β†’ Set (suc β„“) Excluded-Middle p = {P : Set p} β†’ Dec P {-# WARNING_ON_USAGE Excluded-Middle "Warning: Excluded-Middle was deprecated in v1.0. Please use ExcludedMiddle from `Axiom.ExcludedMiddle` instead." #-} Double-Negation-Elimination : (β„“ : Level) β†’ Set (suc β„“) Double-Negation-Elimination p = {P : Set p} β†’ Stable P {-# WARNING_ON_USAGE Double-Negation-Elimination "Warning: Double-Negation-Elimination was deprecated in v1.0. Please use DoubleNegationElimination from `Axiom.DoubleNegationElimination` instead." #-}
Generalizable All Variables. Set Primitive Projections. Class Eq (A : Type) := { eqb : A -> A -> bool; neqb : A -> A -> bool; eqb_refl x : eqb x x = true; eqb_sym x y : eqb x y = eqb y x; eqb_trans {x y z} : eqb x y = true -> eqb y z = true -> eqb x z = true; eqb_eq {x y} : eqb x y = true -> x = y; }. Infix "==" := eqb (at level 70). Infix "/=" := neqb (at level 70). Lemma eqb_neq `{Eq A} {x y} : eqb x y = false -> x <> y. Proof. repeat intro; subst. pose proof (eqb_refl y). rewrite H0 in H1. inversion H1. Qed. From Equations Require Import Equations. Set Equations With UIP. #[export] Program Instance Eq_EqDec `{Eq A} : EqDec A. Next Obligation. destruct (eqb x y) eqn:Heqe. - left. now apply eqb_eq in Heqe. - right. intro. subst. apply eqb_neq in Heqe. contradiction. Defined.
lemma setdist_closed_compact: fixes S :: "'a::heine_borel set" assumes S: "closed S" and T: "compact T" and "S \<noteq> {}" "T \<noteq> {}" shows "\<exists>x \<in> S. \<exists>y \<in> T. dist x y = setdist S T"
suppressPackageStartupMessages(library(dplyr)) suppressPackageStartupMessages(library(ggplot2)) # Set themes file_extensions <- c(".png", ".pdf") plot_theme <- theme( title = element_text(size = 9), axis.title = element_text(size = 9), legend.text = element_text(size = 7), legend.title = element_text(size = 9), legend.key.size = unit(0.5, "cm"), strip.text = element_text(size = 10), strip.background = element_rect(colour="black", fill="#fdfff4") ) # Load L2 distances per MOA cp_file <- file.path("data", "MOA_LSA_metrics.tsv") cp_df <- readr::read_tsv(cp_file) cp_df$model <- factor( cp_df$model, levels = c("Vanilla", "Beta", "MMD", "PCA", "Complete") ) head(cp_df) # Compare performance means across architectures cp_mean_df <- cp_df %>% dplyr::group_by(model, metric) %>% dplyr::mutate( model_mean = round(mean(zscore), 2) ) %>% dplyr::select(model, metric, model_mean) %>% dplyr::distinct() cp_mean_df plot_gg <- ( ggplot(cp_df, aes(x=zscore)) + geom_histogram(aes(y = ..density..), bins = 30) + geom_density() + geom_text( data=cp_mean_df, aes(x = -3, y = 0.5, label = paste0("Mean: ", model_mean)) ) + geom_vline( data=cp_mean_df, aes(xintercept = model_mean), color = "red", linetype="dashed" ) + geom_vline( xintercept = 0, linetype = "dashed", color = "blue" ) + facet_grid("model~metric") + theme_bw() + xlim(c(-5, 5)) + plot_theme + geom_rect( data = cp_df %>% dplyr::filter(model == "MMD"), fill = NA, alpha = 1, color = "red", linetype = "solid", size = 2, xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf ) + ylab("Density") + xlab("Z-score of metrics (L2 distance or Pearson correlation) for LSA predictions of\nground truth (per polypharmacology state) compared to 10 randomly shuffled LSA permutations") ) plot_gg # Save figure output_file_base <- file.path("output", "sup_fig_lsa_metrics") for (file_extension in file_extensions) { output_file <- paste0(output_file_base, file_extension) ggplot2::ggsave(output_file, plot_gg, dpi = 500, width = 8, height = 8) }
#include <boost/thread/win32/shared_mutex.hpp>
#ifndef BIO_RUN_MATCH_H_ #define BIO_RUN_MATCH_H_ #include "bio/defs.h" #include "bio/common.h" #include "bio/match_hit.h" #include "bio/sequence.h" #include "bio/biobase_filter.h" #include "bio/pssm_match.h" #include "bio/phylogenetics.h" #include "bio/biobase_db.h" #include "bio/biobase_data_traits.h" #include <boost/filesystem/path.hpp> #include <vector> #include <set> #include <gsl/gsl_sf_log.h> #include <gsl/gsl_sf_exp.h> namespace boost { namespace program_options { //forward decl class options_description; } } BIO_NS_START enum ScoreAlgorithm { OTT_SCORE_ALGORITHM, BAYESIAN_SCORE_ALGORITHM }; struct MatchParams { MatchParams( float_t t, ScoreAlgorithm alg = OTT_SCORE_ALGORITHM, bool or_better = false) : threshold( t ) , score_algorithm( alg ) , or_better( or_better ) { } float_t threshold; ScoreAlgorithm score_algorithm; bool or_better; }; struct MatchResults { MatchResults(); MatchResults( TableLink link, Hit result); TableLink link; Hit result; size_t number; bool operator<(const MatchResults & rhs) const { if (result == rhs.result) { if (link == rhs.link) { return number < rhs.number; } else { return link < rhs.link; } } else { return result < rhs.result; } } protected: friend class boost::serialization::access; template<class Archive> void serialize(Archive & ar, const unsigned int version) { ar & link; ar & result; ar & number; } }; typedef std::vector<MatchResults> match_result_vec_t; typedef boost::shared_ptr< match_result_vec_t > match_result_vec_ptr_t; void sort_by_position(match_result_vec_t & matches); std::ostream & operator<<(std::ostream & os, const MatchResults & match); /** Compare based initially on position, then link. */ struct MatchResultsPositionLessThan { bool operator()(const MatchResults & h1, const MatchResults & h2) const { return h1.result.position < h2.result.position || ( h1.result.position == h2.result.position && h1.link < h2.link ); } }; inline std::ostream & operator<<(std::ostream & os, const MatchResults & details) { os << details.link << "," << details.result; return os; } /** Score all the pssm on the sequence between match_seq_begin and match_seq_end and put the results in result_insert_it. Returns an estimate that the pssm binds the sequence. */ template <class Pssm, class ResultInsIt> float_t score_pssm( const Pssm & pssm, seq_t::const_iterator match_seq_begin, seq_t::const_iterator match_seq_end, const MatchParams & params, ResultInsIt & result_insert_it) { Scorers scorers(match_seq_begin, match_seq_end); //const hit_vec_t & hit_results = scorers.bayesian_scores.get_result(pssm); const hit_vec_t & hit_results = OTT_SCORE_ALGORITHM == params.score_algorithm ? scorers.ott_normalised_scores.get_result(pssm) : ( params.or_better ? scorers.bayesian_scores.get_result(pssm) : scorers.bayesian_or_better_scores.get_result(pssm)); float_t p_does_not_bind = 1.0; for (hit_vec_t::const_iterator i = hit_results.begin(); hit_results.end() != i; ++i) { if (i->score > params.threshold) { p_does_not_bind *= ( float_t( 1.0 ) - i->score ); MatchResults result(pssm.get_link(), *i); assert(result.result.position < (int) (match_seq_end - match_seq_begin)); //make sure the position is not too high *result_insert_it++ = result; } } return float_t( 1.0 ) - p_does_not_bind; } /** Score all the pssms between begin and end and put the results in result_insert_it. */ template <class PssmIt, class ResultInsIt> size_t score_pssms( PssmIt pssm_begin, PssmIt pssm_end, seq_t::const_iterator match_seq_begin, seq_t::const_iterator match_seq_end, const MatchParams & params, ResultInsIt & result_insert_it) { size_t num_pssms_matched = 0; for ( ; pssm_begin != pssm_end; ++pssm_begin) { try { score_pssm( *(pssm_begin->second.get()), match_seq_begin, match_seq_end, params, result_insert_it); ++num_pssms_matched; } catch (const std::exception & ex) { std::cerr << "Could not score " << pssm_begin->second->get_name() << ": " << ex.what() << std::endl; } catch (const std::string & ex) { std::cerr << "Could not score " << pssm_begin->second->get_name() << ": " << ex << std::endl; } catch (const char * ex) { std::cerr << "Could not score " << pssm_begin->second->get_name() << ": " << ex << std::endl; } catch (...) { std::cerr << "Could not score " << pssm_begin->second->get_name() << std::endl; } } return num_pssms_matched; } template <class SeqIt, class ResultInsIt, class ConsFilter, class MatrixFilter> void pssm_match( SeqIt seq_begin, SeqIt seq_end, float_t threshold, ScoreAlgorithm algorithm, bool use_or_better, ConsFilter consensus_filter, MatrixFilter matrix_filter, ResultInsIt result_inserter) { typedef boost::filter_iterator<MatrixFilter, Matrix::map_t::const_iterator> matrix_filter_it; typedef boost::filter_iterator<ConsFilter, Site::map_t::const_iterator> site_filter_it; const matrix_filter_it matrices_begin(matrix_filter, BiobaseDb::singleton().get_matrices().begin(), BiobaseDb::singleton().get_matrices().end()); const matrix_filter_it matrices_end(matrix_filter, BiobaseDb::singleton().get_matrices().end(), BiobaseDb::singleton().get_matrices().end()); const site_filter_it sites_begin(consensus_filter, BiobaseDb::singleton().get_sites().begin(), BiobaseDb::singleton().get_sites().end()); const site_filter_it sites_end(consensus_filter, BiobaseDb::singleton().get_sites().end(), BiobaseDb::singleton().get_sites().end()); if (matrices_begin == matrices_end && sites_begin == sites_end) { throw std::logic_error( "No PSSMs match filter" ); } MatchParams params(threshold, algorithm, use_or_better); { //std::cout << "Scoring matrices" << std::endl; //const size_t num_matched = score_pssms( matrices_begin, matrices_end, seq_begin, seq_end, params, result_inserter); // ostream_iterator<MatchResults>(cout, "\n")); //std::cout << "Scored " << num_matched << " matrices" << std::endl; } { //std::cout << "Scoring sites" << std::endl; //const size_t num_matched = score_pssms( sites_begin, sites_end, seq_begin, seq_end, params, result_inserter); // ostream_iterator<MatchResults>(cout, "\n")); //std::cout << "Scored " << num_matched << " sites" << std::endl; } } void pssm_match( const seq_t & match_seq, float_t threshold, ScoreAlgorithm algorithm, const boost::filesystem::path & file, const std::string & title, bool show_labels); template <typename HitIt> float_t estimate_binding_prob( HitIt hit_begin, HitIt hit_end) { float_t product = 1.0; for (HitIt hit = hit_begin; hit_end != hit; ++hit) { product *= float_t( 1.0f - hit->result.score ); } return float_t(1.0 - product); } template <typename Exponent> double power(double x, Exponent y) { return 0 == x ? 0 : gsl_sf_exp(y * gsl_sf_log(x)); } /** Adjusts hits for occurence in phylogenetically conserved sequence. */ template <typename ResultIt> void adjust_hits( ResultIt results_begin, ResultIt results_end, seq_t::const_iterator seq_begin, seq_t::const_iterator seq_end, float_t threshold, ScoreAlgorithm algorithm) { const MatchParams params(threshold, algorithm); //maintain a set of already adjusted PSSMs std::set<TableLink> already_adjusted; //for each result for (ResultIt result = results_begin; results_end != result; ++result) { //check we haven't checked this PSSM before if (already_adjusted.end() != already_adjusted.find(result->link)) { //we have so ignore it continue; } //we need to estimate likelihood that it binds in phylogenetic sequence so run PSSM over sequence. match_result_vec_t phylo_hits; std::insert_iterator<bio::match_result_vec_t> inserter(phylo_hits, phylo_hits.begin()); switch (result->link.table_id) { case MATRIX_DATA: score_pssm( *BiobaseDb::singleton().get_entry<MATRIX_DATA>(result->link), seq_begin, seq_end, params, inserter); break; case SITE_DATA: score_pssm( *BiobaseDb::singleton().get_entry<SITE_DATA>(result->link), seq_begin, seq_end, params, inserter); break; default: throw std::logic_error( "Unknown pssm type" ); } const float_t binding_prob = estimate_binding_prob(phylo_hits.begin(), phylo_hits.end()); //adjust all the hits for this PSSM for (ResultIt to_adjust = result; results_end != to_adjust; ++to_adjust) { if (to_adjust->link == result->link) { //to_adjust->result.score *= power(binding_prob, 5.0 * phylo_seq.conservation * phylo_seq.conservation); to_adjust->result.score *= binding_prob; } } //add to the list of already adjusted PSSMs already_adjusted.insert(result->link); } } /** Adjusts hits for occurence in phylogenetically conserved sequence. */ template < typename ResultIt, typename SeqRange > void adjust_hits_for_phylo_sequences( ResultIt results_begin, ResultIt results_end, const SeqRange & sequences, float_t threshold, ScoreAlgorithm algorithm) { unsigned num_seqs = 0; BOOST_FOREACH( const typename boost::range_value< SeqRange >::type & seq, sequences ) { adjust_hits( results_begin, results_end, seq.begin(), seq.end(), threshold, algorithm ); ++num_seqs; } std::cout << "Adjusted hits for " << num_seqs << " sequences" << std::endl; for( ; results_begin != results_end; ++results_begin ) { //adjust hits - raise to 1/#seqs results_begin->result.score = float_t( ( 0.0 == results_begin->result.score ) ? 0.0 : exp( log( results_begin->result.score ) / ( num_seqs + 1 ) ) ); } } /** Adjust hits by power. */ struct RaiseHitToPower { double power; RaiseHitToPower(double power); void operator()(MatchResults & hit) const; }; /** Is a hit above a threshold? */ struct HitAboveThreshold { float_t threshold; HitAboveThreshold(float_t threshold); bool operator()(const MatchResults & results) const; }; BIO_NS_END #endif //BIO_RUN_MATCH_H_
/- Copyright (c) 2022 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang ! This file was ported from Lean 3 source module category_theory.adhesive ! leanprover-community/mathlib commit afff1f24a6b68d0077c9d63782a1d093e337758c ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathbin.CategoryTheory.Extensive import Mathbin.CategoryTheory.Limits.Shapes.KernelPair /-! # Adhesive categories ## Main definitions - `category_theory.is_pushout.is_van_kampen`: A convenience formulation for a pushout being a van Kampen colimit. - `category_theory.adhesive`: A category is adhesive if it has pushouts and pullbacks along monomorphisms, and such pushouts are van Kampen. ## Main Results - `category_theory.type.adhesive`: The category of `Type` is adhesive. - `category_theory.adhesive.is_pullback_of_is_pushout_of_mono_left`: In adhesive categories, pushouts along monomorphisms are pullbacks. - `category_theory.adhesive.mono_of_is_pushout_of_mono_left`: In adhesive categories, monomorphisms are stable under pushouts. - `category_theory.adhesive.to_regular_mono_category`: Monomorphisms in adhesive categories are regular (this implies that adhesive categories are balanced). ## TODO Show that the following are adhesive: - functor categories into adhesive categories - the categories of sheaves over a site ## References - https://ncatlab.org/nlab/show/adhesive+category - [Stephen Lack and PaweΕ‚ SobociΕ„ski, Adhesive Categories][adhesive2004] -/ namespace CategoryTheory open Limits universe v' u' v u variable {J : Type v'} [Category.{u'} J] {C : Type u} [Category.{v} C] variable {W X Y Z : C} {f : W ⟢ X} {g : W ⟢ Y} {h : X ⟢ Z} {i : Y ⟢ Z} -- This only makes sense when the original diagram is a pushout. /-- A convenience formulation for a pushout being a van Kampen colimit. See `is_pushout.is_van_kampen_iff` below. -/ @[nolint unused_arguments] def IsPushout.IsVanKampen (H : IsPushout f g h i) : Prop := βˆ€ ⦃W' X' Y' Z' : C⦄ (f' : W' ⟢ X') (g' : W' ⟢ Y') (h' : X' ⟢ Z') (i' : Y' ⟢ Z') (Ξ±W : W' ⟢ W) (Ξ±X : X' ⟢ X) (Ξ±Y : Y' ⟢ Y) (Ξ±Z : Z' ⟢ Z) (hf : IsPullback f' Ξ±W Ξ±X f) (hg : IsPullback g' Ξ±W Ξ±Y g) (hh : CommSq h' Ξ±X Ξ±Z h) (hi : CommSq i' Ξ±Y Ξ±Z i) (w : CommSq f' g' h' i'), IsPushout f' g' h' i' ↔ IsPullback h' Ξ±X Ξ±Z h ∧ IsPullback i' Ξ±Y Ξ±Z i #align category_theory.is_pushout.is_van_kampen CategoryTheory.IsPushout.IsVanKampen theorem IsPushout.IsVanKampen.flip {H : IsPushout f g h i} (H' : H.IsVanKampen) : H.flip.IsVanKampen := by introv W' hf hg hh hi w simpa only [is_pushout.flip_iff, is_pullback.flip_iff, and_comm'] using H' g' f' i' h' Ξ±W Ξ±Y Ξ±X Ξ±Z hg hf hi hh w.flip #align category_theory.is_pushout.is_van_kampen.flip CategoryTheory.IsPushout.IsVanKampen.flip theorem IsPushout.isVanKampen_iff (H : IsPushout f g h i) : H.IsVanKampen ↔ IsVanKampenColimit (PushoutCocone.mk h i H.w) := by constructor Β· intro H F' c' Ξ± fΞ± eΞ± hΞ± refine' Iff.trans _ ((H (F'.map walking_span.hom.fst) (F'.map walking_span.hom.snd) (c'.ΞΉ.app _) (c'.ΞΉ.app _) (Ξ±.app _) (Ξ±.app _) (Ξ±.app _) fΞ± (by convert hΞ± walking_span.hom.fst) (by convert hΞ± walking_span.hom.snd) _ _ _).trans _) Β· have : F'.map walking_span.hom.fst ≫ c'.ΞΉ.app walking_span.left = F'.map walking_span.hom.snd ≫ c'.ΞΉ.app walking_span.right := by simp only [cocone.w] rw [(is_colimit.equiv_of_nat_iso_of_iso (diagram_iso_span F') c' (pushout_cocone.mk _ _ this) _).nonempty_congr] Β· exact ⟨fun h => ⟨⟨this⟩, h⟩, fun h => h.2⟩ Β· refine' cocones.ext (iso.refl c'.X) _ rintro (_ | _ | _) <;> dsimp <;> simp only [c'.w, category.assoc, category.id_comp, category.comp_id] Β· exact ⟨nat_trans.congr_app eΞ±.symm _⟩ Β· exact ⟨nat_trans.congr_app eΞ±.symm _⟩ Β· exact ⟨by simp⟩ constructor Β· rintro ⟨h₁, hβ‚‚βŸ© (_ | _ | _) Β· rw [← c'.w walking_span.hom.fst] exact (hΞ± walking_span.hom.fst).paste_horiz h₁ exacts[h₁, hβ‚‚] Β· intro h exact ⟨h _, h _⟩ Β· introv H W' hf hg hh hi w refine' Iff.trans _ ((H w.cocone ⟨by rintro (_ | _ | _) exacts[Ξ±W, Ξ±X, Ξ±Y], _⟩ Ξ±Z _ _).trans _) rotate_left Β· rintro i _ (_ | _ | _) Β· dsimp simp only [Functor.map_id, category.comp_id, category.id_comp] exacts[hf.w, hg.w] Β· ext (_ | _ | _) Β· dsimp rw [pushout_cocone.condition_zero] erw [category.assoc, hh.w, hf.w_assoc] exacts[hh.w.symm, hi.w.symm] Β· rintro i _ (_ | _ | _) Β· dsimp simp_rw [Functor.map_id] exact is_pullback.of_horiz_is_iso ⟨by rw [category.comp_id, category.id_comp]⟩ exacts[hf, hg] Β· constructor Β· intro h exact ⟨h walking_cospan.left, h walking_cospan.right⟩ Β· rintro ⟨h₁, hβ‚‚βŸ© (_ | _ | _) Β· dsimp rw [pushout_cocone.condition_zero] exact hf.paste_horiz h₁ exacts[h₁, hβ‚‚] Β· exact ⟨fun h => h.2, fun h => ⟨_, h⟩⟩ #align category_theory.is_pushout.is_van_kampen_iff CategoryTheory.IsPushout.isVanKampen_iff theorem is_coprod_iff_isPushout {X E Y YE : C} (c : BinaryCofan X E) (hc : IsColimit c) {f : X ⟢ Y} {iY : Y ⟢ YE} {fE : c.pt ⟢ YE} (H : CommSq f c.inl iY fE) : Nonempty (IsColimit (BinaryCofan.mk (c.inr ≫ fE) iY)) ↔ IsPushout f c.inl iY fE := by constructor Β· rintro ⟨h⟩ refine' ⟨H, ⟨limits.pushout_cocone.is_colimit_aux' _ _⟩⟩ intro s dsimp refine' ⟨h.desc (binary_cofan.mk (c.inr ≫ s.inr) s.inl), h.fac _ ⟨walking_pair.right⟩, _, _⟩ Β· apply binary_cofan.is_colimit.hom_ext hc Β· rw [← H.w_assoc] erw [h.fac _ ⟨walking_pair.right⟩] exact s.condition Β· rw [← category.assoc] exact h.fac _ ⟨walking_pair.left⟩ Β· intro m e₁ eβ‚‚ apply binary_cofan.is_colimit.hom_ext h Β· dsimp rw [category.assoc, eβ‚‚, eq_comm] exact h.fac _ ⟨walking_pair.left⟩ Β· refine' e₁.trans (Eq.symm _) exact h.fac _ _ Β· refine' fun H => ⟨_⟩ fapply limits.binary_cofan.is_colimit_mk Β· exact fun s => H.is_colimit.desc (pushout_cocone.mk s.inr _ <| (hc.fac (binary_cofan.mk (f ≫ s.inr) s.inl) ⟨walking_pair.left⟩).symm) Β· intro s erw [category.assoc, H.is_colimit.fac _ walking_span.right, hc.fac] rfl Β· intro s exact H.is_colimit.fac _ walking_span.left Β· intro s m e₁ eβ‚‚ apply pushout_cocone.is_colimit.hom_ext H.is_colimit Β· symm exact (H.is_colimit.fac _ walking_span.left).trans eβ‚‚.symm Β· erw [H.is_colimit.fac _ walking_span.right] apply binary_cofan.is_colimit.hom_ext hc Β· dsimp erw [hc.fac, ← H.w_assoc, eβ‚‚] rfl Β· refine' ((category.assoc _ _ _).symm.trans e₁).trans _ symm exact hc.fac _ _ #align category_theory.is_coprod_iff_is_pushout CategoryTheory.is_coprod_iff_isPushout theorem IsPushout.isVanKampen_inl {W E X Z : C} (c : BinaryCofan W E) [FinitaryExtensive C] [HasPullbacks C] (hc : IsColimit c) (f : W ⟢ X) (h : X ⟢ Z) (i : c.pt ⟢ Z) (H : IsPushout f c.inl h i) : H.IsVanKampen := by obtain ⟨hcβ‚βŸ© := (is_coprod_iff_is_pushout c hc H.1).mpr H introv W' hf hg hh hi w obtain ⟨hcβ‚‚βŸ© := ((binary_cofan.is_van_kampen_iff _).mp (finitary_extensive.van_kampen c hc) (binary_cofan.mk _ pullback.fst) _ _ _ hg.w.symm pullback.condition.symm).mpr ⟨hg, is_pullback.of_has_pullback Ξ±Y c.inr⟩ refine' (is_coprod_iff_is_pushout _ hcβ‚‚ w).symm.trans _ refine' ((binary_cofan.is_van_kampen_iff _).mp (finitary_extensive.van_kampen _ hc₁) (binary_cofan.mk _ _) pullback.snd _ _ _ hh.w.symm).trans _ Β· dsimp rw [← pullback.condition_assoc, category.assoc, hi.w] constructor Β· rintro ⟨hc₃, hcβ‚„βŸ© refine' ⟨hcβ‚„, _⟩ let Y'' := pullback Ξ±Z i let cmp : Y' ⟢ Y'' := pullback.lift i' Ξ±Y hi.w have e₁ : (g' ≫ cmp) ≫ pullback.snd = Ξ±W ≫ c.inl := by rw [category.assoc, pullback.lift_snd, hg.w] have eβ‚‚ : (pullback.fst ≫ cmp : pullback Ξ±Y c.inr ⟢ _) ≫ pullback.snd = pullback.snd ≫ c.inr := by rw [category.assoc, pullback.lift_snd, pullback.condition] obtain ⟨hcβ‚„βŸ© := ((binary_cofan.is_van_kampen_iff _).mp (finitary_extensive.van_kampen c hc) (binary_cofan.mk _ _) Ξ±W _ _ e₁.symm eβ‚‚.symm).mpr ⟨_, _⟩ Β· rw [← category.id_comp Ξ±Z, ← show cmp ≫ pullback.snd = Ξ±Y from pullback.lift_snd _ _ _] apply is_pullback.paste_vert _ (is_pullback.of_has_pullback Ξ±Z i) have : cmp = (hcβ‚‚.cocone_point_unique_up_to_iso hcβ‚„).Hom := by apply binary_cofan.is_colimit.hom_ext hcβ‚‚ exacts[(hcβ‚‚.comp_cocone_point_unique_up_to_iso_hom hcβ‚„ ⟨walking_pair.left⟩).symm, (hcβ‚‚.comp_cocone_point_unique_up_to_iso_hom hcβ‚„ ⟨walking_pair.right⟩).symm] rw [this] exact is_pullback.of_vert_is_iso ⟨by rw [← this, category.comp_id, pullback.lift_fst]⟩ Β· apply is_pullback.of_right _ e₁ (is_pullback.of_has_pullback _ _) rw [category.assoc, pullback.lift_fst, ← H.w, ← w.w] exact hf.paste_horiz hcβ‚„ Β· apply is_pullback.of_right _ eβ‚‚ (is_pullback.of_has_pullback _ _) rw [category.assoc, pullback.lift_fst] exact hc₃ Β· rintro ⟨hc₃, hcβ‚„βŸ© exact ⟨(is_pullback.of_has_pullback Ξ±Y c.inr).paste_horiz hcβ‚„, hcβ‚ƒβŸ© #align category_theory.is_pushout.is_van_kampen_inl CategoryTheory.IsPushout.isVanKampen_inl theorem IsPushout.IsVanKampen.isPullback_of_mono_left [Mono f] {H : IsPushout f g h i} (H' : H.IsVanKampen) : IsPullback f g h i := ((H' (πŸ™ _) g g (πŸ™ Y) (πŸ™ _) f (πŸ™ _) i (IsKernelPair.id_of_mono f) (IsPullback.of_vert_isIso ⟨by simp⟩) H.1.flip ⟨rfl⟩ ⟨by simp⟩).mp (IsPushout.of_horiz_isIso ⟨by simp⟩)).1.flip #align category_theory.is_pushout.is_van_kampen.is_pullback_of_mono_left CategoryTheory.IsPushout.IsVanKampen.isPullback_of_mono_left theorem IsPushout.IsVanKampen.isPullback_of_mono_right [Mono g] {H : IsPushout f g h i} (H' : H.IsVanKampen) : IsPullback f g h i := ((H' f (πŸ™ _) (πŸ™ _) f (πŸ™ _) (πŸ™ _) g h (IsPullback.of_vert_isIso ⟨by simp⟩) (IsKernelPair.id_of_mono g) ⟨rfl⟩ H.1 ⟨by simp⟩).mp (IsPushout.of_vert_isIso ⟨by simp⟩)).2 #align category_theory.is_pushout.is_van_kampen.is_pullback_of_mono_right CategoryTheory.IsPushout.IsVanKampen.isPullback_of_mono_right theorem IsPushout.IsVanKampen.mono_of_mono_left [Mono f] {H : IsPushout f g h i} (H' : H.IsVanKampen) : Mono i := IsKernelPair.mono_of_isIso_fst ((H' (πŸ™ _) g g (πŸ™ Y) (πŸ™ _) f (πŸ™ _) i (IsKernelPair.id_of_mono f) (IsPullback.of_vert_isIso ⟨by simp⟩) H.1.flip ⟨rfl⟩ ⟨by simp⟩).mp (IsPushout.of_horiz_isIso ⟨by simp⟩)).2 #align category_theory.is_pushout.is_van_kampen.mono_of_mono_left CategoryTheory.IsPushout.IsVanKampen.mono_of_mono_left theorem IsPushout.IsVanKampen.mono_of_mono_right [Mono g] {H : IsPushout f g h i} (H' : H.IsVanKampen) : Mono h := IsKernelPair.mono_of_isIso_fst ((H' f (πŸ™ _) (πŸ™ _) f (πŸ™ _) (πŸ™ _) g h (IsPullback.of_vert_isIso ⟨by simp⟩) (IsKernelPair.id_of_mono g) ⟨rfl⟩ H.1 ⟨by simp⟩).mp (IsPushout.of_vert_isIso ⟨by simp⟩)).1 #align category_theory.is_pushout.is_van_kampen.mono_of_mono_right CategoryTheory.IsPushout.IsVanKampen.mono_of_mono_right /-- A category is adhesive if it has pushouts and pullbacks along monomorphisms, and such pushouts are van Kampen. -/ class Adhesive (C : Type u) [Category.{v} C] : Prop where [hasPullback_of_mono_left : βˆ€ {X Y S : C} (f : X ⟢ S) (g : Y ⟢ S) [Mono f], HasPullback f g] [hasPushout_of_mono_left : βˆ€ {X Y S : C} (f : S ⟢ X) (g : S ⟢ Y) [Mono f], HasPushout f g] van_kampen : βˆ€ {W X Y Z : C} {f : W ⟢ X} {g : W ⟢ Y} {h : X ⟢ Z} {i : Y ⟢ Z} [Mono f] (H : IsPushout f g h i), H.IsVanKampen #align category_theory.adhesive CategoryTheory.Adhesive attribute [instance] adhesive.has_pullback_of_mono_left adhesive.has_pushout_of_mono_left theorem Adhesive.van_kampen' [Adhesive C] [Mono g] (H : IsPushout f g h i) : H.IsVanKampen := (Adhesive.van_kampen H.flip).flip #align category_theory.adhesive.van_kampen' CategoryTheory.Adhesive.van_kampen' theorem Adhesive.isPullback_of_isPushout_of_mono_left [Adhesive C] (H : IsPushout f g h i) [Mono f] : IsPullback f g h i := (Adhesive.van_kampen H).isPullback_of_mono_left #align category_theory.adhesive.is_pullback_of_is_pushout_of_mono_left CategoryTheory.Adhesive.isPullback_of_isPushout_of_mono_left theorem Adhesive.isPullback_of_isPushout_of_mono_right [Adhesive C] (H : IsPushout f g h i) [Mono g] : IsPullback f g h i := (Adhesive.van_kampen' H).isPullback_of_mono_right #align category_theory.adhesive.is_pullback_of_is_pushout_of_mono_right CategoryTheory.Adhesive.isPullback_of_isPushout_of_mono_right theorem Adhesive.mono_of_isPushout_of_mono_left [Adhesive C] (H : IsPushout f g h i) [Mono f] : Mono i := (Adhesive.van_kampen H).mono_of_mono_left #align category_theory.adhesive.mono_of_is_pushout_of_mono_left CategoryTheory.Adhesive.mono_of_isPushout_of_mono_left theorem Adhesive.mono_of_isPushout_of_mono_right [Adhesive C] (H : IsPushout f g h i) [Mono g] : Mono h := (Adhesive.van_kampen' H).mono_of_mono_right #align category_theory.adhesive.mono_of_is_pushout_of_mono_right CategoryTheory.Adhesive.mono_of_isPushout_of_mono_right instance Type.adhesive : Adhesive (Type u) := by constructor intros exact (is_pushout.is_van_kampen_inl _ (types.is_coprod_of_mono f) _ _ _ H.flip).flip #align category_theory.type.adhesive CategoryTheory.Type.adhesive noncomputable instance (priority := 100) Adhesive.toRegularMonoCategory [Adhesive C] : RegularMonoCategory C := ⟨fun X Y f hf => { z := pushout f f left := pushout.inl right := pushout.inr w := pushout.condition IsLimit := (adhesive.is_pullback_of_is_pushout_of_mono_left (is_pushout.of_has_pushout f f)).isLimitFork }⟩ #align category_theory.adhesive.to_regular_mono_category CategoryTheory.Adhesive.toRegularMonoCategory -- This then implies that adhesive categories are balanced example [Adhesive C] : Balanced C := inferInstance end CategoryTheory
------------------------------------------------------------------------ -- Unary relations (variant for Set₁) ------------------------------------------------------------------------ -- I want universe polymorphism. module Relation.Unary1 where ------------------------------------------------------------------------ -- Unary relations Pred : Set β†’ Setβ‚‚ Pred a = a β†’ Set₁ ------------------------------------------------------------------------ -- Unary relations can be seen as sets -- I.e., they can be seen as subsets of the universe of discourse. private module Dummy {a : Set} -- The universe of discourse. where -- Set membership. infix 4 _∈_ _∈_ : a β†’ Pred a β†’ Set₁ x ∈ P = P x -- The property of being universal. Universal : Pred a β†’ Set₁ Universal P = βˆ€ x β†’ x ∈ P -- PΒ βŠ†Β Q means that P is a subset of Q. _βŠ†β€²_ is a variant of _βŠ†_. infix 4 _βŠ†_ _βŠ‡_ _βŠ†β€²_ _βŠ‡β€²_ _βŠ†_ : Pred a β†’ Pred a β†’ Set₁ P βŠ† Q = βˆ€ {x} β†’ x ∈ P β†’ x ∈ Q _βŠ†β€²_ : Pred a β†’ Pred a β†’ Set₁ P βŠ†β€² Q = βˆ€ x β†’ x ∈ P β†’ x ∈ Q _βŠ‡_ : Pred a β†’ Pred a β†’ Set₁ Q βŠ‡ P = P βŠ† Q _βŠ‡β€²_ : Pred a β†’ Pred a β†’ Set₁ Q βŠ‡β€² P = P βŠ†β€² Q open Dummy public
/- Copyright (c) 2019 SΓ©bastien GouΓ«zel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: SΓ©bastien GouΓ«zel -/ import topology.metric_space.closeds import set_theory.cardinal import topology.metric_space.gromov_hausdorff_realized import topology.metric_space.completion import topology.metric_space.kuratowski /-! # Gromov-Hausdorff distance This file defines the Gromov-Hausdorff distance on the space of nonempty compact metric spaces up to isometry. We introduce the space of all nonempty compact metric spaces, up to isometry, called `GH_space`, and endow it with a metric space structure. The distance, known as the Gromov-Hausdorff distance, is defined as follows: given two nonempty compact spaces `X` and `Y`, their distance is the minimum Hausdorff distance between all possible isometric embeddings of `X` and `Y` in all metric spaces. To define properly the Gromov-Hausdorff space, we consider the non-empty compact subsets of `β„“^∞(ℝ)` up to isometry, which is a well-defined type, and define the distance as the infimum of the Hausdorff distance over all embeddings in `β„“^∞(ℝ)`. We prove that this coincides with the previous description, as all separable metric spaces embed isometrically into `β„“^∞(ℝ)`, through an embedding called the Kuratowski embedding. To prove that we have a distance, we should show that if spaces can be coupled to be arbitrarily close, then they are isometric. More generally, the Gromov-Hausdorff distance is realized, i.e., there is a coupling for which the Hausdorff distance is exactly the Gromov-Hausdorff distance. This follows from a compactness argument, essentially following from Arzela-Ascoli. ## Main results We prove the most important properties of the Gromov-Hausdorff space: it is a polish space, i.e., it is complete and second countable. We also prove the Gromov compactness criterion. -/ noncomputable theory open_locale classical topological_space ennreal local notation `β„“_infty_ℝ`:= lp (Ξ» n : β„•, ℝ) ∞ universes u v w open classical set function topological_space filter metric quotient open bounded_continuous_function nat int Kuratowski_embedding open sum (inl inr) local attribute [instance] metric_space_sum namespace Gromov_Hausdorff section GH_space /- In this section, we define the Gromov-Hausdorff space, denoted `GH_space` as the quotient of nonempty compact subsets of `β„“^∞(ℝ)` by identifying isometric sets. Using the Kuratwoski embedding, we get a canonical map `to_GH_space` mapping any nonempty compact type to `GH_space`. -/ /-- Equivalence relation identifying two nonempty compact sets which are isometric -/ private definition isometry_rel : nonempty_compacts β„“_infty_ℝ β†’ nonempty_compacts β„“_infty_ℝ β†’ Prop := Ξ» x y, nonempty (x.val ≃ᡒ y.val) /-- This is indeed an equivalence relation -/ private lemma is_equivalence_isometry_rel : equivalence isometry_rel := ⟨λ x, ⟨isometric.refl _⟩, Ξ» x y ⟨e⟩, ⟨e.symm⟩, Ξ» x y z ⟨e⟩ ⟨f⟩, ⟨e.trans f⟩⟩ /-- setoid instance identifying two isometric nonempty compact subspaces of β„“^∞(ℝ) -/ instance isometry_rel.setoid : setoid (nonempty_compacts β„“_infty_ℝ) := setoid.mk isometry_rel is_equivalence_isometry_rel /-- The Gromov-Hausdorff space -/ definition GH_space : Type := quotient (isometry_rel.setoid) /-- Map any nonempty compact type to `GH_space` -/ definition to_GH_space (X : Type u) [metric_space X] [compact_space X] [nonempty X] : GH_space := ⟦nonempty_compacts.Kuratowski_embedding X⟧ instance : inhabited GH_space := ⟨quot.mk _ ⟨{0}, by simp⟩⟩ /-- A metric space representative of any abstract point in `GH_space` -/ @[nolint has_inhabited_instance] definition GH_space.rep (p : GH_space) : Type := (quot.out p).val lemma eq_to_GH_space_iff {X : Type u} [metric_space X] [compact_space X] [nonempty X] {p : nonempty_compacts β„“_infty_ℝ} : ⟦p⟧ = to_GH_space X ↔ βˆƒ Ξ¨ : X β†’ β„“_infty_ℝ, isometry Ξ¨ ∧ range Ξ¨ = p.val := begin simp only [to_GH_space, quotient.eq], refine ⟨λ h, _, _⟩, { rcases setoid.symm h with ⟨e⟩, have f := (Kuratowski_embedding.isometry X).isometric_on_range.trans e, use [Ξ» x, f x, isometry_subtype_coe.comp f.isometry], rw [range_comp, f.range_eq_univ, set.image_univ, subtype.range_coe] }, { rintros ⟨Ψ, ⟨isomΞ¨, rangeΨ⟩⟩, have f := ((Kuratowski_embedding.isometry X).isometric_on_range.symm.trans isomΞ¨.isometric_on_range).symm, have E : (range Ξ¨ ≃ᡒ (nonempty_compacts.Kuratowski_embedding X).val) = (p.val ≃ᡒ range (Kuratowski_embedding X)), by { dunfold nonempty_compacts.Kuratowski_embedding, rw [rangeΞ¨]; refl }, exact ⟨cast E f⟩ } end lemma eq_to_GH_space {p : nonempty_compacts β„“_infty_ℝ} : ⟦p⟧ = to_GH_space p.val := eq_to_GH_space_iff.2 ⟨λ x, x, isometry_subtype_coe, subtype.range_coe⟩ section local attribute [reducible] GH_space.rep instance rep_GH_space_metric_space {p : GH_space} : metric_space (p.rep) := by apply_instance instance rep_GH_space_compact_space {p : GH_space} : compact_space (p.rep) := by apply_instance instance rep_GH_space_nonempty {p : GH_space} : nonempty (p.rep) := by apply_instance end lemma GH_space.to_GH_space_rep (p : GH_space) : to_GH_space (p.rep) = p := begin change to_GH_space (quot.out p).val = p, rw ← eq_to_GH_space, exact quot.out_eq p end /-- Two nonempty compact spaces have the same image in `GH_space` if and only if they are isometric. -/ lemma to_GH_space_eq_to_GH_space_iff_isometric {X : Type u} [metric_space X] [compact_space X] [nonempty X] {Y : Type v} [metric_space Y] [compact_space Y] [nonempty Y] : to_GH_space X = to_GH_space Y ↔ nonempty (X ≃ᡒ Y) := ⟨begin simp only [to_GH_space, quotient.eq], rintro ⟨e⟩, have I : ((nonempty_compacts.Kuratowski_embedding X).val ≃ᡒ (nonempty_compacts.Kuratowski_embedding Y).val) = ((range (Kuratowski_embedding X)) ≃ᡒ (range (Kuratowski_embedding Y))), by { dunfold nonempty_compacts.Kuratowski_embedding, refl }, have f := (Kuratowski_embedding.isometry X).isometric_on_range, have g := (Kuratowski_embedding.isometry Y).isometric_on_range.symm, exact ⟨f.trans $ (cast I e).trans g⟩ end, begin rintro ⟨e⟩, simp only [to_GH_space, quotient.eq], have f := (Kuratowski_embedding.isometry X).isometric_on_range.symm, have g := (Kuratowski_embedding.isometry Y).isometric_on_range, have I : ((range (Kuratowski_embedding X)) ≃ᡒ (range (Kuratowski_embedding Y))) = ((nonempty_compacts.Kuratowski_embedding X).val ≃ᡒ (nonempty_compacts.Kuratowski_embedding Y).val), by { dunfold nonempty_compacts.Kuratowski_embedding, refl }, exact ⟨cast I ((f.trans e).trans g)⟩ end⟩ /-- Distance on `GH_space`: the distance between two nonempty compact spaces is the infimum Hausdorff distance between isometric copies of the two spaces in a metric space. For the definition, we only consider embeddings in `β„“^∞(ℝ)`, but we will prove below that it works for all spaces. -/ instance : has_dist (GH_space) := { dist := Ξ» x y, Inf $ (Ξ» p : nonempty_compacts β„“_infty_ℝ Γ— nonempty_compacts β„“_infty_ℝ, Hausdorff_dist p.1.val p.2.val) '' ({a | ⟦a⟧ = x} Γ—Λ’ {b | ⟦b⟧ = y}) } /-- The Gromov-Hausdorff distance between two nonempty compact metric spaces, equal by definition to the distance of the equivalence classes of these spaces in the Gromov-Hausdorff space. -/ def GH_dist (X : Type u) (Y : Type v) [metric_space X] [nonempty X] [compact_space X] [metric_space Y] [nonempty Y] [compact_space Y] : ℝ := dist (to_GH_space X) (to_GH_space Y) lemma dist_GH_dist (p q : GH_space) : dist p q = GH_dist (p.rep) (q.rep) := by rw [GH_dist, p.to_GH_space_rep, q.to_GH_space_rep] /-- The Gromov-Hausdorff distance between two spaces is bounded by the Hausdorff distance of isometric copies of the spaces, in any metric space. -/ theorem GH_dist_le_Hausdorff_dist {X : Type u} [metric_space X] [compact_space X] [nonempty X] {Y : Type v} [metric_space Y] [compact_space Y] [nonempty Y] {Ξ³ : Type w} [metric_space Ξ³] {Ξ¦ : X β†’ Ξ³} {Ξ¨ : Y β†’ Ξ³} (ha : isometry Ξ¦) (hb : isometry Ξ¨) : GH_dist X Y ≀ Hausdorff_dist (range Ξ¦) (range Ξ¨) := begin /- For the proof, we want to embed `Ξ³` in `β„“^∞(ℝ)`, to say that the Hausdorff distance is realized in `β„“^∞(ℝ)` and therefore bounded below by the Gromov-Hausdorff-distance. However, `Ξ³` is not separable in general. We restrict to the union of the images of `X` and `Y` in `Ξ³`, which is separable and therefore embeddable in `β„“^∞(ℝ)`. -/ rcases exists_mem_of_nonempty X with ⟨xX, _⟩, let s : set Ξ³ := (range Ξ¦) βˆͺ (range Ξ¨), let Ξ¦' : X β†’ subtype s := Ξ» y, ⟨Φ y, mem_union_left _ (mem_range_self _)⟩, let Ξ¨' : Y β†’ subtype s := Ξ» y, ⟨Ψ y, mem_union_right _ (mem_range_self _)⟩, have IΞ¦' : isometry Ξ¦' := Ξ» x y, ha x y, have IΞ¨' : isometry Ξ¨' := Ξ» x y, hb x y, have : is_compact s, from (is_compact_range ha.continuous).union (is_compact_range hb.continuous), letI : metric_space (subtype s) := by apply_instance, haveI : compact_space (subtype s) := ⟨is_compact_iff_is_compact_univ.1 β€Ήis_compact sβ€ΊβŸ©, haveI : nonempty (subtype s) := ⟨Φ' xX⟩, have ΦΦ' : Ξ¦ = subtype.val ∘ Ξ¦', by { funext, refl }, have ΨΨ' : Ξ¨ = subtype.val ∘ Ξ¨', by { funext, refl }, have : Hausdorff_dist (range Ξ¦) (range Ξ¨) = Hausdorff_dist (range Ξ¦') (range Ξ¨'), { rw [ΦΦ', ΨΨ', range_comp, range_comp], exact Hausdorff_dist_image (isometry_subtype_coe) }, rw this, -- Embed `s` in `β„“^∞(ℝ)` through its Kuratowski embedding let F := Kuratowski_embedding (subtype s), have : Hausdorff_dist (F '' (range Ξ¦')) (F '' (range Ξ¨')) = Hausdorff_dist (range Ξ¦') (range Ξ¨') := Hausdorff_dist_image (Kuratowski_embedding.isometry _), rw ← this, -- Let `A` and `B` be the images of `X` and `Y` under this embedding. They are in `β„“^∞(ℝ)`, and -- their Hausdorff distance is the same as in the original space. let A : nonempty_compacts β„“_infty_ℝ := ⟨F '' (range Ξ¦'), ⟨(range_nonempty _).image _, (is_compact_range IΞ¦'.continuous).image (Kuratowski_embedding.isometry _).continuous⟩⟩, let B : nonempty_compacts β„“_infty_ℝ := ⟨F '' (range Ξ¨'), ⟨(range_nonempty _).image _, (is_compact_range IΞ¨'.continuous).image (Kuratowski_embedding.isometry _).continuous⟩⟩, have AX : ⟦A⟧ = to_GH_space X, { rw eq_to_GH_space_iff, exact ⟨λ x, F (Ξ¦' x), ⟨(Kuratowski_embedding.isometry _).comp IΞ¦', by rw range_comp⟩⟩ }, have BY : ⟦B⟧ = to_GH_space Y, { rw eq_to_GH_space_iff, exact ⟨λ x, F (Ξ¨' x), ⟨(Kuratowski_embedding.isometry _).comp IΞ¨', by rw range_comp⟩⟩ }, refine cInf_le ⟨0, begin simp [lower_bounds], assume t _ _ _ _ ht, rw ← ht, exact Hausdorff_dist_nonneg end⟩ _, apply (mem_image _ _ _).2, existsi (⟨A, B⟩ : nonempty_compacts β„“_infty_ℝ Γ— nonempty_compacts β„“_infty_ℝ), simp [AX, BY] end /-- The optimal coupling constructed above realizes exactly the Gromov-Hausdorff distance, essentially by design. -/ lemma Hausdorff_dist_optimal {X : Type u} [metric_space X] [compact_space X] [nonempty X] {Y : Type v} [metric_space Y] [compact_space Y] [nonempty Y] : Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) = GH_dist X Y := begin inhabit X, inhabit Y, /- we only need to check the inequality `≀`, as the other one follows from the previous lemma. As the Gromov-Hausdorff distance is an infimum, we need to check that the Hausdorff distance in the optimal coupling is smaller than the Hausdorff distance of any coupling. First, we check this for couplings which already have small Hausdorff distance: in this case, the induced "distance" on `X βŠ• Y` belongs to the candidates family introduced in the definition of the optimal coupling, and the conclusion follows from the optimality of the optimal coupling within this family. -/ have A : βˆ€ p q : nonempty_compacts (β„“_infty_ℝ), ⟦p⟧ = to_GH_space X β†’ ⟦q⟧ = to_GH_space Y β†’ Hausdorff_dist (p.val) (q.val) < diam (univ : set X) + 1 + diam (univ : set Y) β†’ Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) ≀ Hausdorff_dist (p.val) (q.val), { assume p q hp hq bound, rcases eq_to_GH_space_iff.1 hp with ⟨Φ, ⟨Φisom, Ξ¦range⟩⟩, rcases eq_to_GH_space_iff.1 hq with ⟨Ψ, ⟨Ψisom, Ξ¨range⟩⟩, have I : diam (range Ξ¦ βˆͺ range Ξ¨) ≀ 2 * diam (univ : set X) + 1 + 2 * diam (univ : set Y), { rcases exists_mem_of_nonempty X with ⟨xX, _⟩, have : βˆƒ y ∈ range Ξ¨, dist (Ξ¦ xX) y < diam (univ : set X) + 1 + diam (univ : set Y), { rw Ξ¨range, have : Ξ¦ xX ∈ p.val := Ξ¦range β–Έ mem_range_self _, exact exists_dist_lt_of_Hausdorff_dist_lt this bound (Hausdorff_edist_ne_top_of_nonempty_of_bounded p.2.1 q.2.1 p.2.2.bounded q.2.2.bounded) }, rcases this with ⟨y, hy, dy⟩, rcases mem_range.1 hy with ⟨z, hzy⟩, rw ← hzy at dy, have DΞ¦ : diam (range Ξ¦) = diam (univ : set X) := Ξ¦isom.diam_range, have DΞ¨ : diam (range Ξ¨) = diam (univ : set Y) := Ξ¨isom.diam_range, calc diam (range Ξ¦ βˆͺ range Ξ¨) ≀ diam (range Ξ¦) + dist (Ξ¦ xX) (Ξ¨ z) + diam (range Ξ¨) : diam_union (mem_range_self _) (mem_range_self _) ... ≀ diam (univ : set X) + (diam (univ : set X) + 1 + diam (univ : set Y)) + diam (univ : set Y) : by { rw [DΞ¦, DΞ¨], apply add_le_add (add_le_add le_rfl (le_of_lt dy)) le_rfl } ... = 2 * diam (univ : set X) + 1 + 2 * diam (univ : set Y) : by ring }, let f : X βŠ• Y β†’ β„“_infty_ℝ := Ξ» x, match x with | inl y := Ξ¦ y | inr z := Ξ¨ z end, let F : (X βŠ• Y) Γ— (X βŠ• Y) β†’ ℝ := Ξ» p, dist (f p.1) (f p.2), -- check that the induced "distance" is a candidate have Fgood : F ∈ candidates X Y, { simp only [candidates, forall_const, and_true, add_comm, eq_self_iff_true, dist_eq_zero, and_self, set.mem_set_of_eq], repeat {split}, { exact Ξ» x y, calc F (inl x, inl y) = dist (Ξ¦ x) (Ξ¦ y) : rfl ... = dist x y : Ξ¦isom.dist_eq x y }, { exact Ξ» x y, calc F (inr x, inr y) = dist (Ξ¨ x) (Ξ¨ y) : rfl ... = dist x y : Ξ¨isom.dist_eq x y }, { exact Ξ» x y, dist_comm _ _ }, { exact Ξ» x y z, dist_triangle _ _ _ }, { exact Ξ» x y, calc F (x, y) ≀ diam (range Ξ¦ βˆͺ range Ξ¨) : begin have A : βˆ€ z : X βŠ• Y, f z ∈ range Ξ¦ βˆͺ range Ξ¨, { assume z, cases z, { apply mem_union_left, apply mem_range_self }, { apply mem_union_right, apply mem_range_self } }, refine dist_le_diam_of_mem _ (A _) (A _), rw [Ξ¦range, Ξ¨range], exact (p.2.2.union q.2.2).bounded, end ... ≀ 2 * diam (univ : set X) + 1 + 2 * diam (univ : set Y) : I } }, let Fb := candidates_b_of_candidates F Fgood, have : Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) ≀ HD Fb := Hausdorff_dist_optimal_le_HD _ _ (candidates_b_of_candidates_mem F Fgood), refine le_trans this (le_of_forall_le_of_dense (Ξ» r hr, _)), have I1 : βˆ€ x : X, (β¨… y, Fb (inl x, inr y)) ≀ r, { assume x, have : f (inl x) ∈ p.val, by { rw [← Ξ¦range], apply mem_range_self }, rcases exists_dist_lt_of_Hausdorff_dist_lt this hr (Hausdorff_edist_ne_top_of_nonempty_of_bounded p.2.1 q.2.1 p.2.2.bounded q.2.2.bounded) with ⟨z, zq, hz⟩, have : z ∈ range Ξ¨, by rwa [← Ξ¨range] at zq, rcases mem_range.1 this with ⟨y, hy⟩, calc (β¨… y, Fb (inl x, inr y)) ≀ Fb (inl x, inr y) : cinfi_le (by simpa using HD_below_aux1 0) y ... = dist (Ξ¦ x) (Ξ¨ y) : rfl ... = dist (f (inl x)) z : by rw hy ... ≀ r : le_of_lt hz }, have I2 : βˆ€ y : Y, (β¨… x, Fb (inl x, inr y)) ≀ r, { assume y, have : f (inr y) ∈ q.val, by { rw [← Ξ¨range], apply mem_range_self }, rcases exists_dist_lt_of_Hausdorff_dist_lt' this hr (Hausdorff_edist_ne_top_of_nonempty_of_bounded p.2.1 q.2.1 p.2.2.bounded q.2.2.bounded) with ⟨z, zq, hz⟩, have : z ∈ range Ξ¦, by rwa [← Ξ¦range] at zq, rcases mem_range.1 this with ⟨x, hx⟩, calc (β¨… x, Fb (inl x, inr y)) ≀ Fb (inl x, inr y) : cinfi_le (by simpa using HD_below_aux2 0) x ... = dist (Ξ¦ x) (Ξ¨ y) : rfl ... = dist z (f (inr y)) : by rw hx ... ≀ r : le_of_lt hz }, simp [HD, csupr_le I1, csupr_le I2] }, /- Get the same inequality for any coupling. If the coupling is quite good, the desired inequality has been proved above. If it is bad, then the inequality is obvious. -/ have B : βˆ€ p q : nonempty_compacts (β„“_infty_ℝ), ⟦p⟧ = to_GH_space X β†’ ⟦q⟧ = to_GH_space Y β†’ Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) ≀ Hausdorff_dist (p.val) (q.val), { assume p q hp hq, by_cases h : Hausdorff_dist (p.val) (q.val) < diam (univ : set X) + 1 + diam (univ : set Y), { exact A p q hp hq h }, { calc Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) ≀ HD (candidates_b_dist X Y) : Hausdorff_dist_optimal_le_HD _ _ (candidates_b_dist_mem_candidates_b) ... ≀ diam (univ : set X) + 1 + diam (univ : set Y) : HD_candidates_b_dist_le ... ≀ Hausdorff_dist (p.val) (q.val) : not_lt.1 h } }, refine le_antisymm _ _, { apply le_cInf, { refine (set.nonempty.prod _ _).image _; exact ⟨_, rfl⟩ }, { rintro b ⟨⟨p, q⟩, ⟨hp, hq⟩, rfl⟩, exact B p q hp hq } }, { exact GH_dist_le_Hausdorff_dist (isometry_optimal_GH_injl X Y) (isometry_optimal_GH_injr X Y) } end /-- The Gromov-Hausdorff distance can also be realized by a coupling in `β„“^∞(ℝ)`, by embedding the optimal coupling through its Kuratowski embedding. -/ theorem GH_dist_eq_Hausdorff_dist (X : Type u) [metric_space X] [compact_space X] [nonempty X] (Y : Type v) [metric_space Y] [compact_space Y] [nonempty Y] : βˆƒ Ξ¦ : X β†’ β„“_infty_ℝ, βˆƒ Ξ¨ : Y β†’ β„“_infty_ℝ, isometry Ξ¦ ∧ isometry Ξ¨ ∧ GH_dist X Y = Hausdorff_dist (range Ξ¦) (range Ξ¨) := begin let F := Kuratowski_embedding (optimal_GH_coupling X Y), let Ξ¦ := F ∘ optimal_GH_injl X Y, let Ξ¨ := F ∘ optimal_GH_injr X Y, refine ⟨Φ, Ξ¨, _, _, _⟩, { exact (Kuratowski_embedding.isometry _).comp (isometry_optimal_GH_injl X Y) }, { exact (Kuratowski_embedding.isometry _).comp (isometry_optimal_GH_injr X Y) }, { rw [← image_univ, ← image_univ, image_comp F, image_univ, image_comp F (optimal_GH_injr X Y), image_univ, ← Hausdorff_dist_optimal], exact (Hausdorff_dist_image (Kuratowski_embedding.isometry _)).symm }, end /-- The Gromov-Hausdorff distance defines a genuine distance on the Gromov-Hausdorff space. -/ instance : metric_space GH_space := { dist_self := Ξ» x, begin rcases exists_rep x with ⟨y, hy⟩, refine le_antisymm _ _, { apply cInf_le, { exact ⟨0, by { rintro b ⟨⟨u, v⟩, ⟨hu, hv⟩, rfl⟩, exact Hausdorff_dist_nonneg } ⟩}, { simp, existsi [y, y], simpa } }, { apply le_cInf, { exact (nonempty.prod ⟨y, hy⟩ ⟨y, hy⟩).image _ }, { rintro b ⟨⟨u, v⟩, ⟨hu, hv⟩, rfl⟩, exact Hausdorff_dist_nonneg } }, end, dist_comm := Ξ» x y, begin have A : (Ξ» (p : nonempty_compacts β„“_infty_ℝ Γ— nonempty_compacts β„“_infty_ℝ), Hausdorff_dist ((p.fst).val) ((p.snd).val)) '' ({a | ⟦a⟧ = x} Γ—Λ’ {b | ⟦b⟧ = y}) = ((Ξ» (p : nonempty_compacts β„“_infty_ℝ Γ— nonempty_compacts β„“_infty_ℝ), Hausdorff_dist ((p.fst).val) ((p.snd).val)) ∘ prod.swap) '' ({a | ⟦a⟧ = x} Γ—Λ’ {b | ⟦b⟧ = y}) := by { congr, funext, simp, rw Hausdorff_dist_comm }, simp only [dist, A, image_comp, image_swap_prod], end, eq_of_dist_eq_zero := Ξ» x y hxy, begin /- To show that two spaces at zero distance are isometric, we argue that the distance is realized by some coupling. In this coupling, the two spaces are at zero Hausdorff distance, i.e., they coincide. Therefore, the original spaces are isometric. -/ rcases GH_dist_eq_Hausdorff_dist x.rep y.rep with ⟨Φ, Ξ¨, Ξ¦isom, Ξ¨isom, DΦΨ⟩, rw [← dist_GH_dist, hxy] at DΦΨ, have : range Ξ¦ = range Ξ¨, { have hΞ¦ : is_compact (range Ξ¦) := is_compact_range Ξ¦isom.continuous, have hΞ¨ : is_compact (range Ξ¨) := is_compact_range Ξ¨isom.continuous, apply (is_closed.Hausdorff_dist_zero_iff_eq _ _ _).1 (DΦΨ.symm), { exact hΞ¦.is_closed }, { exact hΞ¨.is_closed }, { exact Hausdorff_edist_ne_top_of_nonempty_of_bounded (range_nonempty _) (range_nonempty _) hΞ¦.bounded hΞ¨.bounded } }, have T : ((range Ξ¨) ≃ᡒ y.rep) = ((range Ξ¦) ≃ᡒ y.rep), by rw this, have eΞ¨ := cast T Ξ¨isom.isometric_on_range.symm, have e := Ξ¦isom.isometric_on_range.trans eΞ¨, rw [← x.to_GH_space_rep, ← y.to_GH_space_rep, to_GH_space_eq_to_GH_space_iff_isometric], exact ⟨e⟩ end, dist_triangle := Ξ» x y z, begin /- To show the triangular inequality between `X`, `Y` and `Z`, realize an optimal coupling between `X` and `Y` in a space `Ξ³1`, and an optimal coupling between `Y` and `Z` in a space `Ξ³2`. Then, glue these metric spaces along `Y`. We get a new space `Ξ³` in which `X` and `Y` are optimally coupled, as well as `Y` and `Z`. Apply the triangle inequality for the Hausdorff distance in `Ξ³` to conclude. -/ let X := x.rep, let Y := y.rep, let Z := z.rep, let Ξ³1 := optimal_GH_coupling X Y, let Ξ³2 := optimal_GH_coupling Y Z, let Ξ¦ : Y β†’ Ξ³1 := optimal_GH_injr X Y, have hΞ¦ : isometry Ξ¦ := isometry_optimal_GH_injr X Y, let Ξ¨ : Y β†’ Ξ³2 := optimal_GH_injl Y Z, have hΞ¨ : isometry Ξ¨ := isometry_optimal_GH_injl Y Z, let Ξ³ := glue_space hΞ¦ hΞ¨, letI : metric_space Ξ³ := metric.metric_space_glue_space hΞ¦ hΞ¨, have Comm : (to_glue_l hΞ¦ hΞ¨) ∘ (optimal_GH_injr X Y) = (to_glue_r hΞ¦ hΞ¨) ∘ (optimal_GH_injl Y Z) := to_glue_commute hΞ¦ hΞ¨, calc dist x z = dist (to_GH_space X) (to_GH_space Z) : by rw [x.to_GH_space_rep, z.to_GH_space_rep] ... ≀ Hausdorff_dist (range ((to_glue_l hΞ¦ hΞ¨) ∘ (optimal_GH_injl X Y))) (range ((to_glue_r hΞ¦ hΞ¨) ∘ (optimal_GH_injr Y Z))) : GH_dist_le_Hausdorff_dist ((to_glue_l_isometry hΞ¦ hΞ¨).comp (isometry_optimal_GH_injl X Y)) ((to_glue_r_isometry hΞ¦ hΞ¨).comp (isometry_optimal_GH_injr Y Z)) ... ≀ Hausdorff_dist (range ((to_glue_l hΞ¦ hΞ¨) ∘ (optimal_GH_injl X Y))) (range ((to_glue_l hΞ¦ hΞ¨) ∘ (optimal_GH_injr X Y))) + Hausdorff_dist (range ((to_glue_l hΞ¦ hΞ¨) ∘ (optimal_GH_injr X Y))) (range ((to_glue_r hΞ¦ hΞ¨) ∘ (optimal_GH_injr Y Z))) : begin refine Hausdorff_dist_triangle (Hausdorff_edist_ne_top_of_nonempty_of_bounded (range_nonempty _) (range_nonempty _) _ _), { exact (is_compact_range (isometry.continuous ((to_glue_l_isometry hΞ¦ hΞ¨).comp (isometry_optimal_GH_injl X Y)))).bounded }, { exact (is_compact_range (isometry.continuous ((to_glue_l_isometry hΞ¦ hΞ¨).comp (isometry_optimal_GH_injr X Y)))).bounded } end ... = Hausdorff_dist ((to_glue_l hΞ¦ hΞ¨) '' (range (optimal_GH_injl X Y))) ((to_glue_l hΞ¦ hΞ¨) '' (range (optimal_GH_injr X Y))) + Hausdorff_dist ((to_glue_r hΞ¦ hΞ¨) '' (range (optimal_GH_injl Y Z))) ((to_glue_r hΞ¦ hΞ¨) '' (range (optimal_GH_injr Y Z))) : by simp only [← range_comp, Comm, eq_self_iff_true, add_right_inj] ... = Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) + Hausdorff_dist (range (optimal_GH_injl Y Z)) (range (optimal_GH_injr Y Z)) : by rw [Hausdorff_dist_image (to_glue_l_isometry hΞ¦ hΞ¨), Hausdorff_dist_image (to_glue_r_isometry hΞ¦ hΞ¨)] ... = dist (to_GH_space X) (to_GH_space Y) + dist (to_GH_space Y) (to_GH_space Z) : by rw [Hausdorff_dist_optimal, Hausdorff_dist_optimal, GH_dist, GH_dist] ... = dist x y + dist y z: by rw [x.to_GH_space_rep, y.to_GH_space_rep, z.to_GH_space_rep] end } end GH_space --section end Gromov_Hausdorff /-- In particular, nonempty compacts of a metric space map to `GH_space`. We register this in the topological_space namespace to take advantage of the notation `p.to_GH_space`. -/ definition topological_space.nonempty_compacts.to_GH_space {X : Type u} [metric_space X] (p : nonempty_compacts X) : Gromov_Hausdorff.GH_space := Gromov_Hausdorff.to_GH_space p.val open topological_space namespace Gromov_Hausdorff section nonempty_compacts variables {X : Type u} [metric_space X] theorem GH_dist_le_nonempty_compacts_dist (p q : nonempty_compacts X) : dist p.to_GH_space q.to_GH_space ≀ dist p q := begin have ha : isometry (coe : p.val β†’ X) := isometry_subtype_coe, have hb : isometry (coe : q.val β†’ X) := isometry_subtype_coe, have A : dist p q = Hausdorff_dist p.val q.val := rfl, have I : p.val = range (coe : p.val β†’ X), by simp, have J : q.val = range (coe : q.val β†’ X), by simp, rw [I, J] at A, rw A, exact GH_dist_le_Hausdorff_dist ha hb end lemma to_GH_space_lipschitz : lipschitz_with 1 (nonempty_compacts.to_GH_space : nonempty_compacts X β†’ GH_space) := lipschitz_with.mk_one GH_dist_le_nonempty_compacts_dist lemma to_GH_space_continuous : continuous (nonempty_compacts.to_GH_space : nonempty_compacts X β†’ GH_space) := to_GH_space_lipschitz.continuous end nonempty_compacts section /- In this section, we show that if two metric spaces are isometric up to `Ξ΅β‚‚`, then their Gromov-Hausdorff distance is bounded by `Ξ΅β‚‚ / 2`. More generally, if there are subsets which are `Ρ₁`-dense and `Ρ₃`-dense in two spaces, and isometric up to `Ξ΅β‚‚`, then the Gromov-Hausdorff distance between the spaces is bounded by `Ρ₁ + Ξ΅β‚‚/2 + Ρ₃`. For this, we construct a suitable coupling between the two spaces, by gluing them (approximately) along the two matching subsets. -/ variables {X : Type u} [metric_space X] [compact_space X] [nonempty X] {Y : Type v} [metric_space Y] [compact_space Y] [nonempty Y] -- we want to ignore these instances in the following theorem local attribute [instance, priority 10] sum.topological_space sum.uniform_space /-- If there are subsets which are `Ρ₁`-dense and `Ρ₃`-dense in two spaces, and isometric up to `Ξ΅β‚‚`, then the Gromov-Hausdorff distance between the spaces is bounded by `Ρ₁ + Ξ΅β‚‚/2 + Ρ₃`. -/ theorem GH_dist_le_of_approx_subsets {s : set X} (Ξ¦ : s β†’ Y) {Ρ₁ Ξ΅β‚‚ Ρ₃ : ℝ} (hs : βˆ€ x : X, βˆƒ y ∈ s, dist x y ≀ Ρ₁) (hs' : βˆ€ x : Y, βˆƒ y : s, dist x (Ξ¦ y) ≀ Ρ₃) (H : βˆ€ x y : s, |dist x y - dist (Ξ¦ x) (Ξ¦ y)| ≀ Ξ΅β‚‚) : GH_dist X Y ≀ Ρ₁ + Ξ΅β‚‚ / 2 + Ρ₃ := begin refine le_of_forall_pos_le_add (Ξ» Ξ΄ Ξ΄0, _), rcases exists_mem_of_nonempty X with ⟨xX, _⟩, rcases hs xX with ⟨xs, hxs, Dxs⟩, have sne : s.nonempty := ⟨xs, hxs⟩, letI : nonempty s := sne.to_subtype, have : 0 ≀ Ξ΅β‚‚ := le_trans (abs_nonneg _) (H ⟨xs, hxs⟩ ⟨xs, hxs⟩), have : βˆ€ p q : s, |dist p q - dist (Ξ¦ p) (Ξ¦ q)| ≀ 2 * (Ξ΅β‚‚/2 + Ξ΄) := Ξ» p q, calc |dist p q - dist (Ξ¦ p) (Ξ¦ q)| ≀ Ξ΅β‚‚ : H p q ... ≀ 2 * (Ξ΅β‚‚/2 + Ξ΄) : by linarith, -- glue `X` and `Y` along the almost matching subsets letI : metric_space (X βŠ• Y) := glue_metric_approx (Ξ» x:s, (x:X)) (Ξ» x, Ξ¦ x) (Ξ΅β‚‚/2 + Ξ΄) (by linarith) this, let Fl := @sum.inl X Y, let Fr := @sum.inr X Y, have Il : isometry Fl := isometry_emetric_iff_metric.2 (Ξ» x y, rfl), have Ir : isometry Fr := isometry_emetric_iff_metric.2 (Ξ» x y, rfl), /- The proof goes as follows : the `GH_dist` is bounded by the Hausdorff distance of the images in the coupling, which is bounded (using the triangular inequality) by the sum of the Hausdorff distances of `X` and `s` (in the coupling or, equivalently in the original space), of `s` and `Ξ¦ s`, and of `Ξ¦ s` and `Y` (in the coupling or, equivalently, in the original space). The first term is bounded by `Ρ₁`, by `Ρ₁`-density. The third one is bounded by `Ρ₃`. And the middle one is bounded by `Ξ΅β‚‚/2` as in the coupling the points `x` and `Ξ¦ x` are at distance `Ξ΅β‚‚/2` by construction of the coupling (in fact `Ξ΅β‚‚/2 + Ξ΄` where `Ξ΄` is an arbitrarily small positive constant where positivity is used to ensure that the coupling is really a metric space and not a premetric space on `X βŠ• Y`). -/ have : GH_dist X Y ≀ Hausdorff_dist (range Fl) (range Fr) := GH_dist_le_Hausdorff_dist Il Ir, have : Hausdorff_dist (range Fl) (range Fr) ≀ Hausdorff_dist (range Fl) (Fl '' s) + Hausdorff_dist (Fl '' s) (range Fr), { have B : bounded (range Fl) := (is_compact_range Il.continuous).bounded, exact Hausdorff_dist_triangle (Hausdorff_edist_ne_top_of_nonempty_of_bounded (range_nonempty _) (sne.image _) B (B.mono (image_subset_range _ _))) }, have : Hausdorff_dist (Fl '' s) (range Fr) ≀ Hausdorff_dist (Fl '' s) (Fr '' (range Ξ¦)) + Hausdorff_dist (Fr '' (range Ξ¦)) (range Fr), { have B : bounded (range Fr) := (is_compact_range Ir.continuous).bounded, exact Hausdorff_dist_triangle' (Hausdorff_edist_ne_top_of_nonempty_of_bounded ((range_nonempty _).image _) (range_nonempty _) (bounded.mono (image_subset_range _ _) B) B) }, have : Hausdorff_dist (range Fl) (Fl '' s) ≀ Ρ₁, { rw [← image_univ, Hausdorff_dist_image Il], have : 0 ≀ Ρ₁ := le_trans dist_nonneg Dxs, refine Hausdorff_dist_le_of_mem_dist this (Ξ» x hx, hs x) (Ξ» x hx, ⟨x, mem_univ _, by simpa⟩) }, have : Hausdorff_dist (Fl '' s) (Fr '' (range Ξ¦)) ≀ Ξ΅β‚‚/2 + Ξ΄, { refine Hausdorff_dist_le_of_mem_dist (by linarith) _ _, { assume x' hx', rcases (set.mem_image _ _ _).1 hx' with ⟨x, ⟨x_in_s, xx'⟩⟩, rw ← xx', use [Fr (Ξ¦ ⟨x, x_in_s⟩), mem_image_of_mem Fr (mem_range_self _)], exact le_of_eq (glue_dist_glued_points (Ξ» x:s, (x:X)) Ξ¦ (Ξ΅β‚‚/2 + Ξ΄) ⟨x, x_in_s⟩) }, { assume x' hx', rcases (set.mem_image _ _ _).1 hx' with ⟨y, ⟨y_in_s', yx'⟩⟩, rcases mem_range.1 y_in_s' with ⟨x, xy⟩, use [Fl x, mem_image_of_mem _ x.2], rw [← yx', ← xy, dist_comm], exact le_of_eq (glue_dist_glued_points (@subtype.val X s) Ξ¦ (Ξ΅β‚‚/2 + Ξ΄) x) } }, have : Hausdorff_dist (Fr '' (range Ξ¦)) (range Fr) ≀ Ρ₃, { rw [← @image_univ _ _ Fr, Hausdorff_dist_image Ir], rcases exists_mem_of_nonempty Y with ⟨xY, _⟩, rcases hs' xY with ⟨xs', Dxs'⟩, have : 0 ≀ Ρ₃ := le_trans dist_nonneg Dxs', refine Hausdorff_dist_le_of_mem_dist this (Ξ» x hx, ⟨x, mem_univ _, by simpa⟩) (Ξ» x _, _), rcases hs' x with ⟨y, Dy⟩, exact ⟨Φ y, mem_range_self _, Dy⟩ }, linarith end end --section /-- The Gromov-Hausdorff space is second countable. -/ instance : second_countable_topology GH_space := begin refine second_countable_of_countable_discretization (Ξ» Ξ΄ Ξ΄pos, _), let Ξ΅ := (2/5) * Ξ΄, have Ξ΅pos : 0 < Ξ΅ := mul_pos (by norm_num) Ξ΄pos, have : βˆ€ p:GH_space, βˆƒ s : set (p.rep), finite s ∧ (univ βŠ† (⋃x∈s, ball x Ξ΅)) := Ξ» p, by simpa using finite_cover_balls_of_compact (@compact_univ p.rep _ _) Ξ΅pos, -- for each `p`, `s p` is a finite `Ξ΅`-dense subset of `p` (or rather the metric space -- `p.rep` representing `p`) choose s hs using this, have : βˆ€ p:GH_space, βˆ€ t:set (p.rep), finite t β†’ βˆƒ n:β„•, βˆƒ e:equiv t (fin n), true, { assume p t ht, letI : fintype t := finite.fintype ht, exact ⟨fintype.card t, fintype.equiv_fin t, trivial⟩ }, choose N e hne using this, -- cardinality of the nice finite subset `s p` of `p.rep`, called `N p` let N := Ξ» p:GH_space, N p (s p) (hs p).1, -- equiv from `s p`, a nice finite subset of `p.rep`, to `fin (N p)`, called `E p` let E := Ξ» p:GH_space, e p (s p) (hs p).1, -- A function `F` associating to `p : GH_space` the data of all distances between points -- in the `Ξ΅`-dense set `s p`. let F : GH_space β†’ Ξ£n:β„•, (fin n β†’ fin n β†’ β„€) := Ξ»p, ⟨N p, Ξ»a b, ⌊Ρ⁻¹ * dist ((E p).symm a) ((E p).symm b)βŒ‹βŸ©, refine ⟨Σ n, fin n β†’ fin n β†’ β„€, by apply_instance, F, Ξ»p q hpq, _⟩, /- As the target space of F is countable, it suffices to show that two points `p` and `q` with `F p = F q` are at distance `≀ Ξ΄`. For this, we construct a map `Ξ¦` from `s p βŠ† p.rep` (representing `p`) to `q.rep` (representing `q`) which is almost an isometry on `s p`, and with image `s q`. For this, we compose the identification of `s p` with `fin (N p)` and the inverse of the identification of `s q` with `fin (N q)`. Together with the fact that `N p = N q`, this constructs `Ξ¨` between `s p` and `s q`, and then composing with the canonical inclusion we get `Ξ¦`. -/ have Npq : N p = N q := (sigma.mk.inj_iff.1 hpq).1, let Ξ¨ : s p β†’ s q := Ξ» x, (E q).symm (fin.cast Npq ((E p) x)), let Ξ¦ : s p β†’ q.rep := Ξ» x, Ξ¨ x, -- Use the almost isometry `Ξ¦` to show that `p.rep` and `q.rep` -- are within controlled Gromov-Hausdorff distance. have main : GH_dist p.rep q.rep ≀ Ξ΅ + Ξ΅/2 + Ξ΅, { refine GH_dist_le_of_approx_subsets Ξ¦ _ _ _, show βˆ€ x : p.rep, βˆƒ (y : p.rep) (H : y ∈ s p), dist x y ≀ Ξ΅, { -- by construction, `s p` is `Ξ΅`-dense assume x, have : x ∈ ⋃y∈(s p), ball y Ξ΅ := (hs p).2 (mem_univ _), rcases mem_Unionβ‚‚.1 this with ⟨y, ys, hy⟩, exact ⟨y, ys, le_of_lt hy⟩ }, show βˆ€ x : q.rep, βˆƒ (z : s p), dist x (Ξ¦ z) ≀ Ξ΅, { -- by construction, `s q` is `Ξ΅`-dense, and it is the range of `Ξ¦` assume x, have : x ∈ ⋃y∈(s q), ball y Ξ΅ := (hs q).2 (mem_univ _), rcases mem_Unionβ‚‚.1 this with ⟨y, ys, hy⟩, let i : β„• := E q ⟨y, ys⟩, let hi := ((E q) ⟨y, ys⟩).is_lt, have ihi_eq : (⟨i, hi⟩ : fin (N q)) = (E q) ⟨y, ys⟩, by rw [fin.ext_iff, fin.coe_mk], have hiq : i < N q := hi, have hip : i < N p, { rwa Npq.symm at hiq }, let z := (E p).symm ⟨i, hip⟩, use z, have C1 : (E p) z = ⟨i, hip⟩ := (E p).apply_symm_apply ⟨i, hip⟩, have C2 : fin.cast Npq ⟨i, hip⟩ = ⟨i, hi⟩ := rfl, have C3 : (E q).symm ⟨i, hi⟩ = ⟨y, ys⟩, by { rw ihi_eq, exact (E q).symm_apply_apply ⟨y, ys⟩ }, have : Ξ¦ z = y := by { simp only [Ξ¦, Ξ¨], rw [C1, C2, C3], refl }, rw this, exact le_of_lt hy }, show βˆ€ x y : s p, |dist x y - dist (Ξ¦ x) (Ξ¦ y)| ≀ Ξ΅, { /- the distance between `x` and `y` is encoded in `F p`, and the distance between `Ξ¦ x` and `Ξ¦ y` (two points of `s q`) is encoded in `F q`, all this up to `Ξ΅`. As `F p = F q`, the distances are almost equal. -/ assume x y, have : dist (Ξ¦ x) (Ξ¦ y) = dist (Ξ¨ x) (Ξ¨ y) := rfl, rw this, -- introduce `i`, that codes both `x` and `Ξ¦ x` in `fin (N p) = fin (N q)` let i : β„• := E p x, have hip : i < N p := ((E p) x).2, have hiq : i < N q, by rwa Npq at hip, have i' : i = ((E q) (Ξ¨ x)), by { simp [Ξ¨] }, -- introduce `j`, that codes both `y` and `Ξ¦ y` in `fin (N p) = fin (N q)` let j : β„• := E p y, have hjp : j < N p := ((E p) y).2, have hjq : j < N q, by rwa Npq at hjp, have j' : j = ((E q) (Ξ¨ y)).1, by { simp [Ξ¨] }, -- Express `dist x y` in terms of `F p` have : (F p).2 ((E p) x) ((E p) y) = floor (Ρ⁻¹ * dist x y), by simp only [F, (E p).symm_apply_apply], have Ap : (F p).2 ⟨i, hip⟩ ⟨j, hjp⟩ = floor (Ρ⁻¹ * dist x y), by { rw ← this, congr; apply (fin.ext_iff _ _).2; refl }, -- Express `dist (Ξ¦ x) (Ξ¦ y)` in terms of `F q` have : (F q).2 ((E q) (Ξ¨ x)) ((E q) (Ξ¨ y)) = floor (Ρ⁻¹ * dist (Ξ¨ x) (Ξ¨ y)), by simp only [F, (E q).symm_apply_apply], have Aq : (F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩ = floor (Ρ⁻¹ * dist (Ξ¨ x) (Ξ¨ y)), by { rw ← this, congr; apply (fin.ext_iff _ _).2; [exact i', exact j'] }, -- use the equality between `F p` and `F q` to deduce that the distances have equal -- integer parts have : (F p).2 ⟨i, hip⟩ ⟨j, hjp⟩ = (F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩, { -- we want to `subst hpq` where `hpq : F p = F q`, except that `subst` only works -- with a constant, so replace `F q` (and everything that depends on it) by a constant `f` -- then `subst` revert hiq hjq, change N q with (F q).1, generalize_hyp : F q = f at hpq ⊒, subst hpq, intros, refl }, rw [Ap, Aq] at this, -- deduce that the distances coincide up to `Ξ΅`, by a straightforward computation -- that should be automated have I := calc |Ρ⁻¹| * |dist x y - dist (Ξ¨ x) (Ξ¨ y)| = |Ρ⁻¹ * (dist x y - dist (Ξ¨ x) (Ξ¨ y))| : (abs_mul _ _).symm ... = |(Ρ⁻¹ * dist x y) - (Ρ⁻¹ * dist (Ξ¨ x) (Ξ¨ y))| : by { congr, ring } ... ≀ 1 : le_of_lt (abs_sub_lt_one_of_floor_eq_floor this), calc |dist x y - dist (Ξ¨ x) (Ξ¨ y)| = (Ξ΅ * Ρ⁻¹) * |dist x y - dist (Ξ¨ x) (Ξ¨ y)| : by rw [mul_inv_cancel (ne_of_gt Ξ΅pos), one_mul] ... = Ξ΅ * (|Ρ⁻¹| * |dist x y - dist (Ξ¨ x) (Ξ¨ y)|) : by rw [abs_of_nonneg (le_of_lt (inv_pos.2 Ξ΅pos)), mul_assoc] ... ≀ Ξ΅ * 1 : mul_le_mul_of_nonneg_left I (le_of_lt Ξ΅pos) ... = Ξ΅ : mul_one _ } }, calc dist p q = GH_dist (p.rep) (q.rep) : dist_GH_dist p q ... ≀ Ξ΅ + Ξ΅/2 + Ξ΅ : main ... = Ξ΄ : by { simp [Ξ΅], ring } end /-- Compactness criterion: a closed set of compact metric spaces is compact if the spaces have a uniformly bounded diameter, and for all `Ξ΅` the number of balls of radius `Ξ΅` required to cover the spaces is uniformly bounded. This is an equivalence, but we only prove the interesting direction that these conditions imply compactness. -/ lemma totally_bounded {t : set GH_space} {C : ℝ} {u : β„• β†’ ℝ} {K : β„• β†’ β„•} (ulim : tendsto u at_top (𝓝 0)) (hdiam : βˆ€ p ∈ t, diam (univ : set (GH_space.rep p)) ≀ C) (hcov : βˆ€ p ∈ t, βˆ€ n:β„•, βˆƒ s : set (GH_space.rep p), cardinal.mk s ≀ K n ∧ univ βŠ† ⋃x∈s, ball x (u n)) : totally_bounded t := begin /- Let `Ξ΄>0`, and `Ξ΅ = Ξ΄/5`. For each `p`, we construct a finite subset `s p` of `p`, which is `Ξ΅`-dense and has cardinality at most `K n`. Encoding the mutual distances of points in `s p`, up to `Ξ΅`, we will get a map `F` associating to `p` finitely many data, and making it possible to reconstruct `p` up to `Ξ΅`. This is enough to prove total boundedness. -/ refine metric.totally_bounded_of_finite_discretization (Ξ» Ξ΄ Ξ΄pos, _), let Ξ΅ := (1/5) * Ξ΄, have Ξ΅pos : 0 < Ξ΅ := mul_pos (by norm_num) Ξ΄pos, -- choose `n` for which `u n < Ξ΅` rcases metric.tendsto_at_top.1 ulim Ξ΅ Ξ΅pos with ⟨n, hn⟩, have u_le_Ξ΅ : u n ≀ Ξ΅, { have := hn n le_rfl, simp only [real.dist_eq, add_zero, sub_eq_add_neg, neg_zero] at this, exact le_of_lt (lt_of_le_of_lt (le_abs_self _) this) }, -- construct a finite subset `s p` of `p` which is `Ξ΅`-dense and has cardinal `≀ K n` have : βˆ€ p:GH_space, βˆƒ s : set (p.rep), βˆƒ N ≀ K n, βˆƒ E : equiv s (fin N), p ∈ t β†’ univ βŠ† ⋃x∈s, ball x (u n), { assume p, by_cases hp : p βˆ‰ t, { have : nonempty (equiv (βˆ… : set (p.rep)) (fin 0)), { rw ← fintype.card_eq, simp }, use [βˆ…, 0, bot_le, choice (this)] }, { rcases hcov _ (set.not_not_mem.1 hp) n with ⟨s, ⟨scard, scover⟩⟩, rcases cardinal.lt_omega.1 (lt_of_le_of_lt scard (cardinal.nat_lt_omega _)) with ⟨N, hN⟩, rw [hN, cardinal.nat_cast_le] at scard, have : cardinal.mk s = cardinal.mk (fin N), by rw [hN, cardinal.mk_fin], cases quotient.exact this with E, use [s, N, scard, E], simp [hp, scover] } }, choose s N hN E hs using this, -- Define a function `F` taking values in a finite type and associating to `p` enough data -- to reconstruct it up to `Ξ΅`, namely the (discretized) distances between elements of `s p`. let M := ⌊Ρ⁻¹ * max C 0βŒ‹β‚Š, let F : GH_space β†’ (Ξ£k:fin ((K n).succ), (fin k β†’ fin k β†’ fin (M.succ))) := Ξ» p, ⟨⟨N p, lt_of_le_of_lt (hN p) (nat.lt_succ_self _)⟩, Ξ» a b, ⟨min M ⌊Ρ⁻¹ * dist ((E p).symm a) ((E p).symm b)βŒ‹β‚Š, ( min_le_left _ _).trans_lt (nat.lt_succ_self _) ⟩ ⟩, refine ⟨_, _, (Ξ» p, F p), _⟩, apply_instance, -- It remains to show that if `F p = F q`, then `p` and `q` are `Ξ΅`-close rintros ⟨p, pt⟩ ⟨q, qt⟩ hpq, have Npq : N p = N q := (fin.ext_iff _ _).1 (sigma.mk.inj_iff.1 hpq).1, let Ξ¨ : s p β†’ s q := Ξ» x, (E q).symm (fin.cast Npq ((E p) x)), let Ξ¦ : s p β†’ q.rep := Ξ» x, Ξ¨ x, have main : GH_dist (p.rep) (q.rep) ≀ Ξ΅ + Ξ΅/2 + Ξ΅, { -- to prove the main inequality, argue that `s p` is `Ξ΅`-dense in `p`, and `s q` is `Ξ΅`-dense -- in `q`, and `s p` and `s q` are almost isometric. Then closeness follows -- from `GH_dist_le_of_approx_subsets` refine GH_dist_le_of_approx_subsets Ξ¦ _ _ _, show βˆ€ x : p.rep, βˆƒ (y : p.rep) (H : y ∈ s p), dist x y ≀ Ξ΅, { -- by construction, `s p` is `Ξ΅`-dense assume x, have : x ∈ ⋃y∈(s p), ball y (u n) := (hs p pt) (mem_univ _), rcases mem_Unionβ‚‚.1 this with ⟨y, ys, hy⟩, exact ⟨y, ys, le_trans (le_of_lt hy) u_le_Ρ⟩ }, show βˆ€ x : q.rep, βˆƒ (z : s p), dist x (Ξ¦ z) ≀ Ξ΅, { -- by construction, `s q` is `Ξ΅`-dense, and it is the range of `Ξ¦` assume x, have : x ∈ ⋃y∈(s q), ball y (u n) := (hs q qt) (mem_univ _), rcases mem_Unionβ‚‚.1 this with ⟨y, ys, hy⟩, let i : β„• := E q ⟨y, ys⟩, let hi := ((E q) ⟨y, ys⟩).2, have ihi_eq : (⟨i, hi⟩ : fin (N q)) = (E q) ⟨y, ys⟩, by rw [fin.ext_iff, fin.coe_mk], have hiq : i < N q := hi, have hip : i < N p, { rwa Npq.symm at hiq }, let z := (E p).symm ⟨i, hip⟩, use z, have C1 : (E p) z = ⟨i, hip⟩ := (E p).apply_symm_apply ⟨i, hip⟩, have C2 : fin.cast Npq ⟨i, hip⟩ = ⟨i, hi⟩ := rfl, have C3 : (E q).symm ⟨i, hi⟩ = ⟨y, ys⟩, by { rw ihi_eq, exact (E q).symm_apply_apply ⟨y, ys⟩ }, have : Ξ¦ z = y := by { simp only [Ξ¦, Ξ¨], rw [C1, C2, C3], refl }, rw this, exact le_trans (le_of_lt hy) u_le_Ξ΅ }, show βˆ€ x y : s p, |dist x y - dist (Ξ¦ x) (Ξ¦ y)| ≀ Ξ΅, { /- the distance between `x` and `y` is encoded in `F p`, and the distance between `Ξ¦ x` and `Ξ¦ y` (two points of `s q`) is encoded in `F q`, all this up to `Ξ΅`. As `F p = F q`, the distances are almost equal. -/ assume x y, have : dist (Ξ¦ x) (Ξ¦ y) = dist (Ξ¨ x) (Ξ¨ y) := rfl, rw this, -- introduce `i`, that codes both `x` and `Ξ¦ x` in `fin (N p) = fin (N q)` let i : β„• := E p x, have hip : i < N p := ((E p) x).2, have hiq : i < N q, by rwa Npq at hip, have i' : i = ((E q) (Ξ¨ x)), by { simp [Ξ¨] }, -- introduce `j`, that codes both `y` and `Ξ¦ y` in `fin (N p) = fin (N q)` let j : β„• := E p y, have hjp : j < N p := ((E p) y).2, have hjq : j < N q, by rwa Npq at hjp, have j' : j = ((E q) (Ξ¨ y)), by { simp [Ξ¨] }, -- Express `dist x y` in terms of `F p` have Ap : ((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = ⌊Ρ⁻¹ * dist x yβŒ‹β‚Š := calc ((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = ((F p).2 ((E p) x) ((E p) y)).1 : by { congr; apply (fin.ext_iff _ _).2; refl } ... = min M ⌊Ρ⁻¹ * dist x yβŒ‹β‚Š : by simp only [F, (E p).symm_apply_apply] ... = ⌊Ρ⁻¹ * dist x yβŒ‹β‚Š : begin refine min_eq_right (nat.floor_mono _), refine mul_le_mul_of_nonneg_left (le_trans _ (le_max_left _ _)) ((inv_pos.2 Ξ΅pos).le), change dist (x : p.rep) y ≀ C, refine le_trans (dist_le_diam_of_mem compact_univ.bounded (mem_univ _) (mem_univ _)) _, exact hdiam p pt end, -- Express `dist (Ξ¦ x) (Ξ¦ y)` in terms of `F q` have Aq : ((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1 = ⌊Ρ⁻¹ * dist (Ξ¨ x) (Ξ¨ y)βŒ‹β‚Š := calc ((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1 = ((F q).2 ((E q) (Ξ¨ x)) ((E q) (Ξ¨ y))).1 : by { congr; apply (fin.ext_iff _ _).2; [exact i', exact j'] } ... = min M ⌊Ρ⁻¹ * dist (Ξ¨ x) (Ξ¨ y)βŒ‹β‚Š : by simp only [F, (E q).symm_apply_apply] ... = ⌊Ρ⁻¹ * dist (Ξ¨ x) (Ξ¨ y)βŒ‹β‚Š : begin refine min_eq_right (nat.floor_mono _), refine mul_le_mul_of_nonneg_left (le_trans _ (le_max_left _ _)) ((inv_pos.2 Ξ΅pos).le), change dist (Ξ¨ x : q.rep) (Ξ¨ y) ≀ C, refine le_trans (dist_le_diam_of_mem compact_univ.bounded (mem_univ _) (mem_univ _)) _, exact hdiam q qt end, -- use the equality between `F p` and `F q` to deduce that the distances have equal -- integer parts have : ((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = ((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1, { -- we want to `subst hpq` where `hpq : F p = F q`, except that `subst` only works -- with a constant, so replace `F q` (and everything that depends on it) by a constant `f` -- then `subst` revert hiq hjq, change N q with (F q).1, generalize_hyp : F q = f at hpq ⊒, subst hpq, intros, refl }, have : ⌊Ρ⁻¹ * dist x yβŒ‹ = ⌊Ρ⁻¹ * dist (Ξ¨ x) (Ξ¨ y)βŒ‹, { rw [Ap, Aq] at this, have D : 0 ≀ ⌊Ρ⁻¹ * dist x yβŒ‹ := floor_nonneg.2 (mul_nonneg (le_of_lt (inv_pos.2 Ξ΅pos)) dist_nonneg), have D' : 0 ≀ ⌊Ρ⁻¹ * dist (Ξ¨ x) (Ξ¨ y)βŒ‹ := floor_nonneg.2 (mul_nonneg (le_of_lt (inv_pos.2 Ξ΅pos)) dist_nonneg), rw [← int.to_nat_of_nonneg D, ← int.to_nat_of_nonneg D', int.floor_to_nat,int.floor_to_nat, this] }, -- deduce that the distances coincide up to `Ξ΅`, by a straightforward computation -- that should be automated have I := calc |Ρ⁻¹| * |dist x y - dist (Ξ¨ x) (Ξ¨ y)| = |Ρ⁻¹ * (dist x y - dist (Ξ¨ x) (Ξ¨ y))| : (abs_mul _ _).symm ... = |(Ρ⁻¹ * dist x y) - (Ρ⁻¹ * dist (Ξ¨ x) (Ξ¨ y))| : by { congr, ring } ... ≀ 1 : le_of_lt (abs_sub_lt_one_of_floor_eq_floor this), calc |dist x y - dist (Ξ¨ x) (Ξ¨ y)| = (Ξ΅ * Ρ⁻¹) * |dist x y - dist (Ξ¨ x) (Ξ¨ y)| : by rw [mul_inv_cancel (ne_of_gt Ξ΅pos), one_mul] ... = Ξ΅ * (|Ρ⁻¹| * |dist x y - dist (Ξ¨ x) (Ξ¨ y)|) : by rw [abs_of_nonneg (le_of_lt (inv_pos.2 Ξ΅pos)), mul_assoc] ... ≀ Ξ΅ * 1 : mul_le_mul_of_nonneg_left I (le_of_lt Ξ΅pos) ... = Ξ΅ : mul_one _ } }, calc dist p q = GH_dist (p.rep) (q.rep) : dist_GH_dist p q ... ≀ Ξ΅ + Ξ΅/2 + Ξ΅ : main ... = Ξ΄/2 : by { simp [Ξ΅], ring } ... < Ξ΄ : half_lt_self Ξ΄pos end section complete /- We will show that a sequence `u n` of compact metric spaces satisfying `dist (u n) (u (n+1)) < 1/2^n` converges, which implies completeness of the Gromov-Hausdorff space. We need to exhibit the limiting compact metric space. For this, start from a sequence `X n` of representatives of `u n`, and glue in an optimal way `X n` to `X (n+1)` for all `n`, in a common metric space. Formally, this is done as follows. Start from `Y 0 = X 0`. Then, glue `X 0` to `X 1` in an optimal way, yielding a space `Y 1` (with an embedding of `X 1`). Then, consider an optimal gluing of `X 1` and `X 2`, and glue it to `Y 1` along their common subspace `X 1`. This gives a new space `Y 2`, with an embedding of `X 2`. Go on, to obtain a sequence of spaces `Y n`. Let `Z0` be the inductive limit of the `Y n`, and finally let `Z` be the completion of `Z0`. The images `X2 n` of `X n` in `Z` are at Hausdorff distance `< 1/2^n` by construction, hence they form a Cauchy sequence for the Hausdorff distance. By completeness (of `Z`, and therefore of its set of nonempty compact subsets), they converge to a limit `L`. This is the nonempty compact metric space we are looking for. -/ variables (X : β„• β†’ Type) [βˆ€ n, metric_space (X n)] [βˆ€ n, compact_space (X n)] [βˆ€ n, nonempty (X n)] /-- Auxiliary structure used to glue metric spaces below, recording an isometric embedding of a type `A` in another metric space. -/ structure aux_gluing_struct (A : Type) [metric_space A] : Type 1 := (space : Type) (metric : metric_space space) (embed : A β†’ space) (isom : isometry embed) instance (A : Type) [metric_space A] : inhabited (aux_gluing_struct A) := ⟨{ space := A, metric := by apply_instance, embed := id, isom := Ξ» x y, rfl }⟩ /-- Auxiliary sequence of metric spaces, containing copies of `X 0`, ..., `X n`, where each `X i` is glued to `X (i+1)` in an optimal way. The space at step `n+1` is obtained from the space at step `n` by adding `X (n+1)`, glued in an optimal way to the `X n` already sitting there. -/ def aux_gluing (n : β„•) : aux_gluing_struct (X n) := nat.rec_on n { space := X 0, metric := by apply_instance, embed := id, isom := Ξ» x y, rfl } (Ξ» n Y, by letI : metric_space Y.space := Y.metric; exact { space := glue_space Y.isom (isometry_optimal_GH_injl (X n) (X (n+1))), metric := by apply_instance, embed := (to_glue_r Y.isom (isometry_optimal_GH_injl (X n) (X (n+1)))) ∘ (optimal_GH_injr (X n) (X (n+1))), isom := (to_glue_r_isometry _ _).comp (isometry_optimal_GH_injr (X n) (X (n+1))) }) /-- The Gromov-Hausdorff space is complete. -/ instance : complete_space GH_space := begin have : βˆ€ (n : β„•), 0 < ((1:ℝ) / 2) ^ n, by { apply pow_pos, norm_num }, -- start from a sequence of nonempty compact metric spaces within distance `1/2^n` of each other refine metric.complete_of_convergent_controlled_sequences (Ξ» n, (1/2)^n) this (Ξ» u hu, _), -- `X n` is a representative of `u n` let X := Ξ» n, (u n).rep, -- glue them together successively in an optimal way, getting a sequence of metric spaces `Y n` let Y := aux_gluing X, letI : βˆ€ n, metric_space (Y n).space := Ξ» n, (Y n).metric, have E : βˆ€ n : β„•, glue_space (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ)) = (Y n.succ).space := Ξ» n, by { simp [Y, aux_gluing], refl }, let c := Ξ» n, cast (E n), have ic : βˆ€ n, isometry (c n) := Ξ» n x y, rfl, -- there is a canonical embedding of `Y n` in `Y (n+1)`, by construction let f : Ξ n, (Y n).space β†’ (Y n.succ).space := Ξ» n, (c n) ∘ (to_glue_l (aux_gluing X n).isom (isometry_optimal_GH_injl (X n) (X n.succ))), have I : βˆ€ n, isometry (f n), { assume n, apply isometry.comp, { assume x y, refl }, { apply to_glue_l_isometry } }, -- consider the inductive limit `Z0` of the `Y n`, and then its completion `Z` let Z0 := metric.inductive_limit I, let Z := uniform_space.completion Z0, let Ξ¦ := to_inductive_limit I, let coeZ := (coe : Z0 β†’ Z), -- let `X2 n` be the image of `X n` in the space `Z` let X2 := Ξ» n, range (coeZ ∘ (Ξ¦ n) ∘ (Y n).embed), have isom : βˆ€ n, isometry (coeZ ∘ (Ξ¦ n) ∘ (Y n).embed), { assume n, apply isometry.comp completion.coe_isometry _, apply isometry.comp _ (Y n).isom, apply to_inductive_limit_isometry }, -- The Hausdorff distance of `X2 n` and `X2 (n+1)` is by construction the distance between -- `u n` and `u (n+1)`, therefore bounded by `1/2^n` have D2 : βˆ€ n, Hausdorff_dist (X2 n) (X2 n.succ) < (1/2)^n, { assume n, have X2n : X2 n = range ((coeZ ∘ (Ξ¦ n.succ) ∘ (c n) ∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ)))) ∘ (optimal_GH_injl (X n) (X n.succ))), { change X2 n = range (coeZ ∘ (Ξ¦ n.succ) ∘ (c n) ∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ))) ∘ (optimal_GH_injl (X n) (X n.succ))), simp only [X2, Ξ¦], rw [← to_inductive_limit_commute I], simp only [f], rw ← to_glue_commute }, rw range_comp at X2n, have X2nsucc : X2 n.succ = range ((coeZ ∘ (Ξ¦ n.succ) ∘ (c n) ∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ)))) ∘ (optimal_GH_injr (X n) (X n.succ))), by refl, rw range_comp at X2nsucc, rw [X2n, X2nsucc, Hausdorff_dist_image, Hausdorff_dist_optimal, ← dist_GH_dist], { exact hu n n n.succ (le_refl n) (le_succ n) }, { apply isometry.comp completion.coe_isometry _, apply isometry.comp _ ((ic n).comp (to_glue_r_isometry _ _)), apply to_inductive_limit_isometry } }, -- consider `X2 n` as a member `X3 n` of the type of nonempty compact subsets of `Z`, which -- is a metric space let X3 : β„• β†’ nonempty_compacts Z := Ξ» n, ⟨X2 n, ⟨range_nonempty _, is_compact_range (isom n).continuous ⟩⟩, -- `X3 n` is a Cauchy sequence by construction, as the successive distances are -- bounded by `(1/2)^n` have : cauchy_seq X3, { refine cauchy_seq_of_le_geometric (1/2) 1 (by norm_num) (Ξ» n, _), rw one_mul, exact le_of_lt (D2 n) }, -- therefore, it converges to a limit `L` rcases cauchy_seq_tendsto_of_complete this with ⟨L, hL⟩, -- the images of `X3 n` in the Gromov-Hausdorff space converge to the image of `L` have M : tendsto (Ξ» n, (X3 n).to_GH_space) at_top (𝓝 L.to_GH_space) := tendsto.comp (to_GH_space_continuous.tendsto _) hL, -- By construction, the image of `X3 n` in the Gromov-Hausdorff space is `u n`. have : βˆ€ n, (X3 n).to_GH_space = u n, { assume n, rw [nonempty_compacts.to_GH_space, ← (u n).to_GH_space_rep, to_GH_space_eq_to_GH_space_iff_isometric], constructor, convert (isom n).isometric_on_range.symm, }, -- Finally, we have proved the convergence of `u n` exact ⟨L.to_GH_space, by simpa [this] using M⟩ end end complete--section end Gromov_Hausdorff --namespace
/* specfunc/legendre_P.c * * Copyright (C) 2009-2013 Patrick Alken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_sf_legendre.h> /* * The routines in this module compute associated Legendre functions * (ALFs) up to order and degree 2700, using the method described * in * * [1] S. A. Holmes and W. E. Featherstone, A unified approach * to the Clenshaw summation and the recursive computation of very * high degree and order normalised associated Legendre functions, * Journal of Geodesy, 76, pg. 279-299, 2002. * * Further information on ALFs can be found in * * [2] Abramowitz and Stegun, Handbook of Mathematical Functions, * Chapter 8, 1972. */ static void legendre_sqrts(const size_t lmax, double *array); #define LEGENDRE #include "legendre_source.c" #undef LEGENDRE #define LEGENDRE_DERIV #include "legendre_source.c" #undef LEGENDRE_DERIV #define LEGENDRE_DERIV_ALT #include "legendre_source.c" #undef LEGENDRE_DERIV_ALT #define LEGENDRE_DERIV2 #include "legendre_source.c" #undef LEGENDRE_DERIV2 #define LEGENDRE_DERIV2_ALT #include "legendre_source.c" #undef LEGENDRE_DERIV2_ALT /* number of P_{lm} functions for a given lmax */ size_t gsl_sf_legendre_nlm(const size_t lmax) { return ((lmax + 1) * (lmax + 2) / 2); } /* gsl_sf_legendre_array_n() This routine returns the minimum result_array[] size needed for a given lmax */ size_t gsl_sf_legendre_array_n(const size_t lmax) { size_t nlm = gsl_sf_legendre_nlm(lmax); size_t nsqrt = 2 * lmax + 2; /* extra room to precompute sqrt factors */ return (nlm + nsqrt); } /* gsl_sf_legendre_array_n() */ /* gsl_sf_legendre_array_index() This routine computes the index into a result_array[] corresponding to a given (l,m) */ size_t gsl_sf_legendre_array_index(const size_t l, const size_t m) { return (l * (l + 1) / 2 + m); } /* gsl_sf_legendre_array_index() */ /********************************************************* * INTERNAL ROUTINES * *********************************************************/ /* legendre_sqrts() Precompute square root factors needed for Legendre recurrence. On output, array[i] = sqrt(i) */ static void legendre_sqrts(const size_t lmax, double *array) { size_t l; for (l = 0; l <= 2 * lmax + 1; ++l) array[l] = sqrt((double) l); }
/- Copyright (c) 2022 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author : Kevin Buzzard -/ import tactic -- imports all the Lean tactics /-! # Sets in Lean, example sheet 2 : "the" empty set and the "universal set". Lean notation for the empty subset of `X` is `βˆ…`. Unlike in set theory, there is more than one empty set in Lean! Every type has an empty subset, and it *doesn't make sense* to ask if `βˆ… : set β„•` and `βˆ… : set β„€` are equal, because they have different types. At the other extreme, the subset of `X` containing all the terms of type `X` is...well...mathematicians would just call it `X`, but `X` is a type not a subset. The subset of `X` consisting of every element of `X` is called `set.univ : set X`, or just `univ : set X` if we have opened the `set` namespace. Let's do that now. -/ open set /- ## Definition of βˆ… and univ `x ∈ βˆ…` is *by definition* equal to `false` and `x ∈ univ` is *by definition* equal to `true`. You can use the `change` tactic to make these changes if you like. But you don't have to. Remember that `triv` proves `true` and `cases h` will solve a goal if `h : false`. -/ -- set up variables variables (X : Type) -- Everything will be a subset of `X` (A B C D E : set X) -- A,B,C,D,E are subsets of `X` (x y z : X) -- x,y,z are elements of `X` or, more precisely, terms of type `X` open set example : x ∈ (univ : set X) := begin sorry end example : x ∈ (βˆ… : set X) β†’ false := begin sorry end example : A βŠ† univ := begin sorry end example : βˆ… βŠ† A := begin sorry end
test = forall (_Set_ : Set) β†’ Set
function outcome=getOutcomeStr(obj, verbosity) % give string indicating the outcome of the test % % outcome=getOutcomeStr(obj, verbosity) % % Inputs: % obj MOxUnitTestOutcome object % verbosity Integer in the range [0,1,2] % % Returns: % outcome: Depending on the value of verbosity % 0: '' % 1: '.' % 2: 'passed' % outcome_cell={'','.','passed'}; outcome=outcome_cell{verbosity+1};
-- https://www.codewars.com/kata/5e889a3c0f55ed0032f1879f/train/lean /- Incidence geometry in Lean, referenced from https://sites.math.washington.edu/~lee/Courses/444-2009/theorems-incidence.pdf and the lecture notes for MATH 4221 (not publicly available on the Internet) -/ -- Undefined terms and axioms of incidence geometry -- In incidence geometry, there are 3 undefined terms: -- - Point -- - Line -- - "Incident with"/"lies on", e.g. point P is incident with / lies on line l -- And there are 3 axioms: -- - I₁: For every pair of distinct points P and Q there is exactly 1 line l such -- that P and Q lie on l -- - Iβ‚‚: For every line l there exist at least two distinct points P and Q such -- that both P and Q lie on l -- - I₃: There exist three points that do not all lie on any one line -- Note that the three points in I₃ are implicitly assumed to be distinct, because -- otherwise one could construct a trivial model with only one point and no lines -- that trivially satisfies the axioms, which is uninteresting, and some of the -- theorems stated below do not hold in the trivial model import tactic class incidence (point line : Type) (incident_with : point β†’ line β†’ Prop) := (I₁ : βˆ€ P Q, P β‰  Q β†’ βˆƒ! l, incident_with P l ∧ incident_with Q l) (Iβ‚‚ : βˆ€ l, βˆƒ P Q, P β‰  Q ∧ incident_with P l ∧ incident_with Q l) (I₃ : βˆƒ P Q R, P β‰  Q ∧ Q β‰  R ∧ P β‰  R ∧ βˆ€ l, Β¬(incident_with P l ∧ incident_with Q l ∧ incident_with R l)) theorem thm_3p6p2 (point line : Type) (incident_with : point β†’ line β†’ Prop) [incidence point line incident_with] (l : line) : βˆƒ P, Β¬incident_with P l := begin -- from _inst_1.I₃ extract three points P, Q, R, -- the proofs of distinctness hPQ, hQR, hPR, -- and the proof of incidence hl of P, Q, R on l rcases _inst_1.I₃ with ⟨ P, Q, R, hPQ, hQR, hPR, hl⟩, specialize hl l, push_neg at hl, by_cases hpl: (incident_with P l), by_cases hql: (incident_with Q l), -- both P and Q lie on l show βˆƒ (P : point), Β¬incident_with P l, use R, exact hl hpl hql, -- P lies on l but Q does not lie on l show βˆƒ (P : point), Β¬incident_with P l, use Q, -- P does not lie on l show βˆƒ (P : point), Β¬incident_with P l, use P, end
Formal statement is: lemma scale_measure_0[simp]: "scale_measure 0 M = null_measure M" Informal statement is: If you scale a measure by 0, you get the null measure.
lemma emeasure_gfp[consumes 1, case_names cont measurable]: assumes sets[simp]: "\<And>s. sets (M s) = sets N" assumes "\<And>s. finite_measure (M s)" assumes cont: "inf_continuous F" "inf_continuous f" assumes meas: "\<And>P. Measurable.pred N P \<Longrightarrow> Measurable.pred N (F P)" assumes iter: "\<And>P s. Measurable.pred N P \<Longrightarrow> emeasure (M s) {x\<in>space N. F P x} = f (\<lambda>s. emeasure (M s) {x\<in>space N. P x}) s" assumes bound: "\<And>P. f P \<le> f (\<lambda>s. emeasure (M s) (space (M s)))" shows "emeasure (M s) {x\<in>space N. gfp F x} = gfp f s"
# DiversificaciΓ³n y fuentes de riesgo en un portafolio I > Las dos clases pasadas vimos entonces como medir el rendimiento esperado y la volatilidad (varianza) de un portafolio conociendo los rendimientos esperados, las volatilidades (varianzas), y covarianzas (correlaciones) entre sΓ­, de los activos individuales. > **Aspecto clave:** incluso cuando los activos individuales son riesgosos, mientras haya cierta falta de paralelismo de su suerte en la economΓ­a, combinarlos en un portafolio crea **diversificaciΓ³n** y reduce el riesgo. > En tΓ©rminos coloquiales, "*no poner todo el blanquillo en una sola canasta*" ("don't put all your eggs in a single basket"). > ΒΏCΓ³mo medir la falta de paralelismo? $\Rightarrow$ **CorrelaciΓ³n**. **Objetivos:** - ΒΏPorquΓ© la diversificaciΓ³n reduce el riesgo? - ΒΏQuΓ© es riesgo sistemΓ‘tico? - ΒΏQuΓ© es riesgo idiosincrΓ‘tico (no sistemΓ‘tico)? *Referencia:* - Notas del curso "Portfolio Selection and Risk Management", Rice University, disponible en Coursera. ___ ## 1. DiversificaciΓ³n y riesgo en un portafolio. ### 1.1. Efecto de la correlaciΓ³n en un portafolio con dos activos. Revisemos la siguiente situaciΓ³n: 1. Supongamos que dos activos se mueven exactamente en tΓ‘ndem. - ΒΏConstruir un portafolio con dichos activos reducirΓ­a el riesgo? - Su coeficiente de correlaciΓ³n es $\rho=+1.0$, y no habrΓ­a beneficio de diversificaciΓ³n. 2. Ahora, tΓ­picamente esto no es posible. Los rendimientos de dos compaΓ±Γ­as distintas no se mueven exactamente igual. - Esto nos provee mucho portencial para diversificar el riesgo poniendo dos activos distintos en un portafolio. - Y, ahora, la buena noticia: la correlaciΓ³n entre dos activos no tiene que ser necesariamente negativa para poder reducir el riesgo mediante diversificaciΓ³n. | Coeficiente de correlaciΓ³n | Efecto en la diversificaciΓ³n | | -------------------------- | -------------------------------------- | | +1.0 | No es posible reducir riesgo | | +0.5 | ReducciΓ³n de riesgo moderada | | 0 | ReducciΓ³n de riesgo considerable | | -0.5 | Casi todo el riesgo puede ser eliminado| | -1.0 | Todo el riesgo puede ser eliminado | ### 1.2 IlustraciΓ³n grΓ‘fica con dos activos. #### <font color = blue> Ver en el tablero... </font> - Supongamos que tenemos dos activos: $A$ y $B$. - Vamos a graficar en el espacio de rendimiento esperado $E[r]$, en el eje de las ordenadas (eje $y$), contra volatilidad $\sigma$, en el eje de las abscisas (eje $x$). - El punto etiquetado con $A$, representa la combinaciΓ³n riesgo-rendimiento que obtendrΓ­amos si invirtiΓ©ramos $100\%$ de nuestra riqueza en el activo $A$. - El punto etiquetado con $B$, representa la combinaciΓ³n riesgo-rendimiento que obtendrΓ­amos si invirtiΓ©ramos $100\%$ de nuestra riqueza en el activo $B$. **Discutir el posicionamiento de los puntos $A$ y $B$**. - ΒΏQuΓ© pasa si combinamos estos activos en un portafolio? 1. Empezamos suponiendo que los rendimientos de $A$ y $B$ estΓ‘n perfectamente correlacionados: <font color = blue> $\rho_{AB}=+1$ </font>. - ΒΏCuΓ‘les son las combinaciones riesgo/rendimiento que obtenemos combinando $A$ y $B$ en un portafolio? - SΓ³lo en este caso, tanto rendimiento como riesgo son el promedio ponderado de los activos individuales. - LΓ­nea recta: No diversificaciΓ³n. 2. Ahora, ΒΏquΓ© pasa si los rendimientos de $A$ y $B$ no negativamente perfectamente correlacionados?: <font color = green> $\rho_{AB}=-1$ </font>. - ΒΏCuΓ‘les son las combinaciones riesgo/rendimiento que obtenemos combinando $A$ y $B$ en un portafolio? 3. Por ΓΊltimo, ΒΏquΓ© pasa si los rendimientos de $A$ y $B$ no estΓ‘n perfectamente correlacionados?: <font color = red> $-1<\rho_{AB}<+1$ </font>. - ΒΏCuΓ‘les son las combinaciones riesgo/rendimiento que obtenemos combinando $A$ y $B$ en un portafolio? - Notar que mientras los rendimientos se siguen calculando igual, el riesgo es menor que en el primer caso. Comparar. ### 1.3. IlustraciΓ³n grΓ‘fica con tres activos. #### <font color = blue> Ver en el tablero... </font> - Supongamos que tenemos tres activos: $A$, $B$ y $C$. - Supongamos que las correlaciones entre cada par de activos son imperfectas: $-1<\rho_{ij}<+1$. - Podemos armar portafolios entre cada par de activos (dibujar). - Luego, podrΓ­amos pensar un portafolio con los tres activos, como una combinaciΓ³n de un portafolio de dos activos (por ejemplo, $A$ y $B$) con el activo restante (ejemplo, $C$). - ΒΏQuΓ© se obtiene? **ConclusiΓ³n.** Combinar mΓ‘s activos abre mΓ‘s posibilidades a la diversificaciΓ³n del riesgo. ___ ## 2. DiversificaciΓ³n: riesgo sistemΓ‘tico y riesgo idiosincrΓ‘tico. En la clase pasada vimos que si tenemos $n$ activos en un portafolio, el riesgo del portafolio (medido con la varianza) se puede calcular a partir de los riesgos individuales y movimientos relativos par a par como: \begin{align} \sigma_p^2 &=\sum_{i=1}^{n}\sum_{k=1}^{n}w_iw_k\sigma_{ik}\\ &=\sum_{i=1}^{n}w_i^2\sigma_{ii}+\sum_{i=1}^{n}\sum_{k=1, k\neq i}^{n}w_iw_k\sigma_{ik}\\ &=\sum_{i=1}^{n}w_i^2\sigma_{i}^2+\sum_{i=1}^{n}\sum_{k=1, k\neq i}^{n}w_iw_k\sigma_{ik}. \end{align} - Los primeros son los tΓ©rminos de varianza individual de cada activo: $n$ tΓ©rminos. - Los segundos son los tΓ©rminos de covarianza entre pares de activos: $n(n-1)$ tΓ©rminos. - Cuando $n$ crece, la importancia relativa de los tΓ©rminos de varianza es menor a la de los tΓ©rminos de covarianza. ___ **Ejercicio para ilustrar este punto.** Suponga que se forma un portafolio con las siguientes condiciones: 1. Se combinan $n$ activos en el portafolio. 2. Todos los activos tienen la misma varianza. Esto es, $\sigma_i^2=\sigma^2$ para $i=1,2,\dots,n$. 3. La covarianza entre cada par de activos es la misma. Esto es, $\sigma_{ij}=\lambda$ para $i,j=1,2,\dots,n$, con $i\neq j$. 4. La participaciΓ³n de cada activo en el portafolio es igual. Es decir, $w_i=\frac{1}{n}$ para $i=1,2,\dots,n$. ΒΏA quΓ© es igual la varianza del portafolio cuando el nΓΊmero de activos es muy grande? *Pista:* reemplazar en la fΓ³rmula de arriba y tomar el lΓ­mite cuando $n\to\infty$. *RecomendaciΓ³n:* hΓ‘ganlo que va a venir en el prΓ³ximo quiz. ___ **Entonces tenemos dos fuentes de riesgo en un portafolio:** 1. Riesgo sistemΓ‘tico: - Es un hecho que todos los activos se ven afectados econΓ³micamente por factores comunes. - Ejemplo: si hay una recesiΓ³n, la gente se encontrarΓ­a desempleada, lo que afectarΓ­a a la mayorΓ­a de los negocios al mismo tiempo. - Esto es lo que llamamos **riesgo sistemΓ‘tico**, o **riesgo de mercado**. 2. Riesgo idiosincrΓ‘tico - La otra fuente de riesgo en un portafolio es llamada **riesgo idiosincrΓ‘tico**, o **riesgo especΓ­fico de firma**, o **riesgo ΓΊnico**, o **riesgo no sistemΓ‘tico**. - Esta fuente de riesgo afecta a cada activo en particular por razones especΓ­ficas. - Por definiciΓ³n, este tipo de riesgo especΓ­fico, no estΓ‘ relacionado con otros activos. - Entonces cuando combinamos activos en un portafolio, el riesgo idiosincrΓ‘tico tiende a eliminarse. Sin embargo, hay un lΓ­mite en *cuanta* diversificaciΓ³n podemos alcanzar. Claro, - siempre podemos diversificar el riesgo no sistemΓ‘tico con un portafolio con muchos activos y bien diversificado, - pero no nos podemos deshacer del riesgo sistemΓ‘tico, porque afecta a todo. *En un portafolio correctamente diversificado, el ΓΊnico riesgo al que estamos sujetos es al riesgo que no podemos diversificar: riesgo sistemΓ‘tico*. Imagen tomada de: Makiel, R. *A Random Walk Down Wall Street*, 2012. Entonces, con todo lo anterior, **ΒΏporquΓ© diversificar?** - para disminuir el riesgo. - ΒΏporquΓ© usar casco?, ΒΏporquΓ© usar cinturΓ³n de seguridad cuando voy en el coche? ___ # Anuncios parroquiales ## 1. Cuadrar fecha de examen mΓ³dulos 1 y 2. Lunes 8 de Marzo. ## 2. [ArtΓ­culo interesante](https://www.economist.com/buttonwoods-notebook/2012/02/23/globalisation-and-diversification). <footer id="attribution" style="float:right; color:#808080; background:#fff;"> Created with Jupyter by Esteban JimΓ©nez RodrΓ­guez. </footer>
\documentclass[a4paper]{article} \title{Something} \author{Some SCer} \date{Tomorrow} \begin{document} \maketitle %------------------- \section{Conclusions} Read the {\LaTeX} Bible~\cite{Lamport:LDP86}. No, \emph{not} the {\TeX} Bible~\cite{Knuth:TB84}. %------------------- \bibliographystyle{scplain} \bibliography{texbook1}% installed in TeX Live %------------------- \end{document}
install.packages("shiny", dependencies=TRUE) install.packages("magrittr",dependencies=TRUE) install.packages("highcharter",dependencies=TRUE)
%==================================================================================== \section{How to prepare initial and boundary data} \label{sec:adv_datainput} %==================================================================================== \begin{table}[tbh] \begin{center} \caption{External input data supported in \scalelib} \begin{tabularx}{150mm}{l|l|X} \hline \rowcolor[gray]{0.9} Data type & \verb|FILETYPE_ORG| & Note \\ \hline SCALE format & \verb|SCALE-RM| & History and restart files are supported. The latitude-longitude catalog is needed. \\ \hline Binary format & \verb|GrADS| & Another namelist for data input is required. \\ \hline WRF format & \verb|WRF-ARW| & Both ``wrfout'' and``wrfrst'' are supported.\\ \hline \end{tabularx} \label{tab:inputdata_format} \end{center} \end{table} The program \verb|scale-rm_init| converts external data into boundary and initial data by using the configuration file \verb|init.conf|. It can treat various types of external data as shown in Table \ref{tab:inputdata_format}. The format of input data is specified by \nmitem{FILETYPE_ORG} in \namelist{PARAM_MKINIT_REAL_(ATMOS|OCEAN|LAND)}. The ``SCALE format'' is mainly used for offline nesting experiments (Sec. \ref{subsec:nest_offline}). The ``Binary format'' is defined as binary format with single-precision floating point values that FORTRAN can directly access. The example of practical usage of binary format data is described in Sec. \ref{sec:tutorial_real_data}. The ``WRF data format'' is available; WRF model output data can be read directly. Note that the file should contain all data required to generate the boundary data for \scalerm. Other format data, such as GRIB/GRIB2 data, can be read in \scale by converting the data to the binary format data. Note that the format of output files in the latest version is different from that in the version 5.3 or older. Therefore, the init/boundary files which are made in the version 5.3 or older can't be used in the current version (\scalelib \version). %%%---------------------------------------------------------------------------------%%%% \subsubsection{Settings common to SCALE format and Binary format} \label{sec:datainput_common_setting} %% The base name of the initial file to be output is set by \nmitem{RESTART_OUT_BASENAME} in \namelist{PARAM_RESTART} as follows: %% \editbox{ \verb|&PARAM_RESTART|\\ \verb| RESTART_OUTPUT = .false.,| ; whether initial (or restart) files is output. \\ \verb| RESTART_OUT_BASENAME = "",| ; base name of initial (or restart) files \\ \verb|/|\\ } To generate initial file, \nmitem{RESTART_OUTPUT} is set to \verb|.true.|. The base name of initial file is specified by \nmitem{RESTART_OUT_BASENAME}. For example, in the tutorial described in Sec. \ref{sec:tutorial_real_intro}, \nmitem{RESTART_OUT_BASENAME} = ``\verb|init_d01|''. These settings are used when you want to output restart files in executing \scalerm (see Sec. \ref{sec:restart} for details). The structure of generated restart files is same as that of initial files. The settings for input data and boundary files are specified by \namelist{PARAM_MKINIT_REAL_(ATMOS|OCEAN|LAND)} in the file \verb|init.conf|. %% \editboxtwo{ \verb|&PARAM_MKINIT_REAL_ATMOS| & \\ \verb| NUMBER_OF_FILES = 1, | & ; Number of input files \\ \verb| NUMBER_OF_TSTEPS = 1, | & ; Number of time step for each input files \\ \verb| FILETYPE_ORG = '',| & ; Select from Table\ref{tab:inputdata_format}\\ \verb| BASENAME_ORG = '',| & ; Information about input files \\ & ~~~ (the specified value depends on \verb|FILETYPE_ORG|)\\ \verb| BASENAME_ADD_NUM = .false.,| & ; Switch to number the name of file when \verb|NUMBER_OF_FILES|=1 \\ \verb| BASENAME_BOUNDARY = '',| & ; Base name of boundary files \\ \verb| BOUNDARY_UPDATE_DT = 0.0,| & ; Time interval for input data [s]\\ \verb| USE_FILE_DENSITY = .false.,| & ; Switch to use data of density stored in input files \\ \verb| USE_NONHYDRO_DENS_BOUNDARY = .false.,| & ; Switch to use nonhydrostatic density as boundary data \\ \verb| USE_SFC_DIAGNOSES = .false.,| & ; Switch to use diagnostic variables at surface in parent model \\ \verb| USE_DATA_UNDER_SFC = .true.,| & ; Switch to use values below the surface in parent model \\ \verb| SAME_MP_TYPE = .false.,| & ; (For SCALE format) Whether the microphysics scheme is same as that used in parent model \\ \verb| INTRP_TYPE = 'LINEAR',| & ; Type of horizontal interpolation ("\verb|LINEAR|", "\verb|DIST-WEIGHT|") \\ \verb| SERIAL_PROC_READ = .true.,| & ; Whether only the master process read input data? \\ \verb|/| & \\ \verb|&PARAM_MKINIT_REAL_OCEAN| & \\ \verb| NUMBER_OF_FILES = 1, | & ; Number of input files\\ \verb| NUMBER_OF_TSTEPS = 1, | & ; Number of time steps for each input files\\ \verb| FILETYPE_ORG = '',| & ; Select from Table\ref{tab:inputdata_format}\\ \verb| BASENAME_ORG = '',| & ; Information about input file\\ & ~~~ (the specified value depends on \verb|FILETYPE_ORG|)\\ \verb| INTRP_OCEAN_SFC_TEMP = 'off',| & ; (For GrADS format) ("\verb|off|", "\verb|mask|", "\verb|fill|") \\ \verb| INTRP_OCEAN_TEMP = 'off',| & ; (For GrADS format) ("\verb|off|", "\verb|mask|", "\verb|fill|") \\ \verb| SERIAL_PROC_READ = .true.,| & ; Whether only the master process read input data? \\ \verb|/| & \\ \verb|&PARAM_MKINIT_REAL_LAND| & \\ \verb| NUMBER_OF_FILES = 1, | & ; Number of input files\\ \verb| NUMBER_OF_TSTEPS = 1, | & ; Number of time steps for each input files\\ \verb| FILETYPE_ORG = '',| & ; Select from Table\ref{tab:inputdata_format}\\ \verb| BASENAME_ORG = '',| & ; Information about input file\\ & ~~~ (the specified value depends on \verb|FILETYPE_ORG|)\\ \verb| USE_FILE_LANDWATER = .true.,| & ; Switch to use data of soil moisture stored in input file\\ \verb| INTRP_LAND_TEMP = 'off',| & ; (For GrADS format) ("\verb|off|", "\verb|mask|", "\verb|fill|") \\ \verb| INTRP_LAND_WATER = 'off',| & ; (For GrADS format) ("\verb|off|", "\verb|mask|", "\verb|fill|") \\ \verb| INTRP_LAND_SFC_TEMP = 'off',| & ; (For GrADS format) ("\verb|off|", "\verb|mask|", "\verb|fill|") \\ \verb| ELEVATION_CORRECTION = .true.,| & ; Switch to correct the difference of topography elevation from parent model \\ \verb| SERIAL_PROC_READ = .true.,| & ; Whether only the master process read input data? \\ \verb|/| & \\ } \nmitem{NUMBER_OF_FILES} is the number of input files. The program \verb|scale-rm_init| reads these files enumerated from \verb|00000| to the given number \nmitem{NUMBER_OF_FILES}-1. For the case of \nmitem{NUMBER_OF_FILES}=1 where the enumeration is not automatically performed, you should set \nmitem{BASENAME_ADD_NUM}=\verb|.true.| to enumerate the files. \nmitem{NUMBER_OF_TSTEPS} is the number of time steps stored in each input file. \nmitem{BOUNDARY_UPDATE_DT} is the time interval of input data; the time interval of boundary data is the same as that of the input data. \nmitem{BASENAME_BOUNDARY} is the base name of the output boundary files. If \nmitem{BASENAME_BOUNDARY} is not specified, no boundary files are output. For example, in the above case, the boundary file(s) are created only for the atmospheric variables; the initial file is prepared for all atmospheric, ocean, and land variables. In order to perform model integrations, the boundary data for atmospheric variables must have two time steps at least. On the other hands, whether boundary data for variables of ocean and land is necessary depends on schemes employed in executing models. \nmitem{INTRP_TYPE} is the type of horizontal interpolation; ``\verb|LINEAR|'' and ``\verb|DIST-WEIGHT|'' are available. If ``\verb|LINEAR|'' is selected, the bi-linear interpolation is used. This type can not be used when the total number of horizontal gird cells in either the x- or y-direction is 1, i.e., \nmitem{IMAXG} = 1 or \nmitem{JMAXG} = 1, such as a case of 2-dimensional experiment or an unstructured grid data which is stored in one-dimensional array in the horizontal direction. If ``\verb|DIST-WEIGHT|'' is selected, distance-weighted mean of the nearest $N$-neighbors is used. In the case of distance-weighted mean, the number of the neighbors is set by \nmitem{COMM_CARTESC_NEST_INTERP_LEVEL} in \namelist{PARAM_COMM_CARTESC_NEST}. In \scalerm, only the master process reads input data, and then broadcasts the data to each node. At this time, the algorithm may cause insufficient memory error when reading large input data, especially on a high-performance computing system. By setting \nmitem{SERIAL_PROC_READ} to \verb|.false.|, each node accesses by itself to only the data it needs, resulting in the reduction of memory usage. Note that, the computational performance may deteriorate due to locking file access because the algorithm places a load on file I/O. The above configurations except for \nmitem{BASENAME_BOUNDARY} can be shared between \verb|ATMOS| and \verb|OCEAN| (or \verb|LAND|); namely, if the items of namelist are not specified in \namelist{PARAM_MKINIT_REAL_(OCEAN|LAND)}, the values same as that in \namelist{PARAM_MKINIT_REAL_ATMOS} are used. \\ \noindent\textbf{\underline{Settings for \texttt{PARAM\_MKINIT\_REAL\_ATMOS}}} The method to calculate density is specified by \nmitem{USE_FILE_DENSITY} and \nmitem{USE_NONHYDRO_DENS_BOUNDARY}. For the default setting where both of values are \verb|.false.|, the density in initial and boundary data is calculated with hydrostatic balance, i.e., $\frac{dp}{dz}=-\rho g$ from the input data of temperature and humidity. If \nmitem{USE_FILE_DENSITY} = \verb|.true.|, the density read from the input file(s) is used as well as the other variables. Regardless of the \nmitem{USE_FILE_DENS}, if \nmitem{USE_NONHYDRO_DENS_BOUNDARY} = \verb|.true.|, the density of boundary data is calculated using the equation of state, i.e., $\rho = p/RT$ and the input temperature, pressure, and humidity data (the initial data is not affected). This density is generally consistent with that in the parent model. % The densities in the initial and boundary data become different if \nmitem{USE_FILE_DENSITY}=\verb|.false.| and \nmitem{USE_NONHYDRO_DENS_BOUNDARY} = \verb|.true.|. The reason why the option for density boundary data is provided is the following. In most cases, the density satisfying the hydrostatic balance is preferred for the initial data to reduce initial shock in the simulation. Therefore, \nmitem{USE_FILE_DENSITY}=\verb|.false.| is recommended. On the other hand, since the density constructed with the hydrostatic balance could differ from that in the parent model (or realistic value), this may cause a significant mass bias in the simulation. In such cases, in terms of representation of the simulation such as pressure field, it could be better to use consistent density with the parent's one using \nmitem{USE_NONHYDRO_DENS_BOUNDARY}=\verb|.true.|. The vertical acceleration or waves due to the use of hydrostatically inbalanced density as the boundary data is expected to be quickly dumped by the lateral nudging. \nmitem{USE_SFC_DIAGNOSES} is the switch of method to calculate the values at layers on \scale below the lowermost layer of input data. If \nmitem{USE_SFC_DIAGNOSES} = \verb|.true.|, the surface quantities, such as T2, RH2, U10, V10, and PSFC are used. Otherwise, constant potential temperature and hydrostatic balance are assumed. \nmitem{USE_DATA_UNDER_SFC} is switch whether the input data below its surface is used or ignored. %The data below the surface may appear on a high-pressure surface at high mountainous region. \\ \noindent\textbf{\underline{Settings for \texttt{PARAM\_MKINIT\_REAL\_LAND}}} The soil water is configured by \nmitem{USE_FILE_LANDWATER} of \namelist{PARAM_MKINIT_REAL_LAND} in \verb|init.conf|. There are two options in preparation of soil moisture: i) the data provided from the input file (\nmitem{USE_FILE_LANDWATER} = \verb|.true.|) and ii) a constant value in the entire region (\nmitem{USE_FILE_LANDWATER} = \verb|.false.|). In the case of the option i), either fraction of volume of soil moisture (\verb|SMOISVC|) or saturation ratio (\verb|SMOISDS|) is required as the 3D soil moisture data. Here, the fraction of volume of soil moisture is the ratio of water volume ($V_w$) to soil volume ($V$), i.e., $V_w / V$, and the saturation ratio is the ratio of water volume ($V_w$) to void spaces in $V$ ($V_v$), i.e., $V_w / V_v$. % In the case of the option ii), the saturation ratio is specified by \nmitem{INIT_LANDWATER_RATIO} whose default value is 0.5. The porosity of the soil ($V_v/V$) depends on the land use. \editboxtwo{ \verb|&PARAM_MKINIT_REAL_LAND| &\\ \verb| USE_FILE_LANDWATER = .false.| & ; Switch to give soil moisture by input files. The default is \verb|.true.| \\ \verb| INIT_LANDWATER_RATIO = 0.5 | & ; (For \verb|USE_FILE_LANDWATER=.false.|) saturation ratio\\ \verb| .......... | & \\ \verb|/| & \\ } \nmitem{ELEVATION_CORRECTION} in \namelist{PARAM_MKINIT_REAL_LAND} determines whether soil temperature and land surface temperature for the initial and boundary data are corrected according to the topographical difference between the parent model and the \scalerm. In general, topographies of the parent model and the \scalerm are different. Therefore, if soil temperature and land surface temperature for the initial and boundary data are made by simply interpolating the data of the parent model, there could be inconsistency of temperature according to the height difference of the topography. If \nmitem{ELEVATION_CORRECTION} is \verb|.true.|, soil temperature and land surface temperature for the initial and boundary data are corrected according to the height difference. For example, if the topography made by the \scalerm is $\Delta h$ higher than that of the parent model, soil temperature and land surface temperature are uniformly reduced by $\Delta h\Gamma$, where $\Gamma$ is lapse rate of the international standard atmosphere (ISA): $\Gamma=6.5\times 10^{-3}$ [K/m]. The default value is \nmitem{ELEVATION_CORRECTION} = \verb|.true.|. %%%---------------------------------------------------------------------------------%%%% \subsubsection{Input from SCALE format data} \label{sec:datainput_scale} An example of configurations in \namelist{PARAM_MKINIT_REAL_(ATMOS|OCEAN|LAND)} for the SCALE foramt data is as follows: \editbox{ \verb|&PARAM_MKINIT_REAL_ATMOS|\\ \verb| NUMBER_OF_FILES = 2, | \\ \verb| FILETYPE_ORG = "SCALE-RM",| \\ \verb| BASENAME_ORG = "history_d01",| \\ \verb| BASENAME_ADD_NUM = .true.,| \\ \verb| BASENAME_BOUNDARY = 'boundary_d01',| \\ \verb| SAME_MP_TYPE = .false.,| \\ ... \\ \verb|/|\\ \verb|&PARAM_MKINIT_REAL_OCEAN|\\ \verb| FILETYPE_ORG = "SCALE-RM",| \\ \verb| BASENAME_ORG = "history_d01",| \\ ... \\ \verb|/|\\ \verb|&PARAM_MKINIT_REAL_LAND|\\ \verb| FILETYPE_ORG = "SCALE-RM",| \\ \verb| BASENAME_ORG = "history_d01",| \\ ... \\ \verb|/|\\ } \nmitem{FILETYPE_ORG} is set to \verb|"SCALE-RM"|. The base name of input files is specified by \nmitem{BASENAME_ORG}. Given \verb|BASENAME_ORG="history_d01"|, the input file should be named \verb|history_d01.nc| when the number of input file is 1. When the number of input files is larger than 1 or \nmitem{BASENAME_ADD_NUM} = \verb|.true.| in \namelist{PARAM_RESTART}, the name of the input files should be numbered as \verb|"history_d01_XXXXX.nc"|. If cloud microphysical scheme used is same as that in the parent model, specify \nmitem{SAME_MP_TYPE}. %%%---------------------------------------------------------------------------------%%%% \subsubsection{Input from binary format data} \label{sec:datainput_grads} If the binary data is used as input files, you need to prepare data according to the format used in \grads. For the details, see \url{http://cola.gmu.edu/grads/gadoc/aboutgriddeddata.html#structure} . An example of configurations in \namelist{PARAM_MKINIT_REAL_(ATMOS|OCEAN|LAND)} for the binary format data is as follows:\editbox{ \verb|&PARAM_MKINIT_REAL_ATMOS|\\ \verb| NUMBER_OF_FILES = 2, | \\ \verb| FILETYPE_ORG = "GrADS",|\\ \verb| BASENAME_ORG = "namelist.grads_boundary.FNL.2005053112-2016051106",|\\ \verb| BASENAME_ADD_NUM = .true.,| \\ \verb| BASENAME_BOUNDARY = 'boundary_d01',| \\ \verb| BOUNDARY_UPDATE_DT = 21600.0,|\\ ... \\ \verb|/|\\ \verb|&PARAM_MKINIT_REAL_OCEAN|\\ \verb| FILETYPE_ORG = "GrADS",|\\ \verb| BASENAME_ORG = "namelist.grads_boundary.FNL.2005053112-2016051106",|\\ \verb| INTRP_OCEAN_SFC_TEMP = "mask",|\\ \verb| INTRP_OCEAN_TEMP = "mask",|\\ ... \\ \verb|/|\\ \verb|&PARAM_MKINIT_REAL_LAND|\\ \verb| FILETYPE_ORG = "GrADS",|\\ \verb| BASENAME_ORG = "namelist.grads_boundary.FNL.2005053112-2016051106",|\\ \verb| INTRP_LAND_TEMP = "fill",|\\ \verb| INTRP_LAND_WATER = "fill",|\\ \verb| INTRP_LAND_SFC_TEMP = "fill",|\\ ... \\ \verb|/|\\ } \nmitem{FILETYPE_ORG} is set to \verb|"GrADS"|. In \scalerm, the file name and the data structure of the \grads formatted binary data are specified in the namelist file specified by \nmitem{BASENAME_ORG} instead of the ``ctl'' file. The namelist file needs to be prepared beforehand by users. The following is an example of the namelist file \verb|namelist.grads_boundary*| which provides information of the data file name and data structure. \editbox{ \verb|#| \\ \verb|# Dimension | \\ \verb|#| \\ \verb|&GrADS_DIMS| \\ \verb| nx = 360,|~~~ ; Default value of the number of grids in x direction \\ \verb| ny = 181,|~~~ ; Default value of the number of grids in y direction \\ \verb| nz = 26, |~~~~~ ; Default value of the number of layers in z direction \\ \verb|/| \\ \\ \verb|# | \\ \verb|# Variables | \\ \verb|# | \\ \verb|&GrADS_ITEM name='lon', dtype='linear', swpoint=0.0d0, dd=1.0d0 / | \\ \verb|&GrADS_ITEM name='lat', dtype='linear', swpoint=90.0d0, dd=-1.0d0 / | \\ \verb|&GrADS_ITEM name='plev', dtype='levels', lnum=26,| \\ ~~~\verb| lvars=100000,97500,.........,2000,1000, / | \\ \verb|&GrADS_ITEM name='HGT', dtype='map', fname='FNLatm', startrec=1, totalrec=125 / | \\ \verb|&GrADS_ITEM name='U', dtype='map', fname='FNLatm', startrec=27, totalrec=125 / | \\ \verb|&GrADS_ITEM name='V', dtype='map', fname='FNLatm', startrec=53, totalrec=125 / | \\ \verb|&GrADS_ITEM name='T', dtype='map', fname='FNLatm', startrec=79, totalrec=125 / | \\ \verb|&GrADS_ITEM name='RH', dtype='map', fname='FNLatm', startrec=105,totalrec=125, nz=21 / | \\ \verb|&GrADS_ITEM name='MSLP', dtype='map', fname='FNLsfc', startrec=1, totalrec=9 / | \\ \verb|&GrADS_ITEM name='PSFC', dtype='map', fname='FNLsfc', startrec=2, totalrec=9 / | \\ \verb|&GrADS_ITEM name='SKINT', dtype='map', fname='FNLsfc', startrec=3, totalrec=9 / | \\ \verb|&GrADS_ITEM name='topo', dtype='map', fname='FNLsfc', startrec=4, totalrec=9 / | \\ \verb|&GrADS_ITEM name='lsmask', dtype='map', fname='FNLsfc', startrec=5, totalrec=9 / | \\ \verb|&GrADS_ITEM name='U10', dtype='map', fname='FNLsfc', startrec=6, totalrec=9 / | \\ \verb|&GrADS_ITEM name='V10', dtype='map', fname='FNLsfc', startrec=7, totalrec=9 / | \\ \verb|&GrADS_ITEM name='T2', dtype='map', fname='FNLsfc', startrec=8, totalrec=9 / | \\ \verb|&GrADS_ITEM name='RH2', dtype='map', fname='FNLsfc', startrec=9, totalrec=9 / | \\ \verb|&GrADS_ITEM name='llev', dtype='levels', nz=4, lvars=0.05,0.25,0.70,1.50, / | \\ ~~~~~~~~\verb| missval=9.999e+20 /| \\ \verb|&GrADS_ITEM name='STEMP', dtype='map', fname='FNLland', nz=4, startrec=1, totalrec=8,|\\ ~~~~~~~~\verb| missval=9.999e+20 /| \\ \verb|&GrADS_ITEM name='SMOISVC', dtype='map', fname='FNLland', nz=4, startrec=5, totalrec=8,|\\ ~~~~~~~~\verb| missval=9.999e+20 /| \\ } The default value of the number of grids is specified as \verb|nx, ny, nz| in \namelist{GrADS_DIMS}. Configurations for the variables are individually specified by \namelist{GrADS_ITEM}. The explanations of \namelist{GrADS_ITEM} is described in Table \ref{tab:namelist_grdvar}. The base name of input files is set as \verb|fname| in the \namelist{GrADS_ITEM}. Given the base name is set as \verb|fname="filename"|, the input binary data file should be named \verb|filename.grd| in the case that the number of the input binary file is one (\nmitem{NUMBER_OF_FILES} = 1). In the case that there is more than one input files or \nmitem{BASENAME_ADD_NUM} = \verb|.true.| in \namelist{PARAM_RESTART}, prepare the files numbered as \verb|"filename_XXXXX.grd"|. If the number of grids for a variable is different from the default value, the value is specified by \verb|nx, ny, nz| of \namelist{GrADS_ITEM}. For example, specific humidity (\verb|QV|) and relative humidity (\verb|RH|) in upper levels are not always available. In such case, the number of layers where the data exist is specified as \verb|nz|. The method to give the values of QV at layers higher than \verb|nz| is specified by \nmitem{upper_qv_type} in \namelist{PARAM_MKINIT_REAL_GrADS}. For \nmitem{upper_qv_type}='\verb|ZERO|', the value of QV is set to zero. For \nmitem{upper_qv_type}='\verb|COPY|', the value of RH at layers higher than \verb|nz| is set to that at the top layer where input humidity data exists; it determine the value of QV. The default value of \verb|upper_qv_type| is "ZERO". \editboxtwo{ \verb|&PARAM_MKINIT_REAL_GrADS| & \\ \verb| upper_qv_type = "ZERO"| & ; Method to give QV at layers higher than \verb|nz|\\ & ~~~("\verb|ZERO|", "\verb|COPY|")\\ \verb|/|\\ } The variables required for the calculation with \scalerm are listed in Table \ref{tab:grdvar_item}. {\small \begin{table}[tbh] \begin{center} \caption{Variables of \namelist{GrADS_ITEM}} \label{tab:namelist_grdvar} \begin{tabularx}{150mm}{llX} \hline \rowcolor[gray]{0.9} item of \verb|GrADS_ITEM| & Explanation & Note \\ \hline name & Variable name & Select from Table \ref{tab:grdvar_item} \\ dtype & Data type & \verb|"linear"|,\verb|"levels"| or \verb|"map"| \\\hline \multicolumn{3}{l}{namelist at \nmitem{dtype}\verb|="linear"| (specific use of \verb|"lon", "lat"| )} \\ \hline fname & Header name of files & \\ swpoint & Value of start point & \\ dd & Increment & \\ \hline \multicolumn{3}{l}{namelist at \nmitem{dtype}\verb|"=levels"| (specific use of \verb|"plev", "llev"|)} \\ \hline lnum & Number of levels (layers ) & \\ lvars & Values of each layer & \\ \hline \multicolumn{3}{l}{namelist at \nmitem{dtype}\verb|="map"|} \\ \hline startrec & Recorded number of variables \nmitem{item} & time at t=1\\ totalrec & Recorded length of all variables per time & \\ missval & Missing value & (option) \\ \hline nx & Number of grids in x direction & (option) \\ \hline ny & Number of grids in y direction & (option) \\ \hline nz & Number of layers in z direction & (option) \\ \hline yrev & If the data is stored from the north to south, set \verb|.true.| & (option) \\ \hline \end{tabularx} \end{center} \end{table} } { \begin{table}[bth] \begin{center} \caption{Variable list of \nmitem{name} in \namelist{GrADS_ITEM}. The asterisk means ``it is optional but recommended as possible''. The double-asterisk means ``it is available but not recommended''.} \label{tab:grdvar_item} \small \begin{tabularx}{150mm}{rl|l|l|X} \hline \rowcolor[gray]{0.9} & Variable name \nmitem{name} & Explanation & Unit & Data type \nmitem{dtype} \\ \hline &\verb|lon| & longitude data & [deg.] & \verb|linear, map| \\ &\verb|lat| & latitude data & [deg.] & \verb|linear, map| \\ &\verb|plev| & pressure data & [Pa] & \verb|levels, map| \\ &\verb|HGT| & geopotential height data & [m] & \verb|map| \\ $\ast$ &\verb|DENS| & air density & [kg/m3] & \verb|map| \\ &\verb|U| & eastward wind speed & [m/s] & \verb|map| \\ &\verb|V| & northward wind speed & [m/s] & \verb|map| \\ $\ast\ast$ &\verb|W| & vertical wind speed & [m/s] & \verb|map| \\ &\verb|T| & temperature & [K] & \verb|map| \\ &\verb|RH| & relative humidity & [\%] & \verb|map| \\ & & (optional if QV is given) & & \\ &\verb|QV| & specific humidity & [kg/kg] & \verb|map| \\ & & (optional if RH is given) & & \\ $\ast\ast$ &\verb|QC| & ratio of cloud water mass & [kg/kg] & \verb|map| \\ $\ast\ast$ &\verb|QR| & ratio of rain water mass & [kg/kg] & \verb|map| \\ $\ast\ast$ &\verb|QI| & ratio of cloud ice mass & [kg/kg] & \verb|map| \\ $\ast\ast$ &\verb|QS| & ratio of snow mass & [kg/kg] & \verb|map| \\ $\ast\ast$ &\verb|QG| & ratio of graupel mass & [kg/kg] & \verb|map| \\ $\ast\ast$ &\verb|MSLP| & sea level pressure & [Pa] & \verb|map| \\ $\ast\ast$ &\verb|PSFC| & surface pressure & [Pa] & \verb|map| \\ $\ast\ast$ &\verb|U10| & eastward 10m wind speed & [m/s] & \verb|map| \\ $\ast\ast$ &\verb|V10| & northward 10m wind speed & [m/s] & \verb|map| \\ $\ast\ast$ &\verb|T2| & 2m temperature & [K] & \verb|map| \\ $\ast\ast$ &\verb|RH2| & 2m relative humidity & [\%] & \verb|map| \\ & & (optional if Q2 is given) & & \\ $\ast\ast$ &\verb|Q2| & 2m specific humidity & [kg/kg] & \verb|map| \\ & & (optional if RH2 is given) & & \\ $\ast$ &\verb|TOPO| & topography of GCM & [m] & \verb|map| \\ $\ast$ &\verb|lsmask| & ocean--land distribution of GCM & 0:ocean,1:land & \verb|map| \\ &\verb|SKINT| & surface temperature & [K] & \verb|map| \\ &\verb|llev| & soil depth & [m] & \verb|levels| \\ &\verb|STEMP| & soil temperature & [K] & \verb|map| \\ &\verb|SMOISVC| & soil moisture (volume fraction) & [-] & \verb|map| \\ & & (optional if SMOISDS is given) & & \\ &\verb|SMOISDS| & soil moisture (saturation ratio) & [-] & \verb|map| \\ & & (optional if SMOISVC is given) & & \\ &\verb|SST| & sea surface temperature & [K] & \verb|map| \\ & & (optional if SKINT is given) & & \\\hline \end{tabularx} \end{center} \end{table} }
Require Import Bool List Arith Nat. Import ListNotations. Require Import Mmx.ast_instructions Mmx.binary Mmx.association_list Mmx.encode. Lemma encode_decode_t_n : forall (i : instruction_tern_n) (bi : binary_instruction), encode_t_n i = Some bi -> decode bi = Some (instr_t_n i). Proof. (* first part trying to get lot of information from encode_t_n *) intros. unfold encode_t_n in H. apply bind_rewrite in H. destruct H. destruct H. apply bind_rewrite in H. destruct H. destruct H. apply bind_rewrite in H. destruct H. destruct H. apply bind_rewrite in H. destruct H. destruct H. apply bind_rewrite in H. destruct H. destruct H. unfold decode. rewrite ret_rewrite in H. inversion H. (* now going to go further into decode *) assert (length x0 = 8) by (apply commut_equal in H1; apply size_n_bit in H1; auto). assert (get_first_n_bit (x0 ++ x1 ++ x2 ++ x3) 8 = (x0,x1 ++ x2 ++ x3)) by (apply get_first_n_bit_size_4; auto). rewrite H7. apply commut_equal in H0. apply lookup_encdecP in H0. apply commut_equal in H1. assert (bit_n x0 = x) by (apply n_bit_n in H1; exact H1). rewrite H8. rewrite H0. assert (forall (f : tag -> (option instruction)), bind (Some (tag_t_n (instr_opcode_t_n i))) f = f (tag_t_n (instr_opcode_t_n i))) by reflexivity. rewrite H9. assert (length x1 = 8) by (apply commut_equal in H2; apply operand_to_bin_size in H2; auto). assert (get_first_n_bit (x1 ++ x2 ++ x3) 8 = (x1,x2 ++ x3)) by (apply get_first_n_bit_size_3; auto). rewrite H11. assert (length x2 = 8) by (apply commut_equal in H3; apply operand_to_bin_size in H3; auto). assert (get_first_n_bit (x2 ++ x3) 8 = (x2,x3))by (apply commut_equal in H4; apply get_first_n_bit_size_tl; auto). rewrite H13. assert (length x3 = 8) by (apply commut_equal in H4; apply operand_to_bin_size in H4; auto). assert (get_first_n_bit (x3) 8 = (x3,[])) by (apply get_first_n_bit_size_nil_n; auto). rewrite H15. rewrite ret_rewrite. apply commut_equal in H2. apply operand_to_bin_hypothesis1_t_n in H2. rewrite H2. apply commut_equal in H3. apply operand_to_bin_hypothesis2_t_n in H3. rewrite H3. apply commut_equal in H4. apply operand_to_bin_hypothesis3_t_n in H4. rewrite H4. assert ({| instr_opcode_t_n := instr_opcode_t_n i; instr_operande1_t_n := instr_operande1_t_n i; instr_operande2_t_n := instr_operande2_t_n i; instr_operande3_t_n := instr_operande3_t_n i |} = i). { simpl. destruct i. compute. reflexivity. } rewrite H16. repeat rewrite app_length. rewrite H5. rewrite H10. rewrite H12. rewrite H14. simpl. reflexivity. Qed. Lemma encode_decode_t_i : forall (i : instruction_tern_i) (bi : binary_instruction), encode_t_i i = Some bi -> decode bi = Some (instr_t_i i). Proof. (* first part trying to get lot of information from encode_t_n *) intros. unfold encode_t_n in H. apply bind_rewrite in H. destruct H. destruct H. apply bind_rewrite in H. destruct H. destruct H. apply bind_rewrite in H. destruct H. destruct H. apply bind_rewrite in H. destruct H. destruct H. apply bind_rewrite in H. destruct H. destruct H. unfold decode. rewrite ret_rewrite in H. inversion H. (* now going to go further into decode *) assert (length x0 = 8) by (apply commut_equal in H1; apply size_n_bit in H1; auto). assert (get_first_n_bit (x0 ++ x1 ++ x2 ++ x3) 8 = (x0,x1 ++ x2 ++ x3)) by (apply get_first_n_bit_size_4; auto). rewrite H7. apply commut_equal in H0. apply lookup_encdecP in H0. apply commut_equal in H1. assert (bit_n x0 = x) by (apply n_bit_n in H1; exact H1). rewrite H8. rewrite H0. assert (forall (f : tag -> (option instruction)), bind (Some (tag_t_i (instr_opcode_t_i i))) f = f (tag_t_i (instr_opcode_t_i i))) by reflexivity. rewrite H9. assert (length x1 = 8) by (apply commut_equal in H2; apply operand_to_bin_size in H2; auto). assert (get_first_n_bit (x1 ++ x2 ++ x3) 8 = (x1,x2 ++ x3)) by (apply get_first_n_bit_size_3; auto). rewrite H11. assert (length x2 = 8) by (apply commut_equal in H3; apply operand_to_bin_size in H3; auto). assert (get_first_n_bit (x2 ++ x3) 8 = (x2,x3))by (apply commut_equal in H4; apply get_first_n_bit_size_tl; auto). rewrite H13. assert (length x3 = 8) by (apply commut_equal in H4; apply operand_to_bin_size in H4; auto). assert (get_first_n_bit (x3) 8 = (x3,[])) by (apply get_first_n_bit_size_nil_n; auto). rewrite H15. rewrite ret_rewrite. apply commut_equal in H2. apply operand_to_bin_hypothesis1_t_i in H2. rewrite H2. apply commut_equal in H3. apply operand_to_bin_hypothesis2_t_i in H3. rewrite H3. apply commut_equal in H4. apply operand_to_bin_hypothesis3_t_i in H4. rewrite H4. assert ({| instr_opcode_t_i := instr_opcode_t_i i; instr_operande1_t_i := instr_operande1_t_i i; instr_operande2_t_i := instr_operande2_t_i i; instr_operande3_t_i := instr_operande3_t_i i |} = i). { simpl. destruct i. compute. reflexivity. } rewrite H16. repeat rewrite app_length. rewrite H5. rewrite H10. rewrite H12. rewrite H14. simpl. reflexivity. Qed. Lemma encode_decode_d_n : forall (i : instruction_duo_n) (bi : binary_instruction), encode_d_n i = Some bi -> decode bi = Some (instr_d_n i). Proof. (* first part trying to get lot of information from encode_t_n *) intros. unfold encode_t_n in H. apply bind_rewrite in H. destruct H. destruct H. apply bind_rewrite in H. destruct H. destruct H. apply bind_rewrite in H. destruct H. destruct H. apply bind_rewrite in H. destruct H. destruct H. unfold decode. rewrite ret_rewrite in H. inversion H. (* now going to go further into decode *) assert (length x0 = 8) by (apply commut_equal in H1; apply size_n_bit in H1; auto). assert (get_first_n_bit (x0 ++ x1 ++ x2) 8 = (x0,x1 ++ x2)) by (apply get_first_n_bit_size_3; auto). rewrite H6. apply commut_equal in H0. apply lookup_encdecP in H0. apply commut_equal in H1. assert (bit_n x0 = x) by (apply n_bit_n in H1; exact H1). rewrite H7. rewrite H0. assert (forall (f : tag -> (option instruction)), bind (Some (tag_d_n (instr_opcode_d_n i))) f = f (tag_d_n (instr_opcode_d_n i))) by reflexivity. rewrite H8. assert (length x1 = 8) by (apply commut_equal in H2; apply operand_to_bin_size in H2; auto). assert (get_first_n_bit (x1 ++ x2) 8 = (x1,x2)) by (apply get_first_n_bit_size_tl; auto). rewrite H10. assert (length x2 = 16) by (apply commut_equal in H3; apply operand_to_bin_double_size in H3; auto). assert (get_first_n_bit x2 16 = (x2,[]))by (apply commut_equal in H4; apply get_first_n_bit_size_nil_n; auto). rewrite H12. rewrite ret_rewrite. apply commut_equal in H2. apply operand_to_bin_hypothesis1_d_n in H2. rewrite H2. apply commut_equal in H3. apply operand_to_bin_double_hypothesis2_d_n in H3. rewrite H3. assert ({| instr_opcode_d_n := instr_opcode_d_n i; instr_operande1_d_n := instr_operande1_d_n i; instr_operande2_d_n := instr_operande2_d_n i; |} = i). { simpl. destruct i. compute. reflexivity. } rewrite H13. repeat rewrite app_length. rewrite H4. rewrite H9. rewrite H11. simpl. reflexivity. Qed. Lemma encode_decode_d_i : forall (i : instruction_duo_i) (bi : binary_instruction), encode_d_i i = Some bi -> decode bi = Some (instr_d_i i). Proof. (* first part trying to get lot of information from encode_t_n *) intros. unfold encode_t_n in H. apply bind_rewrite in H. destruct H. destruct H. apply bind_rewrite in H. destruct H. destruct H. apply bind_rewrite in H. destruct H. destruct H. apply bind_rewrite in H. destruct H. destruct H. unfold decode. rewrite ret_rewrite in H. inversion H. (* now going to go further into decode *) assert (length x0 = 8) by (apply commut_equal in H1; apply size_n_bit in H1; auto). assert (get_first_n_bit (x0 ++ x1 ++ x2) 8 = (x0,x1 ++ x2)) by (apply get_first_n_bit_size_3; auto). rewrite H6. apply commut_equal in H0. apply lookup_encdecP in H0. apply commut_equal in H1. assert (bit_n x0 = x) by (apply n_bit_n in H1; exact H1). rewrite H7. rewrite H0. assert (forall (f : tag -> (option instruction)), bind (Some (tag_d_i (instr_opcode_d_i i))) f = f (tag_d_i (instr_opcode_d_i i))) by reflexivity. rewrite H8. assert (length x1 = 8) by (apply commut_equal in H2; apply operand_to_bin_size in H2; auto). assert (get_first_n_bit (x1 ++ x2) 8 = (x1,x2)) by (apply get_first_n_bit_size_tl; auto). rewrite H10. assert (length x2 = 16) by (apply commut_equal in H3; apply operand_to_bin_double_size in H3; auto). assert (get_first_n_bit x2 16 = (x2,[]))by (apply commut_equal in H4; apply get_first_n_bit_size_nil_n; auto). rewrite H12. rewrite ret_rewrite. apply commut_equal in H2. apply operand_to_bin_hypothesis1_d_i in H2. rewrite H2. apply commut_equal in H3. apply operand_to_bin_double_hypothesis2_d_i in H3. rewrite H3. assert ({| instr_opcode_d_i := instr_opcode_d_i i; instr_operande1_d_i := instr_operande1_d_i i; instr_operande2_d_i := instr_operande2_d_i i; |} = i). { simpl. destruct i. compute. reflexivity. } rewrite H13. repeat rewrite app_length. rewrite H4. rewrite H9. rewrite H11. reflexivity. Qed. Lemma encode_decode : forall (i : instruction) (bi : binary_instruction), encode i = Some bi -> decode bi = Some i. Proof. destruct i. -apply encode_decode_t_n. -apply encode_decode_t_i. -apply encode_decode_d_n. -apply encode_decode_d_i. Qed.
import Euclid.tarski_6 open classical set namespace Euclidean_plane variables {point : Type} [Euclidean_plane point] local attribute [instance] prop_decidable theorem col_of_perp {a b p q : point} : p β‰  q β†’ R a p q β†’ R b p q β†’ col p a b := Ξ» h h1 h2, not_3dim (seven12b h) (seven5 p q).2 h1 h2 theorem coplanar {a : point} (b : point) {A : set point} : line A β†’ a βˆ‰ A β†’ b ∈ pl A a := begin intros h h1, cases exists_of_exists_unique (eight17 h h1) with p hp, by_cases h2 : b ∈ A, exact or.inr (or.inl h2), cases ten15 h hp.1 h2 with c hc, suffices : col p a c, by_cases h_1 : B c p a, apply (or.inr (or.inr ((nine8 _).2 hc.2).symm)), exact ⟨h, (nine11 hc.2).2.1, h1, p, hp.1, h_1⟩, apply or.inl (hc.2.symm.trans _), exact nine12 h hp.1 (six4.2 ⟨(four11 this).2.2.2.1, h_1⟩) (nine11 hc.2).2.1, rcases six22 h hp.1 with ⟨q, h3, h4⟩, subst h4, apply col_of_perp h3, suffices : xperp p (l p q) (l a p), exact (this.2.2.2.2 (six17b p q) (six17a a p)).symm, exact eight15 hp.2 (six17a p q) (six17b a p), suffices : xperp p (l p q) (l c p), exact (this.2.2.2.2 (six17b p q) (six17a c p)).symm, exact eight15 hc.1 (six17a p q) (six17b c p) end def P : set point := planeof (P1 : point) P2 P3 theorem planeP : plane (P : set point) := ⟨P1, P2, P3, six24, rfl⟩ theorem in_P {a : point} : a ∈ (P : set point) := coplanar a (six14 (six26 six24).1) six24 theorem unique_plane {Q : set point} : plane Q β†’ Q = P := begin rintros ⟨x, y, z, h, h1⟩, subst h1, exact (nine26 h planeP in_P in_P in_P).symm end def dpar (A B : set point) : Prop := line A ∧ line B ∧ Β¬βˆƒ x, x ∈ A ∧ x ∈ B def par (A B : set point) : Prop := dpar A B ∨ line A ∧ A = B theorem line_of_par {A B : set point} : par A B β†’ line A ∧ line B := Ξ» h, h.elim (Ξ» h, ⟨h.1, h.2.1⟩) (Ξ» h, ⟨h.1, h.2 β–Έ h.1⟩) theorem twelve1 {A B : set point} : dpar A B β†’ A β‰  B := begin intros h h1, rcases h.1 with ⟨x, y, h2, h3⟩, subst_vars, exact h.2.2 ⟨x, six17a x y, six17a x y⟩ end theorem twelve2 {A B : set point} {a : point} : dpar A B β†’ a ∈ A β†’ a βˆ‰ B := Ξ» h h1 h2, h.2.2 ⟨a, h1, h2⟩ theorem twelve3 {a b c : point} : par (l a b) (l a c) β†’ col a b c := begin intro h, cases h, exact (h.2.2 ⟨a, six17a a b, six17a a c⟩).elim, change c ∈ l a b, simp [h.2] end theorem par.refl {A : set point} : line A β†’ par A A := Ξ» h, or.inr ⟨h, rfl⟩ theorem dpar.symm {A B : set point} : dpar A B β†’ dpar B A := Ξ» h, ⟨h.2.1, h.1, Ξ» ⟨x, hx⟩, h.2.2 ⟨x, hx.symm⟩⟩ theorem par.symm {A B : set point} : par A B β†’ par B A := Ξ» h, h.elim (Ξ» h, or.inl h.symm) (Ξ» h, or.inr ⟨h.2 β–Έ h.1, h.2.symm⟩) theorem twelve5 {A B : set point} {x : point} : par A B β†’ x ∈ A β†’ x ∈ B β†’ A = B := Ξ» h h1 h2, h.elim (Ξ» h, (h.2.2 ⟨x, h1, h2⟩).elim) (and.right) theorem twelve6 {A B : set point} : dpar A B β†’ βˆ€ {b b'}, b ∈ B β†’ b' ∈ B β†’ side A b b' := begin intros h b b' h1 h2, have h3 : b βˆ‰ A, intro h_1, exact h.2.2 ⟨b, h_1, h1⟩, cases coplanar b' h.1 h3, exact h_1.symm, cases h_1, exact (h.2.2 ⟨b', h_1, h2⟩).elim, cases h_1.2.2.2 with x hx, apply (h.2.2 ⟨x, hx.1, _⟩).elim, suffices : B = l b b', rw this, exact or.inr (or.inl hx.2.symm), exact six18 h.2.1 (nine2 h_1) h1 h2 end theorem twelve7 {a b c d : point} : dpar (l a b) (l c d) ↔ side (l a b) c d ∧ Β¬βˆƒ x, col a b x ∧ col c d x := begin split, intro h, refine ⟨twelve6 h (six17a c d) (six17b c d), _⟩, rintros ⟨x, hx⟩, exact h.2.2 ⟨x, hx.1, hx.2⟩, rintros ⟨h, h1⟩, have h2 := six13 (nine11 h).1, have h3 : c β‰  d, intro h_1, subst d, exact h1 ⟨b, or.inl (three1 a b), or.inl (three3 c b)⟩, refine ⟨six14 h2, six14 h3, Ξ» h_1, _⟩, cases h_1 with x hx, exact h1 ⟨x, hx.1, hx.2⟩ end theorem twelve8 (a : point) {L : set point} : line L β†’ βˆƒ! (A : set point), a ∈ A ∧ perp L A := begin intro h, by_cases h1 : a ∈ L, rcases six22 h h1 with ⟨b, hb, h2⟩, subst h2, cases eight25 hb.symm with c hc, refine ⟨l a c, ⟨six17a a c, _⟩, _⟩, suffices : xperp a (l a b) (l a c), exact ⟨a, this⟩, apply eight13.2, simp *, exact ⟨six14 hc.2.symm, b, six17b a b, c, six17b a c, hb.symm, hc.2, hc.1⟩, intros Y hy, rcases six22 (eight14e hy.2).2 hy.1 with ⟨x, hx, h2⟩, subst h2, apply six18 (six14 hx) hc.2.symm (six17a a x) _, apply col_of_perp hb _ hc.1.symm, have h2 := eight15 hy.2.symm (six17a a x) (six17a a b), exact h2.2.2.2.2 (six17b a x) (six17b a b), have h2 := eight18 h h1, cases exists_of_exists_unique h2 with x hx, refine ⟨l a x, ⟨(six17a a x), hx.2⟩, _⟩, intros Y hy, apply six18 (eight14e hy.2).2 _ hy.1 _, intro h_1, subst h_1, exact h1 hx.1, cases hy.2 with z hz, suffices : z = x, subst z, exact hz.2.2.2.1, apply unique_of_exists_unique h2 ⟨hz.2.2.1, _⟩ hx, suffices : Y = l a z, subst Y, exact hy.2, apply six18 (eight14e hy.2).2 _ hy.1 hz.2.2.2.1, intro h_1, subst h_1, exact h1 hz.2.2.1 end theorem twelve9 {A B C : set point} : line A β†’ line B β†’ line C β†’ perp A C β†’ perp B C β†’ par A B := begin intros h h1 h2 h3 h4, by_cases h_1 : A = B, exact or.inr ⟨h, h_1⟩, refine or.inl ⟨h, h1, Ξ» h_2, _⟩, cases h_2 with x hx, apply h_1, exact unique_of_exists_unique (twelve8 x h2) ⟨hx.1, h3.symm⟩ ⟨hx.2, h4.symm⟩ end theorem twelve10 {A : set point} {a : point} : line A β†’ βˆƒ B, par A B ∧ a ∈ B := begin intro h, by_cases h1 : a ∈ A, exact ⟨A, or.inr ⟨h, rfl⟩, h1⟩, cases exists_of_exists_unique (twelve8 a h) with C hc, cases exists_of_exists_unique (twelve8 a (eight14e hc.2).2) with B hb, refine ⟨B, _, hb.1⟩, exact twelve9 h (eight14e hb.2).2 (eight14e hc.2).2 hc.2 hb.2.symm end theorem twelve11 {A B C : set point} {a : point} : line A β†’ a βˆ‰ A β†’ par A B β†’ a ∈ B β†’ par A C β†’ a ∈ C β†’ B = C := begin intros h h1 h2 h3 h4 h5, replace h2 : dpar A B, apply h2.elim (id), intro h_2, exact (h1 (h_2.2.symm β–Έ h3)).elim, replace h4 : dpar A C, apply h4.elim (id), intro h_2, exact (h1 (h_2.2.symm β–Έ h5)).elim, by_contradiction h_1, rcases h with ⟨s, t, h, h6⟩, subst h6, suffices : βˆƒ c', c' ∈ C ∧ Bl t B c', rcases this with ⟨c', hc1, hc2⟩, cases hc2.2.2.2 with b hb, cases three14 c' a with c hc, cases pasch hc.1.symm hb.2 with d hd, have h6 : a β‰  b, intro h_2, subst b, suffices : c' β‰  a, apply twelve2 h4 (six17b s t), rw (six18 h4.2.1 this hc1 h5), exact or.inl hb.2.symm, intro h_2, subst h_2, exact hc2.2.2.1 h3, have h7 : c ∈ C, rw (six18 h4.2.1 _ hc1 h5), exact or.inl hc.1, intro h_2, subst h_2, exact hc2.2.2.1 h3, suffices : a β‰  d, rcases euclids hd.1 hd.2 this with ⟨x, y, hx, hy, ht⟩, suffices : side (l s t) a t, exact (nine11 this).2.2 (six17b s t), apply nine17a (twelve6 h2 h3 _) (twelve6 h4 h5 _) ht, rw six18 h2.2.1 h6 h3 hb.1, exact or.inl hx, rw six18 h4.2.1 hc.2 h5 h7, exact or.inl hy, intro h_2, subst h_2, apply h_1, rw [six18 h2.2.1 h6 h3 hb.1, six18 h4.2.1 hc.2 h5 h7], exact six16 h6 hc.2 (or.inr (or.inr hd.2.symm)), cases six22 h4.2.1 h5 with x hx, rw hx.2, cases coplanar x h2.2.1 (twelve2 h2 (six17b s t)), refine ⟨S a x, (seven24 (six14 hx.1) (six17a a x)).1 (six17b a x), _⟩, exact (nine8 (nine1 h2.2.1 h3 (nine11 h_2).2.1)).2 h_2, cases h_2, apply (h_1 _).elim, apply six21 hx.1 h2.2.1 h4.2.1 h3 h5 h_2, rw hx.2, simp, exact ⟨x, six17b a x, h_2⟩ end theorem twelve13 {A : set point} (a : point) : line A β†’ βˆƒ! B, par A B ∧ a ∈ B := begin intro h, apply exists_unique_of_exists_of_unique, exact twelve10 h, intros X Y hx hy, by_cases h_1 : a ∈ A, exact (twelve5 hx.1 h_1 hx.2).symm.trans (twelve5 hy.1 h_1 hy.2), exact twelve11 h h_1 hx.1 hx.2 hy.1 hy.2 end theorem par.trans {A B C : set point} : par A B β†’ par B C β†’ par A C := begin intros h h1, cases h, cases h1, rw [par, or_iff_not_and_not], simp [h.1], intro h2, replace h2 : βˆƒ x, x ∈ A ∧ x ∈ C, by_contradiction h_1, exact h2 ⟨h.1, h1.2.1, h_1⟩, cases h2 with x hx, exact twelve11 h.2.1 (twelve2 h hx.1) (or.inl h.symm) hx.1 (or.inl h1) hx.2, rw h1.2.symm, exact or.inl h, rwa h.2 end theorem twelve17 {a b c d p : point} : M a p c β†’ M b p d β†’ a β‰  b β†’ par (l a b) (l c d) := begin intros h h1 h2, replace h := seven6 h, replace h1 := seven6 h1, rw [h, h1], by_cases h3 : col a b p, refine or.inr ⟨six14 h2, six18 (six14 h2) (two7 (seven13 p a b) h2) _ _⟩; apply (seven24 (six14 h2) h3).1; simp, refine or.inl ⟨six14 h2, six14 (two7 (seven13 p a b) h2), _⟩, intro h_1, rcases h_1 with ⟨x, hx1, hx2⟩, have h4 : x β‰  p, intro h_1, subst p, exact h3 hx1, suffices : l a b = l (S p a) (S p b), apply h3, apply (six27 (six14 h2) (six17a a b) _ (seven5 p a).1), simpa [this], apply six21 (seven12b h4.symm) (six14 h2) (six14 (two7 (seven13 p a b) h2)) hx1 hx2, rw [←seven7 p a, ←seven7 p b], exact (S_of_col p).1 hx2, exact (S_of_col p).1 hx1 end theorem par_of_S {a b : point} (p : point) : a β‰  b β†’ par (l a b) (l (S p a) (S p b)) := twelve17 (seven5 p a) (seven5 p b) theorem twelve18 {a b c d p : point} : eqd a b c d β†’ eqd b c d a β†’ Β¬col a b c β†’ b β‰  d β†’ col a p c β†’ col b p d β†’ par (l a b) (l c d) ∧ par (l b c) (l d a) ∧ Bl b (l a c) d ∧ Bl a (l b d) c := begin intros h h1 h2 h3 h4 h5, have h6 := seven21 h2 h3 h h1 h4 h5, refine ⟨twelve17 h6.1 h6.2 (six26 h2).1, twelve17 h6.2 h6.1.symm (six26 h2).2.1, _⟩, split, rw seven6 h6.2, exact nine1 (six14 (six26 h2).2.2) (four11 h4).1 (four10 h2).1, rw seven6 h6.1, apply nine1 (six14 h3) (four11 h5).1, intro h_1, suffices : c ∈ l b d, exact h2 (six23.2 ⟨l b d, six14 h3, h_1, six17a b d, this⟩), rw seven6 h6.1, exact (seven24 (six14 h3) (four11 h5).1).1 h_1 end theorem twelve19 {a b c d : point} : Β¬col a b c β†’ par (l a b) (l c d) β†’ par (l b c) (l d a) β†’ eqd a b c d ∧ eqd b c d a ∧ Bl b (l a c) d ∧ Bl a (l b d) c := begin intros h h1 h2, generalize hp : mid a c = p, replace hp : c = S p a, rw ←hp, exact (mid_to_Sa a c).symm, subst c, have h3 : eqd b (S p a) (S p b) a, have h4 := seven13 p b (S p a), simpa using h4, have h4 := twelve18 (seven13 p a b) h3 h _ (or.inl (seven5 p a).1) (or.inl (seven5 p b).1), suffices : d = S p b, rw this, exact ⟨seven13 p a b, h3, h4.2.2.1, h4.2.2.2⟩, have h5 := twelve3 (h1.symm.trans h4.1), have h6 := (h2.symm.trans h4.2.1), rw [six17, six17 (S p b) a] at h6, replace h6 := twelve3 h6, by_contradiction h_1, apply h, rw S_of_col p, simp, exact (four11 (five4 (ne.symm h_1) (four11 h5).2.2.2.2 (four11 h6).2.2.2.2)).2.1, apply seven12b, intro h_1, subst p, exact h (or.inl (seven5 b a).1) end theorem twelve20 {a b c d : point} : par (l a b) (l c d) β†’ eqd a b c d β†’ Bl b (l a c) d β†’ par (l b c) (l d a) ∧ eqd b c d a ∧ Bl a (l b d) c := begin intros h h1 h2, generalize hp : mid b d = p, replace hp : d = S p b, rw ←hp, exact (mid_to_Sa b d).symm, subst d, have h3 : p βˆ‰ l a b, intro h_1, suffices : a ∈ l c (S p b), exact h2.2.2.1 (four11 this).2.2.2.1, suffices : l a b = l c (S p b), simpa [this.symm], exact twelve5 h ((seven24 (line_of_par h).1 h_1).1 (six17b a b)) (six17b c (S p b)), have h4 : par (l b (S p a)) (l (S p b) a), suffices : par(l b (S p a)) (l (S p b) (S p (S p a))), simpa [this], apply par_of_S p, intro h_1, subst b, exact (four10 h3).1 (or.inl (seven5 p a).1), have h5 := twelve19 (Ξ» h_1, h3 (six27 (six14 (six26 h2.2.1).2.2) (six17a a b) h_1 (seven5 p a).1)) (par_of_S p (six26 h2.2.1).2.2) h4, suffices : c = S p a, subst c, exact ⟨h4, h5.2.1, h5.2.2.2⟩, have h6 := h.symm.trans (par_of_S p (six26 h2.2.1).2.2), rw [six17, six17 (S p a)] at h6, apply six11a (six4.2 ⟨(four11 (twelve3 h6)).2.1, _⟩) (h1.symm.flip.trans (seven13 p a b).flip), intro h_1, have h7 : p βˆ‰ l a c, intro h_2, apply h2.2.1, apply six27 h2.1 ((seven24 h2.1 h_2).1 (six17b a c)) (six17a a c), rw [←seven7 p a, ←seven7 p b], exact (seven15 p).1 h_1, apply nine9 h2, suffices : side (l a c) (S p a) (S p c), apply side.trans _ (this.symm.trans _), suffices : sided a b (S p c), exact nine12 h2.1 (six17a a c) this h2.2.1, apply six7 _ (six26 h2.2.1).2.2.symm, rw [←seven7 p a, ←seven7 p b], exact (seven15 p).1 h_1.symm, suffices : sided c (S p b) (S p a), exact (nine12 h2.1 (six17b a c) this h2.2.2.1).symm, exact six7 h_1 (six13 (line_of_par h).2).symm, suffices : side (l a c) p (S p a), apply this.symm.trans, apply nine12 h2.1 (six17b a c) (six7 (seven5 p c).1 _) h7, intro h_1, subst p, exact h7 (six17b a c), apply nine12 h2.1 (six17a a c) (six7 (seven5 p a).1 _) h7, intro h_1, subst p, exact h7 (six17a a c) end theorem twelve21 {a b c d : point} : Bl b (l a c) d β†’ (par (l a b) (l c d) ↔ eqa b a c d c a) := begin intro h, cases exists_of_exists_unique (six11 (six26 h.2.2.1).2.1.symm (six26 h.2.1).2.2) with d' hd, replace h : Bl b (l a c) d', apply ((nine8 h.symm).2 _).symm, exact nine12 h.1 (six17b a c) hd.1.symm h.2.2.1, split, intro h1, rw (six16a hd.1.symm) at h1, suffices : eqa b a c d' c a, exact eleven10 this (six5 this.1) (six5 this.2.1) hd.1.symm (six5 this.2.2.2.1), apply eleven11 (six13 (line_of_par h1).1).symm (six13 h.1).symm, exact ⟨hd.2.symm.flip, eqd_refl a c, (twelve20 h1 hd.2.symm h).2.1⟩, intro h1, replace h1 := eleven10 h1 (six5 h1.1) (six5 h1.2.1) hd.1 (six5 h1.2.2.2.1), rw (six16a hd.1.symm), apply (twelve18 hd.2.symm (SAS h1 hd.2.symm.flip (eqd_refl c a)).1 (four10 h.2.1).1 (nine2 h) (or.inl (ten1 a c).1) _).1, suffices : d' = S (mid a c) b, rw this, exact or.inl (seven5 (mid a c) b).1, apply six11a _, apply hd.2.trans, suffices : eqd a b (S (mid a c) a) (S (mid a c) b), simpa [(mid_to_Sa a c)] using this, exact (seven13 (mid a c) a b), apply eleven15b h.2.2.1 h.2.2.1 (eqa.refl h1.2.2.2.1 h1.2.2.1) (side.refla (four10 h.2.2.1).2.1), apply h1.symm.flip.trans, simpa [mid_to_Sa a c, mid_to_Sb a c] using (eleven12 (mid a c) h1.2.1 h1.1), rw six17, exact ((nine8 h.symm).1 ((nine1 h.1 (or.inr (or.inl (ten1 a c).1.symm)) h.2.1).symm)).symm end theorem twelve22 {a b c d p : point} : sided p a c β†’ side (l p a) b d β†’ (par (l a b) (l c d) ↔ eqa b a p d c p) := begin intros h h1, generalize hp : mid p a = q, replace hp : p = S q a, rw ←hp, exact (mid_to_Sb p a).symm, subst p, have h2 := eleven12 q (six26 (nine11 h1).2.1).2.1.symm h.1.symm, rw seven7 at h2, replace h2 := eleven10 h2 (six5 h2.1) (six5 h2.2.1) (six5 h2.2.2.1) h.symm, have h3 := par_of_S q (six26 (nine11 h1).2.1).2.1, have h4 : Bl (S q b) (l (S q a) c) d, exact (six16a h) β–Έ ((nine8 (nine1 (nine11 h1).1 (or.inr (or.inl (seven5 q a).1)) (nine11 h1).2.1)).2 h1).symm, exact ⟨λ h5, h2.trans ((twelve21 h4).1 (h3.symm.trans h5)), Ξ» h5, h3.trans ((twelve21 h4).2 (h2.symm.trans h5))⟩ end theorem twelve23 {a b c : point} : Β¬col a b c β†’ βˆƒ b' c', Bl b (l a c) b' ∧ Bl c (l a b) c' ∧ B b' a c' ∧ eqa a b c b a c' ∧ eqa a c b c a b' := begin intro h, have h1 := nine1 (six14 (six26 h).2.2) (or.inr (or.inl (ten1 a c).1.symm)) (four10 h).1, have h2 := nine1 (six14 (six26 h).1) (or.inr (or.inl (ten1 a b).1.symm)) h, have h3 := eleven12 (mid a b) (six26 h).1 (six26 h).2.1.symm, have h4 := eleven12 (mid a c) (six26 h).2.2 (six26 h).2.1, simp at h3 h4, refine ⟨S (mid a c) b, S (mid a b) c, h1, h2, _, h3, h4⟩, have h5 : col a (S (mid a c) b) (S (mid a b) c), apply twelve3, rw six17 at h1 h2, suffices : par (l b c) (l a (S (mid a c) b)), exact this.symm.trans ((twelve21 h2).2 h3.flip), exact six17 c b β–Έ ((twelve21 h1).2 h4.flip), apply ((nine18 h2.1 (six17a a b) (four11 h5).2.2.1).1 _).1, apply (nine8 h2).2 _, apply nine15 _ (ten1 a c).1 (seven5 (mid a c) b).1, intro h_1, apply h, rw ←mid_to_Sa a c, exact (seven24 h2.1 h_1).1 (six17a a b) end end Euclidean_plane
Social picture sharing website for pet and animal pictures. Currently growing 100-150 members/day. As of 7th January 2014 we have 6,504 members. There have been 15,271 pictures uploaded onto our website. Since launch we have seen 15,940 unique website visits, 32,045 total visits. There have been 113,569 total page views. Stats above are based on time of writing this, 7th January 2014, below is a more up to date screenshot. The investment would allow our main development team to continue full time and also outsource the development of an IOS application. * Steps to encourage users to complete profile. CEO Elliot Thomas, CTO Steve Tozer & Head of Development Chris Edwards to work full time on Fuzmo. Outsourcing of IOS application to highly experienced development team. Office space located within Tech Hub, Swansea. Dedicated Web & Database servers, backup servers and two DNS/Name servers. In the case of over-funding, another developer shall be hired.
Comfortable Modern Sofa Inviting This Ultra Set Includes A For 3 | Ssmounttemple.com gus modern sofas comfortable. modern comfortable sofas uk. comfortable modern sleeper sofa.
State Before: a b c : Int h : c ≀ a + b ⊒ -a ≀ b - c State After: a b c : Int h✝ : c ≀ a + b h : -a ≀ -c + b ⊒ -a ≀ b - c Tactic: have h := Int.le_neg_add_of_add_le (Int.sub_left_le_of_le_add h) State Before: a b c : Int h✝ : c ≀ a + b h : -a ≀ -c + b ⊒ -a ≀ b - c State After: no goals Tactic: rwa [Int.add_comm] at h
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ /** * Framework for testing features from the analysis phase of compiler. */ #include <test/libsolidity/AnalysisFramework.h> #include <libsolidity/interface/CompilerStack.h> #include <libsolidity/interface/SourceReferenceFormatter.h> #include <libsolidity/ast/AST.h> #include <libsolidity/parsing/Scanner.h> #include <libdevcore/SHA3.h> #include <boost/test/unit_test.hpp> using namespace std; using namespace dev; using namespace dev::solidity; using namespace dev::solidity::test; pair<SourceUnit const*, shared_ptr<Error const>> AnalysisFramework::parseAnalyseAndReturnError( string const& _source, bool _reportWarnings, bool _insertVersionPragma, bool _allowMultipleErrors ) { m_compiler.reset(); m_compiler.addSource("", _insertVersionPragma ? "pragma solidity >=0.0;\n" + _source : _source); if (!m_compiler.parse()) { BOOST_ERROR("Parsing contract failed in analysis test suite:" + formatErrors()); } m_compiler.analyze(); std::shared_ptr<Error const> firstError; for (auto const& currentError: m_compiler.errors()) { solAssert(currentError->comment(), ""); if (currentError->type() == Error::Type::Warning) { bool ignoreWarning = false; for (auto const& filter: m_warningsToFilter) if (currentError->comment()->find(filter) == 0) { ignoreWarning = true; break; } if (ignoreWarning) continue; } if (_reportWarnings || (currentError->type() != Error::Type::Warning)) { if (firstError && !_allowMultipleErrors) { BOOST_FAIL("Multiple errors found: " + formatErrors()); } if (!firstError) firstError = currentError; } } return make_pair(&m_compiler.ast(), firstError); } SourceUnit const* AnalysisFramework::parseAndAnalyse(string const& _source) { auto sourceAndError = parseAnalyseAndReturnError(_source); BOOST_REQUIRE(!!sourceAndError.first); string message; if (sourceAndError.second) message = "Unexpected error: " + formatError(*sourceAndError.second); BOOST_REQUIRE_MESSAGE(!sourceAndError.second, message); return sourceAndError.first; } bool AnalysisFramework::success(string const& _source) { return !parseAnalyseAndReturnError(_source).second; } Error AnalysisFramework::expectError(std::string const& _source, bool _warning, bool _allowMultiple) { auto sourceAndError = parseAnalyseAndReturnError(_source, _warning, true, _allowMultiple); BOOST_REQUIRE(!!sourceAndError.second); BOOST_REQUIRE_MESSAGE(!!sourceAndError.first, "Expected error, but no error happened."); return *sourceAndError.second; } string AnalysisFramework::formatErrors() { string message; for (auto const& error: m_compiler.errors()) message += formatError(*error); return message; } string AnalysisFramework::formatError(Error const& _error) { return SourceReferenceFormatter::formatExceptionInformation( _error, (_error.type() == Error::Type::Warning) ? "Warning" : "Error", [&](std::string const& _sourceName) -> solidity::Scanner const& { return m_compiler.scanner(_sourceName); } ); } ContractDefinition const* AnalysisFramework::retrieveContractByName(SourceUnit const& _source, string const& _name) { ContractDefinition* contract = nullptr; for (shared_ptr<ASTNode> const& node: _source.nodes()) if ((contract = dynamic_cast<ContractDefinition*>(node.get())) && contract->name() == _name) return contract; return nullptr; } FunctionTypePointer AnalysisFramework::retrieveFunctionBySignature( ContractDefinition const& _contract, std::string const& _signature ) { FixedHash<4> hash(dev::keccak256(_signature)); return _contract.interfaceFunctions()[hash]; }
||| There are different flavours of induction-recursion. This is the one ||| introduced in Dybjer and Setzer's paper: ||| Indexed induction-recursion module Data.InductionRecursion.DybjerSetzer public export data Code : (input : sort -> Type) -> (output : Type) -> Type where Yield : output -> Code input output Store : (payload : Type) -> (payload -> Code input output) -> Code input output Branch : (label : Type) -> (toSort : label -> sort) -> (((l : label) -> input (toSort l)) -> Code input output) -> Code input output public export DecodeType : Code input output -> (x : sort -> Type) -> (f : {s : sort} -> x s -> input s) -> Type DecodeType (Yield _) x f = () DecodeType (Store payload k) x f = (v : payload ** DecodeType (k v) x f) DecodeType (Branch label toSort k) x f = (r : ((l : label) -> x (toSort l)) ** DecodeType (k (\ l => f (r l))) x f) public export DecodeOutput : (c : Code input output) -> (x : Lazy (sort -> Type)) -> (f : {s : sort} -> x s -> input s) -> DecodeType c x f -> output DecodeOutput (Yield o) x f _ = o DecodeOutput (Store p k) x f (v ** d) = DecodeOutput (k v) x f d DecodeOutput (Branch l s k) x f (r ** d) = DecodeOutput (k (\ l => f (r l))) x f d mutual public export data Mu : (f : (s : sort) -> Code input (input s)) -> (s : sort) -> Type where MkMu : {f : (s : sort) -> Code input (input s)} -> {s : sort} -> DecodeType (f s) (Mu f) Decode -> Mu {input} f s public export Decode : {f : (s : sort) -> Code input (input s)} -> {s : sort} -> Mu {input} f s -> input s Decode (MkMu d) = DecodeOutput (f s) (Mu f) (\ d => assert_total (Decode d)) d public export bind : Code i o -> (o -> Code i o') -> Code i o' bind (Yield v) f = f v bind (Store p k) f = Store p (\ v => bind (k v) f) bind (Branch l s k) f = Branch l s (\ r => bind (k r) f) public export Functor (Code i) where map f v = bind v (Yield . f) public export Applicative (Code i) where pure = Yield cf <*> co = bind cf (\ f => map (f $) co) public export Monad (Code i) where (>>=) = bind
State Before: u : Lean.Level R : Type u_1 Ξ± : Q(Type u) sΞ± : Q(CommSemiring Β«$Ξ±Β») inst✝ : CommSemiring R a : R k : β„• b c : R x✝¹ : a ^ k = b x✝ : b * b = c ⊒ a ^ Nat.mul 2 k = c State After: u : Lean.Level R : Type u_1 Ξ± : Q(Type u) sΞ± : Q(CommSemiring Β«$Ξ±Β») inst✝ : CommSemiring R a : R k : β„• ⊒ a ^ Nat.mul 2 k = a ^ k * a ^ k Tactic: subst_vars State Before: u : Lean.Level R : Type u_1 Ξ± : Q(Type u) sΞ± : Q(CommSemiring Β«$Ξ±Β») inst✝ : CommSemiring R a : R k : β„• ⊒ a ^ Nat.mul 2 k = a ^ k * a ^ k State After: no goals Tactic: simp [Nat.succ_mul, pow_add]
text \<open> Version 0.5, last changed 2018-03-28 (C) fovefi ltd, www.fovefi.co (author: Lukas Bulwahn [[email protected]], comments by Manfred Kerber [[email protected]]) Dually licenced under Creative Commons Attribution (CC-BY) 4.0 [https://creativecommons.org/licenses/by/4.0/] ISC License (1-clause BSD License) [https://www.isc.org/downloads/software-support-policy/isc-license/] See LICENSE files for details. (Rationale for this dual licence: http://arxiv.org/abs/1107.3212) In the following, an executable definition of the percentile function is given that is close to the one used in OpenSIMM, a system with a standard implementation for the computation of risk. \<close> theory Percentile_Code imports Percentile begin section \<open>Code Generation of Percentile\<close> paragraph \<open>The percentile definition close to the Java implementation\<close> text \<open> In the Java code follows a check that the level is below 1 - 1/(2*size). * If not, it throws an exception. In the Isabelle implementation (there is no exception * handling in Isabelle), the code is underspecified, that is, no specific values will be * returned for larger values. This will be fixed in the definition of the percentile function * in the next section. \<close> term "ceiling" find_theorems "ceiling" text \<open> An integer greater equal 0 considered as a real number is the same as the integer first considered * as a natural number and this then considered as a real number. \<close> lemma real_of_int: assumes "0 \<le> i" shows "real_of_int i = real (nat i)" by (simp add: assms) text \<open> The value of the minimum of the domain of equidistant point is determined. \<close> lemma Min_equidistant_points_on_unit_interval_of_bounded: fixes x :: real assumes "ys \<noteq> []" assumes "1 / (2 * length ys) < x" assumes "x \<le> 1 - 1 / (2 * length ys)" shows "Min {x' \<in> dom (equidistant_points_on_unit_interval_of ys). x \<le> x'} = (ceiling (length ys * x - 0.5) + 0.5) / length ys" (is "Min ?A = ?expr") proof (rule Min_eqI) text \<open>let ?A = "{x' \<in> dom (equidistant_points_on_unit_interval_of ys). x \<le> x'}"\<close> show "finite ?A" by simp show "?expr \<le> y" if "y \<in> ?A" for y proof - from that \<open>ys \<noteq> []\<close> obtain n where "y = (real n + 1 / 2) / real (length ys)" and "x \<le> y" unfolding equidistant_points_on_unit_interval_of_def apply auto done obtain i where "i = int n" by auto from this \<open>y = _\<close> have y: "y = (real_of_int i + 1 / 2) / real (length ys)" by simp have "i \<ge> ceiling (length ys * x - 0.5)" proof - have "x \<le> (real_of_int i + 1 / 2) / real (length ys)" using \<open>x \<le> y\<close> y by blast from this have "length ys * x \<le> (real_of_int i + 1 / 2)" apply - apply (frule mult_left_mono[where c="real (length ys)"]) apply simp by (simp add: assms(1)) find_theorems "_ * _ \<le> _ * _" from this have "length ys * x - 1 / 2 \<le> real_of_int i" by linarith from this show ?thesis by (simp add: ceiling_le) qed from this y have "y \<ge> (real_of_int (ceiling (length ys * x - 0.5)) + 1 / 2) / real (length ys)" apply simp find_theorems "_ / _ \<le> _ / _" apply (rule divide_right_mono) apply simp apply simp done from this show ?thesis by simp qed show "?expr \<in> ?A" proof - from assms have "0 \<le> real (length ys) * x - 1 / 2" apply auto by (simp add: Groups.mult_ac(2) divide_less_eq) from this have "0 \<le> \<lceil>real (length ys) * x - 1 / 2\<rceil>" by simp from this have a: "real_of_int \<lceil>real (length ys) * x - 1 / 2\<rceil> = real (nat \<lceil>real (length ys) * x - 1 / 2\<rceil>)" by simp have b: "nat \<lceil>real (length ys) * x - 1 / 2\<rceil> \<in> {0..<length ys}" proof - have "real (length ys) * x - 1 / 2 \<le> (length ys - 1)" proof - have "real (length ys) * x - 1 / 2 \<le> real (length ys) * (1 - 1 / real (2 * length ys)) - 1 / 2" using assms(1, 3) by simp also have "\<dots> = real (length ys) - 1" apply auto apply (subst right_diff_distrib) apply simp by (simp add: assms(1)) also have "\<dots> = real (length ys - 1)" by (metis One_nat_def Suc_pred assms(1) diff_Suc_Suc diff_is_0_eq length_greater_0_conv of_nat_1 of_nat_diff zero_diff) finally show ?thesis . qed text \<open>have "\<lceil>real (length ys) * x - 1 / 2\<rceil> \<ge> 0" s_orry\<close> from this have a: "\<lceil>real (length ys) * x - 1 / 2\<rceil> \<le> \<lceil>real (length ys - 1)\<rceil>" using ceiling_mono by blast have "\<lceil>real (length ys - 1)\<rceil> = int (length ys - 1)" by simp from a this have "nat \<lceil>real (length ys) * x - 1 / 2\<rceil> < length ys" by (smt assms(1) int_nat_eq length_greater_0_conv nat_less_le of_nat_0_less_iff of_nat_1 of_nat_diff of_nat_less_imp_less zero_less_diff) from this show ?thesis apply auto done qed have "(real_of_int \<lceil>real (length ys) * x - 5 / 10\<rceil> + 5 / 10) / real (length ys) \<in> dom (equidistant_points_on_unit_interval_of ys)" unfolding dom_equidistant_points_on_unit_interval_of apply auto apply (subst a) apply (rule image_eqI) apply (rule refl) apply (rule b) done find_theorems "dom (equidistant_points_on_unit_interval_of _)" moreover have "x \<le> (real_of_int \<lceil>real (length ys) * x - 5 / 10\<rceil> + 5 / 10) / real (length ys)" proof - have "real (length ys) > 0" (* only need \<ge> *) by (simp add: assms) have a: "real (length ys) * x - 5 / 10 \<le> real_of_int \<lceil>real (length ys) * x - 5 / 10\<rceil>" by linarith have "x \<le> ((real (length ys) * x - 5 / 10) + 5 / 10) / real (length ys)" using \<open>real (length ys) > 0\<close> by auto also have "\<dots> \<le> (real_of_int \<lceil>real (length ys) * x - 5 / 10\<rceil> + 5 / 10) / real (length ys)" using \<open>real (length ys) > 0\<close> a apply - apply (rule divide_right_mono) apply linarith apply simp done finally show ?thesis . qed ultimately show ?thesis by auto qed qed text \<open> A property of the ceiling function. \<close> lemma ceiling_minus_leq: assumes "a + b \<ge> 1" shows "real_of_int \<lceil>x - a\<rceil> - b \<le> x" using assms by linarith text \<open> Relationship between floor and ceiling (floor plus 1 is less equal ceiling). \<close> lemma floor_leq_ceiling: fixes x :: real assumes "x \<notin> real_of_int ` UNIV" shows "1 + real_of_int (floor x) \<le> real_of_int (ceiling x)" using assms by (smt UNIV_I ceiling_correct image_eqI int_less_real_le le_floor_iff) text \<open> If an i < y for two integers then i \<le> y - 1 (when converted to real).\<close> lemma less_to_leq: fixes y :: real assumes "real i < y" assumes "y \<in> real_of_int ` UNIV" shows "real i \<le> y - 1" proof - from assms(2) obtain j where "y = real_of_int j" apply auto done obtain k where "j = int k" by (smt \<open>y = real_of_int j\<close> assms(1) int_less_real_le nat_0_le of_int_1 of_nat_0_le_iff) from this \<open>y = _\<close> assms(1) show ?thesis by auto qed text \<open> The value of the maximum of the domain of equidistant point is determined. \<close> lemma Max_equidistant_points_on_unit_interval_of_bounded: fixes x :: real assumes "ys \<noteq> []" assumes "1 / (2 * length ys) < x" "x \<le> 1 - 1 / (2 * length ys)" shows "Max {x' \<in> dom (equidistant_points_on_unit_interval_of ys). x' < x} = (ceiling (length ys * x - 0.5) - 0.5) / length ys" (is "_ = ?expr") proof - let ?A = "{x' \<in> (\<lambda>x. (1 / length ys) * (x + 0.5)) ` {0..<length ys}. x' < x}" have "Max ?A = ?expr" find_theorems "_ ` _" "Max" proof (rule Max_eqI) show "finite ?A" by simp show "y \<le> ?expr" if "y \<in> ?A" for y proof - show ?thesis proof (cases "real (length ys) * x - 1 / 2 \<in> range real_of_int") case True from that obtain i where "i \<in> {0..<length ys}" and y: "y = 1 / real (length ys) * (real i + 5 / 10)" and "y < x" by auto have "(real i + 5 / 10) < real (length ys) * x" by (metis \<open>y < x\<close> assms(1) divide_less_eq length_greater_0_conv mult.commute mult_numeral_1 numeral_One of_nat_0_less_iff times_divide_eq_right y) from this have "real i < real (length ys) * x - 0.5" by linarith from this have "real i \<le> real (length ys) * x - 1.5" apply - apply (frule less_to_leq) apply (simp add: True) by linarith from this have "(real i + 5 / 10) \<le> real (length ys) * x - 1" apply simp done have "1 / real (length ys) > 0" by (simp add: assms(1)) from this assms y have y2: "y \<le> 1 / real (length ys) * (real (length ys) * x - 1)" using \<open>real i + 5 / 10 \<le> real (length ys) * x - 1\<close> real_mult_le_cancel_iff2 by blast have "real (length ys) * x - 1 / 2 \<le> real_of_int \<lceil>real (length ys) * x - 1 / 2\<rceil>" by simp from this have "real (length ys) * x - 1 \<le> real_of_int \<lceil>real (length ys) * x - 1 / 2\<rceil> - 1 / 2" proof - have "real (length ys) * x - 1 = (real (length ys) * x - 1 / 2) - 1 / 2" by simp also have "\<dots> \<le> real_of_int \<lceil>real (length ys) * x - 1 / 2\<rceil> - 1 / 2" by linarith finally show ?thesis . qed from this y2 show ?thesis apply auto find_theorems "?a \<le> ?b \<Longrightarrow> ?b \<le> ?c \<Longrightarrow> ?a \<le> ?c" apply (rule order.trans) apply assumption apply (rule divide_right_mono) apply simp apply simp done find_theorems "_ / _ \<le> _ / _" next case False then show ?thesis proof - have "y \<le> 1 / real (length ys) * (real_of_int \<lfloor>real (length ys) * x - 5 / 10\<rfloor> + 5 / 10)" proof - from that obtain i where "i \<in> {0..<length ys}" and "y = 1 / real (length ys) * (real i + 5 / 10)" and "y \<le> x" by auto have "i \<le> \<lfloor>real (length ys) * x - 5 / 10\<rfloor>" proof - have a: "1 / real (length ys) * (real i + 5 / 10) \<le> x" using \<open>y = _\<close> \<open>y \<le> x\<close> by blast have "(real i + 5 / 10) \<le> real (length ys) * x" proof - have "(real i + 5 / 10) = real (length ys) * (1 / real (length ys) * (real i + 5 / 10))" by (simp add: assms(1)) also have "\<dots> \<le> real (length ys) * x" using a mult_left_mono of_nat_0_le_iff by blast finally show ?thesis . qed from this have "real i \<le> real (length ys) * x - 5 / 10" by linarith from this show ?thesis by linarith qed from this \<open>y = _\<close> show ?thesis proof - have "real (length ys) > 0" by (simp add: assms(1)) from \<open>i \<le> floor _\<close> have "(real i + 5 / 10) \<le> real_of_int \<lfloor>real (length ys) * x - 5 / 10\<rfloor> + 5 / 10" by linarith from this \<open>y = _\<close> \<open>real (length ys) > 0\<close> show ?thesis using real_mult_le_cancel_iff2 by fastforce qed qed also have "\<dots> \<le> (real_of_int \<lceil>real (length ys) * x - 5 / 10\<rceil> - 5 / 10) / real (length ys)" proof - from False have "(real_of_int \<lfloor>real (length ys) * x - 5 / 10\<rfloor> + 5 / 10) \<le> (real_of_int \<lceil>real (length ys) * x - 5 / 10\<rceil> - 5 / 10)" apply simp apply (rule floor_leq_ceiling) apply assumption done from this show ?thesis apply simp apply (rule divide_right_mono) apply simp apply simp done qed finally show ?thesis . qed qed qed show "?expr \<in> ?A" proof - have "?expr \<in> (\<lambda>x. 1 / real (length ys) * (real x + 5 / 10)) ` {0..<length ys}" proof have "real (length ys) * x - 1 / 2 > 0" by (metis assms(1) assms(2) diff_gt_0_iff_gt divide_divide_eq_left divide_less_eq length_greater_0_conv mult.commute of_nat_0_less_iff of_nat_mult of_nat_numeral) from this have "nat \<lceil>real (length ys) * x - 1 / 2\<rceil> \<ge> 1" by linarith from this show "(real_of_int \<lceil>real (length ys) * x - 5 / 10\<rceil> - 5 / 10) / real (length ys) = 1 / real (length ys) * (real (nat \<lceil>real (length ys) * x - 5 / 10\<rceil> - 1) + 5 / 10)" using \<open>ys \<noteq> []\<close> apply auto done have "real (length ys) \<ge> 0" by auto have "x \<le> 1" by (smt assms(3) divide_less_0_1_iff of_nat_0_le_iff) from this have "real (length ys) * x \<le> length ys" by (simp add: mult_left_le) from this \<open>real (length ys) \<ge> 0\<close> have "real (length ys) * x \<le> length ys + 1 / 2" by linarith from this have "real (length ys) * x - 1 / 2 \<le> length ys" by fastforce from this show "nat \<lceil>real (length ys) * x - 5 / 10\<rceil> - 1 \<in> {0..<length ys}" apply auto using \<open>1 \<le> nat \<lceil>real (length ys) * x - 1 / 2\<rceil>\<close> by linarith qed moreover have "?expr < x" proof - have "real_of_int \<lceil>real (length ys) * x - 5 / 10\<rceil> < real (length ys) * x + 5 / 10" by linarith then have "real_of_int \<lceil>real (length ys) * x - 5 / 10\<rceil> < x * real (length ys) + 5 / 10" by (simp add: mult.commute) have "real_of_int \<lceil>real (length ys) * x - 5 / 10\<rceil> - 5 / 10 < x * real (length ys)" using \<open>real_of_int \<lceil>real (length ys) * x - 5 / 10\<rceil> < x * real (length ys) + 5 / 10\<close> by linarith from this show "(real_of_int \<lceil>real (length ys) * x - 5 / 10\<rceil> - 5 / 10) / real (length ys) < x" apply auto by (simp add: assms(1) divide_less_eq) qed ultimately show ?thesis by auto qed qed from this show ?thesis unfolding equidistant_points_on_unit_interval_of_def by simp qed text \<open> The lemma determines the values of equidistant point on the unit interval. \<close> lemma equidistant_points_on_unit_interval_of_eq_nth2: fixes i :: int assumes "0 \<le> i" "nat i < length ys" shows "the (equidistant_points_on_unit_interval_of ys ((real_of_int i + 5 / 10) / size ys)) = ys ! (nat i)" proof - let ?xs = "map (\<lambda>x. (real x + 1 / 2) / real (length ys)) [0..<length ys]" have "distinct ?xs" by (auto intro!: inj_onI simp add: distinct_map) have eq: "(real_of_int i + 1 / 2) / real (length ys) = ?xs ! nat i" using assms by auto show ?thesis unfolding equidistant_points_on_unit_interval_of_def apply simp apply (subst eq) thm map_of_zip_nth apply (subst map_of_zip_nth) apply simp apply (rule \<open>distinct ?xs\<close>) apply (rule assms) apply simp done qed text \<open> The lemma gives an alternative characterization of the values of equidistant point on the unit interval. \<close> lemma equidistant_points_on_unit_interval_of_eq_nth1: fixes i :: int assumes "1 \<le> i" "i \<le> length ys" shows "the (equidistant_points_on_unit_interval_of ys ((real_of_int i - 5 / 10) / size ys)) = ys ! nat (i - 1)" proof - (* todo: size ys = real (length ys); which is better to write down? *) let ?f = "\<lambda>x. the (equidistant_points_on_unit_interval_of ys (x / size ys))" have "?f (real_of_int i - 5 / 10) = ?f (real_of_int (i - 1) + 5 / 10)" by force also have "\<dots> = ys ! nat (i - 1)" using assms by (simp only: equidistant_points_on_unit_interval_of_eq_nth2) finally show ?thesis . qed text \<open> The definition contains executable version of the percentile function which is close to the * Java implementation in the OpenSIMM implementation. \<close> definition percentile_impl :: "real list \<Rightarrow> real \<Rightarrow> real" where "percentile_impl values level_orig = (let level = level_orig - epsilon; (size :: real) = (real (length values)); (sorted :: (real list)) = sort values; i = (ceiling (size * level - 0.5)); (lower :: real) = (i - 0.5) / size; (upper ::real) = (i + 0.5) / size; (lower_value :: real) = sorted ! (nat (i-1)); (upper_value :: real) = sorted ! (nat i) in lower_value + (level - lower) * (upper_value - lower_value) / (upper - lower))" lemma percentile_impl_var: "percentile_impl values level = (let (size :: real) = (real (length values)); (sorted :: (real list)) = sort values; i = (ceiling (size * (level - epsilon) - 0.5)); (lower :: real) = (i - 0.5) / size; (upper ::real) = (i + 0.5) / size; (lower_value :: real) = sorted ! (nat (i-1)); (upper_value :: real) = sorted ! (nat i) in lower_value + ((level - epsilon) - lower) * (upper_value - lower_value) / (upper - lower))" by (metis percentile_impl_def) text \<open> The theorem states the equivalence of the abstract definition of the percentile function from * the Percentile theory and the computational version in the standard interval. \<close> theorem percentile_java_equiv: assumes "values \<noteq> []" assumes "1 / real (2 * length values) < (level - epsilon)" (* todo: lesseq instead of less *) assumes "(level - epsilon) \<le> 1 - 1 / real (2 * length values)" shows "Percentile.percentile values level = percentile_impl values level" proof - from assms(2) have "(level - epsilon) \<noteq> 1 / real (2 * length values)" by linarith let ?def = "(let p = equidistant_points_on_unit_interval_of (sort values); (x1, x2) = (Max {x' \<in> dom p. x' < (level - epsilon)}, Min {x' \<in> dom p. (level - epsilon) \<le> x'}); (y1, y2) = (the (p x1), the (p x2)) in linear (x1, y1) (x2, y2) (level - epsilon))" { fix size sorted i lower upper lower_value upper_value assume "size = real (length values)" assume "sorted = sort values" assume "i = \<lceil>size * (level - epsilon) - 5 / 10\<rceil>" assume "lower = (real_of_int i - 5 / 10) / size" assume "upper = (real_of_int i + 5 / 10) / size" assume "lower_value = sorted ! nat (i - 1)" assume "upper_value = sorted ! nat i" have "length values = length sorted" and "sorted \<noteq> []" (* is this noteq Nil fact needed? *) and "length sorted > 0" using \<open>sorted = _\<close> \<open>_ \<noteq> []\<close> apply auto by (metis length_0_conv length_sort) (* todo: find a better lemma *) have "lower_value + ((level - epsilon) - lower) * (upper_value - lower_value) / (upper - lower) = linear (lower, lower_value) (upper, upper_value) (level - epsilon)" apply (subst linear_eq[symmetric]) .. also have "\<dots> = ?def" proof - have b1: "0 \<le> \<lceil>real (length sorted) * (level - epsilon) - 5 / 10\<rceil>" proof - have "- 1 / 2 \<le> real (length sorted) * (level - epsilon) - 5 / 10" apply simp by (meson assms(2) le_less_trans less_eq_real_def of_nat_0_le_iff zero_le_divide_1_iff zero_le_mult_iff) (* strange proof? *) from this show ?thesis by linarith qed have b2: "nat \<lceil>real (length sorted) * (level - epsilon) - 5 / 10\<rceil> < length sorted" proof - have "real (length sorted) * (level - epsilon) \<le> real (length sorted) - 1 / 2" proof - from assms(3) have "(level - epsilon) \<le> 1 - 1 / real (2 * length sorted)" using \<open>length values = length sorted\<close> by simp from this have "real (length sorted) * (level - epsilon) \<le> real (length sorted) * (1 - 1 / real (2 * length sorted))" using \<open>0 < length sorted\<close> by auto also have "\<dots> = real (length sorted) - 1 / 2" apply simp by (metis \<open>length values = length sorted\<close> \<open>size = real (length values)\<close> assms(1) length_0_conv mult.commute mult.right_neutral mult_cancel_left nonzero_mult_divide_mult_cancel_left of_nat_eq_iff of_nat_mult right_diff_distrib' times_divide_eq_right) finally show ?thesis . qed from this show ?thesis using b1 by linarith qed have b3: "1 \<le> \<lceil>real (length sorted) * (level - epsilon) - 5 / 10\<rceil>" proof - show ?thesis using assms(2) \<open>length _ = _\<close> \<open>length sorted > 0\<close> by (simp add: Groups.mult_ac(2) divide_less_eq) qed from b2 have b4: "\<lceil>real (length sorted) * (level - epsilon) - 5 / 10\<rceil> \<le> int (length sorted)" by simp have "Max {x' \<in> dom (equidistant_points_on_unit_interval_of sorted). x' < (level - epsilon)} = lower" using \<open>lower = _\<close> \<open>i = _\<close> \<open>size = _\<close> \<open>length values = _\<close> apply (subst Max_equidistant_points_on_unit_interval_of_bounded) prefer 4 apply simp using \<open>sorted \<noteq> []\<close> apply blast using assms(2) apply auto[1] using assms(3) by auto moreover have "Min {x' \<in> dom (equidistant_points_on_unit_interval_of sorted). (level - epsilon) \<le> x'} = upper" using \<open>upper = _\<close> \<open>i = _\<close> \<open>size = _\<close> \<open>length values = _\<close> apply (subst Min_equidistant_points_on_unit_interval_of_bounded) prefer 4 apply simp using \<open>sorted \<noteq> []\<close> apply blast using assms(2) apply auto[1] using assms(3) by auto moreover have "the (equidistant_points_on_unit_interval_of sorted lower) = lower_value" using \<open>i = _\<close> \<open>size = _\<close> \<open>lower_value = _\<close> \<open>lower = _\<close> \<open>length values = _\<close> apply (simp only:) apply (subst equidistant_points_on_unit_interval_of_eq_nth1) apply (rule b3) apply (rule b4) apply simp done moreover have "the (equidistant_points_on_unit_interval_of sorted upper) = upper_value" using \<open>i = _\<close> \<open>size = _\<close> \<open>upper_value = _\<close> \<open>upper = _\<close> \<open>length values = _\<close> apply (simp only:) apply (subst equidistant_points_on_unit_interval_of_eq_nth2) apply (rule b1) apply (rule b2) apply simp done ultimately show ?thesis using \<open>sorted = _\<close> by simp qed finally have "lower_value + ((level - epsilon) - lower) * (upper_value - lower_value) / (upper - lower) = ?def" by simp (* intermediate proof step not needed? change proof structure? *) } from this \<open>(level - epsilon) \<noteq> _\<close> show ?thesis by (simp add: percentile_alternative_pseudo_def percentile_impl_var) qed (* lemma percentile_impl_lower_bound: assumes "values \<noteq> []" assumes "1 / real (2 * length values) < level" assumes "level \<le> 1 - 1 / real (2 * length values)" shows "Min (set values) \<le> percentile_impl values level" using assms apply - apply (subst percentile_java_equiv[symmetric]) apply assumption+ apply (rule percentile_lower_bound) apply assumption apply simp done lemma percentile_impl_upper_bound: assumes "values \<noteq> []" assumes "1 / real (2 * length values) < level" assumes "level \<le> 1 - 1 / real (2 * length values)" shows "percentile_impl values level \<le> Max (set values)" using assms apply - apply (subst percentile_java_equiv[symmetric]) apply assumption+ apply (rule percentile_upper_bound) apply assumption apply simp done lemma assumes "values \<noteq> []" assumes "1 / real (2 * length values) < level" assumes "level' \<le> 1 - 1 / real (2 * length values)" assumes "level \<le> level'" shows "percentile_impl values level \<le> percentile_impl values level'" using assms apply - apply (subst percentile_java_equiv[symmetric]) apply assumption+ apply simp apply (subst percentile_java_equiv[symmetric]) apply assumption+ apply simp apply assumption+ apply (rule percentile_monotonic) apply assumption+ apply simp apply assumption+ done *) export_code percentile_impl in Scala end
Formal statement is: lemma nullhomotopic_into_contractible: assumes f: "continuous_on S f" "f ` S \<subseteq> T" and T: "contractible T" obtains c where "homotopic_with_canon (\<lambda>h. True) S T f (\<lambda>x. c)" Informal statement is: If $f$ is a continuous map from $S$ to $T$ and $T$ is contractible, then $f$ is nullhomotopic.
lemma fmeasurable_Diff_D: assumes m: "T - S \<in> fmeasurable M" "S \<in> fmeasurable M" and sub: "S \<subseteq> T" shows "T \<in> fmeasurable M"
lemma poly_induct2 [case_names 0 pCons]: assumes "P 0 0" "\<And>a p b q. P p q \<Longrightarrow> P (pCons a p) (pCons b q)" shows "P p q"
[GOAL] n a b n' a' b' : β„• H : IsFibAux n a b hn : 2 * n = n' h1 : a * (2 * b - a) = a' h2 : a * a + b * b = b' ⊒ fib n' = a' [PROOFSTEP] rw [← hn, fib_two_mul, H.1, H.2, ← h1] [GOAL] n a b n' a' b' : β„• H : IsFibAux n a b hn : 2 * n = n' h1 : a * (2 * b - a) = a' h2 : a * a + b * b = b' ⊒ fib (n' + 1) = b' [PROOFSTEP] rw [← hn, fib_two_mul_add_one, H.1, H.2, pow_two, pow_two, add_comm, h2] [GOAL] n a b n' a' b' : β„• H : IsFibAux n a b hn : 2 * n + 1 = n' h1 : a * a + b * b = a' h2 : b * (2 * a + b) = b' ⊒ fib n' = a' [PROOFSTEP] rw [← hn, fib_two_mul_add_one, H.1, H.2, pow_two, pow_two, add_comm, h1] [GOAL] n a b n' a' b' : β„• H : IsFibAux n a b hn : 2 * n + 1 = n' h1 : a * a + b * b = a' h2 : b * (2 * a + b) = b' ⊒ fib (n' + 1) = b' [PROOFSTEP] rw [← hn, fib_two_mul_add_two, H.1, H.2, h2]
\documentclass[10pt, aspectratio=169]{beamer} \usefonttheme{professionalfonts} %\usetheme{CambridgeUS} % % Choose how your presentation looks. % % For more themes, color themes and font themes, see: % http://deic.uab.es/~iblanes/beamer_gallery/index_by_theme.html % \mode<presentation> { \usetheme{default} % or try Darmstadt, Madrid, Warsaw, ... \usecolortheme{beaver} % or try albatross, beaver, crane, ... \usefonttheme{default} % or try serif, structurebold, ... \setbeamertemplate{navigation symbols}{} \setbeamertemplate{caption}[numbered] } \usepackage[english]{babel} \usepackage[utf8x]{inputenc} \usepackage{tikz} \usepackage{pgfplots} \usepackage{array} % for table column M \usepackage{makecell} % to break line within a cell \usepackage{verbatim} \usepackage{graphicx} \usepackage{epstopdf} \usepackage{amsfonts} \usepackage{xcolor} %\captionsetup{compatibility=false} %\usepackage{dsfont} \usepackage[absolute,overlay]{textpos} \usetikzlibrary{calc} \usetikzlibrary{pgfplots.fillbetween, backgrounds} \usetikzlibrary{positioning} \usetikzlibrary{arrows} \usetikzlibrary{pgfplots.groupplots} \usetikzlibrary{arrows.meta} \usetikzlibrary{plotmarks} \usepgfplotslibrary{groupplots} \pgfplotsset{compat=newest} %\pgfplotsset{plot coordinates/math parser=false} \usepackage{hyperref} \hypersetup{ colorlinks=true, linkcolor=blue, filecolor=magenta, urlcolor=cyan, } %% \def\EXTERNALIZE{1} % for externalizing figures \input{header.tex} \title[EE 264]{Sampling, Reconstruction, and DT Filtering} \author{Jose Krause Perin} \institute{Stanford University} \date{July 9, 2017} \begin{document} \begin{frame} \titlepage \end{frame} \begin{frame}{Last lecture} \begin{itemize} \item The frequency response of a system tell us how much each frequency is scaled (magnitude response), and delayed (phase response) by the system. \item Poles increase magnitude and introduce phase lag (positive group delay) \item Zeros decrease the magnitude and introduce phase lead (negative group delay) \item All-pass systems have constant magnitude response. For each pole at $e_k$, there will be a zero at the conjugate reciprocal $1/e^*_k$ \item Minimum phase systems have all zeros inside the unit circle \item Any system $H(z)$ can be decomposed into a cascade of a minimum phase system and an all-pass system $H(z) = H_{min}(z)H_{ap}(z)$ \item For minimum phase systems, the phase response is given by the Hilbert transform of the log-magnitude response. \item The phase response of a generalized linear phase systems is an affine function of $\omega$ \item FIR systems are linear phase as long as their impulse response is either even or odd symmetric \item Linear phase rational IIR systems do not exist \end{itemize} \end{frame} % \section{Outline} \begin{frame}{Today's lecture} \begin{enumerate} \item Sampling (continuous-to-discrete time conversion) \item Reconstruction (discrete-to-continuous time conversion) \item Discrete-time filtering of continuous-time signals \end{enumerate} \end{frame} % \section{Sampling} \begin{frame}<handout:0>{Digital processing of analog signals} \begin{block}{Typical system} \vspace{-0.7cm} \begin{center} \resizebox{0.7\linewidth}{!}{\input{figs/adc-dsp-dac.tex}} \end{center} \end{block} \vspace{-0.5cm} \begin{block}{Analog-to-digital converter (ADC)} \begin{itemize} \item Performs filtering, sampling, and quantization \item Sampling rate may be of tens of kHz (audio processing), or it may be of tens of GHz (optical communications) \end{itemize} \end{block} \vspace{-0.3cm} \begin{block}{Digital signal processor} \begin{itemize} \itemsep 0pt \item Performs some operation e.g., filtering, FFT, etc \item May be implemented on PCs with 64-bit floating-point precision, or on ASICs with limited arithmetic precision (e.g., 6 bits). \end{itemize} \end{block} \vspace{-0.3cm} \begin{block}{Digital-to-analog converter (DAC)} \begin{itemize} \item Performs quantization and reconstruction (filtering) \item Sampling rate could be similar to ADC \end{itemize} \end{block} \end{frame} \begin{frame}{Digital processing of analog signals} \begin{block}{Typical system} \vspace{-0.7cm} \begin{center} \resizebox{0.7\linewidth}{!}{\input{figs/adc-dsp-dac.tex}} \end{center} \end{block} \vspace{-0.5cm} \begin{block}{\textbf{Analog-to-digital converter (ADC)}} \begin{itemize} \item Performs filtering, sampling, and quantization \item Sampling rate may be of tens of kHz (audio processing), or it may be of tens of GHz (optical communications) \end{itemize} \end{block} \vspace{-0.3cm} \begin{block}{Digital signal processor} \begin{itemize} \itemsep 0pt \item Performs some operation e.g., filtering, FFT, etc \item May be implemented on PCs with 64-bit floating-point precision, or on ASICs with limited arithmetic precision (e.g., 6 bits). \end{itemize} \end{block} \vspace{-0.3cm} \begin{block}{Digital-to-analog converter (DAC)} \begin{itemize} \item Performs quantization and reconstruction (filtering) \item Sampling rate could be similar to ADC \end{itemize} \end{block} \end{frame} \begin{frame}{Analog-to-digital conversion} \begin{block}{In practice} Example of successive-approximation analog-to-digital converter (SA-ADC) \begin{figure} \centering \includegraphics[width=\textwidth]{figs/ADC_EE102B.png}\\ {\tiny \color{gray} Taken from the lecture notes of EE 102B by Prof. Joseph Kahn} \end{figure} \end{block} {\small More about ADCs in EE 315: Analog-Digital Interface Circuits.} \end{frame} % \begin{frame}{Analog-to-digital conversion} \begin{block}{In this class} We'll model the ADC as an ideal continuous-to-discrete (C-to-D) time converter. \begin{center} \begin{tikzpicture}[->, >=stealth, shorten >= 0pt, draw=black!50, node distance=3cm, font=\sffamily] \tikzstyle{node}=[circle,fill=black,minimum size=2pt,inner sep=0pt] \tikzstyle{block}=[draw=black,rectangle,fill=none,minimum size=1.5cm, inner sep=0pt] \tikzstyle{annot} = [] \node[node] (xc) {}; \node[block, right of=xc, align=center, text width=2cm] (DSP) {C-to-D Converter}; \coordinate[right of=DSP] (yc) {}; \path (xc) edge (DSP); \path (DSP) edge (yc); \node[above = 0mm of xc, text width = 2cm, align=center] {$x_c(t)$}; \node[below = 0mm of xc, text width = 2cm, align=center] {$X_c(j\Omega)$}; \node[above = 0mm of yc, text width = 3cm, align=center] {$x[n] = x_c(nT)$}; \node[below = 0mm of yc, text width = 2cm, align=center] {$X(e^{j\omega}), X(e^{j\Omega T})$}; \end{tikzpicture} \end{center} \end{block} \textbf{Notation:} \\ $X_c(j\Omega)$ denotes the Fourier transform of the continuous-time signal $x_c(t)$, where $\Omega$ is the continuous-time frequency. $X(e^{j\omega})$ denotes the discrete-time Fourier transform of a discrete-time signal $x[n]$, where $\omega$ is the normalized frequency. \end{frame} % \begin{frame}{Continuous-to-discrete time conversion} The C-to-D converter simply samples the continuous-time signal every $T$ seconds, where $T$ is the \textbf{sampling period}. \begin{center} \resizebox{0.45\linewidth}{!}{\input{figs/ct_signal_sampled.tex}} \end{center} \pause \textbf{Question:} How are $x_c(t)$ and $x[n]$ related in the frequency domain? That is, how to obtain the discrete-time Fourier transform $X(e^{j\omega})$ from the continuous-time Fourier transform $X_c(j\Omega)$? \end{frame} % \begin{frame}{Continuous-to-discrete time conversion} \textbf{Impulse sampling interpretation:}\\ We can think of the C-to-D converter as multiplication by an \textbf{impulse train}, followed by an impulse-to-sequence converter. This representation is purely for mathematical convenience. \begin{center} \resizebox{\linewidth}{!}{\input{figs/c-to-d_impulse_train.tex}} \end{center} \end{frame} \begin{frame}{Impulse sampling example} \vspace{-0.4cm} \begin{center} \resizebox{0.75\linewidth}{!}{\input{figs/sampling_example_time_domain.tex}} \end{center} \end{frame} \begin{frame}{Continuous-to-discrete time conversion} \textbf{Question:} How to obtain the discrete-time Fourier transform $X(e^{j\omega})$ from the continuous-time Fourier transform $X_c(j\Omega)$? \begin{center} \resizebox{0.8\linewidth}{!}{\input{figs/c-to-d_impulse_train.tex}} \end{center} We'll calculate the continuous-time (CT) Fourier transform of $x_s(t)$ in two different ways. First, we'll calculate $X_s(j\Omega) = \frac{1}{2\pi}X_c(j\Omega)\ast S(j\Omega)$. Then, we'll calculate $X_s(j\Omega) = \mathcal{F}\{x_s(t)\}$. We'll use these two equations of $X_s(j\Omega)$ to obtain an equation for $X(e^{j\omega})$, the DTFT of $x[n]$. \end{frame} % \begin{frame} Starting with $X_s(j\Omega) = \frac{1}{2\pi}X_c(j\Omega)\ast S(j\Omega)$, recall that the Fourier transform of the impulse train is given by \begin{equation*} s(t) = \sum_{n=-\infty}^\infty \delta(t-nT) \Longleftrightarrow S(j\Omega) = \sum_{k=-\infty}^\infty \frac{2\pi}{T}\delta\Big(\Omega-k\frac{2\pi}{T}\Big) \end{equation*} Now we can calculate $X_s(j\Omega)$: \begin{align} \nonumber X_s(j\Omega) &= \frac{1}{2\pi}X_c(j\Omega) \ast S(j\Omega) \\ \nonumber X_s(j\Omega) &= \frac{1}{2\pi}X_c(j\Omega) \ast \bigg(\sum_{k=-\infty}^\infty\frac{2\pi}{T}\delta\Big(\Omega-k\frac{2\pi}{T}\Big)\bigg) \\ &\tikz[baseline]{ \node[fill=blue!20,anchor=base] (t1) {$X_s(j\Omega) = \displaystyle\sum_{k=-\infty}^\infty\frac{1}{T}X_c\Big(j\Big(\Omega-k\frac{2\pi}{T}\Big)\Big)$};} \label{eq:Xs1} \end{align} Note that $X_s(j\Omega)$ is equal to $X_c(j\Omega)$ scaled by $1/T$ and repeated every $2\pi/T$, which we define as the \textbf{sampling frequency} $\Omega_s \equiv 2\pi/T$ \end{frame} % \begin{frame} Now let's calculate $X_s(j\Omega) = \mathcal{F}\{x_s(t)\}$, where $x_s(t) = x_c(t)\cdot s(t)$: \begin{align} \nonumber X_s(j\Omega) &= \mathcal{F}\{x_c(t)\cdot s(t)\} = \mathcal{F}\bigg\lbrace \sum_{n=-\infty}^{\infty} x_c(nT)\delta(t-nT) \bigg\rbrace \\ \nonumber &= \mathcal{F}\bigg\lbrace \sum_{n=-\infty}^{\infty} x[n]\delta(t-nT) \bigg\rbrace \\ \nonumber &= \int_{-\infty}^{\infty}\sum_{n=-\infty}^{\infty} x[n]\delta(t-nT)e^{-j\Omega t}dt \tag{CT Fourier transform} \\ \nonumber &= \sum_{n=-\infty}^{\infty} x[n]\int_{-\infty}^{\infty}\delta(t-nT)e^{-j\Omega t}dt \\ \nonumber &= \sum_{n=-\infty}^{\infty} x[n]e^{-jn\Omega T} \tag{recall: $X(e^{j\omega}) \equiv \sum_{n=-\infty}^{\infty} x[n]e^{-jn\omega}$} \\ &\tikz[baseline]{ \node[fill=blue!20,anchor=base] (t1) {$X_s(j\Omega) = X(e^{j\omega})\Big|_{\omega=\Omega T}$};} \label{eq:Xs2} \end{align} $X_s(j\Omega)$ is equal to $X(e^{j\omega})$ evaluated at $\omega = \Omega T$, or equivalently $X(e^{j\omega})$ is equal to $X_s(j\Omega)$ evaluated at $\Omega = \omega/T$. \end{frame} % \begin{frame} Substituting \eqref{eq:Xs1} in \eqref{eq:Xs2}: \begin{equation*} X(e^{j\Omega T}) = \frac{1}{T}\sum_{k=-\infty}^{\infty} X_c\Big(j\Big(\Omega - k\frac{2\pi}{T}\Big)\Big), \end{equation*} where we used the relation $\omega = \Omega T$. \begin{itemize} \item $T$ is the \textbf{sampling period}, and $\Omega_s = \frac{2\pi}{T}$ is the \textbf{sampling frequency} \item This equation shows that in discrete time ($\omega = \Omega T$) replicas of the original spectrum appear with period $2\pi$ \end{itemize} \end{frame} \begin{frame}{Graphically} \vspace{-0.4cm} \begin{center} \resizebox{0.7\linewidth}{!}{\input{figs/sampling_example_freq_domain.tex}} \end{center} \vspace{-0.4cm} \onslide<4|handout:1>{Replicas of the original spectrum appear with period $2\pi$} \end{frame} \begin{frame}{Oversampling} \begin{itemize} \item A signal is \textbf{band limited} if $X_c(j\Omega) = 0$ for $|\Omega| > \Omega_N$. In this case, the signal has maximum frequency $\Omega_N$ and \textbf{bandwidth} $2\Omega_N$ \item Sampling at $\Omega_s > 2\Omega_N$ is called \textbf{oversampling} \item Oversampling leads to gaps between the spectrum replicas \end{itemize} \begin{center} \resizebox{0.8\linewidth}{!}{\PlotSampledSpectrum{figs/oversampling_example.tex}{10.0}{5.0}{$\Omega_s > 2\Omega_N$}} \end{center} \end{frame} \begin{frame}{Nyquist sampling} \begin{itemize} \item Sampling at $\Omega_s = 2\Omega_N$ is called \textbf{Nyquist sampling} \item Note that if $\Omega_s$ is any smaller than $2\Omega_N$, there will be overlapping of the spectrum replicas \begin{center} \resizebox{0.9\linewidth}{!}{\PlotSampledSpectrum{figs/oversampling_example.tex}{5}{2.5}{$\Omega_s = 2\Omega_N$}} \end{center} \end{itemize} \end{frame} \begin{frame}{Undersampling} \begin{itemize} \item Undersampling occurs when $\Omega_s < 2\Omega_N$ \item In this case, the spectrum replicas overlap \item The overlapping causes \textbf{aliasing distortion} \end{itemize} \begin{center} \resizebox{0.9\linewidth}{!}{\input{figs/aliasing_spectrum.tex}} \end{center} The regions in red are the regions where the spectrum replicas overlap \end{frame} \begin{frame}{Aliasing: time domain} \only<1|handout:0>{A sinusoidal signal with frequency $\Omega_N = 1.5\pi$} \only<2|handout:0>{Samples taken at frequency $\Omega_s = 2\pi$ \textbf{(undersampling)}} \only<3|handout:1>{Samples taken at frequency $\Omega_s = 2\pi$ form an {\color{red} \textbf{alias signal}} of frequency $0.5\pi$, but {\color{gray} \textbf{original signal}} had frequency $1.5\pi$} \begin{center} \resizebox{0.65\linewidth}{!}{\input{figs/aliased_sinusoid.tex}} \end{center} \end{frame} \begin{frame}{Aliasing: frequency domain} Same example, but now in the frequency domain \begin{center} \resizebox{0.75\linewidth}{!}{\input{figs/aliased_sinusoid_freq.tex}} \end{center} \onslide<3-|handout:1>{ Blue components correspond to spectrum replica centered at $2\pi$, while red components correspond to spectrum replica centered at $-2\pi$. The final spectrum corresponds to $\cos(0.5\pi n)$ } \end{frame} % \begin{frame}{Aliasing examples} Cameras and our own visual system are sampling devices with a certain sampling frequency. Therefore, we can \textit{see} aliasing. \begin{block}{Examples} \begin{itemize} \item This \href{https://www.youtube.com/watch?v=R-IVw8OKjvQ}{video}. The blades of the helicopter are spinning at the same frequency of the camera shutter \item Wheels of the car that appear to spin backwards \item Stroboscopic effect (search videos of this) \end{itemize} \end{block} \end{frame} % \begin{frame}{Sampling random signals} The same theory applies to random signals. Specifically, we we'll apply the same results to the autocorrelation function and PSD of random signals Autocorrelation function of a continuous-time WSS process and its PSD: \begin{equation*} \phi_{x_cx_c}(\tau) = \E(x_c(t+\tau)x_c^*(t)) \Longleftrightarrow \Phi_{x_cx_c}(j\Omega) \end{equation*} If we sample the random signal with sampling period $T = 2\pi/\Omega_s$, we obtain $x[n] = x_c(nT)$. Calculating the autocorrelation function of $x[n]$: \begin{align*} \phi_{xx}[m] &= \E(x[n+m]x^*[n]) = \E(x_c((n+m)T)x_c^*(nT)) \\ &= \phi_{x_cx_c}(mT) \tag{the autocorrelation is sampled} \end{align*} And for the PSD: \begin{align*} \Phi_{xx}(e^{j\Omega T}) &= \mathcal{F}(\phi_{xx}[m]) = \sum_{m=-\infty}^{\infty}\phi_{xx}[m]e^{-j\Omega T} \\ &= \frac{1}{T}\sum_{k=-\infty}^{\infty}\Phi_{x_cx_c}(j(\Omega-k\Omega_s)) \tag{the PSD is replicated with period $\Omega_s$} \end{align*} \end{frame} \section{Reconstruction} \begin{frame}{Digital processing of analog signals} \begin{block}{Typical system} \vspace{-0.7cm} \begin{center} \resizebox{0.7\linewidth}{!}{\input{figs/adc-dsp-dac.tex}} \end{center} \end{block} \vspace{-0.5cm} \begin{block}{Analog-to-digital converter (ADC)} \begin{itemize} \item Performs filtering, sampling, and quantization \item Sampling rate may be of tens of kHz (audio processing), or it may be of tens of GHz (optical communications) \end{itemize} \end{block} \vspace{-0.3cm} \begin{block}{Digital signal processor} \begin{itemize} \itemsep 0pt \item Performs some operation e.g., filtering, FFT, etc \item May be implemented on PCs with 64-bit floating-point precision, or on ASICs with limited arithmetic precision (e.g., 6 bits). \end{itemize} \end{block} \vspace{-0.3cm} \begin{block}{\textbf{Digital-to-analog converter (DAC)}} \begin{itemize} \item Performs quantization and reconstruction (filtering) \item Sampling rate could be similar to ADC \end{itemize} \end{block} \end{frame} \begin{frame}{Digital-to-analog conversion} \begin{block}{In practice} Example of digital-to-analog converter (DAC) \begin{figure} \centering \includegraphics[width=\textwidth]{figs/DAC_EE102B.png}\\ {\tiny \color{gray} Taken from the lecture notes of EE 102B by Prof. Joseph Kahn} \end{figure} \end{block} \end{frame} \begin{frame}{Digital-to-analog conversion} \begin{block}{In this class} We'll model the ADC as an ideal discrete-to-continuous (D-to-C) time converter. \begin{center} \begin{tikzpicture}[->, >=stealth, shorten >= 0pt, draw=black!50, node distance=3cm, font=\sffamily] \tikzstyle{node}=[circle,fill=black,minimum size=2pt,inner sep=0pt] \tikzstyle{block}=[draw=black,rectangle,fill=none,minimum size=1.5cm, inner sep=0pt] \tikzstyle{annot} = [] \node[node] (xc) {}; \node[block, right of=xc, align=center, text width=2cm] (DSP) {D-to-C Converter}; \coordinate[right of=DSP] (yc) {}; \path (xc) edge (DSP); \path (DSP) edge (yc); \node[above = 0mm of xc, text width = 2cm, align=center] {$x[n]$}; \node[below = 0mm of xc, text width = 2cm, align=center] {$X(e^{j\omega}), X(e^{j\Omega T})$}; \node[above = 0mm of yc, text width = 3cm, align=center] {$x_c(t)$}; \node[below = 0mm of yc, text width = 2cm, align=center] {$X(j\Omega)$}; \end{tikzpicture} \end{center} \end{block} In essence, a D-to-C converter performs \textbf{interpolation}. \end{frame} \begin{frame}{Discrete-to-continuous time conversion} For mathematical convenience we can model the D-to-C as \begin{center} \begin{tikzpicture}[->, >=stealth, shorten >= 0pt, draw=black!50, node distance=4cm, font=\sffamily] \tikzstyle{node}=[circle,fill=black,minimum size=2pt,inner sep=0pt] \tikzstyle{block}=[draw=black,rectangle,fill=none,minimum size=1.5cm, inner sep=0pt] \tikzstyle{annot} = [] \node[node] (xc) {}; \node[block, right=1.5cm of xc, text width=3cm, align=center] (b1) {\small Discrete-time sequence to impulse train}; \node[block, right=0.5cm of b1, text width=2.5cm, align=center] (b2) {\small Lowpass filter $h_r(t) \leftrightarrow H_r(j\Omega)$}; \coordinate[right=1.5cm of b2.east] (yc) {}; \path (xc) edge (b1); \path (b1) edge (b2); \path (b2) edge (yc); \node[above = 0mm of xc, text width = 2cm, align=center] {$x[n]$}; \node[above = 0mm of yc, text width = 3cm, align=center] {$x_r(t)$}; \draw[dashed] ($(b1.west) - (0.25cm, 1.5cm)$) rectangle ($(b2.east) + (0.25cm, 1.2cm)$) {}; \node at ($(b1.west)!0.5!(b2.east) - (0, 1.2cm)$) {D-to-C converter}; \end{tikzpicture} \end{center} \begin{equation*} x_r(t) = \sum_{n=-\infty}^{\infty} x[n]h_r(t-nT) \tag{D-to-C converter} \end{equation*} \begin{block}{Important questions} \begin{enumerate} \item How close to the original signal is $x_r(t)$? \item What lowpass filter $H_r(j\Omega)$ will lead to the best performance? \end{enumerate} \end{block} \end{frame} \begin{frame}{Reconstruction: time domain} \begin{center} \resizebox{0.75\linewidth}{!}{\input{figs/reconstruction_example_time.tex}} \end{center} \end{frame} \begin{frame}{Reconstruction: frequency domain} \begin{center} \resizebox{0.75\linewidth}{!}{\input{figs/reconstruction_example_freq.tex}} \end{center} \end{frame} \begin{frame}{Shannon-Nyquist sampling theorem} \begin{block}{Shannon-Nyquist sampling theorem} A band-limited signal with highest frequency $\Omega_N$ can be \textbf{perfectly reconstructed} from samples taken with sampling frequency $\Omega_s = \frac{2\pi}{T} > 2\Omega_N$. \begin{equation*} X_r(j\Omega) = H_r(j\Omega)X(e^{j\Omega T}) = X_c(j\Omega) \end{equation*} \end{block} \begin{itemize} \item Sampling above the Nyquist frequency ($2\Omega_N$) avoids aliasing \item In practice, it is common to use an \textbf{anti-aliasing filter} to minimize aliasing when the analog signal is not band-limited. \item Perfect reconstruction is achieved if $H_r(j\Omega)$ is the ideal lowpass filter. In other words, the ideal lowpass filter (or sinc function in time domain) is the perfect \textit{interpolator} for band-limited signals. \end{itemize} \end{frame} \begin{frame}[t]{Ideal lowpass filter} \begin{columns}[t] \begin{column}{0.5\linewidth} \textbf{Time domain} \vspace{0.2cm} \begin{equation*} h_{lpf}(t) = \frac{\sin\frac{\pi}{T}t}{\frac{\pi}{T}t} = \mathrm{sinc}\Big(\frac{t}{T}\Big) \end{equation*} \end{column} \begin{column}{0.5\linewidth} \textbf{Frequency domain} \begin{equation*} H_{lpf}(j\Omega) = \begin{cases} T, & |\Omega|\leq\frac{\pi}{T} \\ 0, & |\Omega| > \frac{\pi}{T} \end{cases} \end{equation*} \end{column} \end{columns} \begin{center} \resizebox{0.9\linewidth}{!}{\input{figs/ideal_lowpass_filter_ct.tex}} \end{center} \end{frame} \begin{frame}{Example of reconstruction with an ideal lowpass filter} \vspace{-0.5cm} \begin{equation} x_r(t) = \sum_{n=-\infty}^{\infty} x[n]h_r(t-nT) = \sum_{n=-\infty}^{\infty} x[n]\mathrm{sinc}(t-nT) \tag{reconstruction} \end{equation} \begin{center} \resizebox{0.45\linewidth}{!}{\input{figs/reconstruction_ideal_lpf.tex}} \end{center} \only<1|handout:1>{Original continuous-time signal} \only<2|handout:2>{Samples from original continuous-time signal} \only<3-6|handout:3>{At the $n$th sample, we have the sinc function $x[n]\mathrm{sinc}(t-nT)$} \only<7|handout:4>{The sum of all {\color{blue2} \textbf{sincs}} results in the perfectly {\color{red}\textbf{reconstructed signal}}.} \end{frame} \begin{frame}{Practical reconstruction} \begin{block}{Problem} The ideal lowpass filter is not feasible, as it is non-causal and requires infinitely many samples. \end{block} \begin{block}{Common reconstruction filters} \begin{enumerate} \item Zero-order hold (square pulse) \item Linear interpolation (triangular pulse) \item Cubic spline interpolation \end{enumerate} \end{block} \end{frame} \begin{frame}{Practical reconstruction: zero-order holder (ZOH)} \begin{columns}[t] \begin{column}{0.5\textwidth} \textbf{Impulse response} \begin{equation*} h_{ZOH}(t) = \begin{cases} 1, & -T/2 \leq t \leq T/2 \\ 0, & \text{otherwise} \end{cases} \end{equation*} \end{column} \begin{column}{0.5\textwidth} \textbf{Frequency response} \begin{align*} H_{ZOH}(j\Omega) &= T\frac{\sin(\Omega T/2)}{\Omega T/2} \\ &= T\mathrm{sinc}\Big(\frac{\Omega}{2\pi} T\Big) \end{align*} \end{column} \end{columns} \begin{center} \resizebox{0.8\linewidth}{!}{\input{figs/zoh_time_freq.tex}} \end{center} \end{frame} \begin{frame}{Practical reconstruction: zero-order holder (ZOH)} Example of reconstruction (or interpolation) using the ZOH \begin{center} \resizebox{0.7\linewidth}{!}{\input{figs/interp_example_with_zoh.tex}} \end{center} \onslide<3|handout:2>{This would be the result for a \textbf{causal ZOH filter}. That is, $h_{ZOH}(t) = 1, 0 \leq t \leq T$, and zero otherwise. This is what can be implemented in analog.} \end{frame} \begin{frame}{Practical reconstruction: linear interpolator} \begin{columns}[t] \begin{column}{0.5\textwidth} \textbf{Impulse response} \begin{align*} h_{lin}(t) &= \frac{1}{T}h_{ZOH}(t)\ast h_{ZOH}(t) \\ &= \begin{cases} 1-|t|/T, & |t| < T/2 \\ 0, & \text{otherwise} \end{cases} \end{align*} \end{column} \begin{column}{0.5\textwidth} \textbf{Frequency response} \begin{align*} H_{lin}(j\Omega) &= \frac{1}{T}H^2_{ZOH}(j\Omega) \\ &= T\mathrm{sinc}^2\Big(\frac{\Omega}{2\pi} T\Big) \end{align*} \end{column} \end{columns} \begin{center} \resizebox{0.75\linewidth}{!}{\input{figs/linear_interp_time_freq.tex}} \end{center} \end{frame} \begin{frame}{Practical reconstruction: linear interpolation} Example of reconstruction using linear interpolation \begin{center} \resizebox{0.7\linewidth}{!}{\input{figs/interp_example_with_linear.tex}} \end{center} \onslide<3|handout:1>{Adding the scaled triangular pulses produces the linear interpolation (red curve)} \end{frame} \begin{frame}{Practical reconstruction: cubic-spline interpolation} \textbf{Impulse response} \begin{align*} h_{spline}(t) = \begin{cases} (a+2)|t/T|^3 - (a+3)|t/T|^2 + 1, & 0 \leq |t| \leq T \\ a|t/T|^3 - 5a|t/T|^2 + 8a|t/T|-4a, & T < |t| \leq 2T \\ 0, & \text{otherwise} \end{cases} \end{align*} \textbf{Frequency response} \begin{align*} H_{spline}(j\Omega) &= \frac{12T}{(\Omega T)^2}\Big(\mathrm{sinc}^2(fT)-\mathrm{sinc}(2fT)\Big) \\ &+ \frac{8Ta}{(\Omega T)^2}\Big(3\mathrm{sinc}^2(2fT) - 2\mathrm{sinc}(2fT) - \mathrm{sinc}(4fT)\Big) \end{align*} where $f = \Omega/(2\pi)$. \end{frame} \begin{frame}{Practical reconstruction: cubic-spline interpolation} \begin{columns}[t] \begin{column}{0.5\textwidth} \textbf{Impulse response} \end{column} \begin{column}{0.5\textwidth} \textbf{Frequency response} \end{column} \end{columns} \begin{center} \resizebox{0.9\linewidth}{!}{\input{figs/spline_interp_time_freq.tex}} \end{center} This assumes $a = 0.1$ in the previous slide. \end{frame} \begin{frame}{Practical reconstruction: cubic-spline interpolation} Example of reconstruction using cubic-spline interpolation \begin{center} \resizebox{0.7\linewidth}{!}{\input{figs/interp_example_with_spline.tex}} \end{center} \end{frame} \begin{frame}{Comparison of reconstruction filters} The interpolation filter must suppress the spectrum replicas without distorting the spectrum centered at the origin \begin{center} \resizebox{0.8\linewidth}{!}{\input{figs/interpolation_comparison.tex}} \end{center} \end{frame} \begin{frame}{Comparison of reconstruction filters} Oversampling makes the job of the interpolation filter much easier. \begin{center} \resizebox{0.8\linewidth}{!}{\input{figs/interpolation_comparison_with_oversampling.tex}} \end{center} \onslide<5|handout:1>{With oversampling, the interpolation filters look approximately flat around $[-\omega_N, \omega_N]$, and they suppress the spectrum replicas more strongly.} \end{frame} \section{Discrete-Time Filtering of Continuous-Time Signals} \begin{frame}{Discrete-time filtering of continuous-time signals} \begin{block}{In practice} \begin{center} \resizebox{0.9\linewidth}{!}{\input{figs/adc-dsp-dac.tex}} \end{center} \end{block} \begin{block}{DSP theory} \begin{center} \resizebox{0.9\linewidth}{!}{\input{figs/ctd-lti-dtc.tex}} \end{center} \end{block} \end{frame} \begin{frame}{Discrete-time filtering of continuous-time signals} \vspace{-0.2cm} \begin{center} \resizebox{0.65\linewidth}{!}{\input{figs/ctd-lti-dtc.tex}} \end{center} \pause For the C-to-D converter (sampling): \begin{equation*} X(e^{j\Omega T}) = \frac{1}{T}\sum_{k=-\infty}^{\infty}X_c(j(\Omega - k\Omega_s)) \end{equation*} \pause For the discrete-time LTI system: \begin{equation*} Y(e^{j\Omega T}) = H(e^{j\Omega T})X(e^{j\Omega T}) \tag{using $\omega = \Omega T$} \end{equation*} \pause For the D-to-C converter (reconstruction or interpolation): \begin{equation*} Y_r(j\Omega) = H_r(j\Omega)Y(e^{j\Omega T}) \end{equation*} \pause Putting it all together: \begin{equation*} Y_r(j\Omega) = H_r(j\Omega)H(e^{j\Omega T})\frac{1}{T}\sum_{k=-\infty}^{\infty}X_c(j(\Omega - k\Omega_s)) \end{equation*} \end{frame} \begin{frame}{Discrete-time filtering of continuous-time signals} \begin{equation*} Y_r(j\Omega) = H_r(j\Omega)H(e^{j\Omega T})\frac{1}{T}\sum_{k=-\infty}^{\infty}X_c(j(\Omega - k\Omega_s)) \label{eq:ct-dt-dsp} \end{equation*} We can simplify this equation by making two assumptions: \begin{enumerate} \item \textbf{No aliasing}. That is, assuming that the signal $X_c(j(\Omega - k\Omega_s))$ is bandlimited such that \begin{equation*} X_c(j\Omega) = 0~\text{for}~|\Omega| \geq \Omega_N \end{equation*} and that the sampling frequency is such that $\Omega_s > 2\Omega_N$. \item \textbf{Ideal reconstruction}. That is, $H_r(j\Omega)$ is the ideal lowpass filter: \end{enumerate} With these assumptions: \begin{equation*} Y_r(j\Omega) = H(e^{j\Omega T})X_c(j\Omega),~\text{for}~|\Omega| < \Omega_N \end{equation*} \end{frame} \begin{frame}{Discrete-time filtering of continuous-time signals} The simplified equation $Y_r(j\Omega) = H(e^{j\Omega T})X_c(j\Omega),~\text{for}~|\Omega| < \Omega_N$ implies that the following two systems are equivalent \begin{center} \resizebox{\linewidth}{!}{\input{figs/ctd-lti-dtc.tex}} \end{center} \vspace{-0.25cm} \begin{center} \resizebox{0.95\linewidth}{!}{ \begin{tikzpicture}[->, >=stealth, shorten >= 0pt, draw=black!50, node distance=4.5cm, font=\sffamily] \tikzstyle{node}=[circle,fill=black,minimum size=2pt,inner sep=0pt] \tikzstyle{block}=[draw=black,rectangle,fill=none,minimum size=1.5cm, inner sep=0pt] \tikzstyle{annot} = [] \node[node] (xc) {}; \node[block, right of=xc, text width = 2.5cm, align= center] (DSP) {$h_c(t) \leftrightarrow H_c(j\Omega)$}; \coordinate[right of=DSP] (yc) {}; \path (xc) edge (DSP); \path (DSP) edge (yc); \node[above = 0mm of xc, text width = 1cm, align=center] {$x_c(t)$}; \node[below = 0mm of xc, text width = 1cm, align=center] {$X_c(j\Omega)$}; \node[above = 0mm of yc, text width = 1cm, align=center] {$y_c(t)$}; \node[below = 0mm of yc, text width = 1cm, align=center] {$Y_c(j\Omega)$}; \end{tikzpicture} } \end{center} \begin{equation*} H_c(j\Omega) = H(e^{j\Omega T}), |\Omega| \leq \Omega_s/2 \end{equation*} \textbf{Conclusion:} in theory, we can perform any LTI continuous-time filtering in discrete-time. \end{frame} \begin{frame}{Graphically} \vspace{-0.4cm} \begin{center} \resizebox{0.7\linewidth}{!}{\input{figs/dt_processing_of_ct_signals.tex}} \end{center} \end{frame} \begin{frame}<beamer:0|handout:1> \fontsize{8pt}{7.2}\selectfont \begin{itemize} \item We start with a bandlimited analog signal $x_c(t) \leftrightarrow X_c(j\Omega)$ (top plot) \item After sampling with frequency $\Omega_s = \frac{2\pi}{T}$, we obtain the discrete-time signal (second plot from the top). As usual we have the spectrum replicas in discrete-time. Note that for plotting we used the continuous-time frequency $\Omega$. As a result, the spectrum replicas are centered around multiples of $\Omega_s$. If we had used the discrete-time frequency $\omega = \Omega T$, the signal replicas would appear around multiples of $2\pi$. \item The Third plot corresponds to some operation that we'll perform in discrete time. It could be any sort of LTI system, but for this illustration we'll use an ideal lowpass filter whose cutoff frequency is smaller than $\Omega_N$. As a result, some part of the signal will be cut off. \item Filtering by $H(e^{j\Omega T})$ yields the output discrete-time signal $Y(e^{j\Omega T})$. \item After signal reconstruction with the ideal reconstruction filter (lowpass filter with cutoff frequency $\Omega_s/2$), we obtain the analog signal (no spectrum replicas) shown in the bottom plot. \item Note that the output analog signal is the same that we'd have obtained if we had filtered the original analog signal with an ideal (analog) lowpass filter of cutoff frequency smaller than $\Omega_N$. \item Therefore, this example illustrates that we achieved continuous-time filtering by performing discrete-time filtering by $H(e^{j\Omega T})$. In fact, any continuous-time filtering can be performed in discrete-time, provided that there is no aliasing and that the reconstruction filter is the ideal lowpass filter. Although the latter condition is unfeasible, we can use practical interpolation filters to achieve very similar results. \end{itemize} \end{frame} \begin{frame}{Summary} \begin{itemize} \item Sampling a continuous-time signal results in replicas of the spectrum at multiples of the sampling frequency $\Omega_s$ (or $2\pi$ of the normalized frequency $\omega$) \item A band-limited signal has highest frequency $\Omega_N$ ($X_c(j\Omega) = 0, |\Omega| > \Omega_N$) \item If a band-limited signal is oversampled ($\Omega_s > 2\Omega_N$) there'll be gaps between the spectrum replicas \item If the signal is undersampled ($\Omega_s < 2\Omega_N$) the spectrum replicas will overlap resulting in aliasing distortion \item We can perfectly reconstruct a signal from its samples, provided that there is no aliasing and that we use the ideal lowpass filter as reconstruction filter \item In practice, we use different reconstruction filters, since the ideal lowpass filter is unfeasible. \item Oversampling relaxes the reconstruction filter specifications \item In theory, we can perform any LTI continuous-time filtering in discrete-time (in DSP), provided that there is no aliasing and that we use the ideal reconstruction filter \end{itemize} \end{frame} \end{document}
```python import pycalphad from pycalphad.tests.datasets import ALFE_TDB from pycalphad import Database, Model import pycalphad.variables as v from sympy import Piecewise, Function dbf = Database(ALFE_TDB) mod = Model(dbf, ['AL','FE', 'VA'], 'B2_BCC') t = mod.ast.diff(v.Y('B2_BCC', 1, 'AL'), v.Y('B2_BCC', 0, 'FE')) #print(t) def func(x): f = Function('f') a = [] for t in x.args: a.append(t[0]) #print(a) return f(*a) t = t.replace(lambda expr: isinstance(expr, Piecewise), func) for _ in range(5): t = t + t**(t+3) from timeit import default_timer as clock from symengine import sympify t1 = clock() p = str(t) t2 = clock() sympy_time = t2-t1 print(t2-t1) t1 = clock() t = sympify(t) p = str(t) t2 = clock() print(t2-t1) symengine_time = t2-t1 print(sympy_time / symengine_time) ``` ```python import pycalphad from pycalphad.tests.datasets import ALFE_TDB from pycalphad import Database, Model import pycalphad.variables as v from sympy import Piecewise, Function dbf = Database(ALFE_TDB) mod = Model(dbf, ['AL','FE', 'VA'], 'B2_BCC') t = mod.ast def func(x): f = Function('f') a = [] for t in x.args: a.append(t[0]) return f(*a) t = t.replace(lambda expr: isinstance(expr, Piecewise), func) from timeit import default_timer as clock from symengine import sympify, diff t1 = clock() p = str(t.diff(v.Y('B2_BCC', 1, 'AL'), v.Y('B2_BCC', 0, 'FE'))) t2 = clock() print(t2-t1) sympy_time = t2-t1 t1 = clock() t = sympify(t) p = str(t.diff(v.Y('B2_BCC', 1, 'AL')).diff(v.Y('B2_BCC', 0, 'FE'))) t2 = clock() print(t2-t1) symengine_time = t2-t1 print(sympy_time/symengine_time) ``` 2.1349420790002114 0.11995693399967422 17.797571243409816 ```python ```
function biosigpathlast str2doublepath = fileparts( which('str2double') ); sopenpath = fileparts( which('sopen') ); if strcmp(str2doublepath,sopenpath) rmpath(str2doublepath); str2doublepat2 = fileparts( which('str2double') ); addpath(str2doublepath,'-begin'); addpath(str2doublepat2,'-begin'); end
#vamos a imprimir el archivo (funciona en linux, en windows deberΓ­a ejecutarse otra orden) run(`cat ../instances/SAWYER30.IN2`) using JuMP, CPLEX #CPLEX es el solver de IP de IBM. #using JuMP, GLPK ## leo archivo y guardo datos function readFile(filename) f = open(filename, "r") # "r" -> read s = readlines(f) #leer el archivo y guardarlo en la variable s nt=parse(Int,s[1]) #lee el nΓΊmero de tareas duracion=zeros(Int, nt) #crea vector de duraciones precedencias=zeros(Int,nt,nt) #crea vector de precedencias println("tareas ",nt) for i in 1:nt #para cada pieza duracion[i]=parse(Int,s[1+i]) end println("duraciones",duracion) c=1 while true divided=split(s[nt+1+c],",") if parse(Int,divided[1])==(-1) break end precedencias[parse(Int,divided[1]),parse(Int,divided[2])]=1 c+=1 end println("precedencias",precedencias) close(f) return nt,duracion,precedencias end function salbp1(nt,c,duracion,precedencias) model = Model(CPLEX.Optimizer) #model=Model(GLPK.Optimizer) #set_optimizer_attribute(model,"msg_lev",GLPK.GLP_MSG_ALL) @variable(model,x[1:nt,1:nt],Bin) #tarea i en estaciΓ³n j @variable(model,y[1:nt],Bin) #EstaciΓ³n j #minimizar el nΓΊmero de estaciones @objective(model, Min, sum(y[i] for i in 1:nt)) #asignar cada tarea @constraint(model,[i in 1:nt], sum(x[i,j] for j in 1:nt) == 1 ) #tiempo de ciclo @constraint(model,[j in 1:nt], sum(duracion[i]*x[i,j] for i in 1:nt) <= c*y[j] ) #precedencias for i in 1:nt for j in 1:nt if precedencias[i,j]==1 @constraint(model, sum(k*x[i,k] for k in 1:nt) <= sum(k*x[j,k] for k in 1:nt) ) end end end #println(model) optimize!(model) println("Objective: ",objective_value(model)) for i in 1:nt println("y[$i] = ", JuMP.value(y[i])) end end nt,duracion,precedencias=readFile("../instances/SAWYER30.IN2") for i in 25:40 salbp1(nt,i,duracion,precedencias) end
[STATEMENT] lemma natfun_bigo_1E: assumes "(f :: nat \<Rightarrow> _) \<in> O(\<lambda>_. 1)" obtains C where "C \<ge> lb" "\<And>n. norm (f n) \<le> C" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<And>C. \<lbrakk>lb \<le> C; \<And>n. norm (f n) \<le> C\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. (\<And>C. \<lbrakk>lb \<le> C; \<And>n. norm (f n) \<le> C\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] from assms [PROOF STATE] proof (chain) picking this: f \<in> O(\<lambda>_. 1::'a) [PROOF STEP] obtain C N where "\<forall>n\<ge>N. norm (f n) \<le> C" [PROOF STATE] proof (prove) using this: f \<in> O(\<lambda>_. 1::'a) goal (1 subgoal): 1. (\<And>N C. \<forall>n\<ge>N. norm (f n) \<le> C \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by (auto elim!: landau_o.bigE simp: eventually_at_top_linorder) [PROOF STATE] proof (state) this: \<forall>n\<ge>N. norm (f n) \<le> C goal (1 subgoal): 1. (\<And>C. \<lbrakk>lb \<le> C; \<And>n. norm (f n) \<le> C\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] hence *: "norm (f n) \<le> Max ({C, lb} \<union> (norm ` f ` {..<N}))" for n [PROOF STATE] proof (prove) using this: \<forall>n\<ge>N. norm (f n) \<le> C goal (1 subgoal): 1. norm (f n) \<le> Max ({C, lb} \<union> norm ` f ` {..<N}) [PROOF STEP] by (cases "n \<ge> N") (subst Max_ge_iff; force simp: image_iff)+ [PROOF STATE] proof (state) this: norm (f ?n) \<le> Max ({C, lb} \<union> norm ` f ` {..<N}) goal (1 subgoal): 1. (\<And>C. \<lbrakk>lb \<le> C; \<And>n. norm (f n) \<le> C\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] moreover [PROOF STATE] proof (state) this: norm (f ?n) \<le> Max ({C, lb} \<union> norm ` f ` {..<N}) goal (1 subgoal): 1. (\<And>C. \<lbrakk>lb \<le> C; \<And>n. norm (f n) \<le> C\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] have "Max ({C, lb} \<union> (norm ` f ` {..<N})) \<ge> lb" [PROOF STATE] proof (prove) goal (1 subgoal): 1. lb \<le> Max ({C, lb} \<union> norm ` f ` {..<N}) [PROOF STEP] by (intro Max.coboundedI) auto [PROOF STATE] proof (state) this: lb \<le> Max ({C, lb} \<union> norm ` f ` {..<N}) goal (1 subgoal): 1. (\<And>C. \<lbrakk>lb \<le> C; \<And>n. norm (f n) \<le> C\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] ultimately [PROOF STATE] proof (chain) picking this: norm (f ?n) \<le> Max ({C, lb} \<union> norm ` f ` {..<N}) lb \<le> Max ({C, lb} \<union> norm ` f ` {..<N}) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: norm (f ?n) \<le> Max ({C, lb} \<union> norm ` f ` {..<N}) lb \<le> Max ({C, lb} \<union> norm ` f ` {..<N}) goal (1 subgoal): 1. thesis [PROOF STEP] using that [PROOF STATE] proof (prove) using this: norm (f ?n) \<le> Max ({C, lb} \<union> norm ` f ` {..<N}) lb \<le> Max ({C, lb} \<union> norm ` f ` {..<N}) \<lbrakk>lb \<le> ?C; \<And>n. norm (f n) \<le> ?C\<rbrakk> \<Longrightarrow> thesis goal (1 subgoal): 1. thesis [PROOF STEP] by blast [PROOF STATE] proof (state) this: thesis goal: No subgoals! [PROOF STEP] qed
[GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : Finite J ⊒ Function.Injective (colimitLimitToLimitColimit F) [PROOFSTEP] classical cases nonempty_fintype J intro x y h obtain ⟨kx, x, rfl⟩ := jointly_surjective'.{v, v} x obtain ⟨ky, y, rfl⟩ := jointly_surjective'.{v, v} y dsimp at x y replace h := fun j => congr_arg (limit.Ο€ (curry.obj F β‹™ colim) j) h simp [colimit_eq_iff.{v, v}] at h let k j := (h j).choose let f : βˆ€ j, kx ⟢ k j := fun j => (h j).choose_spec.choose let g : βˆ€ j, ky ⟢ k j := fun j => (h j).choose_spec.choose_spec.choose have w : βˆ€ j, F.map ((πŸ™ j, f j) : (j, kx) ⟢ (j, k j)) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map ((πŸ™ j, g j) : (j, ky) ⟢ (j, k j)) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) := fun j => (h j).choose_spec.choose_spec.choose_spec let O : Finset K := Finset.univ.image k βˆͺ { kx, ky } have kxO : kx ∈ O := Finset.mem_union.mpr (Or.inr (by simp)) have kyO : ky ∈ O := Finset.mem_union.mpr (Or.inr (by simp)) have kjO : βˆ€ j, k j ∈ O := fun j => Finset.mem_union.mpr (Or.inl (by simp)) let H : Finset (Ξ£' (X Y : K) (_ : X ∈ O) (_ : Y ∈ O), X ⟢ Y) := (Finset.univ.image fun j : J => ⟨kx, k j, kxO, Finset.mem_union.mpr (Or.inl (by simp)), f j⟩) βˆͺ Finset.univ.image fun j : J => ⟨ky, k j, kyO, Finset.mem_union.mpr (Or.inl (by simp)), g j⟩ obtain ⟨S, T, W⟩ := IsFiltered.sup_exists O H have fH : βˆ€ j, (⟨kx, k j, kxO, kjO j, f j⟩ : Ξ£' (X Y : K) (_ : X ∈ O) (_ : Y ∈ O), X ⟢ Y) ∈ H := fun j => Finset.mem_union.mpr (Or.inl (by simp only [true_and_iff, Finset.mem_univ, eq_self_iff_true, exists_prop_of_true, Finset.mem_image, heq_iff_eq] refine' ⟨j, _⟩ simp only [heq_iff_eq])) have gH : βˆ€ j, (⟨ky, k j, kyO, kjO j, g j⟩ : Ξ£' (X Y : K) (_ : X ∈ O) (_ : Y ∈ O), X ⟢ Y) ∈ H := fun j => Finset.mem_union.mpr (Or.inr (by simp only [true_and_iff, Finset.mem_univ, eq_self_iff_true, exists_prop_of_true, Finset.mem_image, heq_iff_eq] refine' ⟨j, _⟩ simp only [heq_iff_eq])) -- Our goal is now an equation between equivalence classes of representatives of a colimit, -- and so it suffices to show those representative become equal somewhere, in particular at `S`. apply colimit_sound'.{v, v} (T kxO) (T kyO) -- We can check if two elements of a limit (in `Type`) -- are equal by comparing them componentwise. ext j simp only [Functor.comp_map, Limit.map_Ο€_apply, curry_obj_map_app, swap_map] rw [← W _ _ (fH j)] rw [← W _ _ (gH j)] -- porting note: this was `simp [w]` in lean 3; this is presumably a confluence issue rw [lim_map, lim_map, Limit.map_Ο€_apply', Limit.map_Ο€_apply', Functor.map_comp, Functor.map_comp, FunctorToTypes.comp, FunctorToTypes.comp, curry_obj_map_app, curry_obj_map_app, curry_obj_map_app, Functor.comp_map, Functor.comp_map, Functor.comp_map, swap_map, swap_map, swap_map, w] [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : Finite J ⊒ Function.Injective (colimitLimitToLimitColimit F) [PROOFSTEP] cases nonempty_fintype J [GOAL] case intro J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : Finite J val✝ : Fintype J ⊒ Function.Injective (colimitLimitToLimitColimit F) [PROOFSTEP] intro x y h [GOAL] case intro J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : Finite J val✝ : Fintype J x y : colimit (curry.obj (swap K J β‹™ F) β‹™ lim) h : colimitLimitToLimitColimit F x = colimitLimitToLimitColimit F y ⊒ x = y [PROOFSTEP] obtain ⟨kx, x, rfl⟩ := jointly_surjective'.{v, v} x [GOAL] case intro.intro.intro J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : Finite J val✝ : Fintype J y : colimit (curry.obj (swap K J β‹™ F) β‹™ lim) kx : K x : (curry.obj (swap K J β‹™ F) β‹™ lim).obj kx h : colimitLimitToLimitColimit F (colimit.ΞΉ (curry.obj (swap K J β‹™ F) β‹™ lim) kx x) = colimitLimitToLimitColimit F y ⊒ colimit.ΞΉ (curry.obj (swap K J β‹™ F) β‹™ lim) kx x = y [PROOFSTEP] obtain ⟨ky, y, rfl⟩ := jointly_surjective'.{v, v} y [GOAL] case intro.intro.intro.intro.intro J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : Finite J val✝ : Fintype J kx : K x : (curry.obj (swap K J β‹™ F) β‹™ lim).obj kx ky : K y : (curry.obj (swap K J β‹™ F) β‹™ lim).obj ky h : colimitLimitToLimitColimit F (colimit.ΞΉ (curry.obj (swap K J β‹™ F) β‹™ lim) kx x) = colimitLimitToLimitColimit F (colimit.ΞΉ (curry.obj (swap K J β‹™ F) β‹™ lim) ky y) ⊒ colimit.ΞΉ (curry.obj (swap K J β‹™ F) β‹™ lim) kx x = colimit.ΞΉ (curry.obj (swap K J β‹™ F) β‹™ lim) ky y [PROOFSTEP] dsimp at x y [GOAL] case intro.intro.intro.intro.intro J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : Finite J val✝ : Fintype J kx : K x : limit ((curry.obj (swap K J β‹™ F)).obj kx) ky : K y : limit ((curry.obj (swap K J β‹™ F)).obj ky) h : colimitLimitToLimitColimit F (colimit.ΞΉ (curry.obj (swap K J β‹™ F) β‹™ lim) kx x) = colimitLimitToLimitColimit F (colimit.ΞΉ (curry.obj (swap K J β‹™ F) β‹™ lim) ky y) ⊒ colimit.ΞΉ (curry.obj (swap K J β‹™ F) β‹™ lim) kx x = colimit.ΞΉ (curry.obj (swap K J β‹™ F) β‹™ lim) ky y [PROOFSTEP] replace h := fun j => congr_arg (limit.Ο€ (curry.obj F β‹™ colim) j) h [GOAL] case intro.intro.intro.intro.intro J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : Finite J val✝ : Fintype J kx : K x : limit ((curry.obj (swap K J β‹™ F)).obj kx) ky : K y : limit ((curry.obj (swap K J β‹™ F)).obj ky) h : βˆ€ (j : J), limit.Ο€ (curry.obj F β‹™ colim) j (colimitLimitToLimitColimit F (colimit.ΞΉ (curry.obj (swap K J β‹™ F) β‹™ lim) kx x)) = limit.Ο€ (curry.obj F β‹™ colim) j (colimitLimitToLimitColimit F (colimit.ΞΉ (curry.obj (swap K J β‹™ F) β‹™ lim) ky y)) ⊒ colimit.ΞΉ (curry.obj (swap K J β‹™ F) β‹™ lim) kx x = colimit.ΞΉ (curry.obj (swap K J β‹™ F) β‹™ lim) ky y [PROOFSTEP] simp [colimit_eq_iff.{v, v}] at h [GOAL] case intro.intro.intro.intro.intro J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : Finite J val✝ : Fintype J kx : K x : limit ((curry.obj (swap K J β‹™ F)).obj kx) ky : K y : limit ((curry.obj (swap K J β‹™ F)).obj ky) h : βˆ€ (j : J), βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) ⊒ colimit.ΞΉ (curry.obj (swap K J β‹™ F) β‹™ lim) kx x = colimit.ΞΉ (curry.obj (swap K J β‹™ F) β‹™ lim) ky y [PROOFSTEP] let k j := (h j).choose [GOAL] case intro.intro.intro.intro.intro J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : Finite J val✝ : Fintype J kx : K x : limit ((curry.obj (swap K J β‹™ F)).obj kx) ky : K y : limit ((curry.obj (swap K J β‹™ F)).obj ky) h : βˆ€ (j : J), βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) k : J β†’ K := fun j => Exists.choose (_ : βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) ⊒ colimit.ΞΉ (curry.obj (swap K J β‹™ F) β‹™ lim) kx x = colimit.ΞΉ (curry.obj (swap K J β‹™ F) β‹™ lim) ky y [PROOFSTEP] let f : βˆ€ j, kx ⟢ k j := fun j => (h j).choose_spec.choose [GOAL] case intro.intro.intro.intro.intro J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : Finite J val✝ : Fintype J kx : K x : limit ((curry.obj (swap K J β‹™ F)).obj kx) ky : K y : limit ((curry.obj (swap K J β‹™ F)).obj ky) h : βˆ€ (j : J), βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) k : J β†’ K := fun j => Exists.choose (_ : βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) f : (j : J) β†’ kx ⟢ k j := fun j => Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) ⊒ colimit.ΞΉ (curry.obj (swap K J β‹™ F) β‹™ lim) kx x = colimit.ΞΉ (curry.obj (swap K J β‹™ F) β‹™ lim) ky y [PROOFSTEP] let g : βˆ€ j, ky ⟢ k j := fun j => (h j).choose_spec.choose_spec.choose [GOAL] case intro.intro.intro.intro.intro J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : Finite J val✝ : Fintype J kx : K x : limit ((curry.obj (swap K J β‹™ F)).obj kx) ky : K y : limit ((curry.obj (swap K J β‹™ F)).obj ky) h : βˆ€ (j : J), βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) k : J β†’ K := fun j => Exists.choose (_ : βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) f : (j : J) β†’ kx ⟢ k j := fun j => Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) g : (j : J) β†’ ky ⟢ k j := fun j => Exists.choose (_ : βˆƒ g, F.map (πŸ™ j, Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y))) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) ⊒ colimit.ΞΉ (curry.obj (swap K J β‹™ F) β‹™ lim) kx x = colimit.ΞΉ (curry.obj (swap K J β‹™ F) β‹™ lim) ky y [PROOFSTEP] have w : βˆ€ j, F.map ((πŸ™ j, f j) : (j, kx) ⟢ (j, k j)) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map ((πŸ™ j, g j) : (j, ky) ⟢ (j, k j)) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) := fun j => (h j).choose_spec.choose_spec.choose_spec [GOAL] case intro.intro.intro.intro.intro J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : Finite J val✝ : Fintype J kx : K x : limit ((curry.obj (swap K J β‹™ F)).obj kx) ky : K y : limit ((curry.obj (swap K J β‹™ F)).obj ky) h : βˆ€ (j : J), βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) k : J β†’ K := fun j => Exists.choose (_ : βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) f : (j : J) β†’ kx ⟢ k j := fun j => Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) g : (j : J) β†’ ky ⟢ k j := fun j => Exists.choose (_ : βˆƒ g, F.map (πŸ™ j, Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y))) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) w : βˆ€ (j : J), F.map (πŸ™ j, f j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) ⊒ colimit.ΞΉ (curry.obj (swap K J β‹™ F) β‹™ lim) kx x = colimit.ΞΉ (curry.obj (swap K J β‹™ F) β‹™ lim) ky y [PROOFSTEP] let O : Finset K := Finset.univ.image k βˆͺ { kx, ky } [GOAL] case intro.intro.intro.intro.intro J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : Finite J val✝ : Fintype J kx : K x : limit ((curry.obj (swap K J β‹™ F)).obj kx) ky : K y : limit ((curry.obj (swap K J β‹™ F)).obj ky) h : βˆ€ (j : J), βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) k : J β†’ K := fun j => Exists.choose (_ : βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) f : (j : J) β†’ kx ⟢ k j := fun j => Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) g : (j : J) β†’ ky ⟢ k j := fun j => Exists.choose (_ : βˆƒ g, F.map (πŸ™ j, Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y))) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) w : βˆ€ (j : J), F.map (πŸ™ j, f j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) O : Finset K := Finset.image k Finset.univ βˆͺ {kx, ky} ⊒ colimit.ΞΉ (curry.obj (swap K J β‹™ F) β‹™ lim) kx x = colimit.ΞΉ (curry.obj (swap K J β‹™ F) β‹™ lim) ky y [PROOFSTEP] have kxO : kx ∈ O := Finset.mem_union.mpr (Or.inr (by simp)) [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : Finite J val✝ : Fintype J kx : K x : limit ((curry.obj (swap K J β‹™ F)).obj kx) ky : K y : limit ((curry.obj (swap K J β‹™ F)).obj ky) h : βˆ€ (j : J), βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) k : J β†’ K := fun j => Exists.choose (_ : βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) f : (j : J) β†’ kx ⟢ k j := fun j => Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) g : (j : J) β†’ ky ⟢ k j := fun j => Exists.choose (_ : βˆƒ g, F.map (πŸ™ j, Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y))) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) w : βˆ€ (j : J), F.map (πŸ™ j, f j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) O : Finset K := Finset.image k Finset.univ βˆͺ {kx, ky} ⊒ kx ∈ {kx, ky} [PROOFSTEP] simp [GOAL] case intro.intro.intro.intro.intro J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : Finite J val✝ : Fintype J kx : K x : limit ((curry.obj (swap K J β‹™ F)).obj kx) ky : K y : limit ((curry.obj (swap K J β‹™ F)).obj ky) h : βˆ€ (j : J), βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) k : J β†’ K := fun j => Exists.choose (_ : βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) f : (j : J) β†’ kx ⟢ k j := fun j => Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) g : (j : J) β†’ ky ⟢ k j := fun j => Exists.choose (_ : βˆƒ g, F.map (πŸ™ j, Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y))) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) w : βˆ€ (j : J), F.map (πŸ™ j, f j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) O : Finset K := Finset.image k Finset.univ βˆͺ {kx, ky} kxO : kx ∈ O ⊒ colimit.ΞΉ (curry.obj (swap K J β‹™ F) β‹™ lim) kx x = colimit.ΞΉ (curry.obj (swap K J β‹™ F) β‹™ lim) ky y [PROOFSTEP] have kyO : ky ∈ O := Finset.mem_union.mpr (Or.inr (by simp)) [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : Finite J val✝ : Fintype J kx : K x : limit ((curry.obj (swap K J β‹™ F)).obj kx) ky : K y : limit ((curry.obj (swap K J β‹™ F)).obj ky) h : βˆ€ (j : J), βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) k : J β†’ K := fun j => Exists.choose (_ : βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) f : (j : J) β†’ kx ⟢ k j := fun j => Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) g : (j : J) β†’ ky ⟢ k j := fun j => Exists.choose (_ : βˆƒ g, F.map (πŸ™ j, Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y))) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) w : βˆ€ (j : J), F.map (πŸ™ j, f j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) O : Finset K := Finset.image k Finset.univ βˆͺ {kx, ky} kxO : kx ∈ O ⊒ ky ∈ {kx, ky} [PROOFSTEP] simp [GOAL] case intro.intro.intro.intro.intro J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : Finite J val✝ : Fintype J kx : K x : limit ((curry.obj (swap K J β‹™ F)).obj kx) ky : K y : limit ((curry.obj (swap K J β‹™ F)).obj ky) h : βˆ€ (j : J), βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) k : J β†’ K := fun j => Exists.choose (_ : βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) f : (j : J) β†’ kx ⟢ k j := fun j => Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) g : (j : J) β†’ ky ⟢ k j := fun j => Exists.choose (_ : βˆƒ g, F.map (πŸ™ j, Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y))) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) w : βˆ€ (j : J), F.map (πŸ™ j, f j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) O : Finset K := Finset.image k Finset.univ βˆͺ {kx, ky} kxO : kx ∈ O kyO : ky ∈ O ⊒ colimit.ΞΉ (curry.obj (swap K J β‹™ F) β‹™ lim) kx x = colimit.ΞΉ (curry.obj (swap K J β‹™ F) β‹™ lim) ky y [PROOFSTEP] have kjO : βˆ€ j, k j ∈ O := fun j => Finset.mem_union.mpr (Or.inl (by simp)) [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : Finite J val✝ : Fintype J kx : K x : limit ((curry.obj (swap K J β‹™ F)).obj kx) ky : K y : limit ((curry.obj (swap K J β‹™ F)).obj ky) h : βˆ€ (j : J), βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) k : J β†’ K := fun j => Exists.choose (_ : βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) f : (j : J) β†’ kx ⟢ k j := fun j => Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) g : (j : J) β†’ ky ⟢ k j := fun j => Exists.choose (_ : βˆƒ g, F.map (πŸ™ j, Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y))) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) w : βˆ€ (j : J), F.map (πŸ™ j, f j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) O : Finset K := Finset.image k Finset.univ βˆͺ {kx, ky} kxO : kx ∈ O kyO : ky ∈ O j : J ⊒ k j ∈ Finset.image k Finset.univ [PROOFSTEP] simp [GOAL] case intro.intro.intro.intro.intro J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : Finite J val✝ : Fintype J kx : K x : limit ((curry.obj (swap K J β‹™ F)).obj kx) ky : K y : limit ((curry.obj (swap K J β‹™ F)).obj ky) h : βˆ€ (j : J), βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) k : J β†’ K := fun j => Exists.choose (_ : βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) f : (j : J) β†’ kx ⟢ k j := fun j => Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) g : (j : J) β†’ ky ⟢ k j := fun j => Exists.choose (_ : βˆƒ g, F.map (πŸ™ j, Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y))) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) w : βˆ€ (j : J), F.map (πŸ™ j, f j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) O : Finset K := Finset.image k Finset.univ βˆͺ {kx, ky} kxO : kx ∈ O kyO : ky ∈ O kjO : βˆ€ (j : J), k j ∈ O ⊒ colimit.ΞΉ (curry.obj (swap K J β‹™ F) β‹™ lim) kx x = colimit.ΞΉ (curry.obj (swap K J β‹™ F) β‹™ lim) ky y [PROOFSTEP] let H : Finset (Ξ£' (X Y : K) (_ : X ∈ O) (_ : Y ∈ O), X ⟢ Y) := (Finset.univ.image fun j : J => ⟨kx, k j, kxO, Finset.mem_union.mpr (Or.inl (by simp)), f j⟩) βˆͺ Finset.univ.image fun j : J => ⟨ky, k j, kyO, Finset.mem_union.mpr (Or.inl (by simp)), g j⟩ [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : Finite J val✝ : Fintype J kx : K x : limit ((curry.obj (swap K J β‹™ F)).obj kx) ky : K y : limit ((curry.obj (swap K J β‹™ F)).obj ky) h : βˆ€ (j : J), βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) k : J β†’ K := fun j => Exists.choose (_ : βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) f : (j : J) β†’ kx ⟢ k j := fun j => Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) g : (j : J) β†’ ky ⟢ k j := fun j => Exists.choose (_ : βˆƒ g, F.map (πŸ™ j, Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y))) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) w : βˆ€ (j : J), F.map (πŸ™ j, f j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) O : Finset K := Finset.image k Finset.univ βˆͺ {kx, ky} kxO : kx ∈ O kyO : ky ∈ O kjO : βˆ€ (j : J), k j ∈ O j : J ⊒ k j ∈ Finset.image k Finset.univ [PROOFSTEP] simp [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : Finite J val✝ : Fintype J kx : K x : limit ((curry.obj (swap K J β‹™ F)).obj kx) ky : K y : limit ((curry.obj (swap K J β‹™ F)).obj ky) h : βˆ€ (j : J), βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) k : J β†’ K := fun j => Exists.choose (_ : βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) f : (j : J) β†’ kx ⟢ k j := fun j => Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) g : (j : J) β†’ ky ⟢ k j := fun j => Exists.choose (_ : βˆƒ g, F.map (πŸ™ j, Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y))) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) w : βˆ€ (j : J), F.map (πŸ™ j, f j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) O : Finset K := Finset.image k Finset.univ βˆͺ {kx, ky} kxO : kx ∈ O kyO : ky ∈ O kjO : βˆ€ (j : J), k j ∈ O j : J ⊒ k j ∈ Finset.image k Finset.univ [PROOFSTEP] simp [GOAL] case intro.intro.intro.intro.intro J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : Finite J val✝ : Fintype J kx : K x : limit ((curry.obj (swap K J β‹™ F)).obj kx) ky : K y : limit ((curry.obj (swap K J β‹™ F)).obj ky) h : βˆ€ (j : J), βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) k : J β†’ K := fun j => Exists.choose (_ : βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) f : (j : J) β†’ kx ⟢ k j := fun j => Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) g : (j : J) β†’ ky ⟢ k j := fun j => Exists.choose (_ : βˆƒ g, F.map (πŸ™ j, Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y))) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) w : βˆ€ (j : J), F.map (πŸ™ j, f j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) O : Finset K := Finset.image k Finset.univ βˆͺ {kx, ky} kxO : kx ∈ O kyO : ky ∈ O kjO : βˆ€ (j : J), k j ∈ O H : Finset ((X : K) Γ—' (Y : K) Γ—' (_ : X ∈ O) Γ—' (_ : Y ∈ O) Γ—' (X ⟢ Y)) := Finset.image (fun j => { fst := kx, snd := { fst := k j, snd := { fst := kxO, snd := { fst := (_ : k j ∈ Finset.image k Finset.univ βˆͺ {kx, ky}), snd := f j } } } }) Finset.univ βˆͺ Finset.image (fun j => { fst := ky, snd := { fst := k j, snd := { fst := kyO, snd := { fst := (_ : k j ∈ Finset.image k Finset.univ βˆͺ {kx, ky}), snd := g j } } } }) Finset.univ ⊒ colimit.ΞΉ (curry.obj (swap K J β‹™ F) β‹™ lim) kx x = colimit.ΞΉ (curry.obj (swap K J β‹™ F) β‹™ lim) ky y [PROOFSTEP] obtain ⟨S, T, W⟩ := IsFiltered.sup_exists O H [GOAL] case intro.intro.intro.intro.intro.intro.intro J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : Finite J val✝ : Fintype J kx : K x : limit ((curry.obj (swap K J β‹™ F)).obj kx) ky : K y : limit ((curry.obj (swap K J β‹™ F)).obj ky) h : βˆ€ (j : J), βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) k : J β†’ K := fun j => Exists.choose (_ : βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) f : (j : J) β†’ kx ⟢ k j := fun j => Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) g : (j : J) β†’ ky ⟢ k j := fun j => Exists.choose (_ : βˆƒ g, F.map (πŸ™ j, Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y))) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) w : βˆ€ (j : J), F.map (πŸ™ j, f j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) O : Finset K := Finset.image k Finset.univ βˆͺ {kx, ky} kxO : kx ∈ O kyO : ky ∈ O kjO : βˆ€ (j : J), k j ∈ O H : Finset ((X : K) Γ—' (Y : K) Γ—' (_ : X ∈ O) Γ—' (_ : Y ∈ O) Γ—' (X ⟢ Y)) := Finset.image (fun j => { fst := kx, snd := { fst := k j, snd := { fst := kxO, snd := { fst := (_ : k j ∈ Finset.image k Finset.univ βˆͺ {kx, ky}), snd := f j } } } }) Finset.univ βˆͺ Finset.image (fun j => { fst := ky, snd := { fst := k j, snd := { fst := kyO, snd := { fst := (_ : k j ∈ Finset.image k Finset.univ βˆͺ {kx, ky}), snd := g j } } } }) Finset.univ S : K T : {X : K} β†’ X ∈ O β†’ (X ⟢ S) W : βˆ€ {X Y : K} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟢ Y}, { fst := X, snd := { fst := Y, snd := { fst := mX, snd := { fst := mY, snd := f } } } } ∈ H β†’ f ≫ T mY = T mX ⊒ colimit.ΞΉ (curry.obj (swap K J β‹™ F) β‹™ lim) kx x = colimit.ΞΉ (curry.obj (swap K J β‹™ F) β‹™ lim) ky y [PROOFSTEP] have fH : βˆ€ j, (⟨kx, k j, kxO, kjO j, f j⟩ : Ξ£' (X Y : K) (_ : X ∈ O) (_ : Y ∈ O), X ⟢ Y) ∈ H := fun j => Finset.mem_union.mpr (Or.inl (by simp only [true_and_iff, Finset.mem_univ, eq_self_iff_true, exists_prop_of_true, Finset.mem_image, heq_iff_eq] refine' ⟨j, _⟩ simp only [heq_iff_eq])) [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : Finite J val✝ : Fintype J kx : K x : limit ((curry.obj (swap K J β‹™ F)).obj kx) ky : K y : limit ((curry.obj (swap K J β‹™ F)).obj ky) h : βˆ€ (j : J), βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) k : J β†’ K := fun j => Exists.choose (_ : βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) f : (j : J) β†’ kx ⟢ k j := fun j => Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) g : (j : J) β†’ ky ⟢ k j := fun j => Exists.choose (_ : βˆƒ g, F.map (πŸ™ j, Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y))) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) w : βˆ€ (j : J), F.map (πŸ™ j, f j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) O : Finset K := Finset.image k Finset.univ βˆͺ {kx, ky} kxO : kx ∈ O kyO : ky ∈ O kjO : βˆ€ (j : J), k j ∈ O H : Finset ((X : K) Γ—' (Y : K) Γ—' (_ : X ∈ O) Γ—' (_ : Y ∈ O) Γ—' (X ⟢ Y)) := Finset.image (fun j => { fst := kx, snd := { fst := k j, snd := { fst := kxO, snd := { fst := (_ : k j ∈ Finset.image k Finset.univ βˆͺ {kx, ky}), snd := f j } } } }) Finset.univ βˆͺ Finset.image (fun j => { fst := ky, snd := { fst := k j, snd := { fst := kyO, snd := { fst := (_ : k j ∈ Finset.image k Finset.univ βˆͺ {kx, ky}), snd := g j } } } }) Finset.univ S : K T : {X : K} β†’ X ∈ O β†’ (X ⟢ S) W : βˆ€ {X Y : K} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟢ Y}, { fst := X, snd := { fst := Y, snd := { fst := mX, snd := { fst := mY, snd := f } } } } ∈ H β†’ f ≫ T mY = T mX j : J ⊒ { fst := kx, snd := { fst := k j, snd := { fst := kxO, snd := { fst := (_ : k j ∈ O), snd := f j } } } } ∈ Finset.image (fun j => { fst := kx, snd := { fst := k j, snd := { fst := kxO, snd := { fst := (_ : k j ∈ Finset.image k Finset.univ βˆͺ {kx, ky}), snd := f j } } } }) Finset.univ [PROOFSTEP] simp only [true_and_iff, Finset.mem_univ, eq_self_iff_true, exists_prop_of_true, Finset.mem_image, heq_iff_eq] [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : Finite J val✝ : Fintype J kx : K x : limit ((curry.obj (swap K J β‹™ F)).obj kx) ky : K y : limit ((curry.obj (swap K J β‹™ F)).obj ky) h : βˆ€ (j : J), βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) k : J β†’ K := fun j => Exists.choose (_ : βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) f : (j : J) β†’ kx ⟢ k j := fun j => Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) g : (j : J) β†’ ky ⟢ k j := fun j => Exists.choose (_ : βˆƒ g, F.map (πŸ™ j, Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y))) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) w : βˆ€ (j : J), F.map (πŸ™ j, f j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) O : Finset K := Finset.image k Finset.univ βˆͺ {kx, ky} kxO : kx ∈ O kyO : ky ∈ O kjO : βˆ€ (j : J), k j ∈ O H : Finset ((X : K) Γ—' (Y : K) Γ—' (_ : X ∈ O) Γ—' (_ : Y ∈ O) Γ—' (X ⟢ Y)) := Finset.image (fun j => { fst := kx, snd := { fst := k j, snd := { fst := kxO, snd := { fst := (_ : k j ∈ Finset.image k Finset.univ βˆͺ {kx, ky}), snd := f j } } } }) Finset.univ βˆͺ Finset.image (fun j => { fst := ky, snd := { fst := k j, snd := { fst := kyO, snd := { fst := (_ : k j ∈ Finset.image k Finset.univ βˆͺ {kx, ky}), snd := g j } } } }) Finset.univ S : K T : {X : K} β†’ X ∈ O β†’ (X ⟢ S) W : βˆ€ {X Y : K} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟢ Y}, { fst := X, snd := { fst := Y, snd := { fst := mX, snd := { fst := mY, snd := f } } } } ∈ H β†’ f ≫ T mY = T mX j : J ⊒ βˆƒ a, { fst := kx, snd := { fst := Exists.choose (_ : βˆƒ k f g, F.map (πŸ™ a, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) a x) = F.map (πŸ™ a, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) a y)), snd := { fst := kxO, snd := { fst := (_ : k a ∈ Finset.image k Finset.univ βˆͺ {kx, ky}), snd := Exists.choose (_ : βˆƒ f g, F.map (πŸ™ a, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) a x) = F.map (πŸ™ a, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) a y)) } } } } = { fst := kx, snd := { fst := Exists.choose (_ : βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)), snd := { fst := kxO, snd := { fst := (_ : k j ∈ O), snd := Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) } } } } [PROOFSTEP] refine' ⟨j, _⟩ [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : Finite J val✝ : Fintype J kx : K x : limit ((curry.obj (swap K J β‹™ F)).obj kx) ky : K y : limit ((curry.obj (swap K J β‹™ F)).obj ky) h : βˆ€ (j : J), βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) k : J β†’ K := fun j => Exists.choose (_ : βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) f : (j : J) β†’ kx ⟢ k j := fun j => Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) g : (j : J) β†’ ky ⟢ k j := fun j => Exists.choose (_ : βˆƒ g, F.map (πŸ™ j, Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y))) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) w : βˆ€ (j : J), F.map (πŸ™ j, f j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) O : Finset K := Finset.image k Finset.univ βˆͺ {kx, ky} kxO : kx ∈ O kyO : ky ∈ O kjO : βˆ€ (j : J), k j ∈ O H : Finset ((X : K) Γ—' (Y : K) Γ—' (_ : X ∈ O) Γ—' (_ : Y ∈ O) Γ—' (X ⟢ Y)) := Finset.image (fun j => { fst := kx, snd := { fst := k j, snd := { fst := kxO, snd := { fst := (_ : k j ∈ Finset.image k Finset.univ βˆͺ {kx, ky}), snd := f j } } } }) Finset.univ βˆͺ Finset.image (fun j => { fst := ky, snd := { fst := k j, snd := { fst := kyO, snd := { fst := (_ : k j ∈ Finset.image k Finset.univ βˆͺ {kx, ky}), snd := g j } } } }) Finset.univ S : K T : {X : K} β†’ X ∈ O β†’ (X ⟢ S) W : βˆ€ {X Y : K} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟢ Y}, { fst := X, snd := { fst := Y, snd := { fst := mX, snd := { fst := mY, snd := f } } } } ∈ H β†’ f ≫ T mY = T mX j : J ⊒ { fst := kx, snd := { fst := Exists.choose (_ : βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)), snd := { fst := kxO, snd := { fst := (_ : k j ∈ Finset.image k Finset.univ βˆͺ {kx, ky}), snd := Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) } } } } = { fst := kx, snd := { fst := Exists.choose (_ : βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)), snd := { fst := kxO, snd := { fst := (_ : k j ∈ O), snd := Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) } } } } [PROOFSTEP] simp only [heq_iff_eq] [GOAL] case intro.intro.intro.intro.intro.intro.intro J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : Finite J val✝ : Fintype J kx : K x : limit ((curry.obj (swap K J β‹™ F)).obj kx) ky : K y : limit ((curry.obj (swap K J β‹™ F)).obj ky) h : βˆ€ (j : J), βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) k : J β†’ K := fun j => Exists.choose (_ : βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) f : (j : J) β†’ kx ⟢ k j := fun j => Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) g : (j : J) β†’ ky ⟢ k j := fun j => Exists.choose (_ : βˆƒ g, F.map (πŸ™ j, Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y))) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) w : βˆ€ (j : J), F.map (πŸ™ j, f j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) O : Finset K := Finset.image k Finset.univ βˆͺ {kx, ky} kxO : kx ∈ O kyO : ky ∈ O kjO : βˆ€ (j : J), k j ∈ O H : Finset ((X : K) Γ—' (Y : K) Γ—' (_ : X ∈ O) Γ—' (_ : Y ∈ O) Γ—' (X ⟢ Y)) := Finset.image (fun j => { fst := kx, snd := { fst := k j, snd := { fst := kxO, snd := { fst := (_ : k j ∈ Finset.image k Finset.univ βˆͺ {kx, ky}), snd := f j } } } }) Finset.univ βˆͺ Finset.image (fun j => { fst := ky, snd := { fst := k j, snd := { fst := kyO, snd := { fst := (_ : k j ∈ Finset.image k Finset.univ βˆͺ {kx, ky}), snd := g j } } } }) Finset.univ S : K T : {X : K} β†’ X ∈ O β†’ (X ⟢ S) W : βˆ€ {X Y : K} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟢ Y}, { fst := X, snd := { fst := Y, snd := { fst := mX, snd := { fst := mY, snd := f } } } } ∈ H β†’ f ≫ T mY = T mX fH : βˆ€ (j : J), { fst := kx, snd := { fst := k j, snd := { fst := kxO, snd := { fst := (_ : k j ∈ O), snd := f j } } } } ∈ H ⊒ colimit.ΞΉ (curry.obj (swap K J β‹™ F) β‹™ lim) kx x = colimit.ΞΉ (curry.obj (swap K J β‹™ F) β‹™ lim) ky y [PROOFSTEP] have gH : βˆ€ j, (⟨ky, k j, kyO, kjO j, g j⟩ : Ξ£' (X Y : K) (_ : X ∈ O) (_ : Y ∈ O), X ⟢ Y) ∈ H := fun j => Finset.mem_union.mpr (Or.inr (by simp only [true_and_iff, Finset.mem_univ, eq_self_iff_true, exists_prop_of_true, Finset.mem_image, heq_iff_eq] refine' ⟨j, _⟩ simp only [heq_iff_eq])) -- Our goal is now an equation between equivalence classes of representatives of a colimit, -- and so it suffices to show those representative become equal somewhere, in particular at `S`. [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : Finite J val✝ : Fintype J kx : K x : limit ((curry.obj (swap K J β‹™ F)).obj kx) ky : K y : limit ((curry.obj (swap K J β‹™ F)).obj ky) h : βˆ€ (j : J), βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) k : J β†’ K := fun j => Exists.choose (_ : βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) f : (j : J) β†’ kx ⟢ k j := fun j => Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) g : (j : J) β†’ ky ⟢ k j := fun j => Exists.choose (_ : βˆƒ g, F.map (πŸ™ j, Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y))) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) w : βˆ€ (j : J), F.map (πŸ™ j, f j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) O : Finset K := Finset.image k Finset.univ βˆͺ {kx, ky} kxO : kx ∈ O kyO : ky ∈ O kjO : βˆ€ (j : J), k j ∈ O H : Finset ((X : K) Γ—' (Y : K) Γ—' (_ : X ∈ O) Γ—' (_ : Y ∈ O) Γ—' (X ⟢ Y)) := Finset.image (fun j => { fst := kx, snd := { fst := k j, snd := { fst := kxO, snd := { fst := (_ : k j ∈ Finset.image k Finset.univ βˆͺ {kx, ky}), snd := f j } } } }) Finset.univ βˆͺ Finset.image (fun j => { fst := ky, snd := { fst := k j, snd := { fst := kyO, snd := { fst := (_ : k j ∈ Finset.image k Finset.univ βˆͺ {kx, ky}), snd := g j } } } }) Finset.univ S : K T : {X : K} β†’ X ∈ O β†’ (X ⟢ S) W : βˆ€ {X Y : K} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟢ Y}, { fst := X, snd := { fst := Y, snd := { fst := mX, snd := { fst := mY, snd := f } } } } ∈ H β†’ f ≫ T mY = T mX fH : βˆ€ (j : J), { fst := kx, snd := { fst := k j, snd := { fst := kxO, snd := { fst := (_ : k j ∈ O), snd := f j } } } } ∈ H j : J ⊒ { fst := ky, snd := { fst := k j, snd := { fst := kyO, snd := { fst := (_ : k j ∈ O), snd := g j } } } } ∈ Finset.image (fun j => { fst := ky, snd := { fst := k j, snd := { fst := kyO, snd := { fst := (_ : k j ∈ Finset.image k Finset.univ βˆͺ {kx, ky}), snd := g j } } } }) Finset.univ [PROOFSTEP] simp only [true_and_iff, Finset.mem_univ, eq_self_iff_true, exists_prop_of_true, Finset.mem_image, heq_iff_eq] [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : Finite J val✝ : Fintype J kx : K x : limit ((curry.obj (swap K J β‹™ F)).obj kx) ky : K y : limit ((curry.obj (swap K J β‹™ F)).obj ky) h : βˆ€ (j : J), βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) k : J β†’ K := fun j => Exists.choose (_ : βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) f : (j : J) β†’ kx ⟢ k j := fun j => Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) g : (j : J) β†’ ky ⟢ k j := fun j => Exists.choose (_ : βˆƒ g, F.map (πŸ™ j, Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y))) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) w : βˆ€ (j : J), F.map (πŸ™ j, f j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) O : Finset K := Finset.image k Finset.univ βˆͺ {kx, ky} kxO : kx ∈ O kyO : ky ∈ O kjO : βˆ€ (j : J), k j ∈ O H : Finset ((X : K) Γ—' (Y : K) Γ—' (_ : X ∈ O) Γ—' (_ : Y ∈ O) Γ—' (X ⟢ Y)) := Finset.image (fun j => { fst := kx, snd := { fst := k j, snd := { fst := kxO, snd := { fst := (_ : k j ∈ Finset.image k Finset.univ βˆͺ {kx, ky}), snd := f j } } } }) Finset.univ βˆͺ Finset.image (fun j => { fst := ky, snd := { fst := k j, snd := { fst := kyO, snd := { fst := (_ : k j ∈ Finset.image k Finset.univ βˆͺ {kx, ky}), snd := g j } } } }) Finset.univ S : K T : {X : K} β†’ X ∈ O β†’ (X ⟢ S) W : βˆ€ {X Y : K} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟢ Y}, { fst := X, snd := { fst := Y, snd := { fst := mX, snd := { fst := mY, snd := f } } } } ∈ H β†’ f ≫ T mY = T mX fH : βˆ€ (j : J), { fst := kx, snd := { fst := k j, snd := { fst := kxO, snd := { fst := (_ : k j ∈ O), snd := f j } } } } ∈ H j : J ⊒ βˆƒ a, { fst := ky, snd := { fst := Exists.choose (_ : βˆƒ k f g, F.map (πŸ™ a, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) a x) = F.map (πŸ™ a, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) a y)), snd := { fst := kyO, snd := { fst := (_ : k a ∈ Finset.image k Finset.univ βˆͺ {kx, ky}), snd := Exists.choose (_ : βˆƒ g, F.map (πŸ™ a, Exists.choose (_ : βˆƒ f g, F.map (πŸ™ a, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) a x) = F.map (πŸ™ a, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) a y))) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) a x) = F.map (πŸ™ a, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) a y)) } } } } = { fst := ky, snd := { fst := Exists.choose (_ : βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)), snd := { fst := kyO, snd := { fst := (_ : k j ∈ O), snd := Exists.choose (_ : βˆƒ g, F.map (πŸ™ j, Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y))) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) } } } } [PROOFSTEP] refine' ⟨j, _⟩ [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : Finite J val✝ : Fintype J kx : K x : limit ((curry.obj (swap K J β‹™ F)).obj kx) ky : K y : limit ((curry.obj (swap K J β‹™ F)).obj ky) h : βˆ€ (j : J), βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) k : J β†’ K := fun j => Exists.choose (_ : βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) f : (j : J) β†’ kx ⟢ k j := fun j => Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) g : (j : J) β†’ ky ⟢ k j := fun j => Exists.choose (_ : βˆƒ g, F.map (πŸ™ j, Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y))) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) w : βˆ€ (j : J), F.map (πŸ™ j, f j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) O : Finset K := Finset.image k Finset.univ βˆͺ {kx, ky} kxO : kx ∈ O kyO : ky ∈ O kjO : βˆ€ (j : J), k j ∈ O H : Finset ((X : K) Γ—' (Y : K) Γ—' (_ : X ∈ O) Γ—' (_ : Y ∈ O) Γ—' (X ⟢ Y)) := Finset.image (fun j => { fst := kx, snd := { fst := k j, snd := { fst := kxO, snd := { fst := (_ : k j ∈ Finset.image k Finset.univ βˆͺ {kx, ky}), snd := f j } } } }) Finset.univ βˆͺ Finset.image (fun j => { fst := ky, snd := { fst := k j, snd := { fst := kyO, snd := { fst := (_ : k j ∈ Finset.image k Finset.univ βˆͺ {kx, ky}), snd := g j } } } }) Finset.univ S : K T : {X : K} β†’ X ∈ O β†’ (X ⟢ S) W : βˆ€ {X Y : K} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟢ Y}, { fst := X, snd := { fst := Y, snd := { fst := mX, snd := { fst := mY, snd := f } } } } ∈ H β†’ f ≫ T mY = T mX fH : βˆ€ (j : J), { fst := kx, snd := { fst := k j, snd := { fst := kxO, snd := { fst := (_ : k j ∈ O), snd := f j } } } } ∈ H j : J ⊒ { fst := ky, snd := { fst := Exists.choose (_ : βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)), snd := { fst := kyO, snd := { fst := (_ : k j ∈ Finset.image k Finset.univ βˆͺ {kx, ky}), snd := Exists.choose (_ : βˆƒ g, F.map (πŸ™ j, Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y))) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) } } } } = { fst := ky, snd := { fst := Exists.choose (_ : βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)), snd := { fst := kyO, snd := { fst := (_ : k j ∈ O), snd := Exists.choose (_ : βˆƒ g, F.map (πŸ™ j, Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y))) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) } } } } [PROOFSTEP] simp only [heq_iff_eq] [GOAL] case intro.intro.intro.intro.intro.intro.intro J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : Finite J val✝ : Fintype J kx : K x : limit ((curry.obj (swap K J β‹™ F)).obj kx) ky : K y : limit ((curry.obj (swap K J β‹™ F)).obj ky) h : βˆ€ (j : J), βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) k : J β†’ K := fun j => Exists.choose (_ : βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) f : (j : J) β†’ kx ⟢ k j := fun j => Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) g : (j : J) β†’ ky ⟢ k j := fun j => Exists.choose (_ : βˆƒ g, F.map (πŸ™ j, Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y))) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) w : βˆ€ (j : J), F.map (πŸ™ j, f j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) O : Finset K := Finset.image k Finset.univ βˆͺ {kx, ky} kxO : kx ∈ O kyO : ky ∈ O kjO : βˆ€ (j : J), k j ∈ O H : Finset ((X : K) Γ—' (Y : K) Γ—' (_ : X ∈ O) Γ—' (_ : Y ∈ O) Γ—' (X ⟢ Y)) := Finset.image (fun j => { fst := kx, snd := { fst := k j, snd := { fst := kxO, snd := { fst := (_ : k j ∈ Finset.image k Finset.univ βˆͺ {kx, ky}), snd := f j } } } }) Finset.univ βˆͺ Finset.image (fun j => { fst := ky, snd := { fst := k j, snd := { fst := kyO, snd := { fst := (_ : k j ∈ Finset.image k Finset.univ βˆͺ {kx, ky}), snd := g j } } } }) Finset.univ S : K T : {X : K} β†’ X ∈ O β†’ (X ⟢ S) W : βˆ€ {X Y : K} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟢ Y}, { fst := X, snd := { fst := Y, snd := { fst := mX, snd := { fst := mY, snd := f } } } } ∈ H β†’ f ≫ T mY = T mX fH : βˆ€ (j : J), { fst := kx, snd := { fst := k j, snd := { fst := kxO, snd := { fst := (_ : k j ∈ O), snd := f j } } } } ∈ H gH : βˆ€ (j : J), { fst := ky, snd := { fst := k j, snd := { fst := kyO, snd := { fst := (_ : k j ∈ O), snd := g j } } } } ∈ H ⊒ colimit.ΞΉ (curry.obj (swap K J β‹™ F) β‹™ lim) kx x = colimit.ΞΉ (curry.obj (swap K J β‹™ F) β‹™ lim) ky y [PROOFSTEP] apply colimit_sound'.{v, v} (T kxO) (T kyO) -- We can check if two elements of a limit (in `Type`) -- are equal by comparing them componentwise. [GOAL] case intro.intro.intro.intro.intro.intro.intro J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : Finite J val✝ : Fintype J kx : K x : limit ((curry.obj (swap K J β‹™ F)).obj kx) ky : K y : limit ((curry.obj (swap K J β‹™ F)).obj ky) h : βˆ€ (j : J), βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) k : J β†’ K := fun j => Exists.choose (_ : βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) f : (j : J) β†’ kx ⟢ k j := fun j => Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) g : (j : J) β†’ ky ⟢ k j := fun j => Exists.choose (_ : βˆƒ g, F.map (πŸ™ j, Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y))) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) w : βˆ€ (j : J), F.map (πŸ™ j, f j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) O : Finset K := Finset.image k Finset.univ βˆͺ {kx, ky} kxO : kx ∈ O kyO : ky ∈ O kjO : βˆ€ (j : J), k j ∈ O H : Finset ((X : K) Γ—' (Y : K) Γ—' (_ : X ∈ O) Γ—' (_ : Y ∈ O) Γ—' (X ⟢ Y)) := Finset.image (fun j => { fst := kx, snd := { fst := k j, snd := { fst := kxO, snd := { fst := (_ : k j ∈ Finset.image k Finset.univ βˆͺ {kx, ky}), snd := f j } } } }) Finset.univ βˆͺ Finset.image (fun j => { fst := ky, snd := { fst := k j, snd := { fst := kyO, snd := { fst := (_ : k j ∈ Finset.image k Finset.univ βˆͺ {kx, ky}), snd := g j } } } }) Finset.univ S : K T : {X : K} β†’ X ∈ O β†’ (X ⟢ S) W : βˆ€ {X Y : K} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟢ Y}, { fst := X, snd := { fst := Y, snd := { fst := mX, snd := { fst := mY, snd := f } } } } ∈ H β†’ f ≫ T mY = T mX fH : βˆ€ (j : J), { fst := kx, snd := { fst := k j, snd := { fst := kxO, snd := { fst := (_ : k j ∈ O), snd := f j } } } } ∈ H gH : βˆ€ (j : J), { fst := ky, snd := { fst := k j, snd := { fst := kyO, snd := { fst := (_ : k j ∈ O), snd := g j } } } } ∈ H ⊒ (curry.obj (swap K J β‹™ F) β‹™ lim).map (T kxO) x = (curry.obj (swap K J β‹™ F) β‹™ lim).map (T kyO) y [PROOFSTEP] ext j [GOAL] case intro.intro.intro.intro.intro.intro.intro.w J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : Finite J val✝ : Fintype J kx : K x : limit ((curry.obj (swap K J β‹™ F)).obj kx) ky : K y : limit ((curry.obj (swap K J β‹™ F)).obj ky) h : βˆ€ (j : J), βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) k : J β†’ K := fun j => Exists.choose (_ : βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) f : (j : J) β†’ kx ⟢ k j := fun j => Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) g : (j : J) β†’ ky ⟢ k j := fun j => Exists.choose (_ : βˆƒ g, F.map (πŸ™ j, Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y))) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) w : βˆ€ (j : J), F.map (πŸ™ j, f j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) O : Finset K := Finset.image k Finset.univ βˆͺ {kx, ky} kxO : kx ∈ O kyO : ky ∈ O kjO : βˆ€ (j : J), k j ∈ O H : Finset ((X : K) Γ—' (Y : K) Γ—' (_ : X ∈ O) Γ—' (_ : Y ∈ O) Γ—' (X ⟢ Y)) := Finset.image (fun j => { fst := kx, snd := { fst := k j, snd := { fst := kxO, snd := { fst := (_ : k j ∈ Finset.image k Finset.univ βˆͺ {kx, ky}), snd := f j } } } }) Finset.univ βˆͺ Finset.image (fun j => { fst := ky, snd := { fst := k j, snd := { fst := kyO, snd := { fst := (_ : k j ∈ Finset.image k Finset.univ βˆͺ {kx, ky}), snd := g j } } } }) Finset.univ S : K T : {X : K} β†’ X ∈ O β†’ (X ⟢ S) W : βˆ€ {X Y : K} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟢ Y}, { fst := X, snd := { fst := Y, snd := { fst := mX, snd := { fst := mY, snd := f } } } } ∈ H β†’ f ≫ T mY = T mX fH : βˆ€ (j : J), { fst := kx, snd := { fst := k j, snd := { fst := kxO, snd := { fst := (_ : k j ∈ O), snd := f j } } } } ∈ H gH : βˆ€ (j : J), { fst := ky, snd := { fst := k j, snd := { fst := kyO, snd := { fst := (_ : k j ∈ O), snd := g j } } } } ∈ H j : J ⊒ limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj S) j ((curry.obj (swap K J β‹™ F) β‹™ lim).map (T kxO) x) = limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj S) j ((curry.obj (swap K J β‹™ F) β‹™ lim).map (T kyO) y) [PROOFSTEP] simp only [Functor.comp_map, Limit.map_Ο€_apply, curry_obj_map_app, swap_map] [GOAL] case intro.intro.intro.intro.intro.intro.intro.w J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : Finite J val✝ : Fintype J kx : K x : limit ((curry.obj (swap K J β‹™ F)).obj kx) ky : K y : limit ((curry.obj (swap K J β‹™ F)).obj ky) h : βˆ€ (j : J), βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) k : J β†’ K := fun j => Exists.choose (_ : βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) f : (j : J) β†’ kx ⟢ k j := fun j => Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) g : (j : J) β†’ ky ⟢ k j := fun j => Exists.choose (_ : βˆƒ g, F.map (πŸ™ j, Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y))) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) w : βˆ€ (j : J), F.map (πŸ™ j, f j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) O : Finset K := Finset.image k Finset.univ βˆͺ {kx, ky} kxO : kx ∈ O kyO : ky ∈ O kjO : βˆ€ (j : J), k j ∈ O H : Finset ((X : K) Γ—' (Y : K) Γ—' (_ : X ∈ O) Γ—' (_ : Y ∈ O) Γ—' (X ⟢ Y)) := Finset.image (fun j => { fst := kx, snd := { fst := k j, snd := { fst := kxO, snd := { fst := (_ : k j ∈ Finset.image k Finset.univ βˆͺ {kx, ky}), snd := f j } } } }) Finset.univ βˆͺ Finset.image (fun j => { fst := ky, snd := { fst := k j, snd := { fst := kyO, snd := { fst := (_ : k j ∈ Finset.image k Finset.univ βˆͺ {kx, ky}), snd := g j } } } }) Finset.univ S : K T : {X : K} β†’ X ∈ O β†’ (X ⟢ S) W : βˆ€ {X Y : K} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟢ Y}, { fst := X, snd := { fst := Y, snd := { fst := mX, snd := { fst := mY, snd := f } } } } ∈ H β†’ f ≫ T mY = T mX fH : βˆ€ (j : J), { fst := kx, snd := { fst := k j, snd := { fst := kxO, snd := { fst := (_ : k j ∈ O), snd := f j } } } } ∈ H gH : βˆ€ (j : J), { fst := ky, snd := { fst := k j, snd := { fst := kyO, snd := { fst := (_ : k j ∈ O), snd := g j } } } } ∈ H j : J ⊒ limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj S) j (lim.map ((curry.obj (swap K J β‹™ F)).map (T kxO)) x) = limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj S) j (lim.map ((curry.obj (swap K J β‹™ F)).map (T kyO)) y) [PROOFSTEP] rw [← W _ _ (fH j)] [GOAL] case intro.intro.intro.intro.intro.intro.intro.w J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : Finite J val✝ : Fintype J kx : K x : limit ((curry.obj (swap K J β‹™ F)).obj kx) ky : K y : limit ((curry.obj (swap K J β‹™ F)).obj ky) h : βˆ€ (j : J), βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) k : J β†’ K := fun j => Exists.choose (_ : βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) f : (j : J) β†’ kx ⟢ k j := fun j => Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) g : (j : J) β†’ ky ⟢ k j := fun j => Exists.choose (_ : βˆƒ g, F.map (πŸ™ j, Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y))) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) w : βˆ€ (j : J), F.map (πŸ™ j, f j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) O : Finset K := Finset.image k Finset.univ βˆͺ {kx, ky} kxO : kx ∈ O kyO : ky ∈ O kjO : βˆ€ (j : J), k j ∈ O H : Finset ((X : K) Γ—' (Y : K) Γ—' (_ : X ∈ O) Γ—' (_ : Y ∈ O) Γ—' (X ⟢ Y)) := Finset.image (fun j => { fst := kx, snd := { fst := k j, snd := { fst := kxO, snd := { fst := (_ : k j ∈ Finset.image k Finset.univ βˆͺ {kx, ky}), snd := f j } } } }) Finset.univ βˆͺ Finset.image (fun j => { fst := ky, snd := { fst := k j, snd := { fst := kyO, snd := { fst := (_ : k j ∈ Finset.image k Finset.univ βˆͺ {kx, ky}), snd := g j } } } }) Finset.univ S : K T : {X : K} β†’ X ∈ O β†’ (X ⟢ S) W : βˆ€ {X Y : K} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟢ Y}, { fst := X, snd := { fst := Y, snd := { fst := mX, snd := { fst := mY, snd := f } } } } ∈ H β†’ f ≫ T mY = T mX fH : βˆ€ (j : J), { fst := kx, snd := { fst := k j, snd := { fst := kxO, snd := { fst := (_ : k j ∈ O), snd := f j } } } } ∈ H gH : βˆ€ (j : J), { fst := ky, snd := { fst := k j, snd := { fst := kyO, snd := { fst := (_ : k j ∈ O), snd := g j } } } } ∈ H j : J ⊒ limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj S) j (lim.map ((curry.obj (swap K J β‹™ F)).map (f j ≫ T (_ : k j ∈ O))) x) = limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj S) j (lim.map ((curry.obj (swap K J β‹™ F)).map (T kyO)) y) [PROOFSTEP] rw [← W _ _ (gH j)] -- porting note: this was `simp [w]` in lean 3; this is presumably a confluence issue [GOAL] case intro.intro.intro.intro.intro.intro.intro.w J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : Finite J val✝ : Fintype J kx : K x : limit ((curry.obj (swap K J β‹™ F)).obj kx) ky : K y : limit ((curry.obj (swap K J β‹™ F)).obj ky) h : βˆ€ (j : J), βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) k : J β†’ K := fun j => Exists.choose (_ : βˆƒ k f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) f : (j : J) β†’ kx ⟢ k j := fun j => Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) g : (j : J) β†’ ky ⟢ k j := fun j => Exists.choose (_ : βˆƒ g, F.map (πŸ™ j, Exists.choose (_ : βˆƒ f g, F.map (πŸ™ j, f) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y))) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y)) w : βˆ€ (j : J), F.map (πŸ™ j, f j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj kx) j x) = F.map (πŸ™ j, g j) (limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj ky) j y) O : Finset K := Finset.image k Finset.univ βˆͺ {kx, ky} kxO : kx ∈ O kyO : ky ∈ O kjO : βˆ€ (j : J), k j ∈ O H : Finset ((X : K) Γ—' (Y : K) Γ—' (_ : X ∈ O) Γ—' (_ : Y ∈ O) Γ—' (X ⟢ Y)) := Finset.image (fun j => { fst := kx, snd := { fst := k j, snd := { fst := kxO, snd := { fst := (_ : k j ∈ Finset.image k Finset.univ βˆͺ {kx, ky}), snd := f j } } } }) Finset.univ βˆͺ Finset.image (fun j => { fst := ky, snd := { fst := k j, snd := { fst := kyO, snd := { fst := (_ : k j ∈ Finset.image k Finset.univ βˆͺ {kx, ky}), snd := g j } } } }) Finset.univ S : K T : {X : K} β†’ X ∈ O β†’ (X ⟢ S) W : βˆ€ {X Y : K} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟢ Y}, { fst := X, snd := { fst := Y, snd := { fst := mX, snd := { fst := mY, snd := f } } } } ∈ H β†’ f ≫ T mY = T mX fH : βˆ€ (j : J), { fst := kx, snd := { fst := k j, snd := { fst := kxO, snd := { fst := (_ : k j ∈ O), snd := f j } } } } ∈ H gH : βˆ€ (j : J), { fst := ky, snd := { fst := k j, snd := { fst := kyO, snd := { fst := (_ : k j ∈ O), snd := g j } } } } ∈ H j : J ⊒ limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj S) j (lim.map ((curry.obj (swap K J β‹™ F)).map (f j ≫ T (_ : k j ∈ O))) x) = limit.Ο€ ((curry.obj (swap K J β‹™ F)).obj S) j (lim.map ((curry.obj (swap K J β‹™ F)).map (g j ≫ T (_ : k j ∈ O))) y) [PROOFSTEP] rw [lim_map, lim_map, Limit.map_Ο€_apply', Limit.map_Ο€_apply', Functor.map_comp, Functor.map_comp, FunctorToTypes.comp, FunctorToTypes.comp, curry_obj_map_app, curry_obj_map_app, curry_obj_map_app, Functor.comp_map, Functor.comp_map, Functor.comp_map, swap_map, swap_map, swap_map, w] [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J ⊒ Function.Surjective (colimitLimitToLimitColimit F) [PROOFSTEP] classical -- We begin with some element `x` in the limit (over J) over the colimits (over K), intro x have z := fun j => jointly_surjective'.{v, v} (limit.Ο€ (curry.obj F β‹™ Limits.colim) j x) -- `k : J ⟢ K` records where the representative of the -- element in the `j`-th element of `x` lives let k : J β†’ K := fun j => (z j).choose let y : βˆ€ j, F.obj (j, k j) := fun j => (z j).choose_spec.choose have e : βˆ€ j, colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ Limits.colim) j x := fun j => (z j).choose_spec.choose_spec clear_value k y clear z let k' : K := IsFiltered.sup (Finset.univ.image k) βˆ… -- and name the morphisms as `g j : k j ⟢ k'`. have g : βˆ€ j, k j ⟢ k' := fun j => IsFiltered.toSup (Finset.univ.image k) βˆ… (by simp) clear_value k' have w : βˆ€ {j j' : J} (f : j ⟢ j'), colimit.ΞΉ ((curry.obj F).obj j') k' (F.map ((πŸ™ j', g j') : (j', k j') ⟢ (j', k')) (y j')) = colimit.ΞΉ ((curry.obj F).obj j') k' (F.map ((f, g j) : (j, k j) ⟢ (j', k')) (y j)) := by intro j j' f have t : (f, g j) = (((f, πŸ™ (k j)) : (j, k j) ⟢ (j', k j)) ≫ (πŸ™ j', g j) : (j, k j) ⟢ (j', k')) := by simp only [id_comp, comp_id, prod_comp] erw [Colimit.w_apply', t, FunctorToTypes.map_comp_apply, Colimit.w_apply', e, ← Limit.w_apply' f, ← e] simp -- Because `K` is filtered, we can restate this as saying that -- for each such `f`, there is some place to the right of `k'` -- where these images of `y j` and `y j'` become equal. simp_rw [colimit_eq_iff.{v, v}] at w let kf : βˆ€ {j j'} (_ : j ⟢ j'), K := fun f => (w f).choose let gf : βˆ€ {j j'} (f : j ⟢ j'), k' ⟢ kf f := fun f => (w f).choose_spec.choose let hf : βˆ€ {j j'} (f : j ⟢ j'), k' ⟢ kf f := fun f => (w f).choose_spec.choose_spec.choose have wf : βˆ€ {j j'} (f : j ⟢ j'), F.map ((πŸ™ j', g j' ≫ gf f) : (j', k j') ⟢ (j', kf f)) (y j') = F.map ((f, g j ≫ hf f) : (j, k j) ⟢ (j', kf f)) (y j) := fun {j j'} f => by have q : ((curry.obj F).obj j').map (gf f) (F.map ((πŸ™ j', g j') : (j', k j') ⟢ (j', k')) (y j')) = ((curry.obj F).obj j').map (hf f) (F.map ((f, g j) : (j, k j) ⟢ (j', k')) (y j)) := (w f).choose_spec.choose_spec.choose_spec rw [curry_obj_obj_map, curry_obj_obj_map] at q simp_rw [← FunctorToTypes.map_comp_apply, CategoryStruct.comp] at q convert q <;> simp only [comp_id] clear_value kf gf hf clear w let O := (Finset.univ.biUnion fun j => Finset.univ.biUnion fun j' => Finset.univ.image (@kf j j')) βˆͺ { k' } have kfO : βˆ€ {j j'} (f : j ⟢ j'), kf f ∈ O := fun {j} {j'} f => Finset.mem_union.mpr (Or.inl (by rw [Finset.mem_biUnion] refine' ⟨j, Finset.mem_univ j, _⟩ rw [Finset.mem_biUnion] refine' ⟨j', Finset.mem_univ j', _⟩ rw [Finset.mem_image] refine' ⟨f, Finset.mem_univ _, _⟩ rfl)) have k'O : k' ∈ O := Finset.mem_union.mpr (Or.inr (Finset.mem_singleton.mpr rfl)) let H : Finset (Ξ£' (X Y : K) (_ : X ∈ O) (_ : Y ∈ O), X ⟢ Y) := Finset.univ.biUnion fun j : J => Finset.univ.biUnion fun j' : J => Finset.univ.biUnion fun f : j ⟢ j' => {⟨k', kf f, k'O, kfO f, gf f⟩, ⟨k', kf f, k'O, kfO f, hf f⟩} obtain ⟨k'', i', s'⟩ := IsFiltered.sup_exists O H let i : βˆ€ {j j'} (f : j ⟢ j'), kf f ⟢ k'' := fun {j} {j'} f => i' (kfO f) have s : βˆ€ {j₁ jβ‚‚ j₃ jβ‚„} (f : j₁ ⟢ jβ‚‚) (f' : j₃ ⟢ jβ‚„), gf f ≫ i f = hf f' ≫ i f' := by intros j₁ jβ‚‚ j₃ jβ‚„ f f' rw [s', s'] -- porting note: the three goals here in Lean 3 were in a different order exact k'O swap Β· rw [Finset.mem_biUnion] refine' ⟨j₁, Finset.mem_univ _, _⟩ rw [Finset.mem_biUnion] refine' ⟨jβ‚‚, Finset.mem_univ _, _⟩ rw [Finset.mem_biUnion] refine' ⟨f, Finset.mem_univ _, _⟩ simp only [true_or_iff, eq_self_iff_true, and_self_iff, Finset.mem_insert, heq_iff_eq] Β· rw [Finset.mem_biUnion] refine' ⟨j₃, Finset.mem_univ _, _⟩ rw [Finset.mem_biUnion] refine' ⟨jβ‚„, Finset.mem_univ _, _⟩ rw [Finset.mem_biUnion] refine' ⟨f', Finset.mem_univ _, _⟩ simp only [eq_self_iff_true, or_true_iff, and_self_iff, Finset.mem_insert, Finset.mem_singleton, heq_iff_eq] clear_value i clear s' i' H kfO k'O O fconstructor Β· -- We construct the pre-image (which, recall is meant to be a point -- in the colimit (over `K`) of the limits (over `J`)) via a representative at `k''`. apply colimit.ΞΉ (curry.obj (swap K J β‹™ F) β‹™ Limits.lim) k'' _ dsimp -- This representative is meant to be an element of a limit, -- so we need to construct a family of elements in `F.obj (j, k'')` for varying `j`, -- then show that are coherent with respect to morphisms in the `j` direction. apply Limit.mk.{v, v} swap Β· -- We construct the elements as the images of the `y j`.exact fun j => F.map (βŸ¨πŸ™ j, g j ≫ gf (πŸ™ j) ≫ i (πŸ™ j)⟩ : (j, k j) ⟢ (j, k'')) (y j) Β· -- After which it's just a calculation, using `s` and `wf`, to see they are coherent. dsimp intro j j' f simp only [← FunctorToTypes.map_comp_apply, prod_comp, id_comp, comp_id] calc F.map ((f, g j ≫ gf (πŸ™ j) ≫ i (πŸ™ j)) : (j, k j) ⟢ (j', k'')) (y j) = F.map ((f, g j ≫ hf f ≫ i f) : (j, k j) ⟢ (j', k'')) (y j) := by rw [s (πŸ™ j) f] _ = F.map ((πŸ™ j', i f) : (j', kf f) ⟢ (j', k'')) (F.map ((f, g j ≫ hf f) : (j, k j) ⟢ (j', kf f)) (y j)) := by rw [← FunctorToTypes.map_comp_apply, prod_comp, comp_id, assoc] _ = F.map ((πŸ™ j', i f) : (j', kf f) ⟢ (j', k'')) (F.map ((πŸ™ j', g j' ≫ gf f) : (j', k j') ⟢ (j', kf f)) (y j')) := by rw [← wf f] _ = F.map ((πŸ™ j', g j' ≫ gf f ≫ i f) : (j', k j') ⟢ (j', k'')) (y j') := by rw [← FunctorToTypes.map_comp_apply, prod_comp, id_comp, assoc] _ = F.map ((πŸ™ j', g j' ≫ gf (πŸ™ j') ≫ i (πŸ™ j')) : (j', k j') ⟢ (j', k'')) (y j') := by rw [s f (πŸ™ j'), ← s (πŸ™ j') (πŸ™ j')] -- Finally we check that this maps to `x`. Β· -- We can do this componentwise: apply limit_ext' intro j simp only [id.def, ← e, Limits.ΞΉ_colimitLimitToLimitColimit_Ο€_apply, colimit_eq_iff.{v, v}, Bifunctor.map_id_comp, types_comp_apply, curry_obj_obj_map, Functor.comp_obj, colim_obj, Limit.Ο€_mk] refine' ⟨k'', πŸ™ k'', g j ≫ gf (πŸ™ j) ≫ i (πŸ™ j), _⟩ -- porting note: the lean 3 proof finished with -- `simp only [Bifunctor.map_id_comp, types_comp_apply, Bifunctor.map_id, types_id_apply]` -- which doesn't work; the corresponding `rw` works fine: rw [Bifunctor.map_id_comp, Bifunctor.map_id_comp, types_comp_apply, types_comp_apply, Bifunctor.map_id, types_id_apply] [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J ⊒ Function.Surjective (colimitLimitToLimitColimit F) [PROOFSTEP] intro x [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) ⊒ βˆƒ a, colimitLimitToLimitColimit F a = x [PROOFSTEP] have z := fun j => jointly_surjective'.{v, v} (limit.Ο€ (curry.obj F β‹™ Limits.colim) j x) -- `k : J ⟢ K` records where the representative of the -- element in the `j`-th element of `x` lives [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) z : βˆ€ (j : J), βˆƒ j_1 y, colimit.ΞΉ ((curry.obj F).obj j) j_1 y = limit.Ο€ (curry.obj F β‹™ colim) j x ⊒ βˆƒ a, colimitLimitToLimitColimit F a = x [PROOFSTEP] let k : J β†’ K := fun j => (z j).choose [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) z : βˆ€ (j : J), βˆƒ j_1 y, colimit.ΞΉ ((curry.obj F).obj j) j_1 y = limit.Ο€ (curry.obj F β‹™ colim) j x k : J β†’ K := fun j => Exists.choose (_ : βˆƒ j_1 y, colimit.ΞΉ ((curry.obj F).obj j) j_1 y = limit.Ο€ (curry.obj F β‹™ colim) j x) ⊒ βˆƒ a, colimitLimitToLimitColimit F a = x [PROOFSTEP] let y : βˆ€ j, F.obj (j, k j) := fun j => (z j).choose_spec.choose [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) z : βˆ€ (j : J), βˆƒ j_1 y, colimit.ΞΉ ((curry.obj F).obj j) j_1 y = limit.Ο€ (curry.obj F β‹™ colim) j x k : J β†’ K := fun j => Exists.choose (_ : βˆƒ j_1 y, colimit.ΞΉ ((curry.obj F).obj j) j_1 y = limit.Ο€ (curry.obj F β‹™ colim) j x) y : (j : J) β†’ F.obj (j, k j) := fun j => Exists.choose (_ : βˆƒ y, colimit.ΞΉ ((curry.obj F).obj j) (Exists.choose (_ : βˆƒ j_1 y, colimit.ΞΉ ((curry.obj F).obj j) j_1 y = limit.Ο€ (curry.obj F β‹™ colim) j x)) y = limit.Ο€ (curry.obj F β‹™ colim) j x) ⊒ βˆƒ a, colimitLimitToLimitColimit F a = x [PROOFSTEP] have e : βˆ€ j, colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ Limits.colim) j x := fun j => (z j).choose_spec.choose_spec [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) z : βˆ€ (j : J), βˆƒ j_1 y, colimit.ΞΉ ((curry.obj F).obj j) j_1 y = limit.Ο€ (curry.obj F β‹™ colim) j x k : J β†’ K := fun j => Exists.choose (_ : βˆƒ j_1 y, colimit.ΞΉ ((curry.obj F).obj j) j_1 y = limit.Ο€ (curry.obj F β‹™ colim) j x) y : (j : J) β†’ F.obj (j, k j) := fun j => Exists.choose (_ : βˆƒ y, colimit.ΞΉ ((curry.obj F).obj j) (Exists.choose (_ : βˆƒ j_1 y, colimit.ΞΉ ((curry.obj F).obj j) j_1 y = limit.Ο€ (curry.obj F β‹™ colim) j x)) y = limit.Ο€ (curry.obj F β‹™ colim) j x) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x ⊒ βˆƒ a, colimitLimitToLimitColimit F a = x [PROOFSTEP] clear_value k y [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) z : βˆ€ (j : J), βˆƒ j_1 y, colimit.ΞΉ ((curry.obj F).obj j) j_1 y = limit.Ο€ (curry.obj F β‹™ colim) j x k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x ⊒ βˆƒ a, colimitLimitToLimitColimit F a = x [PROOFSTEP] clear z [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x ⊒ βˆƒ a, colimitLimitToLimitColimit F a = x [PROOFSTEP] let k' : K := IsFiltered.sup (Finset.univ.image k) βˆ… -- and name the morphisms as `g j : k j ⟢ k'`. [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K := IsFiltered.sup (Finset.image k Finset.univ) βˆ… ⊒ βˆƒ a, colimitLimitToLimitColimit F a = x [PROOFSTEP] have g : βˆ€ j, k j ⟢ k' := fun j => IsFiltered.toSup (Finset.univ.image k) βˆ… (by simp) [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K := IsFiltered.sup (Finset.image k Finset.univ) βˆ… j : J ⊒ k j ∈ Finset.image k Finset.univ [PROOFSTEP] simp [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K := IsFiltered.sup (Finset.image k Finset.univ) βˆ… g : (j : J) β†’ k j ⟢ k' ⊒ βˆƒ a, colimitLimitToLimitColimit F a = x [PROOFSTEP] clear_value k' [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' ⊒ βˆƒ a, colimitLimitToLimitColimit F a = x [PROOFSTEP] have w : βˆ€ {j j' : J} (f : j ⟢ j'), colimit.ΞΉ ((curry.obj F).obj j') k' (F.map ((πŸ™ j', g j') : (j', k j') ⟢ (j', k')) (y j')) = colimit.ΞΉ ((curry.obj F).obj j') k' (F.map ((f, g j) : (j, k j) ⟢ (j', k')) (y j)) := by intro j j' f have t : (f, g j) = (((f, πŸ™ (k j)) : (j, k j) ⟢ (j', k j)) ≫ (πŸ™ j', g j) : (j, k j) ⟢ (j', k')) := by simp only [id_comp, comp_id, prod_comp] erw [Colimit.w_apply', t, FunctorToTypes.map_comp_apply, Colimit.w_apply', e, ← Limit.w_apply' f, ← e] simp -- Because `K` is filtered, we can restate this as saying that -- for each such `f`, there is some place to the right of `k'` -- where these images of `y j` and `y j'` become equal. [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' ⊒ βˆ€ {j j' : J} (f : j ⟢ j'), colimit.ΞΉ ((curry.obj F).obj j') k' (F.map (πŸ™ j', g j') (y j')) = colimit.ΞΉ ((curry.obj F).obj j') k' (F.map (f, g j) (y j)) [PROOFSTEP] intro j j' f [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' j j' : J f : j ⟢ j' ⊒ colimit.ΞΉ ((curry.obj F).obj j') k' (F.map (πŸ™ j', g j') (y j')) = colimit.ΞΉ ((curry.obj F).obj j') k' (F.map (f, g j) (y j)) [PROOFSTEP] have t : (f, g j) = (((f, πŸ™ (k j)) : (j, k j) ⟢ (j', k j)) ≫ (πŸ™ j', g j) : (j, k j) ⟢ (j', k')) := by simp only [id_comp, comp_id, prod_comp] [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' j j' : J f : j ⟢ j' ⊒ (f, g j) = (f, πŸ™ (k j)) ≫ (πŸ™ j', g j) [PROOFSTEP] simp only [id_comp, comp_id, prod_comp] [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' j j' : J f : j ⟢ j' t : (f, g j) = (f, πŸ™ (k j)) ≫ (πŸ™ j', g j) ⊒ colimit.ΞΉ ((curry.obj F).obj j') k' (F.map (πŸ™ j', g j') (y j')) = colimit.ΞΉ ((curry.obj F).obj j') k' (F.map (f, g j) (y j)) [PROOFSTEP] erw [Colimit.w_apply', t, FunctorToTypes.map_comp_apply, Colimit.w_apply', e, ← Limit.w_apply' f, ← e] [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' j j' : J f : j ⟢ j' t : (f, g j) = (f, πŸ™ (k j)) ≫ (πŸ™ j', g j) ⊒ (curry.obj F β‹™ colim).map f (colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j)) = colimit.ΞΉ ((curry.obj F).obj j') (k j) (F.map (f, πŸ™ (k j)) (y j)) [PROOFSTEP] simp -- Because `K` is filtered, we can restate this as saying that -- for each such `f`, there is some place to the right of `k'` -- where these images of `y j` and `y j'` become equal. [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' w : βˆ€ {j j' : J} (f : j ⟢ j'), colimit.ΞΉ ((curry.obj F).obj j') k' (F.map (πŸ™ j', g j') (y j')) = colimit.ΞΉ ((curry.obj F).obj j') k' (F.map (f, g j) (y j)) ⊒ βˆƒ a, colimitLimitToLimitColimit F a = x [PROOFSTEP] simp_rw [colimit_eq_iff.{v, v}] at w [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' w : βˆ€ {j j' : J} (f : j ⟢ j'), βˆƒ k_1 f_1 g_1, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j)) ⊒ βˆƒ a, colimitLimitToLimitColimit F a = x [PROOFSTEP] let kf : βˆ€ {j j'} (_ : j ⟢ j'), K := fun f => (w f).choose [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' w : βˆ€ {j j' : J} (f : j ⟢ j'), βˆƒ k_1 f_1 g_1, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j)) kf : {j j' : J} β†’ (j ⟢ j') β†’ K := fun {j j'} f => Exists.choose (_ : βˆƒ k_1 f_1 g_1, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j))) ⊒ βˆƒ a, colimitLimitToLimitColimit F a = x [PROOFSTEP] let gf : βˆ€ {j j'} (f : j ⟢ j'), k' ⟢ kf f := fun f => (w f).choose_spec.choose [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' w : βˆ€ {j j' : J} (f : j ⟢ j'), βˆƒ k_1 f_1 g_1, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j)) kf : {j j' : J} β†’ (j ⟢ j') β†’ K := fun {j j'} f => Exists.choose (_ : βˆƒ k_1 f_1 g_1, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j))) gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f := fun {j j'} f => Exists.choose (_ : βˆƒ f_1 g_1, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j))) ⊒ βˆƒ a, colimitLimitToLimitColimit F a = x [PROOFSTEP] let hf : βˆ€ {j j'} (f : j ⟢ j'), k' ⟢ kf f := fun f => (w f).choose_spec.choose_spec.choose [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' w : βˆ€ {j j' : J} (f : j ⟢ j'), βˆƒ k_1 f_1 g_1, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j)) kf : {j j' : J} β†’ (j ⟢ j') β†’ K := fun {j j'} f => Exists.choose (_ : βˆƒ k_1 f_1 g_1, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j))) gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f := fun {j j'} f => Exists.choose (_ : βˆƒ f_1 g_1, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j))) hf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f := fun {j j'} f => Exists.choose (_ : βˆƒ g_1, ((curry.obj F).obj j').map (Exists.choose (_ : βˆƒ f_1 g_2, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_2 (F.map (f, g j) (y j)))) (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j))) ⊒ βˆƒ a, colimitLimitToLimitColimit F a = x [PROOFSTEP] have wf : βˆ€ {j j'} (f : j ⟢ j'), F.map ((πŸ™ j', g j' ≫ gf f) : (j', k j') ⟢ (j', kf f)) (y j') = F.map ((f, g j ≫ hf f) : (j, k j) ⟢ (j', kf f)) (y j) := fun {j j'} f => by have q : ((curry.obj F).obj j').map (gf f) (F.map ((πŸ™ j', g j') : (j', k j') ⟢ (j', k')) (y j')) = ((curry.obj F).obj j').map (hf f) (F.map ((f, g j) : (j, k j) ⟢ (j', k')) (y j)) := (w f).choose_spec.choose_spec.choose_spec rw [curry_obj_obj_map, curry_obj_obj_map] at q simp_rw [← FunctorToTypes.map_comp_apply, CategoryStruct.comp] at q convert q <;> simp only [comp_id] [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' w : βˆ€ {j j' : J} (f : j ⟢ j'), βˆƒ k_1 f_1 g_1, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j)) kf : {j j' : J} β†’ (j ⟢ j') β†’ K := fun {j j'} f => Exists.choose (_ : βˆƒ k_1 f_1 g_1, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j))) gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f := fun {j j'} f => Exists.choose (_ : βˆƒ f_1 g_1, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j))) hf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f := fun {j j'} f => Exists.choose (_ : βˆƒ g_1, ((curry.obj F).obj j').map (Exists.choose (_ : βˆƒ f_1 g_2, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_2 (F.map (f, g j) (y j)))) (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j))) j j' : J f : j ⟢ j' ⊒ F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) [PROOFSTEP] have q : ((curry.obj F).obj j').map (gf f) (F.map ((πŸ™ j', g j') : (j', k j') ⟢ (j', k')) (y j')) = ((curry.obj F).obj j').map (hf f) (F.map ((f, g j) : (j, k j) ⟢ (j', k')) (y j)) := (w f).choose_spec.choose_spec.choose_spec [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' w : βˆ€ {j j' : J} (f : j ⟢ j'), βˆƒ k_1 f_1 g_1, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j)) kf : {j j' : J} β†’ (j ⟢ j') β†’ K := fun {j j'} f => Exists.choose (_ : βˆƒ k_1 f_1 g_1, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j))) gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f := fun {j j'} f => Exists.choose (_ : βˆƒ f_1 g_1, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j))) hf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f := fun {j j'} f => Exists.choose (_ : βˆƒ g_1, ((curry.obj F).obj j').map (Exists.choose (_ : βˆƒ f_1 g_2, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_2 (F.map (f, g j) (y j)))) (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j))) j j' : J f : j ⟢ j' q : ((curry.obj F).obj j').map (gf f) (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map (hf f) (F.map (f, g j) (y j)) ⊒ F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) [PROOFSTEP] rw [curry_obj_obj_map, curry_obj_obj_map] at q [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' w : βˆ€ {j j' : J} (f : j ⟢ j'), βˆƒ k_1 f_1 g_1, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j)) kf : {j j' : J} β†’ (j ⟢ j') β†’ K := fun {j j'} f => Exists.choose (_ : βˆƒ k_1 f_1 g_1, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j))) gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f := fun {j j'} f => Exists.choose (_ : βˆƒ f_1 g_1, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j))) hf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f := fun {j j'} f => Exists.choose (_ : βˆƒ g_1, ((curry.obj F).obj j').map (Exists.choose (_ : βˆƒ f_1 g_2, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_2 (F.map (f, g j) (y j)))) (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j))) j j' : J f : j ⟢ j' q : F.map (πŸ™ j', gf f) (F.map (πŸ™ j', g j') (y j')) = F.map (πŸ™ j', hf f) (F.map (f, g j) (y j)) ⊒ F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) [PROOFSTEP] simp_rw [← FunctorToTypes.map_comp_apply, CategoryStruct.comp] at q [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' w : βˆ€ {j j' : J} (f : j ⟢ j'), βˆƒ k_1 f_1 g_1, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j)) kf : {j j' : J} β†’ (j ⟢ j') β†’ K := fun {j j'} f => Exists.choose (_ : βˆƒ k_1 f_1 g_1, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j))) gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f := fun {j j'} f => Exists.choose (_ : βˆƒ f_1 g_1, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j))) hf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f := fun {j j'} f => Exists.choose (_ : βˆƒ g_1, ((curry.obj F).obj j').map (Exists.choose (_ : βˆƒ f_1 g_2, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_2 (F.map (f, g j) (y j)))) (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j))) j j' : J f : j ⟢ j' q : F.map (πŸ™ j' ≫ πŸ™ j', g j' ≫ Exists.choose (_ : βˆƒ f_1 g_1, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j)))) (y j') = F.map (f ≫ πŸ™ j', g j ≫ Exists.choose (_ : βˆƒ g_1, ((curry.obj F).obj j').map (Exists.choose (_ : βˆƒ f_1 g_2, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_2 (F.map (f, g j) (y j)))) (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j)))) (y j) ⊒ F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) [PROOFSTEP] convert q [GOAL] case h.e'_2.h.h.e'_4.h.e'_3 J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' w : βˆ€ {j j' : J} (f : j ⟢ j'), βˆƒ k_1 f_1 g_1, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j)) kf : {j j' : J} β†’ (j ⟢ j') β†’ K := fun {j j'} f => Exists.choose (_ : βˆƒ k_1 f_1 g_1, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j))) gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f := fun {j j'} f => Exists.choose (_ : βˆƒ f_1 g_1, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j))) hf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f := fun {j j'} f => Exists.choose (_ : βˆƒ g_1, ((curry.obj F).obj j').map (Exists.choose (_ : βˆƒ f_1 g_2, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_2 (F.map (f, g j) (y j)))) (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j))) j j' : J f : j ⟢ j' q : F.map (πŸ™ j' ≫ πŸ™ j', g j' ≫ Exists.choose (_ : βˆƒ f_1 g_1, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j)))) (y j') = F.map (f ≫ πŸ™ j', g j ≫ Exists.choose (_ : βˆƒ g_1, ((curry.obj F).obj j').map (Exists.choose (_ : βˆƒ f_1 g_2, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_2 (F.map (f, g j) (y j)))) (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j)))) (y j) e_1✝ : F.obj (j', kf f) = ((curry.obj F).obj j').obj (Exists.choose (_ : βˆƒ k_1 f_1 g_1, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j)))) ⊒ πŸ™ j' = πŸ™ j' ≫ πŸ™ j' [PROOFSTEP] simp only [comp_id] [GOAL] case h.e'_3.h.h.e'_4.h.e'_3 J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' w : βˆ€ {j j' : J} (f : j ⟢ j'), βˆƒ k_1 f_1 g_1, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j)) kf : {j j' : J} β†’ (j ⟢ j') β†’ K := fun {j j'} f => Exists.choose (_ : βˆƒ k_1 f_1 g_1, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j))) gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f := fun {j j'} f => Exists.choose (_ : βˆƒ f_1 g_1, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j))) hf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f := fun {j j'} f => Exists.choose (_ : βˆƒ g_1, ((curry.obj F).obj j').map (Exists.choose (_ : βˆƒ f_1 g_2, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_2 (F.map (f, g j) (y j)))) (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j))) j j' : J f : j ⟢ j' q : F.map (πŸ™ j' ≫ πŸ™ j', g j' ≫ Exists.choose (_ : βˆƒ f_1 g_1, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j)))) (y j') = F.map (f ≫ πŸ™ j', g j ≫ Exists.choose (_ : βˆƒ g_1, ((curry.obj F).obj j').map (Exists.choose (_ : βˆƒ f_1 g_2, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_2 (F.map (f, g j) (y j)))) (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j)))) (y j) e_1✝ : F.obj (j', kf f) = ((curry.obj F).obj j').obj (Exists.choose (_ : βˆƒ k_1 f_1 g_1, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j)))) ⊒ f = f ≫ πŸ™ j' [PROOFSTEP] simp only [comp_id] [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' w : βˆ€ {j j' : J} (f : j ⟢ j'), βˆƒ k_1 f_1 g_1, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j)) kf : {j j' : J} β†’ (j ⟢ j') β†’ K := fun {j j'} f => Exists.choose (_ : βˆƒ k_1 f_1 g_1, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j))) gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f := fun {j j'} f => Exists.choose (_ : βˆƒ f_1 g_1, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j))) hf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f := fun {j j'} f => Exists.choose (_ : βˆƒ g_1, ((curry.obj F).obj j').map (Exists.choose (_ : βˆƒ f_1 g_2, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_2 (F.map (f, g j) (y j)))) (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j))) wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) ⊒ βˆƒ a, colimitLimitToLimitColimit F a = x [PROOFSTEP] clear_value kf gf hf [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' w : βˆ€ {j j' : J} (f : j ⟢ j'), βˆƒ k_1 f_1 g_1, ((curry.obj F).obj j').map f_1 (F.map (πŸ™ j', g j') (y j')) = ((curry.obj F).obj j').map g_1 (F.map (f, g j) (y j)) kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) ⊒ βˆƒ a, colimitLimitToLimitColimit F a = x [PROOFSTEP] clear w [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) ⊒ βˆƒ a, colimitLimitToLimitColimit F a = x [PROOFSTEP] let O := (Finset.univ.biUnion fun j => Finset.univ.biUnion fun j' => Finset.univ.image (@kf j j')) βˆͺ { k' } [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) O : Finset K := (Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.image kf Finset.univ) βˆͺ {k'} ⊒ βˆƒ a, colimitLimitToLimitColimit F a = x [PROOFSTEP] have kfO : βˆ€ {j j'} (f : j ⟢ j'), kf f ∈ O := fun {j} {j'} f => Finset.mem_union.mpr (Or.inl (by rw [Finset.mem_biUnion] refine' ⟨j, Finset.mem_univ j, _⟩ rw [Finset.mem_biUnion] refine' ⟨j', Finset.mem_univ j', _⟩ rw [Finset.mem_image] refine' ⟨f, Finset.mem_univ _, _⟩ rfl)) [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) O : Finset K := (Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.image kf Finset.univ) βˆͺ {k'} j j' : J f : j ⟢ j' ⊒ kf f ∈ Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.image kf Finset.univ [PROOFSTEP] rw [Finset.mem_biUnion] [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) O : Finset K := (Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.image kf Finset.univ) βˆͺ {k'} j j' : J f : j ⟢ j' ⊒ βˆƒ a, a ∈ Finset.univ ∧ kf f ∈ Finset.biUnion Finset.univ fun j' => Finset.image kf Finset.univ [PROOFSTEP] refine' ⟨j, Finset.mem_univ j, _⟩ [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) O : Finset K := (Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.image kf Finset.univ) βˆͺ {k'} j j' : J f : j ⟢ j' ⊒ kf f ∈ Finset.biUnion Finset.univ fun j' => Finset.image kf Finset.univ [PROOFSTEP] rw [Finset.mem_biUnion] [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) O : Finset K := (Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.image kf Finset.univ) βˆͺ {k'} j j' : J f : j ⟢ j' ⊒ βˆƒ a, a ∈ Finset.univ ∧ kf f ∈ Finset.image kf Finset.univ [PROOFSTEP] refine' ⟨j', Finset.mem_univ j', _⟩ [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) O : Finset K := (Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.image kf Finset.univ) βˆͺ {k'} j j' : J f : j ⟢ j' ⊒ kf f ∈ Finset.image kf Finset.univ [PROOFSTEP] rw [Finset.mem_image] [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) O : Finset K := (Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.image kf Finset.univ) βˆͺ {k'} j j' : J f : j ⟢ j' ⊒ βˆƒ a, a ∈ Finset.univ ∧ kf a = kf f [PROOFSTEP] refine' ⟨f, Finset.mem_univ _, _⟩ [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) O : Finset K := (Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.image kf Finset.univ) βˆͺ {k'} j j' : J f : j ⟢ j' ⊒ kf f = kf f [PROOFSTEP] rfl [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) O : Finset K := (Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.image kf Finset.univ) βˆͺ {k'} kfO : βˆ€ {j j' : J} (f : j ⟢ j'), kf f ∈ O ⊒ βˆƒ a, colimitLimitToLimitColimit F a = x [PROOFSTEP] have k'O : k' ∈ O := Finset.mem_union.mpr (Or.inr (Finset.mem_singleton.mpr rfl)) [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) O : Finset K := (Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.image kf Finset.univ) βˆͺ {k'} kfO : βˆ€ {j j' : J} (f : j ⟢ j'), kf f ∈ O k'O : k' ∈ O ⊒ βˆƒ a, colimitLimitToLimitColimit F a = x [PROOFSTEP] let H : Finset (Ξ£' (X Y : K) (_ : X ∈ O) (_ : Y ∈ O), X ⟢ Y) := Finset.univ.biUnion fun j : J => Finset.univ.biUnion fun j' : J => Finset.univ.biUnion fun f : j ⟢ j' => {⟨k', kf f, k'O, kfO f, gf f⟩, ⟨k', kf f, k'O, kfO f, hf f⟩} [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) O : Finset K := (Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.image kf Finset.univ) βˆͺ {k'} kfO : βˆ€ {j j' : J} (f : j ⟢ j'), kf f ∈ O k'O : k' ∈ O H : Finset ((X : K) Γ—' (Y : K) Γ—' (_ : X ∈ O) Γ—' (_ : Y ∈ O) Γ—' (X ⟢ Y)) := Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.biUnion Finset.univ fun f => {{ fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := gf f } } } }, { fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := hf f } } } }} ⊒ βˆƒ a, colimitLimitToLimitColimit F a = x [PROOFSTEP] obtain ⟨k'', i', s'⟩ := IsFiltered.sup_exists O H [GOAL] case intro.intro J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) O : Finset K := (Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.image kf Finset.univ) βˆͺ {k'} kfO : βˆ€ {j j' : J} (f : j ⟢ j'), kf f ∈ O k'O : k' ∈ O H : Finset ((X : K) Γ—' (Y : K) Γ—' (_ : X ∈ O) Γ—' (_ : Y ∈ O) Γ—' (X ⟢ Y)) := Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.biUnion Finset.univ fun f => {{ fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := gf f } } } }, { fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := hf f } } } }} k'' : K i' : {X : K} β†’ X ∈ O β†’ (X ⟢ k'') s' : βˆ€ {X Y : K} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟢ Y}, { fst := X, snd := { fst := Y, snd := { fst := mX, snd := { fst := mY, snd := f } } } } ∈ H β†’ f ≫ i' mY = i' mX ⊒ βˆƒ a, colimitLimitToLimitColimit F a = x [PROOFSTEP] let i : βˆ€ {j j'} (f : j ⟢ j'), kf f ⟢ k'' := fun {j} {j'} f => i' (kfO f) [GOAL] case intro.intro J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) O : Finset K := (Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.image kf Finset.univ) βˆͺ {k'} kfO : βˆ€ {j j' : J} (f : j ⟢ j'), kf f ∈ O k'O : k' ∈ O H : Finset ((X : K) Γ—' (Y : K) Γ—' (_ : X ∈ O) Γ—' (_ : Y ∈ O) Γ—' (X ⟢ Y)) := Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.biUnion Finset.univ fun f => {{ fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := gf f } } } }, { fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := hf f } } } }} k'' : K i' : {X : K} β†’ X ∈ O β†’ (X ⟢ k'') s' : βˆ€ {X Y : K} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟢ Y}, { fst := X, snd := { fst := Y, snd := { fst := mX, snd := { fst := mY, snd := f } } } } ∈ H β†’ f ≫ i' mY = i' mX i : {j j' : J} β†’ (f : j ⟢ j') β†’ kf f ⟢ k'' := fun {j j'} f => i' (_ : kf f ∈ O) ⊒ βˆƒ a, colimitLimitToLimitColimit F a = x [PROOFSTEP] have s : βˆ€ {j₁ jβ‚‚ j₃ jβ‚„} (f : j₁ ⟢ jβ‚‚) (f' : j₃ ⟢ jβ‚„), gf f ≫ i f = hf f' ≫ i f' := by intros j₁ jβ‚‚ j₃ jβ‚„ f f' rw [s', s'] -- porting note: the three goals here in Lean 3 were in a different order exact k'O swap Β· rw [Finset.mem_biUnion] refine' ⟨j₁, Finset.mem_univ _, _⟩ rw [Finset.mem_biUnion] refine' ⟨jβ‚‚, Finset.mem_univ _, _⟩ rw [Finset.mem_biUnion] refine' ⟨f, Finset.mem_univ _, _⟩ simp only [true_or_iff, eq_self_iff_true, and_self_iff, Finset.mem_insert, heq_iff_eq] Β· rw [Finset.mem_biUnion] refine' ⟨j₃, Finset.mem_univ _, _⟩ rw [Finset.mem_biUnion] refine' ⟨jβ‚„, Finset.mem_univ _, _⟩ rw [Finset.mem_biUnion] refine' ⟨f', Finset.mem_univ _, _⟩ simp only [eq_self_iff_true, or_true_iff, and_self_iff, Finset.mem_insert, Finset.mem_singleton, heq_iff_eq] [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) O : Finset K := (Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.image kf Finset.univ) βˆͺ {k'} kfO : βˆ€ {j j' : J} (f : j ⟢ j'), kf f ∈ O k'O : k' ∈ O H : Finset ((X : K) Γ—' (Y : K) Γ—' (_ : X ∈ O) Γ—' (_ : Y ∈ O) Γ—' (X ⟢ Y)) := Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.biUnion Finset.univ fun f => {{ fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := gf f } } } }, { fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := hf f } } } }} k'' : K i' : {X : K} β†’ X ∈ O β†’ (X ⟢ k'') s' : βˆ€ {X Y : K} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟢ Y}, { fst := X, snd := { fst := Y, snd := { fst := mX, snd := { fst := mY, snd := f } } } } ∈ H β†’ f ≫ i' mY = i' mX i : {j j' : J} β†’ (f : j ⟢ j') β†’ kf f ⟢ k'' := fun {j j'} f => i' (_ : kf f ∈ O) ⊒ βˆ€ {j₁ jβ‚‚ j₃ jβ‚„ : J} (f : j₁ ⟢ jβ‚‚) (f' : j₃ ⟢ jβ‚„), gf f ≫ i f = hf f' ≫ i f' [PROOFSTEP] intros j₁ jβ‚‚ j₃ jβ‚„ f f' [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) O : Finset K := (Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.image kf Finset.univ) βˆͺ {k'} kfO : βˆ€ {j j' : J} (f : j ⟢ j'), kf f ∈ O k'O : k' ∈ O H : Finset ((X : K) Γ—' (Y : K) Γ—' (_ : X ∈ O) Γ—' (_ : Y ∈ O) Γ—' (X ⟢ Y)) := Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.biUnion Finset.univ fun f => {{ fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := gf f } } } }, { fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := hf f } } } }} k'' : K i' : {X : K} β†’ X ∈ O β†’ (X ⟢ k'') s' : βˆ€ {X Y : K} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟢ Y}, { fst := X, snd := { fst := Y, snd := { fst := mX, snd := { fst := mY, snd := f } } } } ∈ H β†’ f ≫ i' mY = i' mX i : {j j' : J} β†’ (f : j ⟢ j') β†’ kf f ⟢ k'' := fun {j j'} f => i' (_ : kf f ∈ O) j₁ jβ‚‚ j₃ jβ‚„ : J f : j₁ ⟢ jβ‚‚ f' : j₃ ⟢ jβ‚„ ⊒ gf f ≫ i f = hf f' ≫ i f' [PROOFSTEP] rw [s', s'] -- porting note: the three goals here in Lean 3 were in a different order [GOAL] case mX J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) O : Finset K := (Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.image kf Finset.univ) βˆͺ {k'} kfO : βˆ€ {j j' : J} (f : j ⟢ j'), kf f ∈ O k'O : k' ∈ O H : Finset ((X : K) Γ—' (Y : K) Γ—' (_ : X ∈ O) Γ—' (_ : Y ∈ O) Γ—' (X ⟢ Y)) := Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.biUnion Finset.univ fun f => {{ fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := gf f } } } }, { fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := hf f } } } }} k'' : K i' : {X : K} β†’ X ∈ O β†’ (X ⟢ k'') s' : βˆ€ {X Y : K} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟢ Y}, { fst := X, snd := { fst := Y, snd := { fst := mX, snd := { fst := mY, snd := f } } } } ∈ H β†’ f ≫ i' mY = i' mX i : {j j' : J} β†’ (f : j ⟢ j') β†’ kf f ⟢ k'' := fun {j j'} f => i' (_ : kf f ∈ O) j₁ jβ‚‚ j₃ jβ‚„ : J f : j₁ ⟢ jβ‚‚ f' : j₃ ⟢ jβ‚„ ⊒ k' ∈ O case a J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) O : Finset K := (Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.image kf Finset.univ) βˆͺ {k'} kfO : βˆ€ {j j' : J} (f : j ⟢ j'), kf f ∈ O k'O : k' ∈ O H : Finset ((X : K) Γ—' (Y : K) Γ—' (_ : X ∈ O) Γ—' (_ : Y ∈ O) Γ—' (X ⟢ Y)) := Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.biUnion Finset.univ fun f => {{ fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := gf f } } } }, { fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := hf f } } } }} k'' : K i' : {X : K} β†’ X ∈ O β†’ (X ⟢ k'') s' : βˆ€ {X Y : K} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟢ Y}, { fst := X, snd := { fst := Y, snd := { fst := mX, snd := { fst := mY, snd := f } } } } ∈ H β†’ f ≫ i' mY = i' mX i : {j j' : J} β†’ (f : j ⟢ j') β†’ kf f ⟢ k'' := fun {j j'} f => i' (_ : kf f ∈ O) j₁ jβ‚‚ j₃ jβ‚„ : J f : j₁ ⟢ jβ‚‚ f' : j₃ ⟢ jβ‚„ ⊒ { fst := k', snd := { fst := kf f', snd := { fst := ?mX, snd := { fst := (_ : kf f' ∈ O), snd := hf f' } } } } ∈ H case a J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) O : Finset K := (Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.image kf Finset.univ) βˆͺ {k'} kfO : βˆ€ {j j' : J} (f : j ⟢ j'), kf f ∈ O k'O : k' ∈ O H : Finset ((X : K) Γ—' (Y : K) Γ—' (_ : X ∈ O) Γ—' (_ : Y ∈ O) Γ—' (X ⟢ Y)) := Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.biUnion Finset.univ fun f => {{ fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := gf f } } } }, { fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := hf f } } } }} k'' : K i' : {X : K} β†’ X ∈ O β†’ (X ⟢ k'') s' : βˆ€ {X Y : K} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟢ Y}, { fst := X, snd := { fst := Y, snd := { fst := mX, snd := { fst := mY, snd := f } } } } ∈ H β†’ f ≫ i' mY = i' mX i : {j j' : J} β†’ (f : j ⟢ j') β†’ kf f ⟢ k'' := fun {j j'} f => i' (_ : kf f ∈ O) j₁ jβ‚‚ j₃ jβ‚„ : J f : j₁ ⟢ jβ‚‚ f' : j₃ ⟢ jβ‚„ ⊒ { fst := k', snd := { fst := kf f, snd := { fst := ?mX, snd := { fst := (_ : kf f ∈ O), snd := gf f } } } } ∈ H [PROOFSTEP] exact k'O [GOAL] case a J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) O : Finset K := (Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.image kf Finset.univ) βˆͺ {k'} kfO : βˆ€ {j j' : J} (f : j ⟢ j'), kf f ∈ O k'O : k' ∈ O H : Finset ((X : K) Γ—' (Y : K) Γ—' (_ : X ∈ O) Γ—' (_ : Y ∈ O) Γ—' (X ⟢ Y)) := Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.biUnion Finset.univ fun f => {{ fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := gf f } } } }, { fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := hf f } } } }} k'' : K i' : {X : K} β†’ X ∈ O β†’ (X ⟢ k'') s' : βˆ€ {X Y : K} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟢ Y}, { fst := X, snd := { fst := Y, snd := { fst := mX, snd := { fst := mY, snd := f } } } } ∈ H β†’ f ≫ i' mY = i' mX i : {j j' : J} β†’ (f : j ⟢ j') β†’ kf f ⟢ k'' := fun {j j'} f => i' (_ : kf f ∈ O) j₁ jβ‚‚ j₃ jβ‚„ : J f : j₁ ⟢ jβ‚‚ f' : j₃ ⟢ jβ‚„ ⊒ { fst := k', snd := { fst := kf f', snd := { fst := k'O, snd := { fst := (_ : kf f' ∈ O), snd := hf f' } } } } ∈ H case a J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) O : Finset K := (Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.image kf Finset.univ) βˆͺ {k'} kfO : βˆ€ {j j' : J} (f : j ⟢ j'), kf f ∈ O k'O : k' ∈ O H : Finset ((X : K) Γ—' (Y : K) Γ—' (_ : X ∈ O) Γ—' (_ : Y ∈ O) Γ—' (X ⟢ Y)) := Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.biUnion Finset.univ fun f => {{ fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := gf f } } } }, { fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := hf f } } } }} k'' : K i' : {X : K} β†’ X ∈ O β†’ (X ⟢ k'') s' : βˆ€ {X Y : K} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟢ Y}, { fst := X, snd := { fst := Y, snd := { fst := mX, snd := { fst := mY, snd := f } } } } ∈ H β†’ f ≫ i' mY = i' mX i : {j j' : J} β†’ (f : j ⟢ j') β†’ kf f ⟢ k'' := fun {j j'} f => i' (_ : kf f ∈ O) j₁ jβ‚‚ j₃ jβ‚„ : J f : j₁ ⟢ jβ‚‚ f' : j₃ ⟢ jβ‚„ ⊒ { fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := gf f } } } } ∈ H [PROOFSTEP] swap [GOAL] case a J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) O : Finset K := (Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.image kf Finset.univ) βˆͺ {k'} kfO : βˆ€ {j j' : J} (f : j ⟢ j'), kf f ∈ O k'O : k' ∈ O H : Finset ((X : K) Γ—' (Y : K) Γ—' (_ : X ∈ O) Γ—' (_ : Y ∈ O) Γ—' (X ⟢ Y)) := Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.biUnion Finset.univ fun f => {{ fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := gf f } } } }, { fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := hf f } } } }} k'' : K i' : {X : K} β†’ X ∈ O β†’ (X ⟢ k'') s' : βˆ€ {X Y : K} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟢ Y}, { fst := X, snd := { fst := Y, snd := { fst := mX, snd := { fst := mY, snd := f } } } } ∈ H β†’ f ≫ i' mY = i' mX i : {j j' : J} β†’ (f : j ⟢ j') β†’ kf f ⟢ k'' := fun {j j'} f => i' (_ : kf f ∈ O) j₁ jβ‚‚ j₃ jβ‚„ : J f : j₁ ⟢ jβ‚‚ f' : j₃ ⟢ jβ‚„ ⊒ { fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := gf f } } } } ∈ H [PROOFSTEP] rw [Finset.mem_biUnion] [GOAL] case a J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) O : Finset K := (Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.image kf Finset.univ) βˆͺ {k'} kfO : βˆ€ {j j' : J} (f : j ⟢ j'), kf f ∈ O k'O : k' ∈ O H : Finset ((X : K) Γ—' (Y : K) Γ—' (_ : X ∈ O) Γ—' (_ : Y ∈ O) Γ—' (X ⟢ Y)) := Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.biUnion Finset.univ fun f => {{ fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := gf f } } } }, { fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := hf f } } } }} k'' : K i' : {X : K} β†’ X ∈ O β†’ (X ⟢ k'') s' : βˆ€ {X Y : K} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟢ Y}, { fst := X, snd := { fst := Y, snd := { fst := mX, snd := { fst := mY, snd := f } } } } ∈ H β†’ f ≫ i' mY = i' mX i : {j j' : J} β†’ (f : j ⟢ j') β†’ kf f ⟢ k'' := fun {j j'} f => i' (_ : kf f ∈ O) j₁ jβ‚‚ j₃ jβ‚„ : J f : j₁ ⟢ jβ‚‚ f' : j₃ ⟢ jβ‚„ ⊒ βˆƒ a, a ∈ Finset.univ ∧ { fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := gf f } } } } ∈ Finset.biUnion Finset.univ fun j' => Finset.biUnion Finset.univ fun f => {{ fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := gf f } } } }, { fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := hf f } } } }} [PROOFSTEP] refine' ⟨j₁, Finset.mem_univ _, _⟩ [GOAL] case a J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) O : Finset K := (Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.image kf Finset.univ) βˆͺ {k'} kfO : βˆ€ {j j' : J} (f : j ⟢ j'), kf f ∈ O k'O : k' ∈ O H : Finset ((X : K) Γ—' (Y : K) Γ—' (_ : X ∈ O) Γ—' (_ : Y ∈ O) Γ—' (X ⟢ Y)) := Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.biUnion Finset.univ fun f => {{ fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := gf f } } } }, { fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := hf f } } } }} k'' : K i' : {X : K} β†’ X ∈ O β†’ (X ⟢ k'') s' : βˆ€ {X Y : K} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟢ Y}, { fst := X, snd := { fst := Y, snd := { fst := mX, snd := { fst := mY, snd := f } } } } ∈ H β†’ f ≫ i' mY = i' mX i : {j j' : J} β†’ (f : j ⟢ j') β†’ kf f ⟢ k'' := fun {j j'} f => i' (_ : kf f ∈ O) j₁ jβ‚‚ j₃ jβ‚„ : J f : j₁ ⟢ jβ‚‚ f' : j₃ ⟢ jβ‚„ ⊒ { fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := gf f } } } } ∈ Finset.biUnion Finset.univ fun j' => Finset.biUnion Finset.univ fun f => {{ fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := gf f } } } }, { fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := hf f } } } }} [PROOFSTEP] rw [Finset.mem_biUnion] [GOAL] case a J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) O : Finset K := (Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.image kf Finset.univ) βˆͺ {k'} kfO : βˆ€ {j j' : J} (f : j ⟢ j'), kf f ∈ O k'O : k' ∈ O H : Finset ((X : K) Γ—' (Y : K) Γ—' (_ : X ∈ O) Γ—' (_ : Y ∈ O) Γ—' (X ⟢ Y)) := Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.biUnion Finset.univ fun f => {{ fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := gf f } } } }, { fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := hf f } } } }} k'' : K i' : {X : K} β†’ X ∈ O β†’ (X ⟢ k'') s' : βˆ€ {X Y : K} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟢ Y}, { fst := X, snd := { fst := Y, snd := { fst := mX, snd := { fst := mY, snd := f } } } } ∈ H β†’ f ≫ i' mY = i' mX i : {j j' : J} β†’ (f : j ⟢ j') β†’ kf f ⟢ k'' := fun {j j'} f => i' (_ : kf f ∈ O) j₁ jβ‚‚ j₃ jβ‚„ : J f : j₁ ⟢ jβ‚‚ f' : j₃ ⟢ jβ‚„ ⊒ βˆƒ a, a ∈ Finset.univ ∧ { fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := gf f } } } } ∈ Finset.biUnion Finset.univ fun f => {{ fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := gf f } } } }, { fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := hf f } } } }} [PROOFSTEP] refine' ⟨jβ‚‚, Finset.mem_univ _, _⟩ [GOAL] case a J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) O : Finset K := (Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.image kf Finset.univ) βˆͺ {k'} kfO : βˆ€ {j j' : J} (f : j ⟢ j'), kf f ∈ O k'O : k' ∈ O H : Finset ((X : K) Γ—' (Y : K) Γ—' (_ : X ∈ O) Γ—' (_ : Y ∈ O) Γ—' (X ⟢ Y)) := Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.biUnion Finset.univ fun f => {{ fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := gf f } } } }, { fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := hf f } } } }} k'' : K i' : {X : K} β†’ X ∈ O β†’ (X ⟢ k'') s' : βˆ€ {X Y : K} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟢ Y}, { fst := X, snd := { fst := Y, snd := { fst := mX, snd := { fst := mY, snd := f } } } } ∈ H β†’ f ≫ i' mY = i' mX i : {j j' : J} β†’ (f : j ⟢ j') β†’ kf f ⟢ k'' := fun {j j'} f => i' (_ : kf f ∈ O) j₁ jβ‚‚ j₃ jβ‚„ : J f : j₁ ⟢ jβ‚‚ f' : j₃ ⟢ jβ‚„ ⊒ { fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := gf f } } } } ∈ Finset.biUnion Finset.univ fun f => {{ fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := gf f } } } }, { fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := hf f } } } }} [PROOFSTEP] rw [Finset.mem_biUnion] [GOAL] case a J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) O : Finset K := (Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.image kf Finset.univ) βˆͺ {k'} kfO : βˆ€ {j j' : J} (f : j ⟢ j'), kf f ∈ O k'O : k' ∈ O H : Finset ((X : K) Γ—' (Y : K) Γ—' (_ : X ∈ O) Γ—' (_ : Y ∈ O) Γ—' (X ⟢ Y)) := Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.biUnion Finset.univ fun f => {{ fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := gf f } } } }, { fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := hf f } } } }} k'' : K i' : {X : K} β†’ X ∈ O β†’ (X ⟢ k'') s' : βˆ€ {X Y : K} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟢ Y}, { fst := X, snd := { fst := Y, snd := { fst := mX, snd := { fst := mY, snd := f } } } } ∈ H β†’ f ≫ i' mY = i' mX i : {j j' : J} β†’ (f : j ⟢ j') β†’ kf f ⟢ k'' := fun {j j'} f => i' (_ : kf f ∈ O) j₁ jβ‚‚ j₃ jβ‚„ : J f : j₁ ⟢ jβ‚‚ f' : j₃ ⟢ jβ‚„ ⊒ βˆƒ a, a ∈ Finset.univ ∧ { fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := gf f } } } } ∈ {{ fst := k', snd := { fst := kf a, snd := { fst := k'O, snd := { fst := (_ : kf a ∈ O), snd := gf a } } } }, { fst := k', snd := { fst := kf a, snd := { fst := k'O, snd := { fst := (_ : kf a ∈ O), snd := hf a } } } }} [PROOFSTEP] refine' ⟨f, Finset.mem_univ _, _⟩ [GOAL] case a J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) O : Finset K := (Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.image kf Finset.univ) βˆͺ {k'} kfO : βˆ€ {j j' : J} (f : j ⟢ j'), kf f ∈ O k'O : k' ∈ O H : Finset ((X : K) Γ—' (Y : K) Γ—' (_ : X ∈ O) Γ—' (_ : Y ∈ O) Γ—' (X ⟢ Y)) := Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.biUnion Finset.univ fun f => {{ fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := gf f } } } }, { fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := hf f } } } }} k'' : K i' : {X : K} β†’ X ∈ O β†’ (X ⟢ k'') s' : βˆ€ {X Y : K} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟢ Y}, { fst := X, snd := { fst := Y, snd := { fst := mX, snd := { fst := mY, snd := f } } } } ∈ H β†’ f ≫ i' mY = i' mX i : {j j' : J} β†’ (f : j ⟢ j') β†’ kf f ⟢ k'' := fun {j j'} f => i' (_ : kf f ∈ O) j₁ jβ‚‚ j₃ jβ‚„ : J f : j₁ ⟢ jβ‚‚ f' : j₃ ⟢ jβ‚„ ⊒ { fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := gf f } } } } ∈ {{ fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := gf f } } } }, { fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := hf f } } } }} [PROOFSTEP] simp only [true_or_iff, eq_self_iff_true, and_self_iff, Finset.mem_insert, heq_iff_eq] [GOAL] case a J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) O : Finset K := (Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.image kf Finset.univ) βˆͺ {k'} kfO : βˆ€ {j j' : J} (f : j ⟢ j'), kf f ∈ O k'O : k' ∈ O H : Finset ((X : K) Γ—' (Y : K) Γ—' (_ : X ∈ O) Γ—' (_ : Y ∈ O) Γ—' (X ⟢ Y)) := Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.biUnion Finset.univ fun f => {{ fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := gf f } } } }, { fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := hf f } } } }} k'' : K i' : {X : K} β†’ X ∈ O β†’ (X ⟢ k'') s' : βˆ€ {X Y : K} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟢ Y}, { fst := X, snd := { fst := Y, snd := { fst := mX, snd := { fst := mY, snd := f } } } } ∈ H β†’ f ≫ i' mY = i' mX i : {j j' : J} β†’ (f : j ⟢ j') β†’ kf f ⟢ k'' := fun {j j'} f => i' (_ : kf f ∈ O) j₁ jβ‚‚ j₃ jβ‚„ : J f : j₁ ⟢ jβ‚‚ f' : j₃ ⟢ jβ‚„ ⊒ { fst := k', snd := { fst := kf f', snd := { fst := k'O, snd := { fst := (_ : kf f' ∈ O), snd := hf f' } } } } ∈ H [PROOFSTEP] rw [Finset.mem_biUnion] [GOAL] case a J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) O : Finset K := (Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.image kf Finset.univ) βˆͺ {k'} kfO : βˆ€ {j j' : J} (f : j ⟢ j'), kf f ∈ O k'O : k' ∈ O H : Finset ((X : K) Γ—' (Y : K) Γ—' (_ : X ∈ O) Γ—' (_ : Y ∈ O) Γ—' (X ⟢ Y)) := Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.biUnion Finset.univ fun f => {{ fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := gf f } } } }, { fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := hf f } } } }} k'' : K i' : {X : K} β†’ X ∈ O β†’ (X ⟢ k'') s' : βˆ€ {X Y : K} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟢ Y}, { fst := X, snd := { fst := Y, snd := { fst := mX, snd := { fst := mY, snd := f } } } } ∈ H β†’ f ≫ i' mY = i' mX i : {j j' : J} β†’ (f : j ⟢ j') β†’ kf f ⟢ k'' := fun {j j'} f => i' (_ : kf f ∈ O) j₁ jβ‚‚ j₃ jβ‚„ : J f : j₁ ⟢ jβ‚‚ f' : j₃ ⟢ jβ‚„ ⊒ βˆƒ a, a ∈ Finset.univ ∧ { fst := k', snd := { fst := kf f', snd := { fst := k'O, snd := { fst := (_ : kf f' ∈ O), snd := hf f' } } } } ∈ Finset.biUnion Finset.univ fun j' => Finset.biUnion Finset.univ fun f => {{ fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := gf f } } } }, { fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := hf f } } } }} [PROOFSTEP] refine' ⟨j₃, Finset.mem_univ _, _⟩ [GOAL] case a J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) O : Finset K := (Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.image kf Finset.univ) βˆͺ {k'} kfO : βˆ€ {j j' : J} (f : j ⟢ j'), kf f ∈ O k'O : k' ∈ O H : Finset ((X : K) Γ—' (Y : K) Γ—' (_ : X ∈ O) Γ—' (_ : Y ∈ O) Γ—' (X ⟢ Y)) := Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.biUnion Finset.univ fun f => {{ fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := gf f } } } }, { fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := hf f } } } }} k'' : K i' : {X : K} β†’ X ∈ O β†’ (X ⟢ k'') s' : βˆ€ {X Y : K} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟢ Y}, { fst := X, snd := { fst := Y, snd := { fst := mX, snd := { fst := mY, snd := f } } } } ∈ H β†’ f ≫ i' mY = i' mX i : {j j' : J} β†’ (f : j ⟢ j') β†’ kf f ⟢ k'' := fun {j j'} f => i' (_ : kf f ∈ O) j₁ jβ‚‚ j₃ jβ‚„ : J f : j₁ ⟢ jβ‚‚ f' : j₃ ⟢ jβ‚„ ⊒ { fst := k', snd := { fst := kf f', snd := { fst := k'O, snd := { fst := (_ : kf f' ∈ O), snd := hf f' } } } } ∈ Finset.biUnion Finset.univ fun j' => Finset.biUnion Finset.univ fun f => {{ fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := gf f } } } }, { fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := hf f } } } }} [PROOFSTEP] rw [Finset.mem_biUnion] [GOAL] case a J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) O : Finset K := (Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.image kf Finset.univ) βˆͺ {k'} kfO : βˆ€ {j j' : J} (f : j ⟢ j'), kf f ∈ O k'O : k' ∈ O H : Finset ((X : K) Γ—' (Y : K) Γ—' (_ : X ∈ O) Γ—' (_ : Y ∈ O) Γ—' (X ⟢ Y)) := Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.biUnion Finset.univ fun f => {{ fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := gf f } } } }, { fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := hf f } } } }} k'' : K i' : {X : K} β†’ X ∈ O β†’ (X ⟢ k'') s' : βˆ€ {X Y : K} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟢ Y}, { fst := X, snd := { fst := Y, snd := { fst := mX, snd := { fst := mY, snd := f } } } } ∈ H β†’ f ≫ i' mY = i' mX i : {j j' : J} β†’ (f : j ⟢ j') β†’ kf f ⟢ k'' := fun {j j'} f => i' (_ : kf f ∈ O) j₁ jβ‚‚ j₃ jβ‚„ : J f : j₁ ⟢ jβ‚‚ f' : j₃ ⟢ jβ‚„ ⊒ βˆƒ a, a ∈ Finset.univ ∧ { fst := k', snd := { fst := kf f', snd := { fst := k'O, snd := { fst := (_ : kf f' ∈ O), snd := hf f' } } } } ∈ Finset.biUnion Finset.univ fun f => {{ fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := gf f } } } }, { fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := hf f } } } }} [PROOFSTEP] refine' ⟨jβ‚„, Finset.mem_univ _, _⟩ [GOAL] case a J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) O : Finset K := (Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.image kf Finset.univ) βˆͺ {k'} kfO : βˆ€ {j j' : J} (f : j ⟢ j'), kf f ∈ O k'O : k' ∈ O H : Finset ((X : K) Γ—' (Y : K) Γ—' (_ : X ∈ O) Γ—' (_ : Y ∈ O) Γ—' (X ⟢ Y)) := Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.biUnion Finset.univ fun f => {{ fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := gf f } } } }, { fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := hf f } } } }} k'' : K i' : {X : K} β†’ X ∈ O β†’ (X ⟢ k'') s' : βˆ€ {X Y : K} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟢ Y}, { fst := X, snd := { fst := Y, snd := { fst := mX, snd := { fst := mY, snd := f } } } } ∈ H β†’ f ≫ i' mY = i' mX i : {j j' : J} β†’ (f : j ⟢ j') β†’ kf f ⟢ k'' := fun {j j'} f => i' (_ : kf f ∈ O) j₁ jβ‚‚ j₃ jβ‚„ : J f : j₁ ⟢ jβ‚‚ f' : j₃ ⟢ jβ‚„ ⊒ { fst := k', snd := { fst := kf f', snd := { fst := k'O, snd := { fst := (_ : kf f' ∈ O), snd := hf f' } } } } ∈ Finset.biUnion Finset.univ fun f => {{ fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := gf f } } } }, { fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := hf f } } } }} [PROOFSTEP] rw [Finset.mem_biUnion] [GOAL] case a J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) O : Finset K := (Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.image kf Finset.univ) βˆͺ {k'} kfO : βˆ€ {j j' : J} (f : j ⟢ j'), kf f ∈ O k'O : k' ∈ O H : Finset ((X : K) Γ—' (Y : K) Γ—' (_ : X ∈ O) Γ—' (_ : Y ∈ O) Γ—' (X ⟢ Y)) := Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.biUnion Finset.univ fun f => {{ fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := gf f } } } }, { fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := hf f } } } }} k'' : K i' : {X : K} β†’ X ∈ O β†’ (X ⟢ k'') s' : βˆ€ {X Y : K} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟢ Y}, { fst := X, snd := { fst := Y, snd := { fst := mX, snd := { fst := mY, snd := f } } } } ∈ H β†’ f ≫ i' mY = i' mX i : {j j' : J} β†’ (f : j ⟢ j') β†’ kf f ⟢ k'' := fun {j j'} f => i' (_ : kf f ∈ O) j₁ jβ‚‚ j₃ jβ‚„ : J f : j₁ ⟢ jβ‚‚ f' : j₃ ⟢ jβ‚„ ⊒ βˆƒ a, a ∈ Finset.univ ∧ { fst := k', snd := { fst := kf f', snd := { fst := k'O, snd := { fst := (_ : kf f' ∈ O), snd := hf f' } } } } ∈ {{ fst := k', snd := { fst := kf a, snd := { fst := k'O, snd := { fst := (_ : kf a ∈ O), snd := gf a } } } }, { fst := k', snd := { fst := kf a, snd := { fst := k'O, snd := { fst := (_ : kf a ∈ O), snd := hf a } } } }} [PROOFSTEP] refine' ⟨f', Finset.mem_univ _, _⟩ [GOAL] case a J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) O : Finset K := (Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.image kf Finset.univ) βˆͺ {k'} kfO : βˆ€ {j j' : J} (f : j ⟢ j'), kf f ∈ O k'O : k' ∈ O H : Finset ((X : K) Γ—' (Y : K) Γ—' (_ : X ∈ O) Γ—' (_ : Y ∈ O) Γ—' (X ⟢ Y)) := Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.biUnion Finset.univ fun f => {{ fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := gf f } } } }, { fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := hf f } } } }} k'' : K i' : {X : K} β†’ X ∈ O β†’ (X ⟢ k'') s' : βˆ€ {X Y : K} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟢ Y}, { fst := X, snd := { fst := Y, snd := { fst := mX, snd := { fst := mY, snd := f } } } } ∈ H β†’ f ≫ i' mY = i' mX i : {j j' : J} β†’ (f : j ⟢ j') β†’ kf f ⟢ k'' := fun {j j'} f => i' (_ : kf f ∈ O) j₁ jβ‚‚ j₃ jβ‚„ : J f : j₁ ⟢ jβ‚‚ f' : j₃ ⟢ jβ‚„ ⊒ { fst := k', snd := { fst := kf f', snd := { fst := k'O, snd := { fst := (_ : kf f' ∈ O), snd := hf f' } } } } ∈ {{ fst := k', snd := { fst := kf f', snd := { fst := k'O, snd := { fst := (_ : kf f' ∈ O), snd := gf f' } } } }, { fst := k', snd := { fst := kf f', snd := { fst := k'O, snd := { fst := (_ : kf f' ∈ O), snd := hf f' } } } }} [PROOFSTEP] simp only [eq_self_iff_true, or_true_iff, and_self_iff, Finset.mem_insert, Finset.mem_singleton, heq_iff_eq] [GOAL] case intro.intro J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) O : Finset K := (Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.image kf Finset.univ) βˆͺ {k'} kfO : βˆ€ {j j' : J} (f : j ⟢ j'), kf f ∈ O k'O : k' ∈ O H : Finset ((X : K) Γ—' (Y : K) Γ—' (_ : X ∈ O) Γ—' (_ : Y ∈ O) Γ—' (X ⟢ Y)) := Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.biUnion Finset.univ fun f => {{ fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := gf f } } } }, { fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := hf f } } } }} k'' : K i' : {X : K} β†’ X ∈ O β†’ (X ⟢ k'') s' : βˆ€ {X Y : K} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟢ Y}, { fst := X, snd := { fst := Y, snd := { fst := mX, snd := { fst := mY, snd := f } } } } ∈ H β†’ f ≫ i' mY = i' mX i : {j j' : J} β†’ (f : j ⟢ j') β†’ kf f ⟢ k'' := fun {j j'} f => i' (_ : kf f ∈ O) s : βˆ€ {j₁ jβ‚‚ j₃ jβ‚„ : J} (f : j₁ ⟢ jβ‚‚) (f' : j₃ ⟢ jβ‚„), gf f ≫ i f = hf f' ≫ i f' ⊒ βˆƒ a, colimitLimitToLimitColimit F a = x [PROOFSTEP] clear_value i [GOAL] case intro.intro J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) O : Finset K := (Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.image kf Finset.univ) βˆͺ {k'} kfO : βˆ€ {j j' : J} (f : j ⟢ j'), kf f ∈ O k'O : k' ∈ O H : Finset ((X : K) Γ—' (Y : K) Γ—' (_ : X ∈ O) Γ—' (_ : Y ∈ O) Γ—' (X ⟢ Y)) := Finset.biUnion Finset.univ fun j => Finset.biUnion Finset.univ fun j' => Finset.biUnion Finset.univ fun f => {{ fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := gf f } } } }, { fst := k', snd := { fst := kf f, snd := { fst := k'O, snd := { fst := (_ : kf f ∈ O), snd := hf f } } } }} k'' : K i' : {X : K} β†’ X ∈ O β†’ (X ⟢ k'') s' : βˆ€ {X Y : K} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟢ Y}, { fst := X, snd := { fst := Y, snd := { fst := mX, snd := { fst := mY, snd := f } } } } ∈ H β†’ f ≫ i' mY = i' mX i : {j j' : J} β†’ (f : j ⟢ j') β†’ kf f ⟢ k'' s : βˆ€ {j₁ jβ‚‚ j₃ jβ‚„ : J} (f : j₁ ⟢ jβ‚‚) (f' : j₃ ⟢ jβ‚„), gf f ≫ i f = hf f' ≫ i f' ⊒ βˆƒ a, colimitLimitToLimitColimit F a = x [PROOFSTEP] clear s' i' H kfO k'O O [GOAL] case intro.intro J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) k'' : K i : {j j' : J} β†’ (f : j ⟢ j') β†’ kf f ⟢ k'' s : βˆ€ {j₁ jβ‚‚ j₃ jβ‚„ : J} (f : j₁ ⟢ jβ‚‚) (f' : j₃ ⟢ jβ‚„), gf f ≫ i f = hf f' ≫ i f' ⊒ βˆƒ a, colimitLimitToLimitColimit F a = x [PROOFSTEP] fconstructor [GOAL] case intro.intro.w J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) k'' : K i : {j j' : J} β†’ (f : j ⟢ j') β†’ kf f ⟢ k'' s : βˆ€ {j₁ jβ‚‚ j₃ jβ‚„ : J} (f : j₁ ⟢ jβ‚‚) (f' : j₃ ⟢ jβ‚„), gf f ≫ i f = hf f' ≫ i f' ⊒ colimit (curry.obj (swap K J β‹™ F) β‹™ lim) [PROOFSTEP] apply colimit.ΞΉ (curry.obj (swap K J β‹™ F) β‹™ Limits.lim) k'' _ [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) k'' : K i : {j j' : J} β†’ (f : j ⟢ j') β†’ kf f ⟢ k'' s : βˆ€ {j₁ jβ‚‚ j₃ jβ‚„ : J} (f : j₁ ⟢ jβ‚‚) (f' : j₃ ⟢ jβ‚„), gf f ≫ i f = hf f' ≫ i f' ⊒ (curry.obj (swap K J β‹™ F) β‹™ lim).obj k'' [PROOFSTEP] dsimp -- This representative is meant to be an element of a limit, -- so we need to construct a family of elements in `F.obj (j, k'')` for varying `j`, -- then show that are coherent with respect to morphisms in the `j` direction. [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) k'' : K i : {j j' : J} β†’ (f : j ⟢ j') β†’ kf f ⟢ k'' s : βˆ€ {j₁ jβ‚‚ j₃ jβ‚„ : J} (f : j₁ ⟢ jβ‚‚) (f' : j₃ ⟢ jβ‚„), gf f ≫ i f = hf f' ≫ i f' ⊒ limit ((curry.obj (swap K J β‹™ F)).obj k'') [PROOFSTEP] apply Limit.mk.{v, v} [GOAL] case h J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) k'' : K i : {j j' : J} β†’ (f : j ⟢ j') β†’ kf f ⟢ k'' s : βˆ€ {j₁ jβ‚‚ j₃ jβ‚„ : J} (f : j₁ ⟢ jβ‚‚) (f' : j₃ ⟢ jβ‚„), gf f ≫ i f = hf f' ≫ i f' ⊒ βˆ€ (j j' : J) (f : j ⟢ j'), ((curry.obj (swap K J β‹™ F)).obj k'').map f (?x j) = ?x j' case x J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) k'' : K i : {j j' : J} β†’ (f : j ⟢ j') β†’ kf f ⟢ k'' s : βˆ€ {j₁ jβ‚‚ j₃ jβ‚„ : J} (f : j₁ ⟢ jβ‚‚) (f' : j₃ ⟢ jβ‚„), gf f ≫ i f = hf f' ≫ i f' ⊒ (j : J) β†’ ((curry.obj (swap K J β‹™ F)).obj k'').obj j [PROOFSTEP] swap [GOAL] case x J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) k'' : K i : {j j' : J} β†’ (f : j ⟢ j') β†’ kf f ⟢ k'' s : βˆ€ {j₁ jβ‚‚ j₃ jβ‚„ : J} (f : j₁ ⟢ jβ‚‚) (f' : j₃ ⟢ jβ‚„), gf f ≫ i f = hf f' ≫ i f' ⊒ (j : J) β†’ ((curry.obj (swap K J β‹™ F)).obj k'').obj j [PROOFSTEP] exact fun j => F.map (βŸ¨πŸ™ j, g j ≫ gf (πŸ™ j) ≫ i (πŸ™ j)⟩ : (j, k j) ⟢ (j, k'')) (y j) [GOAL] case h J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) k'' : K i : {j j' : J} β†’ (f : j ⟢ j') β†’ kf f ⟢ k'' s : βˆ€ {j₁ jβ‚‚ j₃ jβ‚„ : J} (f : j₁ ⟢ jβ‚‚) (f' : j₃ ⟢ jβ‚„), gf f ≫ i f = hf f' ≫ i f' ⊒ βˆ€ (j j' : J) (f : j ⟢ j'), ((curry.obj (swap K J β‹™ F)).obj k'').map f (F.map (πŸ™ j, g j ≫ gf (πŸ™ j) ≫ i (πŸ™ j)) (y j)) = F.map (πŸ™ j', g j' ≫ gf (πŸ™ j') ≫ i (πŸ™ j')) (y j') [PROOFSTEP] dsimp [GOAL] case h J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) k'' : K i : {j j' : J} β†’ (f : j ⟢ j') β†’ kf f ⟢ k'' s : βˆ€ {j₁ jβ‚‚ j₃ jβ‚„ : J} (f : j₁ ⟢ jβ‚‚) (f' : j₃ ⟢ jβ‚„), gf f ≫ i f = hf f' ≫ i f' ⊒ βˆ€ (j j' : J) (f : j ⟢ j'), F.map (f, πŸ™ k'') (F.map (πŸ™ j, g j ≫ gf (πŸ™ j) ≫ i (πŸ™ j)) (y j)) = F.map (πŸ™ j', g j' ≫ gf (πŸ™ j') ≫ i (πŸ™ j')) (y j') [PROOFSTEP] intro j j' f [GOAL] case h J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) k'' : K i : {j j' : J} β†’ (f : j ⟢ j') β†’ kf f ⟢ k'' s : βˆ€ {j₁ jβ‚‚ j₃ jβ‚„ : J} (f : j₁ ⟢ jβ‚‚) (f' : j₃ ⟢ jβ‚„), gf f ≫ i f = hf f' ≫ i f' j j' : J f : j ⟢ j' ⊒ F.map (f, πŸ™ k'') (F.map (πŸ™ j, g j ≫ gf (πŸ™ j) ≫ i (πŸ™ j)) (y j)) = F.map (πŸ™ j', g j' ≫ gf (πŸ™ j') ≫ i (πŸ™ j')) (y j') [PROOFSTEP] simp only [← FunctorToTypes.map_comp_apply, prod_comp, id_comp, comp_id] [GOAL] case h J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) k'' : K i : {j j' : J} β†’ (f : j ⟢ j') β†’ kf f ⟢ k'' s : βˆ€ {j₁ jβ‚‚ j₃ jβ‚„ : J} (f : j₁ ⟢ jβ‚‚) (f' : j₃ ⟢ jβ‚„), gf f ≫ i f = hf f' ≫ i f' j j' : J f : j ⟢ j' ⊒ F.map (f, g j ≫ gf (πŸ™ j) ≫ i (πŸ™ j)) (y j) = F.map (πŸ™ j', g j' ≫ gf (πŸ™ j') ≫ i (πŸ™ j')) (y j') [PROOFSTEP] calc F.map ((f, g j ≫ gf (πŸ™ j) ≫ i (πŸ™ j)) : (j, k j) ⟢ (j', k'')) (y j) = F.map ((f, g j ≫ hf f ≫ i f) : (j, k j) ⟢ (j', k'')) (y j) := by rw [s (πŸ™ j) f] _ = F.map ((πŸ™ j', i f) : (j', kf f) ⟢ (j', k'')) (F.map ((f, g j ≫ hf f) : (j, k j) ⟢ (j', kf f)) (y j)) := by rw [← FunctorToTypes.map_comp_apply, prod_comp, comp_id, assoc] _ = F.map ((πŸ™ j', i f) : (j', kf f) ⟢ (j', k'')) (F.map ((πŸ™ j', g j' ≫ gf f) : (j', k j') ⟢ (j', kf f)) (y j')) := by rw [← wf f] _ = F.map ((πŸ™ j', g j' ≫ gf f ≫ i f) : (j', k j') ⟢ (j', k'')) (y j') := by rw [← FunctorToTypes.map_comp_apply, prod_comp, id_comp, assoc] _ = F.map ((πŸ™ j', g j' ≫ gf (πŸ™ j') ≫ i (πŸ™ j')) : (j', k j') ⟢ (j', k'')) (y j') := by rw [s f (πŸ™ j'), ← s (πŸ™ j') (πŸ™ j')] -- Finally we check that this maps to `x`. [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) k'' : K i : {j j' : J} β†’ (f : j ⟢ j') β†’ kf f ⟢ k'' s : βˆ€ {j₁ jβ‚‚ j₃ jβ‚„ : J} (f : j₁ ⟢ jβ‚‚) (f' : j₃ ⟢ jβ‚„), gf f ≫ i f = hf f' ≫ i f' j j' : J f : j ⟢ j' ⊒ F.map (f, g j ≫ gf (πŸ™ j) ≫ i (πŸ™ j)) (y j) = F.map (f, g j ≫ hf f ≫ i f) (y j) [PROOFSTEP] rw [s (πŸ™ j) f] [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) k'' : K i : {j j' : J} β†’ (f : j ⟢ j') β†’ kf f ⟢ k'' s : βˆ€ {j₁ jβ‚‚ j₃ jβ‚„ : J} (f : j₁ ⟢ jβ‚‚) (f' : j₃ ⟢ jβ‚„), gf f ≫ i f = hf f' ≫ i f' j j' : J f : j ⟢ j' ⊒ F.map (f, g j ≫ hf f ≫ i f) (y j) = F.map (πŸ™ j', i f) (F.map (f, g j ≫ hf f) (y j)) [PROOFSTEP] rw [← FunctorToTypes.map_comp_apply, prod_comp, comp_id, assoc] [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) k'' : K i : {j j' : J} β†’ (f : j ⟢ j') β†’ kf f ⟢ k'' s : βˆ€ {j₁ jβ‚‚ j₃ jβ‚„ : J} (f : j₁ ⟢ jβ‚‚) (f' : j₃ ⟢ jβ‚„), gf f ≫ i f = hf f' ≫ i f' j j' : J f : j ⟢ j' ⊒ F.map (πŸ™ j', i f) (F.map (f, g j ≫ hf f) (y j)) = F.map (πŸ™ j', i f) (F.map (πŸ™ j', g j' ≫ gf f) (y j')) [PROOFSTEP] rw [← wf f] [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) k'' : K i : {j j' : J} β†’ (f : j ⟢ j') β†’ kf f ⟢ k'' s : βˆ€ {j₁ jβ‚‚ j₃ jβ‚„ : J} (f : j₁ ⟢ jβ‚‚) (f' : j₃ ⟢ jβ‚„), gf f ≫ i f = hf f' ≫ i f' j j' : J f : j ⟢ j' ⊒ F.map (πŸ™ j', i f) (F.map (πŸ™ j', g j' ≫ gf f) (y j')) = F.map (πŸ™ j', g j' ≫ gf f ≫ i f) (y j') [PROOFSTEP] rw [← FunctorToTypes.map_comp_apply, prod_comp, id_comp, assoc] [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) k'' : K i : {j j' : J} β†’ (f : j ⟢ j') β†’ kf f ⟢ k'' s : βˆ€ {j₁ jβ‚‚ j₃ jβ‚„ : J} (f : j₁ ⟢ jβ‚‚) (f' : j₃ ⟢ jβ‚„), gf f ≫ i f = hf f' ≫ i f' j j' : J f : j ⟢ j' ⊒ F.map (πŸ™ j', g j' ≫ gf f ≫ i f) (y j') = F.map (πŸ™ j', g j' ≫ gf (πŸ™ j') ≫ i (πŸ™ j')) (y j') [PROOFSTEP] rw [s f (πŸ™ j'), ← s (πŸ™ j') (πŸ™ j')] -- Finally we check that this maps to `x`. [GOAL] case intro.intro.h J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) k'' : K i : {j j' : J} β†’ (f : j ⟢ j') β†’ kf f ⟢ k'' s : βˆ€ {j₁ jβ‚‚ j₃ jβ‚„ : J} (f : j₁ ⟢ jβ‚‚) (f' : j₃ ⟢ jβ‚„), gf f ≫ i f = hf f' ≫ i f' ⊒ colimitLimitToLimitColimit F (colimit.ΞΉ (curry.obj (swap K J β‹™ F) β‹™ lim) k'' (id (Limit.mk ((curry.obj (swap K J β‹™ F)).obj k'') (fun j => F.map (πŸ™ j, g j ≫ gf (πŸ™ j) ≫ i (πŸ™ j)) (y j)) (_ : βˆ€ (j j' : J) (f : j ⟢ j'), ((curry.obj (swap K J β‹™ F)).obj k'').map f (F.map (πŸ™ j, g j ≫ gf (πŸ™ j) ≫ i (πŸ™ j)) (y j)) = F.map (πŸ™ j', g j' ≫ gf (πŸ™ j') ≫ i (πŸ™ j')) (y j'))))) = x [PROOFSTEP] apply limit_ext' [GOAL] case intro.intro.h.w J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) k'' : K i : {j j' : J} β†’ (f : j ⟢ j') β†’ kf f ⟢ k'' s : βˆ€ {j₁ jβ‚‚ j₃ jβ‚„ : J} (f : j₁ ⟢ jβ‚‚) (f' : j₃ ⟢ jβ‚„), gf f ≫ i f = hf f' ≫ i f' ⊒ βˆ€ (j : J), limit.Ο€ (curry.obj F β‹™ colim) j (colimitLimitToLimitColimit F (colimit.ΞΉ (curry.obj (swap K J β‹™ F) β‹™ lim) k'' (id (Limit.mk ((curry.obj (swap K J β‹™ F)).obj k'') (fun j => F.map (πŸ™ j, g j ≫ gf (πŸ™ j) ≫ i (πŸ™ j)) (y j)) (_ : βˆ€ (j j' : J) (f : j ⟢ j'), ((curry.obj (swap K J β‹™ F)).obj k'').map f (F.map (πŸ™ j, g j ≫ gf (πŸ™ j) ≫ i (πŸ™ j)) (y j)) = F.map (πŸ™ j', g j' ≫ gf (πŸ™ j') ≫ i (πŸ™ j')) (y j')))))) = limit.Ο€ (curry.obj F β‹™ colim) j x [PROOFSTEP] intro j [GOAL] case intro.intro.h.w J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) k'' : K i : {j j' : J} β†’ (f : j ⟢ j') β†’ kf f ⟢ k'' s : βˆ€ {j₁ jβ‚‚ j₃ jβ‚„ : J} (f : j₁ ⟢ jβ‚‚) (f' : j₃ ⟢ jβ‚„), gf f ≫ i f = hf f' ≫ i f' j : J ⊒ limit.Ο€ (curry.obj F β‹™ colim) j (colimitLimitToLimitColimit F (colimit.ΞΉ (curry.obj (swap K J β‹™ F) β‹™ lim) k'' (id (Limit.mk ((curry.obj (swap K J β‹™ F)).obj k'') (fun j => F.map (πŸ™ j, g j ≫ gf (πŸ™ j) ≫ i (πŸ™ j)) (y j)) (_ : βˆ€ (j j' : J) (f : j ⟢ j'), ((curry.obj (swap K J β‹™ F)).obj k'').map f (F.map (πŸ™ j, g j ≫ gf (πŸ™ j) ≫ i (πŸ™ j)) (y j)) = F.map (πŸ™ j', g j' ≫ gf (πŸ™ j') ≫ i (πŸ™ j')) (y j')))))) = limit.Ο€ (curry.obj F β‹™ colim) j x [PROOFSTEP] simp only [id.def, ← e, Limits.ΞΉ_colimitLimitToLimitColimit_Ο€_apply, colimit_eq_iff.{v, v}, Bifunctor.map_id_comp, types_comp_apply, curry_obj_obj_map, Functor.comp_obj, colim_obj, Limit.Ο€_mk] [GOAL] case intro.intro.h.w J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) k'' : K i : {j j' : J} β†’ (f : j ⟢ j') β†’ kf f ⟢ k'' s : βˆ€ {j₁ jβ‚‚ j₃ jβ‚„ : J} (f : j₁ ⟢ jβ‚‚) (f' : j₃ ⟢ jβ‚„), gf f ≫ i f = hf f' ≫ i f' j : J ⊒ βˆƒ k_1 f g_1, F.map (πŸ™ j, f) (F.map (πŸ™ j, g j ≫ gf (πŸ™ j) ≫ i (πŸ™ j)) (y j)) = F.map (πŸ™ j, g_1) (y j) [PROOFSTEP] refine' ⟨k'', πŸ™ k'', g j ≫ gf (πŸ™ j) ≫ i (πŸ™ j), _⟩ -- porting note: the lean 3 proof finished with -- `simp only [Bifunctor.map_id_comp, types_comp_apply, Bifunctor.map_id, types_id_apply]` -- which doesn't work; the corresponding `rw` works fine: [GOAL] case intro.intro.h.w J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J x : limit (curry.obj F β‹™ colim) k : J β†’ K y : (j : J) β†’ F.obj (j, k j) e : βˆ€ (j : J), colimit.ΞΉ ((curry.obj F).obj j) (k j) (y j) = limit.Ο€ (curry.obj F β‹™ colim) j x k' : K g : (j : J) β†’ k j ⟢ k' kf : {j j' : J} β†’ (j ⟢ j') β†’ K hf gf : {j j' : J} β†’ (f : j ⟢ j') β†’ k' ⟢ kf f wf : βˆ€ {j j' : J} (f : j ⟢ j'), F.map (πŸ™ j', g j' ≫ gf f) (y j') = F.map (f, g j ≫ hf f) (y j) k'' : K i : {j j' : J} β†’ (f : j ⟢ j') β†’ kf f ⟢ k'' s : βˆ€ {j₁ jβ‚‚ j₃ jβ‚„ : J} (f : j₁ ⟢ jβ‚‚) (f' : j₃ ⟢ jβ‚„), gf f ≫ i f = hf f' ≫ i f' j : J ⊒ F.map (πŸ™ j, πŸ™ k'') (F.map (πŸ™ j, g j ≫ gf (πŸ™ j) ≫ i (πŸ™ j)) (y j)) = F.map (πŸ™ j, g j ≫ gf (πŸ™ j) ≫ i (πŸ™ j)) (y j) [PROOFSTEP] rw [Bifunctor.map_id_comp, Bifunctor.map_id_comp, types_comp_apply, types_comp_apply, Bifunctor.map_id, types_id_apply] [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F✝ : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J F : J β₯€ K β₯€ Type v ⊒ IsIso (colimitLimitToLimitColimitCone F) [PROOFSTEP] have : IsIso (colimitLimitToLimitColimitCone F).Hom := by suffices : IsIso (colimitLimitToLimitColimit (uncurry.obj F) ≫ lim.map (whiskerRight (currying.unitIso.app F).inv colim)) apply IsIso.comp_isIso infer_instance [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F✝ : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J F : J β₯€ K β₯€ Type v ⊒ IsIso (colimitLimitToLimitColimitCone F).Hom [PROOFSTEP] suffices : IsIso (colimitLimitToLimitColimit (uncurry.obj F) ≫ lim.map (whiskerRight (currying.unitIso.app F).inv colim)) [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F✝ : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J F : J β₯€ K β₯€ Type v this : IsIso (colimitLimitToLimitColimit (uncurry.obj F) ≫ lim.map (whiskerRight (currying.unitIso.app F).inv colim)) ⊒ IsIso (colimitLimitToLimitColimitCone F).Hom case this J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F✝ : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J F : J β₯€ K β₯€ Type v ⊒ IsIso (colimitLimitToLimitColimit (uncurry.obj F) ≫ lim.map (whiskerRight (currying.unitIso.app F).inv colim)) [PROOFSTEP] apply IsIso.comp_isIso [GOAL] case this J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F✝ : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J F : J β₯€ K β₯€ Type v ⊒ IsIso (colimitLimitToLimitColimit (uncurry.obj F) ≫ lim.map (whiskerRight (currying.unitIso.app F).inv colim)) [PROOFSTEP] infer_instance [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F✝ : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J F : J β₯€ K β₯€ Type v this : IsIso (colimitLimitToLimitColimitCone F).Hom ⊒ IsIso (colimitLimitToLimitColimitCone F) [PROOFSTEP] apply Cones.cone_iso_of_hom_iso [GOAL] J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J ⊒ PreservesFiniteLimits colim [PROOFSTEP] apply preservesFiniteLimitsOfPreservesFiniteLimitsOfSize.{v} [GOAL] case h J K : Type v inst✝³ : SmallCategory J inst✝² : SmallCategory K F : J Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J ⊒ (J : Type v) β†’ {π’₯ : SmallCategory J} β†’ FinCategory J β†’ PreservesLimitsOfShape J colim [PROOFSTEP] intro J _ _ [GOAL] case h J✝ K : Type v inst✝³ : SmallCategory J✝ inst✝² : SmallCategory K F : J✝ Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J✝ J : Type v π’₯✝ : SmallCategory J x✝ : FinCategory J ⊒ PreservesLimitsOfShape J colim [PROOFSTEP] refine ⟨fun {F} => ⟨fun {c} hc => IsLimit.ofIsoLimit (limit.isLimit _) ?_⟩⟩ [GOAL] case h J✝ K : Type v inst✝³ : SmallCategory J✝ inst✝² : SmallCategory K F✝ : J✝ Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J✝ J : Type v π’₯✝ : SmallCategory J x✝ : FinCategory J F : J β₯€ K β₯€ Type v c : Cone F hc : IsLimit c ⊒ limit.cone (F β‹™ colim) β‰… colim.mapCone c [PROOFSTEP] symm [GOAL] case h J✝ K : Type v inst✝³ : SmallCategory J✝ inst✝² : SmallCategory K F✝ : J✝ Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J✝ J : Type v π’₯✝ : SmallCategory J x✝ : FinCategory J F : J β₯€ K β₯€ Type v c : Cone F hc : IsLimit c ⊒ colim.mapCone c β‰… limit.cone (F β‹™ colim) [PROOFSTEP] trans colim.mapCone (limit.cone F) [GOAL] J✝ K : Type v inst✝³ : SmallCategory J✝ inst✝² : SmallCategory K F✝ : J✝ Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J✝ J : Type v π’₯✝ : SmallCategory J x✝ : FinCategory J F : J β₯€ K β₯€ Type v c : Cone F hc : IsLimit c ⊒ colim.mapCone c β‰… colim.mapCone (limit.cone F) [PROOFSTEP] exact Functor.mapIso _ (hc.uniqueUpToIso (limit.isLimit F)) [GOAL] J✝ K : Type v inst✝³ : SmallCategory J✝ inst✝² : SmallCategory K F✝ : J✝ Γ— K β₯€ Type v inst✝¹ : IsFiltered K inst✝ : FinCategory J✝ J : Type v π’₯✝ : SmallCategory J x✝ : FinCategory J F : J β₯€ K β₯€ Type v c : Cone F hc : IsLimit c ⊒ colim.mapCone (limit.cone F) β‰… limit.cone (F β‹™ colim) [PROOFSTEP] exact asIso (colimitLimitToLimitColimitCone.{v, v + 1} F) [GOAL] J K : Type v inst✝¹⁰ : SmallCategory J inst✝⁹ : SmallCategory K F : J Γ— K β₯€ Type v inst✝⁸ : IsFiltered K inst✝⁷ : FinCategory J C : Type u inst✝⁢ : Category.{v, u} C inst✝⁡ : ConcreteCategory C inst✝⁴ : PreservesFiniteLimits (forget C) inst✝³ : PreservesFilteredColimits (forget C) inst✝² : HasFiniteLimits C inst✝¹ : HasColimitsOfShape K C inst✝ : ReflectsIsomorphisms (forget C) ⊒ PreservesFiniteLimits colim [PROOFSTEP] apply preservesFiniteLimitsOfPreservesFiniteLimitsOfSize.{v} [GOAL] case h J K : Type v inst✝¹⁰ : SmallCategory J inst✝⁹ : SmallCategory K F : J Γ— K β₯€ Type v inst✝⁸ : IsFiltered K inst✝⁷ : FinCategory J C : Type u inst✝⁢ : Category.{v, u} C inst✝⁡ : ConcreteCategory C inst✝⁴ : PreservesFiniteLimits (forget C) inst✝³ : PreservesFilteredColimits (forget C) inst✝² : HasFiniteLimits C inst✝¹ : HasColimitsOfShape K C inst✝ : ReflectsIsomorphisms (forget C) ⊒ (J : Type v) β†’ {π’₯ : SmallCategory J} β†’ FinCategory J β†’ PreservesLimitsOfShape J colim [PROOFSTEP] intro J _ _ [GOAL] case h J✝ K : Type v inst✝¹⁰ : SmallCategory J✝ inst✝⁹ : SmallCategory K F : J✝ Γ— K β₯€ Type v inst✝⁸ : IsFiltered K inst✝⁷ : FinCategory J✝ C : Type u inst✝⁢ : Category.{v, u} C inst✝⁡ : ConcreteCategory C inst✝⁴ : PreservesFiniteLimits (forget C) inst✝³ : PreservesFilteredColimits (forget C) inst✝² : HasFiniteLimits C inst✝¹ : HasColimitsOfShape K C inst✝ : ReflectsIsomorphisms (forget C) J : Type v π’₯✝ : SmallCategory J x✝ : FinCategory J ⊒ PreservesLimitsOfShape J colim [PROOFSTEP] infer_instance [GOAL] J K : Type v inst✝¹⁰ : SmallCategory J inst✝⁹ : SmallCategory K F✝ : J Γ— K β₯€ Type v inst✝⁸ : IsFiltered K inst✝⁷ : FinCategory J C : Type u inst✝⁢ : Category.{v, u} C inst✝⁡ : ConcreteCategory C inst✝⁴ : HasLimitsOfShape J C inst✝³ : HasColimitsOfShape K C inst✝² : ReflectsLimitsOfShape J (forget C) inst✝¹ : PreservesColimitsOfShape K (forget C) inst✝ : PreservesLimitsOfShape J (forget C) F : J β₯€ K β₯€ C a : K b : J ⊒ colimit.ΞΉ (limit F) a ≫ (colimitLimitIso F).hom ≫ limit.Ο€ (colimit (Functor.flip F)) b = NatTrans.app (limit.Ο€ F b) a ≫ NatTrans.app (colimit.ΞΉ (Functor.flip F) a) b [PROOFSTEP] dsimp [colimitLimitIso] [GOAL] J K : Type v inst✝¹⁰ : SmallCategory J inst✝⁹ : SmallCategory K F✝ : J Γ— K β₯€ Type v inst✝⁸ : IsFiltered K inst✝⁷ : FinCategory J C : Type u inst✝⁢ : Category.{v, u} C inst✝⁡ : ConcreteCategory C inst✝⁴ : HasLimitsOfShape J C inst✝³ : HasColimitsOfShape K C inst✝² : ReflectsLimitsOfShape J (forget C) inst✝¹ : PreservesColimitsOfShape K (forget C) inst✝ : PreservesLimitsOfShape J (forget C) F : J β₯€ K β₯€ C a : K b : J ⊒ colimit.ΞΉ (limit F) a ≫ ((IsLimit.conePointUniqueUpToIso (isLimitOfPreserves colim (limit.isLimit F)) (limit.isLimit (F β‹™ colim))).hom ≫ (HasLimit.isoOfNatIso (colimitFlipIsoCompColim F).symm).hom) ≫ limit.Ο€ (colimit (Functor.flip F)) b = NatTrans.app (limit.Ο€ F b) a ≫ NatTrans.app (colimit.ΞΉ (Functor.flip F) a) b [PROOFSTEP] simp only [Functor.mapCone_Ο€_app, Iso.symm_hom, Limits.limit.conePointUniqueUpToIso_hom_comp_assoc, Limits.limit.cone_Ο€, Limits.colimit.ΞΉ_map_assoc, Limits.colimitFlipIsoCompColim_inv_app, assoc, Limits.HasLimit.isoOfNatIso_hom_Ο€] [GOAL] J K : Type v inst✝¹⁰ : SmallCategory J inst✝⁹ : SmallCategory K F✝ : J Γ— K β₯€ Type v inst✝⁸ : IsFiltered K inst✝⁷ : FinCategory J C : Type u inst✝⁢ : Category.{v, u} C inst✝⁡ : ConcreteCategory C inst✝⁴ : HasLimitsOfShape J C inst✝³ : HasColimitsOfShape K C inst✝² : ReflectsLimitsOfShape J (forget C) inst✝¹ : PreservesColimitsOfShape K (forget C) inst✝ : PreservesLimitsOfShape J (forget C) F : J β₯€ K β₯€ C a : K b : J ⊒ NatTrans.app (limit.Ο€ F b) a ≫ colimit.ΞΉ (F.obj b) a ≫ (HasColimit.isoOfNatIso (flipCompEvaluation F b)).inv ≫ (colimitObjIsoColimitCompEvaluation (Functor.flip F) b).inv = NatTrans.app (limit.Ο€ F b) a ≫ NatTrans.app (colimit.ΞΉ (Functor.flip F) a) b [PROOFSTEP] congr 1 [GOAL] case e_a J K : Type v inst✝¹⁰ : SmallCategory J inst✝⁹ : SmallCategory K F✝ : J Γ— K β₯€ Type v inst✝⁸ : IsFiltered K inst✝⁷ : FinCategory J C : Type u inst✝⁢ : Category.{v, u} C inst✝⁡ : ConcreteCategory C inst✝⁴ : HasLimitsOfShape J C inst✝³ : HasColimitsOfShape K C inst✝² : ReflectsLimitsOfShape J (forget C) inst✝¹ : PreservesColimitsOfShape K (forget C) inst✝ : PreservesLimitsOfShape J (forget C) F : J β₯€ K β₯€ C a : K b : J ⊒ colimit.ΞΉ (F.obj b) a ≫ (HasColimit.isoOfNatIso (flipCompEvaluation F b)).inv ≫ (colimitObjIsoColimitCompEvaluation (Functor.flip F) b).inv = NatTrans.app (colimit.ΞΉ (Functor.flip F) a) b [PROOFSTEP] simp only [← Category.assoc, Iso.comp_inv_eq, Limits.colimitObjIsoColimitCompEvaluation_ΞΉ_app_hom, Limits.HasColimit.isoOfNatIso_ΞΉ_hom, NatIso.ofComponents_hom_app] [GOAL] case e_a J K : Type v inst✝¹⁰ : SmallCategory J inst✝⁹ : SmallCategory K F✝ : J Γ— K β₯€ Type v inst✝⁸ : IsFiltered K inst✝⁷ : FinCategory J C : Type u inst✝⁢ : Category.{v, u} C inst✝⁡ : ConcreteCategory C inst✝⁴ : HasLimitsOfShape J C inst✝³ : HasColimitsOfShape K C inst✝² : ReflectsLimitsOfShape J (forget C) inst✝¹ : PreservesColimitsOfShape K (forget C) inst✝ : PreservesLimitsOfShape J (forget C) F : J β₯€ K β₯€ C a : K b : J ⊒ colimit.ΞΉ (F.obj b) a = NatTrans.app (flipCompEvaluation F b).hom a ≫ colimit.ΞΉ (F.obj b) a [PROOFSTEP] dsimp [GOAL] case e_a J K : Type v inst✝¹⁰ : SmallCategory J inst✝⁹ : SmallCategory K F✝ : J Γ— K β₯€ Type v inst✝⁸ : IsFiltered K inst✝⁷ : FinCategory J C : Type u inst✝⁢ : Category.{v, u} C inst✝⁡ : ConcreteCategory C inst✝⁴ : HasLimitsOfShape J C inst✝³ : HasColimitsOfShape K C inst✝² : ReflectsLimitsOfShape J (forget C) inst✝¹ : PreservesColimitsOfShape K (forget C) inst✝ : PreservesLimitsOfShape J (forget C) F : J β₯€ K β₯€ C a : K b : J ⊒ colimit.ΞΉ (F.obj b) a = πŸ™ ((F.obj b).obj a) ≫ colimit.ΞΉ (F.obj b) a [PROOFSTEP] simp
/- Copyright (c) 2020 FrΓ©dΓ©ric Dupuis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: FrΓ©dΓ©ric Dupuis -/ import analysis.convex.function import topology.algebra.affine import topology.local_extr import topology.metric_space.basic /-! # Minima and maxima of convex functions We show that if a function `f : E β†’ Ξ²` is convex, then a local minimum is also a global minimum, and likewise for concave functions. -/ variables {E Ξ² : Type*} [add_comm_group E] [topological_space E] [module ℝ E] [topological_add_group E] [has_continuous_smul ℝ E] [linear_ordered_add_comm_group Ξ²] [module ℝ Ξ²] [ordered_smul ℝ Ξ²] {s : set E} open set filter open_locale classical /-- Helper lemma for the more general case: `is_min_on.of_is_local_min_on_of_convex_on`. -/ lemma is_min_on.of_is_local_min_on_of_convex_on_Icc {f : ℝ β†’ Ξ²} {a b : ℝ} (a_lt_b : a < b) (h_local_min : is_local_min_on f (Icc a b) a) (h_conv : convex_on ℝ (Icc a b) f) : βˆ€ x ∈ Icc a b, f a ≀ f x := begin by_contra' H_cont, rcases H_cont with ⟨x, ⟨h_ax, h_xb⟩, fx_lt_fa⟩, obtain ⟨z, hz, ge_on_nhd⟩ : βˆƒ z > a, βˆ€ y ∈ (Icc a z), f y β‰₯ f a, { rcases eventually_iff_exists_mem.mp h_local_min with ⟨U, U_in_nhds_within, fy_ge_fa⟩, rw [nhds_within_Icc_eq_nhds_within_Ici a_lt_b, mem_nhds_within_Ici_iff_exists_Icc_subset] at U_in_nhds_within, rcases U_in_nhds_within with ⟨Ρ, Ξ΅_in_Ioi, Ioc_in_U⟩, exact ⟨Ρ, mem_Ioi.mp Ξ΅_in_Ioi, Ξ» y y_in_Ioc, fy_ge_fa y $ Ioc_in_U y_in_Ioc⟩ }, have a_lt_x : a < x := lt_of_le_of_ne h_ax (Ξ» H, by subst H; exact lt_irrefl (f a) fx_lt_fa), have lt_on_nhd : βˆ€ y ∈ Ioc a x, f y < f a, { intros y y_in_Ioc, rcases (convex.mem_Ioc a_lt_x).mp y_in_Ioc with ⟨ya, yx, ya_pos, yx_pos, yax, y_combo⟩, calc f y = f (ya * a + yx * x) : by rw [y_combo] ... ≀ ya β€’ f a + yx β€’ f x : h_conv.2 (left_mem_Icc.mpr (le_of_lt a_lt_b)) ⟨h_ax, h_xb⟩ (ya_pos) (le_of_lt yx_pos) yax ... < ya β€’ f a + yx β€’ f a : add_lt_add_left (smul_lt_smul_of_pos fx_lt_fa yx_pos) _ ... = f a : by rw [←add_smul, yax, one_smul] }, by_cases h_xz : x ≀ z, { exact not_lt_of_ge (ge_on_nhd x (show x ∈ Icc a z, by exact ⟨h_ax, h_xz⟩)) fx_lt_fa, }, { have h₁ : z ∈ Ioc a x := ⟨hz, le_of_not_ge h_xz⟩, have hβ‚‚ : z ∈ Icc a z := ⟨le_of_lt hz, le_refl z⟩, exact not_lt_of_ge (ge_on_nhd z hβ‚‚) (lt_on_nhd z h₁) } end /-- A local minimum of a convex function is a global minimum, restricted to a set `s`. -/ lemma is_min_on.of_is_local_min_on_of_convex_on {f : E β†’ Ξ²} {a : E} (a_in_s : a ∈ s) (h_localmin : is_local_min_on f s a) (h_conv : convex_on ℝ s f) : βˆ€ x ∈ s, f a ≀ f x := begin by_contra' H_cont, rcases H_cont with ⟨x, ⟨x_in_s, fx_lt_fa⟩⟩, let g : ℝ →ᡃ[ℝ] E := affine_map.line_map a x, have hg0 : g 0 = a := affine_map.line_map_apply_zero a x, have hg1 : g 1 = x := affine_map.line_map_apply_one a x, have fg_local_min_on : is_local_min_on (f ∘ g) (g ⁻¹' s) 0, { rw ←hg0 at h_localmin, refine is_local_min_on.comp_continuous_on h_localmin subset.rfl (continuous.continuous_on (affine_map.line_map_continuous)) _, simp [mem_preimage, hg0, a_in_s] }, have fg_min_on : βˆ€ x ∈ (Icc 0 1 : set ℝ), (f ∘ g) 0 ≀ (f ∘ g) x, { have Icc_in_s' : Icc 0 1 βŠ† (g ⁻¹' s), { have h0 : (0 : ℝ) ∈ (g ⁻¹' s) := by simp [mem_preimage, a_in_s], have h1 : (1 : ℝ) ∈ (g ⁻¹' s) := by simp [mem_preimage, hg1, x_in_s], rw ←segment_eq_Icc (show (0 : ℝ) ≀ 1, by linarith), exact (convex.affine_preimage g h_conv.1).segment_subset (by simp [mem_preimage, hg0, a_in_s]) (by simp [mem_preimage, hg1, x_in_s]) }, have fg_local_min_on' : is_local_min_on (f ∘ g) (Icc 0 1) 0 := is_local_min_on.on_subset fg_local_min_on Icc_in_s', refine is_min_on.of_is_local_min_on_of_convex_on_Icc (by linarith) fg_local_min_on' _, exact (convex_on.comp_affine_map g h_conv).subset Icc_in_s' (convex_Icc 0 1) }, have gx_lt_ga : (f ∘ g) 1 < (f ∘ g) 0 := by simp [hg1, fx_lt_fa, hg0], exact not_lt_of_ge (fg_min_on 1 (mem_Icc.mpr ⟨zero_le_one, le_refl 1⟩)) gx_lt_ga, end /-- A local maximum of a concave function is a global maximum, restricted to a set `s`. -/ lemma is_max_on.of_is_local_max_on_of_concave_on {f : E β†’ Ξ²} {a : E} (a_in_s : a ∈ s) (h_localmax: is_local_max_on f s a) (h_conc : concave_on ℝ s f) : βˆ€ x ∈ s, f x ≀ f a := @is_min_on.of_is_local_min_on_of_convex_on _ (order_dual Ξ²) _ _ _ _ _ _ _ _ s f a a_in_s h_localmax h_conc /-- A local minimum of a convex function is a global minimum. -/ lemma is_min_on.of_is_local_min_of_convex_univ {f : E β†’ Ξ²} {a : E} (h_local_min : is_local_min f a) (h_conv : convex_on ℝ univ f) : βˆ€ x, f a ≀ f x := Ξ» x, (is_min_on.of_is_local_min_on_of_convex_on (mem_univ a) (is_local_min.on h_local_min univ) h_conv) x (mem_univ x) /-- A local maximum of a concave function is a global maximum. -/ lemma is_max_on.of_is_local_max_of_convex_univ {f : E β†’ Ξ²} {a : E} (h_local_max : is_local_max f a) (h_conc : concave_on ℝ univ f) : βˆ€ x, f x ≀ f a := @is_min_on.of_is_local_min_of_convex_univ _ (order_dual Ξ²) _ _ _ _ _ _ _ _ f a h_local_max h_conc
We will inform you about the 2 Hitch 2015 Subaru Outback image gallery we carry this website. You can look for pictures you like for details objectives. 2 Hitch 2015 Subaru Outback is the most searched search of the month. If you want to download please click β€œDownload” switch to save money on your smartphone, Tablet or Computer. If you need a photo of 2 Hitch 2015 Subaru Outback much more you could search the search on this website. We really hope the details on this web site can help you locate something you are looking for. If you have criticism and also recommendations concerning this short article, please leave a message in the comment field regarding 2 Hitch 2015 Subaru Outback.You can look for photos you like for info objectives. 2 Hitch 2015 Subaru Outback is the most looked search of the month. If you require a photo of 2 Hitch 2015 Subaru Outback more you can search the search on this web site. We have references to the background of the car you can see on the Wikipedia. A car (or car) is a wheeled automobile used for transport. Most interpretations of car state they run mostly on roadways, seat one to 8 people, have 4 tires, and also primarily transportation individuals as opposed to products. Cars and trucks entered into global use throughout the 20th century, and established economies depend on them. The year 1886 is considered as the birth year of the modern car, when German creator Karl Benz constructed his Benz Patent-Motorwagen. Cars and trucks did not become extensively offered up until the very early 20th century. One of the initial autos that was accessible to the masses was the 1908 Design T, an American car made by the Ford Electric motor Company. Vehicles were swiftly taken on in the United States, where they changed animal-drawn carriages as well as carts, but took a lot longer to be approved in Western Europe as well as various other components of the world.|A car (or auto) is a rolled electric motor vehicle made use of for transportation. The year 1886 is related to as the birth year of the modern-day car, when German inventor Karl Benz constructed his Benz Patent-Motorwagen. One of the initial cars and trucks that was accessible to the masses was the 1908 Design T, an American car made by the Ford Motor Business. When we talk about 2 Hitch 2015 Subaru Outback then we will certainly think of as well as several things. However sometimes we have to know about to understand much better. It is not far away with the crucial . If you wish to open the picture gallery please click photo image listed below. You could also download for your image collection.
function constant_test ( ) %*****************************************************************************80 % %% CONSTANT_TEST examines the constant correlation. % % Discussion: % % This code is based substantially on a document by Toby Driscoll. % % Licensing: % % This code is distributed under the GNU LGPL license. % % Modified: % % 25 February 2012 % % Author: % % John Burkardt % % Reference: % % Toby Driscoll, % Mercer's theorem and the Karhunen-Loeve expansion, % Oxford University Mathematical Institute, % http://www2.maths.ox.ac.uk/chebfun/examples/stats/pdf/MercerKarhunenLoeve.pdf % rmpath ( '/usr/local/matlab/toolbox/datafeed/datafeed' ) addpath ( '../chebfun' ) timestamp ( ); fprintf ( 1, '\n' ); fprintf ( 1, 'CONSTANT_TEST:\n' ); fprintf ( 1, ' Demonstrate Mercer''s theorem and the KL expansion\n' ); fprintf ( 1, ' for the constant kernel.\n' ); % % Set the interval. % a = 0.0; b = +10.0; fprintf ( 1, ' Using interval [%g,%g]\n', a, b ); s_num = 21; s_vec = linspace ( a, b, s_num ); % % FRED is a function from the CHEBFUN library. % % It constructs a "chebop" representing the Fredholm integral operator % with kernel K for functions in domain [A,B]. % F = fred ( @constant_correlation, domain ( [ a, b ] ) ); % % EIGS has been extended to be able to compute the eigenvalues Lambda % and eigenfunctions Psi of the Fredholm integral operator represented by F. % % The "LM" switch requests that we return the eigenvalues of largest magnitude. % % Each Psi is a CHEBFUN, that is, it takes a real number argument. % eigen_num = 20; [ Psi, Lambda ] = eigs ( F, eigen_num, 'lm' ); eigen_found = length ( Lambda ); fprintf ( 1, ' Requested %d eigenmodes, computed %d\n', eigen_num, eigen_found ); eigen_num = min ( eigen_num, eigen_found ); % % Print the eigenvalues. % lambda_vec = diag ( Lambda ); fprintf ( 1, '\n' ); fprintf ( 1, ' I Lambda(I)\n' ); fprintf ( 1, '\n' ); for i = 1 : eigen_num fprintf ( 1, ' %2d %10g\n', i, lambda_vec(i) ); end % % Plot the eigenvalues. % figure ( 1 ) clf plot ( lambda_vec, 'Linewidth', 2 ); hold on plot ( lambda_vec, 'b.', 'Markersize', 20 ); title ( 'constant: Mercer eigenvalues' ); xlabel ( '<--- N --->') grid on print -dpng 'constant_figure1.png' % % Plot selected eigenfunctions. % figure ( 2 ) subplot ( 4, 1, 1 ) plot ( Psi(:,1), 'Linewidth', 2 ); title ( 'constant: Mercer eigenfunction PSI(1)' ) grid on if ( 2 <= eigen_found ) subplot ( 4, 1, 2 ) plot ( Psi(:,2), 'Linewidth', 2 ); title ( 'constant: Mercer eigenfunction PSI(2)' ) grid on end if ( 3 <= eigen_found ) subplot ( 4, 1, 3 ) plot ( Psi(:,5), 'Linewidth', 2 ); title ( 'constant: Mercer eigenfunction PSI(5)' ) grid on end if ( 4 <= eigen_found ) subplot ( 4, 1, 4 ) plot ( Psi(:,10), 'Linewidth', 2 ); title ( 'constant: Mercer eigenfunction PSI(10)' ) grid on end print -dpng 'constant_figure2.png' % % Orthonormality check. % ptp = Psi' * Psi; error_frobenius = r8mat_is_identity ( eigen_num, ptp ); fprintf ( 1, '\n' ); fprintf ( 1, ' Frobenius norm of I - Psi'' * Psi = %g\n', error_frobenius ); % % K(S,S) should be exactly 1. % Because we are using a truncated representation of K, our estimate of K(S,S) % will be smaller than 1. % fprintf ( 1, '\n' ); fprintf ( 1, ' Truncated estimate of K(s,s) = 1 for S in the interval.\n' ); fprintf ( 1, '\n' ); fprintf ( 1, ' S K(s,s) estimate\n' ); fprintf ( 1, '\n' ); for i = 1 : 21 s = s_vec(i); ptlp = Psi(s,:) * Lambda * Psi(s,:)'; fprintf ( 1, ' %10g %14g\n', s, ptlp ); end % % Look at eigenvalue decay. % x = diff ( log ( ( 1:eigen_num ) ) ); y = diff ( log ( lambda_vec ) )'; c = y ./ x; figure ( 3 ); clf plot ( c, 'Linewidth', 2 ); grid on hold on plot ( c, 'b.', 'Markersize', 20 ); xlabel ( '<-- N -->' ) title ( 'constant: Eigenvalue decay rate' ); print -dpng 'constant_figure3.png' % % Look at eigenvalue sum. % % The trace of K(s,s) over [a,b] should be the integral of 1 over [a,b], % that is, b - a. % % We compare the trace to the partial sums of the lambda's to see how much % of the variance of the process we have captured. % trace_K = b - a; lambda_cum = cumsum ( lambda_vec ) / trace_K; fprintf ( 1, '\n' ); fprintf ( 1, ' Index Cumulative Eigenvalue sum\n' ); fprintf ( 1, '\n' ); for i = 1 : eigen_num fprintf ( 1, ' %5d %10g\n', i, lambda_cum(i) ); end % % We decide to use the first 10 eigenfunctions. % eigen_use = min ( 10, eigen_found ); % % Find 400 realizations of the process by selecting, for each realization, % 10 random parameters Z in the truncated KL expansion. % Z = randn ( eigen_use, 400 ); X = Psi(:,1:eigen_use) * ( sqrt ( Lambda(1:eigen_use,1:eigen_use) ) * Z ); % % Plot 40 of the realizations; % Plot their mean, computed from all 400. % figure ( 4 ) clf plot ( X(:,1:40) ) mu = sum ( X, 2 ) / 400; hold on; plot ( mu, 'k', 'linewidth', 3 ); title ( 'constant: 40 Random Realizations X(t,omega), and their Mean.' ) print -dpng 'constant_figure4.png' % % Estimate the covariance from the data. % figure ( 5 ) clf [ S, T ] = meshgrid ( s_vec, s_vec ); C = cov ( X(s_vec,:)' ); mesh ( S, T, C ); hold on; D = constant_correlation ( S, T ); plot3 ( S, T, D, 'k.', 'markersize', 10 ) title ( 'constant: Covariance K(S,T) (dots), and Estimate from Realizations (mesh)' ) print -dpng 'constant_figure5.png' % % Using just 10 functions in the expansion, % reduce the correlation length, % and examine the sum of the lambda's. % if ( 0 ) fprintf ( 1, '\n' ); fprintf ( 1, ' Use a fixed number of eigenfunctions = %d\n', eigen_use ); fprintf ( 1, ' but vary the correlation length RHOBAR.\n' ); fprintf ( 1, ' (We used RHOBAR = 1 above.)\n' ); fprintf ( 1, '\n' ); fprintf ( 1, ' The sum of the eigenvalues, divided by (B-A),\n' ); fprintf ( 1, ' discloses the relative amount of the total variation\n' ); fprintf ( 1, ' that is captured by the truncated expansion.\n' ); fprintf ( 1, '\n' ); fprintf ( 1, ' RHOBAR VARSUM\n' ); fprintf ( 1, '\n' ); rhobar = 4.0; for i = 1 : 10 F = fred ( @constant_correlation, domain ( [ a, b ] ) ); lambda_vec = eigs ( F, 20, 'lm' ); varsum = sum ( lambda_vec(1:eigen_use) ) / ( b - a ); fprintf ( 1, ' %10g %10g\n', rhobar, varsum ); rhobar = rhobar / 2.0; end end % % Terminate. % fprintf ( 1, '\n' ); fprintf ( 1, 'CONSTANT_TEST:\n' ); fprintf ( 1, ' Normal end of execution.\n' ); fprintf ( 1, '\n' ); timestamp ( ); rmpath ( '../chebfun' ) return end
#include "reverse_string.h" #define BOOST_TEST_MAIN #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_CASE(an_empty_string) { BOOST_REQUIRE_EQUAL("", reverse_string::reverse_string("")); } BOOST_AUTO_TEST_CASE(a_word) { BOOST_REQUIRE_EQUAL("tobor", reverse_string::reverse_string("robot")); } BOOST_AUTO_TEST_CASE(a_capitalized_word) { BOOST_REQUIRE_EQUAL("nemaR", reverse_string::reverse_string("Ramen")); } BOOST_AUTO_TEST_CASE(a_sentence_with_punctuation) { BOOST_REQUIRE_EQUAL("!yrgnuh m'I", reverse_string::reverse_string("I'm hungry!")); } BOOST_AUTO_TEST_CASE(a_palindrome) { BOOST_REQUIRE_EQUAL("racecar", reverse_string::reverse_string("racecar")); } #if defined(EXERCISM_RUN_ALL_TESTS) #endif
# File: RigidMotionsParameterSpaceCommon.mpl # # Description: # This file contains functions used to obtain an arrangement 6 dimensional parameter space of 3D # digitized rigid motions. # This code has been written for research propose and its aim is to calculate a particular # arrangement of quadrics. Therefore, it can or it cannot be useful in study of generic # arrangements. The final output are sample points of full dimensional open cells. # # The code was written in relation with the paper: Kacper Pluta, Guillaume Moroz, Yukiko # Kenmochi, Pascal Romon, Quadric arrangement in classifying rigid motions of a 3D digital image, # 2016, https://hal.archives-ouvertes.fr/hal-01334257 referred late on as [Quadrics:2016]. # # Author: # Kacper Pluta - [email protected] # Laboratoire d'Informatique Gaspard-Monge - LIGM, A3SI, France # Guillaume Moroz - [email protected] # INRIA Nancy, France # # Date: # 11/12/2015 # # License: # Simplified BSD License # # Copyright (c) 2015, Kacper Pluta, Guillaume Moroz # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL Kacper Pluta and Guillaume Moroz BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # RigidMotionsParameterSpaceCommon := module() option package; uses RigidMotionsMaplePrimesCode; local EliminationResultant, RemoveExponants, OneVariableElimination, EliminationGroebner; export CayleyTransform, GetNeighborhood, AlgebraicSort, ReduceEvents, AdjustEvents, GenerateEvents, SerializeEvents, ReconstructEvents, UnivariatePolynomial; # Procedure: CayleyTransform # Compute Cayley transform for a 3x3 skew-symmetric matrix. # # Parameters: # vars - list of variables # # Output: # 3x3 (or 2x2) rotation matrix # # Links: # https://en.wikipedia.org/wiki/Cayley_transform CayleyTransform := proc( vars::list ) local A::Matrix, QLSide::Matrix, QRSide::Matrix, dim: dim := nops(vars); if dim = 1 then A := Matrix( [ [ 0, vars[1] ], [ -vars[1], 0 ] ] ): elif dim = 2 then A := Matrix( [ [ 0, vars[2]/vars[1] ], [ -vars[2]/vars[1], 0 ] ] ); elif dim = 3 then A := Matrix( [ [ 0, vars[1], vars[2] ], [ -vars[1], 0, vars[3] ], [ -vars[2], -vars[3], 0 ] ] ): else error "Unsupported dimension! Check 1, 2 or 3": end if: dim := upperbound(A)[1]; QLSide := Matrix( dim, shape = identity ) - A: QRSide := LinearAlgebra:-MatrixInverse( Matrix( dim, shape = identity ) + A ): return simplify( QLSide . QRSide ): end proc: # Procedure: GetNeighborhood # Compute a neighborhood # # Parameters: # nType - size of neighborhood i.e. N1, N2, N3. # # Output: # List of vectors GetNeighborhood := proc( nType::string ) local n6 := [[1, 0, 0], [0, 1, 0], [0, 0, 1], [-1, 0, 0], [0, -1, 0], [0, 0, -1], [0, 0, 0]]: local n18 := [[1, 1, 0], [1, 0, 1], [0, 1, 1], [-1, -1, 0], [-1, 0, -1], [0, -1, -1], [-1, 1, 0], [-1, 0, 1], [1, -1, 0], [1, 0, -1], [0, -1, 1], [0, 1, -1]]: local n26 := [[1, 1, 1], [-1, 1, 1], [1, -1, 1], [1, 1, -1], [-1, -1, 1], [-1, 1, -1], [-1, -1, -1], [1, -1, -1]]: if nType = "N1" then return n6: elif nType = "N2" then return( [ op( n6 ), op( n18 ) ] ): elif nType = "N3" then return( [ op( n6 ), op( n18 ), op(n26) ] ): else error "Not supported type. Try N1, N2, N3.": end if: end proc: # Procedure: EliminationGroebner # Computes univariate polynomial using Groebner basis and FGb library. # # Parameters: # S - a set of quadrics # vars - a list of variables # # Comments: # To use this procedure you need to install Jean-Charles FaugΓ¨re's FGb library # --http://www-polsys.lip6.fr/~jcf/FGb/FGb/index.html # # Output: # Univariate polynomial obtained from S. # EliminationGroebner := proc(S::list, vars::list) option cache; local univ := op(FGb:-fgb_gbasis_elim(S, 0, vars[2..], vars[1])); if univ = NULL then univ := 0; fi; return univ; end proc; # Procedure: EliminationResultant # Computes univariate polynomial. # # Parameters: # S - a set of polynomials in at least two variables # vars - variables to be eliminated # # Output: # Univariate polynomial obtained from S in the first variable. EliminationResultant := proc( S::list, vars::list ) option cache; local p, var, res := S, permm; if nops(S) < 2 then error "Wrong size of the input set: %1. Expected size is at least 2.", S; fi; if not andmap(type, S, `polynom`) then error "Wrong type of elements. Expected argument is a set of polynomials but received %1."; S; fi; if nops(vars) < 1 then error "Wrong number of indeterminates. It should be at least 2."; fi; if nops(vars) = 1 then permm := combinat:-permute(res, 2); res := []; for p in permm do res := [op(res), OneVariableElimination(p[1], p[2], vars[1])]; od; return foldl( gcd, op(res) ); fi; for var in vars[2..] do permm := combinat:-permute(res, 2); res := []; for p in permm do res := [op(res), OneVariableElimination(p[1], p[2], var)]; od; od; return foldl( gcd, op(res) ); end proc: # Procedure: RemoveExponants # Removes exponants in an expression # # Parameters: # r - expression, the expression to simplify # # Output: # An arithmetic expression that has the same square free part as r. RemoveExponants := proc(r) local remove_exponant, sqrr, result; remove_exponant := e -> if type(e,`^`) then op(1,e) else e end if; result := remove_exponant(r); if type(r,`*`) then result := map(remove_exponant, result); end if; return result; end proc; OneVariableElimination := proc( p, q, v) local r; if degree(p,v)>0 or degree(q,v)>0 then r := resultant(p, q, v); r := RemoveExponants(r); return r; elif nops(indets({p,q}))=1 then return gcd(p, q); else return p; end if; end proc; # Procedure: UnivariatePolynomial # Computes univariate polynomial. # # Parameters: # S - a set of quadrics # vars - a list of variables # # Comments: # If FGb is installed then fgb_gbasis_elim() is used and EliminationResultant, otherwise. # Note that, build-in solutions like Groebner:-UnivariatePolynomial are not used because of # potential memory explosion or other problems which make them practically useless. # # Output: # Univariate polynomial obtained from S. # UnivariatePolynomial := proc(S::list, vars::list) local output; if type(FGb, package) then return EliminationGroebner([op(S)], vars); else output := EliminationResultant([op(S)], vars); if output = 0 then return PolynomialIdeals:-UnivariatePolynomial(PolynomialIdeals:-PolynomialIdeal(S),vars[1]); fi; return output; fi; end proc; # Procedure: GenerateEvents # Generates events from a univariate polynomial (see EventType) # # Parameters: # x::polynom - a univariate polynomial # quads:: - a list of quadrics # # Output: # An Array of events generated from a given univariate polynomial. GenerateEvents := proc(x::polynom, quads::list) uses ArrayTools; local events := Array([]), factored, rootsF, sqrFree, rf; if nops(indets(x)) = 1 then factored := factors(x)[2,..,1]; for sqrFree in factored do rootsF := RootFinding:-Isolate(sqrFree, output='interval'); for rf in rootsF do Append(events, EventType(RealAlgebraicNumber(sqrFree, op(rf)[2][1], op(rf)[2][2]), quads)); od; od; fi; return events; end proc; # Procedure: SerializeEvents # Changes (inplace) an Array of events into an Array of strings of unevaluated calls to # the constructor of EventType. # # Parameters: # events::Array - an Array of events (see EventType) # # Output: # An Array of strings to unevaluated calls of the constructor of EventType. SerializeEvents := proc(events::Array) return map[inplace](proc(x) sprintf("%a", x) end proc, events); end proc; # Procedure: ReconstructEvents # Changes (inplace) an Array of strings of unevaluated calls to the constructor of EventType into # the proper objects. # # Parameters: # events::Array - an Array of events (see SerializeEvents) # # Output: # An Array of EventType. ReconstructEvents := proc(events::Array) return map[inplace](proc(x) eval(parse(x)) end proc, events); end proc; # Procedure: ReduceEvents # Returns an array of events such that they are distinct. Each pair of events which are equal are # merged in such a way that a list of quadrics of the second on from a pair is merged with the # list of the first event. # # Parameters: # L::Array - an Array of events # # Output: # An Array of EventType. ReduceEvents := proc(L::Array) local R, k, j, last, x; R := Array([]); k := 0; last := 1; for j from 2 to upperbound(L) do if Compare(L[j-1], L[j], _rest) <> 0 then k := k+1; R(k) := EventType(GetRealAlgebraicNumber(L[last]), ListTools:-MakeUnique([seq(op(GetQuadrics(x)) ,x=L[last .. j-1])])); last := j end if; end do; if last <> j then ArrayTools:-Append(R, EventType(GetRealAlgebraicNumber(L[last]), ListTools:-MakeUnique([seq(op(GetQuadrics(x)) ,x=L[last .. ()])]))) fi; return R; end proc; # Procedure: AdjustEvents # Returns an array of events such that the first event will contains all the quadris and the last # event will be duplicated with changed interval of the underlaying real algebraic number. # # Parameters: # L::Array - an Array of events # # Output: # An Array of EventType. AdjustEvents := proc(events::Array, quadNum::integer, variables::list) local boundTmp, lastEvent; # assign all quadrics to the first even events[1] := EventType(GetRealAlgebraicNumber(events[1]), [seq(1..quadNum)]); # add the last slice twice but shifted to calculate correctly last quadrics boundTmp:= GetInterval(GetRealAlgebraicNumber(events[-1]))[2]+1; lastEvent := RealAlgebraicNumber(denom(boundTmp)*variables[1]-numer(boundTmp), boundTmp, boundTmp); ArrayTools:-Append(events, EventType(lastEvent, GetQuadrics(events[-1])), inplace=true) end proc; # Procedure: AlgebraicSort # Sorts [if possible in place] RealAlgebraicNumbers or Events. (see types: RealAlgebraicNumber # and EventType). # # Parameters: # events - a list or Array of RealAlgebraicNumbers or Events # # Output: # A increasingly sorted list or Array. AlgebraicSort :=proc(events) # In Maple <2016 there is a bug which causes: stack limit reached if sorting an empty Array if upperbound(events) <> 0 then return sort['inplace'](events, proc( l, r ) if Compare( l, r ) = -1 then return true: else return false: fi: end proc ); fi; return events; end proc; end module;
(* Proving Simplifier Correctness -------------------------- *) theory Example12 imports Main Example08 begin (* Let's try a slightly more sophisticated approach ... *) (* "plusConst n e" looks for a way to build an expression that is the sum of the (known) integer n and some IExpr e. Again, it looks for opportunities to apply constant folding and identity rules, but it can also take advantage of associativity to replace an expression of the form (x + m) + n with x + (m + n) when m and n are both known constants. *) fun plusConst :: "int \<Rightarrow> IExpr \<Rightarrow> IExpr" where "plusConst n (IntExpr m) = IntExpr (n+m)" | "plusConst n (PlusExpr e (IntExpr m)) = plusConst (n+m) e" | "plusConst n e = (if n=0 then e else PlusExpr e (IntExpr n))" lemma [simp] : "eval (plusConst n e) m = n + eval e m" apply (induction e arbitrary: n m rule: plusConst.induct) apply auto done (* "plus l r" looks for opportunities to exploit the optimizations provided by "plusConst"; that is, it looks for special cases where one of the two arguments has a known integer value. *) fun plus :: "IExpr \<Rightarrow> IExpr => IExpr" where "plus (IntExpr n) e = plusConst n e" | "plus e (IntExpr n) = plusConst n e" | "plus l r = PlusExpr l r" lemma [simp] : "eval (plus l r) m = eval l m + eval r m" apply (induction rule: plus.induct) apply auto done fun simpIExpr :: "IExpr \<Rightarrow> IExpr" where "simpIExpr (PlusExpr l r) = plus (simpIExpr l) (simpIExpr r)" | "simpIExpr other = other" (* Is our "optimization" correct? *) value "PlusExpr ex2 ex3" value "simpIExpr (PlusExpr ex2 ex3)" (* It looks ok here, but can we be sure it will always work? *) theorem "eval (simpIExpr e) m = eval e m" apply (induction rule: simpIExpr.induct) apply auto done end (* --------------------------------------------------------- *)
[STATEMENT] lemma reds1_Nil_iff [iff]: "\<not> uf,P,t \<turnstile>1 \<langle>[], s\<rangle> [-ta\<rightarrow>] \<langle>es', s'\<rangle>" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<not> uf,P,t \<turnstile>1 \<langle>[],s\<rangle> [-ta\<rightarrow>] \<langle>es',s'\<rangle> [PROOF STEP] by(auto elim: reds1.cases)
Formal statement is: lemma interior_interior [simp]: "interior (interior S) = interior S" Informal statement is: The interior of the interior of a set is the interior of the set.
module Registry -- Import the specifications of existing services import Int2Str import Str2Float import CompoInt2Float -- Declare the retrieve procedure of the Registry module. It takes a -- string representing a type signature and return a pair of strings -- representing respectively the name of a service and the name of a -- procedure of that service matching that type signature. The -- implementation is only available in Python for now. export retrieve : String -> (String, String)
""" outputType(s, e::Env) Determine the output type for the sentential term `s` in the environment `e` containing the type information. If `s` is not properly typed return nothing. """ outputType(s::Variable, e::Env) = get(e.userTypes, s.name, nothing)[1] function outputType(s::Union{FunctionTerm,PredicateTerm}, e::Env) if isa(s, PredicateTerm) && s.name.name == "=" # treat equality PredicateTerm oTypes = outputType.(s.args, Ref(e)) all(oTypes .== Ref(oTypes[1])) ? BoolType() : nothing else if haskey(e, s) ts = e[s] # the type of s if length(ts) == length(s.args)+1 && all(outputType.(s.args, Ref(e)) .== ts[1:end-1]) ts[end] # args are well-typed so return the output type else nothing # args are not well-typed so return nothing end else # can't find type in environment nothing end end end outputType(s::Union{NegationTerm,QuantifierTerm}, e::Env) = outputType(s.scope, e) == BoolType() ? BoolType() : nothing outputType(j::JunctionTerm, e::Env) = all(outputType.(j.juncts, Ref(e)) .== Ref(BoolType())) ? BoolType() : nothing """ isWellTyped(s, e::Env) `true/false` depending on whether `s` is well-typed/ill-typed in environment `e`. """ isWellTyped(s::SententialTerm, e::Env) = outputType(s, e) == BoolType() isWellTyped(f::FunctionTerm, e::Env) = haskey(e,f) ? outputType(f, e) == e[f][end] : false
#pragma once #ifndef _NOGSL #include <gsl/gsl_vector.h> #endif class MaxOptimizationWrapper { public: virtual gsl_vector* getMinState() = 0; virtual double getObjectiveVal() = 0; virtual bool maximize(Interface* inputs, const gsl_vector* initState, const gsl_vector* initDir, const set<int>& assertConstraints, int minimizeNode, float beta, int level, int id) = 0; };
Join us at the Strong Beer Festival for their 18th Annual celebration of Craft Beer with over 130 breweries and over 450 craft beers on tap. We will have boards set up for open play. There is NO TOURNAMENT at this event. Just come on down drink some beer, throw some bags and enjoy the beautiful AZ weather in February! 300 E Indian School Rd.
The http://safeparty.ucdavis.edu/ Safe Party Initiative was launched on http://www.news.ucdavis.edu/search/news_detail.lasso?id7481 Sept. 27, 2005 What is the Safe Party Initiative? The Safe Party Initiative (SPI) aims to reduce problems related to college student drinking at parties in the Davis community. It focuses on creating safer party environments by building a closer sense of community between students and neighbors, promoting safety at parties and increasing enforcement of alcoholrelated laws and policies. This initiative is a collaborative effort between the City of Davis and the University of California, Davis. The comprehensive initiative arose from an initial fiveyear, $6.9 million study of alcoholrelated problems at 14 California universities, funded by the National Institute for Alcoholism and Alcohol Abuse (NIAAA). UC Davis was one of seven intervention campuses asked by the Prevention Research Center to develop a coordinated campus community strategy for reducing highrisk drinking and the problems it creates. The research project seeks to reduce violence, property damage, injury and car crashes that result from highrisk drinking and outofcontrol parties. eCHECKUP TO GO UC Davis students can take the free, brief, online, anonymous and confidential program to promote campus community safety, health and wellness. This self assessment helps identify personal risk patterns and offers harm reduction strategies related to alcohol use. http://interwork.sdsu.edu/echug2/UCD Take the eCHECKUP TO GO assessment. RADD Designated Driver Rewards Program Health Education and Promotion has partnered with RADD to offer Designated Driver Cards to Davis bar patrons 21 or over. Nondrinking, sober designated drivers can get a free nonalcoholic beverage in the Davis and Sacramento areas. The Davis RADD Partner establishments are listed below. Mention RADD and that you are the designated driver of your group. Davis Bars that accept RADD cards: Beach Hut Deli Bistro 33 Burgers and Brew Cafe Bernardo Froggys G St. Wunderbar KetMoRee Little Prague Mikuni Our House Red 88 Noodle Bar Sophias Thai Kitchen Sudwerk The Davis Beer Shoppe The Davis Beer Shoppe The Grad Tres Hermanas Woodstocks Pizza Safe Party Tips The http://safeparty.ucdavis.edu Safe Party website has tips for partygoers and partythrowers, as well as a summary of Davis laws. Some safe party tips: Eat a highprotein meal before partying Alternate alcoholic and nonalcoholic drinks like water Know the http://safeparty.ucdavis.edu/laws/index.html laws Designate a nondrinking driver Avoid drinking games and jungle juice One Drink Equals: 12 oz. Beer 10 oz. Malt Liquor 5 oz. of Wine 1.5 oz. Shot of 80 proof liquor Check out our video of safe party tips http://www.youtube.com/watch?v3LAASprmA2I Safe Party Events Come hang out at the Alcohol, Tobacco and Other Drug Issues table or look for HEP volunteers at these events. Participants at the table may have a chance to win cool prizes and learn important information about how to party safely! The Buzz by Campus Unions Programs Davis Neighbors Night Out Housing Day by ASUCD http://asucd.ucdavis.edu/housingday/ Housing Day Wellness Carnival Winter 2013 January 16th, 5:30 7:30 PM at the ARC (by Health Education and Promotion Wellness Team) Presentations Alcohol, Tobacco, and Other Drug Issues Student Assistants are available to conduct programs for residence halls, fraternities, sororities and other student organizations. Alcohol Jeopardy, a program designed to teach students about the effects of alcohol on the body and how to party safely is available upon request. Programs can be scheduled by calling 530.752.9652. More information is available at the http://healthcenter.ucdavis.edu/hep/presentations.html#atod Student Health and Wellness Center website. TIPS Training The Safe Party Initiative collaborates not only with law enforcement and community members, but also with world wide programs related to safe service, sale, and consumption of alcohol, namely TIPS. TIPS, Training for Intervention Procedures provides certification for party hosts and focuses on preventing intoxication, underage drinking, and drunk driving. It also provides training for students dealing with alcohol related emergencies as well as how to intervene to help prevent such situations. This is one of the many services offered by the Student Health and Wellness Center. For information about this as well as other programs offered, please visit http://healthcenter.ucdavis.edu/hep/atod/index.html These collaborative efforts help spread the message of the SPI and put its principles into practice. Safe Party Website http://safeparty.ucdavis.edu UC Davis Safe Party Website: The UC Davis Safe Party website has information for party goers, party throwers, and an explanation of partyrelated policies and laws.
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.ring_theory.algebra_tower import Mathlib.ring_theory.polynomial.scale_roots import Mathlib.PostPort universes u_1 u_3 u_2 u_4 u_5 namespace Mathlib /-! # Integral closure of a subring. If A is an R-algebra then `a : A` is integral over R if it is a root of a monic polynomial with coefficients in R. Enough theory is developed to prove that integral elements form a sub-R-algebra of A. ## Main definitions Let `R` be a `comm_ring` and let `A` be an R-algebra. * `ring_hom.is_integral_elem (f : R β†’+* A) (x : A)` : `x` is integral with respect to the map `f`, * `is_integral (x : A)` : `x` is integral over `R`, i.e., is a root of a monic polynomial with coefficients in `R`. * `integral_closure R A` : the integral closure of `R` in `A`, regarded as a sub-`R`-algebra of `A`. -/ /-- An element `x` of `A` is said to be integral over `R` with respect to `f` if it is a root of a monic polynomial `p : polynomial R` evaluated under `f` -/ def ring_hom.is_integral_elem {R : Type u_1} {A : Type u_3} [comm_ring R] [ring A] (f : R β†’+* A) (x : A) := βˆƒ (p : polynomial R), polynomial.monic p ∧ polynomial.evalβ‚‚ f x p = 0 /-- A ring homomorphism `f : R β†’+* A` is said to be integral if every element `A` is integral with respect to the map `f` -/ def ring_hom.is_integral {R : Type u_1} {A : Type u_3} [comm_ring R] [ring A] (f : R β†’+* A) := βˆ€ (x : A), ring_hom.is_integral_elem f x /-- An element `x` of an algebra `A` over a commutative ring `R` is said to be *integral*, if it is a root of some monic polynomial `p : polynomial R`. Equivalently, the element is integral over `R` with respect to the induced `algebra_map` -/ def is_integral (R : Type u_1) {A : Type u_3} [comm_ring R] [ring A] [algebra R A] (x : A) := ring_hom.is_integral_elem (algebra_map R A) x /-- An algebra is integral if every element of the extension is integral over the base ring -/ def algebra.is_integral (R : Type u_1) (A : Type u_3) [comm_ring R] [ring A] [algebra R A] := ring_hom.is_integral (algebra_map R A) theorem ring_hom.is_integral_map {R : Type u_1} {S : Type u_2} [comm_ring R] [ring S] (f : R β†’+* S) {x : R} : ring_hom.is_integral_elem f (coe_fn f x) := sorry theorem is_integral_algebra_map {R : Type u_1} {A : Type u_3} [comm_ring R] [ring A] [algebra R A] {x : R} : is_integral R (coe_fn (algebra_map R A) x) := ring_hom.is_integral_map (algebra_map R A) theorem is_integral_of_noetherian {R : Type u_1} {A : Type u_3} [comm_ring R] [ring A] [algebra R A] (H : is_noetherian R A) (x : A) : is_integral R x := sorry theorem is_integral_of_submodule_noetherian {R : Type u_1} {A : Type u_3} [comm_ring R] [ring A] [algebra R A] (S : subalgebra R A) (H : is_noetherian R β†₯↑S) (x : A) (hx : x ∈ S) : is_integral R x := sorry theorem is_integral_alg_hom {R : Type u_1} {A : Type u_2} {B : Type u_3} [comm_ring R] [comm_ring A] [comm_ring B] [algebra R A] [algebra R B] (f : alg_hom R A B) {x : A} (hx : is_integral R x) : is_integral R (coe_fn f x) := sorry theorem is_integral_of_is_scalar_tower {R : Type u_1} {A : Type u_2} {B : Type u_3} [comm_ring R] [comm_ring A] [comm_ring B] [algebra R A] [algebra R B] [algebra A B] [is_scalar_tower R A B] (x : B) (hx : is_integral R x) : is_integral A x := sorry theorem is_integral_of_subring {R : Type u_1} {A : Type u_2} [comm_ring R] [comm_ring A] [algebra R A] {x : A} (T : set R) [is_subring T] (hx : is_integral (β†₯T) x) : is_integral R x := is_integral_of_is_scalar_tower x hx theorem is_integral_algebra_map_iff {R : Type u_1} {A : Type u_2} {B : Type u_3} [comm_ring R] [comm_ring A] [comm_ring B] [algebra R A] [algebra R B] [algebra A B] [is_scalar_tower R A B] {x : A} (hAB : function.injective ⇑(algebra_map A B)) : is_integral R (coe_fn (algebra_map A B) x) ↔ is_integral R x := sorry theorem is_integral_iff_is_integral_closure_finite {R : Type u_1} {A : Type u_2} [comm_ring R] [comm_ring A] [algebra R A] {r : A} : is_integral R r ↔ βˆƒ (s : set R), set.finite s ∧ is_integral (β†₯(ring.closure s)) r := sorry theorem fg_adjoin_singleton_of_integral {R : Type u_1} {A : Type u_2} [comm_ring R] [comm_ring A] [algebra R A] (x : A) (hx : is_integral R x) : submodule.fg ↑(algebra.adjoin R (singleton x)) := sorry theorem fg_adjoin_of_finite {R : Type u_1} {A : Type u_2} [comm_ring R] [comm_ring A] [algebra R A] {s : set A} (hfs : set.finite s) (his : βˆ€ (x : A), x ∈ s β†’ is_integral R x) : submodule.fg ↑(algebra.adjoin R s) := sorry theorem is_integral_of_mem_of_fg {R : Type u_1} {A : Type u_2} [comm_ring R] [comm_ring A] [algebra R A] (S : subalgebra R A) (HS : submodule.fg ↑S) (x : A) (hx : x ∈ S) : is_integral R x := sorry theorem ring_hom.is_integral_of_mem_closure {R : Type u_1} {S : Type u_4} [comm_ring R] [comm_ring S] (f : R β†’+* S) {x : S} {y : S} {z : S} (hx : ring_hom.is_integral_elem f x) (hy : ring_hom.is_integral_elem f y) (hz : z ∈ ring.closure (insert x (singleton y))) : ring_hom.is_integral_elem f z := sorry theorem is_integral_of_mem_closure {R : Type u_1} {A : Type u_2} [comm_ring R] [comm_ring A] [algebra R A] {x : A} {y : A} {z : A} (hx : is_integral R x) (hy : is_integral R y) (hz : z ∈ ring.closure (insert x (singleton y))) : is_integral R z := ring_hom.is_integral_of_mem_closure (algebra_map R A) hx hy hz theorem ring_hom.is_integral_zero {R : Type u_1} {S : Type u_4} [comm_ring R] [comm_ring S] (f : R β†’+* S) : ring_hom.is_integral_elem f 0 := ring_hom.map_zero f β–Έ ring_hom.is_integral_map f theorem is_integral_zero {R : Type u_1} {A : Type u_2} [comm_ring R] [comm_ring A] [algebra R A] : is_integral R 0 := ring_hom.is_integral_zero (algebra_map R A) theorem ring_hom.is_integral_one {R : Type u_1} {S : Type u_4} [comm_ring R] [comm_ring S] (f : R β†’+* S) : ring_hom.is_integral_elem f 1 := ring_hom.map_one f β–Έ ring_hom.is_integral_map f theorem is_integral_one {R : Type u_1} {A : Type u_2} [comm_ring R] [comm_ring A] [algebra R A] : is_integral R 1 := ring_hom.is_integral_one (algebra_map R A) theorem ring_hom.is_integral_add {R : Type u_1} {S : Type u_4} [comm_ring R] [comm_ring S] (f : R β†’+* S) {x : S} {y : S} (hx : ring_hom.is_integral_elem f x) (hy : ring_hom.is_integral_elem f y) : ring_hom.is_integral_elem f (x + y) := ring_hom.is_integral_of_mem_closure f hx hy (is_add_submonoid.add_mem (ring.subset_closure (Or.inl rfl)) (ring.subset_closure (Or.inr rfl))) theorem is_integral_add {R : Type u_1} {A : Type u_2} [comm_ring R] [comm_ring A] [algebra R A] {x : A} {y : A} (hx : is_integral R x) (hy : is_integral R y) : is_integral R (x + y) := ring_hom.is_integral_add (algebra_map R A) hx hy theorem ring_hom.is_integral_neg {R : Type u_1} {S : Type u_4} [comm_ring R] [comm_ring S] (f : R β†’+* S) {x : S} (hx : ring_hom.is_integral_elem f x) : ring_hom.is_integral_elem f (-x) := ring_hom.is_integral_of_mem_closure f hx hx (is_add_subgroup.neg_mem (ring.subset_closure (Or.inl rfl))) theorem is_integral_neg {R : Type u_1} {A : Type u_2} [comm_ring R] [comm_ring A] [algebra R A] {x : A} (hx : is_integral R x) : is_integral R (-x) := ring_hom.is_integral_neg (algebra_map R A) hx theorem ring_hom.is_integral_sub {R : Type u_1} {S : Type u_4} [comm_ring R] [comm_ring S] (f : R β†’+* S) {x : S} {y : S} (hx : ring_hom.is_integral_elem f x) (hy : ring_hom.is_integral_elem f y) : ring_hom.is_integral_elem f (x - y) := sorry theorem is_integral_sub {R : Type u_1} {A : Type u_2} [comm_ring R] [comm_ring A] [algebra R A] {x : A} {y : A} (hx : is_integral R x) (hy : is_integral R y) : is_integral R (x - y) := ring_hom.is_integral_sub (algebra_map R A) hx hy theorem ring_hom.is_integral_mul {R : Type u_1} {S : Type u_4} [comm_ring R] [comm_ring S] (f : R β†’+* S) {x : S} {y : S} (hx : ring_hom.is_integral_elem f x) (hy : ring_hom.is_integral_elem f y) : ring_hom.is_integral_elem f (x * y) := ring_hom.is_integral_of_mem_closure f hx hy (is_submonoid.mul_mem (ring.subset_closure (Or.inl rfl)) (ring.subset_closure (Or.inr rfl))) theorem is_integral_mul {R : Type u_1} {A : Type u_2} [comm_ring R] [comm_ring A] [algebra R A] {x : A} {y : A} (hx : is_integral R x) (hy : is_integral R y) : is_integral R (x * y) := ring_hom.is_integral_mul (algebra_map R A) hx hy /-- The integral closure of R in an R-algebra A. -/ def integral_closure (R : Type u_1) (A : Type u_2) [comm_ring R] [comm_ring A] [algebra R A] : subalgebra R A := subalgebra.mk (set_of fun (r : A) => is_integral R r) is_integral_one sorry is_integral_zero sorry sorry theorem mem_integral_closure_iff_mem_fg (R : Type u_1) (A : Type u_2) [comm_ring R] [comm_ring A] [algebra R A] {r : A} : r ∈ integral_closure R A ↔ βˆƒ (M : subalgebra R A), submodule.fg ↑M ∧ r ∈ M := sorry /-- Mapping an integral closure along an `alg_equiv` gives the integral closure. -/ theorem integral_closure_map_alg_equiv {R : Type u_1} {A : Type u_2} {B : Type u_3} [comm_ring R] [comm_ring A] [comm_ring B] [algebra R A] [algebra R B] (f : alg_equiv R A B) : subalgebra.map (integral_closure R A) ↑f = integral_closure R B := sorry theorem integral_closure.is_integral {R : Type u_1} {A : Type u_2} [comm_ring R] [comm_ring A] [algebra R A] (x : β†₯(integral_closure R A)) : is_integral R x := sorry theorem ring_hom.is_integral_of_is_integral_mul_unit {R : Type u_1} {S : Type u_4} [comm_ring R] [comm_ring S] (f : R β†’+* S) (x : S) (y : S) (r : R) (hr : coe_fn f r * y = 1) (hx : ring_hom.is_integral_elem f (x * y)) : ring_hom.is_integral_elem f x := sorry theorem is_integral_of_is_integral_mul_unit {R : Type u_1} {A : Type u_2} [comm_ring R] [comm_ring A] [algebra R A] {x : A} {y : A} {r : R} (hr : coe_fn (algebra_map R A) r * y = 1) (hx : is_integral R (x * y)) : is_integral R x := ring_hom.is_integral_of_is_integral_mul_unit (algebra_map R A) x y r hr hx /-- Generalization of `is_integral_of_mem_closure` bootstrapped up from that lemma -/ theorem is_integral_of_mem_closure' {R : Type u_1} {A : Type u_2} [comm_ring R] [comm_ring A] [algebra R A] (G : set A) (hG : βˆ€ (x : A), x ∈ G β†’ is_integral R x) (x : A) (H : x ∈ subring.closure G) : is_integral R x := subring.closure_induction hx hG is_integral_zero is_integral_one (fun (_x _x_1 : A) => is_integral_add) (fun (_x : A) => is_integral_neg) fun (_x _x_1 : A) => is_integral_mul theorem is_integral_of_mem_closure'' {R : Type u_1} [comm_ring R] {S : Type u_2} [comm_ring S] {f : R β†’+* S} (G : set S) (hG : βˆ€ (x : S), x ∈ G β†’ ring_hom.is_integral_elem f x) (x : S) (H : x ∈ subring.closure G) : ring_hom.is_integral_elem f x := is_integral_of_mem_closure' G hG x hx theorem is_integral_trans_aux {R : Type u_1} {A : Type u_2} {B : Type u_3} [comm_ring R] [comm_ring A] [comm_ring B] [algebra A B] [algebra R B] (x : B) {p : polynomial A} (pmonic : polynomial.monic p) (hp : coe_fn (polynomial.aeval x) p = 0) : is_integral (β†₯(algebra.adjoin R ↑(finsupp.frange (polynomial.map (algebra_map A B) p)))) x := sorry /-- If A is an R-algebra all of whose elements are integral over R, and x is an element of an A-algebra that is integral over A, then x is integral over R.-/ theorem is_integral_trans {R : Type u_1} {A : Type u_2} {B : Type u_3} [comm_ring R] [comm_ring A] [comm_ring B] [algebra A B] [algebra R B] [algebra R A] [is_scalar_tower R A B] (A_int : algebra.is_integral R A) (x : B) (hx : is_integral A x) : is_integral R x := sorry /-- If A is an R-algebra all of whose elements are integral over R, and B is an A-algebra all of whose elements are integral over A, then all elements of B are integral over R.-/ theorem algebra.is_integral_trans {R : Type u_1} {A : Type u_2} {B : Type u_3} [comm_ring R] [comm_ring A] [comm_ring B] [algebra A B] [algebra R B] [algebra R A] [is_scalar_tower R A B] (hA : algebra.is_integral R A) (hB : algebra.is_integral A B) : algebra.is_integral R B := fun (x : B) => is_integral_trans hA x (hB x) theorem ring_hom.is_integral_trans {R : Type u_1} {S : Type u_4} {T : Type u_5} [comm_ring R] [comm_ring S] [comm_ring T] (f : R β†’+* S) (g : S β†’+* T) (hf : ring_hom.is_integral f) (hg : ring_hom.is_integral g) : ring_hom.is_integral (ring_hom.comp g f) := algebra.is_integral_trans hf hg theorem ring_hom.is_integral_of_surjective {R : Type u_1} {S : Type u_4} [comm_ring R] [comm_ring S] (f : R β†’+* S) (hf : function.surjective ⇑f) : ring_hom.is_integral f := fun (x : S) => Exists.rec_on (hf x) fun (y : R) (hy : coe_fn f y = x) => hy β–Έ ring_hom.is_integral_map f theorem is_integral_of_surjective {R : Type u_1} {A : Type u_2} [comm_ring R] [comm_ring A] [algebra R A] (h : function.surjective ⇑(algebra_map R A)) : algebra.is_integral R A := ring_hom.is_integral_of_surjective (algebra_map R A) h /-- If `R β†’ A β†’ B` is an algebra tower with `A β†’ B` injective, then if the entire tower is an integral extension so is `R β†’ A` -/ theorem is_integral_tower_bot_of_is_integral {R : Type u_1} {A : Type u_2} {B : Type u_3} [comm_ring R] [comm_ring A] [comm_ring B] [algebra A B] [algebra R B] [algebra R A] [is_scalar_tower R A B] (H : function.injective ⇑(algebra_map A B)) {x : A} (h : is_integral R (coe_fn (algebra_map A B) x)) : is_integral R x := sorry theorem ring_hom.is_integral_tower_bot_of_is_integral {R : Type u_1} {S : Type u_4} {T : Type u_5} [comm_ring R] [comm_ring S] [comm_ring T] (f : R β†’+* S) (g : S β†’+* T) (hg : function.injective ⇑g) (hfg : ring_hom.is_integral (ring_hom.comp g f)) : ring_hom.is_integral f := fun (x : S) => is_integral_tower_bot_of_is_integral hg (hfg (coe_fn g x)) theorem is_integral_tower_bot_of_is_integral_field {R : Type u_1} {A : Type u_2} {B : Type u_3} [comm_ring R] [field A] [comm_ring B] [nontrivial B] [algebra R A] [algebra A B] [algebra R B] [is_scalar_tower R A B] {x : A} (h : is_integral R (coe_fn (algebra_map A B) x)) : is_integral R x := is_integral_tower_bot_of_is_integral (ring_hom.injective (algebra_map A B)) h theorem ring_hom.is_integral_elem_of_is_integral_elem_comp {R : Type u_1} {S : Type u_4} {T : Type u_5} [comm_ring R] [comm_ring S] [comm_ring T] (f : R β†’+* S) (g : S β†’+* T) {x : T} (h : ring_hom.is_integral_elem (ring_hom.comp g f) x) : ring_hom.is_integral_elem g x := sorry theorem ring_hom.is_integral_tower_top_of_is_integral {R : Type u_1} {S : Type u_4} {T : Type u_5} [comm_ring R] [comm_ring S] [comm_ring T] (f : R β†’+* S) (g : S β†’+* T) (h : ring_hom.is_integral (ring_hom.comp g f)) : ring_hom.is_integral g := fun (x : T) => ring_hom.is_integral_elem_of_is_integral_elem_comp f g (h x) /-- If `R β†’ A β†’ B` is an algebra tower, then if the entire tower is an integral extension so is `A β†’ B`. -/ theorem is_integral_tower_top_of_is_integral {R : Type u_1} {A : Type u_2} {B : Type u_3} [comm_ring R] [comm_ring A] [comm_ring B] [algebra A B] [algebra R B] [algebra R A] [is_scalar_tower R A B] {x : B} (h : is_integral R x) : is_integral A x := sorry theorem ring_hom.is_integral_quotient_of_is_integral {R : Type u_1} {S : Type u_4} [comm_ring R] [comm_ring S] (f : R β†’+* S) {I : ideal S} (hf : ring_hom.is_integral f) : ring_hom.is_integral (ideal.quotient_map I f le_rfl) := sorry theorem is_integral_quotient_of_is_integral {R : Type u_1} {A : Type u_2} [comm_ring R] [comm_ring A] [algebra R A] {I : ideal A} (hRA : algebra.is_integral R A) : algebra.is_integral (ideal.quotient (ideal.comap (algebra_map R A) I)) (ideal.quotient I) := ring_hom.is_integral_quotient_of_is_integral (algebra_map R A) hRA theorem is_integral_quotient_map_iff {R : Type u_1} {S : Type u_4} [comm_ring R] [comm_ring S] (f : R β†’+* S) {I : ideal S} : ring_hom.is_integral (ideal.quotient_map I f le_rfl) ↔ ring_hom.is_integral (ring_hom.comp (ideal.quotient.mk I) f) := sorry /-- If the integral extension `R β†’ S` is injective, and `S` is a field, then `R` is also a field. -/ theorem is_field_of_is_integral_of_is_field {R : Type u_1} {S : Type u_2} [integral_domain R] [integral_domain S] [algebra R S] (H : algebra.is_integral R S) (hRS : function.injective ⇑(algebra_map R S)) (hS : is_field S) : is_field R := sorry theorem integral_closure_idem {R : Type u_1} {A : Type u_2} [comm_ring R] [comm_ring A] [algebra R A] : integral_closure (β†₯↑(integral_closure R A)) A = βŠ₯ := sorry protected instance integral_closure.integral_domain {R : Type u_1} {S : Type u_2} [comm_ring R] [integral_domain S] [algebra R S] : integral_domain β†₯(integral_closure R S) := integral_domain.mk comm_ring.add sorry comm_ring.zero sorry sorry comm_ring.neg comm_ring.sub sorry sorry comm_ring.mul sorry comm_ring.one sorry sorry sorry sorry sorry sorry sorry
Require Import FP.CoreData. Require Import FP.Classes. Require Import FP.Data.Identity. Import CoreDataNotation. Import ClassesNotation. Inductive susp_t (w:Type -> Type) (A:Type) : Type := SuspT { un_susp_t : unit -> w A }. Arguments SuspT {w A} _. Arguments un_susp_t {w A} _ _. Section susp_t. Context {m:Type->Type}. Definition run_susp_t {A} : susp_t m A -> m A := apply_to tt '.' un_susp_t. Definition force_t {A} : susp_t m A -> m A := run_susp_t. End susp_t. Definition susp := susp_t identity. Definition run_susp {A} : susp A -> A := run_identity '.' run_susp_t. Definition force {A} : susp A -> A := run_susp. Module SuspNotation. Notation "'delay_t' | e" := (SuspT (fun _ => e)) (at level 105). Notation "'delay' | e" := (SuspT (fun _ => Identity e)) (at level 105). End SuspNotation. Import SuspNotation. Section Monad. Context {m} `{! Monad m }. Definition susp_t_mret {A} (a:A) : susp_t m A := delay_t | mret a. Definition susp_t_mbind {A B} (aM:susp_t m A) (f:A -> susp_t m B) : susp_t m B := delay_t | a <- force_t aM ;; force_t $ f a. Global Instance susp_t_Monad : Monad (susp_t m) := { mret := @susp_t_mret ; mbind := @susp_t_mbind }. End Monad. Section Comonad. Context {w} `{! Comonad w }. Definition susp_t_coret {A} : susp_t w A -> A := coret '.' run_susp_t. Definition susp_t_cobind {A B} (aMM:susp_t w A) (f:susp_t w A -> B) : susp_t w B := delay_t | codo aM -< force_t aMM => f (delay_t | aM). Global Instance susp_t_Cobind : Comonad (susp_t w) := { coret := @susp_t_coret ; cobind := @susp_t_cobind }. End Comonad.
------------------------------------------------------------------------ -- The Agda standard library -- -- The sublist relation over propositional equality. ------------------------------------------------------------------------ {-# OPTIONS --without-K --safe #-} module Data.List.Relation.Binary.Subset.Propositional {a} {A : Set a} where import Data.List.Relation.Binary.Subset.Setoid as SetoidSubset open import Relation.Binary.PropositionalEquality using (setoid) ------------------------------------------------------------------------ -- Re-export parameterised definitions from setoid sublists open SetoidSubset (setoid A) public
```python %matplotlib inline from matplotlib.pylab import * ``` # Python Fundamentals * If you have not used python, I _hope_ you will find it is easy to do easy things with it. * Experience with any other language will help you get far, but there are some unusual python idioms that you will encounter as you go. * We use **python 3**, not python 2. Many of the online resources you find will be for python2. The languages are _nearly_ identical but different enought that you will not be able to copy-paste what you find. The main difference is `print` is a function (not a keyword) in python3; also there are differences in the names of modules and the way division works, etc. * Python has some easter eggs; `import this` is an easter egg that explains python's philosophy succinctly. ```python import this ``` The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! # The notebook interface You are using a Jupyter Notebook interface to python. In a notebook, you execute _cells_ of code. The output of the last statement is displayed when you execute a cell. You execute a cell by pressing <kbd>SHIFT</kbd>+<kbd>ENTER</kbd> ```python 3+3 ``` 6 You navigate by pressing <kbd>ESC</kbd> and then <kbd>a</kbd> to add a call before ## Fundamentals Primitive types are `int`, `float`, `str`, `list`, `tuple`, `dict`, and `set`. (There are others -- I am not trying to be comprehensive, ok!) You don't (usually) need to assign types; python guesses the types of the values you will be using. _Variables_ refer to objects of _any_ type. ```python x = 3 print(x) ``` 3 ```python print(type(x)) ``` <class 'int'> ```python x = '3' x ``` '3' ```python 3*x ``` '333' As you can see, objects _do_ have types and their behavior depends on their type!! ```python assert isinstance(x, int), "Python can do typechecking if you ask it to" ``` Most types work the way you _probably_ expect. ```python x = 4 x**2 ``` 16 ```python x ** 0.5 ``` 2.0 ```python x % 3 ``` 1 ```python -x % 3 # (-6 is the least multiple of 3 < -4) ``` 2 ## Tuples Tuples are a _read-only_ group of values ```python my_tuple = 1, 2, 3 ``` ```python my_tuple ``` (1, 2, 3) ```python my_tuple[1] ``` 2 ```python my_tuple[1] = 4 # Expect an error ``` ```python my_other_tuple = 1, 'banana', 3.14159 ``` ```python my_other_tuple ``` (1, 'banana', 3.14159) ```python x = 1, # <-- note the trailing comma! isinstance(x, tuple) ``` True ```python x ``` (1,) ## Loops In general, loops are to be avoided unless it is awkward to do something without them. Loops in python are all _foreach_ loops. ```python for i in 1, 2, 3, 4: #<-- that is a tuple by the way print(i) ``` 1 2 3 4 ```python for x in range(4): print(x) ``` 0 1 2 3 ```python for y in range(3, 12, 3): print(y, end=' ') ``` 3 6 9 Python also has `break` and `continue` keywords that work as you would expect. ## Lists ```python my_list = [1, 2, 3, 4] ``` ```python my_list[0] ``` 1 ```python my_list[4] # Expect 4 is out of bounds ``` 'a' ```python my_list[-1] # Indexing in reverse! ``` 4 ```python my_list[2] ``` 3 Slicing is a very powerful way to manipulate lists in python The fommat is `my_list[start:end:step]` to return a subsequence. You can think of it as: ``` for (int i = start; i != end; i += step) result.append(a reference to original[i]) ``` ```python my_list[:2] ``` [1, 2] ```python my_list[2:] ``` [3, 4] ```python my_list[1:3] ``` [2, 3] ```python my_list[::-1] ``` [4, 3, 2, 1] ```python print(my_list.pop()) print(my_list) ``` 4 [1, 2, 3] ```python my_list.append(12) print(my_list) ``` [1, 2, 3, 12] ```python my_list += ['a', 'b', 'c'] my_list ``` [1, 2, 3, 12, 'a', 'b', 'c'] ```python my_list*2 ``` [1, 2, 3, 12, 'a', 'b', 'c', 1, 2, 3, 12, 'a', 'b', 'c'] ## Sets ```python s = {1, 2, 3, 'a'} ``` ```python 1 in s ``` True ```python 4 in s ``` False ```python 4 not in s ``` True ```python t = {2, 3, 4, 5} ``` ```python s.intersection(t) ``` {2, 3} ```python s.union(t) ``` {1, 2, 3, 4, 5, 'a'} ```python s.add(12) ``` ```python s ``` {1, 12, 2, 3, 'a'} ## Dictionaries ```python x = dict(a = 1, b=2, c= 'banana') ``` ```python x ``` {'a': 1, 'b': 2, 'c': 'banana'} ```python x['a'] ``` 1 ```python print(x.keys()) print(x.values()) print(x.items()) ``` dict_keys(['a', 'b', 'c']) dict_values([1, 2, 'banana']) dict_items([('a', 1), ('b', 2), ('c', 'banana')]) ```python x.get('a', 123) ``` 1 ```python x.get('notinthedict', 123) ``` 123 ```python x['newkey'] = 321 ``` ```python 'newkey' in x ``` True ```python 'newkey' not in x ``` False ```python for key in x: #<-- only iterates ver keys print(key) ``` a b c newkey ```python x.update(c = 4, d = 5) x ``` {'a': 1, 'b': 2, 'c': 4, 'newkey': 321, 'd': 5} Sometimes it is useful to `pop` (read + remove) a value ```python print(x) a = x.pop('a', 0) print("a=", a) print(x) ``` {'a': 1, 'b': 2, 'c': 4, 'newkey': 321, 'd': 5} a= 1 {'b': 2, 'c': 4, 'newkey': 321, 'd': 5} ## Functions ```python def foo(): print("Hi, I'm a function") ``` ```python foo() ``` Hi, I'm a function ```python def foo(x): print("You passed in", x) ``` ```python foo(3) ``` You passed in 3 ```python def foo(x, y=0, z=0): print("You passed in", (x, y, z)) foo(3) ``` You passed in (3, 0, 0) ```python foo(3, 4) ``` You passed in (3, 4, 0) ```python foo(3, z=12) ``` You passed in (3, 0, 12) ```python def foo(*args): print("You passed in", args) foo(1, 2, 3, 4) ``` You passed in (1, 2, 3, 4) ```python foo(1, 2, z=7) # Expect an error ``` ```python def foo(*args, **kwargs): print("You passed in", args, "and", kwargs) ``` ```python foo(1, 2, x=6, y=8) ``` You passed in (1, 2) and {'x': 6, 'y': 8} ```python def add(x=0, y=0, z=0): return x + y + z ``` ```python add(3, 4) ``` 7 ```python args = (1,2, 3) add(*args) #Unpacking ``` 6 ```python args = dict(x=3, y=4, z=5) add(**args) #Unpacking named arguments ``` 12 ```python def add(*args, **kwargs): """Adds all of the arguments Parameters ---------- args: A list of arguments kwargs: A list of named arguments (names are ignored) Returns ------- total: The sum of all arguments. Example ------- >>> add(1, 2, x=3, y=4) 10 """ return (sum(args) + sum(list(kwargs.values()))) # <-- converting to list... ``` ```python add(1, 2, x=3, y=4) ``` 10 ```python help(add) ``` Help on function add in module __main__: add(*args, **kwargs) Adds all of the arguments Parameters ---------- args: A list of arguments kwargs: A list of named arguments (names are ignored) Returns ------- total: The sum of all arguments. Example ------- >>> add(1, 2, x=3, y=4) 10 Try typing `add` <kbd>SHIFT</kbd> <kbd>TAB</kbd><kbd>TAB</kbd><kbd>TAB</kbd><kbd>TAB</kbd> ```python def foo(x:int, y:str)->str: """ This function has type annotations. They are not used by python, but other tools that analyse your code use them. """ return "Blegh" ``` ```python def foo(): """Generate pseudo random numbers (forever)""" while True: yield (345 + i * 12345)%(5267) / 5266. ``` ```python foo() ``` <generator object foo at 0x7fb44058f840> ```python foo().__next__() ``` 0.4409418913786555 ```python for i, x in enumerate(foo()): print("{:03}: {:.2f}".format(i, x)) if i > 10: break ``` 000: 0.44 001: 0.07 002: 0.41 003: 0.75 004: 0.10 005: 0.44 006: 0.78 007: 0.13 008: 0.47 009: 0.82 010: 0.16 011: 0.50 ```python ``` ## Classes ```python class Fizz(object): def __init__(self, x, y=3): #Constructor super().__init__() # Explicitly call super-class'es constructor self.x = x self.y = y self._private = 0 def buzz(self): print(f"Bzzzz -- also x={self.x} and y={self.y}") ``` ```python f = Fizz(2) f.buzz() ``` Bzzzz -- also x=2 and y=3 Try typeing `f.`<kbd>TAB</kbd>, notice that `_private` is not suggested. ```python ``` You can _still_ access `f._private`; but you shouldn't unless you are the author of Fizz or you are ready for the repercussins(!) ```python f._private ``` 0 Many tools will generate a warning if you access pseudo-private members. ```python class Fizz(object): def __init__(self, x, y=3): #Constructor super().__init__() # Explicitly call super-class'es constructor self.x = x self.y = y self._private = 0 def buzz(self): print(f"Bzzzz -- also x={self.x} and y={self.y}") @property def notsoprivate(self): return self._private @notsoprivate.setter def notsoprivate(self, value): if value > 0 and value != self._private: self._private = value # Maybe do some other stuff here? else: raise ValueError("notsoprivate must be positive") ``` ```python f = Fizz(2) ``` ```python f.notsoprivate ``` 0 ```python f.notsoprivate = -2 # Expect a ValueError ``` ## Special methods Names with dunders (double undercores) are special ```python help(dict.__getitem__) ``` Help on method_descriptor: __getitem__(...) x.__getitem__(y) <==> x[y] ```python help(str.__len__) ``` Help on wrapper_descriptor: __len__(self, /) Return len(self). ```python class Foo(object): def __repr__(self): return "This is how I look in the REPL" def __str__(self): return "This is what I look like when printed or converted to a string" ``` ```python f = Foo() ``` ```python f ``` This is how I look in the REPL ```python print(f) ``` This is what I look like when printed or converted to a string ```python class Foo(object): def __repr__(self): return "This is how I look in the REPL" def __str__(self): return "This is what I look like when printed or converted to a string" def __len__(self): return 3 def __getitem__(self, index): return "abc"[index] def _repr_html_(self): return "This <font color=red>is what Jupyter</font> will show!" ``` ```python f = Foo() f ``` This <font color=red>is what Jupyter</font> will show! ```python len(f) ``` 3 ```python f[0] ``` 'a' # Arrays, Vectors, Matrices Let $\mathbf{A}$ be a random $2 \times 2$ matrix ```python A = np.random.randint(0, 10, (2,2)).astype(float); print(A) ``` [[9. 1.] [2. 0.]] Let $\mathbf{x}$ be a random vector of two elements. ```python x = np.random.randint(0, 10, 2).astype(float); print(x) ``` [5. 5.] The _matix product_ $\mathbf{A}\mathbf{x}$ is ```python y = A.dot(x) y ``` array([50., 10.]) You can verify this for the first element ```python A[0,0]*x[0] + A[0,1]*x[1] ``` 50.0 Is it **NOT** this: ```python A * x ``` array([[45., 5.], [10., 0.]]) Operators on _arrays_ are all _elementwise_ by default. # Matrix Inversion & Solving ```python x_ = np.linalg.solve(A, y) print(x_) ``` [5. 5.] ```python A_inv = np.linalg.inv(A) print(A_inv) ``` [[ 0. 0.5] [ 1. -4.5]] ```python print(A_inv.dot(y)) ``` [5. 5.] # Eigenvalues ```python evals, evecs = np.linalg.eig(A) print(np.diag(evals)) print("---- ") print(evecs) ``` [[ 9.21699057 0. ] [ 0. -0.21699057]] ---- [[ 0.97725759 -0.1078623 ] [ 0.21205568 0.99416584]] The _**columns**_ of the eigenvector matrix ($\mathbf{\Lambda}$) are eigenvectors. ```python v0 = evecs[:,0] v1 = evecs[:,1] print("v0:", v0) print("v1:", v1) ``` v0: [0.97725759 0.21205568] v1: [-0.1078623 0.99416584] The _**eigenvectors**_ are the vectors that don't change direction when multiplied by $\mathbf{A}$ ```python x, y = np.mgrid[-3:3:20j, -3:3:20j] u, v = A.dot([x.flatten(), y.flatten()]) quiver(x, y, u, v, color='red') quiver(x, y, x, y) arrow(0, 0, *evecs[:,0], width=0.05) arrow(0, 0, *evecs[:,1], width=0.05) axis('equal'); ``` The eigendecomposition is $\mathbf{A} = \mathbf{Q}\mathbf{\Lambda}\mathbf{Q}^{-1}$ ```python (evecs*evals).dot(np.linalg.inv(evecs)) ``` array([[ 9.00000000e+00, 1.00000000e+00], [ 2.00000000e+00, -5.55111512e-17]]) ```python print(A) ``` [[9. 1.] [2. 0.]] # Singular Value Decomposition The SVD is $ \mathbf{A} = \mathbf{U} \mathbf{\Sigma} \mathbf{V}^T $. The matrix $\mathbf{\Sigma} = \texttt{diag}(\pmb{\sigma})$ has the _singular values_. ```python A = np.random.randint(0, 10, (5, 10)).astype(float) A ``` array([[0., 3., 8., 3., 2., 2., 9., 6., 7., 6.], [3., 7., 8., 0., 7., 4., 9., 7., 2., 4.], [6., 9., 5., 2., 6., 6., 4., 8., 1., 8.], [8., 9., 2., 6., 3., 2., 5., 0., 4., 8.], [6., 4., 6., 1., 0., 3., 3., 2., 1., 9.]]) ```python U, sigma, VT = np.linalg.svd(A, full_matrices=False) V = VT.T print(U.shape) print(len(sigma)) print(V.shape) ``` (5, 5) 5 (10, 5) ```python print(sigma) ``` [35.00648313 11.67178935 8.60357175 6.28330328 3.57968224] The matrices $\pmb{U}$ and $\pmb{V}$ are _orthonormal_ ```python U.T.dot(U).round()+0 ``` array([[1., 0., 0., 0., 0.], [0., 1., 0., 0., 0.], [0., 0., 1., 0., 0.], [0., 0., 0., 1., 0.], [0., 0., 0., 0., 1.]]) ```python V.T.dot(V).round()+0 ``` array([[1., 0., 0., 0., 0.], [0., 1., 0., 0., 0.], [0., 0., 1., 0., 0.], [0., 0., 0., 1., 0.], [0., 0., 0., 0., 1.]]) The SVD allows us to _approximate_ the input matrix $\mathbf{A}$ using a small number of vectors. ```python imshow(A, cmap=cm.gray, vmin=0, vmax=10); ``` Try it out with a different number of singular values; change `t` below to see the effect ```python t = 2 imshow((U[:,:t]*sigma[:t]).dot(V[:,:t].T), cmap=cm.gray, vmin=0, vmax=10); ``` This can even be used for image compression ```python import skimage.data, skimage.color ``` ```python A = skimage.data.astronaut() A = skimage.color.rgb2gray(A) ``` ```python imshow(A, cmap=cm.gray) ``` ```python U, sigma, VT = np.linalg.svd(A, full_matrices=False) V = VT.T print(U.shape, V.shape) ``` (512, 512) (512, 512) ```python t = 40 imshow((U[:,:t]*sigma[:t]).dot(VT[:t]), cmap=cm.gray) original_size = A.size compressed_size = U[:,t].size + t + VT[:t].size ratio = original_size/compressed_size print("From", A.size, "to", compressed_size , "values, ",round(ratio), "to 1") ``` ## Another useful property ```python figure(figsize(4,8)) subplot(121) imshow(U.T.dot(U).round(), cmap=cm.binary) title('$\mathbf{U}^T\mathbf{U}$'); xticks([]); yticks([]) subplot(122) imshow(V.T.dot(V).round(), cmap=cm.binary) title('$\mathbf{V}^T\mathbf{V}$'); xticks([]); yticks([]); ``` We have: $$ \pmb{U}^{-1} = \pmb{U}^T$$ $$ \pmb{V}^{-1} = \pmb{U}^T$$ $$ \pmb{\Sigma}^{-1} = \texttt{diag}(1/\sigma_i)$$ And a property of matrices $$(\pmb{U}\pmb{\Sigma}\pmb{V}^T)^{-1} = \pmb{V}^{-T} \pmb{\Sigma}^{-1}\pmb{U}^{-1} = \pmb{V}\pmb{\Sigma}^{-1}\pmb{U}^T$$ So _**this factorization is easy and numerically stable to invert**_ Also we have $\sigma_i^2 = \lambda_i(\pmb{A}^T\pmb{A})$, that is, the ith singular value is the square root of the ith eigenvalue of $\pmb{A}$ squared. ```python evals, evecs = np.linalg.eig(A.T.dot(A)) print(evals[:5].round()) print((sigma[:5]**2).round()) ``` # Other Factorizations $\pmb{A} = \pmb{Q}\pmb{R}$ -- where $\pmb{Q}^T = \pmb{Q}^{-1}$ and $\pmb{R}$ is upper triangular (easy to solve) The QR decomposition is useful for computing the SVD, and for solving poorly condition least-squares problems $\pmb{A} = \pmb{R}^T\pmb{R}$ -- where $\pmb{R}$ is upper triangular. Uppar and lower triangular matrices are easy to solve for $\pmb{x}$. The _Choleski decomposition_ is useful for solving SPD matrices. **NOTE:** For the most part, in this class, you will just use `np.solve`. # Homogenous Coordinates Often, when representing points, we add an extra '1'. So $(x, y)$ becomes $(x, y, 1)$. This allows us to represent vectors (differenced between points) as $(x, y, 0)$ # Least Squares Suppose we have $$ \pmb{y} = \pmb{X}\pmb{w} + \pmb{\delta} $$ where $\pmb{\delta}$ is noise and $\pmb{X}$ is rectangular (more rows than columns). We would like find $\pmb{w}^*$ to minimize $||\pmb{y}-\pmb{X}\pmb{w}||$ For numerical reasons, we will instead minimize $\frac{1}{2}||\pmb{y}-\pmb{X}\pmb{w}||^2$ (which is minimized for the same $\pmb{w}^*$). ```python x = np.sort(np.random.rand(100)) X = np.column_stack([x, np.ones_like(x)]) ``` ```python X[:5] ``` ```python noise = 0.1*np.random.randn(len(x)) w_true = np.array([1, 2]) y = X.dot(w_true) + noise ``` ```python scatter(x, y) plot(x, X.dot(w_true), color='g'); ``` We have $$ \begin{align} ||\pmb{y} - \pmb{X}\pmb{w}||^2 &= (y-Xw)^T(y-Xw) \\ &= y^Ty-y^TXw -x^TX^Ty-w^TX^TXw \\ &= y^Ty -2 w^TX^Ty - w^T X^T X w \end{align} $$ *I got tired of making symbols bold... * Taking the derivative WRT $\pmb{w}$, we get $$ 2X^Ty - 2X^TXw $$ We want to make the derivative equal zero, so $$ X^TXw = X^Ty$$ (the factor of 2 does not effect the solution; this is why we put a $\frac{1}{2}$ in front of the error earlier) So, we can _**solve a system of equations**_ to find $\pmb{w}$ ```python np.linalg.solve(X.T.dot(X), X.T.dot(y)).round(2) ``` ```python w_true ``` There is a more convenient `lstsq` method that used SVD to solve for $\pmb{w}$ ```python w, residual, rank, sigma = np.linalg.lstsq(X, y, rcond=None) print(w.round(2)) ``` The residual is $||y - Xw||^2$ ```python print(sum((y-X.dot(w))**2), float(residual)) ``` The singular values are also returned ```python print(np.linalg.svd(X, compute_uv=False), sigma) ``` The _rank_ is the number of positive singular values (>0). ```python ```
Five students share a room at a college hostel. Two of them decide to move out and stay in a private room for their unique, weird problem. When I was doing my bachelors, my maternal uncle used to stay close to our house. He had a 5 year old son – lets call him PK. Every Sunday, PK used to come to our house to study. I was given the task of tutoring him. PK used to write with his left-hand, which was frowned upon by all the elders – my elder brother, my parents and even PK’s parents. Poor kid PK! He used to really struggle – both physically and mentally – to β€œfit in” the majority social structure. Whatever is the minority in the society – left-handedness or mental illness or queerness – it is always frowned upon, looked down upon. As if these minors are responsible for their so-called β€œdefects”. Room-Mate is a satirical take on this social mentality towards the minority. It is a very short film and hence talking much about it would be giving away the suspense. The end is really funny – but more importantly – thought provoking. It is a story of Antony and his room-mate, who are students living at a hostel. Both of them face social outcasting by the others in subtle forms – be it eve-teasing or being the fun-topic among friends or taking videos of the two and making them public. Both Antony and his roommate hence take the decision to move out of the hostel and stay in a private room. Social outcasting makes any person loose self-confidence. The person begins to doubt oneself. What if there is indeed a β€œdefect” in me? What if this thing is indeed a β€œdisease”? The person internally goes through lot of mental torture – anxiety, nervousness, embarrassment, guilt and shame. All this might easily lead to feeling of self-hatred. The relationship between Antony and his room-mate is delightfully portrayed. Both of them feel so relaxed when around each other. They share their inner feelings comfortably with each other. They are connected by their β€œdefect”, by their misfortune. The story and the direction is really tight and crisp. A beautiful, melodious song in the middle adds to the cinematic effect aptly. There is small mention of handicapped people in between – which I felt was in a bad taste. They could have easily avoided it and taken some other example – like left-handed people – to make their point.
Require Import Lists.List. Fixpoint sum (xs: list nat) : nat := match xs with | nil => 0 | x :: xs => x + sum xs end. Theorem Pigeon_Hole_Principle : forall (xs : list nat), length xs < sum xs -> (exists x, 1<x /\ In x xs). Proof. intros. exists 2. split. apply Lt.lt_n_Sn. induction xs. simpl in H. simpl. apply (Lt.lt_n_0 0 H). simpl. right. apply IHxs. (* わからγͺい... *) Qed.
# Path Integral Ground State QMC for the Harmonic Oscillator ```python import numpy as np import matplotlib.pyplot as plt %config InlineBackend.figure_format = 'retina' %matplotlib inline try: plt.style.use('./notebook.mplstyle') except: pass Ο€ = np.pi red,blue,green = '#e85c47','#4173b2','#7dcca4' ``` ## Hamiltonian \begin{equation} \hat{H} = -\lambda \frac{d^2}{dx^2} + \frac{1}{4\lambda} \left(\frac{\hbar \omega}{k_{\rm B}}\right)^2 x^2 \end{equation} where $\lambda = \hbar^2/2m$. ```python class Paths: '''The set of worldlines, action and estimators.''' def __init__(self,beads,M,Δτ,Ξ»): self.Δτ = Δτ self.Ξ» = Ξ» self.beads = np.copy(beads) self.M = M self.num_time_slices = beads.shape[0] self.N = beads.shape[1] self.norm = np.ones(self.num_time_slices) self.norm[0] = self.norm[-1] = 0.5 def V(self,x): '''harmonic oscillator potential''' Ο‰ = 1.0 return Ο‰*Ο‰*x*x /(4.0*self.Ξ») def Ξ¨(self,x): '''trial wave function''' return 1.0/np.cosh(np.sqrt(np.pi/2)*x) def kinetic_action(self,Ξ±,i): '''kinetic action of a bead.''' if Ξ± == 0.0: cK = (self.beads[Ξ±+1,i]-self.beads[Ξ±,i])**2 elif Ξ± == 2*self.M: cK = (self.beads[Ξ±,i]-self.beads[Ξ±-1,i])**2 else: cK = (self.beads[Ξ±,i]-self.beads[Ξ±-1,i])**2\ + (self.beads[Ξ±+1,i]-self.beads[Ξ±,i])**2 return cK / (4*self.Ξ»*self.Δτ) def potential_action(self,Ξ±): '''potential action of a slice.''' cV = 0.0 Ξ¨T = 1.0 for i in range(self.N): x = self.beads[Ξ±,i] cV += self.norm[Ξ±]*self.V(x) # add the wavefunction at the ends of the path if Ξ± == 0 or Ξ± == 2*self.M: Ξ¨T *= self.Ξ¨(x) return self.Δτ*cV - np.log(Ξ¨T) def Energy(self): '''The total energy.''' # the kinetic part norm = 1.0/(4.0*self.Ξ»*self.Δτ**2) KE = 0.0 for Ξ± in range(self.M-1,self.M+1): for i in range(self.N): Ξ”R = self.beads[Ξ±+1,i] - self.beads[Ξ±,i] KE -= norm*np.dot(Ξ”R,Ξ”R) KE /= 2 KE += 0.5*self.N/self.Δτ # the potential part PE = 0.0 Vslice = np.zeros(self.num_time_slices) for Ξ± in range(2*self.M+1): for i in range(self.N): cV = self.V(self.beads[Ξ±,i]) Vslice[Ξ±] += cV if Ξ± == self.M: PE += self.norm[Ξ±]*cV return KE + PE, Vslice ``` ### Displace Single-Slice Update <pre> i β”Œβ”€β—‹β”€β”€β”€β”€β—‹β”€β”€β”€β”€β—‹β”€β”€β” β”Œβ”€β—‹β”€β”€β”€β”€β—‹β”€β”€β”€β”€β—‹β”€β”€β” p β”‚ β—‹ β—‹ β—‹ β”‚ β”‚ β—‹ β—‹ β—‹ β”‚ r β”‚ β—‹ β—‹ β—‹ β”‚ β”‚ β—‹ β—‹ β—‹ β”‚ o β”‚ β—‹ β—‹ β—‹ β”‚ β”‚ β—‹ β—‹ β—‹ β”‚ j β”‚ β—‹ β—‹ β—‹ β”‚ β”‚ β—‹ ● β—‹ β”‚Ξ± e β”‚ β—‹ β—‹ β—‹ β”‚ β”‚ β—‹ β—‹ β—‹ β”‚ c β”‚ β—‹ β—‹ β—‹ β”‚ ━━▢ β”‚ β—‹ β—‹ β—‹ β”‚ t β”‚ β—‹ β—‹ β—‹ β”‚ β”‚ β—‹ β—‹ β—‹ β”‚ i β”‚ β—‹ β—‹ β—‹ β”‚ β”‚ β—‹ β—‹ β—‹ β”‚ o β”‚ β—‹ β—‹ β—‹ β”‚ β”‚ β—‹ β—‹ β—‹ β”‚ n β”‚ β—‹ β—‹ β—‹ β”‚ β”‚ β—‹ β—‹ β—‹ β”‚ β””β”€β—‹β”€β”€β”€β”€β”€β—‹β”€β”€β”€β—‹β”€β”€β”˜ β””β”€β—‹β”€β”€β”€β”€β”€β—‹β”€β”€β”€β—‹β”€β”€β”˜ </pre> ```python def displace(Path,Ξ±,i,Ξ΄=0.75): '''Single bead displace update. NB: not implemented for periodic boundary conditions. ''' # Calculate the action x = Path.beads[Ξ±,i] oldAction = Path.kinetic_action(Ξ±,i) + Path.potential_action(Ξ±) # Displace the bead Path.beads[Ξ±,i] += Ξ΄*(-1.0 + 2.0*np.random.random()) # Compute the new action newAction = Path.kinetic_action(Ξ±,i) + Path.potential_action(Ξ±) # Accept the move, or reject and restore the bead position if np.random.random() < np.exp(-(newAction - oldAction)): return True else: Path.beads[Ξ±,i] = x return False ``` ### Staging Multi-Slice Update <pre> β”Œβ”€β—‹β”€β”€β”€β”€β—‹β”€β”€β”€β”€β—‹β”€β”€β” β”Œβ”€β—‹β”€β”€β”€β”€β—‹β”€β”€β”€β”€β—‹β”€β”€β” p β”‚ β—‹ β—‹ β—‹ β”‚ β”‚ β—‹ β—‹ β—‹ β”‚ r β”‚ β—‹ β—‹ β—‹ β”‚ β”‚ β—‹ βŠ— β—‹ β”‚Ξ± + m o β”‚ β—‹ β—‹ β—‹ β”‚ β”‚ β—‹ ● β—‹ β”‚ j β”‚ β—‹ β—‹ β—‹ β”‚ β”‚ β—‹ ● β—‹ β”‚ e β”‚ β—‹ β—‹ β—‹ β”‚ β”‚ β—‹ ● β—‹ β”‚ c β”‚ β—‹ β—‹ β—‹ β”‚ ━━▢ β”‚ β—‹ ● β—‹ β”‚ t β”‚ β—‹ β—‹ β—‹ β”‚ β”‚ β—‹ ● β—‹ β”‚ i β”‚ β—‹ β—‹ β—‹ β”‚ β”‚ β—‹ βŠ— β—‹ β”‚Ξ± o β”‚ β—‹ β—‹ β—‹ β”‚ β”‚ β—‹ β—‹ β—‹ β”‚ n β”‚ β—‹ β—‹ β—‹ β”‚ β”‚ β—‹ β—‹ β—‹ β”‚ β””β”€β—‹β”€β”€β”€β”€β”€β—‹β”€β”€β”€β—‹β”€β”€β”˜ β””β”€β—‹β”€β”€β”€β”€β”€β—‹β”€β”€β”€β—‹β”€β”€β”˜ space </pre> ```python def staging(Path,m,i): '''Multi-slice update which eactly samples the free particle propagator between two fixed beads. See: http://link.aps.org/doi/10.1103/PhysRevB.31.4234 NB: not implemented for periodic boundary conditions. ''' # choose the start and end of the stage Ξ±_start = np.random.randint(low=0,high=Path.num_time_slices) Ξ±_end = Ξ±_start + m # if we move off the end of the path, reject the move if Ξ±_end >= Path.num_time_slices: return False # Record the positions of the beads to be updated and store the action x = np.copy(Path.beads[Ξ±_start+1:Ξ±_end,i]) oldAction = 0.0 for Ξ± in range(Ξ±_start+1,Ξ±_end): oldAction += Path.potential_action(Ξ±) # Generate new positions and accumulate the new action newAction = 0.0; for Ξ± in range(Ξ±_start+1,Ξ±_end): Δτ1 = Path.Δτ Δτ2 = (Ξ±_end - Ξ±)*Path.Δτ avex = (Δτ2*Path.beads[Ξ±-1,i] + Δτ1*Path.beads[Ξ±_end,i])\ / (Δτ1 + Δτ2) Οƒ = np.sqrt(2.0*Path.Ξ» / (1.0/Δτ1 + 1.0/Δτ2)) Path.beads[Ξ±,i] = np.random.normal(loc=avex,scale=Οƒ) newAction += Path.potential_action(Ξ±) # Perform the Metropolis step, if we reject, revert the worldline if np.random.random() < np.exp(-(newAction - oldAction)): return True else: Path.beads[Ξ±_start+1:Ξ±_end,i] = x return False ``` ```python def pigs(num_MC_steps,num_equil_steps,Path,m=8): '''Perform a path integral ground state Monte Carlo simulation.''' # initialize estimators and acceptance counters numAccept = {'displace':0,'staging':0} estimator = {'E':np.zeros(num_MC_steps-num_equil_steps), 'Vslice':np.zeros([num_MC_steps-num_equil_steps,Path.num_time_slices])} measure = 0 for step in range(num_MC_steps): # for each particle and slice try a displace move for Ξ± in range(Path.num_time_slices): for i in range(Path.N): numAccept['displace'] += displace(Path,Ξ±,i) # for each particle try a number of staging moves num_stage = int(Path.num_time_slices/m) for stage in range(num_stage): for i in range(Path.N): numAccept['staging'] += staging(Path,m,i) # measure the energy if step >= num_equil_steps: measure = step-num_equil_steps estimator['E'][measure],estimator['Vslice'][measure] = Path.Energy() print('displace: %4.3f' % ((1.0*numAccept['displace'])/(num_MC_steps*Path.num_time_slices*Path.N))) print('staging: %4.3f' % ((1.0*numAccept['staging'])/(num_MC_steps*Path.N*num_stage))) return estimator ``` ## Perform the PIGS Simulation ```python # setup the simulation M,N,Ο„,Ξ» = 10,1,4.0,0.5 Δτ = Ο„/M # random initial positions np.random.seed(1173) beads = -0.5 + np.random.random([2*M+1,N]) # setup the paths Path = Paths(beads,M,Δτ,Ξ») # compute the energy via path integral ground state Monte Carlo num_MC_steps = 10000 num_equil_steps = 1000 estimator = pigs(num_MC_steps,num_equil_steps,Path) ``` displace: 0.678 staging: 0.407 ## Compute the averages and their standard error ```python from scipy.stats import sem EΜ„,Ξ”EΜ„ = np.average(estimator['E']),sem(estimator['E']) VΜ„slice,Ξ”VΜ„slice = np.average(estimator['Vslice'],axis=0),sem(estimator['Vslice'],axis=0) print('EΜ„ = %f Β± %f' % (EΜ„,Ξ”EΜ„)) ``` EΜ„ = 0.488688 Β± 0.010648 ## Plot the potential energy on each slice ```python plt.axhline(y=0.25, color=green, linewidth=1.0, label='Exact') plt.errorbar(np.linspace(0,2*Ο„,2*M+1), VΜ„slice,yerr=Ξ”VΜ„slice, marker='o', color=blue, linewidth=1.0, elinewidth=1.0, markersize=6, markerfacecolor=blue, markeredgecolor=blue, ecolor=blue, label='QMC') plt.xlabel(r'$\tau$') plt.ylabel('V') plt.legend(loc='upper left'); ``` ```python ```
module FFI.System.Exit where open import Agda.Builtin.Int using (Int) open import Agda.Builtin.IO using (IO) open import Agda.Builtin.Unit using (⊀) data ExitCode : Set where ExitSuccess : ExitCode ExitFailure : Int β†’ ExitCode {-# FOREIGN GHC data AgdaExitCode = AgdaExitSuccess | AgdaExitFailure Integer #-} {-# COMPILE GHC ExitCode = data AgdaExitCode (AgdaExitSuccess | AgdaExitFailure) #-} {-# FOREIGN GHC import qualified System.Exit #-} {-# FOREIGN GHC toExitCode :: AgdaExitCode -> System.Exit.ExitCode toExitCode AgdaExitSuccess = System.Exit.ExitSuccess toExitCode (AgdaExitFailure n) = System.Exit.ExitFailure (fromIntegral n) fromExitCode :: System.Exit.ExitCode -> AgdaExitCode fromExitCode System.Exit.ExitSuccess = AgdaExitSuccess fromExitCode (System.Exit.ExitFailure n) = AgdaExitFailure (fromIntegral n) #-} postulate exitWith : ExitCode β†’ IO ⊀ {-# COMPILE GHC exitWith = System.Exit.exitWith . toExitCode #-}
(* Authors: Jose DivasΓ³n Sebastiaan Joosten RenΓ© Thiemann Akihisa Yamada *) theory Code_Abort_Gcd imports "HOL-Computational_Algebra.Polynomial_Factorial" begin text \<open>Dummy code-setup for @{const Gcd} and @{const Lcm} in the presence of Container.\<close> definition dummy_Gcd where "dummy_Gcd x = Gcd x" definition dummy_Lcm where "dummy_Lcm x = Lcm x" declare [[code abort: dummy_Gcd]] lemma dummy_Gcd_Lcm: "Gcd x = dummy_Gcd x" "Lcm x = dummy_Lcm x" unfolding dummy_Gcd_def dummy_Lcm_def by auto lemmas dummy_Gcd_Lcm_poly [code] = dummy_Gcd_Lcm [where ?'a = "'a :: {factorial_ring_gcd,semiring_gcd_mult_normalize} poly"] lemmas dummy_Gcd_Lcm_int [code] = dummy_Gcd_Lcm [where ?'a = int] lemmas dummy_Gcd_Lcm_nat [code] = dummy_Gcd_Lcm [where ?'a = nat] declare [[code abort: Euclidean_Algorithm.Gcd Euclidean_Algorithm.Lcm]] end
This course is offered at Masters level and is delivered at our Glenside Campus. For entry requirements, please see the UWE course page by clicking 'Visit Website'. You will work with your dissertation supervisor to confirm your aims, questions and proposed research strategy and set out a programme of work. You will demonstrate the ability to work independently and manage your study.. You will also participate in a dissertation progress seminar in which you will give a presentation and answer questions about the purpose, research strategy and management of your dissertation. You will have 8 hours of workshops and 12 hours of supervision available to you, totalling 20 contact hours. You will be allocated a supervisor, who will have the main responsibility for co-ordinating formal support, monitoring progress and project supervision. It is your responsibility to initiate and maintain contact with your supervisor. If you are undertaking a project requiring an NRES application you may require extra support, which will be negotiated with the course leader and your supervisor. Please note: Funding may be available to support your learning. Please contact your Trust Education Lead. If you work in the Private, Independent and Voluntary Sector, please contact your employer who will advise you.
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.adjunction.limits import category_theory.adjunction.opposites import category_theory.elements import category_theory.limits.functor_category import category_theory.limits.kan_extension import category_theory.limits.preserves.limits import category_theory.limits.shapes.terminal import category_theory.limits.types /-! # Colimit of representables This file constructs an adjunction `yoneda_adjunction` between `(Cα΅’α΅– β₯€ Type u)` and `β„°` given a functor `A : C β₯€ β„°`, where the right adjoint sends `(E : β„°)` to `c ↦ (A.obj c ⟢ E)` (provided `β„°` has colimits). This adjunction is used to show that every presheaf is a colimit of representables. Further, the left adjoint `colimit_adj.extend_along_yoneda : (Cα΅’α΅– β₯€ Type u) β₯€ β„°` satisfies `yoneda β‹™ L β‰… A`, that is, an extension of `A : C β₯€ β„°` to `(Cα΅’α΅– β₯€ Type u) β₯€ β„°` through `yoneda : C β₯€ Cα΅’α΅– β₯€ Type u`. It is the left Kan extension of `A` along the yoneda embedding, sometimes known as the Yoneda extension, as proved in `extend_along_yoneda_iso_Kan`. `unique_extension_along_yoneda` shows `extend_along_yoneda` is unique amongst cocontinuous functors with this property, establishing the presheaf category as the free cocompletion of a small category. ## Tags colimit, representable, presheaf, free cocompletion ## References * [S. MacLane, I. Moerdijk, *Sheaves in Geometry and Logic*][MM92] * https://ncatlab.org/nlab/show/Yoneda+extension -/ namespace category_theory noncomputable theory open category limits universes u₁ uβ‚‚ variables {C : Type u₁} [small_category C] variables {β„° : Type uβ‚‚} [category.{u₁} β„°] variable (A : C β₯€ β„°) namespace colimit_adj /-- The functor taking `(E : β„°) (c : Cα΅’α΅–)` to the homset `(A.obj C ⟢ E)`. It is shown in `L_adjunction` that this functor has a left adjoint (provided `E` has colimits) given by taking colimits over categories of elements. In the case where `β„° = Cα΅’α΅– β₯€ Type u` and `A = yoneda`, this functor is isomorphic to the identity. Defined as in [MM92], Chapter I, Section 5, Theorem 2. -/ @[simps] def restricted_yoneda : β„° β₯€ (Cα΅’α΅– β₯€ Type u₁) := yoneda β‹™ (whiskering_left _ _ (Type u₁)).obj (functor.op A) /-- The functor `restricted_yoneda` is isomorphic to the identity functor when evaluated at the yoneda embedding. -/ def restricted_yoneda_yoneda : restricted_yoneda (yoneda : C β₯€ Cα΅’α΅– β₯€ Type u₁) β‰… 𝟭 _ := nat_iso.of_components (Ξ» P, nat_iso.of_components (Ξ» X, yoneda_sections_small X.unop _) (Ξ» X Y f, funext $ Ξ» x, begin dsimp, rw ← functor_to_types.naturality _ _ x f (πŸ™ _), dsimp, simp, end)) (Ξ» _ _ _, rfl) /-- (Implementation). The equivalence of homsets which helps construct the left adjoint to `colimit_adj.restricted_yoneda`. It is shown in `restrict_yoneda_hom_equiv_natural` that this is a natural bijection. -/ def restrict_yoneda_hom_equiv (P : Cα΅’α΅– β₯€ Type u₁) (E : β„°) {c : cocone ((category_of_elements.Ο€ P).left_op β‹™ A)} (t : is_colimit c) : (c.X ⟢ E) ≃ (P ⟢ (restricted_yoneda A).obj E) := ((ulift_trivial _).symm β‰ͺ≫ t.hom_iso' E).to_equiv.trans { to_fun := Ξ» k, { app := Ξ» c p, k.1 (opposite.op ⟨_, p⟩), naturality' := Ξ» c c' f, funext $ Ξ» p, (k.2 (quiver.hom.op ⟨f, rfl⟩ : (opposite.op ⟨c', P.map f p⟩ : P.elementsα΅’α΅–) ⟢ opposite.op ⟨c, p⟩)).symm }, inv_fun := Ξ» Ο„, { val := Ξ» p, Ο„.app p.unop.1 p.unop.2, property := Ξ» p p' f, begin simp_rw [← f.unop.2], apply (congr_fun (Ο„.naturality f.unop.1) p'.unop.2).symm, end }, left_inv := begin rintro ⟨k₁, kβ‚‚βŸ©, ext, dsimp, congr' 1, simp, end, right_inv := begin rintro ⟨_, _⟩, refl, end } /-- (Implementation). Show that the bijection in `restrict_yoneda_hom_equiv` is natural (on the right). -/ lemma restrict_yoneda_hom_equiv_natural (P : Cα΅’α΅– β₯€ Type u₁) (E₁ Eβ‚‚ : β„°) (g : E₁ ⟢ Eβ‚‚) {c : cocone _} (t : is_colimit c) (k : c.X ⟢ E₁) : restrict_yoneda_hom_equiv A P Eβ‚‚ t (k ≫ g) = restrict_yoneda_hom_equiv A P E₁ t k ≫ (restricted_yoneda A).map g := begin ext _ X p, apply (assoc _ _ _).symm, end variables [has_colimits β„°] /-- The left adjoint to the functor `restricted_yoneda` (shown in `yoneda_adjunction`). It is also an extension of `A` along the yoneda embedding (shown in `is_extension_along_yoneda`), in particular it is the left Kan extension of `A` through the yoneda embedding. -/ def extend_along_yoneda : (Cα΅’α΅– β₯€ Type u₁) β₯€ β„° := adjunction.left_adjoint_of_equiv (Ξ» P E, restrict_yoneda_hom_equiv A P E (colimit.is_colimit _)) (Ξ» P E E' g, restrict_yoneda_hom_equiv_natural A P E E' g _) @[simp] lemma extend_along_yoneda_obj (P : Cα΅’α΅– β₯€ Type u₁) : (extend_along_yoneda A).obj P = colimit ((category_of_elements.Ο€ P).left_op β‹™ A) := rfl lemma extend_along_yoneda_map {X Y : Cα΅’α΅– β₯€ Type u₁} (f : X ⟢ Y) : (extend_along_yoneda A).map f = colimit.pre ((category_of_elements.Ο€ Y).left_op β‹™ A) (category_of_elements.map f).op := begin ext J, erw colimit.ΞΉ_pre ((category_of_elements.Ο€ Y).left_op β‹™ A) (category_of_elements.map f).op, dsimp only [extend_along_yoneda, restrict_yoneda_hom_equiv, is_colimit.hom_iso', is_colimit.hom_iso, ulift_trivial], simpa end /-- Show `extend_along_yoneda` is left adjoint to `restricted_yoneda`. The construction of [MM92], Chapter I, Section 5, Theorem 2. -/ def yoneda_adjunction : extend_along_yoneda A ⊣ restricted_yoneda A := adjunction.adjunction_of_equiv_left _ _ /-- The initial object in the category of elements for a representable functor. In `is_initial` it is shown that this is initial. -/ def elements.initial (A : C) : (yoneda.obj A).elements := ⟨opposite.op A, πŸ™ _⟩ /-- Show that `elements.initial A` is initial in the category of elements for the `yoneda` functor. -/ def is_initial (A : C) : is_initial (elements.initial A) := { desc := Ξ» s, ⟨s.X.2.op, comp_id _⟩, uniq' := Ξ» s m w, begin simp_rw ← m.2, dsimp [elements.initial], simp, end } /-- `extend_along_yoneda A` is an extension of `A` to the presheaf category along the yoneda embedding. `unique_extension_along_yoneda` shows it is unique among functors preserving colimits with this property (up to isomorphism). The first part of [MM92], Chapter I, Section 5, Corollary 4. See Property 1 of https://ncatlab.org/nlab/show/Yoneda+extension#properties. -/ def is_extension_along_yoneda : (yoneda : C β₯€ Cα΅’α΅– β₯€ Type u₁) β‹™ extend_along_yoneda A β‰… A := nat_iso.of_components (Ξ» X, (colimit.is_colimit _).cocone_point_unique_up_to_iso (colimit_of_diagram_terminal (terminal_op_of_initial (is_initial _)) _)) begin intros X Y f, change (colimit.desc _ ⟨_, _⟩ ≫ colimit.desc _ _) = colimit.desc _ _ ≫ _, apply colimit.hom_ext, intro j, rw [colimit.ΞΉ_desc_assoc, colimit.ΞΉ_desc_assoc], change (colimit.ΞΉ _ _ ≫ πŸ™ _) ≫ colimit.desc _ _ = _, rw [comp_id, colimit.ΞΉ_desc], dsimp, rw ← A.map_comp, congr' 1, end /-- See Property 2 of https://ncatlab.org/nlab/show/Yoneda+extension#properties. -/ instance : preserves_colimits (extend_along_yoneda A) := (yoneda_adjunction A).left_adjoint_preserves_colimits /-- Show that the images of `X` after `extend_along_yoneda` and `Lan yoneda` are indeed isomorphic. This follows from `category_theory.category_of_elements.costructured_arrow_yoneda_equivalence`. -/ @[simps] def extend_along_yoneda_iso_Kan_app (X) : (extend_along_yoneda A).obj X β‰… ((Lan yoneda : (_ β₯€ β„°) β₯€ _).obj A).obj X := let eq := category_of_elements.costructured_arrow_yoneda_equivalence X in { hom := colimit.pre (Lan.diagram (yoneda : C β₯€ _ β₯€ Type u₁) A X) eq.functor, inv := colimit.pre ((category_of_elements.Ο€ X).left_op β‹™ A) eq.inverse, hom_inv_id' := begin erw colimit.pre_pre ((category_of_elements.Ο€ X).left_op β‹™ A) eq.inverse, transitivity colimit.pre ((category_of_elements.Ο€ X).left_op β‹™ A) (𝟭 _), congr, { exact congr_arg functor.op (category_of_elements.from_to_costructured_arrow_eq X) }, { ext, simp only [colimit.ΞΉ_pre], erw category.comp_id, congr } end, inv_hom_id' := begin erw colimit.pre_pre (Lan.diagram (yoneda : C β₯€ _ β₯€ Type u₁) A X) eq.functor, transitivity colimit.pre (Lan.diagram (yoneda : C β₯€ _ β₯€ Type u₁) A X) (𝟭 _), congr, { exact category_of_elements.to_from_costructured_arrow_eq X }, { ext, simp only [colimit.ΞΉ_pre], erw category.comp_id, congr } end } /-- Verify that `extend_along_yoneda` is indeed the left Kan extension along the yoneda embedding. -/ @[simps] def extend_along_yoneda_iso_Kan : extend_along_yoneda A β‰… (Lan yoneda : (_ β₯€ β„°) β₯€ _).obj A := nat_iso.of_components (extend_along_yoneda_iso_Kan_app A) begin intros X Y f, simp, rw extend_along_yoneda_map, erw colimit.pre_pre (Lan.diagram (yoneda : C β₯€ _ β₯€ Type u₁) A Y) (costructured_arrow.map f), erw colimit.pre_pre (Lan.diagram (yoneda : C β₯€ _ β₯€ Type u₁) A Y) (category_of_elements.costructured_arrow_yoneda_equivalence Y).functor, congr' 1, apply category_of_elements.costructured_arrow_yoneda_equivalence_naturality, end /-- extending `F β‹™ yoneda` along the yoneda embedding is isomorphic to `Lan F.op`. -/ @[simps] def extend_of_comp_yoneda_iso_Lan {D : Type u₁} [small_category D] (F : C β₯€ D) : extend_along_yoneda (F β‹™ yoneda) β‰… Lan F.op := adjunction.nat_iso_of_right_adjoint_nat_iso (yoneda_adjunction (F β‹™ yoneda)) (Lan.adjunction (Type u₁) F.op) (iso_whisker_right curried_yoneda_lemma' ((whiskering_left Cα΅’α΅– Dα΅’α΅– (Type u₁)).obj F.op : _)) end colimit_adj open colimit_adj /-- `F β‹™ yoneda` is naturally isomorphic to `yoneda β‹™ Lan F.op`. -/ @[simps] def comp_yoneda_iso_yoneda_comp_Lan {D : Type u₁} [small_category D] (F : C β₯€ D) : F β‹™ yoneda β‰… yoneda β‹™ Lan F.op := (is_extension_along_yoneda (F β‹™ yoneda)).symm β‰ͺ≫ iso_whisker_left yoneda (extend_of_comp_yoneda_iso_Lan F) /-- Since `extend_along_yoneda A` is adjoint to `restricted_yoneda A`, if we use `A = yoneda` then `restricted_yoneda A` is isomorphic to the identity, and so `extend_along_yoneda A` is as well. -/ def extend_along_yoneda_yoneda : extend_along_yoneda (yoneda : C β₯€ _) β‰… 𝟭 _ := adjunction.nat_iso_of_right_adjoint_nat_iso (yoneda_adjunction _) adjunction.id restricted_yoneda_yoneda /-- A functor to the presheaf category in which everything in the image is representable (witnessed by the fact that it factors through the yoneda embedding). `cocone_of_representable` gives a cocone for this functor which is a colimit and has point `P`. -/ -- Maybe this should be reducible or an abbreviation? def functor_to_representables (P : Cα΅’α΅– β₯€ Type u₁) : (P.elements)α΅’α΅– β₯€ Cα΅’α΅– β₯€ Type u₁ := (category_of_elements.Ο€ P).left_op β‹™ yoneda /-- This is a cocone with point `P` for the functor `functor_to_representables P`. It is shown in `colimit_of_representable P` that this cocone is a colimit: that is, we have exhibited an arbitrary presheaf `P` as a colimit of representables. The construction of [MM92], Chapter I, Section 5, Corollary 3. -/ def cocone_of_representable (P : Cα΅’α΅– β₯€ Type u₁) : cocone (functor_to_representables P) := cocone.extend (colimit.cocone _) (extend_along_yoneda_yoneda.hom.app P) @[simp] lemma cocone_of_representable_X (P : Cα΅’α΅– β₯€ Type u₁) : (cocone_of_representable P).X = P := rfl /-- An explicit formula for the legs of the cocone `cocone_of_representable`. -/ -- Marking this as a simp lemma seems to make things more awkward. lemma cocone_of_representable_ΞΉ_app (P : Cα΅’α΅– β₯€ Type u₁) (j : (P.elements)α΅’α΅–): (cocone_of_representable P).ΞΉ.app j = (yoneda_sections_small _ _).inv j.unop.2 := colimit.ΞΉ_desc _ _ /-- The legs of the cocone `cocone_of_representable` are natural in the choice of presheaf. -/ lemma cocone_of_representable_naturality {P₁ Pβ‚‚ : Cα΅’α΅– β₯€ Type u₁} (Ξ± : P₁ ⟢ Pβ‚‚) (j : (P₁.elements)α΅’α΅–) : (cocone_of_representable P₁).ΞΉ.app j ≫ Ξ± = (cocone_of_representable Pβ‚‚).ΞΉ.app ((category_of_elements.map Ξ±).op.obj j) := begin ext T f, simpa [cocone_of_representable_ΞΉ_app] using functor_to_types.naturality _ _ Ξ± f.op _, end /-- The cocone with point `P` given by `the_cocone` is a colimit: that is, we have exhibited an arbitrary presheaf `P` as a colimit of representables. The result of [MM92], Chapter I, Section 5, Corollary 3. -/ def colimit_of_representable (P : Cα΅’α΅– β₯€ Type u₁) : is_colimit (cocone_of_representable P) := begin apply is_colimit.of_point_iso (colimit.is_colimit (functor_to_representables P)), change is_iso (colimit.desc _ (cocone.extend _ _)), rw [colimit.desc_extend, colimit.desc_cocone], apply_instance, end /-- Given two functors L₁ and Lβ‚‚ which preserve colimits, if they agree when restricted to the representable presheaves then they agree everywhere. -/ def nat_iso_of_nat_iso_on_representables (L₁ Lβ‚‚ : (Cα΅’α΅– β₯€ Type u₁) β₯€ β„°) [preserves_colimits L₁] [preserves_colimits Lβ‚‚] (h : yoneda β‹™ L₁ β‰… yoneda β‹™ Lβ‚‚) : L₁ β‰… Lβ‚‚ := begin apply nat_iso.of_components _ _, { intro P, refine (is_colimit_of_preserves L₁ (colimit_of_representable P)).cocone_points_iso_of_nat_iso (is_colimit_of_preserves Lβ‚‚ (colimit_of_representable P)) _, apply functor.associator _ _ _ β‰ͺ≫ _, exact iso_whisker_left (category_of_elements.Ο€ P).left_op h }, { intros P₁ Pβ‚‚ f, apply (is_colimit_of_preserves L₁ (colimit_of_representable P₁)).hom_ext, intro j, dsimp only [id.def, is_colimit.cocone_points_iso_of_nat_iso_hom, iso_whisker_left_hom], have : (L₁.map_cocone (cocone_of_representable P₁)).ΞΉ.app j ≫ L₁.map f = (L₁.map_cocone (cocone_of_representable Pβ‚‚)).ΞΉ.app ((category_of_elements.map f).op.obj j), { dsimp, rw [← L₁.map_comp, cocone_of_representable_naturality], refl }, rw [reassoc_of this, is_colimit.ΞΉ_map_assoc, is_colimit.ΞΉ_map], dsimp, rw [← Lβ‚‚.map_comp, cocone_of_representable_naturality], refl } end variable [has_colimits β„°] /-- Show that `extend_along_yoneda` is the unique colimit-preserving functor which extends `A` to the presheaf category. The second part of [MM92], Chapter I, Section 5, Corollary 4. See Property 3 of https://ncatlab.org/nlab/show/Yoneda+extension#properties. -/ def unique_extension_along_yoneda (L : (Cα΅’α΅– β₯€ Type u₁) β₯€ β„°) (hL : yoneda β‹™ L β‰… A) [preserves_colimits L] : L β‰… extend_along_yoneda A := nat_iso_of_nat_iso_on_representables _ _ (hL β‰ͺ≫ (is_extension_along_yoneda _).symm) /-- If `L` preserves colimits and `β„°` has them, then it is a left adjoint. This is a special case of `is_left_adjoint_of_preserves_colimits` used to prove that. -/ def is_left_adjoint_of_preserves_colimits_aux (L : (Cα΅’α΅– β₯€ Type u₁) β₯€ β„°) [preserves_colimits L] : is_left_adjoint L := { right := restricted_yoneda (yoneda β‹™ L), adj := (yoneda_adjunction _).of_nat_iso_left ((unique_extension_along_yoneda _ L (iso.refl _)).symm) } /-- If `L` preserves colimits and `β„°` has them, then it is a left adjoint. Note this is a (partial) converse to `left_adjoint_preserves_colimits`. -/ def is_left_adjoint_of_preserves_colimits (L : (C β₯€ Type u₁) β₯€ β„°) [preserves_colimits L] : is_left_adjoint L := let e : (_ β₯€ Type u₁) β‰Œ (_ β₯€ Type u₁) := (op_op_equivalence C).congr_left, t := is_left_adjoint_of_preserves_colimits_aux (e.functor β‹™ L : _) in by exactI adjunction.left_adjoint_of_nat_iso (e.inv_fun_id_assoc _) end category_theory