Datasets:
AI4M
/

text
stringlengths
0
3.34M
First, load an instance of the CADRE model and render its depgraph: ``` from IPython.display import SVG, Image, HTML from CADRE import CADRE import networkx as nx assembly = CADRE(150, 100) graph = assembly._depgraph.component_graph() defaults = ["derivative_exec_count", "directory", "itername", "exec_count", "force_execute", "driver"] remove = [] for node in graph.nodes_iter(): for d in defaults: if d in node: remove.append(node) break for node in remove: graph.remove_node(node) ag = nx.to_agraph(graph) ag.layout('dot') ag.draw('design.svg') HTML('') ``` Load an optimized CADRE state, and define a few functions for post processing the results ``` import pickle import pygmaps data = pickle.load(open("src/CADRE/test/data1346.pkl")) savedir = "docs/maps" def val2hex(v, scale=1.0): if not v: return "#000044" j = pylab.get_cmap("jet") v = v / scale nums = [int(255 * i) for i in j(v)][:3] return ''.join(["00" if i == 0 else hex(i)[2:] for i in nums]) def calc_lat_lon(r_e2b_I, O_IE): r2d = 180 / np.pi rgs = 6378.137 lats, lons = [], [] n = r_e2b_I.shape[1] for i in xrange(n): r_e2g_I = r_e2b_I[:3, i] r_e2g_I = r_e2g_I / np.linalg.norm(r_e2g_I) * rgs r_e2g_E = np.dot(O_IE[:, :, i].T, r_e2g_I) lat = np.arcsin(r_e2g_E[2] / rgs) * r2d lon = np.arctan2(r_e2g_E[1], r_e2g_E[0]) * r2d lats.append(lat), lons.append(lon) return lats, lons ``` Now, produce figures and maps for each design point ``` mxdata = max([max(data["%s:Dr" % str(i)]) for i in xrange(6)]) gmap_all = pygmaps.gmap(41, -88, 2) for i in xrange(6): si = str(i) dr = data[si + ":Dr"] p = data[si + ":P_comm"] g = data[si + ":gamma"] s = data[si + ":SOC"] O_IE = data["%s:O_IE" % si] gmap = pygmaps.gmap(41, -88, 2) r_e2b_I = data["%s:r_e2b_I" % si] lats, lons = calc_lat_lon(r_e2b_I, O_IE) path = zip(lats, lons) gmap.add_weighted_path(path, dr, scale=mxdata) gmap_all.add_weighted_path(path, dr, scale=mxdata) gmap.draw(savedir + "/" + si + '_data.html') figure() suptitle("CADRE Design Point " + si) subplot(411) title("Dr") plot(dr) gca().get_xaxis().set_visible(False) subplot(412) title("P_comm") plot(p) gca().get_xaxis().set_visible(False) subplot(413) title("gamma") plot(g) gca().get_xaxis().set_visible(False) subplot(414) title("SOC") plot(s[0]) gmap_all.draw(savedir + '/all_data.html') ``` ``` from IPython.display import display from sympy.interactive import printing printing.init_printing(use_latex=True) import sympy c,gr,l,f,k,t,s,p,gt,S,los = sympy.symbols("c G_r L_{l} f k T_s S_{NR} P_{comm} G_t S LOS_c") B_r = (c**2 * gr * l) / (16*sympy.pi**2*f**2 *k *t*(s) ) * (p * gt)/(S**2) * los ``` Testing some symbolic stuff using the comm bitrate component: $$B_r = \frac{ c^2 G_r L_l}{16 \pi^2 f^2 k T_s \left(SNR\right)} \frac{P_{comm}G_t}{S^2} LOS_c$$ $$\frac{\partial B_r}{\partial S} = $$ ``` sympy.diff(B_r, S) ``` $$\frac{\partial B_r}{\partial P_{comm}} = $$ ``` sympy.diff(B_r, p) ``` ``` HTML('') ``` ``` ```
function [ tokens ] = strtokenize( str, delim ) %STRTOKENIZE Summary of this function goes here % Detailed explanation goes here tokens = cell(0); remain = str; while true [token remain] = strtok(remain, delim); if (isempty(token)) break; end; tokens(end+1) = {token}; end; end
/* Copyright (c) 2002-2011 Tampere University. This file is part of TTA-Based Codesign Environment (TCE). Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @file ControlFlowGraph.hh * * Declaration of prototype control flow graph of TTA program * representation. * * @author Andrea Cilio 2005 (cilio-no.spam-cs.tut.fi) * @author Vladimir Guzma 2006 (vladimir.guzma-no.spam-tut.fi) * @note rating: red */ #ifndef TTA_CONTROL_FLOW_GRAPH_HH #define TTA_CONTROL_FLOW_GRAPH_HH #include <map> #include <vector> #include "CompilerWarnings.hh" IGNORE_CLANG_WARNING("-Wunused-local-typedef") IGNORE_COMPILER_WARNING("-Wunused-parameter") #include <boost/graph/reverse_graph.hpp> #include <boost/graph/depth_first_search.hpp> POP_COMPILER_DIAGS POP_CLANG_DIAGS namespace llvm { class MCSymbol; class MachineInstr; } #include "Exception.hh" #include "BoostGraph.hh" #include "BasicBlockNode.hh" #include "ControlFlowEdge.hh" #include "Address.hh" #include "NullAddress.hh" #include "hash_map.hh" #include "ProgramOperation.hh" namespace TTAProgram { class Program; class Procedure; class Instruction; class Move; class InstructionReferenceManager; class POMRelocBookkeeper; class Address; class NullAddress; class Immediate; class Terminal; } namespace TTAMachine { class Machine; } namespace llvm { class MachineFunction; class MachineBasicBlock; class MCInstrDesc; class MCInstrInfo; } using boost::reverse_graph; class InterPassData; class DataDependenceGraph; class CFGStatistics; /** * Control Flow Graph. * * The basic blocks are initially in the original program order when traversed * with nodeCount()/node(). */ class ControlFlowGraph : public BoostGraph<BasicBlockNode, ControlFlowEdge> { public: ControlFlowGraph( const TCEString name, TTAProgram::Program* program = NULL); ControlFlowGraph( const TTAProgram::Procedure& procedure, InterPassData& passData); ControlFlowGraph(const TTAProgram::Procedure& procedure); virtual ~ControlFlowGraph(); TCEString procedureName() const; int alignment() const; TTAProgram::Program* program() const; BasicBlockNode& entryNode() const; BasicBlockNode& exitNode() const; BasicBlockNode& firstNormalNode() const; TCEString printStatistics(); const CFGStatistics& statistics(); friend class ControlDependenceGraph; friend class ProgramDependenceGraph; void copyToProcedure( TTAProgram::Procedure& proc, TTAProgram::InstructionReferenceManager* irm = NULL); void copyToLLVMMachineFunction( llvm::MachineFunction& mf, TTAProgram::InstructionReferenceManager* irm = NULL); void updateReferencesFromProcToCfg(); void convertBBRefsToInstRefs(); ControlFlowEdge* incomingFTEdge(const BasicBlockNode& bbn) const; EdgeSet incomingJumpEdges(const BasicBlockNode& bbn) const; bool hasIncomingExternalJumps(const BasicBlockNode& bbn) const; void deleteNodeAndRefs(BasicBlockNode& node); TTAProgram::InstructionReferenceManager& instructionReferenceManager(); void setInstructionReferenceManager( TTAProgram::InstructionReferenceManager& irm) { irm_ = &irm; } BasicBlockNode* jumpSuccessor(BasicBlockNode& bbn); BasicBlockNode* fallThruSuccessor(const BasicBlockNode& bbn) const; BasicBlockNode* fallThroughPredecessor(const BasicBlockNode& bbn) const; void addExitFromSinkNodes(BasicBlockNode* exitNode); void detectBackEdges(); void reverseGuardOnOutEdges(const BasicBlockNode& bbn); void optimizeBBOrdering( bool removeDeadCode, TTAProgram::InstructionReferenceManager& irm, DataDependenceGraph* ddg); llvm::MachineBasicBlock& getMBB( llvm::MachineFunction& mf, const TTAProgram::BasicBlock& bb) const; void splitBasicBlocksWithCallsAndRefs(); bool isSingleBBLoop(const BasicBlockNode& node) const; bool hasMultipleUnconditionalSuccessors(const BasicBlockNode& node) const; void addExit(NodeSet& retSourceNodes); void sanitize(); TTAProgram::Immediate* findLimmWrite( TTAProgram::Move& move, BasicBlockNode& bb, int moveIndex); TTAProgram::Terminal* findJumpAddress( BasicBlockNode& src, ControlFlowEdge& e); BasicBlockNode* splitBB(BasicBlockNode& n, int remainingSize); bool hasFallThruPredecessor(const BasicBlockNode& bbn); int findRelJumpDistance( const BasicBlockNode &src, const TTAProgram::Terminal& jumpAddr, const TTAMachine::Machine& mach) const; bool allScheduledInBetween( const BasicBlockNode& src, const BasicBlockNode& dst) const; private: // For temporary storage typedef hash_map<InstructionAddress, const TTAProgram::Instruction*> InstructionAddressMap; typedef std::vector<InstructionAddress> InstructionAddressVector; // Type of reversed underlying graph, needed for control dependence // analysis typedef reverse_graph<ControlFlowGraph::Graph> ReversedGraph; typedef BoostGraph<BasicBlockNode, ControlFlowEdge>::NodeDescriptor NodeDescriptor; typedef std::pair<InstructionAddress, ControlFlowEdge::CFGEdgePredicate> ReturnSource; typedef std::set<ReturnSource> ReturnSourceSet; /// DFS visitor which when finding back edge marks such edge as /// back edge class DFSBackEdgeVisitor : public boost::default_dfs_visitor { public: DFSBackEdgeVisitor(){} template < typename EdgeDescriptor, typename Graph > void back_edge(EdgeDescriptor e, const Graph & g)const { g[e]->setBackEdge(); } }; void buildFrom(const TTAProgram::Procedure& procedure); void createBBEdges( const TTAProgram::Procedure& procedure, InstructionAddressMap& leaders, InstructionAddressMap& dataCodeRellocations); ReversedGraph& reversedGraph() const; bool hasInstructionAnotherJump( const TTAProgram::Instruction& ins, int moveIndex); void computeLeadersFromRefManager( InstructionAddressMap& leaders, const TTAProgram::Procedure& procedure); bool computeLeadersFromJumpSuccessors( InstructionAddressMap& leaders, const TTAProgram::Procedure& procedure); void computeLeadersFromRelocations( InstructionAddressMap& leaderSet, InstructionAddressMap& dataCodeRellocations, const TTAProgram::Procedure& procedure); void createAllBlocks( InstructionAddressMap& leaders, const TTAProgram::Procedure& procedure); BasicBlockNode& createBlock( TTAProgram::Instruction& leader, const TTAProgram::Instruction& endBlock); ControlFlowEdge& createControlFlowEdge( const TTAProgram::Instruction& iTail, const TTAProgram::Instruction& iHead, ControlFlowEdge::CFGEdgePredicate edgePredicate = ControlFlowEdge::CFLOW_EDGE_NORMAL, ControlFlowEdge::CFGEdgeType edgeType = ControlFlowEdge::CFLOW_EDGE_JUMP); void directJump( InstructionAddressMap& leaders, const InstructionAddress& leaderAddr, int insIndex, int moveIndex, const TTAProgram::Instruction& instructionTarget, const TTAProgram::Procedure& procedure); void indirectJump( InstructionAddressMap& leaders, const InstructionAddress& leaderAddr, InstructionAddressMap& dataCodeRellocations, int insIndex, int moveIndex, const TTAProgram::Procedure& procedure); void createJumps( InstructionAddressMap& leaders, const InstructionAddress& leaderAddr, InstructionAddressMap& dataCodeRellocations, const TTAProgram::Procedure& procedure, int insIndex, int moveIndex); unsigned int findNextIndex( const TTAProgram::Procedure& proc, int jumpInsIndex, int jumpMoveIndex); void addExit(); void addEntryExitEdge(); void removeEntryExitEdge(); NodeSet findReachableNodes(); NodeSet findUnreachableNodes(const NodeSet& reachableNodes); BasicBlockNode* splitBasicBlockAtIndex(BasicBlockNode& bbn, int index); void removeUnreachableNodes( const NodeSet& unreachableNodes, DataDependenceGraph* ddg); void mergeNodes( BasicBlockNode& node1, BasicBlockNode& node2, DataDependenceGraph* ddg, const ControlFlowEdge& connectingEdge); bool jumpToBBN( const TTAProgram::Terminal& jumpAddr, const BasicBlockNode& bbn) const; enum RemovedJumpData { JUMP_NOT_REMOVED = 0, /// nothing removed JUMP_REMOVED, /// jump removed, other things remain in BB LAST_ELEMENT_REMOVED /// last jump removed, no immeds in BB. }; RemovedJumpData removeJumpToTarget( TTAProgram::CodeSnippet& cs, const TTAProgram::Instruction& target, int idx, DataDependenceGraph* ddg = NULL); const llvm::MCInstrDesc& findLLVMTargetInstrDesc(TCEString name, const llvm::MCInstrInfo& tii) const; void buildMBBFromBB( llvm::MachineBasicBlock& mbb, const TTAProgram::BasicBlock& bb) const; // Data saved from original procedure object TCEString procedureName_; TTAProgram::Program* program_; const TTAProgram::Procedure* procedure_; TTAProgram::Address startAddress_; TTAProgram::Address endAddress_; int alignment_; // Collection of all basic blocks of the control flow graph indexed by // the address of their start instruction (leader). hash_map<InstructionAddress, BasicBlockNode*> blocks_; // Mapping between original instructions and those in the cfg. typedef hash_map<TTAProgram::Instruction*,TTAProgram::Instruction*> InsMap; InsMap originalToCfgInstructions_; InsMap cfgToOriginalInstructions_; // all basic blocks which contain a return instruction. ReturnSourceSet returnSources_; // Optional interpass data to aid in the construction of the CFG. InterPassData* passData_; // IRM needs to be set explicitly if CFG is built and used without a // Program object. TTAProgram::InstructionReferenceManager* irm_; // Maps BasicBlockNode onto it's MachineBasicBlock equivalent mutable std::map<const TTAProgram::BasicBlock*, llvm::MachineBasicBlock*> bbMap_; /// For LLVM conversion: the dummy label instructions for SPU should be /// created for with the given MCSymbol as argument after building. mutable std::set<std::pair<ProgramOperationPtr, llvm::MCSymbol*> > tpos_; /// For LLVM conversion: mapping of created MachineInstructions to TCE /// ProgramOperations. mutable std::map<ProgramOperation*, llvm::MachineInstr*> programOperationToMIMap_; }; #endif
module Ex5 import Data.Strings import Data.Vect import System import System.File %default total printLonger : HasIO io => io () printLonger = do putStr "Enter the first string: " first <- getLine putStr "Enter the second string: " second <- getLine let firstlen = length first -- no `in` here let secondlen = length second putStrLn $ show (max firstlen secondlen) printLongerBind : HasIO io => io () printLongerBind = putStr "Enter the first string: " >>= \_ => getLine >>= \first => putStr "Enter the second string: " >>= \_ => getLine >>= \second => let firstlen = length first secondlen = length second in -- `in` is used here - why the inconsistency? putStrLn (show (max firstlen secondlen)) readNumber : HasIO io => io (Maybe Nat) readNumber = do ns <- getLine if all isDigit (unpack ns) then pure $ Just (stringToNatOrZ ns) else pure Nothing -- guess the number game partial guess : HasIO io => (n : Nat) -> (guesses : Nat) -> io () guess secret count = do putStr "Enter your guess: " Just g <- readNumber | Nothing => do putStrLn "Invalid input: not a number" pure () case compare g secret of LT => do putStrLn "Too low!" guess secret (count + 1) GT => do putStrLn "Too high!" guess secret (count + 1) EQ => do putStrLn $ "You win! You took " ++ show (count + 1) ++ " guesses!" pure () partial guessingGame : HasIO io => io () guessingGame = do currTime <- time let secret = currTime `mod` 101 + 1 -- secret in [1, 100] guess (integerToNat secret) 0 partial myRepl : HasIO io => String -> (String -> String) -> io () myRepl prompt func = do putStr prompt inp <- getLine putStr (func inp) myRepl prompt func partial reverser : HasIO io => io () reverser = myRepl "Enter a string: " (\s => reverse s ++ "\n") partial myReplWith : HasIO io => a -> String -> (a -> String -> Maybe (String, a)) -> io () myReplWith state prompt func = do putStr prompt inp <- getLine case func state inp of Nothing => pure () Just (out, newState) => do putStr out myReplWith newState prompt func partial adder : HasIO io => io () adder = myReplWith 0 "Enter a number: " (\acc, s => case all isDigit (unpack s) of False => Nothing True => let n = stringToNatOrZ s in Just $ ("Current value: " ++ show (acc + n) ++ "\n", acc + n)) partial readToBlank : HasIO io => io (List String) readToBlank = do line <- getLine if line == "" then pure [] else do lines <- readToBlank pure (line :: lines) partial readAndSave : HasIO io => io () readAndSave = do lines <- readToBlank filename <- getLine Right () <- writeFile filename (unwords (map (\line => line ++ "\n") lines)) | Left err => putStrLn $ "Error while writing to file: " ++ show err putStrLn "Wrote to file successfully" partial printFile : HasIO io => io () printFile = do filename <- getLine Right contents <- readFile filename | Left err => putStrLn $ "Error while reading file: " ++ show err putStrLn contents partial readVectFile : (filename : String) -> IO (n ** Vect n String) readVectFile filename = do Right handle <- openFile filename Read | Left err => do putStrLn $ "error while reading file: " ++ show err pure (_ ** []) readFileHelper handle where partial readFileHelper : File -> IO (n ** Vect n String) readFileHelper handle = do end <- fEOF handle if end then pure (_ ** []) else do Right line <- fGetLine handle | Left err => do putStrLn $ "error while reading line from file: " ++ show err pure (_ ** []) do (_ ** lines) <- readFileHelper handle pure (_ ** (line :: lines))
(**************************************************************) (* Copyright Dominique Larchey-Wendling [*] *) (* *) (* [*] Affiliation LORIA -- CNRS *) (**************************************************************) (* This file is distributed under the terms of the *) (* CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT *) (**************************************************************) Require Import List Permutation Arith Omega. Require Import utils. Set Implicit Arguments. (** * Intuionistic Linear Logic *) Definition ill_vars := nat. Inductive ill_conn := ll_with | ll_limp | ll_rimp | ll_times | ll_plus. Inductive ill_cst := ll_one | ll_bot | ll_top. Inductive ill_form : Set := | ill_var : ill_vars -> ill_form | ill_zero : ill_cst -> ill_form | ill_bang : ill_form -> ill_form | ill_bin : ill_conn -> ill_form -> ill_form -> ill_form. Fact ill_form_eq_dec (f g : ill_form) : { f = g } + { f <> g }. Proof. decide equality. + apply eq_nat_dec. + decide equality. + decide equality. Qed. (* Symbols for cut&paste ⟙ ⟘ 𝝐 ﹠ ⊗ ⊕ ⊸ ❗ ‼ ∅ ⊢ *) Notation "⟙" := (ill_zero ll_top). Notation "⟘" := (ill_zero ll_bot). Notation 𝝐 := (ill_zero ll_one). Infix "&" := (ill_bin ll_with) (at level 50, only parsing). Infix "﹠" := (ill_bin ll_with) (at level 50). Infix "⊗" := (ill_bin ll_times) (at level 50). Infix "⊕" := (ill_bin ll_plus) (at level 50). Infix "-o" := (ill_bin ll_limp) (at level 51, right associativity). Infix "o-" := (ill_bin ll_rimp) (at level 52, left associativity). Notation "'!' x" := (ill_bang x) (at level 52). Definition ill_lbang := map (fun x => !x). Notation "'!l' x" := (ill_lbang x) (at level 60, only parsing). Notation "‼ x" := (ill_lbang x) (at level 52). Notation "£" := ill_var. Notation "∅" := nil (only parsing). Infix "~!" := (perm_bang_t ill_bang) (at level 70). Infix "~p" := (@perm_t _) (at level 70). Hint Resolve perm_bang_t_refl perm_bang_t_cons. Definition perm_bool b := match b with | true => @perm_t ill_form | _ => perm_bang_t ill_bang end. Notation " x '~[' b ']' y " := (perm_bool b x y) (at level 70, format "x ~[ b ] y"). Fact illnc_perm_t_map_inv_t l m : ‼ l ~! m -> { l' | m = ‼ l' }. Proof. apply perm_bang_t_map_inv_t. inversion 1; trivial. Qed. Hint Resolve perm_t_refl. Fact ill_perm_t_refl b l : l ~[b] l. Proof. destruct b; simpl; auto. Qed. Hint Resolve ill_perm_t_refl. Fact ill_perm_t_app b l1 l2 m1 m2 : l1 ~[b] m1 -> l2 ~[b] m2 -> l1++l2 ~[b] m1++m2. Proof. destruct b; simpl. + apply perm_t_app. + apply perm_bang_t_app. Qed. Fact ill_perm_t_trans b l m p : l ~[b] m -> m ~[b] p -> l ~[b] p. Proof. destruct b; simpl. + apply perm_t_trans. + apply perm_bang_t_trans. Qed. Fact ill_perm_t_swap b x y l : !x::!y::l ~[b] !y::!x::l. Proof. destruct b; simpl; constructor 3. Qed. Fact ill_perm_t_map_inv_t b l m : ‼ l ~[b] m -> { l' | m = ‼ l' }. Proof. destruct b; simpl. + intros H. destruct perm_t_map_inv_t with (1 := H) as (l' & H1 & _). exists l'; auto. + apply illnc_perm_t_map_inv_t. Qed.
"""Unit tests for gridrad_utils.py.""" import unittest import numpy from gewittergefahr.gg_utils import gridrad_utils from gewittergefahr.gg_utils import radar_utils TOLERANCE = 1e-6 # The following constants are used to test fields_and_refl_heights_to_pairs. FIELD_NAMES = [ radar_utils.REFL_NAME, radar_utils.DIFFERENTIAL_REFL_NAME, radar_utils.SPEC_DIFF_PHASE_NAME, radar_utils.CORRELATION_COEFF_NAME, radar_utils.SPECTRUM_WIDTH_NAME, radar_utils.VORTICITY_NAME, radar_utils.DIVERGENCE_NAME] HEIGHTS_M_ASL = numpy.array([500, 2500, 5000, 10000]) FIELD_NAME_BY_PAIR = ( [radar_utils.REFL_NAME] * len(HEIGHTS_M_ASL) + [radar_utils.DIFFERENTIAL_REFL_NAME] * len(HEIGHTS_M_ASL) + [radar_utils.SPEC_DIFF_PHASE_NAME] * len(HEIGHTS_M_ASL) + [radar_utils.CORRELATION_COEFF_NAME] * len(HEIGHTS_M_ASL) + [radar_utils.SPECTRUM_WIDTH_NAME] * len(HEIGHTS_M_ASL) + [radar_utils.VORTICITY_NAME] * len(HEIGHTS_M_ASL) + [radar_utils.DIVERGENCE_NAME] * len(HEIGHTS_M_ASL)) HEIGHT_BY_PAIR_M_ASL = numpy.array([500, 2500, 5000, 10000, 500, 2500, 5000, 10000, 500, 2500, 5000, 10000, 500, 2500, 5000, 10000, 500, 2500, 5000, 10000, 500, 2500, 5000, 10000, 500, 2500, 5000, 10000]) # These constants are used to test interp_reflectivity_to_heights. THIS_REFL_MATRIX_1KM_DBZ = numpy.array( [[1., numpy.nan], [3., numpy.nan], [5., numpy.nan]]) THIS_REFL_MATRIX_2KM_DBZ = numpy.array( [[7., 8.], [9., numpy.nan], [11., numpy.nan]]) THIS_REFL_MATRIX_3KM_DBZ = numpy.array( [[13., 14.], [15., 16.], [17., numpy.nan]]) REFLECTIVITY_MATRIX_DBZ = numpy.stack( (THIS_REFL_MATRIX_1KM_DBZ, THIS_REFL_MATRIX_2KM_DBZ, THIS_REFL_MATRIX_3KM_DBZ), axis=0) GRID_POINT_HEIGHTS_M_ASL = numpy.array([1000., 2000., 3000.]) TARGET_HEIGHT_MATRIX_M_ASL = numpy.array( [[500., 1000.], [1500., 2500.], [3000., 3500.]]) INTERP_REFL_MATRIX_DBZ = numpy.array( [[-2., 2.], [6., numpy.nan], [17., numpy.nan]]) # These constants are used to test get_column_max_reflectivity. COLUMN_MAX_REFL_MATRIX_DBZ = numpy.array( [[13., 14.], [15., 16.], [17., numpy.nan]]) # These constants are used to test get_echo_top. THIS_REFL_MATRIX_1KM_DBZ = numpy.array( [[0., 10.], [20., 0.,], [0., numpy.nan]]) THIS_REFL_MATRIX_2KM_DBZ = numpy.array( [[20., 30.], [40., 10.,], [50., 50.]]) THIS_REFL_MATRIX_3KM_DBZ = numpy.array( [[40., 50.], [60., 20.,], [20., 20.]]) REFL_MATRIX_FOR_ECHO_TOPS_DBZ = numpy.stack( (THIS_REFL_MATRIX_1KM_DBZ, THIS_REFL_MATRIX_2KM_DBZ, THIS_REFL_MATRIX_3KM_DBZ), axis=0) CRIT_REFL_FOR_ECHO_TOPS_DBZ = 40. ECHO_TOP_MATRIX_M_ASL = numpy.array( [[3000., 3200.], [3333.333333, numpy.nan], [2333.333333, 2333.333333]]) class GridradUtilsTests(unittest.TestCase): """Each method is a unit test for gridrad_utils.py.""" def test_fields_and_refl_heights_to_pairs(self): """Ensures correct output from fields_and_refl_heights_to_pairs.""" this_field_name_by_pair, this_height_by_pair_m_asl = ( gridrad_utils.fields_and_refl_heights_to_pairs( field_names=FIELD_NAMES, heights_m_asl=HEIGHTS_M_ASL)) self.assertTrue(this_field_name_by_pair == FIELD_NAME_BY_PAIR) self.assertTrue(numpy.array_equal( this_height_by_pair_m_asl, HEIGHT_BY_PAIR_M_ASL)) def test_interp_reflectivity_to_heights(self): """Ensures correct output from interp_reflectivity_to_heights.""" this_interp_matrix_dbz = gridrad_utils.interp_reflectivity_to_heights( reflectivity_matrix_dbz=REFLECTIVITY_MATRIX_DBZ, grid_point_heights_m_asl=GRID_POINT_HEIGHTS_M_ASL, target_height_matrix_m_asl=TARGET_HEIGHT_MATRIX_M_ASL) self.assertTrue(numpy.allclose( this_interp_matrix_dbz, INTERP_REFL_MATRIX_DBZ, atol=TOLERANCE, equal_nan=True)) def test_get_column_max_reflectivity(self): """Ensures correct output from get_column_max_reflectivity.""" this_column_max_matrix_dbz = gridrad_utils.get_column_max_reflectivity( REFLECTIVITY_MATRIX_DBZ) self.assertTrue(numpy.allclose( this_column_max_matrix_dbz, COLUMN_MAX_REFL_MATRIX_DBZ, atol=TOLERANCE, equal_nan=True)) def test_get_echo_tops(self): """Ensures correct output from get_echo_tops.""" this_echo_top_matrix_m_asl = gridrad_utils.get_echo_tops( reflectivity_matrix_dbz=REFL_MATRIX_FOR_ECHO_TOPS_DBZ, grid_point_heights_m_asl=GRID_POINT_HEIGHTS_M_ASL, critical_reflectivity_dbz=CRIT_REFL_FOR_ECHO_TOPS_DBZ) self.assertTrue(numpy.allclose( this_echo_top_matrix_m_asl, ECHO_TOP_MATRIX_M_ASL, atol=TOLERANCE, equal_nan=True)) if __name__ == '__main__': unittest.main()
(* Title: Lazy_LList.thy Author: Andreas Lochbihler *) section {* Code generator setup to implement lazy lists lazily *} theory Lazy_LList imports Coinductive_List begin subsection {* Lazy lists *} code_identifier code_module Lazy_LList \<rightharpoonup> (SML) Coinductive_List and (OCaml) Coinductive_List and (Haskell) Coinductive_List and (Scala) Coinductive_List definition Lazy_llist :: "(unit \<Rightarrow> ('a \<times> 'a llist) option) \<Rightarrow> 'a llist" where [simp]: "Lazy_llist xs = (case xs () of None \<Rightarrow> LNil | Some (x, ys) \<Rightarrow> LCons x ys)" definition force :: "'a llist \<Rightarrow> ('a \<times> 'a llist) option" where [simp, code del]: "force xs = (case xs of LNil \<Rightarrow> None | LCons x ys \<Rightarrow> Some (x, ys))" code_datatype Lazy_llist declare -- {* Restore consistency in code equations between @{const partial_term_of} and @{const narrowing} for @{typ "'a llist"} *} [[code drop: "partial_term_of :: _ llist itself => _"]] lemma partial_term_of_llist_code [code]: fixes tytok :: "'a :: partial_term_of llist itself" shows "partial_term_of tytok (Quickcheck_Narrowing.Narrowing_variable p tt) \<equiv> Code_Evaluation.Free (STR ''_'') (Typerep.typerep TYPE('a llist))" "partial_term_of tytok (Quickcheck_Narrowing.Narrowing_constructor 0 []) \<equiv> Code_Evaluation.Const (STR ''Coinductive_List.llist.LNil'') (Typerep.typerep TYPE('a llist))" "partial_term_of tytok (Quickcheck_Narrowing.Narrowing_constructor 1 [head, tail]) \<equiv> Code_Evaluation.App (Code_Evaluation.App (Code_Evaluation.Const (STR ''Coinductive_List.llist.LCons'') (Typerep.typerep TYPE('a \<Rightarrow> 'a llist \<Rightarrow> 'a llist))) (partial_term_of TYPE('a) head)) (partial_term_of TYPE('a llist) tail)" by-(rule partial_term_of_anything)+ declare option.splits [split] lemma Lazy_llist_inject [simp]: "Lazy_llist xs = Lazy_llist ys \<longleftrightarrow> xs = ys" by(auto simp add: fun_eq_iff) lemma Lazy_llist_inverse [code, simp]: "force (Lazy_llist xs) = xs ()" by(auto) lemma force_inverse [simp]: "Lazy_llist (\<lambda>_. force xs) = xs" by(auto split: llist.split) lemma LNil_Lazy_llist [code]: "LNil = Lazy_llist (\<lambda>_. None)" by(simp) lemma LCons_Lazy_llist [code, code_unfold]: "LCons x xs = Lazy_llist (\<lambda>_. Some (x, xs))" by simp lemma lnull_lazy [code]: "lnull = Option.is_none \<circ> force" unfolding lnull_def by (rule ext) (simp add: Option.is_none_def split: llist.split) declare [[code drop: "equal_class.equal :: 'a :: equal llist \<Rightarrow> _"]] lemma equal_llist_Lazy_llist [code]: "equal_class.equal (Lazy_llist xs) (Lazy_llist ys) \<longleftrightarrow> (case xs () of None \<Rightarrow> (case ys () of None \<Rightarrow> True | _ \<Rightarrow> False) | Some (x, xs') \<Rightarrow> (case ys () of None \<Rightarrow> False | Some (y, ys') \<Rightarrow> if x = y then equal_class.equal xs' ys' else False))" by(auto simp add: equal_llist_def) declare [[code drop: corec_llist]] lemma corec_llist_Lazy_llist [code]: "corec_llist IS_LNIL LHD endORmore LTL_end LTL_more b = Lazy_llist (\<lambda>_. if IS_LNIL b then None else Some (LHD b, if endORmore b then LTL_end b else corec_llist IS_LNIL LHD endORmore LTL_end LTL_more (LTL_more b)))" by(subst llist.corec_code) simp declare [[code drop: unfold_llist]] lemma unfold_llist_Lazy_llist [code]: "unfold_llist IS_LNIL LHD LTL b = Lazy_llist (\<lambda>_. if IS_LNIL b then None else Some (LHD b, unfold_llist IS_LNIL LHD LTL (LTL b)))" by(subst unfold_llist.code) simp declare [[code drop: case_llist]] lemma case_llist_Lazy_llist [code]: "case_llist n c (Lazy_llist xs) = (case xs () of None \<Rightarrow> n | Some (x, ys) \<Rightarrow> c x ys)" by simp declare [[code drop: lappend]] lemma lappend_Lazy_llist [code]: "lappend (Lazy_llist xs) ys = Lazy_llist (\<lambda>_. case xs () of None \<Rightarrow> force ys | Some (x, xs') \<Rightarrow> Some (x, lappend xs' ys))" by(auto split: llist.splits) declare [[code drop: lmap]] lemma lmap_Lazy_llist [code]: "lmap f (Lazy_llist xs) = Lazy_llist (\<lambda>_. map_option (map_prod f (lmap f)) (xs ()))" by simp declare [[code drop: lfinite]] lemma lfinite_Lazy_llist [code]: "lfinite (Lazy_llist xs) = (case xs () of None \<Rightarrow> True | Some (x, ys) \<Rightarrow> lfinite ys)" by simp declare [[code drop: list_of_aux]] lemma list_of_aux_Lazy_llist [code]: "list_of_aux xs (Lazy_llist ys) = (case ys () of None \<Rightarrow> rev xs | Some (y, ys) \<Rightarrow> list_of_aux (y # xs) ys)" by(simp add: list_of_aux_code) declare [[code drop: gen_llength]] lemma gen_llength_Lazy_llist [code]: "gen_llength n (Lazy_llist xs) = (case xs () of None \<Rightarrow> enat n | Some (_, ys) \<Rightarrow> gen_llength (n + 1) ys)" by(simp add: gen_llength_code) declare [[code drop: ltake]] lemma ltake_Lazy_llist [code]: "ltake n (Lazy_llist xs) = Lazy_llist (\<lambda>_. if n = 0 then None else case xs () of None \<Rightarrow> None | Some (x, ys) \<Rightarrow> Some (x, ltake (n - 1) ys))" by(cases n rule: enat_coexhaust) auto declare [[code drop: ldropn]] lemma ldropn_Lazy_llist [code]: "ldropn n (Lazy_llist xs) = Lazy_llist (\<lambda>_. if n = 0 then xs () else case xs () of None \<Rightarrow> None | Some (x, ys) \<Rightarrow> force (ldropn (n - 1) ys))" by(cases n)(auto simp add: eSuc_enat[symmetric] split: llist.split) declare [[code drop: ltakeWhile]] lemma ltakeWhile_Lazy_llist [code]: "ltakeWhile P (Lazy_llist xs) = Lazy_llist (\<lambda>_. case xs () of None \<Rightarrow> None | Some (x, ys) \<Rightarrow> if P x then Some (x, ltakeWhile P ys) else None)" by auto declare [[code drop: ldropWhile]] lemma ldropWhile_Lazy_llist [code]: "ldropWhile P (Lazy_llist xs) = Lazy_llist (\<lambda>_. case xs () of None \<Rightarrow> None | Some (x, ys) \<Rightarrow> if P x then force (ldropWhile P ys) else Some (x, ys))" by(auto split: llist.split) declare [[code drop: lzip]] lemma lzip_Lazy_llist [code]: "lzip (Lazy_llist xs) (Lazy_llist ys) = Lazy_llist (\<lambda>_. Option.bind (xs ()) (\<lambda>(x, xs'). map_option (\<lambda>(y, ys'). ((x, y), lzip xs' ys')) (ys ())))" by auto declare [[code drop: gen_lset]] lemma lset_Lazy_llist [code]: "gen_lset A (Lazy_llist xs) = (case xs () of None \<Rightarrow> A | Some (y, ys) \<Rightarrow> gen_lset (insert y A) ys)" by(auto simp add: gen_lset_code) declare [[code drop: lmember]] lemma lmember_Lazy_llist [code]: "lmember x (Lazy_llist xs) = (case xs () of None \<Rightarrow> False | Some (y, ys) \<Rightarrow> x = y \<or> lmember x ys)" by(simp add: lmember_def) declare [[code drop: llist_all2]] lemma llist_all2_Lazy_llist [code]: "llist_all2 P (Lazy_llist xs) (Lazy_llist ys) = (case xs () of None \<Rightarrow> ys () = None | Some (x, xs') \<Rightarrow> (case ys () of None \<Rightarrow> False | Some (y, ys') \<Rightarrow> P x y \<and> llist_all2 P xs' ys'))" by auto declare [[code drop: lhd]] lemma lhd_Lazy_llist [code]: "lhd (Lazy_llist xs) = (case xs () of None \<Rightarrow> undefined | Some (x, xs') \<Rightarrow> x)" by(simp add: lhd_def) declare [[code drop: ltl]] lemma ltl_Lazy_llist [code]: "ltl (Lazy_llist xs) = Lazy_llist (\<lambda>_. case xs () of None \<Rightarrow> None | Some (x, ys) \<Rightarrow> force ys)" by(auto split: llist.split) declare [[code drop: llast]] lemma llast_Lazy_llist [code]: "llast (Lazy_llist xs) = (case xs () of None \<Rightarrow> undefined | Some (x, xs') \<Rightarrow> (case force xs' of None \<Rightarrow> x | Some (x', xs'') \<Rightarrow> llast (LCons x' xs'')))" by(auto simp add: llast_def zero_enat_def eSuc_def split: enat.split llist.splits) declare [[code drop: ldistinct]] declare [[code drop: lprefix]] lemma lprefix_Lazy_llist [code]: "lprefix (Lazy_llist xs) (Lazy_llist ys) = (case xs () of None \<Rightarrow> True | Some (x, xs') \<Rightarrow> (case ys () of None \<Rightarrow> False | Some (y, ys') \<Rightarrow> x = y \<and> lprefix xs' ys'))" by auto declare [[code drop: lstrict_prefix]] lemma lstrict_prefix_Lazy_llist [code]: "lstrict_prefix (Lazy_llist xs) (Lazy_llist ys) \<longleftrightarrow> (case ys () of None \<Rightarrow> False | Some (y, ys') \<Rightarrow> (case xs () of None \<Rightarrow> True | Some (x, xs') \<Rightarrow> x = y \<and> lstrict_prefix xs' ys'))" by auto declare [[code drop: llcp]] lemma llcp_Lazy_llist [code]: "llcp (Lazy_llist xs) (Lazy_llist ys) = (case xs () of None \<Rightarrow> 0 | Some (x, xs') \<Rightarrow> (case ys () of None \<Rightarrow> 0 | Some (y, ys') \<Rightarrow> if x = y then eSuc (llcp xs' ys') else 0))" by auto declare [[code drop: llexord]] lemma llexord_Lazy_llist [code]: "llexord r (Lazy_llist xs) (Lazy_llist ys) \<longleftrightarrow> (case xs () of None \<Rightarrow> True | Some (x, xs') \<Rightarrow> (case ys () of None \<Rightarrow> False | Some (y, ys') \<Rightarrow> r x y \<or> x = y \<and> llexord r xs' ys'))" by auto declare [[code drop: lfilter]] lemma lfilter_Lazy_llist [code]: "lfilter P (Lazy_llist xs) = Lazy_llist (\<lambda>_. case xs () of None \<Rightarrow> None | Some (x, ys) \<Rightarrow> if P x then Some (x, lfilter P ys) else force (lfilter P ys))" by(auto split: llist.split) declare [[code drop: lconcat]] lemma lconcat_Lazy_llist [code]: "lconcat (Lazy_llist xss) = Lazy_llist (\<lambda>_. case xss () of None \<Rightarrow> None | Some (xs, xss') \<Rightarrow> force (lappend xs (lconcat xss')))" by(auto split: llist.split) declare option.splits [split del] declare Lazy_llist_def [simp del] text {* Simple ML test for laziness *} ML_val {* val zeros = @{code iterates} (fn x => x + 1) 0; val lhd = @{code lhd} zeros; val ltl = @{code ltl} zeros; val ltl' = @{code force} ltl; val ltake = @{code ltake} (@{code eSuc} (@{code eSuc} @{code "0::enat"})) zeros; val ldrop = @{code ldrop} (@{code eSuc} @{code "0::enat"}) zeros; val list_of = @{code list_of} ltake; val ltakeWhile = @{code ltakeWhile} (fn _ => true) zeros; val ldropWhile = @{code ldropWhile} (fn _ => false) zeros; val hd = @{code lhd} ldropWhile; val lfilter = @{code lfilter} (fn _ => false) zeros; *} hide_const (open) force end
{-# OPTIONS --cubical --safe #-} module Lemmas where open import Cubical.Core.Everything using (_≡_; Level; Type) open import Data.Fin using (Fin; toℕ; fromℕ<; zero; suc) open import Data.Integer using (ℤ; +_; -[1+_]) open import Data.Nat open import Data.Nat.Properties using (≤-step) open import Relation.Nullary.Decidable using (False) open import Relation.Nullary using (yes; no) k≤n⇒n-k≤n : (k n : ℕ) → k ≤ n → n ∸ k ≤ n k≤n⇒n-k≤n zero zero z≤n = z≤n k≤n⇒n-k≤n zero (suc n) z≤n = s≤s (k≤n⇒n-k≤n zero n z≤n) k≤n⇒n-k≤n (suc k) zero () k≤n⇒n-k≤n (suc k) (suc n) (s≤s p) = ≤-step (k≤n⇒n-k≤n k n p) finN<N : {n : ℕ} → (k : Fin n) → toℕ k < n finN<N zero = s≤s z≤n finN<N (suc k) = s≤s (finN<N k) suc≤-injective : ∀ {m n : ℕ} → suc m ≤ suc n → m ≤ n suc≤-injective (s≤s p) = p -- revMod k = n - k revMod : ∀ {n : ℕ} → Fin (suc n) → Fin (suc n) revMod {n} k = fromℕ< (s≤s (k≤n⇒n-k≤n (toℕ k) n (suc≤-injective (finN<N k))))
By entering your details in the fields requested, you enable coolrocks.co.uk and its service providers to provide you with the services you select. Whenever you provide such personal information, we will treat that information in accordance with this policy. Our services are designed to give you the information that you want to receive. coolrocks.co.uk will act in accordance with current legislation and aim to meet current Internet best practice. Both the cookies and the embedded code provide non-personal statistical information about visits to pages on the site, the duration of individual page view, paths taken by visitors through the site, data on visitors' screen settings and other general information. coolrocks.co.uk use this type of information, as with that obtained from other cookies used on the site, to help it improve the services to its users. NB: Even if you haven't set your computer to reject cookies you can still browse our site anonymously until such time as you wish to purchase an item using our coolrocks.co.uk services. When you supply any personal information to coolrocks.co.uk (e.g. when ordering products or services) we have legal obligations towards you in the way we deal with that data. We must collect the information fairly and tell you if we want to pass the information on to anyone else. In general, any information you provide to coolrocks.co.uk will only be used within coolrocks.co.uk. It will never be supplied to anyone outside coolrocks.co.uk without first obtaining your consent, unless we are obliged or permitted by law to disclose it. Also, if you post or send offensive or inappropriate content anywhere on or to coolrocks.co.uk and coolrocks.co.uk considers such behaviour to be serious and/or repeated, coolrocks.co.uk can use whatever information that is available to it about you to stop such behaviour. This may include informing relevant third parties such as your employer, school or e-mail provider about the content and your behaviour. We will hold your personal information on our systems for as long as you use the service you have requested, and remove it in the event that the purpose has been met, or, in the case of a personalised service, such as online billing, you no longer wish to continue your registration as a personalised user. Where personal information is held for people who are not yet registered but have taken part in other coolrocks.co.uk services (e.g. information requests), that information will be held only as long as necessary to ensure that the service is run smoothly. We will ensure that all personal information supplied is held securely, in accordance with the Data Protection Act 1998. You have the right to request a copy of the personal information coolrocks.co.uk holds about you and to have any inaccuracies corrected. If you are aged 16 or under, please get your parent/guardian's permission beforehand whenever you provide personal information to coolrocks.co.ukwebsite. Users without this consent are not allowed to provide us with personal information.
Formal statement is: lemma complex_div_gt_0: "(Re (a / b) > 0 \<longleftrightarrow> Re (a * cnj b) > 0) \<and> (Im (a / b) > 0 \<longleftrightarrow> Im (a * cnj b) > 0)" Informal statement is: The real and imaginary parts of a complex number $a/b$ are positive if and only if the real and imaginary parts of $a \overline{b}$ are positive.
From MetaCoq.Template Require Import All. Require Import String List. From ASUB Require Import GenM AssocList DeBruijnMap. (* TODO add another node for embedded terms. This should be a bit more performant when we use predefined terms like "eq" since we don't really need to look them up in the environment. *) Inductive nterm : Type := | nRef : string -> nterm (* turns into tRel, tConst, tInd, tConstruct from the normal term type *) | nHole : nterm | nTerm : term -> nterm | nProd : string -> nterm -> nterm -> nterm | nArr : nterm -> nterm -> nterm | nLambda : string -> nterm -> nterm -> nterm | nApp : nterm -> list nterm -> nterm | nFix : mfixpoint nterm -> nat -> nterm | nCase : string -> nat -> nterm -> nterm -> list (nat * nterm) -> nterm. Fixpoint mknArr (nt0: nterm) (nts: list nterm) := match nts with | [] => nt0 | nt :: nts => nArr nt0 (mknArr nt nts) end. Fixpoint mknArrRev (nts: list nterm) (nt0: nterm) := match nts with | [] => nt0 | nt :: nts => nArr nt (mknArrRev nts nt0) end. Import GenM.Notations GenM. (* MetaCoq Test Quote (match 1 with O => O | S x => x end). *) (* Import MonadNotation. MetaCoq Run (let tm := (tCase (* the type of the discriminant *) ({| inductive_mind := (MPfile ["Datatypes"; "Init"; "Coq"]%list, "nat"); inductive_ind := 0 |}, 0, Relevant) (tLambda {| binder_name := nNamed "x"; binder_relevance := Relevant |} (* (tInd {| inductive_mind := (MPfile ["Datatypes"; "Init"; "Coq"]%list, "nat"); inductive_ind := 0 |} *) (* []%list) *) (* (tInd {| inductive_mind := (MPfile ["Datatypes"; "Init"; "Coq"]%list, "nat"); inductive_ind := 0 |} *) (* []%list)) *) hole hole) (tApp (tConstruct {| inductive_mind := (MPfile ["Datatypes"; "Init"; "Coq"]%list, "nat"); inductive_ind := 0 |} 1 []%list) [tConstruct {| inductive_mind := (MPfile ["Datatypes"; "Init"; "Coq"]%list, "nat"); inductive_ind := 0 |} 0 []%list]) [(0, tConstruct {| inductive_mind := (MPfile ["Datatypes"; "Init"; "Coq"]%list, "nat"); inductive_ind := 0 |} 0 []%list); (1, tLambda {| binder_name := nNamed "x"; binder_relevance := Relevant |} (* (tInd {| inductive_mind := (MPfile ["Datatypes"; "Init"; "Coq"]%list, "nat"); inductive_ind := 0 |} *) (* []%list) *) hole (tRel 0))]) in tmUnquoteTyped nat tm >>= tmPrint). *) (* TODO maybe make it option string but then I don't have error handling. * Just a possible performance improvement *) Definition get_fix_name (d: def nterm) : GenM.t string := match binder_name (dname d) with | nAnon => error "Fixpoint without a name." | nNamed s => pure s end. (* TODO already defined somewhere? *) Definition get_inductive (s: string) : GenM.t inductive := env <- asks snd;; match SFMap.find env s with | None => error (append "get_inductive: not found: " s) | Some t => match t with | tInd ind _ => pure ind | _ => error "wrong kind of term" end end. Fixpoint translate (dbmap: DB.t) (t: nterm) : GenM.t term := match t with | nRef s => (* check dbmap and environment *) match dbmap s with | Some n => pure (tRel n) | None => env <- asks snd;; match SFMap.find env s with | Some t => pure t | None => error (append "Unknown Identifier during Gallina Translation: " s) end end | nHole => pure hole | nTerm t => pure t | nProd s nt0 nt1 => let n := {| binder_name := nNamed s; binder_relevance := Relevant |} in t0 <- translate dbmap nt0;; (* add the newly bound variable when translating nt1 *) let dbmap' := DB.add s dbmap in t1 <- translate dbmap' nt1;; pure (tProd n t0 t1) | nArr nt0 nt1 => let n := {| binder_name := nAnon; binder_relevance := Relevant |} in t0 <- translate dbmap nt0;; (* just shift the dbmap when translating nt1 *) let dbmap' := DB.shift dbmap in t1 <- translate dbmap' nt1;; pure (tProd n t0 t1) | nLambda s nt0 nt1 => let n := {| binder_name := nNamed s; binder_relevance := Relevant |} in t0 <- translate dbmap nt0;; (* add the newly bound variable when translating nt1 *) let dbmap' := DB.add s dbmap in t1 <- translate dbmap' nt1;; pure (tLambda n t0 t1) | nApp nt nts => t <- translate dbmap nt;; ts <- a_map (translate dbmap) nts;; pure (tApp t ts) | nFix mfixs n => fixNames <- a_map get_fix_name mfixs;; let dbmap' := DB.adds fixNames dbmap in mfixs <- a_map (fun '{| dname := nname; dtype := ntype; dbody := nbody; rarg := nrarg |} => ttype <- translate dbmap ntype;; (* the fixpoint names are only bound in the bodies *) tbody <- translate dbmap' nbody;; pure {| dname := nname; dtype := ttype; dbody := tbody; rarg := nrarg |}) mfixs;; pure (tFix mfixs n) | nCase indName paramNum nelimPred ndiscr nbranches => telimPred <- translate dbmap nelimPred;; tdiscr <- translate dbmap ndiscr;; tbranches <- a_map (fun '(n, nt) => t <- translate dbmap nt;; pure (n, t)) nbranches;; ind <- get_inductive indName;; pure (tCase (ind, paramNum, Relevant) telimPred tdiscr tbranches) end. Definition translate_lemma (l: GenM.t (string * nterm * nterm)) : GenM.t (string * term * term) := '(lname, ntype, nbody) <- l;; ttype <- translate DB.empty ntype;; tbody <- translate DB.empty nbody;; pure (lname, ttype, tbody).
input := FileTools:-Text:-ReadFile("AoC-2021-19-input.txt" ): with(StringTools): scanners := map(l->[parse]~(l[2..-1]), map(Split,Split(SubstituteAll(input, "\n\n", "X"),"X"),"\n")): truelocs := table(); truelocs[1] := scanners[1]; # base 0 sunknown := [seq(2..nops(scanners))]; knownscans := [1=[0,0,0]]; dist := (v,u) -> add((v[i]-u[i])^2,i=1..3): # used to generate equations M := Matrix(3,3,(i,j)->a[i,j]): A := <a[0,1], a[0,2], a[0,3]>: for k1 to nops(scanners)-1 do # find a scanner that overlaps with a known scanner for j1 from 1 to nops(knownscans) do sn1 := lhs(knownscans[j1]); scan0 := truelocs[sn1]; for i1 from 1 to nops(sunknown) do # compute all pairwise distances sn2 := sunknown[i1]; scan1 := scanners[sn2]; n0 := nops(scan0); n1 := nops(scan1); # building pairs" M0 := Matrix([seq([seq(dist(scan0[i],scan0[j]),j=1..n0)],i=1..n0)]): M1 := Matrix([seq([seq(dist(scan1[i],scan1[j]),j=1..n1)],i=1..n1)]): ints01 := {entries(M0,'nolist')} intersect {entries(M1,'nolist')} minus {0}; if nops(ints01) < 50 then # printf("scanner %d can not overlap scanner %d -- only %d common pairs\n", sn1, sn2, nops(ints01) ); next; end if; # at least 66 needed for 12 in common # looking up pair from their common distances pairs0 := NULL: pairs1 := NULL: for i from 1 to nops(ints01) do member(ints01[i], M0, 'loc0'); pairs0 := pairs0, [loc0]; member(ints01[i], M1, 'loc1'); pairs1 := pairs1, [loc1];nu end do: pairs0 := [pairs0]; pairs1 := [pairs1]; # these are the overlapping sets of beacons o0 := [seq](ifelse(numboccur(pairs0,i)=11,i,NULL),i=1..n0); o1 := [seq](ifelse(numboccur(pairs1,i)=11,i,NULL),i=1..n1); if nops(o0) <> 12 then #printf("found only %d=%d overlaps between %d and %d skipping\n", nops(o0), nops(o1), sn1, sn2); next; end if; # determine the pairings pot01matches := table(sparse={o1[]}); for i from 1 to nops(pairs0) do if pairs0[i][1] in o0 and pairs0[i][2] in o0 then # check o2 too? pot01matches[pairs0[i][1]] := pot01matches[pairs0[i][1]] intersect {pairs1[i][]}; pot01matches[pairs0[i][2]] := pot01matches[pairs0[i][2]] intersect {pairs1[i][]}; end if; end do; if {} in {entries(pot01matches,'nolist')} then printf("found a contradiction in the potential pairings\n"); next; end if; matches01 := map(p->lhs(p)=rhs(p)[], [entries(pot01matches,'pairs')]); # use symbolic computation to build the equations to solve for the rotation # and translation eqs := {seq(seq((M . Vector(scan1[rhs(matches01[k])]) + A)[j] = Vector(scan0[lhs(matches01[k])])[j], j=1..3),k=1..4)}; sol := solve( eqs ); Mo := eval(M, sol); a0 := eval(<a[0,1], a[0,2], a[0,3]>, sol); scan1 := [seq(convert(Mo . Vector(scan1[i]) + a0,list), i=1..nops(scan1))]; knownscans := [knownscans[], sn2=convert(a0,list)]; sunknown := subsop(i1=NULL, sunknown); # remove this scan from the unknowns truelocs[sn2] := scan1; break; end do; end do; end do; ASSERT(nops(knownscans) = nops(scanners)); answer1 := nops( map(op, {entries}(truelocs,'nolist') ) ); # compute the Manhatten distance between scanners mdist := (u,v) -> add(abs(u[i]-v[i]),i=1..3): scannerlocs := map(rhs, knownscans); answer2 := max( seq(seq(mdist(scannerlocs[i],scannerlocs[j]),j=i+1..nops(scannerlocs)),i=1..nops(scannerlocs)));
#include <api/components.h> #include <api/kvstore_itf.h> #include <common/string_view.h> #include <common/utils.h> /* MiB */ #include <gsl/pointers> /* not_null */ #include <cstddef> /* size_t */ #include <memory> /* unique_ptr */ #include <stdexcept> /* runtime_error */ #include <string> namespace { /* things which differ depending on the type of store used */ struct custom_store { virtual ~custom_store() {} virtual std::size_t minimum_size(std::size_t s) const { return s; } virtual component::uuid_t factory() const = 0; virtual std::size_t presumed_allocation() const = 0; virtual bool uses_numa_nodes() const { return false; } virtual status_t rc_unknown_attribute() const { return E_NOT_SUPPORTED; } virtual status_t rc_percent_used() const { return S_OK; } virtual status_t rc_resize_locked() const { return E_LOCKED; } virtual status_t rc_attribute_key_null_ptr() const { return E_BAD_PARAM; } virtual status_t rc_attribute_key_not_found() const { return component::IKVStore::E_KEY_NOT_FOUND; } virtual status_t rc_attribute_hashtable_expansion() const { return S_OK; } virtual status_t rc_out_of_memory() const { return component::IKVStore::E_TOO_LARGE; } virtual status_t rc_atomic_update() const { return S_OK; } virtual status_t rc_allocate_pool_memory_size_0() const { return S_OK; } virtual bool swap_updates_timestamp() const { return false; } }; struct custom_mapstore : public custom_store { virtual component::uuid_t factory() const override { return component::mapstore_factory; } std::size_t minimum_size(std::size_t s) const override { return std::max(std::size_t(8), s); } std::size_t presumed_allocation() const override { return 1ULL << DM_REGION_LOG_GRAIN_SIZE; } bool uses_numa_nodes() const override { return true; } status_t rc_unknown_attribute() const override { return E_INVALID_ARG; } status_t rc_percent_used() const override { return rc_unknown_attribute(); } status_t rc_resize_locked() const override { return E_INVAL; } status_t rc_attribute_key_null_ptr() const override { return E_INVALID_ARG; } status_t rc_attribute_key_not_found() const override { return rc_unknown_attribute(); } status_t rc_attribute_hashtable_expansion() const override { return rc_unknown_attribute(); } status_t rc_out_of_memory() const override { return E_INVAL; } status_t rc_atomic_update() const override { return E_NOT_SUPPORTED; } status_t rc_allocate_pool_memory_size_0() const override { return E_INVAL; } }; struct custom_hstore : public custom_store { virtual component::uuid_t factory() const override { return component::hstore_factory; } std::size_t presumed_allocation() const override { return MiB(32); } bool swap_updates_timestamp() const override { return true; } }; struct custom_hstore_cc : public custom_hstore { std::size_t presumed_allocation() const override { return MiB(32); } }; custom_mapstore custom_mapstore_i{}; custom_hstore custom_hstore_i{}; custom_hstore_cc custom_hstore_cc_i{}; const std::map<std::string, gsl::not_null<custom_store *>, std::less<>> custom_map = { { "mapstore", &custom_mapstore_i }, { "hstore", &custom_hstore_i }, { "hstore-cc", &custom_hstore_cc_i }, { "hstore-mc", &custom_hstore_i }, { "hstore-mr", &custom_hstore_i }, { "hstore-mm", &custom_hstore_i }, }; } gsl::not_null<custom_store *> locate_custom_store(common::string_view store) { const auto c_it = custom_map.find(store); if ( c_it == custom_map.end() ) { throw std::runtime_error(common::format("store {} not recognized", store)); } return c_it->second; } auto make_kvstore( common::string_view store , gsl::not_null<custom_store *> c , const component::IKVStore_factory::map_create & mc ) -> std::unique_ptr<component::IKVStore> { using IKVStore_factory = component::IKVStore_factory; const std::string store_lib = "libcomponent-" + std::string(store) + ".so"; auto *comp = component::load_component(store_lib.c_str(), c->factory()); if ( ! comp ) { throw std::runtime_error(common::format("failed to load component {}", store_lib)); } const auto fact = make_itf_ref(static_cast<IKVStore_factory*>(comp->query_interface(IKVStore_factory::iid()))); const auto kvstore = fact->create(0, mc); return std::unique_ptr<component::IKVStore>(kvstore); }
Formal statement is: lemma (in topological_space) eventually_at_topological: "eventually P (at a within s) \<longleftrightarrow> (\<exists>S. open S \<and> a \<in> S \<and> (\<forall>x\<in>S. x \<noteq> a \<longrightarrow> x \<in> s \<longrightarrow> P x))" Informal statement is: If $P$ holds eventually at $a$ within $s$, then there exists an open set $S$ containing $a$ such that $P$ holds for all $x \in S$ with $x \neq a$ and $x \in s$.
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq choice. From mathcomp Require Import fintype bigop ssralg poly. (******************************************************************************) (* This file provides a library for the basic theory of Euclidean and pseudo- *) (* Euclidean division for polynomials over ring structures. *) (* The library defines two versions of the pseudo-euclidean division: one for *) (* coefficients in a (not necessarily commutative) ring structure and one for *) (* coefficients equipped with a structure of integral domain. From the latter *) (* we derive the definition of the usual Euclidean division for coefficients *) (* in a field. Only the definition of the pseudo-division for coefficients in *) (* an integral domain is exported by default and benefits from notations. *) (* Also, the only theory exported by default is the one of division for *) (* polynomials with coefficients in a field. *) (* Other definitions and facts are qualified using name spaces indicating the *) (* hypotheses made on the structure of coefficients and the properties of the *) (* polynomial one divides with. *) (* *) (* Pdiv.Field (exported by the present library): *) (* edivp p q == pseudo-division of p by q with p q : {poly R} where *) (* R is an idomainType. *) (* Computes (k, quo, rem) : nat * {poly r} * {poly R}, *) (* such that size rem < size q and: *) (* + if lead_coef q is not a unit, then: *) (* (lead_coef q ^+ k) *: p = q * quo + rem *) (* + else if lead_coef q is a unit, then: *) (* p = q * quo + rem and k = 0 *) (* p %/ q == quotient (second component) computed by (edivp p q). *) (* p %% q == remainder (third component) computed by (edivp p q). *) (* scalp p q == exponent (first component) computed by (edivp p q). *) (* p %| q == tests the nullity of the remainder of the *) (* pseudo-division of p by q. *) (* rgcdp p q == Pseudo-greater common divisor obtained by performing *) (* the Euclidean algorithm on p and q using redivp as *) (* Euclidean division. *) (* p %= q == p and q are associate polynomials, i.e., p %| q and *) (* q %| p, or equivalently, p = c *: q for some nonzero *) (* constant c. *) (* gcdp p q == Pseudo-greater common divisor obtained by performing *) (* the Euclidean algorithm on p and q using edivp as *) (* Euclidean division. *) (* egcdp p q == The pair of Bezout coefficients: if e := egcdp p q, *) (* then size e.1 <= size q, size e.2 <= size p, and *) (* gcdp p q %= e.1 * p + e.2 * q *) (* coprimep p q == p and q are coprime, i.e., (gcdp p q) is a nonzero *) (* constant. *) (* gdcop q p == greatest divisor of p which is coprime to q. *) (* irreducible_poly p <-> p has only trivial (constant) divisors. *) (* *) (* Pdiv.Idomain: theory available for edivp and the related operation under *) (* the sole assumption that the ring of coefficients is canonically an *) (* integral domain (R : idomainType). *) (* *) (* Pdiv.IdomainMonic: theory available for edivp and the related operations *) (* under the assumption that the ring of coefficients is canonically *) (* and integral domain (R : idomainType) an the divisor is monic. *) (* *) (* Pdiv.IdomainUnit: theory available for edivp and the related operations *) (* under the assumption that the ring of coefficients is canonically an *) (* integral domain (R : idomainType) and the leading coefficient of the *) (* divisor is a unit. *) (* *) (* Pdiv.ClosedField: theory available for edivp and the related operation *) (* under the sole assumption that the ring of coefficients is canonically *) (* an algebraically closed field (R : closedField). *) (* *) (* Pdiv.Ring : *) (* redivp p q == pseudo-division of p by q with p q : {poly R} where R is *) (* a ringType. *) (* Computes (k, quo, rem) : nat * {poly r} * {poly R}, *) (* such that if rem = 0 then quo * q = p * (lead_coef q ^+ k) *) (* *) (* rdivp p q == quotient (second component) computed by (redivp p q). *) (* rmodp p q == remainder (third component) computed by (redivp p q). *) (* rscalp p q == exponent (first component) computed by (redivp p q). *) (* rdvdp p q == tests the nullity of the remainder of the pseudo-division *) (* of p by q. *) (* rgcdp p q == analogue of gcdp for coefficients in a ringType. *) (* rgdcop p q == analogue of gdcop for coefficients in a ringType. *) (*rcoprimep p q == analogue of coprimep p q for coefficients in a ringType. *) (* *) (* Pdiv.RingComRreg : theory of the operations defined in Pdiv.Ring, when the *) (* ring of coefficients is canonically commutative (R : comRingType) and *) (* the leading coefficient of the divisor is both right regular and *) (* commutes as a constant polynomial with the divisor itself *) (* *) (* Pdiv.RingMonic : theory of the operations defined in Pdiv.Ring, under the *) (* assumption that the divisor is monic. *) (* *) (* Pdiv.UnitRing: theory of the operations defined in Pdiv.Ring, when the *) (* ring R of coefficients is canonically with units (R : unitRingType). *) (* *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Import GRing.Theory. Local Open Scope ring_scope. Reserved Notation "p %= q" (at level 70, no associativity). Local Notation simp := Monoid.simpm. Module Pdiv. Module CommonRing. Section RingPseudoDivision. Variable R : ringType. Implicit Types d p q r : {poly R}. (* Pseudo division, defined on an arbitrary ring *) Definition redivp_rec (q : {poly R}) := let sq := size q in let cq := lead_coef q in fix loop (k : nat) (qq r : {poly R})(n : nat) {struct n} := if size r < sq then (k, qq, r) else let m := (lead_coef r) *: 'X^(size r - sq) in let qq1 := qq * cq%:P + m in let r1 := r * cq%:P - m * q in if n is n1.+1 then loop k.+1 qq1 r1 n1 else (k.+1, qq1, r1). Definition redivp_expanded_def p q := if q == 0 then (0%N, 0, p) else redivp_rec q 0 0 p (size p). Fact redivp_key : unit. Proof. by []. Qed. Definition redivp : {poly R} -> {poly R} -> nat * {poly R} * {poly R} := locked_with redivp_key redivp_expanded_def. Canonical redivp_unlockable := [unlockable fun redivp]. Definition rdivp p q := ((redivp p q).1).2. Definition rmodp p q := (redivp p q).2. Definition rscalp p q := ((redivp p q).1).1. Definition rdvdp p q := rmodp q p == 0. (*Definition rmultp := [rel m d | rdvdp d m].*) Lemma redivp_def p q : redivp p q = (rscalp p q, rdivp p q, rmodp p q). Proof. by rewrite /rscalp /rdivp /rmodp; case: (redivp p q) => [[]] /=. Qed. Lemma rdiv0p p : rdivp 0 p = 0. Proof. rewrite /rdivp unlock; case: ifP => // Hp; rewrite /redivp_rec !size_poly0. by rewrite polySpred ?Hp. Qed. Lemma rdivp0 p : rdivp p 0 = 0. Proof. by rewrite /rdivp unlock eqxx. Qed. Lemma rdivp_small p q : size p < size q -> rdivp p q = 0. Proof. rewrite /rdivp unlock; have [-> | _ ltpq] := eqP; first by rewrite size_poly0. by case: (size p) => [|s]; rewrite /= ltpq. Qed. Lemma leq_rdivp p q : size (rdivp p q) <= size p. Proof. have [/rdivp_small->|] := ltnP (size p) (size q); first by rewrite size_poly0. rewrite /rdivp /rmodp /rscalp unlock. have [->|q0] //= := eqVneq q 0. have: size (0 : {poly R}) <= size p by rewrite size_poly0. move: {2 3 4 6}(size p) (leqnn (size p)) => A. elim: (size p) 0%N (0 : {poly R}) {1 3 4}p (leqnn (size p)) => [|n ihn] k q1 r. by move/size_poly_leq0P->; rewrite /= size_poly0 size_poly_gt0 q0. move=> /= hrn hr hq1 hq; case: ltnP => //= hqr. have sq: 0 < size q by rewrite size_poly_gt0. have sr: 0 < size r by apply: leq_trans sq hqr. apply: ihn => //. - apply/leq_sizeP => j hnj. rewrite coefB -scalerAl coefZ coefXnM ltn_subRL ltnNge. have hj : (size r).-1 <= j by apply: leq_trans hnj; rewrite -ltnS prednK. rewrite [leqLHS]polySpred -?size_poly_gt0 // coefMC. rewrite (leq_ltn_trans hj) /=; last by rewrite -add1n leq_add2r. move: hj; rewrite leq_eqVlt prednK // => /predU1P [<- | hj]. by rewrite -subn1 subnAC subKn // !subn1 !lead_coefE subrr. have/leq_sizeP-> //: size q <= j - (size r - size q). by rewrite subnBA // leq_psubRL // leq_add2r. by move/leq_sizeP: (hj) => -> //; rewrite mul0r mulr0 subr0. - apply: leq_trans (size_add _ _) _; rewrite geq_max; apply/andP; split. apply: leq_trans (size_mul_leq _ _) _. by rewrite size_polyC lead_coef_eq0 q0 /= addn1. rewrite size_opp; apply: leq_trans (size_mul_leq _ _) _. apply: leq_trans hr; rewrite -subn1 leq_subLR -[in (1 + _)%N](subnK hqr). by rewrite addnA leq_add2r add1n -(@size_polyXn R) size_scale_leq. apply: leq_trans (size_add _ _) _; rewrite geq_max; apply/andP; split. apply: leq_trans (size_mul_leq _ _) _. by rewrite size_polyC lead_coef_eq0 q0 /= addnS addn0. apply: leq_trans (size_scale_leq _ _) _. by rewrite size_polyXn -subSn // leq_subLR -add1n leq_add. Qed. Lemma rmod0p p : rmodp 0 p = 0. Proof. rewrite /rmodp unlock; case: ifP => // Hp; rewrite /redivp_rec !size_poly0. by rewrite polySpred ?Hp. Qed. Lemma rmodp0 p : rmodp p 0 = p. Proof. by rewrite /rmodp unlock eqxx. Qed. Lemma rscalp_small p q : size p < size q -> rscalp p q = 0%N. Proof. rewrite /rscalp unlock; case: eqP => _ // spq. by case sp: (size p) => [| s] /=; rewrite spq. Qed. Lemma ltn_rmodp p q : (size (rmodp p q) < size q) = (q != 0). Proof. rewrite /rdivp /rmodp /rscalp unlock; have [->|q0] := eqVneq q 0. by rewrite /= size_poly0 ltn0. elim: (size p) 0%N 0 {1 3}p (leqnn (size p)) => [|n ihn] k q1 r. move/size_poly_leq0P->. by rewrite /= size_poly0 size_poly_gt0 q0 size_poly0 size_poly_gt0. move=> hr /=; case: (ltnP (size r)) => // hsrq; apply/ihn/leq_sizeP => j hnj. rewrite coefB -scalerAl !coefZ coefXnM coefMC ltn_subRL ltnNge. have sq: 0 < size q by rewrite size_poly_gt0. have sr: 0 < size r by apply: leq_trans hsrq. have hj: (size r).-1 <= j by apply: leq_trans hnj; rewrite -ltnS prednK. move: (leq_add sq hj); rewrite add1n prednK // => -> /=. move: hj; rewrite leq_eqVlt prednK // => /predU1P [<- | hj]. by rewrite -predn_sub subKn // !lead_coefE subrr. have/leq_sizeP -> //: size q <= j - (size r - size q). by rewrite subnBA // leq_subRL ?leq_add2r // (leq_trans hj) // leq_addr. by move/leq_sizeP: hj => -> //; rewrite mul0r mulr0 subr0. Qed. Lemma ltn_rmodpN0 p q : q != 0 -> size (rmodp p q) < size q. Proof. by rewrite ltn_rmodp. Qed. Lemma rmodp1 p : rmodp p 1 = 0. Proof. apply/eqP; have := ltn_rmodp p 1. by rewrite !oner_neq0 -size_poly_eq0 size_poly1 ltnS leqn0. Qed. Lemma rmodp_small p q : size p < size q -> rmodp p q = p. Proof. rewrite /rmodp unlock; have [->|_] := eqP; first by rewrite size_poly0. by case sp: (size p) => [| s] Hs /=; rewrite sp Hs /=. Qed. Lemma leq_rmodp m d : size (rmodp m d) <= size m. Proof. have [/rmodp_small -> //|h] := ltnP (size m) (size d). have [->|d0] := eqVneq d 0; first by rewrite rmodp0. by apply: leq_trans h; apply: ltnW; rewrite ltn_rmodp. Qed. Lemma rmodpC p c : c != 0 -> rmodp p c%:P = 0. Proof. move=> Hc; apply/eqP; rewrite -size_poly_leq0 -ltnS. have -> : 1%N = nat_of_bool (c != 0) by rewrite Hc. by rewrite -size_polyC ltn_rmodp polyC_eq0. Qed. Lemma rdvdp0 d : rdvdp d 0. Proof. by rewrite /rdvdp rmod0p. Qed. Lemma rdvd0p n : rdvdp 0 n = (n == 0). Proof. by rewrite /rdvdp rmodp0. Qed. Lemma rdvd0pP n : reflect (n = 0) (rdvdp 0 n). Proof. by apply: (iffP idP); rewrite rdvd0p; move/eqP. Qed. Lemma rdvdpN0 p q : rdvdp p q -> q != 0 -> p != 0. Proof. by move=> pq hq; apply: contraTneq pq => ->; rewrite rdvd0p. Qed. Lemma rdvdp1 d : rdvdp d 1 = (size d == 1%N). Proof. rewrite /rdvdp; have [->|] := eqVneq d 0. by rewrite rmodp0 size_poly0 (negPf (oner_neq0 _)). rewrite -size_poly_leq0 -ltnS; case: ltngtP => // [|/eqP] hd _. by rewrite rmodp_small ?size_poly1 // oner_eq0. have [c cn0 ->] := size_poly1P _ hd. rewrite /rmodp unlock -size_poly_eq0 size_poly1 /= size_poly1 size_polyC cn0 /=. by rewrite polyC_eq0 (negPf cn0) !lead_coefC !scale1r subrr !size_poly0. Qed. Lemma rdvd1p m : rdvdp 1 m. Proof. by rewrite /rdvdp rmodp1. Qed. Lemma Nrdvdp_small (n d : {poly R}) : n != 0 -> size n < size d -> rdvdp d n = false. Proof. by move=> nn0 hs; rewrite /rdvdp (rmodp_small hs); apply: negPf. Qed. Lemma rmodp_eq0P p q : reflect (rmodp p q = 0) (rdvdp q p). Proof. exact: (iffP eqP). Qed. Lemma rmodp_eq0 p q : rdvdp q p -> rmodp p q = 0. Proof. exact: rmodp_eq0P. Qed. Lemma rdvdp_leq p q : rdvdp p q -> q != 0 -> size p <= size q. Proof. by move=> dvd_pq; rewrite leqNgt; apply: contra => /rmodp_small <-. Qed. Definition rgcdp p q := let: (p1, q1) := if size p < size q then (q, p) else (p, q) in if p1 == 0 then q1 else let fix loop (n : nat) (pp qq : {poly R}) {struct n} := let rr := rmodp pp qq in if rr == 0 then qq else if n is n1.+1 then loop n1 qq rr else rr in loop (size p1) p1 q1. Lemma rgcd0p : left_id 0 rgcdp. Proof. move=> p; rewrite /rgcdp size_poly0 size_poly_gt0 if_neg. case: ifP => /= [_ | nzp]; first by rewrite eqxx. by rewrite polySpred !(rmodp0, nzp) //; case: _.-1 => [|m]; rewrite rmod0p eqxx. Qed. Lemma rgcdp0 : right_id 0 rgcdp. Proof. move=> p; have:= rgcd0p p; rewrite /rgcdp size_poly0 size_poly_gt0. by case: eqVneq => p0; rewrite ?(eqxx, p0) //= eqxx. Qed. Lemma rgcdpE p q : rgcdp p q = if size p < size q then rgcdp (rmodp q p) p else rgcdp (rmodp p q) q. Proof. pose rgcdp_rec := fix rgcdp_rec (n : nat) (pp qq : {poly R}) {struct n} := let rr := rmodp pp qq in if rr == 0 then qq else if n is n1.+1 then rgcdp_rec n1 qq rr else rr. have Irec: forall m n p q, size q <= m -> size q <= n -> size q < size p -> rgcdp_rec m p q = rgcdp_rec n p q. + elim=> [|m Hrec] [|n] //= p1 q1. - move/size_poly_leq0P=> -> _; rewrite size_poly0 size_poly_gt0 rmodp0. by move/negPf->; case: n => [|n] /=; rewrite rmod0p eqxx. - move=> _ /size_poly_leq0P ->; rewrite size_poly0 size_poly_gt0 rmodp0. by move/negPf->; case: m {Hrec} => [|m] /=; rewrite rmod0p eqxx. case: eqVneq => Epq Sm Sn Sq //; have [->|nzq] := eqVneq q1 0. by case: n m {Sm Sn Hrec} => [|m] [|n] //=; rewrite rmod0p eqxx. apply: Hrec; last by rewrite ltn_rmodp. by rewrite -ltnS (leq_trans _ Sm) // ltn_rmodp. by rewrite -ltnS (leq_trans _ Sn) // ltn_rmodp. have [->|nzp] := eqVneq p 0. by rewrite rmod0p rmodp0 rgcd0p rgcdp0 if_same. have [->|nzq] := eqVneq q 0. by rewrite rmod0p rmodp0 rgcd0p rgcdp0 if_same. rewrite /rgcdp -/rgcdp_rec !ltn_rmodp (negPf nzp) (negPf nzq) /=. have [ltpq|leqp] := ltnP; rewrite !(negPf nzp, negPf nzq) //= polySpred //=. have [->|nzqp] := eqVneq. by case: (size p) => [|[|s]]; rewrite /= rmodp0 (negPf nzp) // rmod0p eqxx. apply: Irec => //; last by rewrite ltn_rmodp. by rewrite -ltnS -polySpred // (leq_trans _ ltpq) ?leqW // ltn_rmodp. by rewrite ltnW // ltn_rmodp. have [->|nzpq] := eqVneq. by case: (size q) => [|[|s]]; rewrite /= rmodp0 (negPf nzq) // rmod0p eqxx. apply: Irec => //; last by rewrite ltn_rmodp. by rewrite -ltnS -polySpred // (leq_trans _ leqp) // ltn_rmodp. by rewrite ltnW // ltn_rmodp. Qed. Variant comm_redivp_spec m d : nat * {poly R} * {poly R} -> Type := ComEdivnSpec k (q r : {poly R}) of (GRing.comm d (lead_coef d)%:P -> m * (lead_coef d ^+ k)%:P = q * d + r) & (d != 0 -> size r < size d) : comm_redivp_spec m d (k, q, r). Lemma comm_redivpP m d : comm_redivp_spec m d (redivp m d). Proof. rewrite unlock; have [->|Hd] := eqVneq d 0. by constructor; rewrite !(simp, eqxx). have: GRing.comm d (lead_coef d)%:P -> m * (lead_coef d ^+ 0)%:P = 0 * d + m. by rewrite !simp. elim: (size m) 0%N 0 {1 4 6}m (leqnn (size m)) => [|n IHn] k q r Hr /=. move/size_poly_leq0P: Hr ->. suff hsd: size (0: {poly R}) < size d by rewrite hsd => /= ?; constructor. by rewrite size_poly0 size_poly_gt0. case: ltnP => Hlt Heq; first by constructor. apply/IHn=> [|Cda]; last first. rewrite mulrDl addrAC -addrA subrK exprSr polyCM mulrA Heq //. by rewrite mulrDl -mulrA Cda mulrA. apply/leq_sizeP => j Hj; rewrite coefB coefMC -scalerAl coefZ coefXnM. rewrite ltn_subRL ltnNge (leq_trans Hr) /=; last first. by apply: leq_ltn_trans Hj _; rewrite -add1n leq_add2r size_poly_gt0. move: Hj; rewrite leq_eqVlt; case/predU1P => [<-{j} | Hj]; last first. rewrite !nth_default ?simp ?oppr0 ?(leq_trans Hr) //. by rewrite -{1}(subKn Hlt) leq_sub2r // (leq_trans Hr). move: Hr; rewrite leq_eqVlt ltnS; case/predU1P=> Hqq; last first. by rewrite !nth_default ?simp ?oppr0 // -{1}(subKn Hlt) leq_sub2r. rewrite /lead_coef Hqq polySpred // subSS subKn ?addrN //. by rewrite -subn1 leq_subLR add1n -Hqq. Qed. Lemma rmodpp p : GRing.comm p (lead_coef p)%:P -> rmodp p p = 0. Proof. move=> hC; rewrite /rmodp unlock; have [-> //|] := eqVneq. rewrite -size_poly_eq0 /redivp_rec; case sp: (size p)=> [|n] // _. rewrite sp ltnn subnn expr0 hC alg_polyC !simp subrr. by case: n sp => [|n] sp; rewrite size_polyC /= eqxx. Qed. Definition rcoprimep (p q : {poly R}) := size (rgcdp p q) == 1%N. Fixpoint rgdcop_rec q p n := if n is m.+1 then if rcoprimep p q then p else rgdcop_rec q (rdivp p (rgcdp p q)) m else (q == 0)%:R. Definition rgdcop q p := rgdcop_rec q p (size p). Lemma rgdcop0 q : rgdcop q 0 = (q == 0)%:R. Proof. by rewrite /rgdcop size_poly0. Qed. End RingPseudoDivision. End CommonRing. Module RingComRreg. Import CommonRing. Section ComRegDivisor. Variable R : ringType. Variable d : {poly R}. Hypothesis Cdl : GRing.comm d (lead_coef d)%:P. Hypothesis Rreg : GRing.rreg (lead_coef d). Implicit Types p q r : {poly R}. Lemma redivp_eq q r : size r < size d -> let k := (redivp (q * d + r) d).1.1 in let c := (lead_coef d ^+ k)%:P in redivp (q * d + r) d = (k, q * c, r * c). Proof. move=> lt_rd; case: comm_redivpP=> k q1 r1 /(_ Cdl) Heq. have dn0: d != 0 by case: (size d) lt_rd (size_poly_eq0 d) => // n _ <-. move=> /(_ dn0) Hs. have eC : q * d * (lead_coef d ^+ k)%:P = q * (lead_coef d ^+ k)%:P * d. by rewrite -mulrA polyC_exp (commrX k Cdl) mulrA. suff e1 : q1 = q * (lead_coef d ^+ k)%:P. congr (_, _, _) => //=; move/eqP: Heq. by rewrite [_ + r1]addrC -subr_eq e1 mulrDl addrAC eC subrr add0r; move/eqP. have : (q1 - q * (lead_coef d ^+ k)%:P) * d = r * (lead_coef d ^+ k)%:P - r1. apply: (@addIr _ r1); rewrite subrK. apply: (@addrI _ ((q * (lead_coef d ^+ k)%:P) * d)). by rewrite mulrDl mulNr !addrA [_ + (q1 * d)]addrC addrK -eC -mulrDl. move/eqP; rewrite -[_ == _ - _]subr_eq0 rreg_div0 //. by case/andP; rewrite subr_eq0; move/eqP. rewrite size_opp; apply: (leq_ltn_trans (size_add _ _)); rewrite size_opp. rewrite gtn_max Hs (leq_ltn_trans (size_mul_leq _ _)) //. rewrite size_polyC; case: (_ == _); last by rewrite addnS addn0. by rewrite addn0; apply: leq_ltn_trans lt_rd; case: size. Qed. (* this is a bad name *) Lemma rdivp_eq p : p * (lead_coef d ^+ (rscalp p d))%:P = (rdivp p d) * d + (rmodp p d). Proof. by rewrite /rdivp /rmodp /rscalp; case: comm_redivpP=> k q1 r1 Hc _; apply: Hc. Qed. (* section variables impose an inconvenient order on parameters *) Lemma eq_rdvdp k q1 p: p * ((lead_coef d)^+ k)%:P = q1 * d -> rdvdp d p. Proof. move=> he. have Hnq0 := rreg_lead0 Rreg; set lq := lead_coef d. pose v := rscalp p d; pose m := maxn v k. rewrite /rdvdp -(rreg_polyMC_eq0 _ (@rregX _ _ (m - v) Rreg)). suff: ((rdivp p d) * (lq ^+ (m - v))%:P - q1 * (lq ^+ (m - k))%:P) * d + (rmodp p d) * (lq ^+ (m - v))%:P == 0. rewrite rreg_div0 //; first by case/andP. by rewrite rreg_size ?ltn_rmodp //; exact: rregX. rewrite mulrDl addrAC mulNr -!mulrA polyC_exp -(commrX (m-v) Cdl). rewrite -polyC_exp mulrA -mulrDl -rdivp_eq // [(_ ^+ (m - k))%:P]polyC_exp. rewrite -(commrX (m-k) Cdl) -polyC_exp mulrA -he -!mulrA -!polyCM -/v. by rewrite -!exprD addnC subnK ?leq_maxl // addnC subnK ?subrr ?leq_maxr. Qed. Variant rdvdp_spec p q : {poly R} -> bool -> Type := | Rdvdp k q1 & p * ((lead_coef q)^+ k)%:P = q1 * q : rdvdp_spec p q 0 true | RdvdpN & rmodp p q != 0 : rdvdp_spec p q (rmodp p q) false. (* Is that version useable ? *) Lemma rdvdp_eqP p : rdvdp_spec p d (rmodp p d) (rdvdp d p). Proof. case hdvd: (rdvdp d p); last by apply: RdvdpN; move/rmodp_eq0P/eqP: hdvd. move/rmodp_eq0P: (hdvd)->; apply: (@Rdvdp _ _ (rscalp p d) (rdivp p d)). by rewrite rdivp_eq //; move/rmodp_eq0P: (hdvd)->; rewrite addr0. Qed. Lemma rdvdp_mull p : rdvdp d (p * d). Proof. by apply: (@eq_rdvdp 0%N p); rewrite expr0 mulr1. Qed. Lemma rmodp_mull p : rmodp (p * d) d = 0. Proof. exact/eqP/rdvdp_mull. Qed. Lemma rmodpp : rmodp d d = 0. Proof. by rewrite -[d in rmodp d _]mul1r rmodp_mull. Qed. Lemma rdivpp : rdivp d d = (lead_coef d ^+ rscalp d d)%:P. Proof. have dn0 : d != 0 by rewrite -lead_coef_eq0 rreg_neq0. move: (rdivp_eq d); rewrite rmodpp addr0. suff ->: GRing.comm d (lead_coef d ^+ rscalp d d)%:P by move/(rreg_lead Rreg)->. by rewrite polyC_exp; apply: commrX. Qed. Lemma rdvdpp : rdvdp d d. Proof. exact/eqP/rmodpp. Qed. Lemma rdivpK p : rdvdp d p -> rdivp p d * d = p * (lead_coef d ^+ rscalp p d)%:P. Proof. by rewrite rdivp_eq /rdvdp; move/eqP->; rewrite addr0. Qed. End ComRegDivisor. End RingComRreg. Module RingMonic. Import CommonRing. Import RingComRreg. Section RingMonic. Variable R : ringType. Implicit Types p q r : {poly R}. Section MonicDivisor. Variable d : {poly R}. Hypothesis mond : d \is monic. Lemma redivp_eq q r : size r < size d -> let k := (redivp (q * d + r) d).1.1 in redivp (q * d + r) d = (k, q, r). Proof. case: (monic_comreg mond)=> Hc Hr /(redivp_eq Hc Hr q). by rewrite (eqP mond) => -> /=; rewrite expr1n !mulr1. Qed. Lemma rdivp_eq p : p = rdivp p d * d + rmodp p d. Proof. rewrite -rdivp_eq (eqP mond); last exact: commr1. by rewrite expr1n mulr1. Qed. Lemma rdivpp : rdivp d d = 1. Proof. by case: (monic_comreg mond) => hc hr; rewrite rdivpp // (eqP mond) expr1n. Qed. Lemma rdivp_addl_mul_small q r : size r < size d -> rdivp (q * d + r) d = q. Proof. by move=> Hd; case: (monic_comreg mond)=> Hc Hr; rewrite /rdivp redivp_eq. Qed. Lemma rdivp_addl_mul q r : rdivp (q * d + r) d = q + rdivp r d. Proof. case: (monic_comreg mond)=> Hc Hr; rewrite [r in _ * _ + r]rdivp_eq addrA. by rewrite -mulrDl rdivp_addl_mul_small // ltn_rmodp monic_neq0. Qed. Lemma rdivpDl q r : rdvdp d q -> rdivp (q + r) d = rdivp q d + rdivp r d. Proof. case: (monic_comreg mond)=> Hc Hr; rewrite [r in q + r]rdivp_eq addrA. rewrite [q in q + _ + _]rdivp_eq; move/rmodp_eq0P->. by rewrite addr0 -mulrDl rdivp_addl_mul_small // ltn_rmodp monic_neq0. Qed. Lemma rdivpDr q r : rdvdp d r -> rdivp (q + r) d = rdivp q d + rdivp r d. Proof. by rewrite addrC; move/rdivpDl->; rewrite addrC. Qed. Lemma rdivp_mull p : rdivp (p * d) d = p. Proof. by rewrite -[p * d]addr0 rdivp_addl_mul rdiv0p addr0. Qed. Lemma rmodp_mull p : rmodp (p * d) d = 0. Proof. by apply: rmodp_mull; rewrite (eqP mond); [apply: commr1 | apply: rreg1]. Qed. Lemma rmodpp : rmodp d d = 0. Proof. by apply: rmodpp; rewrite (eqP mond); [apply: commr1 | apply: rreg1]. Qed. Lemma rmodp_addl_mul_small q r : size r < size d -> rmodp (q * d + r) d = r. Proof. by move=> Hd; case: (monic_comreg mond)=> Hc Hr; rewrite /rmodp redivp_eq. Qed. Lemma rmodpD p q : rmodp (p + q) d = rmodp p d + rmodp q d. Proof. rewrite [p in LHS]rdivp_eq [q in LHS]rdivp_eq addrACA -mulrDl. rewrite rmodp_addl_mul_small //; apply: (leq_ltn_trans (size_add _ _)). by rewrite gtn_max !ltn_rmodp // monic_neq0. Qed. Lemma rmodp_mulmr p q : rmodp (p * (rmodp q d)) d = rmodp (p * q) d. Proof. by rewrite [q in RHS]rdivp_eq mulrDr rmodpD mulrA rmodp_mull add0r. Qed. Lemma rdvdpp : rdvdp d d. Proof. by apply: rdvdpp; rewrite (eqP mond); [apply: commr1 | apply: rreg1]. Qed. (* section variables impose an inconvenient order on parameters *) Lemma eq_rdvdp q1 p : p = q1 * d -> rdvdp d p. Proof. (* this probably means I need to specify impl args for comm_rref_rdvdp *) move=> h; apply: (@eq_rdvdp _ _ _ _ 1%N q1); rewrite (eqP mond). - exact: commr1. - exact: rreg1. by rewrite expr1n mulr1. Qed. Lemma rdvdp_mull p : rdvdp d (p * d). Proof. by apply: rdvdp_mull; rewrite (eqP mond) //; [apply: commr1 | apply: rreg1]. Qed. Lemma rdvdpP p : reflect (exists qq, p = qq * d) (rdvdp d p). Proof. case: (monic_comreg mond)=> Hc Hr; apply: (iffP idP) => [|[qq] /eq_rdvdp //]. by case: rdvdp_eqP=> // k qq; rewrite (eqP mond) expr1n mulr1 => ->; exists qq. Qed. Lemma rdivpK p : rdvdp d p -> (rdivp p d) * d = p. Proof. by move=> dvddp; rewrite [RHS]rdivp_eq rmodp_eq0 ?addr0. Qed. End MonicDivisor. Lemma drop_poly_rdivp n p : drop_poly n p = rdivp p 'X^n. Proof. rewrite -[p in RHS](poly_take_drop n) addrC rdivp_addl_mul ?monicXn//. by rewrite rdivp_small ?addr0// size_polyXn ltnS size_take_poly. Qed. Lemma take_poly_rmodp n p : take_poly n p = rmodp p 'X^n. Proof. have mX := monicXn R n; rewrite -[p in RHS](poly_take_drop n) rmodpD//. by rewrite rmodp_small ?rmodp_mull ?addr0// size_polyXn ltnS size_take_poly. Qed. End RingMonic. End RingMonic. Module Ring. Include CommonRing. Import RingMonic. Section ExtraMonicDivisor. Variable R : ringType. Implicit Types d p q r : {poly R}. Lemma rdivp1 p : rdivp p 1 = p. Proof. by rewrite -[p in LHS]mulr1 rdivp_mull // monic1. Qed. Lemma rdvdp_XsubCl p x : rdvdp ('X - x%:P) p = root p x. Proof. have [HcX Hr] := monic_comreg (monicXsubC x). apply/rmodp_eq0P/factor_theorem => [|[p1 ->]]; last exact/rmodp_mull/monicXsubC. move=> e0; exists (rdivp p ('X - x%:P)). by rewrite [LHS](rdivp_eq (monicXsubC x)) e0 addr0. Qed. Lemma polyXsubCP p x : reflect (p.[x] = 0) (rdvdp ('X - x%:P) p). Proof. by apply: (iffP idP); rewrite rdvdp_XsubCl; move/rootP. Qed. Lemma root_factor_theorem p x : root p x = (rdvdp ('X - x%:P) p). Proof. by rewrite rdvdp_XsubCl. Qed. End ExtraMonicDivisor. End Ring. Module ComRing. Import Ring. Import RingComRreg. Section CommutativeRingPseudoDivision. Variable R : comRingType. Implicit Types d p q m n r : {poly R}. Variant redivp_spec (m d : {poly R}) : nat * {poly R} * {poly R} -> Type := EdivnSpec k (q r: {poly R}) of (lead_coef d ^+ k) *: m = q * d + r & (d != 0 -> size r < size d) : redivp_spec m d (k, q, r). Lemma redivpP m d : redivp_spec m d (redivp m d). Proof. rewrite redivp_def; constructor; last by move=> dn0; rewrite ltn_rmodp. by rewrite -mul_polyC mulrC rdivp_eq //= /GRing.comm mulrC. Qed. Lemma rdivp_eq d p : (lead_coef d ^+ rscalp p d) *: p = rdivp p d * d + rmodp p d. Proof. by rewrite /rdivp /rmodp /rscalp; case: redivpP=> k q1 r1 Hc _; apply: Hc. Qed. Lemma rdvdp_eqP d p : rdvdp_spec p d (rmodp p d) (rdvdp d p). Proof. case hdvd: (rdvdp d p); last by move/rmodp_eq0P/eqP/RdvdpN: hdvd. move/rmodp_eq0P: (hdvd)->; apply: (@Rdvdp _ _ _ (rscalp p d) (rdivp p d)). by rewrite mulrC mul_polyC rdivp_eq; move/rmodp_eq0P: (hdvd)->; rewrite addr0. Qed. Lemma rdvdp_eq q p : rdvdp q p = (lead_coef q ^+ rscalp p q *: p == rdivp p q * q). Proof. rewrite rdivp_eq; apply/rmodp_eq0P/eqP => [->|/eqP]; first by rewrite addr0. by rewrite eq_sym addrC -subr_eq subrr; move/eqP<-. Qed. End CommutativeRingPseudoDivision. End ComRing. Module UnitRing. Import Ring. Section UnitRingPseudoDivision. Variable R : unitRingType. Implicit Type p q r d : {poly R}. Lemma uniq_roots_rdvdp p rs : all (root p) rs -> uniq_roots rs -> rdvdp (\prod_(z <- rs) ('X - z%:P)) p. Proof. move=> rrs /(uniq_roots_prod_XsubC rrs) [q ->]. exact/RingMonic.rdvdp_mull/monic_prod_XsubC. Qed. End UnitRingPseudoDivision. End UnitRing. Module IdomainDefs. Import Ring. Section IDomainPseudoDivisionDefs. Variable R : idomainType. Implicit Type p q r d : {poly R}. Definition edivp_expanded_def p q := let: (k, d, r) as edvpq := redivp p q in if lead_coef q \in GRing.unit then (0%N, (lead_coef q)^-k *: d, (lead_coef q)^-k *: r) else edvpq. Fact edivp_key : unit. Proof. by []. Qed. Definition edivp := locked_with edivp_key edivp_expanded_def. Canonical edivp_unlockable := [unlockable fun edivp]. Definition divp p q := ((edivp p q).1).2. Definition modp p q := (edivp p q).2. Definition scalp p q := ((edivp p q).1).1. Definition dvdp p q := modp q p == 0. Definition eqp p q := (dvdp p q) && (dvdp q p). End IDomainPseudoDivisionDefs. Notation "m %/ d" := (divp m d) : ring_scope. Notation "m %% d" := (modp m d) : ring_scope. Notation "p %| q" := (dvdp p q) : ring_scope. Notation "p %= q" := (eqp p q) : ring_scope. End IdomainDefs. Module WeakIdomain. Import Ring ComRing UnitRing IdomainDefs. Section WeakTheoryForIDomainPseudoDivision. Variable R : idomainType. Implicit Type p q r d : {poly R}. Lemma edivp_def p q : edivp p q = (scalp p q, divp p q, modp p q). Proof. by rewrite /scalp /divp /modp; case: (edivp p q) => [[]] /=. Qed. Lemma edivp_redivp p q : lead_coef q \in GRing.unit = false -> edivp p q = redivp p q. Proof. by move=> hu; rewrite unlock hu; case: (redivp p q) => [[? ?] ?]. Qed. Lemma divpE p q : p %/ q = if lead_coef q \in GRing.unit then lead_coef q ^- rscalp p q *: rdivp p q else rdivp p q. Proof. by case: ifP; rewrite /divp unlock redivp_def => ->. Qed. Lemma modpE p q : p %% q = if lead_coef q \in GRing.unit then lead_coef q ^- rscalp p q *: (rmodp p q) else rmodp p q. Proof. by case: ifP; rewrite /modp unlock redivp_def => ->. Qed. Lemma scalpE p q : scalp p q = if lead_coef q \in GRing.unit then 0%N else rscalp p q. Proof. by case: ifP; rewrite /scalp unlock redivp_def => ->. Qed. Lemma dvdpE p q : p %| q = rdvdp p q. Proof. rewrite /dvdp modpE /rdvdp; case ulcq: (lead_coef p \in GRing.unit)=> //. rewrite -[in LHS]size_poly_eq0 size_scale ?size_poly_eq0 //. by rewrite invr_eq0 expf_neq0 //; apply: contraTneq ulcq => ->; rewrite unitr0. Qed. Lemma lc_expn_scalp_neq0 p q : lead_coef q ^+ scalp p q != 0. Proof. have [->|nzq] := eqVneq q 0; last by rewrite expf_neq0 ?lead_coef_eq0. by rewrite /scalp 2!unlock /= eqxx lead_coef0 unitr0 /= oner_neq0. Qed. Hint Resolve lc_expn_scalp_neq0 : core. Variant edivp_spec (m d : {poly R}) : nat * {poly R} * {poly R} -> bool -> Type := |Redivp_spec k (q r: {poly R}) of (lead_coef d ^+ k) *: m = q * d + r & lead_coef d \notin GRing.unit & (d != 0 -> size r < size d) : edivp_spec m d (k, q, r) false |Fedivp_spec (q r: {poly R}) of m = q * d + r & (lead_coef d \in GRing.unit) & (d != 0 -> size r < size d) : edivp_spec m d (0%N, q, r) true. (* There are several ways to state this fact. The most appropriate statement*) (* might be polished in light of usage. *) Lemma edivpP m d : edivp_spec m d (edivp m d) (lead_coef d \in GRing.unit). Proof. have hC : GRing.comm d (lead_coef d)%:P by rewrite /GRing.comm mulrC. case ud: (lead_coef d \in GRing.unit); last first. rewrite edivp_redivp // redivp_def; constructor; rewrite ?ltn_rmodp // ?ud //. by rewrite rdivp_eq. have cdn0: lead_coef d != 0 by apply: contraTneq ud => ->; rewrite unitr0. rewrite unlock ud redivp_def; constructor => //. rewrite -scalerAl -scalerDr -mul_polyC. have hn0 : (lead_coef d ^+ rscalp m d)%:P != 0. by rewrite polyC_eq0; apply: expf_neq0. apply: (mulfI hn0); rewrite !mulrA -exprVn !polyC_exp -exprMn -polyCM. by rewrite divrr // expr1n mul1r -polyC_exp mul_polyC rdivp_eq. move=> dn0; rewrite size_scale ?ltn_rmodp // -exprVn expf_eq0 negb_and. by rewrite invr_eq0 cdn0 orbT. Qed. Lemma edivp_eq d q r : size r < size d -> lead_coef d \in GRing.unit -> edivp (q * d + r) d = (0%N, q, r). Proof. have hC : GRing.comm d (lead_coef d)%:P by apply: mulrC. move=> hsrd hu; rewrite unlock hu; case et: (redivp _ _) => [[s qq] rr]. have cdn0 : lead_coef d != 0 by case: eqP hu => //= ->; rewrite unitr0. move: (et); rewrite RingComRreg.redivp_eq //; last exact/rregP. rewrite et /= mulrC (mulrC r) !mul_polyC; case=> <- <-. by rewrite !scalerA mulVr ?scale1r // unitrX. Qed. Lemma divp_eq p q : (lead_coef q ^+ scalp p q) *: p = (p %/ q) * q + (p %% q). Proof. rewrite divpE modpE scalpE. case uq: (lead_coef q \in GRing.unit); last by rewrite rdivp_eq. rewrite expr0 scale1r; have [->|qn0] := eqVneq q 0. by rewrite lead_coef0 expr0n /rscalp unlock eqxx invr1 !scale1r rmodp0 !simp. by rewrite -scalerAl -scalerDr -rdivp_eq scalerA mulVr (scale1r, unitrX). Qed. Lemma dvdp_eq q p : (q %| p) = (lead_coef q ^+ scalp p q *: p == (p %/ q) * q). Proof. rewrite dvdpE rdvdp_eq scalpE divpE; case: ifP => ulcq //. rewrite expr0 scale1r -scalerAl; apply/eqP/eqP => [<- | {2}->]. by rewrite scalerA mulVr ?scale1r // unitrX. by rewrite scalerA mulrV ?scale1r // unitrX. Qed. Lemma divpK d p : d %| p -> p %/ d * d = (lead_coef d ^+ scalp p d) *: p. Proof. by rewrite dvdp_eq; move/eqP->. Qed. Lemma divpKC d p : d %| p -> d * (p %/ d) = (lead_coef d ^+ scalp p d) *: p. Proof. by move=> ?; rewrite mulrC divpK. Qed. Lemma dvdpP q p : reflect (exists2 cqq, cqq.1 != 0 & cqq.1 *: p = cqq.2 * q) (q %| p). Proof. rewrite dvdp_eq; apply: (iffP eqP) => [e | [[c qq] cn0 e]]. by exists (lead_coef q ^+ scalp p q, p %/ q) => //=. apply/eqP; rewrite -dvdp_eq dvdpE. have Ecc: c%:P != 0 by rewrite polyC_eq0. have [->|nz_p] := eqVneq p 0; first by rewrite rdvdp0. pose p1 : {poly R} := lead_coef q ^+ rscalp p q *: qq - c *: (rdivp p q). have E1: c *: rmodp p q = p1 * q. rewrite mulrDl mulNr -scalerAl -e scalerA mulrC -scalerA -scalerAl. by rewrite -scalerBr rdivp_eq addrC addKr. suff: p1 * q == 0 by rewrite -E1 -mul_polyC mulf_eq0 (negPf Ecc). rewrite mulf_eq0; apply/norP; case=> p1_nz q_nz; have:= ltn_rmodp p q. by rewrite q_nz -(size_scale _ cn0) E1 size_mul // polySpred // ltnNge leq_addl. Qed. Lemma mulpK p q : q != 0 -> p * q %/ q = lead_coef q ^+ scalp (p * q) q *: p. Proof. move=> qn0; apply: (rregP qn0); rewrite -scalerAl divp_eq. suff -> : (p * q) %% q = 0 by rewrite addr0. rewrite modpE RingComRreg.rmodp_mull ?scaler0 ?if_same //. by red; rewrite mulrC. by apply/rregP; rewrite lead_coef_eq0. Qed. Lemma mulKp p q : q != 0 -> q * p %/ q = lead_coef q ^+ scalp (p * q) q *: p. Proof. by move=> nzq; rewrite mulrC; apply: mulpK. Qed. Lemma divpp p : p != 0 -> p %/ p = (lead_coef p ^+ scalp p p)%:P. Proof. move=> np0; have := divp_eq p p. suff -> : p %% p = 0 by rewrite addr0 -mul_polyC; move/(mulIf np0). rewrite modpE Ring.rmodpp; last by red; rewrite mulrC. by rewrite scaler0 if_same. Qed. End WeakTheoryForIDomainPseudoDivision. #[global] Hint Resolve lc_expn_scalp_neq0 : core. End WeakIdomain. Module CommonIdomain. Import Ring ComRing UnitRing IdomainDefs WeakIdomain. Section IDomainPseudoDivision. Variable R : idomainType. Implicit Type p q r d m n : {poly R}. Lemma scalp0 p : scalp p 0 = 0%N. Proof. by rewrite /scalp unlock lead_coef0 unitr0 unlock eqxx. Qed. Lemma divp_small p q : size p < size q -> p %/ q = 0. Proof. move=> spq; rewrite /divp unlock redivp_def /=. by case: ifP; rewrite rdivp_small // scaler0. Qed. Lemma leq_divp p q : (size (p %/ q) <= size p). Proof. rewrite /divp unlock redivp_def /=; case: ifP => ulcq; rewrite ?leq_rdivp //=. rewrite size_scale ?leq_rdivp // -exprVn expf_neq0 // invr_eq0. by case: eqP ulcq => // ->; rewrite unitr0. Qed. Lemma div0p p : 0 %/ p = 0. Proof. by rewrite /divp unlock redivp_def /=; case: ifP; rewrite rdiv0p // scaler0. Qed. Lemma divp0 p : p %/ 0 = 0. Proof. by rewrite /divp unlock redivp_def /=; case: ifP; rewrite rdivp0 // scaler0. Qed. Lemma divp1 m : m %/ 1 = m. Proof. by rewrite divpE lead_coefC unitr1 Ring.rdivp1 expr1n invr1 scale1r. Qed. Lemma modp0 p : p %% 0 = p. Proof. rewrite /modp unlock redivp_def; case: ifP; rewrite rmodp0 //= lead_coef0. by rewrite unitr0. Qed. Lemma mod0p p : 0 %% p = 0. Proof. by rewrite /modp unlock redivp_def /=; case: ifP; rewrite rmod0p // scaler0. Qed. Lemma modp1 p : p %% 1 = 0. Proof. by rewrite /modp unlock redivp_def /=; case: ifP; rewrite rmodp1 // scaler0. Qed. Hint Resolve divp0 divp1 mod0p modp0 modp1 : core. Lemma modp_small p q : size p < size q -> p %% q = p. Proof. move=> spq; rewrite /modp unlock redivp_def; case: ifP; rewrite rmodp_small //. by rewrite /= rscalp_small // expr0 /= invr1 scale1r. Qed. Lemma modpC p c : c != 0 -> p %% c%:P = 0. Proof. move=> cn0; rewrite /modp unlock redivp_def /=; case: ifP; rewrite ?rmodpC //. by rewrite scaler0. Qed. Lemma modp_mull p q : (p * q) %% q = 0. Proof. have [-> | nq0] := eqVneq q 0; first by rewrite modp0 mulr0. have rlcq : GRing.rreg (lead_coef q) by apply/rregP; rewrite lead_coef_eq0. have hC : GRing.comm q (lead_coef q)%:P by red; rewrite mulrC. by rewrite modpE; case: ifP => ulcq; rewrite RingComRreg.rmodp_mull // scaler0. Qed. Lemma modp_mulr d p : (d * p) %% d = 0. Proof. by rewrite mulrC modp_mull. Qed. Lemma modpp d : d %% d = 0. Proof. by rewrite -[d in d %% _]mul1r modp_mull. Qed. Lemma ltn_modp p q : (size (p %% q) < size q) = (q != 0). Proof. rewrite /modp unlock redivp_def /=; case: ifP=> ulcq; rewrite ?ltn_rmodp //=. rewrite size_scale ?ltn_rmodp // -exprVn expf_neq0 // invr_eq0. by case: eqP ulcq => // ->; rewrite unitr0. Qed. Lemma ltn_divpl d q p : d != 0 -> (size (q %/ d) < size p) = (size q < size (p * d)). Proof. move=> dn0. have: (lead_coef d) ^+ (scalp q d) != 0 by apply: lc_expn_scalp_neq0. move/(size_scale q)<-; rewrite divp_eq; have [->|quo0] := eqVneq (q %/ d) 0. rewrite mul0r add0r size_poly0 size_poly_gt0. have [->|pn0] := eqVneq p 0; first by rewrite mul0r size_poly0 ltn0. by rewrite size_mul // (polySpred pn0) addSn ltn_addl // ltn_modp. rewrite size_addl; last first. by rewrite size_mul // (polySpred quo0) addSn /= ltn_addl // ltn_modp. have [->|pn0] := eqVneq p 0; first by rewrite mul0r size_poly0 !ltn0. by rewrite !size_mul ?quo0 // (polySpred dn0) !addnS ltn_add2r. Qed. Lemma leq_divpr d p q : d != 0 -> (size p <= size (q %/ d)) = (size (p * d) <= size q). Proof. by move=> dn0; rewrite leqNgt ltn_divpl // -leqNgt. Qed. Lemma divpN0 d p : d != 0 -> (p %/ d != 0) = (size d <= size p). Proof. move=> dn0. by rewrite -[d in RHS]mul1r -leq_divpr // size_polyC oner_eq0 size_poly_gt0. Qed. Lemma size_divp p q : q != 0 -> size (p %/ q) = (size p - (size q).-1)%N. Proof. move=> nq0; case: (leqP (size q) (size p)) => sqp; last first. move: (sqp); rewrite -{1}(ltn_predK sqp) ltnS -subn_eq0 divp_small //. by move/eqP->; rewrite size_poly0. have np0 : p != 0. by rewrite -size_poly_gt0; apply: leq_trans sqp; rewrite size_poly_gt0. have /= := congr1 (size \o @polyseq R) (divp_eq p q). rewrite size_scale; last by rewrite expf_eq0 lead_coef_eq0 (negPf nq0) andbF. have [->|qq0] := eqVneq (p %/ q) 0. by rewrite mul0r add0r=> es; move: nq0; rewrite -(ltn_modp p) -es ltnNge sqp. rewrite size_addl. by move->; apply/eqP; rewrite size_mul // (polySpred nq0) addnS /= addnK. rewrite size_mul ?qq0 //. move: nq0; rewrite -(ltn_modp p); move/leq_trans; apply. by rewrite (polySpred qq0) addSn /= leq_addl. Qed. Lemma ltn_modpN0 p q : q != 0 -> size (p %% q) < size q. Proof. by rewrite ltn_modp. Qed. Lemma modp_mod p q : (p %% q) %% q = p %% q. Proof. by have [->|qn0] := eqVneq q 0; rewrite ?modp0 // modp_small ?ltn_modp. Qed. Lemma leq_modp m d : size (m %% d) <= size m. Proof. rewrite /modp unlock redivp_def /=; case: ifP; rewrite ?leq_rmodp //. move=> ud; rewrite size_scale ?leq_rmodp // invr_eq0 expf_neq0 //. by apply: contraTneq ud => ->; rewrite unitr0. Qed. Lemma dvdp0 d : d %| 0. Proof. by rewrite /dvdp mod0p. Qed. Hint Resolve dvdp0 : core. Lemma dvd0p p : (0 %| p) = (p == 0). Proof. by rewrite /dvdp modp0. Qed. Lemma dvd0pP p : reflect (p = 0) (0 %| p). Proof. by apply: (iffP idP); rewrite dvd0p; move/eqP. Qed. Lemma dvdpN0 p q : p %| q -> q != 0 -> p != 0. Proof. by move=> pq hq; apply: contraTneq pq => ->; rewrite dvd0p. Qed. Lemma dvdp1 d : (d %| 1) = (size d == 1%N). Proof. rewrite /dvdp modpE; case ud: (lead_coef d \in GRing.unit); last exact: rdvdp1. rewrite -size_poly_eq0 size_scale; first by rewrite size_poly_eq0 -rdvdp1. by rewrite invr_eq0 expf_neq0 //; apply: contraTneq ud => ->; rewrite unitr0. Qed. Lemma dvd1p m : 1 %| m. Proof. by rewrite /dvdp modp1. Qed. Lemma gtNdvdp p q : p != 0 -> size p < size q -> (q %| p) = false. Proof. by move=> nn0 hs; rewrite /dvdp; rewrite (modp_small hs); apply: negPf. Qed. Lemma modp_eq0P p q : reflect (p %% q = 0) (q %| p). Proof. exact: (iffP eqP). Qed. Lemma modp_eq0 p q : (q %| p) -> p %% q = 0. Proof. exact: modp_eq0P. Qed. Lemma leq_divpl d p q : d %| p -> (size (p %/ d) <= size q) = (size p <= size (q * d)). Proof. case: (eqVneq d 0) => [-> /dvd0pP -> | nd0 hd]. by rewrite divp0 size_poly0 !leq0n. rewrite leq_eqVlt ltn_divpl // (leq_eqVlt (size p)). case lhs: (size p < size (q * d)); rewrite ?orbT ?orbF //. have: (lead_coef d) ^+ (scalp p d) != 0 by rewrite expf_neq0 // lead_coef_eq0. move/(size_scale p)<-; rewrite divp_eq; move/modp_eq0P: hd->; rewrite addr0. have [-> | quon0] := eqVneq (p %/ d) 0. rewrite mul0r size_poly0 2!(eq_sym 0%N) !size_poly_eq0. by rewrite mulf_eq0 (negPf nd0) orbF. have [-> | nq0] := eqVneq q 0. by rewrite mul0r size_poly0 !size_poly_eq0 mulf_eq0 (negPf nd0) orbF. by rewrite !size_mul // (polySpred nd0) !addnS /= eqn_add2r. Qed. Lemma dvdp_leq p q : q != 0 -> p %| q -> size p <= size q. Proof. move=> nq0 /modp_eq0P. by case: leqP => // /modp_small -> /eqP; rewrite (negPf nq0). Qed. Lemma eq_dvdp c quo q p : c != 0 -> c *: p = quo * q -> q %| p. Proof. move=> cn0; case: (eqVneq p 0) => [->|nz_quo def_quo] //. pose p1 : {poly R} := lead_coef q ^+ scalp p q *: quo - c *: (p %/ q). have E1: c *: (p %% q) = p1 * q. rewrite mulrDl mulNr -scalerAl -def_quo scalerA mulrC -scalerA. by rewrite -scalerAl -scalerBr divp_eq addrAC subrr add0r. rewrite /dvdp; apply/idPn=> m_nz. have: p1 * q != 0 by rewrite -E1 -mul_polyC mulf_neq0 // polyC_eq0. rewrite mulf_eq0; case/norP=> p1_nz q_nz. have := ltn_modp p q; rewrite q_nz -(size_scale (p %% q) cn0) E1. by rewrite size_mul // polySpred // ltnNge leq_addl. Qed. Lemma dvdpp d : d %| d. Proof. by rewrite /dvdp modpp. Qed. Hint Resolve dvdpp : core. Lemma divp_dvd p q : p %| q -> (q %/ p) %| q. Proof. have [-> | np0] := eqVneq p 0; first by rewrite divp0. rewrite dvdp_eq => /eqP h. apply: (@eq_dvdp ((lead_coef p)^+ (scalp q p)) p); last by rewrite mulrC. by rewrite expf_neq0 // lead_coef_eq0. Qed. Lemma dvdp_mull m d n : d %| n -> d %| m * n. Proof. case: (eqVneq d 0) => [-> /dvd0pP -> | dn0]; first by rewrite mulr0 dvdpp. rewrite dvdp_eq => /eqP e. apply: (@eq_dvdp (lead_coef d ^+ scalp n d) (m * (n %/ d))). by rewrite expf_neq0 // lead_coef_eq0. by rewrite scalerAr e mulrA. Qed. Lemma dvdp_mulr n d m : d %| m -> d %| m * n. Proof. by move=> hdm; rewrite mulrC dvdp_mull. Qed. Hint Resolve dvdp_mull dvdp_mulr : core. Lemma dvdp_mul d1 d2 m1 m2 : d1 %| m1 -> d2 %| m2 -> d1 * d2 %| m1 * m2. Proof. case: (eqVneq d1 0) => [-> /dvd0pP -> | d1n0]; first by rewrite !mul0r dvdpp. case: (eqVneq d2 0) => [-> _ /dvd0pP -> | d2n0]; first by rewrite !mulr0. rewrite dvdp_eq; set c1 := _ ^+ _; set q1 := _ %/ _; move/eqP=> Hq1. rewrite dvdp_eq; set c2 := _ ^+ _; set q2 := _ %/ _; move/eqP=> Hq2. apply: (@eq_dvdp (c1 * c2) (q1 * q2)). by rewrite mulf_neq0 // expf_neq0 // lead_coef_eq0. rewrite -scalerA scalerAr scalerAl Hq1 Hq2 -!mulrA. by rewrite [d1 * (q2 * _)]mulrCA. Qed. Lemma dvdp_addr m d n : d %| m -> (d %| m + n) = (d %| n). Proof. case: (eqVneq d 0) => [-> /dvd0pP -> | dn0]; first by rewrite add0r. rewrite dvdp_eq; set c1 := _ ^+ _; set q1 := _ %/ _; move/eqP=> Eq1. apply/idP/idP; rewrite dvdp_eq; set c2 := _ ^+ _; set q2 := _ %/ _. have sn0 : c1 * c2 != 0. by rewrite !mulf_neq0 // expf_eq0 lead_coef_eq0 (negPf dn0) andbF. move/eqP=> Eq2; apply: (@eq_dvdp _ (c1 *: q2 - c2 *: q1) _ _ sn0). rewrite mulrDl -scaleNr -!scalerAl -Eq1 -Eq2 !scalerA. by rewrite mulNr mulrC scaleNr -scalerBr addrC addKr. have sn0 : c1 * c2 != 0. by rewrite !mulf_neq0 // expf_eq0 lead_coef_eq0 (negPf dn0) andbF. move/eqP=> Eq2; apply: (@eq_dvdp _ (c1 *: q2 + c2 *: q1) _ _ sn0). by rewrite mulrDl -!scalerAl -Eq1 -Eq2 !scalerA mulrC addrC scalerDr. Qed. Lemma dvdp_addl n d m : d %| n -> (d %| m + n) = (d %| m). Proof. by rewrite addrC; apply: dvdp_addr. Qed. Lemma dvdp_add d m n : d %| m -> d %| n -> d %| m + n. Proof. by move/dvdp_addr->. Qed. Lemma dvdp_add_eq d m n : d %| m + n -> (d %| m) = (d %| n). Proof. by move=> ?; apply/idP/idP; [move/dvdp_addr <-| move/dvdp_addl <-]. Qed. Lemma dvdp_subr d m n : d %| m -> (d %| m - n) = (d %| n). Proof. by move=> ?; apply: dvdp_add_eq; rewrite -addrA addNr simp. Qed. Lemma dvdp_subl d m n : d %| n -> (d %| m - n) = (d %| m). Proof. by move/dvdp_addl<-; rewrite subrK. Qed. Lemma dvdp_sub d m n : d %| m -> d %| n -> d %| m - n. Proof. by move=> *; rewrite dvdp_subl. Qed. Lemma dvdp_mod d n m : d %| n -> (d %| m) = (d %| m %% n). Proof. have [-> | nn0] := eqVneq n 0; first by rewrite modp0. case: (eqVneq d 0) => [-> /dvd0pP -> | dn0]; first by rewrite modp0. rewrite dvdp_eq; set c1 := _ ^+ _; set q1 := _ %/ _; move/eqP=> Eq1. apply/idP/idP; rewrite dvdp_eq; set c2 := _ ^+ _; set q2 := _ %/ _. have sn0 : c1 * c2 != 0. by rewrite !mulf_neq0 // expf_eq0 lead_coef_eq0 (negPf dn0) andbF. pose quo := (c1 * lead_coef n ^+ scalp m n) *: q2 - c2 *: (m %/ n) * q1. move/eqP=> Eq2; apply: (@eq_dvdp _ quo _ _ sn0). rewrite mulrDl mulNr -!scalerAl -!mulrA -Eq1 -Eq2 -scalerAr !scalerA. rewrite mulrC [_ * c2]mulrC mulrA -[((_ * _) * _) *: _]scalerA -scalerBr. by rewrite divp_eq addrC addKr. have sn0 : c1 * c2 * lead_coef n ^+ scalp m n != 0. rewrite !mulf_neq0 // expf_eq0 lead_coef_eq0 ?(negPf dn0) ?andbF //. by rewrite (negPf nn0) andbF. move/eqP=> Eq2; apply: (@eq_dvdp _ (c2 *: (m %/ n) * q1 + c1 *: q2) _ _ sn0). rewrite -scalerA divp_eq scalerDr -!scalerA Eq2 scalerAl scalerAr Eq1. by rewrite scalerAl mulrDl mulrA. Qed. Lemma dvdp_trans : transitive (@dvdp R). Proof. move=> n d m. case: (eqVneq d 0) => [-> /dvd0pP -> // | dn0]. case: (eqVneq n 0) => [-> _ /dvd0pP -> // | nn0]. rewrite dvdp_eq; set c1 := _ ^+ _; set q1 := _ %/ _; move/eqP=> Hq1. rewrite dvdp_eq; set c2 := _ ^+ _; set q2 := _ %/ _; move/eqP=> Hq2. have sn0 : c1 * c2 != 0 by rewrite mulf_neq0 // expf_neq0 // lead_coef_eq0. by apply: (@eq_dvdp _ (q2 * q1) _ _ sn0); rewrite -scalerA Hq2 scalerAr Hq1 mulrA. Qed. Lemma dvdp_mulIl p q : p %| p * q. Proof. exact/dvdp_mulr/dvdpp. Qed. Lemma dvdp_mulIr p q : q %| p * q. Proof. exact/dvdp_mull/dvdpp. Qed. Lemma dvdp_mul2r r p q : r != 0 -> (p * r %| q * r) = (p %| q). Proof. move=> nzr. have [-> | pn0] := eqVneq p 0. by rewrite mul0r !dvd0p mulf_eq0 (negPf nzr) orbF. have [-> | qn0] := eqVneq q 0; first by rewrite mul0r !dvdp0. apply/idP/idP; last by move=> ?; rewrite dvdp_mul ?dvdpp. rewrite dvdp_eq; set c := _ ^+ _; set x := _ %/ _; move/eqP=> Hx. apply: (@eq_dvdp c x); first by rewrite expf_neq0 // lead_coef_eq0 mulf_neq0. by apply: (mulIf nzr); rewrite -mulrA -scalerAl. Qed. Lemma dvdp_mul2l r p q: r != 0 -> (r * p %| r * q) = (p %| q). Proof. by rewrite ![r * _]mulrC; apply: dvdp_mul2r. Qed. Lemma ltn_divpr d p q : d %| q -> (size p < size (q %/ d)) = (size (p * d) < size q). Proof. by move=> dv_d_q; rewrite !ltnNge leq_divpl. Qed. Lemma dvdp_exp d k p : 0 < k -> d %| p -> d %| (p ^+ k). Proof. by case: k => // k _ d_dv_m; rewrite exprS dvdp_mulr. Qed. Lemma dvdp_exp2l d k l : k <= l -> d ^+ k %| d ^+ l. Proof. by move/subnK <-; rewrite exprD dvdp_mull // ?lead_coef_exp ?unitrX. Qed. Lemma dvdp_Pexp2l d k l : 1 < size d -> (d ^+ k %| d ^+ l) = (k <= l). Proof. move=> sd; case: leqP => [|gt_n_m]; first exact: dvdp_exp2l. have dn0 : d != 0 by rewrite -size_poly_gt0; apply: ltn_trans sd. rewrite gtNdvdp ?expf_neq0 // polySpred ?expf_neq0 // size_exp /=. rewrite [size (d ^+ k)]polySpred ?expf_neq0 // size_exp ltnS ltn_mul2l. by move: sd; rewrite -subn_gt0 subn1; move->. Qed. Lemma dvdp_exp2r p q k : p %| q -> p ^+ k %| q ^+ k. Proof. case: (eqVneq p 0) => [-> /dvd0pP -> // | pn0]. rewrite dvdp_eq; set c := _ ^+ _; set t := _ %/ _; move/eqP=> e. apply: (@eq_dvdp (c ^+ k) (t ^+ k)); first by rewrite !expf_neq0 ?lead_coef_eq0. by rewrite -exprMn -exprZn; congr (_ ^+ k). Qed. Lemma dvdp_exp_sub p q k l: p != 0 -> (p ^+ k %| q * p ^+ l) = (p ^+ (k - l) %| q). Proof. move=> pn0; case: (leqP k l)=> [|/ltnW] hkl. move: (hkl); rewrite -subn_eq0; move/eqP->; rewrite expr0 dvd1p. exact/dvdp_mull/dvdp_exp2l. by rewrite -[in LHS](subnK hkl) exprD dvdp_mul2r // expf_eq0 (negPf pn0) andbF. Qed. Lemma dvdp_XsubCl p x : ('X - x%:P) %| p = root p x. Proof. by rewrite dvdpE; apply: Ring.rdvdp_XsubCl. Qed. Lemma polyXsubCP p x : reflect (p.[x] = 0) (('X - x%:P) %| p). Proof. by rewrite dvdpE; apply: Ring.polyXsubCP. Qed. Lemma eqp_div_XsubC p c : (p == (p %/ ('X - c%:P)) * ('X - c%:P)) = ('X - c%:P %| p). Proof. by rewrite dvdp_eq lead_coefXsubC expr1n scale1r. Qed. Lemma root_factor_theorem p x : root p x = (('X - x%:P) %| p). Proof. by rewrite dvdp_XsubCl. Qed. Lemma uniq_roots_dvdp p rs : all (root p) rs -> uniq_roots rs -> (\prod_(z <- rs) ('X - z%:P)) %| p. Proof. move=> rrs; case/(uniq_roots_prod_XsubC rrs)=> q ->. by apply: dvdp_mull; rewrite // (eqP (monic_prod_XsubC _)) unitr1. Qed. Lemma root_bigmul x (ps : seq {poly R}) : ~~root (\big[*%R/1]_(p <- ps) p) x = all (fun p => ~~ root p x) ps. Proof. elim: ps => [|p ps ihp]; first by rewrite big_nil root1. by rewrite big_cons /= rootM negb_or ihp. Qed. Lemma eqpP m n : reflect (exists2 c12, (c12.1 != 0) && (c12.2 != 0) & c12.1 *: m = c12.2 *: n) (m %= n). Proof. apply: (iffP idP) => [| [[c1 c2]/andP[nz_c1 nz_c2 eq_cmn]]]; last first. rewrite /eqp (@eq_dvdp c2 c1%:P) -?eq_cmn ?mul_polyC // (@eq_dvdp c1 c2%:P) //. by rewrite eq_cmn mul_polyC. case: (eqVneq m 0) => [-> /andP [/dvd0pP -> _] | m_nz]. by exists (1, 1); rewrite ?scaler0 // oner_eq0. case: (eqVneq n 0) => [-> /andP [_ /dvd0pP ->] | n_nz /andP []]. by exists (1, 1); rewrite ?scaler0 // oner_eq0. rewrite !dvdp_eq; set c1 := _ ^+ _; set c2 := _ ^+ _. set q1 := _ %/ _; set q2 := _ %/ _; move/eqP => Hq1 /eqP Hq2; have Hc1 : c1 != 0 by rewrite expf_eq0 lead_coef_eq0 negb_and m_nz orbT. have Hc2 : c2 != 0 by rewrite expf_eq0 lead_coef_eq0 negb_and n_nz orbT. have def_q12: q1 * q2 = (c1 * c2)%:P. apply: (mulIf m_nz); rewrite mulrAC mulrC -Hq1 -scalerAr -Hq2 scalerA. by rewrite -mul_polyC. have: q1 * q2 != 0 by rewrite def_q12 -size_poly_eq0 size_polyC mulf_neq0. rewrite mulf_eq0; case/norP=> nz_q1 nz_q2. have: size q2 <= 1%N. have:= size_mul nz_q1 nz_q2; rewrite def_q12 size_polyC mulf_neq0 //=. by rewrite polySpred // => ->; rewrite leq_addl. rewrite leq_eqVlt ltnS size_poly_leq0 (negPf nz_q2) orbF. case/size_poly1P=> c cn0 cqe; exists (c2, c); first by rewrite Hc2. by rewrite Hq2 -mul_polyC -cqe. Qed. Lemma eqp_eq p q: p %= q -> (lead_coef q) *: p = (lead_coef p) *: q. Proof. move=> /eqpP [[c1 c2] /= /andP [nz_c1 nz_c2]] eq. have/(congr1 lead_coef) := eq; rewrite !lead_coefZ. move=> eqC; apply/(@mulfI _ c2%:P); rewrite ?polyC_eq0 //. by rewrite !mul_polyC scalerA -eqC mulrC -scalerA eq !scalerA mulrC. Qed. Lemma eqpxx : reflexive (@eqp R). Proof. by move=> p; rewrite /eqp dvdpp. Qed. Hint Resolve eqpxx : core. Lemma eqp_sym : symmetric (@eqp R). Proof. by move=> p q; rewrite /eqp andbC. Qed. Lemma eqp_trans : transitive (@eqp R). Proof. move=> p q r; case/andP=> Dp pD; case/andP=> Dq qD. by rewrite /eqp (dvdp_trans Dp) // (dvdp_trans qD). Qed. Lemma eqp_ltrans : left_transitive (@eqp R). Proof. exact: sym_left_transitive eqp_sym eqp_trans. Qed. Lemma eqp_rtrans : right_transitive (@eqp R). Proof. exact: sym_right_transitive eqp_sym eqp_trans. Qed. Lemma eqp0 p : (p %= 0) = (p == 0). Proof. by apply/idP/eqP => [/andP [_ /dvd0pP] | -> //]. Qed. Lemma eqp01 : 0 %= (1 : {poly R}) = false. Proof. by rewrite eqp_sym eqp0 oner_eq0. Qed. Lemma eqp_scale p c : c != 0 -> c *: p %= p. Proof. move=> c0; apply/eqpP; exists (1, c); first by rewrite c0 oner_eq0. by rewrite scale1r. Qed. Lemma eqp_size p q : p %= q -> size p = size q. Proof. have [->|Eq] := eqVneq q 0; first by rewrite eqp0; move/eqP->. rewrite eqp_sym; have [->|Ep] := eqVneq p 0; first by rewrite eqp0; move/eqP->. by case/andP => Dp Dq; apply: anti_leq; rewrite !dvdp_leq. Qed. Lemma size_poly_eq1 p : (size p == 1%N) = (p %= 1). Proof. apply/size_poly1P/idP=> [[c cn0 ep] |]. by apply/eqpP; exists (1, c); rewrite ?oner_eq0 // alg_polyC scale1r. by move/eqp_size; rewrite size_poly1; move/eqP/size_poly1P. Qed. Lemma polyXsubC_eqp1 (x : R) : ('X - x%:P %= 1) = false. Proof. by rewrite -size_poly_eq1 size_XsubC. Qed. Lemma dvdp_eqp1 p q : p %| q -> q %= 1 -> p %= 1. Proof. move=> dpq hq. have sizeq : size q == 1%N by rewrite size_poly_eq1. have n0q : q != 0 by case: eqP hq => // ->; rewrite eqp01. rewrite -size_poly_eq1 eqn_leq -{1}(eqP sizeq) dvdp_leq //= size_poly_gt0. by apply/eqP => p0; move: dpq n0q; rewrite p0 dvd0p => ->. Qed. Lemma eqp_dvdr q p d: p %= q -> d %| p = (d %| q). Proof. suff Hmn m n: m %= n -> (d %| m) -> (d %| n). by move=> mn; apply/idP/idP; apply: Hmn=> //; rewrite eqp_sym. by rewrite /eqp; case/andP=> pq qp dp; apply: (dvdp_trans dp). Qed. Lemma eqp_dvdl d2 d1 p : d1 %= d2 -> d1 %| p = (d2 %| p). suff Hmn m n: m %= n -> (m %| p) -> (n %| p). by move=> ?; apply/idP/idP; apply: Hmn; rewrite // eqp_sym. by rewrite /eqp; case/andP=> dd' d'd dp; apply: (dvdp_trans d'd). Qed. Lemma dvdpZr c m n : c != 0 -> m %| c *: n = (m %| n). Proof. by move=> cn0; exact/eqp_dvdr/eqp_scale. Qed. Lemma dvdpZl c m n : c != 0 -> (c *: m %| n) = (m %| n). Proof. by move=> cn0; exact/eqp_dvdl/eqp_scale. Qed. Lemma dvdpNl d p : (- d) %| p = (d %| p). Proof. by rewrite -scaleN1r; apply/eqp_dvdl/eqp_scale; rewrite oppr_eq0 oner_neq0. Qed. Lemma dvdpNr d p : d %| (- p) = (d %| p). Proof. by apply: eqp_dvdr; rewrite -scaleN1r eqp_scale ?oppr_eq0 ?oner_eq0. Qed. Lemma eqp_mul2r r p q : r != 0 -> (p * r %= q * r) = (p %= q). Proof. by move=> nz_r; rewrite /eqp !dvdp_mul2r. Qed. Lemma eqp_mul2l r p q: r != 0 -> (r * p %= r * q) = (p %= q). Proof. by move=> nz_r; rewrite /eqp !dvdp_mul2l. Qed. Lemma eqp_mull r p q: q %= r -> p * q %= p * r. Proof. case/eqpP=> [[c d]] /andP [c0 d0 e]; apply/eqpP; exists (c, d); rewrite ?c0 //. by rewrite scalerAr e -scalerAr. Qed. Lemma eqp_mulr q p r : p %= q -> p * r %= q * r. Proof. by move=> epq; rewrite ![_ * r]mulrC eqp_mull. Qed. Lemma eqp_exp p q k : p %= q -> p ^+ k %= q ^+ k. Proof. move=> pq; elim: k=> [|k ihk]; first by rewrite !expr0 eqpxx. by rewrite !exprS (@eqp_trans (q * p ^+ k)) // (eqp_mulr, eqp_mull). Qed. Lemma polyC_eqp1 (c : R) : (c%:P %= 1) = (c != 0). Proof. apply/eqpP/idP => [[[x y]] |nc0] /=. case: (eqVneq c) => [->|] //= /andP [_] /negPf <- /eqP. by rewrite alg_polyC scaler0 eq_sym polyC_eq0. exists (1, c); first by rewrite nc0 /= oner_neq0. by rewrite alg_polyC scale1r. Qed. Lemma dvdUp d p: d %= 1 -> d %| p. Proof. by move/eqp_dvdl->; rewrite dvd1p. Qed. Lemma dvdp_size_eqp p q : p %| q -> size p == size q = (p %= q). Proof. move=> pq; apply/idP/idP; last by move/eqp_size->. have [->|Hq] := eqVneq q 0; first by rewrite size_poly0 size_poly_eq0 eqp0. have [->|Hp] := eqVneq p 0. by rewrite size_poly0 eq_sym size_poly_eq0 eqp_sym eqp0. move: pq; rewrite dvdp_eq; set c := _ ^+ _; set x := _ %/ _; move/eqP=> eqpq. have /= := congr1 (size \o @polyseq R) eqpq. have cn0 : c != 0 by rewrite expf_neq0 // lead_coef_eq0. rewrite (@eqp_size _ q); last exact: eqp_scale. rewrite size_mul ?p0 // => [-> HH|]; last first. apply/eqP=> HH; move: eqpq; rewrite HH mul0r. by move/eqP; rewrite scale_poly_eq0 (negPf Hq) (negPf cn0). suff: size x == 1%N. case/size_poly1P=> y H1y H2y. by apply/eqpP; exists (y, c); rewrite ?H1y // eqpq H2y mul_polyC. case: (size p) HH (size_poly_eq0 p)=> [|n]; first by case: eqP Hp. by rewrite addnS -add1n eqn_add2r; move/eqP->. Qed. Lemma eqp_root p q : p %= q -> root p =1 root q. Proof. move/eqpP=> [[c d]] /andP [c0 d0 e] x; move/negPf:c0=>c0; move/negPf:d0=>d0. by rewrite rootE -[_==_]orFb -c0 -mulf_eq0 -hornerZ e hornerZ mulf_eq0 d0. Qed. Lemma eqp_rmod_mod p q : rmodp p q %= modp p q. Proof. rewrite modpE eqp_sym; case: ifP => ulcq //. apply: eqp_scale; rewrite invr_eq0 //. by apply: expf_neq0; apply: contraTneq ulcq => ->; rewrite unitr0. Qed. Lemma eqp_rdiv_div p q : rdivp p q %= divp p q. Proof. rewrite divpE eqp_sym; case: ifP=> ulcq //; apply: eqp_scale; rewrite invr_eq0 //. by apply: expf_neq0; apply: contraTneq ulcq => ->; rewrite unitr0. Qed. Lemma dvd_eqp_divl d p q (dvd_dp : d %| q) (eq_pq : p %= q) : p %/ d %= q %/ d. Proof. case: (eqVneq q 0) eq_pq=> [->|q_neq0]; first by rewrite eqp0=> /eqP->. have d_neq0: d != 0 by apply: contraTneq dvd_dp=> ->; rewrite dvd0p. move=> eq_pq; rewrite -(@eqp_mul2r d) // !divpK // ?(eqp_dvdr _ eq_pq) //. rewrite (eqp_ltrans (eqp_scale _ _)) ?lc_expn_scalp_neq0 //. by rewrite (eqp_rtrans (eqp_scale _ _)) ?lc_expn_scalp_neq0. Qed. Definition gcdp_rec p q := let: (p1, q1) := if size p < size q then (q, p) else (p, q) in if p1 == 0 then q1 else let fix loop (n : nat) (pp qq : {poly R}) {struct n} := let rr := modp pp qq in if rr == 0 then qq else if n is n1.+1 then loop n1 qq rr else rr in loop (size p1) p1 q1. Definition gcdp := nosimpl gcdp_rec. Lemma gcd0p : left_id 0 gcdp. Proof. move=> p; rewrite /gcdp /gcdp_rec size_poly0 size_poly_gt0 if_neg. case: ifP => /= [_ | nzp]; first by rewrite eqxx. by rewrite polySpred !(modp0, nzp) //; case: _.-1 => [|m]; rewrite mod0p eqxx. Qed. Lemma gcdp0 : right_id 0 gcdp. Proof. move=> p; have:= gcd0p p; rewrite /gcdp /gcdp_rec size_poly0 size_poly_gt0. by case: eqVneq => //= ->; rewrite eqxx. Qed. Lemma gcdpE p q : gcdp p q = if size p < size q then gcdp (modp q p) p else gcdp (modp p q) q. Proof. pose gcdpE_rec := fix gcdpE_rec (n : nat) (pp qq : {poly R}) {struct n} := let rr := modp pp qq in if rr == 0 then qq else if n is n1.+1 then gcdpE_rec n1 qq rr else rr. have Irec: forall k l p q, size q <= k -> size q <= l -> size q < size p -> gcdpE_rec k p q = gcdpE_rec l p q. + elim=> [|m Hrec] [|n] //= p1 q1. - move/size_poly_leq0P=> -> _; rewrite size_poly0 size_poly_gt0 modp0. by move/negPf ->; case: n => [|n] /=; rewrite mod0p eqxx. - move=> _ /size_poly_leq0P ->; rewrite size_poly0 size_poly_gt0 modp0. by move/negPf ->; case: m {Hrec} => [|m] /=; rewrite mod0p eqxx. case: eqP => Epq Sm Sn Sq //; have [->|nzq] := eqVneq q1 0. by case: n m {Sm Sn Hrec} => [|m] [|n] //=; rewrite mod0p eqxx. apply: Hrec; last by rewrite ltn_modp. by rewrite -ltnS (leq_trans _ Sm) // ltn_modp. by rewrite -ltnS (leq_trans _ Sn) // ltn_modp. have [->|nzp] := eqVneq p 0; first by rewrite mod0p modp0 gcd0p gcdp0 if_same. have [->|nzq] := eqVneq q 0; first by rewrite mod0p modp0 gcd0p gcdp0 if_same. rewrite /gcdp /gcdp_rec !ltn_modp !(negPf nzp, negPf nzq) /=. have [ltpq|leqp] := ltnP; rewrite !(negPf nzp, negPf nzq) /= polySpred //. have [->|nzqp] := eqVneq. by case: (size p) => [|[|s]]; rewrite /= modp0 (negPf nzp) // mod0p eqxx. apply: Irec => //; last by rewrite ltn_modp. by rewrite -ltnS -polySpred // (leq_trans _ ltpq) ?leqW // ltn_modp. by rewrite ltnW // ltn_modp. case: eqVneq => [->|nzpq]. by case: (size q) => [|[|s]]; rewrite /= modp0 (negPf nzq) // mod0p eqxx. apply: Irec => //; rewrite ?ltn_modp //. by rewrite -ltnS -polySpred // (leq_trans _ leqp) // ltn_modp. by rewrite ltnW // ltn_modp. Qed. Lemma size_gcd1p p : size (gcdp 1 p) = 1%N. Proof. rewrite gcdpE size_polyC oner_eq0 /= modp1; have [|/size1_polyC ->] := ltnP. by rewrite gcd0p size_polyC oner_eq0. have [->|p00] := eqVneq p`_0 0; first by rewrite modp0 gcdp0 size_poly1. by rewrite modpC // gcd0p size_polyC p00. Qed. Lemma size_gcdp1 p : size (gcdp p 1) = 1%N. Proof. rewrite gcdpE size_polyC oner_eq0 /= modp1 ltnS; case: leqP. by move/size_poly_leq0P->; rewrite gcdp0 modp0 size_polyC oner_eq0. by rewrite gcd0p size_polyC oner_eq0. Qed. Lemma gcdpp : idempotent gcdp. Proof. by move=> p; rewrite gcdpE ltnn modpp gcd0p. Qed. Lemma dvdp_gcdlr p q : (gcdp p q %| p) && (gcdp p q %| q). Proof. have [r] := ubnP (minn (size q) (size p)); elim: r => // r IHr in p q *. have [-> | nz_p] := eqVneq p 0; first by rewrite gcd0p dvdpp andbT. have [-> | nz_q] := eqVneq q 0; first by rewrite gcdp0 dvdpp /=. rewrite ltnS gcdpE; case: leqP => [le_pq | lt_pq] le_qr. suffices /IHr/andP[E1 E2]: minn (size q) (size (p %% q)) < r. by rewrite E2 andbT (dvdp_mod _ E2). by rewrite gtn_min orbC (leq_trans _ le_qr) ?ltn_modp. suffices /IHr/andP[E1 E2]: minn (size p) (size (q %% p)) < r. by rewrite E2 (dvdp_mod _ E2). by rewrite gtn_min orbC (leq_trans _ le_qr) ?ltn_modp. Qed. Lemma dvdp_gcdl p q : gcdp p q %| p. Proof. by case/andP: (dvdp_gcdlr p q). Qed. Lemma dvdp_gcdr p q :gcdp p q %| q. Proof. by case/andP: (dvdp_gcdlr p q). Qed. Lemma leq_gcdpl p q : p != 0 -> size (gcdp p q) <= size p. Proof. by move=> pn0; move: (dvdp_gcdl p q); apply: dvdp_leq. Qed. Lemma leq_gcdpr p q : q != 0 -> size (gcdp p q) <= size q. Proof. by move=> qn0; move: (dvdp_gcdr p q); apply: dvdp_leq. Qed. Lemma dvdp_gcd p m n : p %| gcdp m n = (p %| m) && (p %| n). Proof. apply/idP/andP=> [dv_pmn | []]. by rewrite ?(dvdp_trans dv_pmn) ?dvdp_gcdl ?dvdp_gcdr. have [r] := ubnP (minn (size n) (size m)); elim: r => // r IHr in m n *. have [-> | nz_m] := eqVneq m 0; first by rewrite gcd0p. have [-> | nz_n] := eqVneq n 0; first by rewrite gcdp0. rewrite gcdpE ltnS; case: leqP => [le_nm | lt_mn] le_r dv_m dv_n. apply: IHr => //; last by rewrite -(dvdp_mod _ dv_n). by rewrite gtn_min orbC (leq_trans _ le_r) ?ltn_modp. apply: IHr => //; last by rewrite -(dvdp_mod _ dv_m). by rewrite gtn_min orbC (leq_trans _ le_r) ?ltn_modp. Qed. Lemma gcdpC p q : gcdp p q %= gcdp q p. Proof. by rewrite /eqp !dvdp_gcd !dvdp_gcdl !dvdp_gcdr. Qed. Lemma gcd1p p : gcdp 1 p %= 1. Proof. rewrite -size_poly_eq1 gcdpE size_poly1; case: ltnP. by rewrite modp1 gcd0p size_poly1 eqxx. move/size1_polyC=> e; rewrite e. have [->|p00] := eqVneq p`_0 0; first by rewrite modp0 gcdp0 size_poly1. by rewrite modpC // gcd0p size_polyC p00. Qed. Lemma gcdp1 p : gcdp p 1 %= 1. Proof. by rewrite (eqp_ltrans (gcdpC _ _)) gcd1p. Qed. Lemma gcdp_addl_mul p q r: gcdp r (p * r + q) %= gcdp r q. Proof. suff h m n d : gcdp d n %| gcdp d (m * d + n). apply/andP; split => //. by rewrite {2}(_: q = (-p) * r + (p * r + q)) ?H // mulNr addKr. by rewrite dvdp_gcd dvdp_gcdl /= dvdp_addr ?dvdp_gcdr ?dvdp_mull ?dvdp_gcdl. Qed. Lemma gcdp_addl m n : gcdp m (m + n) %= gcdp m n. Proof. by rewrite -[m in m + _]mul1r gcdp_addl_mul. Qed. Lemma gcdp_addr m n : gcdp m (n + m) %= gcdp m n. Proof. by rewrite addrC gcdp_addl. Qed. Lemma gcdp_mull m n : gcdp n (m * n) %= n. Proof. have [-> | nn0] := eqVneq n 0; first by rewrite gcd0p mulr0 eqpxx. have [-> | mn0] := eqVneq m 0; first by rewrite mul0r gcdp0 eqpxx. rewrite gcdpE modp_mull gcd0p size_mul //; case: leqP; last by rewrite eqpxx. rewrite (polySpred mn0) addSn /= -[leqRHS]add0n leq_add2r -ltnS. rewrite -polySpred //= leq_eqVlt ltnS size_poly_leq0 (negPf mn0) orbF. case/size_poly1P=> c cn0 -> {mn0 m}; rewrite mul_polyC. suff -> : n %% (c *: n) = 0 by rewrite gcd0p; apply: eqp_scale. by apply/modp_eq0P; rewrite dvdpZl. Qed. Lemma gcdp_mulr m n : gcdp n (n * m) %= n. Proof. by rewrite mulrC gcdp_mull. Qed. Lemma gcdp_scalel c m n : c != 0 -> gcdp (c *: m) n %= gcdp m n. Proof. move=> cn0; rewrite /eqp dvdp_gcd [gcdp m n %| _]dvdp_gcd !dvdp_gcdr !andbT. apply/andP; split; last first. by apply: dvdp_trans (dvdp_gcdl _ _) _; rewrite dvdpZr. by apply: dvdp_trans (dvdp_gcdl _ _) _; rewrite dvdpZl. Qed. Lemma gcdp_scaler c m n : c != 0 -> gcdp m (c *: n) %= gcdp m n. Proof. move=> cn0; apply: eqp_trans (gcdpC _ _) _. by apply: eqp_trans (gcdp_scalel _ _ _) _ => //; apply: gcdpC. Qed. Lemma dvdp_gcd_idl m n : m %| n -> gcdp m n %= m. Proof. have [-> | mn0] := eqVneq m 0. by rewrite dvd0p => /eqP ->; rewrite gcdp0 eqpxx. rewrite dvdp_eq; move/eqP/(f_equal (gcdp m)) => h. apply: eqp_trans (gcdp_mull (n %/ m) _). by rewrite -h eqp_sym gcdp_scaler // expf_neq0 // lead_coef_eq0. Qed. Lemma dvdp_gcd_idr m n : n %| m -> gcdp m n %= n. Proof. by move/dvdp_gcd_idl; exact/eqp_trans/gcdpC. Qed. Lemma gcdp_exp p k l : gcdp (p ^+ k) (p ^+ l) %= p ^+ minn k l. Proof. case: leqP => [|/ltnW] /subnK <-; rewrite exprD; first exact: gcdp_mull. exact/(eqp_trans (gcdpC _ _))/gcdp_mull. Qed. Lemma gcdp_eq0 p q : gcdp p q == 0 = (p == 0) && (q == 0). Proof. apply/idP/idP; last by case/andP => /eqP -> /eqP ->; rewrite gcdp0. have h m n: gcdp m n == 0 -> (m == 0). by rewrite -(dvd0p m); move/eqP<-; rewrite dvdp_gcdl. by move=> ?; rewrite (h _ q) // (h _ p) // -eqp0 (eqp_ltrans (gcdpC _ _)) eqp0. Qed. Lemma eqp_gcdr p q r : q %= r -> gcdp p q %= gcdp p r. Proof. move=> eqr; rewrite /eqp !(dvdp_gcd, dvdp_gcdl, andbT) /=. by rewrite -(eqp_dvdr _ eqr) dvdp_gcdr (eqp_dvdr _ eqr) dvdp_gcdr. Qed. Lemma eqp_gcdl r p q : p %= q -> gcdp p r %= gcdp q r. Proof. move=> eqr; rewrite /eqp !(dvdp_gcd, dvdp_gcdr, andbT) /=. by rewrite -(eqp_dvdr _ eqr) dvdp_gcdl (eqp_dvdr _ eqr) dvdp_gcdl. Qed. Lemma eqp_gcd p1 p2 q1 q2 : p1 %= p2 -> q1 %= q2 -> gcdp p1 q1 %= gcdp p2 q2. Proof. move=> e1 e2; exact: eqp_trans (eqp_gcdr _ e2) (eqp_gcdl _ e1). Qed. Lemma eqp_rgcd_gcd p q : rgcdp p q %= gcdp p q. Proof. move: {2}(minn (size p) (size q)) (leqnn (minn (size p) (size q))) => n. elim: n p q => [p q|n ihn p q hs]. rewrite leqn0; case: ltnP => _; rewrite size_poly_eq0; move/eqP->. by rewrite gcd0p rgcd0p eqpxx. by rewrite gcdp0 rgcdp0 eqpxx. have [-> | pn0] := eqVneq p 0; first by rewrite gcd0p rgcd0p eqpxx. have [-> | qn0] := eqVneq q 0; first by rewrite gcdp0 rgcdp0 eqpxx. rewrite gcdpE rgcdpE; case: ltnP hs => sp hs. have e := eqp_rmod_mod q p; apply/eqp_trans/ihn: (eqp_gcdl p e). by rewrite (eqp_size e) geq_min -ltnS (leq_trans _ hs) ?ltn_modp. have e := eqp_rmod_mod p q; apply/eqp_trans/ihn: (eqp_gcdl q e). by rewrite (eqp_size e) geq_min -ltnS (leq_trans _ hs) ?ltn_modp. Qed. Lemma gcdp_modl m n : gcdp (m %% n) n %= gcdp m n. Proof. have [/modp_small -> // | lenm] := ltnP (size m) (size n). by rewrite (gcdpE m n) ltnNge lenm. Qed. Lemma gcdp_modr m n : gcdp m (n %% m) %= gcdp m n. Proof. apply: eqp_trans (gcdpC _ _); apply: eqp_trans (gcdp_modl _ _); exact: gcdpC. Qed. Lemma gcdp_def d m n : d %| m -> d %| n -> (forall d', d' %| m -> d' %| n -> d' %| d) -> gcdp m n %= d. Proof. move=> dm dn h; rewrite /eqp dvdp_gcd dm dn !andbT. by apply: h; [apply: dvdp_gcdl | apply: dvdp_gcdr]. Qed. Definition coprimep p q := size (gcdp p q) == 1%N. Lemma coprimep_size_gcd p q : coprimep p q -> size (gcdp p q) = 1%N. Proof. by rewrite /coprimep=> /eqP. Qed. Lemma coprimep_def p q : coprimep p q = (size (gcdp p q) == 1%N). Proof. done. Qed. Lemma coprimepZl c m n : c != 0 -> coprimep (c *: m) n = coprimep m n. Proof. by move=> ?; rewrite !coprimep_def (eqp_size (gcdp_scalel _ _ _)). Qed. Lemma coprimepZr c m n: c != 0 -> coprimep m (c *: n) = coprimep m n. Proof. by move=> ?; rewrite !coprimep_def (eqp_size (gcdp_scaler _ _ _)). Qed. Lemma coprimepp p : coprimep p p = (size p == 1%N). Proof. by rewrite coprimep_def gcdpp. Qed. Lemma gcdp_eqp1 p q : gcdp p q %= 1 = coprimep p q. Proof. by rewrite coprimep_def size_poly_eq1. Qed. Lemma coprimep_sym p q : coprimep p q = coprimep q p. Proof. by rewrite -!gcdp_eqp1; apply: eqp_ltrans; rewrite gcdpC. Qed. Lemma coprime1p p : coprimep 1 p. Proof. by rewrite /coprimep -[1%N](size_poly1 R); exact/eqP/eqp_size/gcd1p. Qed. Lemma coprimep1 p : coprimep p 1. Proof. by rewrite coprimep_sym; apply: coprime1p. Qed. Lemma coprimep0 p : coprimep p 0 = (p %= 1). Proof. by rewrite /coprimep gcdp0 size_poly_eq1. Qed. Lemma coprime0p p : coprimep 0 p = (p %= 1). Proof. by rewrite coprimep_sym coprimep0. Qed. (* This is different from coprimeP in div. shall we keep this? *) Lemma coprimepP p q : reflect (forall d, d %| p -> d %| q -> d %= 1) (coprimep p q). Proof. rewrite /coprimep; apply: (iffP idP) => [/eqP hs d dvddp dvddq | h]. have/dvdp_eqp1: d %| gcdp p q by rewrite dvdp_gcd dvddp dvddq. by rewrite -size_poly_eq1 hs; exact. by rewrite size_poly_eq1; case/andP: (dvdp_gcdlr p q); apply: h. Qed. Lemma coprimepPn p q : p != 0 -> reflect (exists d, (d %| gcdp p q) && ~~ (d %= 1)) (~~ coprimep p q). Proof. move=> p0; apply: (iffP idP). by rewrite -gcdp_eqp1=> ng1; exists (gcdp p q); rewrite dvdpp /=. case=> d /andP [dg]; apply: contra; rewrite -gcdp_eqp1=> g1. by move: dg; rewrite (eqp_dvdr _ g1) dvdp1 size_poly_eq1. Qed. Lemma coprimep_dvdl q p r : r %| q -> coprimep p q -> coprimep p r. Proof. move=> rp /coprimepP cpq'; apply/coprimepP => d dp dr. exact/cpq'/(dvdp_trans dr). Qed. Lemma coprimep_dvdr p q r : r %| p -> coprimep p q -> coprimep r q. Proof. by move=> rp; rewrite ![coprimep _ q]coprimep_sym; apply/coprimep_dvdl. Qed. Lemma coprimep_modl p q : coprimep (p %% q) q = coprimep p q. Proof. rewrite !coprimep_def [in RHS]gcdpE. by case: ltnP => // hpq; rewrite modp_small // gcdpE hpq. Qed. Lemma coprimep_modr q p : coprimep q (p %% q) = coprimep q p. Proof. by rewrite ![coprimep q _]coprimep_sym coprimep_modl. Qed. Lemma rcoprimep_coprimep q p : rcoprimep q p = coprimep q p. Proof. by rewrite /coprimep /rcoprimep (eqp_size (eqp_rgcd_gcd _ _)). Qed. Lemma eqp_coprimepr p q r : q %= r -> coprimep p q = coprimep p r. Proof. by rewrite -!gcdp_eqp1; move/(eqp_gcdr p)/eqp_ltrans. Qed. Lemma eqp_coprimepl p q r : q %= r -> coprimep q p = coprimep r p. Proof. by rewrite !(coprimep_sym _ p); apply: eqp_coprimepr. Qed. (* This should be implemented with an extended remainder sequence *) Fixpoint egcdp_rec p q k {struct k} : {poly R} * {poly R} := if k is k'.+1 then if q == 0 then (1, 0) else let: (u, v) := egcdp_rec q (p %% q) k' in (lead_coef q ^+ scalp p q *: v, (u - v * (p %/ q))) else (1, 0). Definition egcdp p q := if size q <= size p then egcdp_rec p q (size q) else let e := egcdp_rec q p (size p) in (e.2, e.1). (* No provable egcd0p *) Lemma egcdp0 p : egcdp p 0 = (1, 0). Proof. by rewrite /egcdp size_poly0. Qed. Lemma egcdp_recP : forall k p q, q != 0 -> size q <= k -> size q <= size p -> let e := (egcdp_rec p q k) in [/\ size e.1 <= size q, size e.2 <= size p & gcdp p q %= e.1 * p + e.2 * q]. Proof. elim=> [|k ihk] p q /= qn0; first by rewrite size_poly_leq0 (negPf qn0). move=> sqSn qsp; rewrite (negPf qn0). have sp : size p > 0 by apply: leq_trans qsp; rewrite size_poly_gt0. have [r0 | rn0] /= := eqVneq (p %%q) 0. rewrite r0 /egcdp_rec; case: k ihk sqSn => [|n] ihn sqSn /=. rewrite !scaler0 !mul0r subr0 add0r mul1r size_poly0 size_poly1. by rewrite dvdp_gcd_idr /dvdp ?r0. rewrite !eqxx mul0r scaler0 /= mul0r add0r subr0 mul1r size_poly0 size_poly1. by rewrite dvdp_gcd_idr /dvdp ?r0 //. have h1 : size (p %% q) <= k. by rewrite -ltnS; apply: leq_trans sqSn; rewrite ltn_modp. have h2 : size (p %% q) <= size q by rewrite ltnW // ltn_modp. have := ihk q (p %% q) rn0 h1 h2. case: (egcdp_rec _ _)=> u v /= => [[ihn'1 ihn'2 ihn'3]]. rewrite gcdpE ltnNge qsp //= (eqp_ltrans (gcdpC _ _)); split; last first. - apply: (eqp_trans ihn'3). rewrite mulrBl addrCA -scalerAl scalerAr -mulrA -mulrBr. by rewrite divp_eq addrAC subrr add0r eqpxx. - apply: (leq_trans (size_add _ _)). have [-> | vn0] := eqVneq v 0. rewrite mul0r size_opp size_poly0 maxn0; apply: leq_trans ihn'1 _. exact: leq_modp. have [-> | qqn0] := eqVneq (p %/ q) 0. rewrite mulr0 size_opp size_poly0 maxn0; apply: leq_trans ihn'1 _. exact: leq_modp. rewrite geq_max (leq_trans ihn'1) ?leq_modp //= size_opp size_mul //. move: (ihn'2); rewrite (polySpred vn0) (polySpred qn0). rewrite -(ltn_add2r (size (p %/ q))) !addSn /= ltnS; move/leq_trans; apply. rewrite size_divp // addnBA ?addKn //. by apply: leq_trans qsp; apply: leq_pred. - by rewrite size_scale // lc_expn_scalp_neq0. Qed. Lemma egcdpP p q : p != 0 -> q != 0 -> forall (e := egcdp p q), [/\ size e.1 <= size q, size e.2 <= size p & gcdp p q %= e.1 * p + e.2 * q]. Proof. rewrite /egcdp => pn0 qn0; case: (leqP (size q) (size p)) => /= [|/ltnW] hp. exact: egcdp_recP. case: (egcdp_recP pn0 (leqnn (size p)) hp) => h1 h2 h3; split => //. by rewrite (eqp_ltrans (gcdpC _ _)) addrC. Qed. Lemma egcdpE p q (e := egcdp p q) : gcdp p q %= e.1 * p + e.2 * q. Proof. rewrite {}/e; have [-> /= | qn0] := eqVneq q 0. by rewrite gcdp0 egcdp0 mul1r mulr0 addr0. have [-> | pn0] := eqVneq p 0; last by case: (egcdpP pn0 qn0). by rewrite gcd0p /egcdp size_poly0 size_poly_leq0 (negPf qn0) /= !simp. Qed. Lemma Bezoutp p q : exists u, u.1 * p + u.2 * q %= (gcdp p q). Proof. have [-> | pn0] := eqVneq p 0. by rewrite gcd0p; exists (0, 1); rewrite mul0r mul1r add0r. have [-> | qn0] := eqVneq q 0. by rewrite gcdp0; exists (1, 0); rewrite mul0r mul1r addr0. pose e := egcdp p q; exists e; rewrite eqp_sym. by case: (egcdpP pn0 qn0). Qed. Lemma Bezout_coprimepP p q : reflect (exists u, u.1 * p + u.2 * q %= 1) (coprimep p q). Proof. rewrite -gcdp_eqp1; apply: (iffP idP)=> [g1|]. by case: (Bezoutp p q) => [[u v] Puv]; exists (u, v); apply: eqp_trans g1. case=> [[u v]]; rewrite eqp_sym=> Puv; rewrite /eqp (eqp_dvdr _ Puv). by rewrite dvdp_addr dvdp_mull ?dvdp_gcdl ?dvdp_gcdr //= dvd1p. Qed. Lemma coprimep_root p q x : coprimep p q -> root p x -> q.[x] != 0. Proof. case/Bezout_coprimepP=> [[u v] euv] px0. move/eqpP: euv => [[c1 c2]] /andP /= [c1n0 c2n0 e]. suffices: c1 * (v.[x] * q.[x]) != 0. by rewrite !mulf_eq0 !negb_or c1n0 /=; case/andP. have := f_equal (horner^~ x) e; rewrite /= !hornerZ hornerD. by rewrite !hornerM (eqP px0) mulr0 add0r hornerC mulr1; move->. Qed. Lemma Gauss_dvdpl p q d: coprimep d q -> (d %| p * q) = (d %| p). Proof. move/Bezout_coprimepP=>[[u v] Puv]; apply/idP/idP; last exact: dvdp_mulr. move/(eqp_mull p): Puv; rewrite mulr1 mulrDr eqp_sym=> peq dpq. rewrite (eqp_dvdr _ peq) dvdp_addr; first by rewrite mulrA mulrAC dvdp_mulr. by rewrite mulrA dvdp_mull ?dvdpp. Qed. Lemma Gauss_dvdpr p q d: coprimep d q -> (d %| q * p) = (d %| p). Proof. by rewrite mulrC; apply: Gauss_dvdpl. Qed. (* This could be simplified with the introduction of lcmp *) Lemma Gauss_dvdp m n p : coprimep m n -> (m * n %| p) = (m %| p) && (n %| p). Proof. have [-> | mn0] := eqVneq m 0. by rewrite coprime0p => /eqp_dvdl->; rewrite !mul0r dvd0p dvd1p andbT. have [-> | nn0] := eqVneq n 0. by rewrite coprimep0 => /eqp_dvdl->; rewrite !mulr0 dvd1p. move=> hc; apply/idP/idP => [mnmp | /andP [dmp dnp]]. move/Gauss_dvdpl: hc => <-; move: (dvdp_mull m mnmp); rewrite dvdp_mul2l //. move->; move: (dvdp_mulr n mnmp); rewrite dvdp_mul2r // andbT. exact: dvdp_mulr. move: (dnp); rewrite dvdp_eq. set c2 := _ ^+ _; set q2 := _ %/ _; move/eqP=> e2. have/esym := Gauss_dvdpl q2 hc; rewrite -e2. have -> : m %| c2 *: p by rewrite -mul_polyC dvdp_mull. rewrite dvdp_eq; set c3 := _ ^+ _; set q3 := _ %/ _; move/eqP=> e3. apply: (@eq_dvdp (c3 * c2) q3). by rewrite mulf_neq0 // expf_neq0 // lead_coef_eq0. by rewrite mulrA -e3 -scalerAl -e2 scalerA. Qed. Lemma Gauss_gcdpr p m n : coprimep p m -> gcdp p (m * n) %= gcdp p n. Proof. move=> co_pm; apply/eqP; rewrite /eqp !dvdp_gcd !dvdp_gcdl /= andbC. rewrite dvdp_mull ?dvdp_gcdr // -(@Gauss_dvdpl _ m). by rewrite mulrC dvdp_gcdr. apply/coprimepP=> d; rewrite dvdp_gcd; case/andP=> hdp _ hdm. by move/coprimepP: co_pm; apply. Qed. Lemma Gauss_gcdpl p m n : coprimep p n -> gcdp p (m * n) %= gcdp p m. Proof. by move=> co_pn; rewrite mulrC Gauss_gcdpr. Qed. Lemma coprimepMr p q r : coprimep p (q * r) = (coprimep p q && coprimep p r). Proof. apply/coprimepP/andP=> [hp | [/coprimepP-hq hr]]. by split; apply/coprimepP=> d dp dq; rewrite hp //; [apply/dvdp_mulr | apply/dvdp_mull]. move=> d dp dqr; move/(_ _ dp) in hq. rewrite Gauss_dvdpl in dqr; first exact: hq. by move/coprimep_dvdr: hr; apply. Qed. Lemma coprimepMl p q r: coprimep (q * r) p = (coprimep q p && coprimep r p). Proof. by rewrite ![coprimep _ p]coprimep_sym coprimepMr. Qed. Lemma modp_coprime k u n : k != 0 -> (k * u) %% n %= 1 -> coprimep k n. Proof. move=> kn0 hmod; apply/Bezout_coprimepP. exists (((lead_coef n)^+(scalp (k * u) n) *: u), (- (k * u %/ n))). rewrite -scalerAl mulrC (divp_eq (u * k) n) mulNr -addrAC subrr add0r. by rewrite mulrC. Qed. Lemma coprimep_pexpl k m n : 0 < k -> coprimep (m ^+ k) n = coprimep m n. Proof. case: k => // k _; elim: k => [|k IHk]; first by rewrite expr1. by rewrite exprS coprimepMl -IHk andbb. Qed. Lemma coprimep_pexpr k m n : 0 < k -> coprimep m (n ^+ k) = coprimep m n. Proof. by move=> k_gt0; rewrite !(coprimep_sym m) coprimep_pexpl. Qed. Lemma coprimep_expl k m n : coprimep m n -> coprimep (m ^+ k) n. Proof. by case: k => [|k] co_pm; rewrite ?coprime1p // coprimep_pexpl. Qed. Lemma coprimep_expr k m n : coprimep m n -> coprimep m (n ^+ k). Proof. by rewrite !(coprimep_sym m); apply: coprimep_expl. Qed. Lemma gcdp_mul2l p q r : gcdp (p * q) (p * r) %= (p * gcdp q r). Proof. have [->|hp] := eqVneq p 0; first by rewrite !mul0r gcdp0 eqpxx. rewrite /eqp !dvdp_gcd !dvdp_mul2l // dvdp_gcdr dvdp_gcdl !andbT. move: (Bezoutp q r) => [[u v]] huv. rewrite eqp_sym in huv; rewrite (eqp_dvdr _ (eqp_mull _ huv)). rewrite mulrDr ![p * (_ * _)]mulrCA. by apply: dvdp_add; rewrite dvdp_mull// (dvdp_gcdr, dvdp_gcdl). Qed. Lemma gcdp_mul2r q r p : gcdp (q * p) (r * p) %= gcdp q r * p. Proof. by rewrite ![_ * p]mulrC gcdp_mul2l. Qed. Lemma mulp_gcdr p q r : r * (gcdp p q) %= gcdp (r * p) (r * q). Proof. by rewrite eqp_sym gcdp_mul2l. Qed. Lemma mulp_gcdl p q r : (gcdp p q) * r %= gcdp (p * r) (q * r). Proof. by rewrite eqp_sym gcdp_mul2r. Qed. Lemma coprimep_div_gcd p q : (p != 0) || (q != 0) -> coprimep (p %/ (gcdp p q)) (q %/ gcdp p q). Proof. rewrite -negb_and -gcdp_eq0 -gcdp_eqp1 => gpq0. rewrite -(@eqp_mul2r (gcdp p q)) // mul1r (eqp_ltrans (mulp_gcdl _ _ _)). have: gcdp p q %| p by rewrite dvdp_gcdl. have: gcdp p q %| q by rewrite dvdp_gcdr. rewrite !dvdp_eq => /eqP <- /eqP <-. have lcn0 k : (lead_coef (gcdp p q)) ^+ k != 0. by rewrite expf_neq0 ?lead_coef_eq0. by apply: eqp_gcd; rewrite ?eqp_scale. Qed. Lemma divp_eq0 p q : (p %/ q == 0) = [|| p == 0, q ==0 | size p < size q]. Proof. apply/eqP/idP=> [d0|]; last first. case/or3P; [by move/eqP->; rewrite div0p| by move/eqP->; rewrite divp0|]. by move/divp_small. case: eqVneq => // _; case: eqVneq => // qn0. move: (divp_eq p q); rewrite d0 mul0r add0r. move/(f_equal (fun x : {poly R} => size x)). by rewrite size_scale ?lc_expn_scalp_neq0 // => ->; rewrite ltn_modp qn0 !orbT. Qed. Lemma dvdp_div_eq0 p q : q %| p -> (p %/ q == 0) = (p == 0). Proof. move=> dvdp_qp; have [->|p_neq0] := eqVneq p 0; first by rewrite div0p eqxx. rewrite divp_eq0 ltnNge dvdp_leq // (negPf p_neq0) orbF /=. by apply: contraTF dvdp_qp=> /eqP ->; rewrite dvd0p. Qed. Lemma Bezout_coprimepPn p q : p != 0 -> q != 0 -> reflect (exists2 uv : {poly R} * {poly R}, (0 < size uv.1 < size q) && (0 < size uv.2 < size p) & uv.1 * p = uv.2 * q) (~~ (coprimep p q)). Proof. move=> pn0 qn0; apply: (iffP idP); last first. case=> [[u v] /= /andP [/andP [ps1 s1] /andP [ps2 s2]] e]. have: ~~(size (q * p) <= size (u * p)). rewrite -ltnNge !size_mul // -?size_poly_gt0 // (polySpred pn0) !addnS. by rewrite ltn_add2r. apply: contra => ?; apply: dvdp_leq; rewrite ?mulf_neq0 // -?size_poly_gt0 //. by rewrite mulrC Gauss_dvdp // dvdp_mull // e dvdp_mull. rewrite coprimep_def neq_ltn ltnS size_poly_leq0 gcdp_eq0. rewrite (negPf pn0) (negPf qn0) /=. case sg: (size (gcdp p q)) => [|n] //; case: n sg=> [|n] // sg _. move: (dvdp_gcdl p q); rewrite dvdp_eq; set c1 := _ ^+ _; move/eqP=> hu1. move: (dvdp_gcdr p q); rewrite dvdp_eq; set c2 := _ ^+ _; move/eqP=> hv1. exists (c1 *: (q %/ gcdp p q), c2 *: (p %/ gcdp p q)); last first. by rewrite -!scalerAl !scalerAr hu1 hv1 mulrCA. rewrite !size_scale ?lc_expn_scalp_neq0 //= !size_poly_gt0 !divp_eq0. rewrite gcdp_eq0 !(negPf pn0) !(negPf qn0) /= -!leqNgt leq_gcdpl //. rewrite leq_gcdpr //= !ltn_divpl -?size_poly_eq0 ?sg //. rewrite !size_mul // -?size_poly_eq0 ?sg // ![(_ + n.+2)%N]addnS /=. by rewrite -!(addn1 (size _)) !leq_add2l. Qed. Lemma dvdp_pexp2r m n k : k > 0 -> (m ^+ k %| n ^+ k) = (m %| n). Proof. move=> k_gt0; apply/idP/idP; last exact: dvdp_exp2r. have [-> // | nn0] := eqVneq n 0; have [-> | mn0] := eqVneq m 0. move/prednK: k_gt0=> {1}<-; rewrite exprS mul0r //= !dvd0p expf_eq0. by case/andP=> _ ->. set d := gcdp m n; have := dvdp_gcdr m n; rewrite -/d dvdp_eq. set c1 := _ ^+ _; set n' := _ %/ _; move/eqP=> def_n. have := dvdp_gcdl m n; rewrite -/d dvdp_eq. set c2 := _ ^+ _; set m' := _ %/ _; move/eqP=> def_m. have dn0 : d != 0 by rewrite gcdp_eq0 negb_and nn0 orbT. have c1n0 : c1 != 0 by rewrite !expf_neq0 // lead_coef_eq0. have c2n0 : c2 != 0 by rewrite !expf_neq0 // lead_coef_eq0. have c2k_n0 : c2 ^+ k != 0 by rewrite !expf_neq0 // lead_coef_eq0. rewrite -(@dvdpZr (c1 ^+ k)) ?expf_neq0 ?lead_coef_eq0 //. rewrite -(@dvdpZl (c2 ^+ k)) // -!exprZn def_m def_n !exprMn. rewrite dvdp_mul2r ?expf_neq0 //. have: coprimep (m' ^+ k) (n' ^+ k). by rewrite coprimep_pexpl // coprimep_pexpr // coprimep_div_gcd ?mn0. move/coprimepP=> hc hd. have /size_poly1P [c cn0 em'] : size m' == 1%N. case: (eqVneq m' 0) def_m => [-> /eqP | m'_n0 def_m]. by rewrite mul0r scale_poly_eq0 (negPf mn0) (negPf c2n0). have := hc _ (dvdpp _) hd; rewrite -size_poly_eq1. rewrite polySpred; last by rewrite expf_eq0 negb_and m'_n0 orbT. by rewrite size_exp eqSS muln_eq0 orbC eqn0Ngt k_gt0 /= -eqSS -polySpred. rewrite -(@dvdpZl c2) // def_m em' mul_polyC dvdpZl //. by rewrite -(@dvdpZr c1) // def_n dvdp_mull. Qed. Lemma root_gcd p q x : root (gcdp p q) x = root p x && root q x. Proof. rewrite /= !root_factor_theorem; apply/idP/andP=> [dg| [dp dq]]. by split; apply: dvdp_trans dg _; rewrite ?(dvdp_gcdl, dvdp_gcdr). have:= Bezoutp p q => [[[u v]]]; rewrite eqp_sym=> e. by rewrite (eqp_dvdr _ e) dvdp_addl dvdp_mull. Qed. Lemma root_biggcd x (ps : seq {poly R}) : root (\big[gcdp/0]_(p <- ps) p) x = all (fun p => root p x) ps. Proof. elim: ps => [|p ps ihp]; first by rewrite big_nil root0. by rewrite big_cons /= root_gcd ihp. Qed. (* "gdcop Q P" is the Greatest Divisor of P which is coprime to Q *) (* if P null, we pose that gdcop returns 1 if Q null, 0 otherwise*) Fixpoint gdcop_rec q p k := if k is m.+1 then if coprimep p q then p else gdcop_rec q (divp p (gcdp p q)) m else (q == 0)%:R. Definition gdcop q p := gdcop_rec q p (size p). Variant gdcop_spec q p : {poly R} -> Type := GdcopSpec r of (dvdp r p) & ((coprimep r q) || (p == 0)) & (forall d, dvdp d p -> coprimep d q -> dvdp d r) : gdcop_spec q p r. Lemma gdcop0 q : gdcop q 0 = (q == 0)%:R. Proof. by rewrite /gdcop size_poly0. Qed. Lemma gdcop_recP q p k : size p <= k -> gdcop_spec q p (gdcop_rec q p k). Proof. elim: k p => [p | k ihk p] /=. move/size_poly_leq0P->. have [->|q0] := eqVneq; split; rewrite ?coprime1p // ?eqxx ?orbT //. by move=> d _; rewrite coprimep0 dvdp1 size_poly_eq1. move=> hs; case cop : (coprimep _ _); first by split; rewrite ?dvdpp ?cop. have [-> | p0] := eqVneq p 0. by rewrite div0p; apply: ihk; rewrite size_poly0 leq0n. have [-> | q0] := eqVneq q 0. rewrite gcdp0 divpp ?p0 //= => {hs ihk}; case: k=> /=. rewrite eqxx; split; rewrite ?dvd1p ?coprimep0 ?eqpxx //=. by move=> d _; rewrite coprimep0 dvdp1 size_poly_eq1. move=> n; rewrite coprimep0 polyC_eqp1 //; rewrite lc_expn_scalp_neq0. split; first by rewrite (@eqp_dvdl 1) ?dvd1p // polyC_eqp1 lc_expn_scalp_neq0. by rewrite coprimep0 polyC_eqp1 // ?lc_expn_scalp_neq0. by move=> d _; rewrite coprimep0; move/eqp_dvdl->; rewrite dvd1p. move: (dvdp_gcdl p q); rewrite dvdp_eq; move/eqP=> e. have sgp : size (gcdp p q) <= size p. by apply: dvdp_leq; rewrite ?gcdp_eq0 ?p0 ?q0 // dvdp_gcdl. have : p %/ gcdp p q != 0; last move/negPf=>p'n0. apply: dvdpN0 (dvdp_mulIl (p %/ gcdp p q) (gcdp p q)) _. by rewrite -e scale_poly_eq0 negb_or lc_expn_scalp_neq0. have gn0 : gcdp p q != 0. apply: dvdpN0 (dvdp_mulIr (p %/ gcdp p q) (gcdp p q)) _. by rewrite -e scale_poly_eq0 negb_or lc_expn_scalp_neq0. have sp' : size (p %/ (gcdp p q)) <= k. rewrite size_divp ?sgp // leq_subLR (leq_trans hs) // -add1n leq_add2r -subn1. by rewrite ltn_subRL add1n ltn_neqAle eq_sym [_ == _]cop size_poly_gt0 gn0. case (ihk _ sp')=> r' dr'p'; first rewrite p'n0 orbF=> cr'q maxr'. constructor=> //=; rewrite ?(negPf p0) ?orbF //. exact/(dvdp_trans dr'p')/divp_dvd/dvdp_gcdl. move=> d dp cdq; apply: maxr'; last by rewrite cdq. case dpq: (d %| gcdp p q). move: (dpq); rewrite dvdp_gcd dp /= => dq; apply: dvdUp. apply: contraLR cdq => nd1; apply/coprimepPn; last first. by exists d; rewrite dvdp_gcd dvdpp dq nd1. by apply: contraNneq p0 => d0; move: dp; rewrite d0 dvd0p. apply: contraLR dp => ndp'. rewrite (@eqp_dvdr ((lead_coef (gcdp p q) ^+ scalp p (gcdp p q))*:p)). by rewrite e; rewrite Gauss_dvdpl //; apply: (coprimep_dvdl (dvdp_gcdr _ _)). by rewrite eqp_sym eqp_scale // lc_expn_scalp_neq0. Qed. Lemma gdcopP q p : gdcop_spec q p (gdcop q p). Proof. by rewrite /gdcop; apply: gdcop_recP. Qed. Lemma coprimep_gdco p q : (q != 0)%B -> coprimep (gdcop p q) p. Proof. by move=> q_neq0; case: gdcopP=> d; rewrite (negPf q_neq0) orbF. Qed. Lemma size2_dvdp_gdco p q d : p != 0 -> size d = 2%N -> (d %| (gdcop q p)) = (d %| p) && ~~(d %| q). Proof. have [-> | dn0] := eqVneq d 0; first by rewrite size_poly0. move=> p0 sd; apply/idP/idP. case: gdcopP=> r rp crq maxr dr; move/negPf: (p0)=> p0f. rewrite (dvdp_trans dr) //=. apply: contraL crq => dq; rewrite p0f orbF; apply/coprimepPn. by apply: contraNneq p0 => r0; move: rp; rewrite r0 dvd0p. by exists d; rewrite dvdp_gcd dr dq -size_poly_eq1 sd. case/andP=> dp dq; case: gdcopP=> r rp crq maxr; apply: maxr=> //. apply/coprimepP=> x xd xq. move: (dvdp_leq dn0 xd); rewrite leq_eqVlt sd; case/orP; last first. rewrite ltnS leq_eqVlt ltnS size_poly_leq0 orbC. case/predU1P => [x0|]; last by rewrite -size_poly_eq1. by move: xd; rewrite x0 dvd0p (negPf dn0). by rewrite -sd dvdp_size_eqp //; move/(eqp_dvdl q); rewrite xq (negPf dq). Qed. Lemma dvdp_gdco p q : (gdcop p q) %| q. Proof. by case: gdcopP. Qed. Lemma root_gdco p q x : p != 0 -> root (gdcop q p) x = root p x && ~~(root q x). Proof. move=> p0 /=; rewrite !root_factor_theorem. apply: size2_dvdp_gdco; rewrite ?p0 //. by rewrite size_addl size_polyX // size_opp size_polyC ltnS; case: (x != 0). Qed. Lemma dvdp_comp_poly r p q : (p %| q) -> (p \Po r) %| (q \Po r). Proof. have [-> | pn0] := eqVneq p 0. by rewrite comp_poly0 !dvd0p; move/eqP->; rewrite comp_poly0. rewrite dvdp_eq; set c := _ ^+ _; set s := _ %/ _; move/eqP=> Hq. apply: (@eq_dvdp c (s \Po r)); first by rewrite expf_neq0 // lead_coef_eq0. by rewrite -comp_polyZ Hq comp_polyM. Qed. Lemma gcdp_comp_poly r p q : gcdp p q \Po r %= gcdp (p \Po r) (q \Po r). Proof. apply/andP; split. by rewrite dvdp_gcd !dvdp_comp_poly ?dvdp_gcdl ?dvdp_gcdr. case: (Bezoutp p q) => [[u v]] /andP []. move/(dvdp_comp_poly r) => Huv _. rewrite (dvdp_trans _ Huv) // comp_polyD !comp_polyM. by rewrite dvdp_add // dvdp_mull // (dvdp_gcdl,dvdp_gcdr). Qed. Lemma coprimep_comp_poly r p q : coprimep p q -> coprimep (p \Po r) (q \Po r). Proof. rewrite -!gcdp_eqp1 -!size_poly_eq1 -!dvdp1; move/(dvdp_comp_poly r). rewrite comp_polyC => Hgcd. by apply: dvdp_trans Hgcd; case/andP: (gcdp_comp_poly r p q). Qed. Lemma coprimep_addl_mul p q r : coprimep r (p * r + q) = coprimep r q. Proof. by rewrite !coprimep_def (eqp_size (gcdp_addl_mul _ _ _)). Qed. Definition irreducible_poly p := (size p > 1) * (forall q, size q != 1%N -> q %| p -> q %= p) : Prop. Lemma irredp_neq0 p : irreducible_poly p -> p != 0. Proof. by rewrite -size_poly_gt0 => [[/ltnW]]. Qed. Definition apply_irredp p (irr_p : irreducible_poly p) := irr_p.2. Coercion apply_irredp : irreducible_poly >-> Funclass. Lemma modp_XsubC p c : p %% ('X - c%:P) = p.[c]%:P. Proof. have/factor_theorem [q /(canRL (subrK _)) Dp]: root (p - p.[c]%:P) c. by rewrite /root !hornerE subrr. rewrite modpE /= lead_coefXsubC unitr1 expr1n invr1 scale1r [in LHS]Dp. rewrite RingMonic.rmodp_addl_mul_small // ?monicXsubC // size_XsubC size_polyC. by case: (p.[c] == 0). Qed. Lemma coprimep_XsubC p c : coprimep p ('X - c%:P) = ~~ root p c. Proof. rewrite -coprimep_modl modp_XsubC /root -alg_polyC. have [-> | /coprimepZl->] := eqVneq; last exact: coprime1p. by rewrite scale0r /coprimep gcd0p size_XsubC. Qed. Lemma coprimep_XsubC2 (a b : R) : b - a != 0 -> coprimep ('X - a%:P) ('X - b%:P). Proof. by move=> bBa_neq0; rewrite coprimep_XsubC rootE hornerXsubC. Qed. Lemma coprimepX p : coprimep p 'X = ~~ root p 0. Proof. by rewrite -['X]subr0 coprimep_XsubC. Qed. Lemma eqp_monic : {in monic &, forall p q, (p %= q) = (p == q)}. Proof. move=> p q monic_p monic_q; apply/idP/eqP=> [|-> //]. case/eqpP=> [[a b] /= /andP[a_neq0 _] eq_pq]. apply: (@mulfI _ a%:P); first by rewrite polyC_eq0. rewrite !mul_polyC eq_pq; congr (_ *: q); apply: (mulIf (oner_neq0 _)). by rewrite -[in LHS](monicP monic_q) -(monicP monic_p) -!lead_coefZ eq_pq. Qed. Lemma dvdp_mul_XsubC p q c : (p %| ('X - c%:P) * q) = ((if root p c then p %/ ('X - c%:P) else p) %| q). Proof. case: ifPn => [| not_pc0]; last by rewrite Gauss_dvdpr ?coprimep_XsubC. rewrite root_factor_theorem -eqp_div_XsubC mulrC => /eqP{1}->. by rewrite dvdp_mul2l ?polyXsubC_eq0. Qed. Lemma dvdp_prod_XsubC (I : Type) (r : seq I) (F : I -> R) p : p %| \prod_(i <- r) ('X - (F i)%:P) -> {m | p %= \prod_(i <- mask m r) ('X - (F i)%:P)}. Proof. elim: r => [|i r IHr] in p *. by rewrite big_nil dvdp1; exists nil; rewrite // big_nil -size_poly_eq1. rewrite big_cons dvdp_mul_XsubC root_factor_theorem -eqp_div_XsubC. case: eqP => [{2}-> | _] /IHr[m Dp]; last by exists (false :: m). by exists (true :: m); rewrite /= mulrC big_cons eqp_mul2l ?polyXsubC_eq0. Qed. Lemma irredp_XsubC (x : R) : irreducible_poly ('X - x%:P). Proof. split=> [|d size_d d_dv_Xx]; first by rewrite size_XsubC. have: ~ d %= 1 by apply/negP; rewrite -size_poly_eq1. have [|m /=] := @dvdp_prod_XsubC _ [:: x] id d; first by rewrite big_seq1. by case: m => [|[] [|_ _] /=]; rewrite (big_nil, big_seq1). Qed. Lemma irredp_XsubCP d p : irreducible_poly p -> d %| p -> {d %= 1} + {d %= p}. Proof. move=> irred_p dvd_dp; have [] := boolP (_ %= 1); first by left. by rewrite -size_poly_eq1=> /irred_p /(_ dvd_dp); right. Qed. End IDomainPseudoDivision. #[global] Hint Resolve eqpxx divp0 divp1 mod0p modp0 modp1 : core. #[global] Hint Resolve dvdp_mull dvdp_mulr dvdpp dvdp0 : core. End CommonIdomain. Module Idomain. Include IdomainDefs. Export IdomainDefs. Include WeakIdomain. Include CommonIdomain. End Idomain. Module IdomainMonic. Import Ring ComRing UnitRing IdomainDefs Idomain. Section IdomainMonic. Variable R : idomainType. Implicit Type p d r : {poly R}. Section MonicDivisor. Variable q : {poly R}. Hypothesis monq : q \is monic. Lemma divpE p : p %/ q = rdivp p q. Proof. by rewrite divpE (eqP monq) unitr1 expr1n invr1 scale1r. Qed. Lemma modpE p : p %% q = rmodp p q. Proof. by rewrite modpE (eqP monq) unitr1 expr1n invr1 scale1r. Qed. Lemma scalpE p : scalp p q = 0%N. Proof. by rewrite scalpE (eqP monq) unitr1. Qed. Lemma divp_eq p : p = (p %/ q) * q + (p %% q). Proof. by rewrite -divp_eq (eqP monq) expr1n scale1r. Qed. Lemma divpp p : q %/ q = 1. Proof. by rewrite divpp ?monic_neq0 // (eqP monq) expr1n. Qed. Lemma dvdp_eq p : (q %| p) = (p == (p %/ q) * q). Proof. by rewrite dvdp_eq (eqP monq) expr1n scale1r. Qed. Lemma dvdpP p : reflect (exists qq, p = qq * q) (q %| p). Proof. apply: (iffP idP); first by rewrite dvdp_eq; move/eqP=> e; exists (p %/ q). by case=> qq ->; rewrite dvdp_mull // dvdpp. Qed. Lemma mulpK p : p * q %/ q = p. Proof. by rewrite mulpK ?monic_neq0 // (eqP monq) expr1n scale1r. Qed. Lemma mulKp p : q * p %/ q = p. Proof. by rewrite mulrC mulpK. Qed. End MonicDivisor. Lemma drop_poly_divp n p : drop_poly n p = p %/ 'X^n. Proof. by rewrite RingMonic.drop_poly_rdivp divpE // monicXn. Qed. Lemma take_poly_modp n p : take_poly n p = p %% 'X^n. Proof. by rewrite RingMonic.take_poly_rmodp modpE // monicXn. Qed. End IdomainMonic. End IdomainMonic. Module IdomainUnit. Import Ring ComRing UnitRing IdomainDefs Idomain. Section UnitDivisor. Variable R : idomainType. Variable d : {poly R}. Hypothesis ulcd : lead_coef d \in GRing.unit. Implicit Type p q r : {poly R}. Lemma divp_eq p : p = (p %/ d) * d + (p %% d). Proof. by have := divp_eq p d; rewrite scalpE ulcd expr0 scale1r. Qed. Lemma edivpP p q r : p = q * d + r -> size r < size d -> q = (p %/ d) /\ r = p %% d. Proof. move=> ep srd; have := divp_eq p; rewrite [LHS]ep. move/eqP; rewrite -subr_eq -addrA addrC eq_sym -subr_eq -mulrBl; move/eqP. have lcdn0 : lead_coef d != 0 by apply: contraTneq ulcd => ->; rewrite unitr0. have [-> /esym /eqP|abs] := eqVneq (p %/ d) q. by rewrite subrr mul0r subr_eq0 => /eqP<-. have hleq : size d <= size ((p %/ d - q) * d). rewrite size_proper_mul; last first. by rewrite mulf_eq0 (negPf lcdn0) orbF lead_coef_eq0 subr_eq0. by move: abs; rewrite -subr_eq0; move/polySpred->; rewrite addSn /= leq_addl. have hlt : size (r - p %% d) < size d. apply: leq_ltn_trans (size_add _ _) _. by rewrite gtn_max srd size_opp ltn_modp -lead_coef_eq0. by move=> e; have:= leq_trans hlt hleq; rewrite e ltnn. Qed. Lemma divpP p q r : p = q * d + r -> size r < size d -> q = (p %/ d). Proof. by move/edivpP=> h; case/h. Qed. Lemma modpP p q r : p = q * d + r -> size r < size d -> r = (p %% d). Proof. by move/edivpP=> h; case/h. Qed. Lemma ulc_eqpP p q : lead_coef q \is a GRing.unit -> reflect (exists2 c : R, c != 0 & p = c *: q) (p %= q). Proof. have [->|] := eqVneq (lead_coef q) 0; first by rewrite unitr0. rewrite lead_coef_eq0 => nz_q ulcq; apply: (iffP idP). have [->|nz_p] := eqVneq p 0; first by rewrite eqp_sym eqp0 (negPf nz_q). move/eqp_eq=> eq; exists (lead_coef p / lead_coef q). by rewrite mulf_neq0 // ?invr_eq0 lead_coef_eq0. by apply/(scaler_injl ulcq); rewrite scalerA mulrCA divrr // mulr1. by case=> c nz_c ->; apply/eqpP; exists (1, c); rewrite ?scale1r ?oner_eq0. Qed. Lemma dvdp_eq p : (d %| p) = (p == p %/ d * d). Proof. apply/eqP/eqP=> [modp0 | ->]; last exact: modp_mull. by rewrite [p in LHS]divp_eq modp0 addr0. Qed. Lemma ucl_eqp_eq p q : lead_coef q \is a GRing.unit -> p %= q -> p = (lead_coef p / lead_coef q) *: q. Proof. move=> ulcq /eqp_eq; move/(congr1 ( *:%R (lead_coef q)^-1 )). by rewrite !scalerA mulrC divrr // scale1r mulrC. Qed. Lemma modpZl c p : (c *: p) %% d = c *: (p %% d). Proof. have [-> | cn0] := eqVneq c 0; first by rewrite !scale0r mod0p. have e : (c *: p) = (c *: (p %/ d)) * d + c *: (p %% d). by rewrite -scalerAl -scalerDr -divp_eq. suff s: size (c *: (p %% d)) < size d by case: (edivpP e s) => _ ->. rewrite -mul_polyC; apply: leq_ltn_trans (size_mul_leq _ _) _. rewrite size_polyC cn0 addSn add0n /= ltn_modp -lead_coef_eq0. by apply: contraTneq ulcd => ->; rewrite unitr0. Qed. Lemma divpZl c p : (c *: p) %/ d = c *: (p %/ d). Proof. have [-> | cn0] := eqVneq c 0; first by rewrite !scale0r div0p. have e : (c *: p) = (c *: (p %/ d)) * d + c *: (p %% d). by rewrite -scalerAl -scalerDr -divp_eq. suff s: size (c *: (p %% d)) < size d by case: (edivpP e s) => ->. rewrite -mul_polyC; apply: leq_ltn_trans (size_mul_leq _ _) _. rewrite size_polyC cn0 addSn add0n /= ltn_modp -lead_coef_eq0. by apply: contraTneq ulcd => ->; rewrite unitr0. Qed. Lemma eqp_modpl p q : p %= q -> (p %% d) %= (q %% d). Proof. case/eqpP=> [[c1 c2]] /andP /= [c1n0 c2n0 e]. by apply/eqpP; exists (c1, c2); rewrite ?c1n0 //= -!modpZl e. Qed. Lemma eqp_divl p q : p %= q -> (p %/ d) %= (q %/ d). Proof. case/eqpP=> [[c1 c2]] /andP /= [c1n0 c2n0 e]. by apply/eqpP; exists (c1, c2); rewrite ?c1n0 // -!divpZl e. Qed. Lemma modpN p : (- p) %% d = - (p %% d). Proof. by rewrite -mulN1r -[RHS]mulN1r -polyCN !mul_polyC modpZl. Qed. Lemma divpN p : (- p) %/ d = - (p %/ d). Proof. by rewrite -mulN1r -[RHS]mulN1r -polyCN !mul_polyC divpZl. Qed. Lemma modpD p q : (p + q) %% d = p %% d + q %% d. Proof. have/edivpP [] // : (p + q) = (p %/ d + q %/ d) * d + (p %% d + q %% d). by rewrite mulrDl addrACA -!divp_eq. apply: leq_ltn_trans (size_add _ _) _. rewrite gtn_max !ltn_modp andbb -lead_coef_eq0. by apply: contraTneq ulcd => ->; rewrite unitr0. Qed. Lemma divpD p q : (p + q) %/ d = p %/ d + q %/ d. Proof. have/edivpP [] // : (p + q) = (p %/ d + q %/ d) * d + (p %% d + q %% d). by rewrite mulrDl addrACA -!divp_eq. apply: leq_ltn_trans (size_add _ _) _. rewrite gtn_max !ltn_modp andbb -lead_coef_eq0. by apply: contraTneq ulcd => ->; rewrite unitr0. Qed. Lemma mulpK q : (q * d) %/ d = q. Proof. case/esym/edivpP: (addr0 (q * d)); rewrite // size_poly0 size_poly_gt0. by rewrite -lead_coef_eq0; apply: contraTneq ulcd => ->; rewrite unitr0. Qed. Lemma mulKp q : (d * q) %/ d = q. Proof. by rewrite mulrC; apply: mulpK. Qed. Lemma divp_addl_mul_small q r : size r < size d -> (q * d + r) %/ d = q. Proof. by move=> srd; rewrite divpD (divp_small srd) addr0 mulpK. Qed. Lemma modp_addl_mul_small q r : size r < size d -> (q * d + r) %% d = r. Proof. by move=> srd; rewrite modpD modp_mull add0r modp_small. Qed. Lemma divp_addl_mul q r : (q * d + r) %/ d = q + r %/ d. Proof. by rewrite divpD mulpK. Qed. Lemma divpp : d %/ d = 1. Proof. by rewrite -[d in d %/ _]mul1r mulpK. Qed. Lemma leq_trunc_divp m : size (m %/ d * d) <= size m. Proof. case: (eqVneq d 0) ulcd => [->|dn0 _]; first by rewrite lead_coef0 unitr0. have [->|q0] := eqVneq (m %/ d) 0; first by rewrite mul0r size_poly0 leq0n. rewrite {2}(divp_eq m) size_addl // size_mul // (polySpred q0) addSn /=. by rewrite ltn_addl // ltn_modp. Qed. Lemma dvdpP p : reflect (exists q, p = q * d) (d %| p). Proof. apply: (iffP idP) => [| [k ->]]; last by apply/eqP; rewrite modp_mull. by rewrite dvdp_eq; move/eqP->; exists (p %/ d). Qed. Lemma divpK p : d %| p -> p %/ d * d = p. Proof. by rewrite dvdp_eq; move/eqP. Qed. Lemma divpKC p : d %| p -> d * (p %/ d) = p. Proof. by move=> ?; rewrite mulrC divpK. Qed. Lemma dvdp_eq_div p q : d %| p -> (q == p %/ d) = (q * d == p). Proof. move/divpK=> {2}<-; apply/eqP/eqP; first by move->. apply/mulIf; rewrite -lead_coef_eq0; apply: contraTneq ulcd => ->. by rewrite unitr0. Qed. Lemma dvdp_eq_mul p q : d %| p -> (p == q * d) = (p %/ d == q). Proof. by move=> dv_d_p; rewrite eq_sym -dvdp_eq_div // eq_sym. Qed. Lemma divp_mulA p q : d %| q -> p * (q %/ d) = p * q %/ d. Proof. move=> hdm; apply/eqP; rewrite eq_sym -dvdp_eq_mul. by rewrite -mulrA divpK. by move/divpK: hdm<-; rewrite mulrA dvdp_mull // dvdpp. Qed. Lemma divp_mulAC m n : d %| m -> m %/ d * n = m * n %/ d. Proof. by move=> hdm; rewrite mulrC (mulrC m); apply: divp_mulA. Qed. Lemma divp_mulCA p q : d %| p -> d %| q -> p * (q %/ d) = q * (p %/ d). Proof. by move=> hdp hdq; rewrite mulrC divp_mulAC // divp_mulA. Qed. Lemma modp_mul p q : (p * (q %% d)) %% d = (p * q) %% d. Proof. by rewrite [q in RHS]divp_eq mulrDr modpD mulrA modp_mull add0r. Qed. End UnitDivisor. Section MoreUnitDivisor. Variable R : idomainType. Variable d : {poly R}. Hypothesis ulcd : lead_coef d \in GRing.unit. Implicit Types p q : {poly R}. Lemma expp_sub m n : n <= m -> (d ^+ (m - n))%N = d ^+ m %/ d ^+ n. Proof. by move/subnK=> {2}<-; rewrite exprD mulpK // lead_coef_exp unitrX. Qed. Lemma divp_pmul2l p q : lead_coef q \in GRing.unit -> d * p %/ (d * q) = p %/ q. Proof. move=> uq; rewrite {1}(divp_eq uq p) mulrDr mulrCA divp_addl_mul //; last first. by rewrite lead_coefM unitrM_comm ?ulcd //; red; rewrite mulrC. have dn0 : d != 0. by rewrite -lead_coef_eq0; apply: contraTneq ulcd => ->; rewrite unitr0. have qn0 : q != 0. by rewrite -lead_coef_eq0; apply: contraTneq uq => ->; rewrite unitr0. have dqn0 : d * q != 0 by rewrite mulf_eq0 negb_or dn0. suff : size (d * (p %% q)) < size (d * q). by rewrite ltnNge -divpN0 // negbK => /eqP ->; rewrite addr0. have [-> | rn0] := eqVneq (p %% q) 0. by rewrite mulr0 size_poly0 size_poly_gt0. by rewrite !size_mul // (polySpred dn0) !addSn /= ltn_add2l ltn_modp. Qed. Lemma divp_pmul2r p q : lead_coef p \in GRing.unit -> q * d %/ (p * d) = q %/ p. Proof. by move=> uq; rewrite -!(mulrC d) divp_pmul2l. Qed. Lemma divp_divl r p q : lead_coef r \in GRing.unit -> lead_coef p \in GRing.unit -> q %/ p %/ r = q %/ (p * r). Proof. move=> ulcr ulcp. have e : q = (q %/ p %/ r) * (p * r) + ((q %/ p) %% r * p + q %% p). by rewrite addrA (mulrC p) mulrA -mulrDl; rewrite -divp_eq //; apply: divp_eq. have pn0 : p != 0. by rewrite -lead_coef_eq0; apply: contraTneq ulcp => ->; rewrite unitr0. have rn0 : r != 0. by rewrite -lead_coef_eq0; apply: contraTneq ulcr => ->; rewrite unitr0. have s : size ((q %/ p) %% r * p + q %% p) < size (p * r). have [-> | qn0] := eqVneq ((q %/ p) %% r) 0. rewrite mul0r add0r size_mul // (polySpred rn0) addnS /=. by apply: leq_trans (leq_addr _ _); rewrite ltn_modp. rewrite size_addl mulrC. by rewrite !size_mul // (polySpred pn0) !addSn /= ltn_add2l ltn_modp. rewrite size_mul // (polySpred qn0) addnS /=. by apply: leq_trans (leq_addr _ _); rewrite ltn_modp. case: (edivpP _ e s) => //; rewrite lead_coefM unitrM_comm ?ulcp //. by red; rewrite mulrC. Qed. Lemma divpAC p q : lead_coef p \in GRing.unit -> q %/ d %/ p = q %/ p %/ d. Proof. by move=> ulcp; rewrite !divp_divl // mulrC. Qed. Lemma modpZr c p : c \in GRing.unit -> p %% (c *: d) = (p %% d). Proof. case: (eqVneq d 0) => [-> | dn0 cn0]; first by rewrite scaler0 !modp0. have e : p = (c^-1 *: (p %/ d)) * (c *: d) + (p %% d). by rewrite scalerCA scalerA mulVr // scale1r -(divp_eq ulcd). suff s : size (p %% d) < size (c *: d). by rewrite (modpP _ e s) // -mul_polyC lead_coefM lead_coefC unitrM cn0. by rewrite size_scale ?ltn_modp //; apply: contraTneq cn0 => ->; rewrite unitr0. Qed. Lemma divpZr c p : c \in GRing.unit -> p %/ (c *: d) = c^-1 *: (p %/ d). Proof. case: (eqVneq d 0) => [-> | dn0 cn0]; first by rewrite scaler0 !divp0 scaler0. have e : p = (c^-1 *: (p %/ d)) * (c *: d) + (p %% d). by rewrite scalerCA scalerA mulVr // scale1r -(divp_eq ulcd). suff s : size (p %% d) < size (c *: d). by rewrite (divpP _ e s) // -mul_polyC lead_coefM lead_coefC unitrM cn0. by rewrite size_scale ?ltn_modp //; apply: contraTneq cn0 => ->; rewrite unitr0. Qed. End MoreUnitDivisor. End IdomainUnit. Module Field. Import Ring ComRing UnitRing. Include IdomainDefs. Export IdomainDefs. Include CommonIdomain. Section FieldDivision. Variable F : fieldType. Implicit Type p q r d : {poly F}. Lemma divp_eq p q : p = (p %/ q) * q + (p %% q). Proof. have [-> | qn0] := eqVneq q 0; first by rewrite modp0 mulr0 add0r. by apply: IdomainUnit.divp_eq; rewrite unitfE lead_coef_eq0. Qed. Lemma divp_modpP p q d r : p = q * d + r -> size r < size d -> q = (p %/ d) /\ r = p %% d. Proof. move=> he hs; apply: IdomainUnit.edivpP => //; rewrite unitfE lead_coef_eq0. by rewrite -size_poly_gt0; apply: leq_trans hs. Qed. Lemma divpP p q d r : p = q * d + r -> size r < size d -> q = (p %/ d). Proof. by move/divp_modpP=> h; case/h. Qed. Lemma modpP p q d r : p = q * d + r -> size r < size d -> r = (p %% d). Proof. by move/divp_modpP=> h; case/h. Qed. Lemma eqpfP p q : p %= q -> p = (lead_coef p / lead_coef q) *: q. Proof. have [->|nz_q] := eqVneq q 0; first by rewrite eqp0 scaler0 => /eqP ->. by apply/IdomainUnit.ucl_eqp_eq; rewrite unitfE lead_coef_eq0. Qed. Lemma dvdp_eq q p : (q %| p) = (p == p %/ q * q). Proof. have [-> | qn0] := eqVneq q 0; first by rewrite dvd0p mulr0 eq_sym. by apply: IdomainUnit.dvdp_eq; rewrite unitfE lead_coef_eq0. Qed. Lemma eqpf_eq p q : reflect (exists2 c, c != 0 & p = c *: q) (p %= q). Proof. apply: (iffP idP); last first. case=> c nz_c ->; apply/eqpP. by exists (1, c); rewrite ?scale1r ?oner_eq0. have [->|nz_q] := eqVneq q 0. by rewrite eqp0=> /eqP ->; exists 1; rewrite ?scale1r ?oner_eq0. case/IdomainUnit.ulc_eqpP; first by rewrite unitfE lead_coef_eq0. by move=> c nz_c ->; exists c. Qed. Lemma modpZl c p q : (c *: p) %% q = c *: (p %% q). Proof. have [-> | qn0] := eqVneq q 0; first by rewrite !modp0. by apply: IdomainUnit.modpZl; rewrite unitfE lead_coef_eq0. Qed. Lemma mulpK p q : q != 0 -> p * q %/ q = p. Proof. by move=> qn0; rewrite IdomainUnit.mulpK // unitfE lead_coef_eq0. Qed. Lemma mulKp p q : q != 0 -> q * p %/ q = p. Proof. by rewrite mulrC; apply: mulpK. Qed. Lemma divpZl c p q : (c *: p) %/ q = c *: (p %/ q). Proof. have [-> | qn0] := eqVneq q 0; first by rewrite !divp0 scaler0. by apply: IdomainUnit.divpZl; rewrite unitfE lead_coef_eq0. Qed. Lemma modpZr c p d : c != 0 -> p %% (c *: d) = (p %% d). Proof. case: (eqVneq d 0) => [-> | dn0 cn0]; first by rewrite scaler0 !modp0. have e : p = (c^-1 *: (p %/ d)) * (c *: d) + (p %% d). by rewrite scalerCA scalerA mulVf // scale1r -divp_eq. suff s : size (p %% d) < size (c *: d) by rewrite (modpP e s). by rewrite size_scale ?ltn_modp. Qed. Lemma divpZr c p d : c != 0 -> p %/ (c *: d) = c^-1 *: (p %/ d). Proof. case: (eqVneq d 0) => [-> | dn0 cn0]; first by rewrite scaler0 !divp0 scaler0. have e : p = (c^-1 *: (p %/ d)) * (c *: d) + (p %% d). by rewrite scalerCA scalerA mulVf // scale1r -divp_eq. suff s : size (p %% d) < size (c *: d) by rewrite (divpP e s). by rewrite size_scale ?ltn_modp. Qed. Lemma eqp_modpl d p q : p %= q -> (p %% d) %= (q %% d). Proof. case/eqpP=> [[c1 c2]] /andP /= [c1n0 c2n0 e]. by apply/eqpP; exists (c1, c2); rewrite ?c1n0 // -!modpZl e. Qed. Lemma eqp_divl d p q : p %= q -> (p %/ d) %= (q %/ d). Proof. case/eqpP=> [[c1 c2]] /andP /= [c1n0 c2n0 e]. by apply/eqpP; exists (c1, c2); rewrite ?c1n0 // -!divpZl e. Qed. Lemma eqp_modpr d p q : p %= q -> (d %% p) %= (d %% q). Proof. case/eqpP=> [[c1 c2]] /andP [c1n0 c2n0 e]. have -> : p = (c1^-1 * c2) *: q by rewrite -scalerA -e scalerA mulVf // scale1r. by rewrite modpZr ?eqpxx // mulf_eq0 negb_or invr_eq0 c1n0. Qed. Lemma eqp_mod p1 p2 q1 q2 : p1 %= p2 -> q1 %= q2 -> p1 %% q1 %= p2 %% q2. Proof. move=> e1 e2; exact: eqp_trans (eqp_modpl _ e1) (eqp_modpr _ e2). Qed. Lemma eqp_divr (d m n : {poly F}) : m %= n -> (d %/ m) %= (d %/ n). Proof. case/eqpP=> [[c1 c2]] /andP [c1n0 c2n0 e]. have -> : m = (c1^-1 * c2) *: n by rewrite -scalerA -e scalerA mulVf // scale1r. by rewrite divpZr ?eqp_scale // ?invr_eq0 mulf_eq0 negb_or invr_eq0 c1n0. Qed. Lemma eqp_div p1 p2 q1 q2 : p1 %= p2 -> q1 %= q2 -> p1 %/ q1 %= p2 %/ q2. Proof. move=> e1 e2; exact: eqp_trans (eqp_divl _ e1) (eqp_divr _ e2). Qed. Lemma eqp_gdcor p q r : q %= r -> gdcop p q %= gdcop p r. Proof. move=> eqr; rewrite /gdcop (eqp_size eqr). move: (size r)=> n; elim: n p q r eqr => [|n ihn] p q r; first by rewrite eqpxx. move=> eqr /=; rewrite (eqp_coprimepl p eqr); case: ifP => _ //. exact/ihn/eqp_div/eqp_gcdl. Qed. Lemma eqp_gdcol p q r : q %= r -> gdcop q p %= gdcop r p. Proof. move=> eqr; rewrite /gdcop; move: (size p)=> n. elim: n p q r eqr {1 3}p (eqpxx p) => [|n ihn] p q r eqr s esp /=. case: (eqVneq q 0) eqr => [-> | nq0 eqr] /=. by rewrite eqp_sym eqp0 => ->; rewrite eqpxx. by case: (eqVneq r 0) eqr nq0 => [->|]; rewrite ?eqpxx // eqp0 => ->. rewrite (eqp_coprimepr _ eqr) (eqp_coprimepl _ esp); case: ifP=> _ //. exact/ihn/eqp_div/eqp_gcd. Qed. Lemma eqp_rgdco_gdco q p : rgdcop q p %= gdcop q p. Proof. rewrite /rgdcop /gdcop; move: (size p)=> n. elim: n p q {1 3}p {1 3}q (eqpxx p) (eqpxx q) => [|n ihn] p q s t /= sp tq. case: (eqVneq t 0) tq => [-> | nt0 etq]. by rewrite eqp_sym eqp0 => ->; rewrite eqpxx. by case: (eqVneq q 0) etq nt0 => [->|]; rewrite ?eqpxx // eqp0 => ->. rewrite rcoprimep_coprimep (eqp_coprimepl t sp) (eqp_coprimepr p tq). case: ifP=> // _; apply: ihn => //; apply: eqp_trans (eqp_rdiv_div _ _) _. by apply: eqp_div => //; apply: eqp_trans (eqp_rgcd_gcd _ _) _; apply: eqp_gcd. Qed. Lemma modpD d p q : (p + q) %% d = p %% d + q %% d. Proof. have [-> | dn0] := eqVneq d 0; first by rewrite !modp0. by apply: IdomainUnit.modpD; rewrite unitfE lead_coef_eq0. Qed. Lemma modpN p q : (- p) %% q = - (p %% q). Proof. by apply/eqP; rewrite -addr_eq0 -modpD addNr mod0p. Qed. Lemma modNp p q : (- p) %% q = - (p %% q). Proof. exact: modpN. Qed. Lemma divpD d p q : (p + q) %/ d = p %/ d + q %/ d. Proof. have [-> | dn0] := eqVneq d 0; first by rewrite !divp0 addr0. by apply: IdomainUnit.divpD; rewrite unitfE lead_coef_eq0. Qed. Lemma divpN p q : (- p) %/ q = - (p %/ q). Proof. by apply/eqP; rewrite -addr_eq0 -divpD addNr div0p. Qed. Lemma divp_addl_mul_small d q r : size r < size d -> (q * d + r) %/ d = q. Proof. move=> srd; rewrite divpD (divp_small srd) addr0 mulpK // -size_poly_gt0. exact: leq_trans srd. Qed. Lemma modp_addl_mul_small d q r : size r < size d -> (q * d + r) %% d = r. Proof. by move=> srd; rewrite modpD modp_mull add0r modp_small. Qed. Lemma divp_addl_mul d q r : d != 0 -> (q * d + r) %/ d = q + r %/ d. Proof. by move=> dn0; rewrite divpD mulpK. Qed. Lemma divpp d : d != 0 -> d %/ d = 1. Proof. by move=> dn0; apply: IdomainUnit.divpp; rewrite unitfE lead_coef_eq0. Qed. Lemma leq_trunc_divp d m : size (m %/ d * d) <= size m. Proof. have [-> | dn0] := eqVneq d 0; first by rewrite mulr0 size_poly0. by apply: IdomainUnit.leq_trunc_divp; rewrite unitfE lead_coef_eq0. Qed. Lemma divpK d p : d %| p -> p %/ d * d = p. Proof. case: (eqVneq d 0) => [-> /dvd0pP -> | dn0]; first by rewrite mulr0. by apply: IdomainUnit.divpK; rewrite unitfE lead_coef_eq0. Qed. Lemma divpKC d p : d %| p -> d * (p %/ d) = p. Proof. by move=> ?; rewrite mulrC divpK. Qed. Lemma dvdp_eq_div d p q : d != 0 -> d %| p -> (q == p %/ d) = (q * d == p). Proof. by move=> dn0; apply: IdomainUnit.dvdp_eq_div; rewrite unitfE lead_coef_eq0. Qed. Lemma dvdp_eq_mul d p q : d != 0 -> d %| p -> (p == q * d) = (p %/ d == q). Proof. by move=> dn0 dv_d_p; rewrite eq_sym -dvdp_eq_div // eq_sym. Qed. Lemma divp_mulA d p q : d %| q -> p * (q %/ d) = p * q %/ d. Proof. case: (eqVneq d 0) => [-> /dvd0pP -> | dn0]; first by rewrite !divp0 mulr0. by apply: IdomainUnit.divp_mulA; rewrite unitfE lead_coef_eq0. Qed. Lemma divp_mulAC d m n : d %| m -> m %/ d * n = m * n %/ d. Proof. by move=> hdm; rewrite mulrC (mulrC m); apply: divp_mulA. Qed. Lemma divp_mulCA d p q : d %| p -> d %| q -> p * (q %/ d) = q * (p %/ d). Proof. by move=> hdp hdq; rewrite mulrC divp_mulAC // divp_mulA. Qed. Lemma expp_sub d m n : d != 0 -> m >= n -> (d ^+ (m - n))%N = d ^+ m %/ d ^+ n. Proof. by move=> dn0 /subnK=> {2}<-; rewrite exprD mulpK // expf_neq0. Qed. Lemma divp_pmul2l d q p : d != 0 -> q != 0 -> d * p %/ (d * q) = p %/ q. Proof. by move=> dn0 qn0; apply: IdomainUnit.divp_pmul2l; rewrite unitfE lead_coef_eq0. Qed. Lemma divp_pmul2r d p q : d != 0 -> p != 0 -> q * d %/ (p * d) = q %/ p. Proof. by move=> dn0 qn0; rewrite -!(mulrC d) divp_pmul2l. Qed. Lemma divp_divl r p q : q %/ p %/ r = q %/ (p * r). Proof. have [-> | rn0] := eqVneq r 0; first by rewrite mulr0 !divp0. have [-> | pn0] := eqVneq p 0; first by rewrite mul0r !divp0 div0p. by apply: IdomainUnit.divp_divl; rewrite unitfE lead_coef_eq0. Qed. Lemma divpAC d p q : q %/ d %/ p = q %/ p %/ d. Proof. by rewrite !divp_divl // mulrC. Qed. Lemma edivp_def p q : edivp p q = (0%N, p %/ q, p %% q). Proof. rewrite Idomain.edivp_def; congr (_, _, _); rewrite /scalp 2!unlock /=. have [-> | qn0] := eqVneq; first by rewrite lead_coef0 unitr0. by rewrite unitfE lead_coef_eq0 qn0 /=; case: (redivp_rec _ _ _ _) => [[]]. Qed. Lemma divpE p q : p %/ q = (lead_coef q)^-(rscalp p q) *: (rdivp p q). Proof. have [-> | qn0] := eqVneq q 0; first by rewrite rdivp0 divp0 scaler0. by rewrite Idomain.divpE unitfE lead_coef_eq0 qn0. Qed. Lemma modpE p q : p %% q = (lead_coef q)^-(rscalp p q) *: (rmodp p q). Proof. have [-> | qn0] := eqVneq q 0. by rewrite rmodp0 modp0 /rscalp unlock eqxx lead_coef0 expr0 invr1 scale1r. by rewrite Idomain.modpE unitfE lead_coef_eq0 qn0. Qed. Lemma scalpE p q : scalp p q = 0%N. Proof. have [-> | qn0] := eqVneq q 0; first by rewrite scalp0. by rewrite Idomain.scalpE unitfE lead_coef_eq0 qn0. Qed. (* Just to have it without importing the weak theory *) Lemma dvdpE p q : p %| q = rdvdp p q. Proof. exact: Idomain.dvdpE. Qed. Variant edivp_spec m d : nat * {poly F} * {poly F} -> Type := EdivpSpec n q r of m = q * d + r & (d != 0) ==> (size r < size d) : edivp_spec m d (n, q, r). Lemma edivpP m d : edivp_spec m d (edivp m d). Proof. rewrite edivp_def; constructor; first exact: divp_eq. by apply/implyP=> dn0; rewrite ltn_modp. Qed. Lemma edivp_eq d q r : size r < size d -> edivp (q * d + r) d = (0%N, q, r). Proof. move=> srd; apply: Idomain.edivp_eq; rewrite // unitfE lead_coef_eq0. by rewrite -size_poly_gt0; apply: leq_trans srd. Qed. Lemma modp_mul p q m : (p * (q %% m)) %% m = (p * q) %% m. Proof. by rewrite [in RHS](divp_eq q m) mulrDr modpD mulrA modp_mull add0r. Qed. Lemma dvdpP p q : reflect (exists qq, p = qq * q) (q %| p). Proof. have [-> | qn0] := eqVneq q 0; last first. by apply: IdomainUnit.dvdpP; rewrite unitfE lead_coef_eq0. by rewrite dvd0p; apply: (iffP eqP) => [->| [? ->]]; [exists 1|]; rewrite mulr0. Qed. Lemma Bezout_eq1_coprimepP p q : reflect (exists u, u.1 * p + u.2 * q = 1) (coprimep p q). Proof. apply: (iffP idP)=> [hpq|]; last first. by case=> [[u v]] /= e; apply/Bezout_coprimepP; exists (u, v); rewrite e eqpxx. case/Bezout_coprimepP: hpq => [[u v]] /=. case/eqpP=> [[c1 c2]] /andP /= [c1n0 c2n0] e. exists (c2^-1 *: (c1 *: u), c2^-1 *: (c1 *: v)); rewrite /= -!scalerAl. by rewrite -!scalerDr e scalerA mulVf // scale1r. Qed. Lemma dvdp_gdcor p q : q != 0 -> p %| (gdcop q p) * (q ^+ size p). Proof. rewrite /gdcop => nz_q; have [n hsp] := ubnPleq (size p). elim: n => [|n IHn] /= in p hsp *; first by rewrite (negPf nz_q) mul0r dvdp0. have [_ | ncop_pq] := ifPn; first by rewrite dvdp_mulr. have g_gt1: 1 < size (gcdp p q). rewrite ltn_neqAle eq_sym ncop_pq size_poly_gt0 gcdp_eq0. by rewrite negb_and nz_q orbT. have [-> | nz_p] := eqVneq p 0. by rewrite div0p exprSr mulrA dvdp_mulr // IHn // size_poly0. have le_d_p: size (p %/ gcdp p q) < size p. rewrite size_divp -?size_poly_eq0 -(subnKC g_gt1) // add2n /=. by rewrite polySpred // ltnS subSS leq_subr. rewrite -[p in p %| _](divpK (dvdp_gcdl p q)) exprSr mulrA. by rewrite dvdp_mul ?IHn ?dvdp_gcdr // -ltnS (leq_trans le_d_p). Qed. Lemma reducible_cubic_root p q : size p <= 4 -> 1 < size q < size p -> q %| p -> {r | root p r}. Proof. move=> p_le4 /andP[]; rewrite leq_eqVlt eq_sym. have [/poly2_root[x qx0] _ _ | _ /= q_gt2 p_gt_q] := size q =P 2%N. by exists x; rewrite -!dvdp_XsubCl in qx0 *; apply: (dvdp_trans qx0). case/dvdpP/sig_eqW=> r def_p; rewrite def_p. suffices /poly2_root[x rx0]: size r = 2%N by exists x; rewrite rootM rx0. have /norP[nz_r nz_q]: ~~ [|| r == 0 | q == 0]. by rewrite -mulf_eq0 -def_p -size_poly_gt0 (leq_ltn_trans _ p_gt_q). rewrite def_p size_mul // -subn1 leq_subLR ltn_subRL in p_gt_q p_le4. by apply/eqP; rewrite -(eqn_add2r (size q)) eqn_leq (leq_trans p_le4). Qed. Lemma cubic_irreducible p : 1 < size p <= 4 -> (forall x, ~~ root p x) -> irreducible_poly p. Proof. move=> /andP[p_gt1 p_le4] root'p; split=> // q sz_q_neq1 q_dv_p. have nz_p: p != 0 by rewrite -size_poly_gt0 ltnW. have nz_q: q != 0 by apply: contraTneq q_dv_p => ->; rewrite dvd0p. have q_gt1: size q > 1 by rewrite ltn_neqAle eq_sym sz_q_neq1 size_poly_gt0. rewrite -dvdp_size_eqp // eqn_leq dvdp_leq //= leqNgt; apply/negP=> p_gt_q. by have [|x /idPn//] := reducible_cubic_root p_le4 _ q_dv_p; rewrite q_gt1. Qed. Section FieldRingMap. Variable rR : ringType. Variable f : {rmorphism F -> rR}. Local Notation "p ^f" := (map_poly f p) : ring_scope. Implicit Type a b : {poly F}. Lemma redivp_map a b : redivp a^f b^f = (rscalp a b, (rdivp a b)^f, (rmodp a b)^f). Proof. rewrite /rdivp /rscalp /rmodp !unlock map_poly_eq0 size_map_poly. have [// | q_nz] := ifPn; rewrite -(rmorph0 (map_poly_rmorphism f)) //. have [m _] := ubnPeq (size a); elim: m 0%N 0 a => [|m IHm] qq r a /=. rewrite -!mul_polyC !size_map_poly !lead_coef_map // -(map_polyXn f). by rewrite -!(map_polyC f) -!rmorphM -rmorphB -rmorphD; case: (_ < _). rewrite -!mul_polyC !size_map_poly !lead_coef_map // -(map_polyXn f). by rewrite -!(map_polyC f) -!rmorphM -rmorphB -rmorphD /= IHm; case: (_ < _). Qed. End FieldRingMap. Section FieldMap. Variable rR : idomainType. Variable f : {rmorphism F -> rR}. Local Notation "p ^f" := (map_poly f p) : ring_scope. Implicit Type a b : {poly F}. Lemma edivp_map a b : edivp a^f b^f = (0%N, (a %/ b)^f, (a %% b)^f). Proof. have [-> | bn0] := eqVneq b 0. rewrite (rmorph0 (map_poly_rmorphism f)) WeakIdomain.edivp_def !modp0 !divp0. by rewrite (rmorph0 (map_poly_rmorphism f)) scalp0. rewrite unlock redivp_map lead_coef_map rmorph_unit; last first. by rewrite unitfE lead_coef_eq0. rewrite modpE divpE !map_polyZ !rmorphV ?rmorphX // unitfE. by rewrite expf_neq0 // lead_coef_eq0. Qed. Lemma scalp_map p q : scalp p^f q^f = scalp p q. Proof. by rewrite /scalp edivp_map edivp_def. Qed. Lemma map_divp p q : (p %/ q)^f = p^f %/ q^f. Proof. by rewrite /divp edivp_map edivp_def. Qed. Lemma map_modp p q : (p %% q)^f = p^f %% q^f. Proof. by rewrite /modp edivp_map edivp_def. Qed. Lemma egcdp_map p q : egcdp (map_poly f p) (map_poly f q) = (map_poly f (egcdp p q).1, map_poly f (egcdp p q).2). Proof. wlog le_qp: p q / size q <= size p. move=> IH; have [/IH// | lt_qp] := leqP (size q) (size p). have /IH := ltnW lt_qp; rewrite /egcdp !size_map_poly ltnW // leqNgt lt_qp /=. by case: (egcdp_rec _ _ _) => u v [-> ->]. rewrite /egcdp !size_map_poly {}le_qp; move: (size q) => n. elim: n => /= [|n IHn] in p q *; first by rewrite rmorph1 rmorph0. rewrite map_poly_eq0; have [_ | nz_q] := ifPn; first by rewrite rmorph1 rmorph0. rewrite -map_modp (IHn q (p %% q)); case: (egcdp_rec _ _ n) => u v /=. by rewrite map_polyZ lead_coef_map -rmorphX scalp_map rmorphB rmorphM -map_divp. Qed. Lemma dvdp_map p q : (p^f %| q^f) = (p %| q). Proof. by rewrite /dvdp -map_modp map_poly_eq0. Qed. Lemma eqp_map p q : (p^f %= q^f) = (p %= q). Proof. by rewrite /eqp !dvdp_map. Qed. Lemma gcdp_map p q : (gcdp p q)^f = gcdp p^f q^f. Proof. wlog lt_p_q: p q / size p < size q. move=> IHpq; case: (ltnP (size p) (size q)) => [|le_q_p]; first exact: IHpq. rewrite gcdpE (gcdpE p^f) !size_map_poly ltnNge le_q_p /= -map_modp. have [-> | q_nz] := eqVneq q 0; first by rewrite rmorph0 !gcdp0. by rewrite IHpq ?ltn_modp. have [m le_q_m] := ubnP (size q); elim: m => // m IHm in p q lt_p_q le_q_m *. rewrite gcdpE (gcdpE p^f) !size_map_poly lt_p_q -map_modp. have [-> | q_nz] := eqVneq p 0; first by rewrite rmorph0 !gcdp0. by rewrite IHm ?(leq_trans lt_p_q) ?ltn_modp. Qed. Lemma coprimep_map p q : coprimep p^f q^f = coprimep p q. Proof. by rewrite -!gcdp_eqp1 -eqp_map rmorph1 gcdp_map. Qed. Lemma gdcop_rec_map p q n : (gdcop_rec p q n)^f = gdcop_rec p^f q^f n. Proof. elim: n p q => [|n IH] => /= p q. by rewrite map_poly_eq0; case: eqP; rewrite ?rmorph1 ?rmorph0. rewrite /coprimep -gcdp_map size_map_poly. by case: eqP => Hq0 //; rewrite -map_divp -IH. Qed. Lemma gdcop_map p q : (gdcop p q)^f = gdcop p^f q^f. Proof. by rewrite /gdcop gdcop_rec_map !size_map_poly. Qed. End FieldMap. End FieldDivision. End Field. Module ClosedField. Import Field. Section closed. Variable F : closedFieldType. Lemma root_coprimep (p q : {poly F}): (forall x, root p x -> q.[x] != 0) -> coprimep p q. Proof. move=> Ncmn; rewrite -gcdp_eqp1 -size_poly_eq1; apply/closed_rootP. by case=> r; rewrite root_gcd !rootE=> /andP [/Ncmn/negPf->]. Qed. Lemma coprimepP (p q : {poly F}): reflect (forall x, root p x -> q.[x] != 0) (coprimep p q). Proof. by apply: (iffP idP)=> [/coprimep_root|/root_coprimep]. Qed. End closed. End ClosedField. End Pdiv. Export Pdiv.Field.
Require Import Coq.Lists.List. Require Import ExtLib.Tactics. Require Import ExtLib.Data.HList. Require Import ExtLib.Data.ListNth. Require Import MirrorCore.TypesI. Set Implicit Arguments. Set Strict Implicit. Set Printing Universes. Polymorphic Lemma f_eq@{A B} : forall {T : Type@{A}} {U : Type@{B}} (f : T -> U) (a b : T), a = b -> f a = f b. Proof. intros. destruct H. reflexivity. Defined. Section Env. Variable typ : Set. Context {RType_typ : RType typ}. (** Environments **) Definition tenv : Set := list typ. Definition env : Type@{Urefl} := list (sigT (@typD _ _)). Definition typeof_env (e : env) : tenv := map (@projT1 _ _) e. Fixpoint valof_env (e : env) : hlist typD (typeof_env e) := match e as e return hlist typD (typeof_env e) with | nil => Hnil | t :: ts => Hcons (projT2 t) (valof_env ts) end. Definition lookupAs (e : env) (n : nat) (ty : typ) : option (typD ty) := match nth_error e n with | None => None | Some (existT _ t v) => match type_cast ty t with | Some pf => Some (Relim (fun x => x) pf v) | None => None end end. Theorem lookupAs_weaken : forall (a b : env) n t x, lookupAs a n t = Some x -> lookupAs (a ++ b) n t = Some x. Proof. clear. unfold lookupAs. intros. consider (nth_error a n); intros. { erewrite nth_error_weaken by eassumption. auto. } { exfalso. refine match H0 in _ = x return match x return Prop with | None => True | Some _ => False end with | eq_refl => I end. } Qed. Fixpoint join_env@{} (gs : list typ) (hgs : hlist@{Set Urefl} (@typD _ _) gs) : env := match hgs with | Hnil => nil | Hcons c d => existT _ _ c :: join_env d end. Fixpoint split_env@{} (gs : env) : sigT (hlist@{Set Urefl} (@typD _ _)) := match gs with | nil => existT _ nil Hnil | g :: gs => let res := split_env gs in existT _ (projT1 g :: projT1 res) (Hcons (projT2 g) (projT2 res)) end. Theorem split_env_app : forall (gs gs' : env), split_env (gs ++ gs') = let (a,b) := split_env gs in let (c,d) := split_env gs' in existT _ ((a ++ c) : list (typ : Set)) (hlist_app b d). Proof. induction gs; simpl; intros. { destruct (split_env gs'); reflexivity. } { destruct a. rewrite IHgs. destruct (split_env gs). destruct (split_env gs'). reflexivity. } Qed. Theorem split_env_projT1@{} : forall (x : env), projT1 (split_env x) = map (@projT1 _ _) x. Proof. induction x; simpl; intros; auto. f_equal. auto. Qed. Theorem split_env_typeof_env@{} : forall (x : env), projT1 (split_env x) = typeof_env x. Proof. exact split_env_projT1. Qed. Lemma join_env_app : forall a b (ax : hlist _ a) (bx : hlist _ b), join_env ax ++ join_env bx = join_env (hlist_app ax bx). Proof. refine (fix rec (a b : list typ) (ax : hlist@{Set Urefl} _ _) {struct ax} := match ax with | Hnil => _ | Hcons _ _ => _ end). reflexivity. simpl. intro. rewrite rec. reflexivity. Qed. Theorem split_env_nth_error : forall (ve : env) v tv, nth_error ve v = Some tv <-> match nth_error (projT1 (split_env ve)) v as t return match t return Type@{Urefl} with | Some v => typD v | None => unit end -> Prop with | None => fun _ => False | Some v => fun res => tv = existT _ v res end (hlist_nth (projT2 (split_env ve)) v). Proof. clear. induction ve; simpl; intros. { destruct v; simpl in *; intuition; inversion H. } { destruct v; simpl in *. { intuition. { inversion H; subst. destruct tv; reflexivity. } { subst. destruct a. reflexivity. } } { eapply IHve. } } Qed. Lemma split_env_nth_error_None : forall (ve : env) (v : nat), nth_error ve v = None <-> nth_error (projT1 (split_env ve)) v = None. Proof. clear. induction ve; simpl; intros. { destruct v; simpl; intuition. } { destruct v; simpl. { unfold value. intuition congruence. } { rewrite IHve; auto. reflexivity. } } Qed. Lemma split_env_length : forall (a : env), length a = length (projT1 (split_env a)). Proof. induction a; simpl; auto. Qed. Theorem split_env_join_env : forall (a : tenv) b, split_env (@join_env a b) = existT _ a b. Proof. induction b; simpl; auto. rewrite IHb. eauto. Qed. Theorem join_env_split_env : forall x, join_env (projT2 (split_env x)) = x. Proof. induction x; simpl; auto. rewrite IHx. destruct a; reflexivity. Qed. Lemma split_env_projT2_join_env@{} : forall (x : tenv) (h : hlist@{Set Urefl} _ x) (vs : env), split_env vs = @existT _ _ x h -> vs = join_env h. Proof. induction h using (@hlist_ind@{Set Urefl Set}); destruct vs; simpl; intros; inversion H; auto. subst. rewrite join_env_split_env. destruct s; auto. Qed. Lemma typeof_env_join_env@{} : forall a (b : hlist _ a), typeof_env (join_env b) = a. Proof. induction a; simpl; intros. { rewrite (HList.hlist_eta b). reflexivity. } { rewrite (HList.hlist_eta b). simpl. rewrite IHa. reflexivity. } Qed. Lemma map_projT1_split_env@{} : forall vs x h, split_env vs = existT (hlist _) x h -> map (@projT1 _ _) vs = x. Proof. intros. change x with (projT1 (existT _ x h)). rewrite <- H. rewrite split_env_projT1. reflexivity. Qed. Lemma nth_error_join_env@{} : forall (ls : tenv) (hls : hlist@{Set Urefl} _ ls) v t, nth_error ls v = Some t -> exists val, nth_error (join_env hls) v = Some (@existT _ _ t val). Proof. clear. induction hls using (@hlist_ind@{Set Urefl Set}); simpl; intros. { destruct v; inversion H. } { destruct v; simpl in *; eauto. inversion H; clear H; subst. eauto. } Qed. Theorem split_env_eta@{} : forall (vs : env), split_env vs = existT _ (typeof_env vs) (valof_env vs). Proof. induction vs; simpl; auto. rewrite IHvs. simpl. reflexivity. Qed. End Env. Arguments env {typ _} : rename. Arguments join_env {typ _ _} _ : rename. Arguments split_env {typ _} _ : rename.
""" Imitate playing sounds by choirs or ensembles. Author: Nikolay Lysenko """ from typing import Any, Dict, List import numpy as np from sinethesizer.effects.vibrato import apply_vibrato from sinethesizer.utils.misc import sum_two_sounds def apply_chorus( sound: np.ndarray, event: 'sinethesizer.synth.core.Event', original_sound_gain: float, copies_params: List[Dict[str, Any]] ) -> np.ndarray: """ Apply chorus effect (or flanger effect if delay times are small enough). :param sound: sound to be modified :param event: parameters of sound event for which this function is called :param original_sound_gain: amplitude gain for original non-delayed sound :param copies_params: list of dictionaries each of which contains: 1) delay time for a current copy; 2) amplitude gain for the copy; 3) parameters of vibrato that should be applied to the copy :return: enriched sound somehow resembling sounds produced by choirs or ensembles """ processed_copies = [] for copy_params in copies_params: delay_in_sec = copy_params.pop('delay') gain = copy_params.pop('gain') detuned_copy = apply_vibrato(sound, event, **copy_params) detuned_copy *= gain n_frames_with_silence = int(round(delay_in_sec * event.frame_rate)) silence = np.zeros((sound.shape[0], n_frames_with_silence)) processed_copy = np.hstack((silence, detuned_copy)) processed_copies.append(processed_copy) sound *= original_sound_gain for processed_copy in processed_copies: sound = sum_two_sounds(sound, processed_copy) return sound
include("1.jl") include("5.jl") function smallsquare(r::Robot) angleofsquare(r) i = mod(snake(r,West),2) if (i == 1) i = 1 else i = 3 end for side in (HorizonSide(mod(i, 4)),Nord,HorizonSide(mod(i+2, 4)),Sud) putmarker!(r) putmarkhole1(r,side,mod(i+2,4)) move!(r,HorizonSide(mod(Int(side) + (i+2), 4))) end end function snake(r::Robot,side1::HorizonSide) i = 0 while !isborder(r,Nord) if isborder(r,Ost) movehole1(r,side1) else movehole1(r,inverse(side1)) end if isborder(r,Ost) || isborder(r,West) move!(r,Nord) end i+=1 end return i end function movehole1(r::Robot,side::HorizonSide) while (!isborder(r,side)) move!(r,side) if (isborder(r,Nord)) break end end end function putmarkhole1(r::Robot,side::HorizonSide,i::Int64) while isborder(r,HorizonSide(mod(Int(side) + i, 4))) move!(r,side) putmarker!(r) end end
/* * Copyright 2015 by Philip N. Garner * * See the file COPYING for the licence associated with this software. * * Author(s): * Phil Garner, June 2015 */ #include "lube/graph.h" #include <fstream> #include <boost/graph/adjacency_list.hpp> #include <boost/graph/graphviz.hpp> namespace libube { typedef boost::adjacency_list< boost::vecS, boost::vecS, boost::bidirectionalS, var, var > adjacency_list; typedef boost::graph_traits<adjacency_list>::vertex_descriptor vertex; typedef boost::graph_traits<adjacency_list>::edge_descriptor edge; /** Concrete implementation of graph module */ class Graph : public graph { public: Graph(var iArg) {}; void addEdge(ind iVertex1, ind iVertex2); ind addVertex(); void writeGraphViz(var iFileName); private: adjacency_list mGraph; }; /** Factory function to create a class */ void factory(Module** oModule, var iArg) { *oModule = new Graph(iArg); } }; using namespace libube; void Graph::addEdge(ind iVertex1, ind iVertex2) { // An edge is some non-trivial thing; it does ot cast to an integer type std::pair<edge, bool> ret; ret = add_edge(iVertex1, iVertex2, mGraph); } ind Graph::addVertex() { // A vertex is just an index; at least, it can be cast to an ind. So we // can return an ind vertex v = add_vertex(mGraph); return v; } class LabelWriter { public: LabelWriter(adjacency_list& iGraph) : mGraph(iGraph) {} template <class VertexOrEdge> void operator()(std::ostream& iOut, const VertexOrEdge& iV) const { var v = mGraph[iV]; if (v.index("NAME")) // Should replace with escaped quote rather than nothing iOut << "[label=\"" << v.at("NAME").replace("\"", "").str() << "\"]"; } private: adjacency_list& mGraph; }; void Graph::writeGraphViz(var iFileName) { std::ofstream ofs(iFileName.str(), std::ofstream::out); LabelWriter lw(mGraph); write_graphviz(ofs, mGraph, lw); }
module Demo import Data.Vect %default total data Nat' : Type where Z' : Nat' S' : Nat' -> Nat' %name Nat' n,m,o plus' : Nat' -> Nat' -> Nat' plus' Z' m = m plus' (S' n) m = S' (plus' n m) data Vect' : Nat -> Type -> Type where Nil : Vect' Z a (::) : a -> Vect' n a -> Vect' (S n) a %name Vect' xs,ys,zs append : Vect' n a -> Vect' m a -> Vect' (n + m) a append Nil ys = ys append (x :: xs) ys = x :: (append xs ys) zip : Vect' n a -> Vect' n b -> Vect' n (a, b) zip [] [] = [] zip (x :: xs) (y :: ys) = (x, y) :: (zip xs ys) take' : (n : Nat) -> Vect (n + m) a -> Vect n a take' Z xs = [] take' (S k) (x :: xs) = x :: take' k xs drop' : (n : Nat) -> Vect (n + m) a -> Vect m a drop' Z xs = xs drop' (S k) (x :: xs) = drop' k xs data SnocList : List a -> Type where SnocNil : SnocList [] Snoc : (xs : List a) -> (x :a) -> SnocList (xs ++ [x]) snocced : (xs : List a) -> SnocList xs snocced [] = SnocNil snocced (x :: xs) with (snocced xs) snocced (x :: []) | SnocNil = Snoc [] x snocced (x :: (ys ++ [y])) | (Snoc ys y) = Snoc (x :: ys) y rot : Nat -> List a -> List a rot Z xs = xs rot (S k) xs with (snocced xs) rot (S k) [] | SnocNil = [] rot (S k) (ys ++ [x]) | (Snoc ys x) = rot k (x::ys)
Formal statement is: lemma nonzero_of_real_inverse: "x \<noteq> 0 \<Longrightarrow> of_real (inverse x) = inverse (of_real x :: 'a::real_div_algebra)" Informal statement is: If $x \neq 0$, then $\frac{1}{x} = \frac{1}{\overline{x}}$.
#include "fake_anemometer.h" #include <stdlib.h> /* srand, rand */ #include <time.h> #include <boost/random.hpp> #include <boost/random/normal_distribution.hpp> typedef boost::normal_distribution<double> NormalDistribution; typedef boost::mt19937 RandomGenerator; typedef boost::variate_generator<RandomGenerator&, \ NormalDistribution> GaussianGenerator; int main( int argc, char** argv ) { ros::init(argc, argv, "simulated_anemometer"); ros::NodeHandle n; ros::NodeHandle pn("~"); srand (time(NULL)); //Read parameters loadNodeParameters(pn); //Publishers //ros::Publisher sensor_read_pub = n.advertise<std_msgs::Float32MultiArray>("WindSensor_reading", 500); ros::Publisher sensor_read_pub = n.advertise<olfaction_msgs::anemometer>("WindSensor_reading", 500); ros::Publisher marker_pub = n.advertise<visualization_msgs::Marker>("WindSensor_display", 100); //Service to request wind values to simulator ros::ServiceClient client = n.serviceClient<gaden_player::WindPosition>("/wind_value"); tf::TransformListener tf_; // Init Visualization data (marker) //---------------------------------------------------------------- // sensor = sphere // conector = stick from the floor to the sensor visualization_msgs::Marker sensor; visualization_msgs::Marker connector; visualization_msgs::Marker connector_inv; visualization_msgs::Marker wind_point; visualization_msgs::Marker wind_point_inv; sensor.header.frame_id = input_fixed_frame.c_str(); sensor.ns = "sensor_visualization"; sensor.action = visualization_msgs::Marker::ADD; sensor.type = visualization_msgs::Marker::SPHERE; sensor.id = 0; sensor.scale.x = 0.1; sensor.scale.y = 0.1; sensor.scale.z = 0.1; sensor.color.r = 0.0f; sensor.color.g = 0.0f; sensor.color.b = 1.0f; sensor.color.a = 1.0; connector.header.frame_id = input_fixed_frame.c_str(); connector.ns = "sensor_visualization"; connector.action = visualization_msgs::Marker::ADD; connector.type = visualization_msgs::Marker::CYLINDER; connector.id = 1; connector.scale.x = 0.1; connector.scale.y = 0.1; connector.color.a = 1.0; connector.color.r = 1.0f; connector.color.b = 1.0f; connector.color.g = 1.0f; // Init Marker: arrow to display the wind direction measured. wind_point.header.frame_id = input_sensor_frame.c_str(); wind_point.action = visualization_msgs::Marker::ADD; wind_point.ns = "measured_wind"; wind_point.type = visualization_msgs::Marker::ARROW; // Init Marker: arrow to display the inverted wind direction measured. wind_point_inv.header.frame_id = input_sensor_frame.c_str(); wind_point_inv.action = visualization_msgs::Marker::ADD; wind_point_inv.ns = "measured_wind_inverted"; wind_point_inv.type = visualization_msgs::Marker::ARROW; // LOOP //---------------------------------------------------------------- tf::TransformListener listener; ros::Rate r(2); while (ros::ok()) { //Vars tf::StampedTransform transform; bool know_sensor_pose = true; //Get pose of the sensor in the /map reference try { listener.lookupTransform(input_fixed_frame.c_str(), input_sensor_frame.c_str(), ros::Time(0), transform); } catch (tf::TransformException ex) { ROS_ERROR("%s",ex.what()); know_sensor_pose = false; ros::Duration(1.0).sleep(); } if (know_sensor_pose) { //Current sensor pose float x_pos = transform.getOrigin().x(); float y_pos = transform.getOrigin().y(); float z_pos = transform.getOrigin().z(); // Get Wind vectors (u,v,w) at current position // Service request to the simulator gaden_player::WindPosition srv; srv.request.x = x_pos; srv.request.y = y_pos; srv.request.z = z_pos; float u,v,w; olfaction_msgs::anemometer anemo_msg; if (client.call(srv)) { double wind_speed; double wind_direction; //GT Wind vector Value (u,v,w)[m/s] //From OpenFoam this is the DownWind direction in the map u = (float)srv.response.u; v = (float)srv.response.v; w = (float)srv.response.w; wind_speed = sqrt(pow(u,2)+pow(v,2)); float downWind_direction_map; if (u !=0 || v!=0) downWind_direction_map = atan2(v,u); else downWind_direction_map = 0.0; if (!use_map_ref_system) { // (IMPORTANT) Follow standards on wind measurement (real anemometers): //return the upwind direction in the anemometer reference system //range [-pi,pi] //positive to the right, negative to the left (opposed to ROS poses :s) float upWind_direction_map = angles::normalize_angle(downWind_direction_map + 3.14159); //Transform from map ref_system to the anemometer ref_system using TF geometry_msgs::PoseStamped anemometer_upWind_pose, map_upWind_pose; try { map_upWind_pose.header.frame_id = input_fixed_frame.c_str(); map_upWind_pose.pose.position.x = 0.0; map_upWind_pose.pose.position.y = 0.0; map_upWind_pose.pose.position.z = 0.0; map_upWind_pose.pose.orientation = tf::createQuaternionMsgFromYaw(upWind_direction_map); tf_.transformPose(input_sensor_frame.c_str(), map_upWind_pose, anemometer_upWind_pose); } catch(tf::TransformException &ex) { ROS_ERROR("FakeAnemometer - %s - Error: %s", __FUNCTION__, ex.what()); } double upwind_direction_anemo = tf::getYaw(anemometer_upWind_pose.pose.orientation); wind_direction = upwind_direction_anemo; } else { // for simulations wind_direction = angles::normalize_angle(downWind_direction_map); } // Adding Noise static RandomGenerator rng(static_cast<unsigned> (time(0))); NormalDistribution gaussian_dist(0.0,noise_std); GaussianGenerator generator(rng, gaussian_dist); wind_direction = wind_direction + generator(); wind_speed = wind_speed + generator(); //Publish 2D Anemometer readings //------------------------------ anemo_msg.header.stamp = ros::Time::now(); if (use_map_ref_system) anemo_msg.header.frame_id = input_fixed_frame.c_str(); else anemo_msg.header.frame_id = input_sensor_frame.c_str(); anemo_msg.sensor_label = "Fake_Anemo"; anemo_msg.wind_direction = wind_direction; //rad anemo_msg.wind_speed = wind_speed; //m/s //Publish fake_anemometer reading (m/s) sensor_read_pub.publish(anemo_msg); //Add wind marker ARROW for Rviz (2D) --> Upwind /* wind_point.header.stamp = ros::Time::now(); wind_point.points.clear(); wind_point.id = 1; //unique identifier for each arrow wind_point.pose.position.x = 0.0; wind_point.pose.position.y = 0.0; wind_point.pose.position.z = 0.0; wind_point.pose.orientation = tf::createQuaternionMsgFromYaw(wind_direction_with_noise); wind_point.scale.x = 2*sqrt(pow(u,2)+pow(v,2)); //arrow lenght wind_point.scale.y = 0.1; //arrow width wind_point.scale.z = 0.1; //arrow height wind_point.color.r = 0.0; wind_point.color.g = 1.0; wind_point.color.b = 0.0; wind_point.color.a = 1.0; marker_pub.publish(wind_point); */ //Add inverted wind marker --> DownWind wind_point_inv.header.stamp = ros::Time::now(); wind_point_inv.header.frame_id=anemo_msg.header.frame_id; wind_point_inv.points.clear(); wind_point_inv.id = 1; //unique identifier for each arrow if(use_map_ref_system){ wind_point_inv.pose.position.x = x_pos; wind_point_inv.pose.position.y = y_pos; wind_point_inv.pose.position.z = z_pos; }else{ wind_point_inv.pose.position.x = 0.0; wind_point_inv.pose.position.y = 0.0; wind_point_inv.pose.position.z = 0.0; } wind_point_inv.pose.orientation = tf::createQuaternionMsgFromYaw(wind_direction+3.1416); wind_point_inv.scale.x = 2*sqrt(pow(u,2)+pow(v,2)); //arrow lenght wind_point_inv.scale.y = 0.1; //arrow width wind_point_inv.scale.z = 0.1; //arrow height wind_point_inv.color.r = 0.0; wind_point_inv.color.g = 1.0; wind_point_inv.color.b = 0.0; wind_point_inv.color.a = 1.0; marker_pub.publish(wind_point_inv); notified = false; } else { if (!notified) { ROS_WARN("[fake_anemometer] Cannot read Wind Vector from simulated data."); notified = true; } } //Publish RVIZ sensor pose (a sphere) /* sensor.header.stamp = ros::Time::now(); sensor.pose.position.x = x_pos; sensor.pose.position.y = y_pos; sensor.pose.position.z = z_pos; marker_pub.publish(sensor); */ // PUBLISH ANEMOMETER Stick /* connector.header.stamp = ros::Time::now(); connector.scale.z = z_pos; connector.pose.position.x = x_pos; connector.pose.position.y = y_pos; connector.pose.position.z = float(z_pos)/2; marker_pub.publish(connector); */ } ros::spinOnce(); r.sleep(); } } //Load Sensor parameters void loadNodeParameters(ros::NodeHandle private_nh) { //sensor_frame private_nh.param<std::string>("sensor_frame", input_sensor_frame, "/anemometer_link"); //fixed frame private_nh.param<std::string>("fixed_frame", input_fixed_frame, "/map"); //Noise private_nh.param<double>("noise_std", noise_std, 0.1); //What ref system to use for publishing measurements private_nh.param<bool>("use_map_ref_system", use_map_ref_system, false); ROS_INFO("[fake anemometer]: wind noise: %f", noise_std); }
Below are a collection of quotes and artwork that embodies life after Pregnancy and Infant Loss. As you scroll through our Gallery, may the images resonate with your heart and soul. Click on each individual photo to enlarge. If you have a quote or photo that you have found touching, feel free to submit it and we will consider adding it to our Gallery of Hope.
subroutine hybrd1(fcn,n,x,fvec,tol,maxfev,info,wa,lwa) integer n,info,lwa double precision tol double precision x(n),fvec(n),wa(lwa) external fcn c ********** c c subroutine hybrd1 c c the purpose of hybrd1 is to find a zero of a system of c n nonlinear functions in n variables by a modification c of the powell hybrid method. this is done by using the c more general nonlinear equation solver hybrd. the user c must provide a subroutine which calculates the functions. c the jacobian is then calculated by a forward-difference c approximation. c c the subroutine statement is c c subroutine hybrd1(fcn,n,x,fvec,tol,info,wa,lwa) c c where c c fcn is the name of the user-supplied subroutine which c calculates the functions. fcn must be declared c in an external statement in the user calling c program, and should be written as follows. c c subroutine fcn(n,x,fvec,iflag) c integer n,iflag c double precision x(n),fvec(n) c ---------- c calculate the functions at x and c return this vector in fvec. c --------- c return c end c c the value of iflag should not be changed by fcn unless c the user wants to terminate execution of hybrd1. c in this case set iflag to a negative integer. c c n is a positive integer input variable set to the number c of functions and variables. c c x is an array of length n. on input x must contain c an initial estimate of the solution vector. on output x c contains the final estimate of the solution vector. c c fvec is an output array of length n which contains c the functions evaluated at the output x. c c tol is a nonnegative input variable. termination occurs c when the algorithm estimates that the relative error c between x and the solution is at most tol. c c info is an integer output variable. if the user has c terminated execution, info is set to the (negative) c value of iflag. see description of fcn. otherwise, c info is set as follows. c c info = 0 improper input parameters. c c info = 1 algorithm estimates that the relative error c between x and the solution is at most tol. c c info = 2 number of calls to fcn has reached or exceeded c 200*(n+1). c c info = 3 tol is too small. no further improvement in c the approximate solution x is possible. c c info = 4 iteration is not making good progress. c c wa is a work array of length lwa. c c lwa is a positive integer input variable not less than c (n*(3*n+13))/2. c c subprograms called c c user-supplied ...... fcn c c minpack-supplied ... hybrd c c argonne national laboratory. minpack project. march 1980. c burton s. garbow, kenneth e. hillstrom, jorge j. more c c ********** integer index,j,lr,maxfev,ml,mode,mu,nfev,nprint double precision epsfcn,factor,one,xtol,zero data factor,one,zero /1.0d2,1.0d0,0.0d0/ info = 0 c c check the input parameters for errors. c if (n .le. 0 .or. tol .lt. zero .or. lwa .lt. (n*(3*n + 13))/2) * go to 20 c c call hybrd. c C maxfev = 200*(n + 1) xtol = tol ml = n - 1 mu = n - 1 epsfcn = zero mode = 2 do 10 j = 1, n wa(j) = one 10 continue nprint = 0 lr = (n*(n + 1))/2 index = 6*n + lr call hybrd(fcn,n,x,fvec,xtol,maxfev,ml,mu,epsfcn,wa(1),mode, * factor,nprint,info,nfev,wa(index+1),n,wa(6*n+1),lr, * wa(n+1),wa(2*n+1),wa(3*n+1),wa(4*n+1),wa(5*n+1)) if (info .eq. 5) info = 4 20 continue return c c last card of subroutine hybrd1. c end
module _ where postulate D : Set module A where infixr 5 _∷_ postulate _∷_ : Set₁ → D → D module B where infix 5 _∷_ postulate _∷_ : Set₁ → Set₁ → D open A open B foo : D foo = Set ∷ Set
function ex9mbvp %EX9MBVP Example 9 of the BVP tutorial, solved as a multi-point BVP % This boundary value problem is the subject of Chapter 8 of % C.C. Lin and L.A. Segel, Mathematics Applied to Deterministic % Problems in the Natural Sciences, SIAM, Philadelphia, 1988. % The ODEs % % v' = (C - 1)/n % C' = (vC - min(x,1))/eta % % are solved on the interval [0, lambda]. The boundary conditions % are v(0) = 0, C(lambda) = 1, and continuity of v(x) and C(x) at % x = 1. Example EX9BVP shows how this three-point BVP is % reformulated for solution with BVP4C present in MATLAB 6.0. % Starting with MATLAB 7.0, BVP4C solves multi-point BVPs directly. % % The quantity of most interest is the emergent osmolarity Os = % 1/v(lambda). The parameters are related to another parameter % kappa by eta = lambda^2/(n*kappa^2). Lin and Segel develop an % approximate solution for Os valid for "small" n. Here the BVP is % solved for a range of kappa when lambda = 2 and n = 0.005. The % computed Os is compared to the approximation of Lin and Segel. % Copyright 2004, The MathWorks, Inc. % Known parameters, visible in nested functions. n = 5e-2; lambda = 2; % Initial mesh - duplicate the interface point x = 1. xinit = [0, 0.25, 0.5, 0.75, 1, 1, 1.25, 1.5, 1.75, 2]; lambda = 2; sol = bvpinit(xinit,[1 1]); fprintf(' kappa computed Os approximate Os \n') for kappa = 2:5 eta = lambda^2/(n*kappa^2); % After creating function handles, the new value of eta % will be used in nested functions. sol = bvp4c(@ex9mode,@ex9mbc,sol); K2 = lambda*sinh(kappa/lambda)/(kappa*cosh(kappa)); approx = 1/(1 - K2); computed = 1/sol.y(1,end); fprintf(' %2i %10.3f %10.3f \n',kappa,computed,approx); end figure plot(sol.x,sol.y(1,:),sol.x,sol.y(2,:),'--') legend('v(x)','C(x)') title('A three-point BVP.') xlabel(['\lambda = ',num2str(lambda),', \kappa = ',num2str(kappa),'.']) ylabel('v and C') % -------------------------------------------------------------------------- % Nested functions % function dydx = ex9mode(x,y,region) %EX9MODE ODE function for Example 9 of the BVP tutorial. % Here the problem is solved directly, as a three-point BVP. dydx = zeros(2,1); dydx(1) = (y(2) - 1)/n; % The definition of C'(x) depends on the region. switch region case 1 % x in [0 1] dydx(2) = (y(1)*y(2) - x)/eta; case 2 % x in [1 lambda] dydx(2) = (y(1)*y(2) - 1)/eta; end end % ex9mode % -------------------------------------------------------------------------- function res = ex9mbc(YL,YR) %EX9MBC Boundary conditions for Example 9 of the BVP tutorial. % Here the problem is solved directly, as a three-point BVP. res = [ YL(1,1) % v(0) = 0 YR(1,1) - YL(1,2) % continuity of v(x) at x = 1 YR(2,1) - YL(2,2) % continuity of C(x) at x = 1 YR(2,end) - 1 ]; % C(lambda) = 1 end % ex9mbc % -------------------------------------------------------------------------- end % ex9mbvp
>>> Work in Progress (Following are the lecture notes of Prof Andrew Ng - CS229 - Stanford. This is my interpretation of his excellent teaching and I take full responsibility of any misinterpretation/misinformation provided herein.) # Lecture Notes #### Outline: - Naive Bayes - Laplace smoothing - Element models - Comments on applying ML - SVM ## Naive Bayes - is a generative type of algorithm - To build generative model, P(x|y) and P(y) needs to be modeled. Gaussian discriminative model uses Gaussian and Bernoulli respectively to model this. Naive Bayes uses a different model. > - $ x_{j} = \mathbb 1$ {indicator - word j appears in email or not} > - $ P(x|y) = \prod\limits_{j=1}^{n}P(x_{j}|y)$ - NB uses the product of conditional probabilities of individual features given in the class label y - Parameters of NB model are: > - $P(y=1) = \phi_{y} $ - the class prior for y=1 > - $P(x_{j}=1|y=0) = \phi_{j|y=0}$ - chances of the word appearing in non-spam email. > - $P(x_{j}=1|y=1) = \phi_{j|y=1}$ - chances of the word appearing in spam email. ### Maximum likelihood estimate > $\phi_{y} = \frac{\sum\limits_{i=1}^{m}\mathbb 1 \{y^{(i)}=1\}}{m}$ > $\phi_{j|y=0} = \frac{\sum\limits_{i=1}^{m}\mathbb 1 \{x_{j}^{(i)}=1, y^{(i)}=0\}}{\sum\limits_{i=1}^{m}\mathbb 1 \{y^{(i)}=0\}}$ ### Laplace smoothing - ML conference papers - NIPS - Neural Information Processing Systems - __NB breaks__ - because the probability of some event that you have not seen is trained as 0, which is statistically wrong - the classifier gives wrong result, when it gets such event for the first time - instead using __Laplace smoothing__ helps this problem - add 1 each to pass and fail scenario #### Maximum likelihood estimate > $\phi_{x=i} = \frac{\sum\limits_{j=1}^{m}\mathbb 1 \{x^{(i)}=j\} + 1} {m + k}$ - k is the size of dictionary > $\phi_{i|y=0} = \frac{\sum\limits_{i=1}^{m}\mathbb 1 \{x_{j}^{(i)}=1, y^{(i)}=0\} + 1}{\sum\limits_{i=1}^{m}\mathbb 1 \{y^{(i)}=0\} + 2}$ ## Event models for text classification - The functionality can be generalized from binary to multinomial features instead - Multivariate Bernoulli event - Multinomial event - We can discretize the size of house and transform a Bernoulli event to Multinomial event - a rule of thumb is to discretize variables into 10 buckets $\tiny{\text{YouTube-Stanford-CS229-Andrew Ng}}$ ## NB variation - for text classification - if the email contains text "Drugs! Buy drugs now", - the feature vector will make binary vector of all words appearing in the email - it will lose the information that the word "drug" appeared twice - each featture only stores information $x_{j} \in \{0,1\}$ - instead of making a feature vector of 10000 words of dictionary, we can make a feature vector of 4 words(as above) holding word index and $x_{j} \in \{1, 2, ... ,10000\}$ - algorithm containing feature vector of 10000 is called __"Multivariate Bernoulli algorithm"__ - algorithm containing feature vector of 4 is called __"Multinomial algorithm"__ - Andrew McCallum used these 2 names ### NB advantage - quick to implement - computationally efficient - no need to implement gradient descent - easy to do a quick and dirty type of work - SVM or logistic regression does better work in classification problems - NB or GDA does not result in very good classification, but is very quick to implement, it is quick to train, it is non-iterative ## Support Vector Machines (SVM) - find classification in the form of non linear decision boundaries - SVM does not have many parameters to fiddle with - they have very robust packages - and does not have parameters like learning rate, etc to fiddle with <br> - Let the non-linear feature variables be mapped in vector form as below. This non-linear function can be viewed as a linear function over the variables $\phi(x)$ - derive an algorithm that can take input features of the $x_{1}, x_{2}$ and map them to much higher dimensional set of feature and then apply linear classifier, similar to logistic regression but different in details. This allows us to learn very non-linear decision boundaries. $\tiny{\text{YouTube-Stanford-CS229-Andrew Ng}}$ ### Outline for SVM - Optimal margin classifier (separable case) - Kernel - Kernels will allow us to fit in a large set of features - How to take feature vector say $\mathbb R^{2}$ and map it to $\mathbb R^{5}$ or $\mathbb R^{10000}$ or $\mathbb R^{\inf}$, and train the algorithm to this higher feature. Map 2-dimensional feature space to infinite dimensional set of features. What it helps us is relieve us from lot of burden of manually picking up features. ($x^{2}, \space x^{3}, \space \sqrt{x}, \space x_{1}x_{2}^{2/3}, ...$) - Inseparable case ### Optimal margin classifier (separable case) - Separable case means data is separable #### Functional margin of classifier - How confidently and accurately do you classify an example - Using binary classification and logistic regression - In logistic classifier: > $h_{\theta}(x) = g(\theta^{T}x)$ - If you turn this into binary classification, if you have this algorithm predict not a probability but predict 0 or 1, > - Predict "1", if $\theta^{T}x > 0 \implies h_{\theta}(x) = g(\theta^{T}x) \ge 0.5$) > - Predict "0", otherwise - If $y^{(i)} = 1$, hope that $\theta^{T}x^{(i)} \gg 0$ - If $y^{(i)} = 0$, hope that $\theta^{T}x^{(i)} \ll 0$ - this implies that the prediction is very correct and accurate #### Geometric margin - assuming data is linearly separable, - and there are two lines that separates the true and false variables - the line that has a bigger separation or geometric margin meaning a physical separation from the training examples is a better choice - We need to prove the optimal classifier is the algorithm that tries to maximize the geometric margin - what SVM and low dimensional classifier do is pose an optimization problem to try and find the line that classify these examples to find bigger separation margin #### Notation - Labels: $y \in \{-1, +1\} $ to denote class labels - SVM will generate hypothesis output value as {-1, +1} instead of probability as in logistic regression - g(z) = $\begin{equation} \begin{cases} +1 & \text{if z $\ge$ 0}\\ -1 & \text{otherwise} \end{cases} \end{equation}$ - instead of smooth transition, here we have a hard transition Previously in logistic regression: > $h_{\theta}(x) = g(\theta^{T}x)$ - where x is $\mathbb R^{n+1} $ and $x_{0} = 1$ In SVM: > $h_{W,b}(x) = g(W^{T}x + b)$ - where x is $\mathbb R^{n} $ and b is $\mathbb R $ and drop $x_{0}=1$ - The term Other way to think about is: > $ \begin{bmatrix} \theta_{0}\\ \theta_{1}\\ \theta_{2}\\ \theta_{3} \end{bmatrix} $ - where $\theta_{0}$ corresponds to b and $\theta_{1}, \theta_{2}, \theta_{3}$ corresponds to W #### Functional margin of hyperplane (cont) - Functional margin __wrt single training example__ - Functional margin of hyperplane defined by $(w, b)$ wrt a single training example $(x^{(i)}, y^{(i)})$ is > $\hat{\gamma}^{(i)} = y^{(i)} (w^{T}x^{(i)} + b)$ - If $y^{(i)} = +1$, hope that $(w^{T}x^{(i)} + b) \gg 0$ - If $y^{(i)} = -1$, hope that $(w^{T}x^{(i)} + b) \ll 0$ - Combining these two statements: - we hope that $\hat{\gamma}^{(i)} \gg 0$ - If $\hat{\gamma}^{(i)} \gt 0$, - implies $h(x^{(i)}) = y^{(i)}$ - In logistic regression - $\gt 0$ means the prediction is atleast a little bit above 0.5 or little bit below 0.5 - $\gg 0$ means the prediction is either very close to 1 or very close to 0 - Functional margin __wrt entire training set__ (how well are you doing on the worst example in your training set) > $\hat{\gamma} = \min\limits_{i} \hat{\gamma}^{(i)}$ - where i = 1,..,m - all the training examples - here the assumption is training set is linearly separable - we can assume this kind of worst-case notion because we are assuming that the boundary is linearly separable - we can normalize (w, b), which does not change the classification boundary, it simply rescales the parameters > $(w, b) \rightarrow (\frac{w}{\Vert w \Vert}, \frac{b}{\Vert b \Vert})$ - classification remains the same, with any rescale number #### Geometric margin of hyperplane (cont) - Geometric margin __wrt single training example__ - Upper half of hyperplane has positive cases and the lower half negative cases - Let $(x^{(i)}, y^{(i)})$ be a training example which the classifier is classifying correctly, by predicting it as $h_{w,b}(x) = +1$. It predicts the lower half as $h_{w,b}(x) = -1$. - Let the distance from the plane to the training example be the geometric margin - Geometric margin of hyperplane (w,b) wrt $(x^{(i)}, y^{(i)})$ be > $\hat{\gamma} = \frac{(y^{(i)})(w^{T}x^{(i)} + b)}{\Vert w \Vert}$ - This is the Euclidean distance between training example and decision boundary - For positive examples, $y^{(i)}$ is +1 and the equation reduces to > $\hat{\gamma} = \frac{(w^{T}x^{(i)} + b)}{\Vert w \Vert}$ $\tiny{\text{YouTube-Stanford-CS229-Andrew Ng}}$ #### Relationship between functional and geometric margin > $\gamma^{(i)} = \frac{\hat{\gamma}^{(i)}}{\Vert w \Vert}$ > i.e., $\text{Geometric Margin} = \frac{\text{Functional Margin}}{\text{Norm of w}}$ #### Geometric margin of hyperplane (cont) - Geometric margin __wrt entire training example__ > $\gamma = \min\limits_{i} \gamma^{(i)}$ #### Optimal margin classifier (cont) - what the optimal margin classifier does is to choose w,b to maximize $\gamma$ > $\max_{\gamma, w, b} \text{s.t.} \frac{(y^{(i)})(w^{T}x^{(i)} + b)}{\Vert w \Vert} \ge \gamma$ for i=1,...,m - subject to for every single training example must have the geometric margin greater than or equal to gamma - this causes to maximize the worst-case geometric margin - this is not a convex optimization problem and cannot be solved using gradient descent or local optima - but this can be re-written/reformulated into a equivalent problem which is minimizing norm of w subject to the geometric margin > $\min_{w,b} \Vert w \Vert ^{2} \\ \text{s.t. } y^{(i)}(w^{T}x^{(i)} + b) \ge 1$ - This is a convex optimization problem and can be solved using optimization packages - All this study is for linear separable case only - this is a baby SVM - Once we learn kernels and apply kernels with optimal margin classifier, we get solution for SVM
% arara: pdflatex: {shell: yes, files: [latexindent]} \subsubsection{Environments and their arguments}\label{subsubsec:env-and-their-args} There are a few different YAML switches governing the indentation of environments; let's start with the code shown in \cref{lst:myenvtex}. \cmhlistingsfromfile{demonstrations/myenvironment-simple.tex}{\texttt{myenv.tex}}{lst:myenvtex} \yamltitle{noAdditionalIndent}*{fields} If we do not wish \texttt{myenv} to receive any additional indentation, we have a few choices available to us, as demonstrated in \cref{lst:myenv-noAdd1,lst:myenv-noAdd2}. \begin{minipage}{.45\textwidth} \cmhlistingsfromfile[style=yaml-LST]{demonstrations/myenv-noAdd1.yaml}[width=.8\linewidth,before=\centering,yaml-TCB]{\texttt{myenv-noAdd1.yaml}}{lst:myenv-noAdd1} \end{minipage} \hfill \begin{minipage}{.45\textwidth} \cmhlistingsfromfile[style=yaml-LST]{demonstrations/myenv-noAdd2.yaml}[width=.8\linewidth,before=\centering,yaml-TCB]{\texttt{myenv-noAdd2.yaml}}{lst:myenv-noAdd2} \end{minipage} On applying either of the following commands, \begin{commandshell} latexindent.pl myenv.tex -l myenv-noAdd1.yaml latexindent.pl myenv.tex -l myenv-noAdd2.yaml \end{commandshell} we obtain the output given in \cref{lst:myenv-output}; note in particular that the environment \texttt{myenv} has not received any \emph{additional} indentation, but that the \texttt{outer} environment \emph{has} still received indentation. \cmhlistingsfromfile{demonstrations/myenvironment-simple-noAdd-body1.tex}{\texttt{myenv.tex output (using either \cref{lst:myenv-noAdd1} or \cref{lst:myenv-noAdd2})}}{lst:myenv-output} Upon changing the YAML files to those shown in \cref{lst:myenv-noAdd3,lst:myenv-noAdd4}, and running either \begin{commandshell} latexindent.pl myenv.tex -l myenv-noAdd3.yaml latexindent.pl myenv.tex -l myenv-noAdd4.yaml \end{commandshell} we obtain the output given in \cref{lst:myenv-output-4}. \begin{minipage}{.45\textwidth} \cmhlistingsfromfile[style=yaml-LST]{demonstrations/myenv-noAdd3.yaml}[width=.8\linewidth,before=\centering,yaml-TCB]{\texttt{myenv-noAdd3.yaml}}{lst:myenv-noAdd3} \end{minipage} \hfill \begin{minipage}{.45\textwidth} \cmhlistingsfromfile[style=yaml-LST]{demonstrations/myenv-noAdd4.yaml}[width=.8\linewidth,before=\centering,yaml-TCB]{\texttt{myenv-noAdd4.yaml}}{lst:myenv-noAdd4} \end{minipage} \cmhlistingsfromfile{demonstrations/myenvironment-simple-noAdd-body4.tex}{\texttt{myenv.tex output} (using either \cref{lst:myenv-noAdd3} or \cref{lst:myenv-noAdd4})}{lst:myenv-output-4} Let's now allow \texttt{myenv} to have some optional and mandatory arguments, as in \cref{lst:myenv-args}. \cmhlistingsfromfile{demonstrations/myenvironment-args.tex}{\texttt{myenv-args.tex}}{lst:myenv-args} Upon running \begin{commandshell} latexindent.pl -l=myenv-noAdd1.yaml myenv-args.tex \end{commandshell} we obtain the output shown in \cref{lst:myenv-args-noAdd1}; note that the optional argument, mandatory argument and body \emph{all} have received no additional indent. This is because, when \texttt{noAdditionalIndent} is specified in `scalar' form (as in \cref{lst:myenv-noAdd1}), then \emph{all} parts of the environment (body, optional and mandatory arguments) are assumed to want no additional indent. \cmhlistingsfromfile{demonstrations/myenvironment-args-noAdd-body1.tex}{\texttt{myenv-args.tex} using \cref{lst:myenv-noAdd1}}{lst:myenv-args-noAdd1} We may customise \texttt{noAdditionalIndent} for optional and mandatory arguments of the \texttt{myenv} environment, as shown in, for example, \cref{lst:myenv-noAdd5,lst:myenv-noAdd6}. \begin{minipage}{.49\textwidth} \cmhlistingsfromfile[style=yaml-LST]{demonstrations/myenv-noAdd5.yaml}[width=.8\linewidth,before=\centering,yaml-TCB]{\texttt{myenv-noAdd5.yaml}}{lst:myenv-noAdd5} \end{minipage} \hfill \begin{minipage}{.49\textwidth} \cmhlistingsfromfile[style=yaml-LST]{demonstrations/myenv-noAdd6.yaml}[width=.8\linewidth,before=\centering,yaml-TCB]{\texttt{myenv-noAdd6.yaml}}{lst:myenv-noAdd6} \end{minipage} Upon running \begin{commandshell} latexindent.pl myenv.tex -l myenv-noAdd5.yaml latexindent.pl myenv.tex -l myenv-noAdd6.yaml \end{commandshell} we obtain the respective outputs given in \cref{lst:myenv-args-noAdd5,lst:myenv-args-noAdd6}. Note that in \cref{lst:myenv-args-noAdd5} the text for the \emph{optional} argument has not received any additional indentation, and that in \cref{lst:myenv-args-noAdd6} the \emph{mandatory} argument has not received any additional indentation; in both cases, the \emph{body} has not received any additional indentation. \begin{minipage}{.45\textwidth} \cmhlistingsfromfile{demonstrations/myenvironment-args-noAdd5.tex}{\texttt{myenv-args.tex} using \cref{lst:myenv-noAdd5}}{lst:myenv-args-noAdd5} \end{minipage} \hfill \begin{minipage}{.45\textwidth} \cmhlistingsfromfile{demonstrations/myenvironment-args-noAdd6.tex}{\texttt{myenv-args.tex} using \cref{lst:myenv-noAdd6}}{lst:myenv-args-noAdd6} \end{minipage} \yamltitle{indentRules}*{fields} We may also specify indentation rules for environment code blocks using the \texttt{indentRules} field; see, for example, \cref{lst:myenv-rules1,lst:myenv-rules2}. \begin{minipage}{.45\textwidth} \cmhlistingsfromfile[style=yaml-LST]{demonstrations/myenv-rules1.yaml}[width=.8\linewidth,before=\centering,yaml-TCB]{\texttt{myenv-rules1.yaml}}{lst:myenv-rules1} \end{minipage} \hfill \begin{minipage}{.45\textwidth} \cmhlistingsfromfile[style=yaml-LST]{demonstrations/myenv-rules2.yaml}[width=.8\linewidth,before=\centering,yaml-TCB]{\texttt{myenv-rules2.yaml}}{lst:myenv-rules2} \end{minipage} On applying either of the following commands, \begin{commandshell} latexindent.pl myenv.tex -l myenv-rules1.yaml latexindent.pl myenv.tex -l myenv-rules2.yaml \end{commandshell} we obtain the output given in \cref{lst:myenv-rules-output}; note in particular that the environment \texttt{myenv} has received one tab (from the \texttt{outer} environment) plus three spaces from \cref{lst:myenv-rules1} or \ref{lst:myenv-rules2}. \cmhlistingsfromfile{demonstrations/myenv-rules1.tex}{\texttt{myenv.tex output (using either \cref{lst:myenv-rules1} or \cref{lst:myenv-rules2})}}{lst:myenv-rules-output} If you specify a field in \texttt{indentRules} using anything other than horizontal space, it will be ignored. Returning to the example in \cref{lst:myenv-args} that contains optional and mandatory arguments. Upon using \cref{lst:myenv-rules1} as in \begin{commandshell} latexindent.pl myenv-args.tex -l=myenv-rules1.yaml \end{commandshell} we obtain the output in \cref{lst:myenv-args-rules1}; note that the body, optional argument and mandatory argument have \emph{all} received the same customised indentation. \cmhlistingsfromfile{demonstrations/myenvironment-args-rules1.tex}{\texttt{myenv-args.tex} using \cref{lst:myenv-rules1}}{lst:myenv-args-rules1} You can specify different indentation rules for the different features using, for example, \cref{lst:myenv-rules3,lst:myenv-rules4} \begin{minipage}{.49\textwidth} \cmhlistingsfromfile[style=yaml-LST]{demonstrations/myenv-rules3.yaml}[width=.9\linewidth,before=\centering,yaml-TCB]{\texttt{myenv-rules3.yaml}}{lst:myenv-rules3} \end{minipage} \hfill \begin{minipage}{.49\textwidth} \cmhlistingsfromfile[style=yaml-LST]{demonstrations/myenv-rules4.yaml}[width=.9\linewidth,before=\centering,yaml-TCB]{\texttt{myenv-rules4.yaml}}{lst:myenv-rules4} \end{minipage} After running \begin{commandshell} latexindent.pl myenv-args.tex -l myenv-rules3.yaml latexindent.pl myenv-args.tex -l myenv-rules4.yaml \end{commandshell} then we obtain the respective outputs given in \cref{lst:myenv-args-rules3,lst:myenv-args-rules4}. \begin{minipage}{.45\textwidth} \cmhlistingsfromfile{demonstrations/myenvironment-args-rules3.tex}{\texttt{myenv-args.tex} using \cref{lst:myenv-rules3}}{lst:myenv-args-rules3} \end{minipage} \hfill \begin{minipage}{.45\textwidth} \cmhlistingsfromfile{demonstrations/myenvironment-args-rules4.tex}{\texttt{myenv-args.tex} using \cref{lst:myenv-rules4}}{lst:myenv-args-rules4} \end{minipage} Note that in \cref{lst:myenv-args-rules3}, the optional argument has only received a single space of indentation, while the mandatory argument has received the default (tab) indentation; the environment body has received three spaces of indentation. In \cref{lst:myenv-args-rules4}, the optional argument has received the default (tab) indentation, the mandatory argument has received two tabs of indentation, and the body has received three spaces of indentation. \yamltitle{noAdditionalIndentGlobal}*{fields} \begin{wrapfigure}[6]{r}[0pt]{7cm} \cmhlistingsfromfile[style=noAdditionalIndentGlobalEnv]{../defaultSettings.yaml}[width=.8\linewidth,before=\centering,yaml-TCB]{\texttt{noAdditionalIndentGlobal}}{lst:noAdditionalIndentGlobal:environments} \end{wrapfigure} Assuming that your environment name is not found within neither \texttt{noAdditionalIndent} nor \texttt{indentRules}, the next place that \texttt{latexindent.pl} will look is \texttt{noAdditionalIndentGlobal}, and in particular \emph{for the environments} key (see \cref{lst:noAdditionalIndentGlobal:environments}). Let's say that you change the value of \texttt{environments} to \texttt{1} in \cref{lst:noAdditionalIndentGlobal:environments}, and that you run \begin{widepage} \begin{commandshell} latexindent.pl myenv-args.tex -l env-noAdditionalGlobal.yaml latexindent.pl myenv-args.tex -l myenv-rules1.yaml,env-noAdditionalGlobal.yaml \end{commandshell} \end{widepage} The respective output from these two commands are in \cref{lst:myenv-args-no-add-global1,lst:myenv-args-no-add-global2}; in \cref{lst:myenv-args-no-add-global1} notice that \emph{both} environments receive no additional indentation but that the arguments of \texttt{myenv} still \emph{do} receive indentation. In \cref{lst:myenv-args-no-add-global2} notice that the \emph{outer} environment does not receive additional indentation, but because of the settings from \texttt{myenv-rules1.yaml} (in \vref{lst:myenv-rules1}), the \texttt{myenv} environment still \emph{does} receive indentation. \begin{minipage}{.45\textwidth} \cmhlistingsfromfile{demonstrations/myenvironment-args-rules1-noAddGlobal1.tex}{\texttt{myenv-args.tex} using \cref{lst:noAdditionalIndentGlobal:environments}}{lst:myenv-args-no-add-global1} \end{minipage} \hfill \begin{minipage}{.45\textwidth} \cmhlistingsfromfile{demonstrations/myenvironment-args-rules1-noAddGlobal2.tex}{\texttt{myenv-args.tex} using \cref{lst:noAdditionalIndentGlobal:environments,lst:myenv-rules1}}{lst:myenv-args-no-add-global2} \end{minipage} In fact, \texttt{noAdditionalIndentGlobal} also contains keys that control the indentation of optional and mandatory arguments; on referencing \cref{lst:opt-args-no-add-glob,lst:mand-args-no-add-glob} \begin{minipage}{.49\textwidth} \cmhlistingsfromfile[style=yaml-LST]{demonstrations/opt-args-no-add-glob.yaml}[width=.8\linewidth,before=\centering,yaml-TCB]{\texttt{opt-args-no-add-glob.yaml}}{lst:opt-args-no-add-glob} \end{minipage} \hfill \begin{minipage}{.49\textwidth} \cmhlistingsfromfile[style=yaml-LST]{demonstrations/mand-args-no-add-glob.yaml}[width=.8\linewidth,before=\centering,yaml-TCB]{\texttt{mand-args-no-add-glob.yaml}}{lst:mand-args-no-add-glob} \end{minipage} we may run the commands \begin{commandshell} latexindent.pl myenv-args.tex -local opt-args-no-add-glob.yaml latexindent.pl myenv-args.tex -local mand-args-no-add-glob.yaml \end{commandshell} which produces the respective outputs given in \cref{lst:myenv-args-no-add-opt,lst:myenv-args-no-add-mand}. Notice that in \cref{lst:myenv-args-no-add-opt} the \emph{optional} argument has not received any additional indentation, and in \cref{lst:myenv-args-no-add-mand} the \emph{mandatory} argument has not received any additional indentation. \begin{minipage}{.45\textwidth} \cmhlistingsfromfile{demonstrations/myenvironment-args-rules1-noAddGlobal3.tex}{\texttt{myenv-args.tex} using \cref{lst:opt-args-no-add-glob}}{lst:myenv-args-no-add-opt} \end{minipage} \hfill \begin{minipage}{.45\textwidth} \cmhlistingsfromfile{demonstrations/myenvironment-args-rules1-noAddGlobal4.tex}{\texttt{myenv-args.tex} using \cref{lst:mand-args-no-add-glob}}{lst:myenv-args-no-add-mand} \end{minipage} \yamltitle{indentRulesGlobal}*{fields} \begin{wrapfigure}[4]{r}[0pt]{7cm} \cmhlistingsfromfile[style=indentRulesGlobalEnv]{../defaultSettings.yaml}[width=.8\linewidth,before=\centering,yaml-TCB]{\texttt{indentRulesGlobal}}{lst:indentRulesGlobal:environments} \end{wrapfigure} The final check that \texttt{latexindent.pl} will make is to look for \texttt{indentRulesGlobal} as detailed in \cref{lst:indentRulesGlobal:environments}; if you change the \texttt{environments} field to anything involving horizontal space, say \lstinline!" "!, and then run the following commands \begin{commandshell} latexindent.pl myenv-args.tex -l env-indentRules.yaml latexindent.pl myenv-args.tex -l myenv-rules1.yaml,env-indentRules.yaml \end{commandshell} then the respective output is shown in \cref{lst:myenv-args-indent-rules-global1,lst:myenv-args-indent-rules-global2}. Note that in \cref{lst:myenv-args-indent-rules-global1}, both the environment blocks have received a single-space indentation, whereas in \cref{lst:myenv-args-indent-rules-global2} the \texttt{outer} environment has received single-space indentation (specified by \texttt{indentRulesGlobal}), but \texttt{myenv} has received \lstinline!" "!, as specified by the particular \texttt{indentRules} for \texttt{myenv} \vref{lst:myenv-rules1}. \begin{minipage}{.45\textwidth} \cmhlistingsfromfile{demonstrations/myenvironment-args-global-rules1.tex}{\texttt{myenv-args.tex} using \cref{lst:indentRulesGlobal:environments}}{lst:myenv-args-indent-rules-global1} \end{minipage} \hfill \begin{minipage}{.45\textwidth} \cmhlistingsfromfile{demonstrations/myenvironment-args-global-rules2.tex}{\texttt{myenv-args.tex} using \cref{lst:myenv-rules1,lst:indentRulesGlobal:environments}}{lst:myenv-args-indent-rules-global2} \end{minipage} You can specify \texttt{indentRulesGlobal} for both optional and mandatory arguments, as detailed in \cref{lst:opt-args-indent-rules-glob,lst:mand-args-indent-rules-glob} \begin{minipage}{.49\textwidth} \cmhlistingsfromfile[style=yaml-LST]{demonstrations/opt-args-indent-rules-glob.yaml}[width=.9\linewidth,before=\centering,yaml-TCB]{\texttt{opt-args-indent-rules-glob.yaml}}{lst:opt-args-indent-rules-glob} \end{minipage} \hfill \begin{minipage}{.49\textwidth} \cmhlistingsfromfile[style=yaml-LST]{demonstrations/mand-args-indent-rules-glob.yaml}[width=.9\linewidth,before=\centering,yaml-TCB]{\texttt{mand-args-indent-rules-glob.yaml}}{lst:mand-args-indent-rules-glob} \end{minipage} Upon running the following commands \begin{commandshell} latexindent.pl myenv-args.tex -local opt-args-indent-rules-glob.yaml latexindent.pl myenv-args.tex -local mand-args-indent-rules-glob.yaml \end{commandshell} we obtain the respective outputs in \cref{lst:myenv-args-indent-rules-global3,lst:myenv-args-indent-rules-global4}. Note that the \emph{optional} argument in \cref{lst:myenv-args-indent-rules-global3} has received two tabs worth of indentation, while the \emph{mandatory} argument has done so in \cref{lst:myenv-args-indent-rules-global4}. \begin{minipage}{.45\textwidth} \cmhlistingsfromfile{demonstrations/myenvironment-args-global-rules3.tex}{\texttt{myenv-args.tex} using \cref{lst:opt-args-indent-rules-glob}}{lst:myenv-args-indent-rules-global3} \end{minipage} \hfill \begin{minipage}{.45\textwidth} \cmhlistingsfromfile{demonstrations/myenvironment-args-global-rules4.tex}{\texttt{myenv-args.tex} using \cref{lst:mand-args-indent-rules-glob}}{lst:myenv-args-indent-rules-global4} \end{minipage}
setwd("C:\\Users\\shalini\\Desktop\\Rprograms") getwd() dir() data(Titanic) str(Titanic) View(Titanic) # read AR data converted from titanic data from website http://www.cs.toronto.edu/~delve/ #data/titanic/desc.html titan <- read.table("./dataset.data", header=F) View(titan) names(titan) <- c("Class","Age", "Sex", "Survived") View(titan) install.packages("arules") library(arules) search() # find association rules with default settings #supp=0.1, ; 2) conf=0.8, 3) maxlen=10, #rules.all <- apriori(titanic.raw) rules.all <- apriori(titan) quality(rules.all) <- round(quality(rules.all), digits=3) rules.all inspect(rules.all) #---------------------------------start here-----------------------------------# #rules with rhs containing "Survived" only #restricted rules #rules <- apriori(titanic.raw, control = list(verbose=F), parameter = list(minlen=2, supp=0.005, conf=0.8),appearance = list(rhs=c("Survived=No", "Survived=Yes"),default="lhs")) rules <- apriori(titan, control = list(verbose=F), parameter = list(minlen=2, supp=0.005, conf=0.8),appearance = list(rhs=c("Survived=no", "Survived=yes"),default="lhs")) quality(rules) <- round(quality(rules), digits=2) rules.sorted <- sort(rules, by="lift") inspect(rules.sorted) #restricting LHS rules <- apriori(titan, control = list(verbose=F),parameter = list(minlen=3, supp=0.002, conf=0.7),appearance = list(rhs=c("Survived=yes"),lhs=c("Class=1st", "Class=2nd", "Class=3rd","Age=child", "Age=adult"),default="none")) quality(rules) <- round(quality(rules), digits=4) rules.sorted <- sort(rules, by="lift") inspect(rules.sorted) #plotting AR install.packages("arulesViz") library(arulesViz) search() plot(rules.all) plot(rules.all, method="grouped") #another dataset market basket data(Groceries) inspect(Groceries[1:5]) #to see first 5 transactions # Create an item frequency plot for the top 10 items itemFrequencyPlot(Groceries,topN=10,type="absolute") # Get the rules rules <- apriori(Groceries, parameter = list(supp = 0.001, conf = 0.8)) # Show the top 5 rules, but only 2 digits options(digits=2) inspect(rules[1:5]) summary(rules) #summary statistics
BindGlobal("MitM_rnams", ["name", "attributes", "content"]); # OM elements - known as "omel" in the specification BindGlobal("MitM_OMel", [ "OMS", "OMV", "OMI", "OMB", "OMSTR", "OMF", "OMA", "OMBIND", "OME", "OMATTR", "OMR"]); # # ValidXSD: a collection of functions to check some XML string types # BindGlobal("MitM_ValidXSD", rec()); MitM_ValidXSD.Empty := function(str) if not IsEmpty(str) then return "must be empty"; fi; return true; end; MitM_ValidXSD.Text := function(str) if '<' in str then return "XML strings cannot contain '<'"; elif Number(str, c -> c = '&') > Number(str, c -> c = ';') then return "there is a '&' character without a closing ';'"; fi; # Perhaps we could check some other simple XML things? return true; end; MitM_ValidXSD.NCName := function(str) local result, char; result := MitM_ValidXSD.Text(str); if result <> true then return result; elif IsEmpty(str) then return "must not be the empty string"; elif IsDigitChar(str[1]) or str[1] = '-' or str[1] = '.' then return "must start with a letter or underscore"; fi; for char in str do if not (IsAlphaChar(char) or IsDigitChar(char) or char = '_' or char = '-' or char = '.') then return Concatenation("must not contain the character \"", String(char), "\""); fi; od; return true; end; # Checking ID uniqueness is difficult, but we may want to do it in the future MitM_ValidXSD.ID := MitM_ValidXSD.Text; # Validating URIs is difficult, but we may want to do it in the future MitM_ValidXSD.AnyURI := MitM_ValidXSD.Text; MitM_ValidXSD.Base64Binary := function(str) local len, nreq, i; str := ShallowCopy(str); RemoveCharacters(str, " \n\t\r"); # ignore whitespace len := Length(str); if len mod 4 <> 0 then return "must have length divisible by 4"; fi; nreq := 0; if str[len] = '=' then nreq := 1; if str[len - 1] = '=' then nreq := 2; if not str[len - 2] in "AQgw" then return "one of [AQgw] must come before '=='"; fi; elif not str[len - 1] in "AEIMQUYcgkosw048" then return "one of [AEIMQUYcgkosw048=] must come before '='"; fi; fi; for i in [1 .. len - nreq] do if str[i] = '=' then return "only 1 or 2 '=' characters allowed, and only at the end"; elif not (IsAlphaChar(str[i]) or IsDigitChar(str[i]) or str[i] = '+' or str[i] = '/') then return Concatenation("cannot contain character '", str{[i]}, "'"); fi; od; return true; end; # # ValidAttr: each object type's valid attributes, # along with functions to check their values # BindGlobal("MitM_ValidAttr", rec( OMOBJ := rec(cdbase := MitM_ValidXSD.AnyURI, version := MitM_ValidXSD.Text), OMS := rec(name := MitM_ValidXSD.NCName, cd := MitM_ValidXSD.NCName, cdbase := MitM_ValidXSD.AnyURI), OMV := rec(name := MitM_ValidXSD.NCName), OMI := rec(), OMB := rec(), OMSTR := rec(), OMF := rec(dec := function(str) if str = "INF" or str = "-INF" or str = "NaN" then return true; elif Float(str) = fail then return Concatenation(str, " is not a valid float"); fi; return true; end, hex := function(str) local valid_chars, char, err; if Length(str) <> 16 then return "must be 16 characters long"; fi; valid_chars := "0123456789ABCDEF"; for char in str do if not char in valid_chars then err := "contains non-hex character '"; Add(err, char); Add(err, '''); if char in "abcdef" then Append(err, " (not capital)"); fi; return err; fi; od; return true; end), OMA := rec(cdbase := MitM_ValidXSD.AnyURI), OMBIND := rec(cdbase := MitM_ValidXSD.AnyURI), OME := rec(), OMATTR := rec(cdbase := MitM_ValidXSD.AnyURI), OMR := rec(), OMBVAR := rec(), OMATP := rec(cdbase := MitM_ValidXSD.AnyURI), common := rec(id := MitM_ValidXSD.ID) )); # # RequiredAttr: a list of required attributes for each object type # BindGlobal("MitM_RequiredAttr", rec( OMOBJ := [], OMS := ["cd", "name"], OMV := ["name"], OMI := [], OMB := [], OMSTR := [], OMF := [], OMA := [], OMBIND := [], OME := [], OMATTR := [], OMR := [], OMBVAR := [], OMATP := [] )); # # ValidCont: a function to check content for each object type # BindGlobal("MitM_ValidCont", rec( OMOBJ := function(content) if Length(content) <> 1 then return "must be precisely one object"; elif not (MitM_OMRec(content[1]) and MitM_Tag(content[1]) in MitM_OMel) then return "must be an OM element"; fi; return MitM_IsValidOMRec(content[1]); end, OMS := MitM_ValidXSD.Empty, OMV := MitM_ValidXSD.Empty, OMI := function(content) local str, pos, valid_chars; if not (Length(content) = 1 and IsString(content[1])) then return "must be only a string"; fi; str := ShallowCopy(content[1]); RemoveCharacters(str, " \n\t\r"); # ignore whitespace pos := 1; if str[pos] = '-' then Remove(str, 1); fi; if str[pos] = 'x' then Remove(str, 1); valid_chars := "0123456789ABCDEF"; else valid_chars := "0123456789"; fi; if ForAny(str, char -> not char in valid_chars) or Length(str) = 0 then return Concatenation(content[1], " is not an integer"); fi; return true; end, OMB := function(content) if IsEmpty(content) then return true; elif not (Length(content) = 1 and IsString(content[1])) then return "must be only a string"; fi; return MitM_ValidXSD.Base64Binary(content[1]); end, OMSTR := function(content) if IsEmpty(content) then return true; elif not (Length(content) = 1 and IsString(content[1])) then return "must be only a string"; fi; return MitM_ValidXSD.Text(content[1]); end, OMF := MitM_ValidXSD.Empty, OMA := function(content) local item, result; if Length(content) = 0 then return "must not be empty"; fi; for item in content do if not MitM_OMRec(item) then return "must only contain OM elements"; elif not MitM_Tag(item) in MitM_OMel then return Concatenation("cannot contain ", MitM_Tag(item), " objects"); fi; result := MitM_IsValidOMRec(item); if result <> true then return result; fi; od; return true; end, OMBIND := function(content) local item, result; if not (Length(content) = 3 and ForAll(content, MitM_OMRec) and MitM_Tag(content[1]) in MitM_OMel and MitM_Tag(content[2]) = "OMBVAR" and MitM_Tag(content[3]) in MitM_OMel) then return "must be [OM elm, OMBVAR, OM elm] (in that order)"; fi; for item in content do result := MitM_IsValidOMRec(item); if result <> true then return result; fi; od; return true; end, OME := function(content) return "not implemented"; end, OMATTR := function(content) local i, result; if Length(content) <> 2 then return "must contain precisely two objects"; elif not (MitM_OMRec(content[1]) and MitM_Tag(content[1]) = "OMATP") then return "first object must be OMATP"; elif not (MitM_OMRec(content[2]) and MitM_Tag(content[2]) in MitM_OMel) then return "second object must be an OM element"; fi; for i in [1 .. Length(content)] do result := MitM_IsValidOMRec(content[i]); if result <> true then return result; fi; od; return true; end, OMR := function(content) return "not implemented"; end, OMBVAR := function(content) local item, result; if IsEmpty(content) then return "must not be empty"; fi; for item in content do if not (MitM_OMRec(item) and MitM_Tag(item) = "OMV") then return "must only contain OMV objects"; # ... or attvar objects in the full spec fi; result := MitM_IsValidOMRec(item); if result <> true then return result; fi; od; return true; end, OMATP := function(content) local i, result; if Length(content) = 0 then return "must not be empty"; elif Length(content) mod 2 <> 0 then return "must contain an even number of objects"; fi; for i in [1, 3 .. Length(content) - 1] do if not (MitM_OMRec(content[i]) and MitM_Tag(content[i]) = "OMS") then return StringFormatted("item {} must be an OMS object", i); elif not (MitM_OMRec(content[i + 1]) and MitM_Tag(content[i + 1]) in MitM_OMel) then # TODO: allow OMFOREIGN return StringFormatted("item {} must be an OM element", i + 1); fi; result := MitM_IsValidOMRec(content[i]); if result <> true then return result; fi; result := MitM_IsValidOMRec(content[i + 1]); if result <> true then return result; fi; od; return true; end )); # # IsValidOMRec: the function we call on an object to check its validity # InstallGlobalFunction(MitM_IsValidOMRec, function(tree) local rnam, attr, result; # Check that this is a proper object if not MitM_OMRec(tree) then return "<tree> must be an OM record"; elif not MitM_Tag(tree) in RecNames(MitM_ValidAttr) then return Concatenation(MitM_Tag(tree), " is not a valid OM object name"); fi; for rnam in NamesOfComponents(tree) do if not rnam in MitM_rnams then return Concatenation("invalid XML: ", rnam, " should not exist"); fi; od; # Validate the attributes for attr in RecNames(MitM_Attributes(tree)) do if attr in RecNames(MitM_ValidAttr.(MitM_Tag(tree))) then result := MitM_ValidAttr.(MitM_Tag(tree)).(attr)(MitM_Attributes(tree).(attr)); elif attr in RecNames(MitM_ValidAttr.common) then result := MitM_ValidAttr.common.(attr)(MitM_Attributes(tree).(attr)); else return Concatenation(attr, " is not a valid attribute of ", MitM_Tag(tree), " objects"); fi; if result <> true then return StringFormatted("{} attribute of {} object: {}", attr, MitM_Tag(tree), result); fi; od; # Check required attributes for attr in MitM_RequiredAttr.(MitM_Tag(tree)) do if not attr in RecNames(MitM_Attributes(tree)) then return Concatenation(MitM_Tag(tree), " objects must have the ", attr, " attribute"); fi; od; # Check antirequisite attributes - just one of these if MitM_Tag(tree) = "OMF" then if MitM_Attributes(tree) = fail or not (IsBound(MitM_Attributes(tree).dec) or IsBound(MitM_Attributes(tree).hex)) then return "OMF objects must have either the dec or the hex attribute"; elif IsBound(MitM_Attributes(tree).dec) and IsBound(MitM_Attributes(tree).hex) then return "OMF objects cannot have both the dec and the hex attribute"; fi; fi; # Validate the content if MitM_Content(tree) <> fail then result := MitM_ValidCont.(MitM_Tag(tree))(MitM_Content(tree)); else result := MitM_ValidCont.(MitM_Tag(tree))([]); fi; if result <> true then return Concatenation(MitM_Tag(tree), " contents: ", result); fi; return true; end);
Formal statement is: lemma LIM_zero_iff: "((\<lambda>x. f x - l) \<longlongrightarrow> 0) F = (f \<longlongrightarrow> l) F" for f :: "'a \<Rightarrow> 'b::real_normed_vector" Informal statement is: The limit of a function $f$ at $l$ is $0$ if and only if the limit of $f - l$ at $0$ is $0$.
Formal statement is: lemma fixes m :: real and \<delta> :: "'a::euclidean_space" defines "T r d x \<equiv> r *\<^sub>R x + d" shows emeasure_lebesgue_affine: "emeasure lebesgue (T m \<delta> ` S) = \<bar>m\<bar> ^ DIM('a) * emeasure lebesgue S" (is ?e) and measure_lebesgue_affine: "measure lebesgue (T m \<delta> ` S) = \<bar>m\<bar> ^ DIM('a) * measure lebesgue S" (is ?m) Informal statement is: The Lebesgue measure of an affine transformation of a set is equal to the absolute value of the determinant of the transformation times the Lebesgue measure of the set.
function [xs, info] = pwls_sps_os(x, yi, wi, Ab, R, niter, pixmax, ... denom, aai, relax0, chat) %function [xs, info] = pwls_sps_os(x, yi, wi, Ab, R, niter, pixmax, ... %| denom, aai, relax0, chat) %| %| penalized weighted least squares estimation/reconstruction %| using separable paraboloidal surrogates algorithm with %| (optionally relaxed) ordered subsets. (relaxation ensures convergence.) %| %| cost(x) = (y-Gx)' W (y-Gx) / 2 + R(x) %| %| in %| x [np 1] initial estimate %| yi [nb na] measurements (noisy sinogram) %| wi [nb na] weighting sinogram (or [] for uniform) %| Ab [nd np] Gblock object, aij >= 0 required! %| or sparse matrix (implies nsubset=1) %| R penalty object (see Reg1.m) %| niter # of iterations (including 0) %| %| optional %| pixmax [1] or [2] max pixel value, or [min max] (default [0 inf]) %| denom [np 1] precomputed denominator %| aai [nb na] precomputed row sums of |Ab| %| relax0 [1] or [2] relax0 or (relax0, relax_rate) %| chat %| %| out %| xs [np niter] iterates %| info [niter 1] time %| %| Copyright 2002-2-12, Jeff Fessler, University of Michigan if nargin < 4, ir_usage, end cpu etic info = zeros(niter,1); Ab = block_op(Ab, 'ensure'); % make it a block object (if not already) nblock = block_op(Ab, 'n'); starts = subset_start(nblock); if ~isvar('niter') || isempty(niter), niter = 1; end if ~isvar('pixmax') || isempty(pixmax), pixmax = inf; end if ~isvar('chat') || isempty(chat), chat = false; end if isempty(wi) wi = ones(size(yi)); end if ~isvar('aai') || isempty(aai) aai = reshape(sum(Ab'), size(yi)); % a_i = sum_j |a_ij| % requires real a_ij and a_ij >= 0 end if ~isvar('relax0') || isempty(relax0) relax0 = 1; end if length(relax0) == 1 relax_rate = 0; elseif length(relax0) == 2 relax_rate = relax0(2); relax0 = relax0(1); else error relax end if length(pixmax) == 2 pixmin = pixmax(1); pixmax = pixmax(2); elseif length(pixmax) == 1 pixmin = 0; else error pixmax end % % likelihood denom, if not provided % if ~isvar('denom') || isempty(denom) denom = Ab' * col(aai .* wi); % requires real a_ij and a_ij >= 0 end, clear aai if ~isvar('R') || isempty(R) pgrad = 0; % unregularized default Rdenom = 0; end [nb na] = size(yi); % % loop over iterations % xs = zeros(numel(x), niter, class(x)); x = max(x,pixmin); x = min(x,pixmax); xs(:,1) = x; for iter = 2:niter ticker(mfilename, iter, niter) relax = relax0 / (1 + relax_rate * (iter-2)); % % loop over subsets % for iset=1:nblock iblock = starts(iset); ia = iblock:nblock:na; li = Ab{iblock} * x; li = reshape(li, nb, length(ia)); resid = wi(:,ia) .* (yi(:,ia) - li); grad = Ab{iblock}' * resid(:); % G' * W * (y - G*x) if ~isempty(R) pgrad = R.cgrad(R, x); Rdenom = R.denom(R, x); end num = nblock * grad - pgrad; den = denom + Rdenom; x = x + relax * num ./ den; % relaxed update x = max(x,pixmin); % lower bound x = min(x,pixmax); % upper bound end if chat, printm('range(x) = %g %g', min(x), max(x)), end xs(:,iter) = x; info(iter,1) = cpu('etoc'); end
Require Export UnitaryListRepresentation. Require Export SQIR.DensitySem. Local Open Scope com_scope. Local Close Scope R_scope. Local Open Scope signature_scope. (* This file extends UnitaryListRepr with a 'list of lists' representation for non-unitary programs. *) (** List-of-lists representation for non-unitary programs. **) Inductive instr (U: nat -> Set) (dim : nat): Set := | UC : gate_list U dim -> instr U dim | Meas : nat -> list (instr U dim) -> list (instr U dim) -> instr U dim. Definition com_list U dim := list (instr U dim). Arguments UC {U dim}. Arguments Meas {U dim}. (** Useful operations on the com list representation. **) Fixpoint does_not_reference_instr {U dim} q (i : instr U dim) := match i with | UC u => does_not_reference u q | Meas n l1 l2 => negb (q =? n) && forallb (does_not_reference_instr q) l1 && forallb (does_not_reference_instr q) l2 end. Definition does_not_reference_c {U dim} (l : com_list U dim) (q : nat) := forallb (does_not_reference_instr q) l. (* Get the next measurement operation on qubit q. *) Fixpoint next_measurement {U dim} (l : com_list U dim) q := match l with | [] => None | UC u :: t => if does_not_reference u q then match next_measurement t q with | None => None | Some (l1, l1', l2', l2) => Some (UC u :: l1, l1', l2', l2) end else None | Meas n l1 l2 :: t => if q =? n then Some ([], l1, l2, t) else if does_not_reference_c l1 q && does_not_reference_c l2 q then match next_measurement t q with | None => None | Some (l1', l1'', l2'', l2') => Some (Meas n l1 l2 :: l1', l1'', l2'', l2') end else None end. (* Count the number of UC/Meas operations in a non-unitary program. This is useful when we're too lazy to write functions in a nested recursive style & use the special induction principle 'com_list_ind'. Instead, we can use the result of this function as initial fuel to a function and recurse on the size of the fuel. (This only works if the function in question performs N operations where N can be over-approximated by an expression involving count_ops.) *) Fixpoint count_ops_instr {U dim} (i : instr U dim) := match i with | UC u => 1%nat | Meas n l1 l2 => let fix f l := match l with | [] => O | h :: t => (count_ops_instr h + f t)%nat end in (1 + f l1 + f l2)%nat end. Fixpoint count_ops {U dim} (l : com_list U dim) := match l with | [] => O | h :: t => (count_ops_instr h + count_ops t)%nat end. (* 'canonicalize' a non-unitary program by combining adjacent UC terms and removing empty UC terms. This will allow for more effective application of unitary optimizations (and nicer printing). *) Fixpoint canonicalize_com_l' {U dim} (l : com_list U dim) n : com_list U dim := match n with | O => l | S n' => match l with | [] => [] | Meas n l1 l2 :: t => let l1' := canonicalize_com_l' l1 n' in let l2' := canonicalize_com_l' l2 n' in Meas n l1' l2' :: (canonicalize_com_l' t n') | UC [] :: t => canonicalize_com_l' t n' | UC u1 :: UC u2 :: t => canonicalize_com_l' ((UC (u1 ++ u2)) :: t) n' | h :: t => h :: (canonicalize_com_l' t n') end end. Definition canonicalize_com_l {U dim} (l : com_list U dim) := canonicalize_com_l' l (count_ops l). (** Correctness properties for non-unitary programs. **) Module NUListProofs (G : GateSet). Module UL := UListProofs G. Export UL. (* Well-typedness *) Inductive c_well_typed_l {dim} : com_list G.U dim -> Prop := | WT_nilc : c_well_typed_l [] | WT_UC : forall u t, uc_well_typed_l u -> c_well_typed_l t -> c_well_typed_l ((UC u) :: t) | WT_Meas : forall n l1 l2 t, (n < dim)%nat -> c_well_typed_l l1 -> c_well_typed_l l2 -> c_well_typed_l t -> c_well_typed_l ((Meas n l1 l2) :: t). (* Induction principle for com_list *) Section com_list_ind. Variable dim : nat. Variable P : com_list G.U dim -> Prop. Hypothesis Nil_case : P ([] : com_list G.U dim). Hypothesis UC_case : forall (u : gate_list G.U dim) t, P t -> P ((UC u) :: t). Hypothesis Meas_case : forall n (l1 l2 : com_list G.U dim) t, P l1 -> P l2 -> P t -> P ((Meas n l1 l2) :: t). Fixpoint instr_ind_aux (i : instr G.U dim) := match i with | UC u => (fun t Pft => UC_case u t Pft) | Meas n l1 l2 => let fix f (l : com_list G.U dim) := match l with | [] => Nil_case | h :: t => instr_ind_aux h t (f t) end in (fun t Pft => Meas_case n l1 l2 t (f l1) (f l2) Pft) end. Fixpoint com_list_ind (l : com_list G.U dim) : P l := match l with | [] => Nil_case | h :: t => instr_ind_aux h t (com_list_ind t) end. End com_list_ind. (* Conversion to the base gate set - written awkwardly to convince Coq of termination. *) Fixpoint instr_to_com {dim} (i : instr G.U dim) : base_com dim := match i with | UC u => uc (list_to_ucom u) | Meas n l1 l2 => let fix f l := match l with | [] => skip | h :: t => instr_to_com h ; f t end in meas n (f l1) (f l2) end. Fixpoint list_to_com {dim} (l : com_list G.U dim) : base_com dim := match l with | [] => skip | h :: t => instr_to_com h ; list_to_com t end. Lemma instr_to_com_UC : forall dim (u : gate_list G.U dim), instr_to_com (UC u) = uc (list_to_ucom u). Proof. intros. reflexivity. Qed. Lemma instr_to_com_Meas : forall dim n (l1 : com_list G.U dim) l2, instr_to_com (Meas n l1 l2) = meas n (list_to_com l1) (list_to_com l2). Proof. intros. simpl. apply f_equal2. - induction l1; try rewrite IHl1; reflexivity. - induction l2; try rewrite IHl2; reflexivity. Qed. Global Opaque instr_to_com. Hint Rewrite instr_to_com_UC instr_to_com_Meas. Lemma list_to_com_append : forall {dim} (l1 l2 : com_list G.U dim), list_to_com (l1 ++ l2) ≡ list_to_com l1 ; list_to_com l2. Proof. intros dim l1 l2. unfold c_equiv. induction l1; simpl; try reflexivity. destruct a; simpl; intros; unfold compose_super; rewrite IHl1; auto with wf_db. Qed. Lemma list_to_com_WT : forall {dim} (l : com_list G.U dim), c_well_typed_l l <-> c_well_typed (list_to_com l). Proof. intros; split; intros H. - induction H; constructor; try rewrite instr_to_com_UC; try rewrite instr_to_com_Meas; try constructor; auto. apply list_to_ucom_WT. assumption. - induction l using (com_list_ind dim); inversion H; subst; try rewrite instr_to_com_UC in H2; try rewrite instr_to_com_Meas in H2; try inversion H2; subst; constructor; auto. apply list_to_ucom_WT. assumption. Qed. (** Equivalences over non-unitary programs. **) Definition c_equiv_l {dim} (l1 l2 : com_list G.U dim) := list_to_com l1 ≡ list_to_com l2. Infix "=l=" := c_equiv_l (at level 70) : com_scope. Lemma c_equiv_l_refl : forall {dim} (l1 : com_list G.U dim), l1 =l= l1. Proof. easy. Qed. Lemma c_equiv_l_sym : forall {dim} (l1 l2 : com_list G.U dim), l1 =l= l2 -> l2 =l= l1. Proof. unfold c_equiv_l. easy. Qed. Lemma c_equiv_l_trans : forall {dim} (l1 l2 l3 : com_list G.U dim), l1 =l= l2 -> l2 =l= l3 -> l1 =l= l3. Proof. unfold c_equiv_l. intros dim l1 l2 l3 H12 H23. rewrite H12. easy. Qed. Lemma c_cons_congruence : forall {dim} (i : instr G.U dim) (l l' : com_list G.U dim), l =l= l' -> i :: l =l= i :: l'. Proof. unfold c_equiv_l. intros dim i l l' Hl. simpl. rewrite Hl. reflexivity. Qed. Lemma c_app_congruence : forall {dim} (l1 l1' l2 l2' : com_list G.U dim), l1 =l= l1' -> l2 =l= l2' -> l1 ++ l2 =l= l1' ++ l2'. Proof. unfold c_equiv_l. intros dim l1 l1' l2 l2' Hl1 Hl2. repeat rewrite list_to_com_append; simpl. rewrite Hl1, Hl2. reflexivity. Qed. Add Parametric Relation (dim : nat) : (com_list G.U dim) (@c_equiv_l dim) reflexivity proved by c_equiv_l_refl symmetry proved by c_equiv_l_sym transitivity proved by c_equiv_l_trans as c_equiv_l_rel. Add Parametric Morphism (dim : nat) : (@List.cons (instr G.U dim)) with signature eq ==> (@c_equiv_l dim) ==> (@c_equiv_l dim) as c_cons_mor. Proof. intros y x0 y0 H0. apply c_cons_congruence; easy. Qed. Add Parametric Morphism (dim : nat) : (@app (instr G.U dim)) with signature (@c_equiv_l dim) ==> (@c_equiv_l dim) ==> (@c_equiv_l dim) as c_app_mor. Proof. intros x y H x0 y0 H0. apply c_app_congruence; easy. Qed. Lemma uc_equiv_l_implies_c_equiv_l : forall dim (u u' : gate_list G.U dim), (u =l= u')%ucom -> [UC u] =l= [UC u']. Proof. unfold uc_equiv_l, uc_equiv, c_equiv_l, c_equiv. intros dim u u' H Hdim ρ WFρ. simpl. repeat rewrite instr_to_com_UC. simpl; rewrite H; reflexivity. Qed. Lemma UC_append : forall {dim} (l1 l2: gate_list G.U dim), [UC (l1 ++ l2)] =l= [UC l1] ++ [UC l2]. Proof. intros. unfold c_equiv_l, c_equiv; simpl. intros. repeat rewrite instr_to_com_UC; simpl. rewrite list_to_ucom_append; simpl. rewrite compose_super_assoc. unfold compose_super, super. Msimpl. repeat rewrite Mmult_assoc. reflexivity. Qed. Lemma UC_nil : forall dim, [UC []] =l= ([] : com_list G.U dim). Proof. unfold c_equiv_l, c_equiv. intros; simpl. rewrite instr_to_com_UC; simpl. unfold compose_super, super. rewrite denote_SKIP; try assumption. Msimpl; reflexivity. Qed. (* Also useful to have a congruence lemma for rewriting inside Meas. *) Definition c_eval_l {dim} (l : com_list G.U dim) := c_eval (list_to_com l). Local Coercion Nat.b2n : bool >-> nat. Definition project_onto {dim} ρ n (b : bool) := super (@pad 1 n dim (∣b⟩ × ∣b⟩†)) ρ. Lemma Meas_cons_congruence : forall dim n (l1 l2 l1' l2' l l' : com_list G.U dim), (forall ρ, WF_Matrix ρ -> c_eval_l l1 (project_onto ρ n true) = c_eval_l l1' (project_onto ρ n true)) -> (forall ρ, WF_Matrix ρ -> c_eval_l l2 (project_onto ρ n false) = c_eval_l l2' (project_onto ρ n false)) -> l =l= l' -> Meas n l1 l2 :: l =l= Meas n l1' l2' :: l'. Proof. intros. unfold c_equiv_l; simpl. repeat rewrite instr_to_com_Meas. apply seq_congruence; auto. unfold c_equiv; simpl. intros Hdim ρ WFρ. unfold Splus, compose_super; simpl. unfold c_eval_l, project_onto in *. simpl in *. rewrite H, H0; auto. Qed. Lemma does_not_reference_instr_UC : forall dim q (u : gate_list G.U dim), does_not_reference_instr q (UC u) = does_not_reference u q. Proof. intros. reflexivity. Qed. Lemma does_not_reference_instr_Meas : forall dim q n (l1 : com_list G.U dim) l2, does_not_reference_instr q (Meas n l1 l2) = negb (q =? n) && does_not_reference_c l1 q && does_not_reference_c l2 q. Proof. intros. simpl. apply f_equal2; [apply f_equal2 |]. - reflexivity. - induction l1; simpl; try rewrite IHl1; reflexivity. - induction l2; simpl; try rewrite IHl2; reflexivity. Qed. Global Opaque does_not_reference_instr. Lemma next_measurement_preserves_structure : forall dim (l : com_list G.U dim) q l1 l1' l2' l2, next_measurement l q = Some (l1, l1', l2', l2) -> l = l1 ++ [Meas q l1' l2'] ++ l2. Proof. intros. generalize dependent l1. induction l; intros. - inversion H. - simpl in H. destruct a. + destruct (does_not_reference g q); try discriminate. destruct (next_measurement l q); try discriminate. do 3 destruct p. inversion H; subst. rewrite IHl with (l1:=l4); reflexivity. + bdestruct (q =? n). inversion H; subst. reflexivity. destruct (does_not_reference_c l0 q && does_not_reference_c l3 q); try discriminate. destruct (next_measurement l q); try discriminate. do 3 destruct p. inversion H; subst. rewrite IHl with (l1:=l6); reflexivity. Qed. Lemma next_measurement_l1_does_not_reference : forall {dim} (l : com_list G.U dim) q l1 l1' l2' l2, next_measurement l q = Some (l1, l1', l2', l2) -> does_not_reference_c l1 q = true. Proof. intros. generalize dependent l1. induction l; intros. - inversion H. - simpl in H. destruct a. + destruct (does_not_reference g q) eqn:dnr; try discriminate. destruct (next_measurement l q) eqn:nm; try discriminate. do 3 destruct p. inversion H; subst. simpl. apply andb_true_intro; split. assumption. rewrite IHl with (l1:=l4); reflexivity. + bdestruct (q =? n). inversion H; subst. reflexivity. destruct (does_not_reference_c l0 q) eqn:dnrl0. destruct (does_not_reference_c l3 q) eqn:dnrl3. all: simpl in H; try discriminate. destruct (next_measurement l q) eqn:Hnm; try discriminate. do 3 destruct p. inversion H; subst. simpl. rewrite does_not_reference_instr_Meas. repeat (try apply andb_true_intro; split). apply negb_true_iff; apply Nat.eqb_neq; assumption. all: try assumption. rewrite IHl with (l1:=l6); reflexivity. Qed. Lemma only_uses_commutes_pad1 : forall {dim} (u : base_ucom dim) q qs (A : Square 2), WF_Matrix A -> only_uses u qs -> not (In q qs) -> (@pad 1 q dim A) × uc_eval u = uc_eval u × (@pad 1 q dim A). Proof. intros dim u q qs A WFA Hou Hin. induction Hou; simpl. - rewrite <- Mmult_assoc. rewrite IHHou2; auto. rewrite Mmult_assoc. rewrite IHHou1; auto. rewrite <- Mmult_assoc. reflexivity. - assert (H0: q <> q0). intro contra; subst; auto. clear - WFA H0. dependent destruction u. autorewrite with eval_db. gridify; trivial. - assert (H1: q <> q1). intro contra; subst; auto. assert (H2: q <> q2). intro contra; subst; auto. clear - WFA H1 H2. autorewrite with eval_db. gridify; trivial. - dependent destruction u. Qed. Lemma does_not_reference_c_commutes_app1 : forall {dim} (l : com_list G.U dim) u q, does_not_reference_c l q = true -> [UC [App1 u q]] ++ l =l= l ++ [UC [App1 u q]]. Proof. intros dim l u q H. induction l using (com_list_ind dim); try reflexivity. - simpl in H. apply andb_true_iff in H as [Hu0 Hl]. rewrite <- (app_comm_cons _ _ (UC u0)). rewrite <- IHl; try assumption. rewrite (cons_to_app (UC u0)). rewrite (cons_to_app (UC u0) (_ ++ l)). repeat rewrite app_assoc. apply c_app_congruence; try reflexivity. rewrite does_not_reference_instr_UC in Hu0. repeat rewrite <- UC_append. apply uc_equiv_l_implies_c_equiv_l. apply does_not_reference_commutes_app1. assumption. - simpl in H. apply andb_true_iff in H as [Hmeas Hl3]. rewrite <- (app_comm_cons _ _ (Meas n l1 l2)). rewrite <- IHl3; try assumption. rewrite (cons_to_app (Meas n l1 l2)). rewrite (cons_to_app (Meas n l1 l2) (_ ++ l3)). repeat rewrite app_assoc. apply c_app_congruence; try reflexivity. rewrite does_not_reference_instr_Meas in Hmeas. apply andb_true_iff in Hmeas as [Hmeas Hl2]. apply andb_true_iff in Hmeas as [Hq Hl1]. apply IHl1 in Hl1. apply IHl2 in Hl2. apply negb_true_iff in Hq. apply Nat.eqb_neq in Hq. clear - Hq Hl1 Hl2. unfold c_equiv_l in *. repeat rewrite list_to_com_append in Hl1, Hl2. simpl in *. rewrite instr_to_com_UC in *. rewrite instr_to_com_Meas in *. unfold c_equiv in *; simpl in *. intros Hdim ρ WFρ. unfold compose_super, Splus in *. rewrite denote_SKIP in *; try assumption. rewrite Mmult_1_l in *; try auto with wf_db. remember (uc_eval (G.to_base u [q] (one_elem_list q))) as U. remember (proj n dim true) as pad1. remember (proj n dim false) as pad0. replace (super pad1 (super U ρ)) with (super U (super pad1 ρ)). 2: { subst; clear - Hq. unfold super. repeat rewrite Mmult_assoc. rewrite <- 2 Mmult_adjoint. repeat rewrite <- Mmult_assoc. unfold proj, pad_u. rewrite only_uses_commutes_pad1 with (qs:=[q]). reflexivity. auto with wf_db. apply G.to_base_only_uses_qs. intro contra. destruct_In; auto. } replace (super pad0 (super U ρ)) with (super U (super pad0 ρ)). 2: { subst; clear - Hq. unfold super. repeat rewrite Mmult_assoc. rewrite <- 2 Mmult_adjoint. repeat rewrite <- Mmult_assoc. unfold proj, pad_u. rewrite only_uses_commutes_pad1 with (qs:=[q]). reflexivity. auto with wf_db. apply G.to_base_only_uses_qs. intro contra. destruct_In; auto. } rewrite Hl1, Hl2; auto. 2, 3: subst; auto with wf_db. unfold super. rewrite <- Mmult_plus_distr_r. rewrite <- Mmult_plus_distr_l. reflexivity. Qed. End NUListProofs.
From mathcomp Require Import ssreflect ssrfun ssrbool ssrnat eqtype seq choice fintype path ssrint rat bigop. From extructures Require Import ord fset fmap ffun. Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Local Open Scope fset_scope. Definition int_ordMixin := CanOrdMixin natsum_of_intK. Canonical int_ordType := Eval hnf in OrdType int int_ordMixin. Definition rat_ordMixin := [ordMixin of rat by <:]. Canonical rat_ordType := Eval hnf in OrdType rat rat_ordMixin. Section Update. Context {T : ordType} {S : eqType} {def : T -> S}. Definition updm (f : ffun def) (xs : {fmap T -> S}) : ffun def := mkffun (fun v => if xs v is Some x then x else f v) (supp f :|: domm xs). Lemma updmE f xs x : updm f xs x = if xs x is Some y then y else f x. Proof. rewrite /updm mkffunE in_fsetU orbC mem_domm. case e: (xs x)=> [y|] //=. by case: ifPn=> // /suppPn ->. Qed. End Update. Arguments bigcupP {_ _ _ _ _ _}. Arguments mkfmap {_ _}.
-- exercises in "Type-Driven Development with Idris" -- chapter 8 import Data.Vect -- check that all functions are total %default total -- -- section 8.1 -- data Vector : Nat -> Type -> Type where Nil : Vector Z a (::) : a -> Vector k a -> Vector (S k) a same_cons : {xs : List a} -> {ys : List a} -> xs = ys -> x :: xs = x :: ys same_cons Refl = Refl same_lists : {xs : List a} -> {ys : List a} -> x = y -> xs = ys -> x :: xs = y :: ys same_lists Refl Refl = Refl data ThreeEq : a -> b -> c -> Type where Same3 : ThreeEq n n n -- for all three natural numbers, -- if the three numbers are equal then their three successors are equal allSameS : (x, y, z : Nat) -> ThreeEq x y z -> ThreeEq (S x) (S y) (S z) allSameS z z z Same3 = Same3 -- > allSameS 2 3 2 Same3 -- (input):1:1-20:When checking an application of function Main.allSameS: -- Type mismatch between -- ThreeEq n n n (Type of Same3) -- and -- ThreeEq 2 3 2 (Expected type) -- -- Specifically: -- Type mismatch between -- 0 -- and -- 1 -- > allSameS 2 2 2 Same3 -- Same3 : ThreeEq 3 3 3 -- -- section 8.2 -- myPlusCommutes : (n : Nat) -> (m : Nat) -> n + m = m + n myPlusCommutes Z m = rewrite sym (plusZeroRightNeutral m) in Refl myPlusCommutes (S k) m = rewrite myPlusCommutes k m in rewrite plusSuccRightSucc m k in Refl reverseProof_nil : Vect n1 a -> Vect (plus n1 0) a reverseProof_nil {n1} xs = rewrite plusZeroRightNeutral n1 in xs reverseProof_xs : Vect (S (plus n1 len)) a -> Vect (plus n1 (S len)) a reverseProof_xs {n1} {len} xs = rewrite sym (plusSuccRightSucc n1 len) in xs myReverse : Vect n a -> Vect n a myReverse xs = reverse [] xs where reverse : Vect n a -> Vect m a -> Vect (n+m) a reverse acc [] = reverseProof_nil acc reverse acc (x :: xs) = reverseProof_xs (reverse (x :: acc) xs) -- -- section 8.3 -- headUnequal : DecEq a => {xs : Vector n a} -> {ys : Vector n a} -> (contra : (x = y) -> Void) -> ((x :: xs) = (y :: ys)) -> Void headUnequal contra Refl = contra Refl tailUnequal : DecEq a => {xs : Vector n a} -> {ys : Vector n a} -> (contra : (xs = ys) -> Void) -> ((x :: xs) = (x :: ys)) -> Void tailUnequal contra Refl = contra Refl DecEq a => DecEq (Vector n a) where decEq [] [] = Yes Refl decEq (x :: xs) (y :: ys) = case decEq x y of Yes Refl => case decEq xs ys of Yes Refl => Yes Refl No contra2 => No (tailUnequal contra2) No contra => No (headUnequal contra)
using URIParser struct Address scheme::String host::String port::Integer end function Base.show(io::IO, address::Address) print(io, "Address(scheme: $(address.scheme), host: $(address.host) port: $(address.port))") end function from_uri(uri::String, default_port::Integer=0) parsed = URI(uri) return Address(parsed.scheme, parsed.host, if parsed.port == 0 default_port else parsed.port end) end Base.:(==)(x::Address, y::Address) = x.scheme == y.scheme && x.host == y.host && x.port == y.port
# Overview and Examples A brief description of what linearsolve is for followed by examples. ## What linearsolve Does linearsolve defines a class - linearsolve.model - with several functions for approximating, solving, and simulating dynamic stochastic general equilibrium (DSGE) models. The equilibrium conditions for most DSGE models can be expressed as a vector function $f$: \begin{align} f(E_t X_{t+1}, X_t, \epsilon_{t+1}) = 0, \tag{1} \end{align} where 0 is an $n\times 1$ vector of zeros, $X_t$ is an $n\times 1$ vector of endogenous variables, and $\epsilon_{t+1}$ is an $m\times 1$ vector of exogenous structural shocks to the model. $E_tX_{t+1}$ denotes the expecation of the $t+1$ endogenous variables based on the information available to agents in the model as of time period $t$. linearsolve.model has methods for computing linear and log-linear approximations of the model in equation (1) and methods for solving and simulating the linear model. ## Example 1: Quickly Simulate an RBC Model Here I demonstrate how how relatively straightforward it is to appoximate, solve, and simulate a DSGE model using `linearsolve`. In the example that follows, I describe the procedure more carefully. \begin{align} C_t^{-\sigma} & = \beta E_t \left[C_{t+1}^{-\sigma}(\alpha A_{t+1} K_{t+1}^{\alpha-1} + 1 - \delta)\right]\\ C_t + K_{t+1} & = A_t K_t^{\alpha} + (1-\delta)K_t\\ \log A_{t+1} & = \rho_a \log A_{t} + \epsilon_{t+1} \end{align} In the block of code that immediately follows, I input the model, solve for the steady state, compute the log-linear approximation of the equilibirum conditions, and compute some impulse responses following a shock to technology $A_t$. ```python # Import numpy, pandas, linearsolve, matplotlib.pyplot import numpy as np import pandas as pd import linearsolve as ls import matplotlib.pyplot as plt plt.style.use('classic') %matplotlib inline # Input model parameters parameters = pd.Series() parameters['alpha'] = .35 parameters['beta'] = 0.99 parameters['delta'] = 0.025 parameters['rhoa'] = .9 parameters['sigma'] = 1.5 parameters['A'] = 1 # Funtion that evaluates the equilibrium conditions def equilibrium_equations(variables_forward,variables_current,parameters): # Parameters p = parameters # Variables fwd = variables_forward cur = variables_current # Household Euler equation euler_eqn = p.beta*fwd.c**-p.sigma*(p.alpha*cur.a*fwd.k**(p.alpha-1)+1-p.delta) - cur.c**-p.sigma # Goods market clearing market_clearing = cur.c + fwd.k - (1-p.delta)*cur.k - cur.a*cur.k**p.alpha # Exogenous technology technology_proc = p.rhoa*np.log(cur.a) - np.log(fwd.a) # Stack equilibrium conditions into a numpy array return np.array([ euler_eqn, market_clearing, technology_proc ]) # Initialize the model model = ls.model(equations = equilibrium_equations, n_states=2, var_names=['a','k','c'], shock_names=['e_a','e_k'], parameters = parameters) # Compute the steady state numerically guess = [1,1,1] model.compute_ss(guess) # Find the log-linear approximation around the non-stochastic steady state and solve model.approximate_and_solve() # Compute impulse responses and plot model.impulse(T=41,t0=5,shocks=None) fig = plt.figure(figsize=(12,4)) ax1 =fig.add_subplot(1,2,1) model.irs['e_a'][['a','k','c']].plot(lw='5',alpha=0.5,grid=True,ax=ax1).legend(loc='upper right',ncol=3) ax2 =fig.add_subplot(1,2,2) model.irs['e_a'][['e_a','a']].plot(lw='5',alpha=0.5,grid=True,ax=ax2).legend(loc='upper right',ncol=2) ``` ## Example 2: An RBC Model with More Details Consider the equilibrium conditions for a basic RBC model without labor: \begin{align} C_t^{-\sigma} & = \beta E_t \left[C_{t+1}^{-\sigma}(\alpha A_{t+1} K_{t+1}^{\alpha-1} + 1 - \delta)\right]\\ Y_t & = A_t K_t^{\alpha}\\ I_t & = K_{t+1} - (1-\delta)K_t\\ Y_t & = C_t + I_t\\ \log A_t & = \rho_a \log A_{t-1} + \epsilon_t \end{align} In the nonstochastic steady state, we have: \begin{align} K & = \left(\frac{\alpha A}{1/\beta+\delta-1}\right)^{\frac{1}{1-\alpha}}\\ Y & = AK^{\alpha}\\ I & = \delta K\\ C & = Y - I \end{align} Given values for the parameters $\beta$, $\sigma$, $\alpha$, $\delta$, and $A$, steady state values of capital, output, investment, and consumption are easily computed. ### Initializing the model in `linearsolve` To initialize the model, we need to first set the model's parameters. We do this by creating a Pandas Series variable called `parameters`: ```python # Input model parameters parameters = pd.Series() parameters['alpha'] = .35 parameters['beta'] = 0.99 parameters['delta'] = 0.025 parameters['rhoa'] = .9 parameters['sigma'] = 1.5 parameters['A'] = 1 ``` Next, we need to define a function that returns the equilibrium conditions of the model. The function will take as inputs two vectors: one vector of "current" variables and another of "forward-looking" or one-period-ahead variables. The function will return an array that represents the equilibirum conditions of the model. We'll enter each equation with all variables moved to one side of the equals sign. For example, here's how we'll enter the produciton fucntion: `production_function = technology_current*capital_current**alpha - output_curent` Here the variable `production_function` stores the production function equation set equal to zero. We can enter the equations in almost any way we want. For example, we could also have entered the production function this way: `production_function = 1 - output_curent/technology_current/capital_current**alpha` One more thing to consider: the natural log in the equation describing the evolution of total factor productivity will create problems for the solution routine later on. So rewrite the equation as: \begin{align} A_{t+1} & = A_{t}^{\rho_a}e^{\epsilon_{t+1}}\\ \end{align} So the complete system of equations that we enter into the program looks like: \begin{align} C_t^{-\sigma} & = \beta E_t \left[C_{t+1}^{-\sigma}(\alpha Y_{t+1} /K_{t+1}+ 1 - \delta)\right]\\ Y_t & = A_t K_t^{\alpha}\\ I_t & = K_{t+1} - (1-\delta)K_t\\ Y_t & = C_t + I_t\\ A_{t+1} & = A_{t}^{\rho_a}e^{\epsilon_{t+1}} \end{align} Now let's define the function that returns the equilibrium conditions: ```python def equilibrium_equations(variables_forward,variables_current,parameters): # Parameters p = parameters # Variables fwd = variables_forward cur = variables_current # Household Euler equation euler_eqn = p.beta*fwd.c**-p.sigma*(p.alpha*fwd.y/fwd.k+1-p.delta) - cur.c**-p.sigma # Production function production_fuction = cur.a*cur.k**p.alpha - cur.y # Capital evolution capital_evolution = fwd.k - (1-p.delta)*cur.k - cur.i # Goods market clearing market_clearing = cur.c + cur.i - cur.y # Exogenous technology technology_proc = cur.a**p.rhoa- fwd.a # Stack equilibrium conditions into a numpy array return np.array([ euler_eqn, production_fuction, capital_evolution, market_clearing, technology_proc ]) ``` Notice that inside the function we have to define the variables of the model form the elements of the input vectors `variables_forward` and `variables_current`. It is *essential* that the predetermined or state variables are ordered first. ### Initializing the model To initialize the model, we need to specify the number of state variables in the model, the names of the endogenous varaibles in the same order used in the `equilibrium_equations` function, and the names of the exogenous shocks to the model. ```python # Initialize the model rbc = ls.model(equations = equilibrium_equations, n_states=2, var_names=['a','k','c','y','i'], shock_names=['e_a','e_k'], parameters=parameters) ``` The solution routine solves the model as if there were a separate exogenous shock for each state variable and that's why I initialized the model with two exogenous shocks `e_a` and `e_k` even though the RBC model only has one exogenous shock. ### Steady state Next, we need to compute the nonstochastic steady state of the model. The `.compute_ss()` method can be used to compute the steady state numerically. The method's default is to use scipy's `fsolve()` function, but other scipy root-finding functions can be used: `root`, `broyden1`, and `broyden2`. The optional argument `options` lets the user pass keywords directly to the optimization function. Check out the documentation for Scipy's nonlinear solvers here: http://docs.scipy.org/doc/scipy/reference/optimize.html ```python # Compute the steady state numerically guess = [1,1,1,1,1] rbc.compute_ss(guess) print(rbc.ss) ``` a 1.000000 k 34.398226 c 2.589794 y 3.449750 i 0.859956 dtype: float64 Note that the steady state is returned as a Pandas Series. Alternatively, you could compute the steady state directly and then sent the `rbc.ss` attribute: ```python # Steady state solution p = parameters K = (p.alpha*p.A/(1/p.beta+p.delta-1))**(1/(1-p.alpha)) C = p.A*K**p.alpha - p.delta*K Y = p.A*K**p.alpha I = Y - C rbc.set_ss([p.A,K,C,Y,I]) print(rbc.ss) ``` a 1.000000 k 34.398226 c 2.589794 y 3.449750 i 0.859956 dtype: float64 ### Log-linearization and solution Now we use the `.log_linear()` method to find the log-linear appxoximation to the model's equilibrium conditions. That is, we'll transform the nonlinear model into a linear model in which all variables are expressed as log-deviations from the steady state. Specifically, we'll compute the matrices $A$ and $B$ that satisfy: \begin{align} A E_t\left[ x_{t+1} \right] & = B x_t + \left[ \begin{array}{c} \epsilon_{t+1} \\ 0 \end{array} \right], \end{align} where the vector $x_{t}$ denotes the log deviation of the endogenous variables from their steady state values. ```python # Find the log-linear approximation around the non-stochastic steady state rbc.log_linear_approximation() print('The matrix A:\n\n',np.around(rbc.a,4),'\n\n') print('The matrix B:\n\n',np.around(rbc.b,4)) ``` The matrix A: [[ 0.00000e+00 -8.30000e-03 -3.59900e-01 8.30000e-03 0.00000e+00] [ 0.00000e+00 0.00000e+00 0.00000e+00 0.00000e+00 0.00000e+00] [ 0.00000e+00 3.43982e+01 0.00000e+00 0.00000e+00 0.00000e+00] [ 0.00000e+00 0.00000e+00 0.00000e+00 0.00000e+00 0.00000e+00] [-1.00000e+00 0.00000e+00 0.00000e+00 0.00000e+00 0.00000e+00]] The matrix B: [[-0. -0. -0.3599 -0. -0. ] [-3.4497 -1.2074 -0. 3.4497 -0. ] [-0. 33.5383 -0. -0. 0.86 ] [-0. -0. -2.5898 3.4497 -0.86 ] [-0.9 -0. -0. -0. -0. ]] Finally, we need to obtain the *solution* to the log-linearized model. The solution is a pair of matrices $F$ and $P$ that specify: 1. The current values of the non-state variables $u_{t}$ as a linear function of the previous values of the state variables $s_t$. 1. The future values of the state variables $s_{t+1}$ as a linear function of the previous values of the state variables $s_t$ and the future realisation of the exogenous shock process $\epsilon_{t+1}$. \begin{align} u_t & = Fs_t\\ s_{t+1} & = Ps_t + \epsilon_{t+1}. \end{align} We use the `.klein()` method to find the solution. ```python # Solve the model rbc.solve_klein(rbc.a,rbc.b) # Display the output print('The matrix F:\n\n',np.around(rbc.f,4),'\n\n') print('The matrix P:\n\n',np.around(rbc.p,4)) ``` The matrix F: [[ 0.2297 0.513 ] [ 1. 0.35 ] [ 3.3197 -0.1408]] The matrix P: [[0.9 0. ] [0.083 0.9715]] ### Impulse responses One the model is solved, use the `.impulse()` method to compute impulse responses to exogenous shocks to the state. The method creates the `.irs` attribute which is a dictionary with keys equal to the names of the exogenous shocks and the values are Pandas DataFrames with the computed impulse respones. You can supply your own values for the shocks, but the default is 0.01 for each exogenous shock. ```python # Compute impulse responses and plot rbc.impulse(T=41,t0=1,shocks=None,percent=True) print('Impulse responses to a 0.01 unit shock to A:\n\n',rbc.irs['e_a'].head()) ``` Impulse responses to a 0.01 unit shock to A: e_a a k c y i 0 0.0 0.000 0.000000 0.000000 0.000000 0.000000 1 1.0 1.000 0.000000 0.229718 1.000000 3.319739 2 0.0 0.900 0.082993 0.249318 0.929048 2.976083 3 0.0 0.810 0.155321 0.265744 0.864362 2.667127 4 0.0 0.729 0.218116 0.279348 0.805341 2.389390 Plotting is easy. ```python rbc.irs['e_a'][['a','k','c','y','i']].plot(lw='5',alpha=0.5,grid=True).legend(loc='upper right',ncol=2) rbc.irs['e_a'][['e_a','a']].plot(lw='5',alpha=0.5,grid=True).legend(loc='upper right',ncol=2) ``` ### Stochastic simulation Creating a stochastic simulation of the model is straightforward with the `.stoch_sim()` method. In the following example, I create a 151 period (including t=0) simulation by first simulating the model for 251 periods and then dropping the first 100 values. The variance of the shock to $A_t$ is set to 0.001 and the variance of the shock to $K_t$ is set to zero because there is not capital shock in the model. The seed for the numpy random number generator is set to 0. ```python rbc.stoch_sim(T=121,drop_first=100,cov_mat=np.array([[0.00763**2,0],[0,0]]),seed=0,percent=True) rbc.simulated[['k','c','y','i']].plot(lw='5',alpha=0.5,grid=True).legend(loc='upper right',ncol=4) rbc.simulated[['a']].plot(lw='5',alpha=0.5,grid=True).legend(ncol=4) rbc.simulated[['e_a','e_k']].plot(lw='5',alpha=0.5,grid=True).legend(ncol=4) ``` ## Example 3: A New-Keynesian Model Consider the new-Keynesian business cycle model from Walsh (2017), chapter 8 expressed in log-linear terms: \begin{align} y_t & = E_ty_{t+1} - \sigma^{-1} (i_t - E_t\pi_{t+1}) + g_t\\ \pi_t & = \beta E_t\pi_{t+1} + \kappa y_t + u_t\\ i_t & = \phi_x y_t + \phi_{\pi} \pi_t + v_t\\ r_t & = i_t - E_t\pi_{t+1}\\ g_{t+1} & = \rho_g g_{t} + \epsilon_{t+1}^g\\ u_{t+1} & = \rho_u u_{t} + \epsilon_{t+1}^u\\ v_{t+1} & = \rho_v v_{t} + \epsilon_{t+1}^v \end{align} where $y_t$ is the output gap (log-deviation of output from the natural rate), $\pi_t$ is the quarterly rate of inflation between $t-1$ and $t$, $i_t$ is the nominal interest rate on funds moving between period $t$ and $t+1$, $r_t$ is the real interest rate, $g_t$ is the exogenous component of demand, $u_t$ is an exogenous component of inflation, and $v_t$ is the exogenous component of monetary policy. Since the model is already log-linear, there is no need to approximate the equilibrium conditions. We'll still use the `.log_linear` method to find the matrices $A$ and $B$, but we'll have to set the `islinear` option to `True` to avoid generating an error. ### Inintialize model and solve ```python # Input model parameters beta = 0.99 sigma= 1 eta = 1 omega= 0.8 kappa= (sigma+eta)*(1-omega)*(1-beta*omega)/omega rhor = 0.9 phipi= 1.5 phiy = 0 rhog = 0.5 rhou = 0.5 rhov = 0.9 Sigma = 0.001*np.eye(3) # This time we'll input the model parameters a list of values and we'll include a list of name strings. And # the program will consolidate the information into a Pandas Series. FYI the parameters list is required, # but the parameter names is optional. If omitted, the names are set to 'parameter 1', 'parameter 2', etc. parameters = [beta,sigma,eta,omega,kappa,rhor,phipi,phiy,rhog,rhou,rhov] parameter_names = ['beta','sigma','eta','omega','kappa','rhor','phipi','phiy','rhog','rhou','rhov'] def equilibrium_equations(variables_forward,variables_current,parameters): # Parameters p = parameters # Variables fwd = variables_forward cur = variables_current # Exogenous demand g_proc = p.rhog*cur.g - fwd.g # Exogenous inflation u_proc = p.rhou*cur.u - fwd.u # Exogenous monetary policy v_proc = p.rhov*cur.v - fwd.v # Euler equation euler_eqn = fwd.y -1/p.sigma*(cur.i-fwd.pi) + fwd.g - cur.y # NK Phillips curve evolution phillips_curve = p.beta*fwd.pi + p.kappa*cur.y + fwd.u - cur.pi # interest rate rule interest_rule = p.phiy*cur.y+p.phipi*cur.pi + fwd.v - cur.i # Fisher equation fisher_eqn = cur.i - fwd.pi - cur.r # Stack equilibrium conditions into a numpy array return np.array([ g_proc, u_proc, v_proc, euler_eqn, phillips_curve, interest_rule, fisher_eqn ]) # Initialize the nk model nk = ls.model(equilibrium_equations, n_states=3, var_names=['g','u','v','i','r','y','pi'], shock_names=['e_g','e_u','e_v'], parameters=parameters, parameter_names=parameter_names) # Set the steady state of the nk model nk.set_ss([0,0,0,0,0,0,0]) # Find the log-linear approximation around the non-stochastic steady state nk.linear_approximation() # Solve the nk model nk.solve_klein(nk.a,nk.b) ``` ### Compute impulse responses and plot Compute impulse responses of the endogenous variables to a one percent shock to each exogenous variable. ```python # Compute impulse responses nk.impulse(T=11,t0=1,shocks=None) # Create the figure and axes fig = plt.figure(figsize=(12,12)) ax1 = fig.add_subplot(3,1,1) ax2 = fig.add_subplot(3,1,2) ax3 = fig.add_subplot(3,1,3) # Plot commands nk.irs['e_g'][['g','y','i','pi','r']].plot(lw='5',alpha=0.5,grid=True,title='Demand shock',ax=ax1).legend(loc='upper right',ncol=5) nk.irs['e_u'][['u','y','i','pi','r']].plot(lw='5',alpha=0.5,grid=True,title='Inflation shock',ax=ax2).legend(loc='upper right',ncol=5) nk.irs['e_v'][['v','y','i','pi','r']].plot(lw='5',alpha=0.5,grid=True,title='Interest rate shock',ax=ax3).legend(loc='upper right',ncol=5) ``` ### Construct a stochastic simulation and plot Contruct a 151 period stochastic simulation by first siumlating the model for 251 periods and then dropping the first 100 values. The seed for the numpy random number generator is set to 0. ```python # Compute stochastic simulation nk.stoch_sim(T=151,drop_first=100,cov_mat=Sigma,seed=0) # Create the figure and axes fig = plt.figure(figsize=(12,8)) ax1 = fig.add_subplot(2,1,1) ax2 = fig.add_subplot(2,1,2) # Plot commands nk.simulated[['y','i','pi','r']].plot(lw='5',alpha=0.5,grid=True,title='Output, inflation, and interest rates',ax=ax1).legend(ncol=4) nk.simulated[['g','u','v']].plot(lw='5',alpha=0.5,grid=True,title='Exogenous demand, inflation, and policy',ax=ax2).legend(ncol=4,loc='lower right') ``` ```python # Plot simulated exogenous shocks nk.simulated[['e_g','g']].plot(lw='5',alpha=0.5,grid=True).legend(ncol=2) nk.simulated[['e_u','u']].plot(lw='5',alpha=0.5,grid=True).legend(ncol=2) nk.simulated[['e_v','v']].plot(lw='5',alpha=0.5,grid=True).legend(ncol=2) ```
\begin{wrapfigure}{r}{0.5\textwidth} \begin{center} \includegraphics[width=0.5\textwidth]{cpp14faqs/cover} \end{center} %\caption{Front Cover} \end{wrapfigure} This book contains selected questions (\textbf{84}) related to C++14 with detailed solutions to all of these which will help the reader to hone her skills to solve a particular problem. Primary source of this collection is \emph{Advanced C++ FAQs: Volumes 1 \& 2}. This book is not an introduction to C++. It assumes that the reader is aware of the basics of C++98 and C++03 and wants to expand her horizon to latest and greatest in C++14(aka C++1y). The problems are marked on a scale of one(*)(simplest) to five stars(*****)(hardest). \hrulefill \section{Table of Contents} \begin{enumerate}[noitemsep] \item variable templates \item Constexpr static data members of class templates \item constexpr function templates \item variable templates in action \item static data member template \item specialization of variable template \item default argument and specialization of variable template \item lambda and variable template \item variable templates variables vary \item auto variable templates \item valid specialization but error ? \item variable templates and lambda revisited \item Incremental improvement to integral\_constant \item is\_same musings \item auto variable template and generic lambda \item constexpr member functions and implicit const \item constexpr constructor and initialization \item constexpr and branching \item constexpr and looping iteration \item constexpr and mutation \item constexpr vs static vs uninitialized \item constexpr vs member function revisited \item deprecated attribute \item Member initializers and aggregate class \item Member initializers and aggregate array \item Data Member initializers \item time duration literals \item Expressing π multiplication \item Compile Time \_binary Literal Operator \item Square Literal Operator \item Type Transformation Aliases \item unique\_ptr vs make\_unique as function argument \item make\_unique as perfect forwarding guy \item make\_unique and new \item make\_unique and value initialization \item make\_unique and single object \item make\_unique and default initialization \item make\_unique and array T[n] \item make\_unique and array T[] \item make\_unique and default initialization with T[] \item Extend make\_unique : Support list initialization T[] \item Extend make\_unique : Value Initialize T[] \item Extend make\_unique : T[N] \item allocate\_unique \item Compile-time integer sequences \item Simplified Creation of std::integer\_sequence \item std::index\_sequence \item Custom Sequence : Addition \item Custom Sequence : Multiply \item Custom Sequence : Split \item Extract from tuple \item convert std::array to std::tuple \item Piecewise construction of std::pair \item Compile Time Integer Sequence Simplified \item sfinae and represent type of function \item metafunction : check presence of type member \item std::common\_type and sfinae \item Contextual Conversion \item Single quotation mark as digit separator \item Binary Literals \item auto return type in function declaration \item return type deduction for function \item return type deduction for lambdas \item return type deduction for lambdas contd.. \item decltype(auto) \item return type deduction for function templates \item explicit instantiation and auto \item return type deduction and virtual \item deduce return type \item generalized lambda capture \item generic lambda and product vector \item generic lambda \item generic lambda definition \item conversion function of generic lambda \item generic lambda quiz \item Preventing Name Hijacking \item Find First Null Pointer in a Container \item Generic Operator Functors \item Exchange Utility \item Addressing Tuple By Type \item Quoted manipulators \item Null Iterator \item std::move is rvalue\_cast \item C++14 Compiler \end{enumerate} \hrulefill \underline{\textbf{\textcolor{BurntOrange}{Excerpt} \textcolor{Sepia}{(Questions 1-23 with Solutions):}}} \section{variable templates} \begin{Exercise}[title={variable template}, difficulty=3, label=ex01] \index{variable template} What is a \emph{variable template} ? \end{Exercise} \begin{Answer}[ref=ex01]\index{variable template} A \emph{variable template} is a declaration which is introduced by a template declaration of a variable. As we already know that a template declaration is also a definition if its declaration defines a function, a class, a variable, or a static data member. A \emph{variable template} at class scope is a \emph{static data member template}. Consider a simple template meta function, which uses variable template feature to store the boolean value of result of comparing two types: \begin{lstlisting} template <typename T, typename U> constexpr bool is_same = std::is_same<T, U>::value; bool t = is_same<int, int>; // true bool f = is_same<int, float>; // false \end{lstlisting} The types of variable templates are not restricted to just built-in types; they can be user defined types. \begin{lstlisting} struct matrix_constants { template<typename T> using pauli = hermitian_matrix<T, 2>; template<typename T> constexpr pauli<T> sigma1 = { { 0, 1 }, { 1, 0 } }; template<typename T> constexpr pauli<T> sigma2 = { { 0, -1i }, { 1i, 0 } }; template<typename T> constexpr pauli<T> sigma3 = { { 1, 0 }, { -1, 0 } }; }; \end{lstlisting} It makes definitions and uses of parameterized constants much simpler, leading to simplified and more uniform programming rules to teach and to remember like: \begin{lstlisting} template<typename T> struct lexical_cast_fn { template<typename U> T operator()(U const &u) const { //... } }; template<typename T> constexpr lexical_cast_fn<T> lexical_cast{}; int main() { lexical_cast<int>("42"); } \end{lstlisting} \end{Answer} \section{Constexpr static data members of class templates} \begin{Exercise}[title={\small Constexpr static data members of class templates}, difficulty=3, label=ex02] \index{Constexpr static data members of class templates} What is issue with constexpr static data members of class templates ? \end{Exercise} \begin{Answer}[ref=ex02]\index{Constexpr static data members of class templates} Let us revisit how \emph{std::is\_same} is designed: \begin{lstlisting} template<typename T, T v> struct integral_constant { static constexpr T value = v; typedef T value_type; .... }; template<typename T, T v> constexpr T integral_constant<T, v>::value; typedef integral_constant<bool, true> true_type; typedef integral_constant<bool, false> false_type; template<typename T, typename U> struct is_same : false_type{}; template<typename T> struct is_same<T, T> : true_type{}; \end{lstlisting} The main problems with \emph{static data member} are: \begin{itemize} \item they require \emph{duplicate} declarations: \begin{enumerate} \item once inside the class template, \item once outside the class template to provide the real definition in case the constants is odr(One Definition Rule) used. \end{enumerate} \item It creates confusion by the necessity of providing twice the same declaration, whereas ordinary constant declarations do not need duplicate declarations. \end{itemize} The standard class \emph{numeric\_limits} also suffers from the same problem as far as constexpr static data members are concerned. \end{Answer} \section{constexpr function templates} \begin{Exercise}[title={constexpr function templates}, difficulty=3, label=ex03] \index{constexpr function templates} What is issue with constexpr function templates ? \end{Exercise} \begin{Answer}[ref=ex03]\index{constexpr function templates} Constexpr functions templates provide functional abstraction. A simple constexpr function template : \begin{lstlisting} template <typename T, typename U> constexpr bool is_same() { return std::is_same<T, U>::value; } \end{lstlisting} Constexpr functions templates do not have the duplicate declarations issue that static data members have. However, they force us to chose in advance, at the definition site, how the constants are to be delivered: either by a const reference, or by plain non-reference type. If delivered by const reference then the constants must be systematically be allocated in static storage. If by non-reference type, then the constants need copying. Copying isn't an issue for built-in types, but it is an issue for user-defined types with value semantics that aren't just wrappers around tiny built-in types Whereas ordinary const(expr) variables do not suffer from this problem. A simple definition is provided, and the decision of whether the constants actually needs to be layout out in storage only depends on the usage, not the definition. Another examples are the static member functions of \emph{std::numeric\_limits} and functions like $boost::constants::pi<T>()$: \begin{lstlisting} #include <boost/math/constants/constants.hpp> template <class Real> Real area(Real r) { using namespace boost::math::constants; return pi<Real>() * r * r; } \end{lstlisting} The function template versions of the constants are simple inline functions that return a constant of the correct precision for the type used. In addition, these functions are declared constexpr for those compilers that support this, allowing the result to be used in constant expressions provided the template argument is a literal type. It looks like we are creating constexpr functions only to return a constant. \end{Answer} \section{variable templates in action} \begin{Exercise}[title={variable templates in action}, difficulty=2, label=ex04] \index{variable templates} Illustrate how \emph{variable templates} can be used to compute the area of a circle for a given type with appropriate precision? \end{Exercise} \begin{Answer}[ref=ex04]\index{variable templates in action} \emph{variable templates} address both of the issues illustrated before and no syntax modification was required to incorporate this feature in C++11 because current grammar allows any declaration to be parameterized. It was prohibited earlier via semantic constraints which is relaxed now on template declarations. Let us first represent the mathematical constant $\pi$ with precision dictated by a floating point datatype: \lstinputlisting[caption=$\pi$ and variable template]{cpp14faqs/code/c++14/variable_template.cpp} With the following command: \begin{verbatim} clang++ -std=c++1y variable_template.cpp \end{verbatim} we get the following output: \begin{verbatim} pi<int> : 3 pi<float> : 3.1415927410125732421875 pi<double> : 3.141592653589793115997963468544185161591 \end{verbatim} This variable template can be used in a generic function to compute the area of a circle for a given radius: \lstinputlisting{cpp14faqs/code/c++14/variable_template_area.cpp} \end{Answer} \section{static data member template} \begin{Exercise}[title={static data member template}, difficulty=2, label=ex05] \index{static data member template} Provide a suitable definition of the static data member template \emph{min}: \begin{lstlisting} struct limits { template<typename T> static const T min; // declaration of min }; \end{lstlisting} \end{Exercise} \begin{Answer}[ref=ex05]\index{static data member template} As we already know that a variable template at class scope is a \emph{static data member template} and a definition for a static data member or static data member template may be provided in a namespace scope enclosing the definition of the static member's class template. \begin{lstlisting} struct limits { template<typename T> static const T min; // declaration of min }; template<typename T> const T limits::min = { }; // definition of min \end{lstlisting} \end{Answer} \section{specialization of variable template} \begin{Exercise}[title={specialization of variable template}, difficulty=3, label=ex06] \index{specialization of variable template} Simplify the program below to do the needful: \begin{lstlisting} template <typename T, typename U> constexpr bool is_same = std::is_same<T, U>::value; bool t = is_same<int, int>; // true bool f = is_same<int, float>; // false \end{lstlisting} \end{Exercise} \begin{Answer}[ref=ex06]\index{specialization of variable template} Variable templates are subject to template specialization like template functions, so we can simplify the code as follows: \begin{lstlisting} template<typename T, typename U> constexpr bool is_same = false; template<typename T> constexpr bool is_same<T, T> = true; \end{lstlisting} \end{Answer} \section{default argument and specialization of variable template} \begin{Exercise}[title={\small default argument and specialization of variable template}, difficulty=3, label=ex07] \index{default argument and specialization of variable template} What is the output of the program ? \lstinputlisting{cpp14faqs/code/c++14/specialize_variable_templates.cpp} \end{Exercise} \begin{Answer}[ref=ex07]\index{default argument and specialization of variable template} \begin{verbatim} pi<> : 3.14159265358979311599796346854 pi<int> : 3.1415927410125732421875 pi<float> : 3.1415927410125732421875 \end{verbatim} \end{Answer} \section{lambda and variable template} \begin{Exercise}[title={\small lambda and variable template}, difficulty=3, label=ex08] \index{lambda and variable template} Simplify the program below. \lstinputlisting{cpp14faqs/code/c++14/variable_template_area.cpp} \end{Exercise} \begin{Answer}[ref=ex08]\index{lambda and variable template} \lstinputlisting{cpp14faqs/code/c++14/variable_template_simplify.cpp} \end{Answer} \section{variable templates variables vary} \begin{Exercise}[title={variable templates variables vary}, difficulty=2, label=ex09] \index{variable templates variables vary} Is this a legal code ? \lstinputlisting{cpp14faqs/code/c++14/variable_template1.cpp} If yes, what is the output ? \end{Exercise} \begin{Answer}[ref=ex09]\index{variable templates variables vary} Yes, the code is correct because variable template instances are first-class objects. Output is : \begin{verbatim} 42 0 \end{verbatim} \end{Answer} \section{auto variable templates} \begin{Exercise}[title={variable templates variables vary}, difficulty=2, label=ex010] \index{auto variable templates} Is this a legal code ? \lstinputlisting{cpp14faqs/code/c++14/auto_variable_templates.cpp} \end{Exercise} \begin{Answer}[ref=ex010]\index{auto variable templates} Yes, a specialization of a variable template is a variable and as per the standard : \emph{No diagnostic shall be issued for a template for which a valid specialization can be generated}. \end{Answer} \section{valid specialization but error ?} \begin{Exercise}[title={valid specialization but error}, difficulty=3, label=ex011] \index{valid specialization but error} Why this code doesn't compile ? \lstinputlisting{cpp14faqs/code/c++14/specialize.cpp} \end{Exercise} \begin{Answer}[ref=ex011]\index{valid specialization but error} Typical error is: \begin{verbatim} specialize.cpp:3:17: error: ‘typedef int Y::type’ is private typedef int type; ^ specialize.cpp:6:13: error: within this context template<Y::type N> ^ \end{verbatim} Because the template parameter declaration is ill-formed, it gets diagnosed immediately and does not form any larger structure. Hence there is no template to be specialized in the first place. There is no ``being ill-formed'', because ill-formedness implies the state of not being. So, if the parameter is nonsensical, then we don't have a template declaration. And if the template declaration itself is nonsensical, we don't have a declaration to specialize, hencde the compiler error is issued. \end{Answer} \section{variable templates and lambda revisited} \begin{Exercise}[title={variable templates and lambda revisited}, difficulty=3, label=ex012] \index{variable templates and lambda revisited} Exploit \emph{variable templates} and \emph{lambda} to compute the area of a circle class. \end{Exercise} \begin{Answer}[ref=ex012]\index{variable templates and lambda revisited} \lstinputlisting{cpp14faqs/code/c++14/variable_template_lambda.cpp} Alternatively: \begin{lstlisting} template<typename T> using f_type = T(*)(Circle<T>); template<typename T> f_type<T> area = []( Circle<T> c ) { return pi<T> * c.radius * c.radius; }; \end{lstlisting} \end{Answer} \section{Incremental improvement to integral\_constant} \begin{Exercise}[title={\small Incremental improvement to integral\_constant}, difficulty=3, label=ex013] \index{Incremental improvement to integral\_constant} Revisit the class template \emph{is\_arithmetic}: \begin{lstlisting} template <class T> struct is_arithmetic : integral_constant< bool, is_integral<T>::value || is_floating_point<T>::value > {}; \end{lstlisting} Before C++14, the typical usage of such a class template was: \begin{lstlisting} std::is_arithmetic<T>::value \end{lstlisting} or \begin{lstlisting} static_cast<bool>(std::is_arithmetic<T>{}) \end{lstlisting} What was the increment improvement to the class \emph{integral\_constant} to enable simplified usage like \begin{lstlisting} std::is_arithmetic<T>{}() \end{lstlisting} \end{Exercise} \begin{Answer}[ref=ex013]\index{Incremental improvement to integral\_constant} The following addition was made in order to allow the template to serve as a source of compile-time function objects: \begin{lstlisting} constexpr value_type operator()() { return value; } \end{lstlisting} So the final class looked like: \begin{lstlisting} template <class T, T v> struct integral_constant { static constexpr T value = v; using value_type = T; using type = integral_constant<T,v>; constexpr operator value_type() { return value; } constexpr value_type operator()() { return value; } // C++14 }; \end{lstlisting} \end{Answer} \section{is\_same musings} \begin{Exercise}[title={is\_same musing}, difficulty=2, label=ex014] \index{is\_same musings} Enumerate different ways to use $is\_same<T, U>$. \end{Exercise} \begin{Answer}[ref=ex014]\index{is\_same musing} \begin{enumerate} \item As a function object: \begin{lstlisting}[numbers=none] std::is_same<T, U>() \end{lstlisting} \item As a compile time evaluation by invoking the nested \emph{value\_type}: \begin{lstlisting}[numbers=none] std::is_same<T, U>::value \end{lstlisting} \item By having a template alias as follows: \begin{lstlisting}[numbers=none] template<typename T, typename U> using is_same_v = typename std::is_same<T, U>::value; \end{lstlisting} Now we can use it like \begin{lstlisting}[numbers=none] is_same_v<T, U>() \end{lstlisting} \item In C++11: \begin{lstlisting}[numbers=none] static_cast<bool>(std::is_same<T, U>{}) \end{lstlisting} \item Using variable template like: \begin{lstlisting}[numbers=none] template<typename T, typename U> constexpr bool is_same = false; template<typename T> constexpr bool is_same<T, T> = true; \end{lstlisting} It can be used like a variable: \begin{lstlisting}[numbers=none] is_same<T, U> \end{lstlisting} \end{enumerate} Note that in C++14, template aliases like the following are incorporated: \begin{lstlisting} template <class T, class U> using is_same_t = typename is_same<T, U>::type; \end{lstlisting} \end{Answer} \section{auto variable template and generic lambda} \begin{Exercise}[title={auto variable template and generic lambda}, difficulty=2, label=ex015] \index{auto variable template and generic lambda} Is this a valid code? \lstinputlisting{cpp14faqs/code/c++14/generic_lambda3.cpp} \end{Exercise} \begin{Answer}[ref=ex015]\index{auto variable template and generic lambda} Yes and it works as expected in C++14 and clang 3.5 trunk. \end{Answer} \section{constexpr member functions and implicit const} \begin{Exercise}[title={constexpr member functions and implicit const}, difficulty=3, label=ex016] \index{constexpr member functions and implicit const} Review the program : \lstinputlisting{cpp14faqs/code/c++14/constexpr_implicit_const.cpp} \end{Exercise} \begin{Answer}[ref=ex016]\index{constexpr member functions and implicit const} Compiler error looks like: \begin{verbatim} constexpr_implicit_const.cpp: In function ‘int main()’: constexpr_implicit_const.cpp:31:32: error: call to non-constexpr function ‘A& B::getA()’ constexpr int n = B().getA().getN(); ^ \end{verbatim} \emph{B().getA()} selects the non-constant overload version, leading to this error. After rendering the code as : \lstinputlisting{cpp14faqs/code/c++14/constexpr_implicit_const1.cpp} We get the following compiler error with C++11: clang++ -std=c++11 \begin{verbatim} constexpr_implicit_const1.cpp:19:18: warning: 'constexpr' non-static member function will not be implicitly 'const' in C++1y; add 'const' to avoid a change in behavior [-Wconstexpr-not-const] constexpr A &getA() ^ const constexpr_implicit_const1.cpp:19:18: error: functions that differ only in their return type cannot be overloaded constexpr_implicit_const1.cpp:15:24: note: previous declaration is here constexpr const A &getA() const ^ constexpr_implicit_const1.cpp:21:16: error: binding of reference to type 'A' to a value of type 'const A' drops qualifiers return a; ^ 1 warning and 2 errors generated. \end{verbatim} It points to a couple of issues including the restriction that \emph{constexpr member functions are implicitly const in C++11} which creates problems for literal class types which desire to be usable both within constant expressions and outside them. So in C++14, this rule is removed. So it works fine with C++14 compliant compiler like clang 3.5 trunk. \end{Answer} \section{constexpr constructor and initialization} \begin{Exercise}[title={constexpr constructor and initialization}, difficulty=2, label=ex017] \index{constexpr constructor and initialization} Review the program : \lstinputlisting{cpp14faqs/code/c++14/constexpr_constructor.cpp} \end{Exercise} \begin{Answer}[ref=ex017]\index{constexpr constructor and initialization} Compiler error with gcc 4.9 trunk is: \begin{verbatim} constexpr_constructor.cpp:11:28: in constexpr expansion of ‘A(0)’ constexpr_constructor.cpp:11:28: error: the value of ‘x’ is not usable in a constant expression constexpr int w = A(false).m; ^ constexpr_constructor.cpp:1:5: note: ‘int x’ is not const int x; ^ \end{verbatim} Compiler error with clang 3.5 trunk is: \begin{verbatim} constexpr_constructor.cpp:11:15: error: constexpr variable 'w' must be initialized by a constant expression constexpr int w = A(false).m; ^ ~~~~~~~~~~ constexpr_constructor.cpp:5:34: note: read of non-const variable 'x' is not allowed in a constant expression constexpr A(bool b) : m(b?42:x) { } ^ constexpr_constructor.cpp:11:19: note: in call to 'A(false)' constexpr int w = A(false).m; ^ constexpr_constructor.cpp:1:5: note: declared here int x; ^ 1 error generated. \end{verbatim} The first call to constructor is ok it initializes m with the value $42$ whereas the second call is in error because initializer for $m$ is $x$, which is non-constant. \end{Answer} \section{constexpr and branching} \begin{Exercise}[title={constexpr and branching}, difficulty=2, label=ex018] \index{constexpr and branching} Can we use if-then-else version of the following constexpr factorial program: \begin{lstlisting} constexpr unsigned long long fact( unsigned long long x ) { return x <= 1 ? 1ull : x * fact(x-1); } \end{lstlisting} \end{Exercise} \begin{Answer}[ref=ex018]\index{constexpr and branching} C++14 allowed constexpr to include branching, so we can rewrite as follows: \begin{lstlisting} constexpr auto fact( unsigned long long x ) { if( x <= 1 ) return 1ull; else return x * fact(x-1); } \end{lstlisting} \end{Answer} \section{constexpr and looping iteration} \begin{Exercise}[title={constexpr and looping iteration}, difficulty=2, label=ex019] \index{constexpr and looping iteration} Can we use if-then-else version of the following constexpr factorial program: \begin{lstlisting} constexpr unsigned long long fact( unsigned long long x ) { return x <= 1 ? 1ull : x * fact(x-1); } \end{lstlisting} \end{Exercise} \begin{Answer}[ref=ex019]\index{constexpr and looping iteration} C++14 allowed constexpr to support loop constructs, so we can rewrite the factorial program in its iterative version as follows: \begin{lstlisting} constexpr auto fact( unsigned long long x ) { auto product = x; while( --x ) product *= x; return product; } \end{lstlisting} C++11 requirement that constexprs be single return statements worked well enough, but simple functions that required more than one line could not be constexpr. It sometimes forced inefficient implementations in order to have at least some of its results generated at compile-time, but not always all. So this limitation was removed in C++14. Note that this version may be more efficient, both at compile time and run time. \end{Answer} \section{constexpr and mutation} \begin{Exercise}[title={constexpr and mutation}, difficulty=2, label=ex020] \index{constexpr and initialization} Review the program: \lstinputlisting{cpp14faqs/code/c++14/constexpr_init.cpp} \end{Exercise} \begin{Answer}[ref=ex020]\index{constexpr and mutation} It results into compiler error like: \begin{verbatim} constexpr_init.cpp:3:19: error: constexpr variable 'x' must be initialized by a constant expression constexpr int x = k; ^ ~ constexpr_init.cpp:3:23: note: read of non-const variable 'k' is not allowed in a constant expression constexpr int x = k; ^ constexpr_init.cpp:1:21: note: declared here constexpr int f(int k) ^ 1 error generated. \end{verbatim} The reason is : $x$ is not initialized by a constant expression because lifetime of $k$ began outside the initializer of $x$. So the line \begin{lstlisting}[numbers=none] constexpr int x = k; \end{lstlisting} should be replaced by: \begin{lstlisting}[numbers=none] int x = k; \end{lstlisting} To understand it better, let us review the following program: \begin{lstlisting} constexpr int incr(int &n) { return ++n; } constexpr int g(int k) { constexpr int x = incr(k); return x; } \end{lstlisting} Here also, $incr(k)$ is not a core constant expression because lifetime of $k$ began outside the expression $incr(k)$, so the culprit line responsible for compiler error is: \begin{lstlisting} constexpr int x = incr(k); \end{lstlisting} Note that the following program is valid: \begin{lstlisting} constexpr int h(int k) { int x = incr(k); return x; } constexpr int y = h(1); \end{lstlisting} Because $h(1)$ is a core constant expression because the lifetime of $k$ begins inside $h(1)$. It initializes $y$ with the value $2$. To summarize, C++14 allows \emph{mutation of objects whose lifetime began within the constant expression evaluation}. \end{Answer} \section{constexpr vs static vs uninitialized} \begin{Exercise}[title={constexpr vs static vs uninitialized}, difficulty=2, label=ex021] \index{constexpr vs static vs uninitialized} Review the program: \lstinputlisting{cpp14faqs/code/c++14/constexpr_static.cpp} \end{Exercise} \begin{Answer}[ref=ex021]\index{constexpr vs static vs uninitialized} It does not compile. Typical error is, which is self-explanatory: \begin{verbatim} constexpr_static.cpp:3:16: error: static variable not permitted in a constexpr function static int value = n; ^ constexpr_static.cpp:9:9: error: variables defined in a constexpr function must be initialized int a; ^ 2 errors generated. \end{verbatim} \end{Answer} \section{constexpr vs member function revisited} \begin{Exercise}[title={constexpr vs member function revisited}, difficulty=2, label=ex022] \index{constexpr vs member function revisited} Is this code valid in C++14 ? \lstinputlisting{cpp14faqs/code/c++14/constexpr_memfn.cpp} \end{Exercise} \begin{Answer}[ref=ex022]\index{constexpr vs member function revisited} It was valid in C++11, but no more valid in C++14 because \emph{constexpr} non-static member functions are not implicitly const member functions anymore. Rationale behind this change was \emph{to allow constexpr member functions to mutate the object}. So the error is because it declares the same member function twice with different return types. Typical error is, which is self-explanatory: \begin{verbatim} constexpr_memfn.cpp:4:10: error: functions that differ only in their return type cannot be overloaded int &f(); ^ constexpr_memfn.cpp:3:26: note: previous declaration is here constexpr const int &f(); ^ 1 error generated. \end{verbatim} \end{Answer} \section{deprecated attribute} \begin{Exercise}[title={deprecated attribute}, difficulty=2, label=ex023] \index{deprecated attribute} Describe a mechanism to mark the usage of the class $A$ and the function $func1$ deprecated. \begin{lstlisting} class A1 {}; void func1() {} int main() { A1 a; func1(); } \end{lstlisting} \end{Exercise} \begin{Answer}[ref=ex023]\index{deprecated attribute} C++14 introduced an attribute \emph{[[deprecated]]} to do the needful. So we can rewrite the above code as: \lstinputlisting{cpp14faqs/code/c++14/deprecated_attribute.cpp} Compiler diagnostic messages with clang 3.5 trunk : \begin{verbatim} deprecated_attribute.cpp:8:5: warning: 'A1' is deprecated [-Wdeprecated-declarations] A1 a; ^ deprecated_attribute.cpp:1:22: note: 'A1' has been explicitly marked deprecated here class [[deprecated]] A1 {}; ^ deprecated_attribute.cpp:9:5: warning: 'func1' is deprecated [-Wdeprecated-declarations] func1(); ^ deprecated_attribute.cpp:4:6: note: 'func1' has been explicitly marked deprecated here void func1() {} ^ 2 warnings generated. \end{verbatim} With gcc 4.9 trunk: \begin{verbatim} deprecated_attribute.cpp: In function ‘int main()’: deprecated_attribute.cpp:8:8: warning: ‘A1’ is deprecated (declared at deprecated_attribute.cpp:1) [-Wdeprecated-declarations] A1 a; ^ deprecated_attribute.cpp:9:5: warning: ‘void func1()’ is deprecated (declared at deprecated_attribute.cpp:4) [-Wdeprecated-declarations] func1(); ^ deprecated_attribute.cpp:9:11: warning: ‘void func1()’ is deprecated (declared at deprecated_attribute.cpp:4) [-Wdeprecated-declarations] func1(); ^ \end{verbatim} The diagnostic message can be customized by passing a literal string as an argument to \emph{[[deprecated]]} like: \lstinputlisting{cpp14faqs/code/c++14/deprecated_attribute_msg.cpp} gcc 4.9 trunk yields now: \begin{verbatim} deprecated_attribute_msg.cpp: In function ‘int main()’: deprecated_attribute_msg.cpp:8:8: warning: ‘A1’ is deprecated (declared at deprecated_attribute_msg.cpp:1): Usage of class A is deprecated. Please class X instead. [-Wdeprecated-declarations] A1 a; ^ deprecated_attribute_msg.cpp:9:5: warning: ‘void func1()’ is deprecated (declared at deprecated_attribute_msg.cpp:4): Usage of func1 is deprecated. Please use func2 instead. [-Wdeprecated-declarations] func1(); ^ deprecated_attribute_msg.cpp:9:11: warning: ‘void func1()’ is deprecated (declared at deprecated_attribute_msg.cpp:4): Usage of func1 is deprecated. Please use func2 instead. [-Wdeprecated-declarations] func1(); ^ \end{verbatim} The attribute-token \emph{deprecated} can be used to mark names and entities whose use is still allowed, but is discouraged for some reason. The attribute may be applied to the declaration of \begin{itemize} \item a class, \item a typedef-name, \item a variable, \item a non-static data member, \item a function, \item an enumeration, or \item a template specialization. \end{itemize} A name or entity declared without the \emph{deprecated} attribute can later be redeclared with the attribute and vice-versa. \begin{lstlisting} class A; class [[deprecated]] A; class A{}; int main() { A a; } \end{lstlisting} Compiler issues proper diagnostic. Thus, an entity initially declared without the attribute can be marked as deprecated by a subsequent redeclaration. However, after an entity is marked as deprecated, later redeclarations do not un-deprecate the entity. So for the code below, compiler still issues the relevant diagnostics: \begin{lstlisting} class [[deprecated]] A; class A; class A{}; int main() { A a; } \end{lstlisting} Redeclarations using different forms of the attribute, with or without the attribute-argument-clause or with different attribute-argument-clauses) are allowed. \lstinputlisting{cpp14faqs/code/c++14/deprecated_redeclare.cpp} Compiler issues diagnostic message for the last one : \begin{verbatim} deprecated_redeclare.cpp:9:5: warning: 'A' is deprecated: A is dangerous. [-Wdeprecated-declarations] A a; ^ deprecated_redeclare.cpp:5:7: note: 'A' has been explicitly marked deprecated here class A{}; ^ 1 warning generated. \end{verbatim} \end{Answer}
/- Copyright (c) 2023 Devon Tuma. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Devon Tuma -/ import computational_monads.distribution_semantics.defs.independence /-! # Distributional Equivalence Between Oracle Computations This file defines a notion of distributional equivalence between computations. `dist_equiv oa oa'` (or `oa ≃ₚ oa`) represents two computations for which all values have the same probability under the denotational semantics provided by `eval_dist`. Such an equivalence implies equality of `support`, `fin_support`, `eval_dist`, and `prob_event`. This is especially usefull when it's necessary to avoid "leaving" computations, as regular probability lemmas will move into the realm of `pmf`, which is sometimes not preferable. As an example, distribution-wise we have that `⁅g <$> f <$> oa⁆ = ⁅oa⁆.map (g ∘ f)`, while the equivalence would give `g <$> f <$> oa ≃ₚ (g ∘ f) <$> oa`. While the former is more specific, it can cause problems when other parts of the proof rely on using induction on the computation, as this doesn't translate well into `pmf`. Additionally using the former to talk about e.g. `support` requires additional rewrites to get the necessary equivalences in terms of sets and not computations. Note that distributional equivalence is not preserved under simulation via `oracle_comp.simulate`, as computations with the same distribution may make different oracle calls that are simulated differently, in term giving computations that behave differently. TODO: It should be possible to write a tactic similar to `rw` that works for this relation. As of now, situations requiring `rw` behavior will usually have to apply `dist_equiv.ext` first. -/ namespace oracle_comp open oracle_spec open_locale big_operators ennreal variables {α β γ : Type} {spec spec' spec'' : oracle_spec} /-- Equivalence between computations in terms of the associated probability distribution. Note that the behavior of equivalent computations may still differ in their oracle queries, and so this equivalence is not in general preserved under `oracle_comp.simulate`. -/ def dist_equiv (oa : oracle_comp spec α) (oa' : oracle_comp spec' α) : Prop := ⁅oa⁆ = ⁅oa'⁆ variables {oa : oracle_comp spec α} {oa' : oracle_comp spec' α} {oa'' : oracle_comp spec'' α} infix ` ≃ₚ ` : 50 := dist_equiv lemma dist_equiv.def : oa ≃ₚ oa' ↔ ⁅oa⁆ = ⁅oa'⁆ := iff.rfl /-- Show that two computations are equivalent by showing every output has the same probability. -/ lemma dist_equiv.ext (h : ∀ x, ⁅= x | oa⁆ = ⁅= x | oa'⁆) : oa ≃ₚ oa' := pmf.ext h lemma dist_equiv.ext_iff (oa : oracle_comp spec α) (oa' : oracle_comp spec' α) : oa ≃ₚ oa' ↔ ∀ x, ⁅= x | oa⁆ = ⁅= x | oa'⁆ := ⟨λ h x, congr_fun (congr_arg _ h) x, dist_equiv.ext⟩ @[refl] instance dist_equiv.is_refl : is_refl (oracle_comp spec α) dist_equiv := ⟨λ x, rfl⟩ /-- More general than regular `symm`, the two computations may have different `oracle_spec`. -/ lemma dist_equiv.symm (h : oa ≃ₚ oa') : oa' ≃ₚ oa := h.symm instance dist_equiv.is_symm : is_symm (oracle_comp spec α) dist_equiv := ⟨λ oa oa' h, h.symm⟩ /-- More general than regular `trans`, the three computations may have different `oracle_spec`. -/ @[trans] lemma dist_equiv.trans (h : oa ≃ₚ oa') (h' : oa' ≃ₚ oa'') : oa ≃ₚ oa'' := h.trans h' instance dist_equiv.is_trans : is_trans (oracle_comp spec α) dist_equiv := ⟨λ oa oa' oa'' h h', h.trans h'⟩ lemma dist_equiv.support_eq (h : oa ≃ₚ oa') : oa.support = oa'.support := (oa.support_eval_dist).symm.trans ((congr_arg pmf.support h).trans oa'.support_eval_dist) lemma dist_equiv.fin_support_eq [oa.decidable] [oa'.decidable] (h : oa ≃ₚ oa') : oa.fin_support = oa'.fin_support := (fin_support_eq_fin_support_iff_support_eq_support oa oa').2 h.support_eq lemma dist_equiv.eval_dist_eq (h : oa ≃ₚ oa') : ⁅oa⁆ = ⁅oa'⁆ := h lemma dist_equiv.eval_dist_apply_eq (h : oa ≃ₚ oa') (x : α) : ⁅= x | oa⁆ = ⁅= x | oa'⁆ := congr_fun (congr_arg _ h) x lemma dist_equiv.prob_event_eq (h : oa ≃ₚ oa') (e : set α) : ⁅e | oa⁆ = ⁅e | oa'⁆ := prob_event_eq_of_eval_dist_eq h.eval_dist_eq e lemma dist_equiv.indep_events_iff (h : oa ≃ₚ oa') (es es' : set (set α)) : oa.indep_events es es' ↔ oa'.indep_events es es' := indep_events_iff_of_eval_dist_eq oa oa' es es' h lemma dist_equiv.indep_event_iff (h : oa ≃ₚ oa') (e e' : set α) : oa.indep_event e e' ↔ oa'.indep_event e e' := indep_event_iff_of_eval_dist_eq oa oa' e e' h end oracle_comp
From Equations Require Import Equations. Section sum. Variable (L R : Set) (L_eqdec : EqDec L) (R_eqdec : EqDec R). Inductive sum : Type := | inl : L -> sum| inr : R -> sum. Equations Derive NoConfusion EqDec for sum. End sum. Succeed Check sum_eqdec.
If $F_1$ is a filter that is finer than $F_2$, and $f$ is a function that is $F_2$-limit of $g$, then $f$ is also an $F_1$-limit of $g$.
############################################################ # R script 2 of: Birds exposed to physiological stress # # post-breeding engage in stress-reducing social # # interactions in winter flocks # # Running the main analysis and making the figures 3, 4, 5 # # author: Lionel Hertzog # ############################################################ # set wd to the local position of the github repo setwd("~/PostDoc_Ghent/Feeder_stuff/network_stress/") # load packages library(tidyverse) library(gridExtra) # load data network_dat <- read.csv("data/network_dat.csv") # 1. Fit the centrality ~ cort_orig models ## some data points were dropped to ensure that ## model assumptions were met m_1 <- lm(betw ~ cort_orig + sex + age + barl_orig, network_dat[-c(153),]) # males have higher betw slight effect of cort m_2 <- lm(degree ~ cort_orig + sex + age + barl_orig, network_dat[-c(153),]) # effect of cort m_3 <- lm(eigen ~ cort_orig + sex + age + barl_orig, network_dat[-c(153),]) # trend for positive effect of cort on centrality m_4 <- lm(strength ~ cort_orig + sex + age + barl_orig, network_dat[-c(153),]) # effect of cort ## save these models m_orig <- list(betw = m_1, degree = m_2, eigen = m_3, strength = m_4) saveRDS(m_orig, "models/m_orig.rds") ## make the figure ### the data frame to derive the prediction from newdat <- expand.grid(cort_orig = seq(0,0.15,length=10), sex = "f", age = "1Y",barl_orig = 14.26) ### betweenness newdat$betw <- predict(m_1, newdata = newdat, se.fit = TRUE)$fit + mean(c(0,coef(m_1)[3])) + mean(c(0,coef(m_1)[4])) # remove sex and age effect newdat$se_betw <- predict(m_1, newdata = newdat, se.fit = TRUE)$se.fit ### degree newdat$degree <- predict(m_2, newdata = newdat, se.fit = TRUE)$fit + mean(c(0,coef(m_2)[3])) + mean(c(0,coef(m_2)[4])) # remove sex and age effect newdat$se_degree <- predict(m_2, newdata = newdat, se.fit = TRUE)$se.fit ### eigenvector newdat$eigen <- predict(m_3, newdata = newdat, se.fit = TRUE)$fit + mean(c(0,coef(m_3)[3])) + mean(c(0,coef(m_3)[4])) # remove sex and age effect newdat$se_eigen <- predict(m_3, newdata = newdat, se.fit = TRUE)$se.fit ### strength newdat$strength <- predict(m_4, newdata = newdat, se.fit = TRUE)$fit + mean(c(0,coef(m_4)[3])) + mean(c(0,coef(m_4)[4])) # remove sex and age effect newdat$se_strength <- predict(m_4, newdata = newdat, se.fit = TRUE)$se.fit ### the theme for all plots theme_gg <- theme(panel.background = element_blank(), axis.line = element_line()) ### the plots gg_betw <- ggplot(newdat, aes(x=cort_orig,y=betw)) + geom_line() + geom_ribbon(alpha = 0.1,aes(ymin=betw - 1.96*se_betw, ymax = betw + 1.96*se_betw)) + geom_point(data=network_dat[-153,]) + labs(x="", y="Betweenness centrality") + theme_gg gg_degree <- ggplot(newdat, aes(x=cort_orig,y=degree)) + geom_line() + geom_ribbon(alpha = 0.1,aes(ymin=degree - 1.96*se_degree, ymax = degree + 1.96*se_degree)) + geom_point(data=network_dat[-153,]) + labs(x="", y="Degree") + theme_gg gg_eigen <- ggplot(newdat, aes(x=cort_orig,y=eigen)) + geom_line() + geom_ribbon(alpha = 0.1,aes(ymin=eigen - 1.96*se_eigen, ymax = eigen + 1.96*se_eigen)) + geom_point(data=network_dat[-153,]) + labs(x="", y="Eigenvector centrality") + theme_gg gg_strength <- ggplot(newdat, aes(x=cort_orig,y=strength)) + geom_line() + geom_ribbon(alpha = 0.1,aes(ymin=strength - 1.96*se_strength, ymax = strength + 1.96*se_strength)) + geom_point(data=network_dat[-153,]) + labs(x="", y="Strength") + theme_gg ### put this all together gg_orig <- grid.arrange(gg_eigen,gg_betw,gg_degree,gg_strength,bottom="Original feather CORT (\U003BCg)") ggsave("figures/fig_03.png",gg_orig) # 1.2 Fit the centrality ~ cort_orig models without the pullis # some individuals were dropped to meet model requirements m_1 <- lm(betw ~ cort_orig + sex + barl_orig, network_dat[-153,], subset = age == "AD") # males have higher betw slight effect of cort m_2 <- lm(degree ~ cort_orig + sex + barl_orig, network_dat[-153,], subset = age == "AD") # effect of cort m_3 <- lm(eigen ~ cort_orig + sex + barl_orig, network_dat[-c(153),], subset = age == "AD") # trend for positive effect of cort on centrality m_4 <- lm(strength ~ cort_orig + sex + barl_orig, network_dat[-c(153),], subset = age == "AD") # effect of cort ## save these models m_orig_ad <- list(betw = m_1, degree = m_2, eigen = m_3, strength = m_4) saveRDS(m_orig_ad, "models/m_orig_ad.rds") # 1.3 Fit the centrality ~ cort_orig models with feeder visits m_1 <- lm(betw ~ cort_orig + sex + age + barl_orig + feeding_freq, network_dat[-153,]) # males have higher betw slight effect of cort m_2 <- lm(degree ~ cort_orig + sex + age + barl_orig + feeding_freq, network_dat[-153,]) # effect of cort m_3 <- lm(eigen ~ cort_orig + sex + age + barl_orig + feeding_freq, network_dat[-c(153),]) # trend for positive effect of cort on centrality m_4 <- lm(strength ~ cort_orig + sex + age + barl_orig + feeding_freq, network_dat[-c(153),]) # effect of cort m_orig_feeding <- list(betw = m_1, degree = m_2, eigen = m_3, strength = m_4) saveRDS(m_orig_feeding, "models/m_orig_feeding.rds") # 2. Fit the cort_induced ~ centrality models ## some data points were dropped to ensure that ## model assumptions were met m_5 <- glm(cort_ind + 0.0001 ~ betw + sex + age + barl_ind, network_dat[-272,], family = Gamma(link="log")) m_6 <- glm(cort_ind + 0.0001 ~ degree + sex + age + barl_ind, network_dat[-272,], family = Gamma(link="log")) m_7 <- glm(cort_ind + 0.0001 ~ eigen + sex + age + barl_ind, network_dat[-c(25,272),], family = Gamma(link="log")) m_8 <- glm(cort_ind + 0.0001 ~ strength + sex + age + barl_ind, network_dat[-272,], family = Gamma(link="log")) ## save the models m_ind <- list(betw = m_5, degree = m_6, eigen = m_7, strength = m_8) saveRDS(m_ind, "models/m_ind.rds") ## plot the predicted responses ### betw newdat <- expand.grid(betw = seq(0,8.6,length=10), sex = "f", age = "AD",barl_ind = 11.55) newdat$cort_ind <- predict(m_ind$betw, newdata = newdat, se.fit = TRUE)$fit + mean(c(0,coef(m_ind$betw)[3])) + mean(c(0,coef(m_ind$betw)[4])) newdat$se <- predict(m_ind$betw, newdata = newdat, se.fit = TRUE)$se.fit newdat$LCI <- exp(newdat$cort_ind - 1.96 * newdat$se) newdat$UCI <- exp(newdat$cort_ind + 1.96 * newdat$se) newdat$cort_ind <- exp(newdat$cort_ind) gg_betw <- ggplot(newdat, aes(x=betw,y=cort_ind)) + geom_line() + geom_ribbon(alpha = 0.1,aes(ymin=LCI, ymax = UCI)) + geom_point(data=network_dat[-272,]) + labs(x="Betwenness centrality", y="Induced feather CORT (\U003BCg)") + ylim(c(0,2)) + theme_gg ### degree newdat <- expand.grid(degree = seq(42,139,length=10), sex = "f", age = "AD",barl_ind = 11.55) newdat$cort_ind <- predict(m_ind$degree, newdata = newdat, se.fit = TRUE)$fit + mean(c(0,coef(m_ind$degree)[3])) + mean(c(0,coef(m_ind$degree)[4])) newdat$se <- predict(m_ind$degree, newdata = newdat, se.fit = TRUE)$se.fit newdat$LCI <- exp(newdat$cort_ind - 1.96 * newdat$se) newdat$UCI <- exp(newdat$cort_ind + 1.96 * newdat$se) newdat$cort_ind <- exp(newdat$cort_ind) gg_degree <- ggplot(newdat, aes(x=degree,y=cort_ind)) + geom_line() + geom_ribbon(alpha = 0.1,aes(ymin=LCI, ymax = UCI)) + geom_point(data=network_dat[-272,]) + labs(x="Degree", y="Induced feather CORT (\U003BCg)") + xlim(c(40,140)) + ylim(c(0,2)) + theme_gg ### eigenvector newdat <- expand.grid(eigen = seq(0,1,length=10), sex = "f", age = "AD",barl_ind = 11.55) newdat$cort_ind <- predict(m_ind$eigen, newdata = newdat, se.fit = TRUE)$fit + mean(c(0,coef(m_ind$eigen)[3])) + mean(c(0,coef(m_ind$eigen)[4])) newdat$se <- predict(m_ind$eigen, newdata = newdat, se.fit = TRUE)$se.fit newdat$LCI <- exp(newdat$cort_ind - 1.96 * newdat$se) newdat$UCI <- exp(newdat$cort_ind + 1.96 * newdat$se) newdat$cort_ind <- exp(newdat$cort_ind) gg_eigen <- ggplot(newdat, aes(x=eigen,y=cort_ind)) + geom_line() + geom_ribbon(alpha = 0.1,aes(ymin=LCI, ymax = UCI)) + geom_point(data=network_dat[-c(25,272,279),]) + labs(x="Eigenvector centrality", y="Induced feather CORT (\U003BCg)") + ylim(c(0,2)) + theme_gg ### strength newdat <- expand.grid(strength = seq(0,19,length=10), sex = "f", age = "AD",barl_ind = 11.55) newdat$cort_ind <- predict(m_ind$strength, newdata = newdat, se.fit = TRUE)$fit + mean(c(0,coef(m_ind$strength)[3])) + mean(c(0,coef(m_ind$strength)[4])) newdat$se <- predict(m_ind$strength, newdata = newdat, se.fit = TRUE)$se.fit newdat$LCI <- exp(newdat$cort_ind - 1.96 * newdat$se) newdat$UCI <- exp(newdat$cort_ind + 1.96 * newdat$se) newdat$cort_ind <- exp(newdat$cort_ind) gg_strength <- ggplot(newdat, aes(x=strength,y=cort_ind)) + geom_line() + geom_ribbon(alpha = 0.1,aes(ymin=LCI, ymax = UCI)) + geom_point(data=network_dat[-c(272),]) + labs(x="Strength", y="Induced feather CORT (\U003BCg)") + ylim(c(0,2)) + theme_gg gg_ind <- grid.arrange(gg_eigen,gg_betw,gg_degree,gg_strength) ggsave("figures/fig_04.png",gg_ind) # 3. Fit the feeding frequency ~ network centrality models m_9 <- lm(feeding_freq ~ betw + sex + age, network_dat) m_10 <- lm(feeding_freq ~ degree + sex + age, network_dat) m_11 <- lm(feeding_freq ~ eigen + sex + age, network_dat) m_12 <- lm(feeding_freq ~ strength + sex + age, network_dat) ## save these models m_feed <- list(betw = m_9, degree = m_10, eigen = m_11, strength = m_12) saveRDS(m_feed, "models/m_feed.rds") ## plot (also with prediction interval) ### betwenness newdat <- data.frame(betw = seq(min(network_dat$betw,na.rm=TRUE),max(network_dat$betw,na.rm=TRUE),length.out = 10), age = "1Y", sex = "f") pred <- predict(m_9,newdat,interval = "confidence") newdat <- cbind(newdat, pred) names(newdat)[4] <- "feeding_freq" pred_2 <- predict(m_9,newdat,interval="prediction") colnames(pred_2)[2:3] <- c("P_lwr","P_upr") newdat <- cbind(newdat, pred_2[,2:3]) cst <- mean(c(0,coef(m_9)[3])) + mean(c(0,coef(m_9)[4])) # constant to average out sex and age effects newdat[,4:8] <- newdat[,4:8] + cst gg_betw <- ggplot(network_dat,aes(x=betw,y=feeding_freq)) + geom_point() + geom_ribbon(data=newdat,aes(ymin=P_lwr,ymax=P_upr),color=NA,alpha=0.08) + # prediction interval geom_ribbon(data=newdat,aes(ymin=lwr,ymax=upr),color=NA,alpha=0.2) + # confidence interval geom_line(data=newdat) + labs(x="Betweenness centrality", y = "Feeder visits") + theme_gg ### eigenvector newdat <- data.frame(eigen = seq(min(network_dat$eigen,na.rm=TRUE),max(network_dat$eigen,na.rm=TRUE),length.out = 10), age = "1Y", sex = "f") pred <- predict(m_11,newdat,interval = "confidence") newdat <- cbind(newdat, pred) names(newdat)[4] <- "feeding_freq" pred_2 <- predict(m_11,newdat,interval="prediction") colnames(pred_2)[2:3] <- c("P_lwr","P_upr") newdat <- cbind(newdat, pred_2[,2:3]) cst <- mean(c(0,coef(m_11)[3])) + mean(c(0,coef(m_11)[4])) # constant to average out sex and age effects newdat[,4:8] <- newdat[,4:8] + cst gg_eigen <- ggplot(network_dat,aes(x=eigen,y=feeding_freq)) + geom_point() + geom_ribbon(data=newdat,aes(ymin=P_lwr,ymax=P_upr),color=NA,alpha=0.08) + # prediction interval geom_ribbon(data=newdat,aes(ymin=lwr,ymax=upr),color=NA,alpha=0.2) + # confidence interval geom_line(data=newdat) + labs(x="Eigenvector centrality", y = "Feeder visits") + theme_gg ### degree newdat <- data.frame(degree = seq(min(network_dat$degree,na.rm=TRUE),max(network_dat$degree,na.rm=TRUE),length.out = 10), age = "1Y", sex = "f") pred <- predict(m_10,newdat,interval = "confidence") newdat <- cbind(newdat, pred) names(newdat)[4] <- "feeding_freq" pred_2 <- predict(m_10,newdat,interval="prediction") colnames(pred_2)[2:3] <- c("P_lwr","P_upr") newdat <- cbind(newdat, pred_2[,2:3]) cst <- mean(c(0,coef(m_10)[3])) + mean(c(0,coef(m_10)[4])) # constant to average out sex and age effects newdat[,4:8] <- newdat[,4:8] + cst gg_degree <- ggplot(network_dat,aes(x=degree,y=feeding_freq)) + geom_point() + geom_ribbon(data=newdat,aes(ymin=P_lwr,ymax=P_upr),color=NA,alpha=0.08) + # prediction interval geom_ribbon(data=newdat,aes(ymin=lwr,ymax=upr),color=NA,alpha=0.2) + # confidence interval geom_line(data=newdat) + labs(x="Degree", y = "Feeder visits") + theme_gg ### strength newdat <- data.frame(strength = seq(min(network_dat$strength,na.rm=TRUE),max(network_dat$strength,na.rm=TRUE),length.out = 10), age = "1Y", sex = "f") pred <- predict(m_12,newdat,interval = "confidence") newdat <- cbind(newdat, pred) names(newdat)[4] <- "feeding_freq" pred_2 <- predict(m_12,newdat,interval="prediction") colnames(pred_2)[2:3] <- c("P_lwr","P_upr") newdat <- cbind(newdat, pred_2[,2:3]) cst <- mean(c(0,coef(m_12)[3])) + mean(c(0,coef(m_12)[4])) # constant to average out sex and age effects newdat[,4:8] <- newdat[,4:8] + cst gg_strength <- ggplot(network_dat,aes(x=strength,y=feeding_freq)) + geom_point() + geom_ribbon(data=newdat,aes(ymin=P_lwr,ymax=P_upr),color=NA,alpha=0.08) + # prediction interval geom_ribbon(data=newdat,aes(ymin=lwr,ymax=upr),color=NA,alpha=0.2) + # confidence interval geom_line(data=newdat) + labs(x="Strength", y = "Feeder visits") + theme_gg ### put together and save the figure gg_feed <- grid.arrange(gg_eigen,gg_betw,gg_degree,gg_strength) ggsave("figures/fig_05.png",gg_feed) # 4. fit the cort_induced ~ feeding frequency model m_13 <- glm(cort_ind + 0.0001 ~ feeding_freq + barl_ind + sex + age, network_dat,family = Gamma(link="log"), subset = cort_ind < 10) # no detectable effect m_14 <- lm(feeding_freq ~ cort_orig + barl_orig + sex +age, network_dat[-c(153, 258),])
[STATEMENT] lemma const_Int_Field[simp]: "Field s \<inter> - {x. const x = r.zero} = {}" [PROOF STATE] proof (prove) goal (1 subgoal): 1. Field s \<inter> - {x. const x = r.zero} = {} [PROOF STEP] by auto
{-# OPTIONS --allow-unsolved-metas #-} module regex1 where open import Level renaming ( suc to succ ; zero to Zero ) open import Data.Fin open import Data.Nat hiding ( _≟_ ) open import Data.List hiding ( any ; [_] ) -- import Data.Bool using ( Bool ; true ; false ; _∧_ ) -- open import Data.Bool using ( Bool ; true ; false ; _∧_ ; _∨_ ) open import Relation.Binary.PropositionalEquality as RBF hiding ( [_] ) open import Relation.Nullary using (¬_; Dec; yes; no) open import regex open import logic -- postulate a b c d : Set data In : Set where a : In b : In c : In d : In -- infixr 40 _&_ _||_ r1' = (< a > & < b >) & < c > --- abc r1 = < a > & < b > & < c > --- abc r0 : ¬ (r1' ≡ r1) r0 () any = < a > || < b > || < c > || < d > --- a|b|c|d r2 = ( any * ) & ( < a > & < b > & < c > ) -- .*abc r3 = ( any * ) & ( < a > & < b > & < c > & < a > & < b > & < c > ) r4 = ( < a > & < b > & < c > ) || ( < b > & < c > & < d > ) r5 = ( any * ) & ( < a > & < b > & < c > || < b > & < c > & < d > ) open import nfa -- former ++ later ≡ x split : {Σ : Set} → ((former : List Σ) → Bool) → ((later : List Σ) → Bool) → (x : List Σ ) → Bool split x y [] = x [] /\ y [] split x y (h ∷ t) = (x [] /\ y (h ∷ t)) \/ split (λ t1 → x ( h ∷ t1 )) (λ t2 → y t2 ) t -- tt1 : {Σ : Set} → ( P Q : List In → Bool ) → split P Q ( a ∷ b ∷ c ∷ [] ) -- tt1 P Q = ? {-# TERMINATING #-} repeat : {Σ : Set} → (List Σ → Bool) → List Σ → Bool repeat x [] = true repeat {Σ} x ( h ∷ t ) = split x (repeat {Σ} x) ( h ∷ t ) -- Meaning of regular expression regular-language : {Σ : Set} → Regex Σ → ((x y : Σ ) → Dec (x ≡ y)) → List Σ → Bool regular-language φ cmp _ = false regular-language ε cmp [] = true regular-language ε cmp (_ ∷ _) = false regular-language (x *) cmp = repeat ( regular-language x cmp ) regular-language (x & y) cmp = split ( λ z → regular-language x cmp z ) (λ z → regular-language y cmp z ) regular-language (x || y) cmp = λ s → ( regular-language x cmp s ) \/ ( regular-language y cmp s) regular-language < h > cmp [] = false regular-language < h > cmp (h1 ∷ [] ) with cmp h h1 ... | yes _ = true ... | no _ = false regular-language < h > _ (_ ∷ _ ∷ _) = false cmpi : (x y : In ) → Dec (x ≡ y) cmpi a a = yes refl cmpi b b = yes refl cmpi c c = yes refl cmpi d d = yes refl cmpi a b = no (λ ()) cmpi a c = no (λ ()) cmpi a d = no (λ ()) cmpi b a = no (λ ()) cmpi b c = no (λ ()) cmpi b d = no (λ ()) cmpi c a = no (λ ()) cmpi c b = no (λ ()) cmpi c d = no (λ ()) cmpi d a = no (λ ()) cmpi d b = no (λ ()) cmpi d c = no (λ ()) test-regex : regular-language r1' cmpi ( a ∷ [] ) ≡ false test-regex = refl test-regex1 : regular-language r2 cmpi ( a ∷ a ∷ b ∷ c ∷ [] ) ≡ true test-regex1 = refl test-AB→split : {Σ : Set} → {A B : List In → Bool} → split A B ( a ∷ b ∷ a ∷ [] ) ≡ ( ( A [] /\ B ( a ∷ b ∷ a ∷ [] ) ) \/ ( A ( a ∷ [] ) /\ B ( b ∷ a ∷ [] ) ) \/ ( A ( a ∷ b ∷ [] ) /\ B ( a ∷ [] ) ) \/ ( A ( a ∷ b ∷ a ∷ [] ) /\ B [] ) ) test-AB→split {_} {A} {B} = refl list-eq : {Σ : Set} → (cmpi : (s t : Σ) → Dec (s ≡ t )) → (s t : List Σ ) → Bool list-eq cmpi [] [] = true list-eq cmpi [] (x ∷ t) = false list-eq cmpi (x ∷ s) [] = false list-eq cmpi (x ∷ s) (y ∷ t) with cmpi x y ... | yes _ = list-eq cmpi s t ... | no _ = false -- split-spec-01 : {s t u : List In } → s ++ t ≡ u → split (list-eq cmpi s) (list-eq cmpi t) u ≡ true -- split-spec-01 = {!!} -- from example 1.53 1 ex53-1 : Set ex53-1 = (s : List In ) → regular-language ( (< a > *) & < b > & (< a > *) ) cmpi s ≡ true → {!!} -- contains exact one b ex53-2 : Set ex53-2 = (s : List In ) → regular-language ( (any * ) & < b > & (any *) ) cmpi s ≡ true → {!!} -- contains at lease one b evenp : {Σ : Set} → List Σ → Bool oddp : {Σ : Set} → List Σ → Bool oddp [] = false oddp (_ ∷ t) = evenp t evenp [] = true evenp (_ ∷ t) = oddp t -- from example 1.53 5 egex-even : Set egex-even = (s : List In ) → regular-language ( ( any & any ) * ) cmpi s ≡ true → evenp s ≡ true test11 = regular-language ( ( any & any ) * ) cmpi (a ∷ []) test12 = regular-language ( ( any & any ) * ) cmpi (a ∷ b ∷ []) -- proof-egex-even : egex-even -- proof-egex-even [] _ = refl -- proof-egex-even (a ∷ []) () -- proof-egex-even (b ∷ []) () -- proof-egex-even (c ∷ []) () -- proof-egex-even (x ∷ x₁ ∷ s) y = proof-egex-even s {!!} open import finiteSet iFin : FiniteSet In iFin = record { finite = finite0 ; Q←F = Q←F0 ; F←Q = F←Q0 ; finiso→ = finiso→0 ; finiso← = finiso←0 } where finite0 : ℕ finite0 = 4 Q←F0 : Fin finite0 → In Q←F0 zero = a Q←F0 (suc zero) = b Q←F0 (suc (suc zero)) = c Q←F0 (suc (suc (suc zero))) = d F←Q0 : In → Fin finite0 F←Q0 a = # 0 F←Q0 b = # 1 F←Q0 c = # 2 F←Q0 d = # 3 finiso→0 : (q : In) → Q←F0 ( F←Q0 q ) ≡ q finiso→0 a = refl finiso→0 b = refl finiso→0 c = refl finiso→0 d = refl finiso←0 : (f : Fin finite0 ) → F←Q0 ( Q←F0 f ) ≡ f finiso←0 zero = refl finiso←0 (suc zero) = refl finiso←0 (suc (suc zero)) = refl finiso←0 (suc (suc (suc zero))) = refl open import derive In iFin open import automaton ra-ex = trace (regex→automaton cmpi r2) (record { state = r2 ; is-derived = unit }) ( a ∷ b ∷ c ∷ [])
State Before: α : Type u_1 β : Type ?u.179008 γ : Type ?u.179011 inst✝ : DecidableEq α s t u : Multiset α a b : α h : s ≤ t ⊢ s ∪ t = t State After: no goals Tactic: rw [union_comm, eq_union_left h]
| pc = 0xc002 | a = 0xff | x = 0x00 | y = 0x00 | sp = 0x01fd | p[NV-BDIZC] = 10110100 | | pc = 0xc004 | a = 0x03 | x = 0x00 | y = 0x00 | sp = 0x01fd | p[NV-BDIZC] = 00110101 | | pc = 0xc005 | a = 0x03 | x = 0x00 | y = 0x00 | sp = 0x01fc | p[NV-BDIZC] = 00110101 | MEM[0x01fd] = 0x03 | | pc = 0xc007 | a = 0x30 | x = 0x00 | y = 0x00 | sp = 0x01fc | p[NV-BDIZC] = 00110101 | | pc = 0xc008 | a = 0x03 | x = 0x00 | y = 0x00 | sp = 0x01fd | p[NV-BDIZC] = 00110101 | MEM[0x01fd] = 0x03 |
{-# OPTIONS --cubical --safe #-} open import Prelude open import Relation.Binary module Relation.Binary.Construct.LowerBound {e} {E : Type e} {r₁ r₂} (totalOrder : TotalOrder E r₁ r₂) where open TotalOrder totalOrder renaming (refl to <-refl) import Data.Unit.UniversePolymorphic as Poly import Data.Empty.UniversePolymorphic as Poly data ⌊∙⌋ : Type e where ⌊⊥⌋ : ⌊∙⌋ ⌊_⌋ : E → ⌊∙⌋ ⌊_⌋≤_ : E → ⌊∙⌋ → Type _ ⌊ x ⌋≤ ⌊⊥⌋ = Poly.⊥ ⌊ x ⌋≤ ⌊ y ⌋ = x ≤ y _⌊≤⌋_ : ⌊∙⌋ → ⌊∙⌋ → Type _ ⌊⊥⌋ ⌊≤⌋ y = Poly.⊤ ⌊ x ⌋ ⌊≤⌋ y = ⌊ x ⌋≤ y _<⌊_⌋ : ⌊∙⌋ → E → Type _ ⌊⊥⌋ <⌊ y ⌋ = Poly.⊤ ⌊ x ⌋ <⌊ y ⌋ = x < y _⌊<⌋_ : ⌊∙⌋ → ⌊∙⌋ → Type _ _ ⌊<⌋ ⌊⊥⌋ = Poly.⊥ x ⌊<⌋ ⌊ y ⌋ = x <⌊ y ⌋ lb-pord : PartialOrder ⌊∙⌋ _ Preorder._≤_ (PartialOrder.preorder lb-pord) = _⌊≤⌋_ Preorder.refl (PartialOrder.preorder lb-pord) {⌊⊥⌋} = _ Preorder.refl (PartialOrder.preorder lb-pord) {⌊ x ⌋} = <-refl Preorder.trans (PartialOrder.preorder lb-pord) {⌊⊥⌋} {_} {_} p q = _ Preorder.trans (PartialOrder.preorder lb-pord) {⌊ x ⌋} {⌊ y ⌋} {⌊ z ⌋} p q = ≤-trans p q PartialOrder.antisym lb-pord {⌊⊥⌋} {⌊⊥⌋} p q = refl PartialOrder.antisym lb-pord {⌊ x ⌋} {⌊ x₁ ⌋} p q = cong ⌊_⌋ (antisym p q) lb-sord : StrictPartialOrder ⌊∙⌋ _ StrictPreorder._<_ (StrictPartialOrder.strictPreorder lb-sord) = _⌊<⌋_ StrictPreorder.trans (StrictPartialOrder.strictPreorder lb-sord) {⌊⊥⌋} {⌊⊥⌋} {⌊⊥⌋} p q = q StrictPreorder.trans (StrictPartialOrder.strictPreorder lb-sord) {⌊⊥⌋} {⌊⊥⌋} {⌊ x ⌋} p q = q StrictPreorder.trans (StrictPartialOrder.strictPreorder lb-sord) {⌊⊥⌋} {⌊ x ⌋} {⌊ x₁ ⌋} p q = p StrictPreorder.trans (StrictPartialOrder.strictPreorder lb-sord) {⌊ x ⌋} {⌊ x₁ ⌋} {⌊ x₂ ⌋} p q = <-trans p q StrictPreorder.irrefl (StrictPartialOrder.strictPreorder lb-sord) {⌊ x ⌋} = irrefl {x = x} StrictPartialOrder.conn lb-sord {⌊⊥⌋} {⌊⊥⌋} p q = refl StrictPartialOrder.conn lb-sord {⌊⊥⌋} {⌊ x ⌋} p q = ⊥-elim (p _) StrictPartialOrder.conn lb-sord {⌊ x ⌋} {⌊⊥⌋} p q = ⊥-elim (q _) StrictPartialOrder.conn lb-sord {⌊ x ⌋} {⌊ x₁ ⌋} p q = cong ⌊_⌋ (conn p q) lb-lt : ∀ x y → Dec (x ⌊<⌋ y) lb-lt x ⌊⊥⌋ = no (λ ()) lb-lt ⌊⊥⌋ ⌊ y ⌋ = yes Poly.tt lb-lt ⌊ x ⌋ ⌊ y ⌋ = x <? y lb-ord : TotalOrder ⌊∙⌋ _ _ TotalOrder.strictPartialOrder lb-ord = lb-sord TotalOrder.partialOrder lb-ord = lb-pord TotalOrder._<?_ lb-ord = lb-lt TotalOrder.≰⇒> lb-ord {⌊⊥⌋} {⌊⊥⌋} p = ⊥-elim (p _) TotalOrder.≰⇒> lb-ord {⌊⊥⌋} {⌊ x ⌋} p = ⊥-elim (p _ ) TotalOrder.≰⇒> lb-ord {⌊ x ⌋} {⌊⊥⌋} p = _ TotalOrder.≰⇒> lb-ord {⌊ x ⌋} {⌊ x₁ ⌋} p = ≰⇒> p TotalOrder.≮⇒≥ lb-ord {x} {⌊⊥⌋} p = _ TotalOrder.≮⇒≥ lb-ord {⌊⊥⌋} {⌊ y ⌋} p = ⊥-elim (p _) TotalOrder.≮⇒≥ lb-ord {⌊ x ⌋} {⌊ y ⌋} p = ≮⇒≥ p
#pragma once #ifndef DSFMTAVXDC_HPP #define DSFMTAVXDC_HPP /** * @file dSFMTAVXdc.hpp */ #include "devavxprng.h" #include <MTToolBox/AlgorithmReducibleRecursionSearch.hpp> #include <MTToolBox/AlgorithmCalculateParity.hpp> #include <MTToolBox/AlgorithmEquidistribution.hpp> #include <MTToolBox/MersenneTwister64.hpp> #include <NTL/GF2X.h> #include "AlgorithmDSFMTEquidistribution.hpp" #include "Annihilate.hpp" #include "AlgorithmCalcFixPoint.hpp" #include "DCOptions.hpp" namespace MTToolBox { /** * search parameters using all_in_one function in the file search_all.hpp * @param opt command line options * @param count number of parameters user requested * @return 0 if this ends normally */ template<typename U, typename G, int bitWidth> int dsfmtavx_search(DCOptions& opt, int count) { using namespace std; using namespace NTL; MersenneTwister64 mt(opt.seed); G g(opt.mexp); cout << "#seed = " << dec << opt.seed << endl; if (opt.verbose) { time_t t = time(NULL); cout << "search start at " << ctime(&t); } if (opt.fixedL) { g.setFixedSL1(opt.fixedSL1); } if (opt.fixedP) { g.setFixedPerm(opt.fixedPerm); } AlgorithmReducibleRecursionSearch<U> ars(g, mt); int i = 0; AlgorithmCalculateParity<U, G> cp; Annihilate<G, U> annihilate; cout << "# " << g.getHeaderString() << ", delta52" << endl; while (i < count) { if (ars.start(opt.mexp * 1000)) { GF2X irreducible = ars.getIrreducibleFactor(); GF2X characteristic = ars.getCharacteristicPolynomial(); if (deg(irreducible) != opt.mexp) { cout << "error mexp = " << dec << opt.mexp << " deg = " << dec << deg(irreducible) << endl; return -1; } annihilate.getLCMPoly(characteristic, g); GF2X quotient = characteristic / irreducible; U fixpoint = calc_fixpoint<G, U>(g, irreducible, quotient); g.setFixPoint(fixpoint); cp.searchParity(g, irreducible); U seed; setBitOfPos(&seed, 0, 1); g.seed(seed); if (!annihilate.anni(g)) { return -1; } int veq52[52]; DSFMTInfo info; info.bitSize = bitWidth; info.elementNo = bitWidth / 64; int delta52 = calc_dSFMT_equidistribution<U, G> (g, veq52, 52, info, opt.mexp); cout << g.getParamString(); cout << dec << delta52; cout << "," << veq52[51] << endl; //cout << endl; i++; } else { cout << "search failed" << endl; break; } } if (opt.verbose) { time_t t = time(NULL); cout << "search end at " << ctime(&t) << endl; } return 0; } } #endif // DSFMTAVX512FDC_HPP
(** * Annotated Terms syntax In this file, we describe a slightly different syntax for terms: we add two annotations to applications. If the head of an application if a function from [A] to [B], we had both informations in the application, in order to keep track of the conversion during the typing that would be impossible to rebuild after. *) Require Import Peano_dec. Require Import Compare_dec. Require Import Lt. Require Import Le. Require Import Gt. Require Import Plus. Require Import Minus. Require Import Bool. Require Import base. Unset Standard Proposition Elimination Names. (** Term syntax. Notice the two additional [Term] in the application.*) Module Type term_mod (X:term_sig). Import X. Inductive Term : Set:= | Var : Vars -> Term | Sort : Sorts -> Term | App : Term -> Term -> Term -> Term -> Term | Pi : Term -> Term -> Term | La :Term -> Term -> Term . (** this notation means that the product x y is annotated by the function space A -> B.**) Notation "x ·( A , B ) y" := (App x A B y) (at level 15, left associativity) : Typ_scope. Notation "! s" := (Sort s) (at level 1) : Typ_scope. Notation "# v" := (Var v) (at level 1) : Typ_scope. Notation "'Π' ( U ) , V " := (Pi U V) (at level 20, U, V at level 30) : Typ_scope. Notation "'λ' [ U ] , v " := (La U v) (at level 20, U , v at level 30) : Typ_scope. Reserved Notation " t ↑ x # n " (at level 5, x at level 0, left associativity). Delimit Scope Typ_scope with Typ. (** Same as for usual terms, we need lift and subst functions, with the very same properties. They are just extended to deal with the two annotations.*) Open Scope Typ_scope. (* lift c n times *) Fixpoint lift_rec (n:nat) (k:nat) (T:Term) {struct T} := match T with | # x => if le_gt_dec k x then Var (n+x) else Var x | ! s => Sort s | M ·(A, B) N=> App (M ↑ n # k) (A↑ n # k) (B ↑ n # (S k)) (N ↑ n # k) | Π ( A ), B => Π (A ↑ n # k), (B ↑ n # (S k)) | λ [ A ], M => λ [A ↑ n # k], (M ↑ n # (S k)) end where "t ↑ n # k" := (lift_rec n k t) : Typ_scope. Notation " t ↑ n " := (lift_rec n 0 t) (at level 5, n at level 0, left associativity) : Typ_scope. Lemma inv_lift : forall M N n m , M ↑ n # m = N ↑ n # m -> M = N. intros M; induction M; destruct N; intros; simpl in *; try (discriminate || intuition); (try (destruct (le_gt_dec m v) ; discriminate)). destruct (le_gt_dec m v); destruct (le_gt_dec m v0) ; injection H; intros; subst; intuition. apply plus_reg_l in H0; rewrite H0; trivial. elim (lt_irrefl m). apply le_lt_trans with v. trivial. induction n; intuition. elim (lt_irrefl v0). apply lt_le_trans with m. induction n; intuition. trivial. injection H; intros; subst; clear H. rewrite (IHM1 N1 n m H3); rewrite (IHM2 N2 n m H2); rewrite (IHM3 N3 n (S m) H1); rewrite (IHM4 N4 n m H0); reflexivity. injection H; intros; rewrite (IHM1 N1 n m H1); rewrite (IHM2 N2 n (S m) H0); reflexivity. injection H; intros; rewrite (IHM1 N1 n m H1); rewrite (IHM2 N2 n (S m) H0); reflexivity. Qed. Lemma lift_rec0 : forall M n, M ↑ 0 # n = M. induction M; intros; simpl. destruct (le_gt_dec n v); reflexivity. reflexivity. rewrite IHM1; rewrite IHM2; rewrite IHM3; rewrite IHM4; reflexivity. rewrite IHM1; rewrite IHM2; reflexivity. rewrite IHM1; rewrite IHM2; reflexivity. Qed. Lemma lift0 : forall M, M ↑ 0 = M . intros; apply lift_rec0. Qed. Lemma liftP1 : forall M i j k, (M ↑ j # i) ↑ k # (j+i) = M ↑ (j+k) # i. intros M; induction M; intros;simpl. destruct (le_gt_dec i v); simpl. destruct (le_gt_dec (j+i) (j+v)); simpl. rewrite plus_assoc. replace (k+j) with (j+k) by (apply plus_comm). trivial. apply plus_gt_reg_l in g. elim (lt_irrefl v). apply lt_le_trans with i; intuition. simpl; destruct (le_gt_dec (j+i)); intuition. elim (lt_irrefl v). apply lt_le_trans with i; intuition. induction j; intuition. reflexivity. rewrite IHM1. rewrite IHM2. rewrite IHM4. rewrite <- IHM3. replace (j+S i) with (S(j+i)) by intuition. trivial. rewrite IHM1; rewrite <-IHM2 ;replace (j+S i) with (S(j+i)) by intuition; reflexivity. rewrite IHM1; rewrite <- IHM2 ;replace (j+S i) with (S(j+i)) by intuition; reflexivity. Qed. Lemma liftP2: forall M i j k n, i <= n -> (M ↑ j # i) ↑ k # (j+n) = (M ↑ k # n) ↑ j # i. intro M; induction M; intros; simpl. destruct (le_gt_dec i v); destruct (le_gt_dec n v). simpl. destruct le_gt_dec. destruct le_gt_dec. rewrite 2! plus_assoc. replace (k+j) with (j+k) by (apply plus_comm). trivial. elim (lt_irrefl v). apply lt_le_trans with i. induction k; intuition. trivial. apply plus_gt_reg_l in g. elim (lt_irrefl v). apply lt_le_trans with n; intuition. simpl. destruct le_gt_dec. apply plus_le_reg_l in l0. elim (lt_irrefl v). apply lt_le_trans with n; intuition. destruct le_gt_dec. trivial. elim (lt_irrefl v). apply lt_le_trans with i; intuition. simpl. destruct le_gt_dec. elim (lt_irrefl n). apply lt_le_trans with i. apply le_lt_trans with v; intuition. trivial. elim (lt_irrefl v). apply lt_le_trans with n. apply lt_le_trans with i; intuition. trivial. simpl. destruct le_gt_dec. elim (lt_irrefl v). apply lt_le_trans with n. intuition. induction j; intuition. destruct le_gt_dec. elim (lt_irrefl i). apply le_lt_trans with v; intuition. trivial. trivial. rewrite IHM1; intuition. replace (S(j+n)) with (j+S n) by intuition. rewrite IHM2; intuition. rewrite IHM3; intuition. rewrite IHM4; intuition. rewrite IHM1; intuition. replace (S(j+n)) with (j+S n) by intuition. rewrite (IHM2 (S i) j k (S n)); intuition. rewrite IHM1; intuition. replace (S(j+n)) with (j+S n) by intuition. rewrite (IHM2 (S i) j k (S n) ); intuition. Qed. Lemma liftP3 : forall M i k j n , i <= k -> k <= (i+n) -> (M ↑ n # i) ↑ j # k = M ↑ (j+n) # i. intro M; induction M; intros; simpl. destruct (le_gt_dec i v); simpl. destruct (le_gt_dec k (n+v)); intuition. elim (lt_irrefl (i+n)). apply lt_le_trans with k. apply le_lt_trans with (n+v). rewrite plus_comm. intuition. intuition. trivial. destruct (le_gt_dec k v); intuition. elim (lt_irrefl k). apply lt_le_trans with i. apply le_lt_trans with v. trivial. intuition. trivial. reflexivity. rewrite IHM1; intuition. rewrite IHM2; intuition. rewrite IHM3; intuition. rewrite IHM4; intuition. change (S i + n) with (S (i+n)). intuition. rewrite IHM1; intuition;rewrite IHM2; intuition. change (S i + n) with (S (i+n)). intuition. rewrite IHM1; intuition; rewrite IHM2; intuition. change (S i + n) with (S (i+n)). intuition. Qed. Lemma lift_lift : forall M n m, (M ↑ m) ↑ n = M ↑ (n+m). intros. apply liftP3; intuition. Qed. (* i = index to replace t = term we are replacing k = limit between free and bound indices *) Reserved Notation "M [ n ← N ]" (at level 5, n at level 0, left associativity). Fixpoint subst_rec U T n {struct T} := match T with | # x => match (lt_eq_lt_dec x n) with | inleft (left _) => # x (* x < n *) | inleft (right _) => U ↑ n (* x = n *) | inright _ => # (x - 1) (* x > n *) end | ! s => ! s | M ·(A,B) N => (M [ n ← U ]) ·(A[n← U], B [ S n ← U]) ( N [ n ← U ]) | Π ( A ), B => Π ( A [ n ← U ] ), (B [ S n ← U ]) | λ [ A ], M => λ [ A [ n ← U ] ], (M [ S n ← U ]) end where " t [ n ← w ] " := (subst_rec w t n) : Typ_scope. Notation " t [ ← w ] " := (subst_rec w t 0) (at level 5) : Typ_scope. Lemma expand_term_with_subst : forall M n, (M ↑ 1 # (S n)) [ n ← #0 ] = M. induction M; intros. unfold lift_rec. destruct (le_gt_dec (S n) v). unfold subst_rec. destruct (lt_eq_lt_dec (1+v) n) as [[] | ]. apply le_not_lt in l. elim l. intuition. elim (lt_irrefl v). apply lt_le_trans with (S (S v)). intuition. subst; trivial. change (1+v) with (S v). destruct v; simpl; trivial. simpl. destruct (lt_eq_lt_dec v n) as [[] | ]. trivial. simpl; subst; trivial. rewrite <- plus_n_O. trivial. elim (lt_irrefl n). apply lt_le_trans with v; intuition. simpl; trivial. simpl. rewrite IHM1. rewrite IHM2. rewrite IHM3. rewrite IHM4. reflexivity. simpl. rewrite IHM1. rewrite IHM2. reflexivity. simpl. rewrite IHM1. rewrite IHM2. reflexivity. Qed. Lemma substP1: forall M N i j k , ( M [ j ← N] ) ↑ k # (j+i) = (M ↑ k # (S (j+i))) [ j ← (N ↑ k # i ) ]. intros M; induction M; intros. simpl (#v [j ← N] ↑ k # (j+i)). change (#v ↑ k # (S (j+i))) with (if le_gt_dec (S (j+i)) v then #(k+v) else #v). destruct (lt_eq_lt_dec v j) as [[] | ]. destruct (le_gt_dec (S (j+i)) v). elim (lt_irrefl v). apply lt_le_trans with j; intuition. apply le_trans with (S (j+i)); intuition. simpl. destruct (le_gt_dec (j+i) v). elim (lt_irrefl v). apply lt_le_trans with j; intuition. apply le_trans with (j+i); intuition. destruct (lt_eq_lt_dec v j) as [[] | ]. trivial. subst. elim (lt_irrefl j);trivial. elim (lt_irrefl j); apply lt_trans with v; trivial. destruct (le_gt_dec (S(j+i)) v). subst. elim (lt_irrefl j). apply lt_le_trans with (S (j+i)). intuition. trivial. simpl. destruct (lt_eq_lt_dec v j) as [[] | ]. subst. elim (lt_irrefl j); trivial. apply liftP2; intuition. subst. elim (lt_irrefl j); trivial. destruct (le_gt_dec (S (j+i)) v). simpl. destruct (le_gt_dec (j+i) (v-1)). destruct (lt_eq_lt_dec (k+v) j) as [[] | ]. elim (lt_irrefl j). apply lt_le_trans with v. trivial. induction k; intuition. subst. elim (lt_irrefl v). apply lt_le_trans with (S(k+v+i)). intuition. trivial. destruct v. apply lt_n_O in l; elim l. rewrite <- 2! pred_of_minus. replace (k+ S v) with (S (k+v)) by intuition. simpl. trivial. elim (lt_irrefl v). apply lt_le_trans with (S (j+i)). destruct v. apply lt_n_O in l; elim l. rewrite <- pred_of_minus in g. simpl in g. intuition. trivial. simpl. destruct (le_gt_dec (j+i) (v-1)). destruct (lt_eq_lt_dec v j) as [[] | ]. elim (lt_irrefl j); apply lt_trans with v; trivial. subst. elim (lt_irrefl j); trivial. elim (lt_irrefl v). apply lt_le_trans with (S (j+i)). intuition. destruct v. apply lt_n_O in l; elim l. rewrite <- pred_of_minus in l0. simpl in l0. intuition. destruct (lt_eq_lt_dec) as [[] | ]. elim (lt_irrefl j); apply lt_trans with v; trivial. subst. elim (lt_irrefl j); trivial. trivial. simpl; trivial. simpl. rewrite IHM1; intuition; rewrite IHM2; intuition. rewrite IHM4; intuition. replace (S(S(j+i))) with (S((S j)+i)) by intuition. rewrite <- (IHM3 N i (S j) k ); intuition. simpl; rewrite IHM1; intuition. replace (S(S(j+i))) with (S((S j)+i)) by intuition. rewrite <- (IHM2 N i (S j) k ); intuition. simpl; rewrite IHM1; intuition. replace (S(S(j+i))) with ((S ((S j)+i))) by intuition. rewrite <- (IHM2 N i (S j) k ); intuition. Qed. Lemma substP2: forall M N i j n, i <= n -> (M ↑ j # i ) [ j+n ← N ] = ( M [ n ← N]) ↑ j # i . intro M; induction M; intros; simpl. destruct (le_gt_dec i v); destruct (lt_eq_lt_dec v n) as [[] | ]. simpl. destruct (le_gt_dec i v). destruct (lt_eq_lt_dec (j+v) (j+n)) as [[] | ]. reflexivity. apply plus_reg_l in e. subst. elim (lt_irrefl n); trivial. apply plus_lt_reg_l in l2. elim (lt_asym v n); trivial. elim (lt_irrefl i). apply le_lt_trans with v; intuition. subst. simpl. destruct (lt_eq_lt_dec (j+n) (j+n)) as [[] | ]. apply lt_irrefl in l0; elim l0. symmetry. apply liftP3; intuition. apply lt_irrefl in l0; elim l0. simpl. destruct (le_gt_dec i (v-1)). destruct (lt_eq_lt_dec (j+v) (j+n))as [[] | ]. apply plus_lt_reg_l in l2. elim (lt_asym v n ); trivial. apply plus_reg_l in e; subst. elim (lt_irrefl n); trivial. destruct v. apply lt_n_O in l0; elim l0. rewrite <- 2! pred_of_minus. replace (j+ S v) with (S (j+v)) by intuition. simpl. trivial. unfold gt in g. unfold lt in g. rewrite <- pred_of_minus in g. rewrite <- (S_pred v n l0) in g. elim (lt_irrefl n). apply lt_le_trans with v; trivial. apply le_trans with i; trivial. simpl. destruct (le_gt_dec i v). elim (lt_irrefl i). apply le_lt_trans with v; trivial. destruct (lt_eq_lt_dec v (j+n)) as [[] | ]. reflexivity. subst. elim (lt_irrefl n). apply le_lt_trans with (j+n); intuition. elim (lt_irrefl n). apply lt_trans with v. apply le_lt_trans with (j+n); intuition. trivial. simpl. subst. elim (lt_irrefl n). apply lt_le_trans with i; intuition. simpl. elim (lt_irrefl n). apply lt_le_trans with v; intuition. apply le_trans with i; intuition. trivial. rewrite IHM1; intuition. replace (S(j+n)) with (j+(S n)) by intuition. rewrite IHM3; intuition. rewrite IHM2; intuition; rewrite IHM4; intuition. replace (S(j+n)) with (j+(S n)) by intuition. rewrite IHM1; intuition; rewrite <- (IHM2 N (S i) j (S n)); intuition. replace (S(j+n)) with (j+(S n)) by intuition. rewrite IHM1; intuition; rewrite <- (IHM2 N (S i) j (S n)); intuition. Qed. Lemma substP3: forall M N i k n, i <= k -> k <= i+n -> (M↑ (S n) # i) [ k← N] = M ↑ n # i. intro M; induction M; intros; simpl. destruct (le_gt_dec i v). unfold subst_rec. destruct (lt_eq_lt_dec (S(n+v)) k) as [[] | ]. elim (lt_irrefl (i+n)). apply lt_le_trans with k; intuition. apply le_lt_trans with (v+n). intuition. rewrite plus_comm; intuition. subst. replace (i+n) with (n+i) in H0 by (apply plus_comm) . replace (S (n+v)) with (n + S v) in H0 by intuition. apply plus_le_reg_l in H0. elim (lt_irrefl i). apply le_lt_trans with v; intuition. simpl. rewrite <- minus_n_O. trivial. simpl. destruct (lt_eq_lt_dec v k) as [[] | ]. reflexivity. subst. elim (lt_irrefl i). apply le_lt_trans with k; intuition. elim (lt_irrefl k). apply lt_trans with v; trivial. apply lt_le_trans with i; intuition. reflexivity. rewrite IHM1; intuition;rewrite IHM4; intuition. rewrite IHM2; intuition. change (S i + n) with (S (i+n)). rewrite IHM3; intuition. change (S i + n) with (S (i+n)). intuition. rewrite IHM1; intuition; rewrite <- (IHM2 N (S i) (S k) n); intuition. change (S i + n) with (S (i+n)). intuition. rewrite IHM1; intuition; rewrite <- (IHM2 N (S i) (S k) n); intuition. change (S i + n) with (S (i+n)). intuition. Qed. Lemma substP4: forall M N P i j, (M [ i← N]) [i+j ← P] = (M [S(i+j) ← P]) [i← N[j← P]]. intro M; induction M; intros; simpl. destruct (lt_eq_lt_dec v i) as [[] | ] ; destruct (lt_eq_lt_dec v (S(i+j))) as [[] | ]. simpl. destruct (lt_eq_lt_dec v (i+j)) as [[] | ]. destruct (lt_eq_lt_dec v i) as [[] | ]. trivial. subst. apply lt_irrefl in l; elim l. elim ( lt_asym v i); trivial. subst. rewrite plus_comm in l. elim (lt_irrefl i). induction j; simpl in *; intuition. elim (lt_irrefl i). apply le_lt_trans with v;intuition. rewrite plus_comm in l1; intuition. induction j; simpl in *; intuition. subst. elim (lt_irrefl i). apply lt_trans with (S (i+j)); intuition. elim (lt_irrefl i). apply lt_trans with (S (i+j)); intuition. apply lt_trans with v; trivial. simpl. subst. destruct (lt_eq_lt_dec i i) as [[] | ]. elim (lt_irrefl i); trivial. apply substP2; intuition. elim (lt_irrefl i); trivial. subst v. rewrite plus_comm in e0. apply succ_plus_discr in e0. elim e0. subst. elim (lt_irrefl i). apply le_lt_trans with (i+j); intuition. simpl. destruct (lt_eq_lt_dec (v-1) (i+j)) as [[] | ]. destruct (lt_eq_lt_dec v i) as [[] | ]. elim (lt_asym v i); trivial. subst. elim (lt_irrefl i); trivial. trivial. rewrite <- e in l0. rewrite <- pred_of_minus in l0. rewrite <- (S_pred v i l) in l0. elim (lt_irrefl v); trivial. apply lt_n_S in l1. elim (lt_irrefl v). apply lt_trans with (S(i+j)); trivial. rewrite <- pred_of_minus in l1. rewrite <- (S_pred v i l) in l1. trivial. subst. simpl. rewrite <- minus_n_O. destruct (lt_eq_lt_dec (i+j) (i+j)) as [[] | ]. elim (lt_irrefl (i+j)) ; trivial. symmetry. apply substP3; intuition. elim (lt_irrefl (i+j)) ; trivial. simpl. destruct (lt_eq_lt_dec (v-1) (i+j)) as [[] | ]. elim (lt_irrefl v). apply lt_trans with (S (i+j)) ;trivial. apply lt_n_S in l1. rewrite <- pred_of_minus in l1. rewrite <- (S_pred v i l) in l1. trivial. apply eq_S in e. rewrite <- pred_of_minus in e. rewrite <- (S_pred v i l) in e. subst. elim (lt_irrefl (S(i+j))); trivial. destruct (lt_eq_lt_dec (v-1) i) as [[] | ]. elim (lt_irrefl v). apply le_lt_trans with i; trivial. destruct v. apply lt_n_O in l; elim l. rewrite <- pred_of_minus in l2. simpl in l2. trivial. destruct v. elim (lt_n_O i); trivial. rewrite <- pred_of_minus in e. simpl in e. subst. rewrite <- pred_of_minus in l1. simpl in l1. elim (lt_irrefl i). apply le_lt_trans with (i+j); intuition. trivial. trivial. rewrite IHM1; rewrite IHM4; intuition. rewrite IHM2; intuition. replace (S(S(i+j))) with (S((S i)+ j)) by intuition. rewrite <- IHM3; intuition. rewrite IHM1; replace (S(S(i+j))) with (S((S i)+ j)) by intuition; rewrite <- (IHM2 N P (S i)); replace (S(i+j)) with ((S i)+ j) by intuition; intuition. rewrite IHM1; replace (S(S(i+j))) with (S((S i)+j)) by intuition; rewrite <- (IHM2 N P (S i)); replace (S(i+j)) with ((S i)+ j) by intuition; intuition. Qed. Lemma subst_travers : forall M N P n, (M [← N]) [n ← P] = (M [n+1 ← P])[← N[n← P]]. intros. rewrite plus_comm. change n with (O+n). apply substP4. Qed. End term_mod.
Require Import Arith. Require Import Omega. Require Import Recdef. Require Import String. Require Import List. Require Import Program.Tactics. Require Import Relation_Operators. Require Import Ascii. Require Import Program. Require Import Bool. Require Import Sorting.Permutation. Section CharacterFacts. (* Perhaps useful in your regular-expression development. *) (* `ascii_eq` is an executable equality test for characters. *) Definition ascii_eq (a b:ascii) : bool := match (a, b) with | (Ascii a1 a2 a3 a4 a5 a6 a7 a8, Ascii b1 b2 b3 b4 b5 b6 b7 b8) => eqb a1 b1 && eqb a2 b2 && eqb a3 b3 && eqb a4 b4 && eqb a5 b5 && eqb a6 b6 && eqb a7 b7 && eqb a8 b8 end. Lemma ascii_eq_refl (a:ascii): ascii_eq a a = true. Proof. destruct a; unfold ascii_eq; repeat rewrite eqb_reflx; simpl; auto. Qed. (* `ascii_eq` is equivalent to character equality. *) Lemma ascii_eq_iff a b: ascii_eq a b = true <-> a = b. Proof. split; intros. - unfold ascii_eq in H; destruct a; destruct b; repeat rewrite andb_true_iff in *; destruct_pairs; rewrite eqb_true_iff in *; congruence. - rewrite H; apply ascii_eq_refl. Qed. End CharacterFacts. Section StringFacts. (* Perhaps useful in your regular-expression development. *) (* Coq `string`s are constructed from characters using a `list`-like cons procedure. The two `string` constructors are `EmptyString` (also written ` ""%string `; like `nil`) and `String ch s` (which is like `ch :: s`). *) (* `append` is the string version of `app` (list append). The Coq library has fewer `append` lemmas; we provide them. *) Lemma append_nil_l s: ("" ++ s)%string = s. Proof. simpl; auto. Qed. Lemma append_nil_r s: (s ++ "")%string = s. Proof. induction s; simpl; try rewrite IHs; auto. Qed. Lemma append_assoc s1 s2 s3: (s1 ++ s2 ++ s3)%string = ((s1 ++ s2) ++ s3)%string. Proof. induction s1; simpl; try rewrite IHs1; auto. Qed. Lemma append_comm_cons a s1 s2: (String a s1 ++ s2)%string = String a (s1 ++ s2)%string. Proof. induction s1; simpl; auto. Qed. Definition strlen := String.length. Lemma append_strlen_l s1 s2: strlen s1 <= strlen (s1 ++ s2). Proof. induction s1; simpl; try rewrite IHs1; omega. Qed. Lemma append_strlen_r s1 s2: strlen s2 <= strlen (s1 ++ s2). Proof. induction s1; simpl; try rewrite IHs1; omega. Qed. End StringFacts. (* Define a type that represents regular expressions. Support the following grammar (but you don’t need to use this concrete syntax): regex ::= 'ε' // matches the empty string | 'ANY' // matches any character | CHAR // matches a specific character | regex '++' regex // concatenation | regex '|' regex // or | regex '*' // Kleene star This type *represents* regular expressions in memory, so it is a `Set` (not a `Prop`). *) (* YOUR CODE HERE *) (* Now define an inductive proposition with two parameters, a regex and a string, that holds iff the regex matches the string. (This type *defines* the semantics of regular expressions, so you can’t prove it correct---it just needs to match the expected semantics.) *) (* YOUR CODE HERE *) (* Write a couple `Example`s that show that specific regular expressions match specific strings, and prove them. *) (* YOUR CODE HERE *) (* State and prove a theorem that relates Kleene-star and concatenation. Your theorem should say that if `r*` matches a string `s`, then there exists a regex `r ++ r ++ ... ++ r` that matches `s`, and vice versa. (Probably easiest to introduce a helper function that produces `r ++ ... ++ r` for a given count, and then to prove two lemmas, one per direction. *) (* YOUR CODE HERE *) (* Now, write a regular expression IMPLEMENTATION and prove it at least partially correct. Q. What does “implementation” mean? A. Here are some possibilities. - COMPUTATIONAL MATCHER: You could write a `Function` or `Fixpoint` that takes a regex as an argument and returns `true` if the regex matches. - NFA MATCHER: You could design an inductive type for nondeterministic finite automata. This would include a `Function` or `Fixpoint` that builds the NFA for a regex using Thompson’s construction, and an inductive proposition that implements NFA matching. - DERIVATIVES MATCHER: http://www.ccs.neu.edu/home/turon/re-deriv.pdf - OTHER: Check with me! Q. Any general gotchas? A. DON’T PREMATURELY OPTIMIZE. Q. Any gotchas with a computational matcher? A. Kleene-star will cause problems since your recursion might never terminate. It’s OK to add an extra “fuel” argument to force termination. Each recursive call will consume a unit of fuel, and the match may terminate prematurely (i.e., return `false`) if it runs out of fuel. But given enough fuel, your matcher should succeed on Kleene-star arguments (it’s not OK to return `false` for every Kleene-star regex). Q. Any gotchas with an NFA matcher? A. I found it far easier to work with a “nested” NFA design, in which an NFA node may contain another NFA as a subgraph, than a “flat” NFA design, in which the regex-to-NFA function flattens the regex as it goes. Q. What does “partially correct” mean? A. Full correctness requires that (1) every string that matches the spec also matches the implementation (perhaps with a “given enough fuel” clause), and (2) every string that matches the implementation also matches the spec. Please prove AT LEAST ONE of these directions. Q. Any general hints? A. I found the NFA matcher easier to work with because of the absence of fuel. A. You will likely need some additional type definitions. A. `inversion` is your friend. A. You will almost certainly want `Hint Constructors` for your types. `auto` goes a lot further when `Hint Constructors` is active. Consider writing your own tactics too; I benefited enormously from a tactic that can tell when an edge (such as one created by `inversion` or `destruct`) is not actually in an NFA. Q. This is fun. How can I go further? A. You’re crazy. But, for example, given an NFA matcher, you could implement an NFA-to-DFA converter and prove it preserved the NFA’s semantics. I wrote an NFA flattener, which de-nests a recursive NFA into a flat graph, and proved that flattening preserves the NFA’s semantics. That was hard, but fun. Q. How can I not get stuck? A. Share your inductive definitions with me before you get too far down the proof route. *) (* YOUR CODE HERE *)
Formal statement is: lemma zero_right: "prod a 0 = 0" Informal statement is: The product of any number and zero is zero.
theory Star imports Main begin inductive star :: "('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> 'a \<Rightarrow> 'a \<Rightarrow> bool" for r where refl: "star r x x" | step: "r x y \<Longrightarrow> star r y z \<Longrightarrow> star r x z" hide_fact (open) refl step \<comment> \<open>names too generic\<close> lemma star_trans: "star r x y \<Longrightarrow> star r y z \<Longrightarrow> star r x z" proof(induction rule: star.induct) case refl thus ?case . next case step thus ?case by (metis star.step) qed lemmas star_induct = star.induct[of "r:: 'a*'b \<Rightarrow> 'a*'b \<Rightarrow> bool", split_format(complete)] declare star.refl[simp,intro] lemma star_step1[simp, intro]: "r x y \<Longrightarrow> star r x y" by(metis star.refl star.step) code_pred star . end
function h = p13_fh ( p, varargin ) %*****************************************************************************80 % %% P13_FH returns a mesh size function for problem 13. % % Licensing: % % This code is distributed under the GNU LGPL license. % % Modified: % % 06 February 2006 % % Reference: % % Per-Olof Persson and Gilbert Strang, % A Simple Mesh Generator in MATLAB, % SIAM Review, % Volume 46, Number 2, June 2004, pages 329-345. % % Parameters: % % Input, real P(NP,ND), the point coordinates. % % Input, VARARGIN, room for extra arguments. % % Output, real H(NP,1), the mesh size function. % np = size ( p, 1 ); h = ones ( np, 1 ); return end
Formal statement is: lemma eventually_nhds_top: fixes P :: "'a :: {order_top,linorder_topology} \<Rightarrow> bool" and b :: 'a assumes "b < top" shows "eventually P (nhds top) \<longleftrightarrow> (\<exists>b<top. (\<forall>z. b < z \<longrightarrow> P z))" Informal statement is: If $b$ is less than the top element of a linearly ordered topological space, then the following are equivalent: $P$ holds eventually in a neighborhood of the top element. There exists $b < top$ such that $P$ holds for all $z > b$.
```python import numpy as np from skspatial.objects import plane from sympy import Plane def perpendicular(a): b = np.empty_like(a) b[0] = -a[1] b[1] = a[0] return b def normalize(a): a = np.array(a) return a/np.linalg.norm(a) def get2DProjection(origin, target_point): points = [origin, target_point, [target_point[0], target_point[1], target_point[2] + 1]] # add 1 in order not to be collinear plane = Plane(points[0], points[1], points[2]) plane_normal = np.array(plane.normal_vector) target_point, origin = np.array(target_point), np.array(origin) x_axis = normalize(np.array([target_point[0], target_point[1], 0])) y_axis = normalize(np.array([0, 0, 1])) s = np.dot(plane_normal, target_point-origin) x_coord = np.dot(x_axis, target_point-origin) y_coord = np.dot(y_axis, target_point-origin) return s, x_coord, y_coord if __name__ == "__main__": target_point = [2, 2, 1] origin = [0, 0, 0] s, t_1, t_2 = get2DProjection(target_point, origin) print("s:", s) print("t_1:", t_1) print("t_2:", t_2) ``` s: 0 t_1: nan t_2: -1.0 /var/folders/sd/1vc_q83x5rn9jjrd0x47_cc00000gn/T/ipykernel_92659/4172601782.py:14: RuntimeWarning: invalid value encountered in true_divide return a/np.linalg.norm(a) ```python ```
*Total work in progress; more than anything an early attempt at sorting it all out by myself. Code and derivations are my own and not necessarily bug-free (though about 80% of the equations here are standard results that are easy to find).* # Combinatorics *If there are m ways to do one thing, and n ways to do another, then there are mn ways of doing both.* - Deepak Chopra I am using the language convention that 'collections' are unordered and 'sequences' are ordered. # Principles ### Product Principle if we have a partition of a set S into m blocks, each of size n, then S has size mn. ### Quotient Principle If we partition a set P into q blocks, each of size r, then q = p/r. ### Sum Principle if we have a partition of a set S, then the size of S is the sum of the sizes of the blocks of the partition. ### Bijection Principle Two sets have the same size if and only if there is a bijection between them. # Combinatorics Code - factorial - binomial coefficent - subsets of size n (choices of n out of S) - subsets of size n+m where n and m are drawn from different, possibly overlappingsets - multinomial - permutations - unordered multiplicities for all n-sized multisets with m classes (no permutations of multiplicities) - multiplicities for all n-sized multisets with m classes ```python import numpy as np def factorial(x): if x == 0: return 1 else: res = 1 for i in range(1,x+1): res *= i return int(res) def binomial(n,k): """ binomial coefficients. convention is that it's 0 if k>n """ if k <= n: return int(factorial(n)/(factorial(k)*factorial(n-k))) else: return 0 def multinomial(n,k): """ multinomial coefficient. k is multiindex. Returns error if sum(k) != n """ assert np.sum(k) == n return int(factorial(n)/np.product([factorial(x) for x in k])) def unordered_multiplicities(n,m,k0_max=None): """ Generator that yields all unordered multiplicities for multisets with n objects of m classes. The convention is that they are sorted: n_1 >= n_2 >= n_3 >= ... >= n_m Example: (n=3,m=3) returns [3,0,0],[2,1,0],[1,1,1] I don't know what the proper math term for this is: If a set of n elements is partitioned into m subsets, then these are the possible relative sizes of that partitions can have. In a multiset of size n, so {1,1,2} = [2,0] is different from {1,2,2} = [0,2]. The multiplicities are ordered, and so [0,2] and [2,0] are counted twice. The "unordered multiplicites" here treat [2,0] and [0,2] as identical. As of now, I don't know how many there should be, but I think that she solution probably lies in creating a bijection to lattice paths. For the case m = n, I think the count might be the Catalan number C_n. I haven't checked. EDIT: These are called partitions and I am using the 'decreasing list' representation of partitions """ if m == 0: yield [] else: # define range of largest entry if not k0_max: k0_max = n k0_min = int(np.ceil(n/m)) # iterate over largest entry, add combinations of remaining entries recursively for k0 in range(k0_min,k0_max+1): # the remaining entries are distributed as n-k0 objects over m-1 buckets, including constraint on maximum amount k_rem = unordered_multiplicities(n-k0,m-1,k0_max=np.min([n-k0,k0])) for k_n in k_rem: res = [k0] + k_n assert np.sum(res) == n yield res def permutations(x): """ generator that yields all permutations of an array x will be a total of factorial(len(x)) if all elements of x are distinguishable (you can just use itertools library) """ pivots = set() if len(x) == 0 or len(x) == 1: yield x elif len(x) == 2: if x[0] == x[1]: yield x else: res = [x,x[::-1]] for i in range(2): yield res[i] else: for i in range(len(x)): p = x[i] if p in pivots: pass else: pivots.add(p) y = permutations(x[:i]+x[i+1:]) for remainder in y: yield [p] + remainder def subsets(n,S): """ Return all choices n out of S assumes all elements of the set are distinguishable """ S = list(S) assert len(S) >= n if n == 0: yield [] else: for i in range(len(S)-n+1): p = [S[i]] rem = subsets(n-1,S[i+1:]) for r in rem: yield p+r def choose(n,m,A,B): """ Returns all unordered collections where n are chosen from A and m are chosen from B, where A & B may overlap. """ C = [x for x in A if x in set(B)] A_ = [x for x in A if x not in B] B_ = [x for x in B if x not in A] a_ = len(A_) b_ = len(B_) c = len(C) for i in range(np.max([n-a_,0]),np.min([c,n])+1): for j in range(np.max([m-b_,0]),np.min([c-i,m])+1): c_C = subsets(i+j,C) for cc in c_C: # iterate over picks from intersection a_A = subsets(n-i,A_) for aa in a_A: # iterate over picks from A b_B = subsets(m-j,B_) for bb in b_B: # iterate over picks from B yield aa+bb+cc def multisets(n,m): """ All multisets of n objects of m classes. All possible ways for n objects divided into m distinguishable classes. ex.: [1,0,0],[0,1,0],[0,0,1] Will be a total of (n multichoose m) This could be huge. """ distributions = unordered_multiplicities(n,m) for distribution in distributions: mindexes = permutations(distribution) for mindex in mindexes: yield mindex ``` # Subsets and Permutations ### k-Element Permutations A permutation is an ordered sequence of distinguishable elements drawn from some set without replacement. Let $[S]$ be a set of $S$ distinguishable elements. A $k$-element permutation can be thought of as a injective function from $[k]=\{1,2,3,...,k\}$ to $[S]$. There are $S^{\underline{k}} = \frac{|S|!}{(|S|-k)!}$ different $k$-element permutations. The notation $S^\underline{k} = S(S-1)(S-2)...(S-k+1)$ is the "falling factorial". ### Number of Subsets of Set with Size n The number of subsets of a set $S$ with size $n$ is $2^n$. One way to calculate that: \begin{equation} n_{subsets} = \sum^n_{i=0} (\mathrm{ways\ of\ picking\ i\ out\ of\ n}) = \sum^n_{i=0}\left(\begin{array}{c}n\\i\end{array}\right) = 2^n \end{equation} There is a better way, though. A subset can be thought of as assigning a label to each element of $S$: it's in or out. That means that any possible subset cen be described by an $n$-element binary string and vice versa -- the subsets and the $n$-element strings can be linked by bijection. The number of subsets is therefore the number of $n$-element binary strings, which is: \begin{equation} n_{subsets} = 2^n \end{equation} ### Number of ways to Divide a Set of size n into m Partitions Equally well, one might ask: how many ways are there to partition $S$ into $k$ subsets? In that case there are $k$ labels, so there are $k^n$ ways. That means: \begin{equation} \sum_{\begin{array}{c}k_1,k_2,...,k_m\\ \sum_{k_i}=n\end{array}}\left(\begin{array}{c}n\\k_1 k_2 ... k_m \end{array}\right) = m^n \end{equation} Which is: (ways of taking $k_1$ out of $n$) x (ways of taking $k_2$ out of ($n-k_1$)) x (ways of ...). Progressively dividing the set into subsets, and adding up all ways of making the division. # Sequences and Collections ### Sequences sampled with Replacement Let [A] be a set of size $A$. \begin{equation} \begin{array}{c} S = \left\{ (a_1,a_2,...,a_n) : a_1,a_2,...,a_n\in [A] \right\}\\ |S| = A^n \end{array} \end{equation} The creation of n-tuples $(a_1,a_2,...,a_n)$ from elements of $A$ can be thought of in terms of functions that map each element of the tuple ($a_i$ for any choice of $i\in (1,n)$) to an element of $A$. For ordered tuples, these functions are always injective. *Example: bit strings of length $3$: [0,0,0],[0,0,1],[0,1,1],[1,0,1],...* ### Collections sampled with Replacement (Multisets) Let [A] a set of size A. \begin{equation} S = \left\{ \{a_1,a_2,...,a_n\} : a_1,a_2,...,a_n \in [A] \right\} \end{equation} This can be thought of as picking a total of $n$ objects from a choice of $k$ classes. There are three entries, that can correspond to up to $\min(3,A)$ different elements of $[A]$. For $n=3$, the options are: they are all the same, two are the same, or they're all different. There are $A$ ways for them to be all the same, $2*A*(A-1)$ ways for two of them to be the same (the factor 2 is because $(a,a,b) \neq (b,b,a)$) and $\left(\begin{array}{c}A\\3\end{array}\right)$ ways for them to all be different. Instead of expressing the elements of S in terms of the unordered multiset $\{a,b,c\}$, we can write them in terms of an ordered sequence that contains the multiplicity of the elements of the multisets. That is, if $[A] = \{1,2,3,4\}$, we write $\{1,1,2\} \in S$ as $[2_1|1_2|0_3|0_4]$. This is a bijection between elements of $S$ and the elements of $N = \{[i_1,i_2,...,i_k]: i_1,i_2,...,i_k \in \mathbb{N}_0^+ , \sum_{i_j} i_j = n\}$ (all length $k$ sequences of integers $[i_1,i_2,...,i_k]$ so that $\sum_{i_j} i_j = n$). The bijection implies that $S$ and $K$ have the same size. The amount of elements in $N$ is the Bose-Einstein Coefficient that is derived in the ``Bose Einstein Coefficients - Stars and Bars`` notebook. Therefore: \begin{equation} |S| = \left(\begin{array}{c}n+k-1\\n\end{array}\right) \end{equation} This is also known as *multichoose*. It is the number of $k$-element multisets on $n$ symbols. *Example: You are 8 years old and you get to pick n pieces of candy from a candy store that has k different types of candy.* *Example: Ways for n bosons to be distributed over k degenerate states.* *Example: The number of ways to draw n elements from k equally likely classes, when the order does not matter.* *Example: How many ways are there to partition a set with n elements (apart the empty set). (In this case k=n)* *Example: In a universe of k stocks, how many portfolios are possible that consist of n stocks?* ### Sequences sampled without Replacement Assume $a,b,c$ are all drawn from a single set $[A]$ without replacement. Then $|S| = A*(A-1)*(A-2)$, i.e. $\frac{n!}{(n-k)!} = n^\underline{k}$ *Example: Possible ways of assigning first, second and third place in a competition.* ### Collections sampled without Replacement This means, selecting $k$ out of $n$: \begin{equation} |S| = \frac{n^\underline{k}}{k!} = \left(\begin{array}{c}n\\k\end{array}\right) \end{equation} Which is the *binomial coefficient*. That's the same as taking the number of ordered $k$-tuples and dividing by the number of internal orderings $k!$. *Example: Possible ways that k fermions might be distributed over n degenerate states* *Example: Possible groups of k people that can be formed out of a pool of n.* ### Collections sampled from several Disjoint Sets with or without Replacement Let [A], [B] and [C] be disjoint subsets of size $A$, $B$ and $C$, respectively. \begin{equation} \begin{array}{c} S = \left\{ \{a,b,c\} : a\in [A], b\in [B], c\in[C] \right\}\\ |S| = ABC \end{array} \end{equation} The mappings between the domain $S$ and co-domain are injective: each entry in the n-tuples is mapped to a disjoint subset of the co-domain. It is impossible for two tuples in $S$ to be permutations of each other, so that different permutations doesn't lead to overcounting. *Example: Choose one drink $a$, one sandwich $b$ and one free T-shirt $c$. How many options are there?* ### Collections from several Overlapping Sets with Replacement Let $[A]$ and $[B]$ be two sets of size $A$ and $B$ respectively, where $A$ and $B$ may or may not overlap. Let: \begin{equation} S = \{\{a_1,a_2,...,a_n,b_1,b_2,...,b_m\}: a\in[A],b\in[B]\} \end{equation} Then, I *think*, but haven't checked: \begin{equation} |S| = \left( \begin{array}{c}n+a-1\\n \end{array}\right)\left( \begin{array}{c}n+b-1\\m \end{array}\right) \end{equation} ### Collections from several Overlapping Sets without Replacement Let $[A]$ and $[B]$ be two sets of size $A$ and $B$ respectively, so that $[A] \neq [B]$ but $[A]\cap[B]=[C]$, with the $C$ the size of $[C]$. The set $S$ consists of all collections of $n$ items from $[A]$ and $m$ items of $[B]$. Let: \begin{equation} S = \{\{a_1,a_2,...,a_n,b_1,b_2,...,b_m\}: a\in[A],b\in[B]\} \end{equation} Then the size of $|S|$: \begin{equation} |S| = \sum_{\max(n-A+C,0)\leq i \leq \min(C,n)\\\max(m-B+C,0)\leq j \leq \min(C,m) \\i+j\leq C} \left(\begin{array}{c}C\\i+j\end{array}\right)\left(\begin{array}{c}A-C\\n-i\end{array}\right)\left(\begin{array}{c}B-C\\m-j\end{array}\right) \end{equation} This can be thought of choosing unordered collections from the 3 disjoint sets $[C]$,$[A]\setminus[C]$ and $[B]\setminus[C]$ and summing over the ways in which $[A]$ and $[B]$-assigned elements can be drawn from $[C]$. TO DO: Generalize this to more than two sets. The key will be to reduce the problem to sampling from disjoint sets again. *Example: You want to travel to 6 countries, of which at least 3 are Spanish speaking and at least 3 are in Europe.* ## Experiments Testing almost everything. ```python # Permutations print("Permutations:") for n in range(10): x = list(range(n)) print('objects: %i\t permutations: %i %i' % (n,len(list(permutations(x))),factorial(n))) #Subsets nn = [2,5,10] mm = [2,5,10] print("\nTotal number of subsets of an n-sized set") for n in nn: n_subsets = 0 for i in range(n+1): n_subsets += binomial(n,i) # choose i out of n print("n: %i\t %i %i" % (n,n_subsets,2**n)) #Number of Partitionings into m Partitions print("\nTotal number of partitionings of an n-sized set into m") for n in nn: for m in mm: n_partitions = 0 for mindex in multisets(n,m): n_partitions += multinomial(n,mindex) print("n: %i m: %i\t %i %i" % (n,m,n_partitions,m**n)) print("\nSubsets Generator:") S = 'A,B,C,D,E'.split(',') for n in range(6): print('choose %i out of %i\t size: %i %i' % (n,len(S),len(list(subsets(n,S))),binomial(len(S),n))) print([''.join(x) for x in subsets(n,S)]) # Class balances when choosing n from k classes print("\nMultiplicities:") print("Class balances when choosing n from k classes") m = 4 for n in range(10): x = list(range(n)) print('objects: %i classes: %i\t size: %i %i' % (n,m,len(list(unordered_multiplicities(n,m))),0)) print(list(unordered_multiplicities(n,m))) # Collections of n objects from k classes with replacement print("\nMultisets:") print("(Collections of n objects from k classes with replacement)") m = 4 for n in range(7): x = list(range(n)) print('objects: %i classes: %i\t size: %i %i' % (n,m,len(list(multisets(n,m))), factorial(n+m-1)/(factorial(n)*factorial(m-1)))) print(list(multisets(n,m))) A = list('1234') ordered_pairs = np.vstack(np.vstack(np.vstack([[[[(a,b,c) for a in A ] for b in A]] for c in A]))) print('\nOrdered Sequences with Replacement %i %i' % (len(ordered_pairs),len(A)**3)) print([''.join(x) for x in ordered_pairs]) unordered_pairs = {tuple(sorted(pair)) for pair in ordered_pairs} print('\nUnordered Collections with Replacement %i %i' % (len(unordered_pairs),factorial(3+len(A)-1)/(factorial(3)*factorial(len(A)-1)))) print([''.join(x) for x in sorted(list(unordered_pairs))]) unordered_pairs_without_replacement = [] for i in range(len(A)): for j in range(i+1,len(A)): for k in range(j+1,len(A)): unordered_pairs_without_replacement+=[(A[i],A[j],A[k])] print('\nUnordered Collections without Replacement %i %i' % (len(unordered_pairs_without_replacement), factorial(len(A))/(factorial(3)*factorial(len(A)-3)))) print([''.join(x) for x in sorted(unordered_pairs_without_replacement)]) def count_choices(n,m,A,B): """ Count choices for drawing n from A and m from B without replacement, where A and B may overlap. """ C = [x for x in A if x in B] a = len(A) b = len(B) c = len(C) i_min = np.max([n-a+c,0]) j_min = np.max([m-b+c,0]) s = 0 for i in range(i_min,np.min([c,n])+1): for j in range(j_min,np.min([c-i,m])+1): s += binomial(c,i+j)*binomial(a-c,n-i)*binomial(b-c,m-j) return s A = 'Spain,Mexico,Cuba'.split(',') # spanish speaking countries B = 'Spain,France,Germany'.split(',') # countries in Europe print("\nChoose from Overlapping Sets") for n in range(len(A)): for m in range(len(B)): S = list(choose(n,m,A,B)) print("Spanish speaking: %i European: %i \t %i %i" % (n,m,len(S),count_choices(n,m,A,B))) print(['-'.join(x) for x in S]) ``` Permutations: objects: 0 permutations: 1 1 objects: 1 permutations: 1 1 objects: 2 permutations: 2 2 objects: 3 permutations: 6 6 objects: 4 permutations: 24 24 objects: 5 permutations: 120 120 objects: 6 permutations: 720 720 objects: 7 permutations: 5040 5040 objects: 8 permutations: 40320 40320 objects: 9 permutations: 362880 362880 Total number of subsets of an n-sized set n: 2 4 4 n: 5 32 32 n: 10 1024 1024 Total number of partitionings of an n-sized set into m n: 2 m: 2 4 4 n: 2 m: 5 25 25 n: 2 m: 10 100 100 n: 5 m: 2 32 32 n: 5 m: 5 3125 3125 n: 5 m: 10 100000 100000 n: 10 m: 2 1024 1024 n: 10 m: 5 9765625 9765625 n: 10 m: 10 10000000000 10000000000 Subsets Generator: choose 0 out of 5 size: 1 1 [''] choose 1 out of 5 size: 5 5 ['A', 'B', 'C', 'D', 'E'] choose 2 out of 5 size: 10 10 ['AB', 'AC', 'AD', 'AE', 'BC', 'BD', 'BE', 'CD', 'CE', 'DE'] choose 3 out of 5 size: 10 10 ['ABC', 'ABD', 'ABE', 'ACD', 'ACE', 'ADE', 'BCD', 'BCE', 'BDE', 'CDE'] choose 4 out of 5 size: 5 5 ['ABCD', 'ABCE', 'ABDE', 'ACDE', 'BCDE'] choose 5 out of 5 size: 1 1 ['ABCDE'] Multiplicities: Class balances when choosing n from k classes objects: 0 classes: 4 size: 1 0 [[0, 0, 0, 0]] objects: 1 classes: 4 size: 1 0 [[1, 0, 0, 0]] objects: 2 classes: 4 size: 2 0 [[1, 1, 0, 0], [2, 0, 0, 0]] objects: 3 classes: 4 size: 3 0 [[1, 1, 1, 0], [2, 1, 0, 0], [3, 0, 0, 0]] objects: 4 classes: 4 size: 5 0 [[1, 1, 1, 1], [2, 1, 1, 0], [2, 2, 0, 0], [3, 1, 0, 0], [4, 0, 0, 0]] objects: 5 classes: 4 size: 6 0 [[2, 1, 1, 1], [2, 2, 1, 0], [3, 1, 1, 0], [3, 2, 0, 0], [4, 1, 0, 0], [5, 0, 0, 0]] objects: 6 classes: 4 size: 9 0 [[2, 2, 1, 1], [2, 2, 2, 0], [3, 1, 1, 1], [3, 2, 1, 0], [3, 3, 0, 0], [4, 1, 1, 0], [4, 2, 0, 0], [5, 1, 0, 0], [6, 0, 0, 0]] objects: 7 classes: 4 size: 11 0 [[2, 2, 2, 1], [3, 2, 1, 1], [3, 2, 2, 0], [3, 3, 1, 0], [4, 1, 1, 1], [4, 2, 1, 0], [4, 3, 0, 0], [5, 1, 1, 0], [5, 2, 0, 0], [6, 1, 0, 0], [7, 0, 0, 0]] objects: 8 classes: 4 size: 15 0 [[2, 2, 2, 2], [3, 2, 2, 1], [3, 3, 1, 1], [3, 3, 2, 0], [4, 2, 1, 1], [4, 2, 2, 0], [4, 3, 1, 0], [4, 4, 0, 0], [5, 1, 1, 1], [5, 2, 1, 0], [5, 3, 0, 0], [6, 1, 1, 0], [6, 2, 0, 0], [7, 1, 0, 0], [8, 0, 0, 0]] objects: 9 classes: 4 size: 18 0 [[3, 2, 2, 2], [3, 3, 2, 1], [3, 3, 3, 0], [4, 2, 2, 1], [4, 3, 1, 1], [4, 3, 2, 0], [4, 4, 1, 0], [5, 2, 1, 1], [5, 2, 2, 0], [5, 3, 1, 0], [5, 4, 0, 0], [6, 1, 1, 1], [6, 2, 1, 0], [6, 3, 0, 0], [7, 1, 1, 0], [7, 2, 0, 0], [8, 1, 0, 0], [9, 0, 0, 0]] Multisets: (Collections of n objects from k classes with replacement) objects: 0 classes: 4 size: 1 1 [[0, 0, 0, 0]] objects: 1 classes: 4 size: 4 4 [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]] objects: 2 classes: 4 size: 10 10 [[1, 1, 0, 0], [1, 0, 1, 0], [1, 0, 0, 1], [0, 1, 1, 0], [0, 1, 0, 1], [0, 0, 1, 1], [2, 0, 0, 0], [0, 2, 0, 0], [0, 0, 2, 0], [0, 0, 0, 2]] objects: 3 classes: 4 size: 20 20 [[1, 1, 1, 0], [1, 1, 0, 1], [1, 0, 1, 1], [0, 1, 1, 1], [2, 1, 0, 0], [2, 0, 1, 0], [2, 0, 0, 1], [1, 2, 0, 0], [1, 0, 2, 0], [1, 0, 0, 2], [0, 2, 1, 0], [0, 2, 0, 1], [0, 1, 2, 0], [0, 1, 0, 2], [0, 0, 2, 1], [0, 0, 1, 2], [3, 0, 0, 0], [0, 3, 0, 0], [0, 0, 3, 0], [0, 0, 0, 3]] objects: 4 classes: 4 size: 35 35 [[1, 1, 1, 1], [2, 1, 1, 0], [2, 1, 0, 1], [2, 0, 1, 1], [1, 2, 1, 0], [1, 2, 0, 1], [1, 1, 2, 0], [1, 1, 0, 2], [1, 0, 2, 1], [1, 0, 1, 2], [0, 2, 1, 1], [0, 1, 2, 1], [0, 1, 1, 2], [2, 2, 0, 0], [2, 0, 2, 0], [2, 0, 0, 2], [0, 2, 2, 0], [0, 2, 0, 2], [0, 0, 2, 2], [3, 1, 0, 0], [3, 0, 1, 0], [3, 0, 0, 1], [1, 3, 0, 0], [1, 0, 3, 0], [1, 0, 0, 3], [0, 3, 1, 0], [0, 3, 0, 1], [0, 1, 3, 0], [0, 1, 0, 3], [0, 0, 3, 1], [0, 0, 1, 3], [4, 0, 0, 0], [0, 4, 0, 0], [0, 0, 4, 0], [0, 0, 0, 4]] objects: 5 classes: 4 size: 56 56 [[2, 1, 1, 1], [1, 2, 1, 1], [1, 1, 2, 1], [1, 1, 1, 2], [2, 2, 1, 0], [2, 2, 0, 1], [2, 1, 2, 0], [2, 1, 0, 2], [2, 0, 2, 1], [2, 0, 1, 2], [1, 2, 2, 0], [1, 2, 0, 2], [1, 0, 2, 2], [0, 2, 2, 1], [0, 2, 1, 2], [0, 1, 2, 2], [3, 1, 1, 0], [3, 1, 0, 1], [3, 0, 1, 1], [1, 3, 1, 0], [1, 3, 0, 1], [1, 1, 3, 0], [1, 1, 0, 3], [1, 0, 3, 1], [1, 0, 1, 3], [0, 3, 1, 1], [0, 1, 3, 1], [0, 1, 1, 3], [3, 2, 0, 0], [3, 0, 2, 0], [3, 0, 0, 2], [2, 3, 0, 0], [2, 0, 3, 0], [2, 0, 0, 3], [0, 3, 2, 0], [0, 3, 0, 2], [0, 2, 3, 0], [0, 2, 0, 3], [0, 0, 3, 2], [0, 0, 2, 3], [4, 1, 0, 0], [4, 0, 1, 0], [4, 0, 0, 1], [1, 4, 0, 0], [1, 0, 4, 0], [1, 0, 0, 4], [0, 4, 1, 0], [0, 4, 0, 1], [0, 1, 4, 0], [0, 1, 0, 4], [0, 0, 4, 1], [0, 0, 1, 4], [5, 0, 0, 0], [0, 5, 0, 0], [0, 0, 5, 0], [0, 0, 0, 5]] objects: 6 classes: 4 size: 84 84 [[2, 2, 1, 1], [2, 1, 2, 1], [2, 1, 1, 2], [1, 2, 2, 1], [1, 2, 1, 2], [1, 1, 2, 2], [2, 2, 2, 0], [2, 2, 0, 2], [2, 0, 2, 2], [0, 2, 2, 2], [3, 1, 1, 1], [1, 3, 1, 1], [1, 1, 3, 1], [1, 1, 1, 3], [3, 2, 1, 0], [3, 2, 0, 1], [3, 1, 2, 0], [3, 1, 0, 2], [3, 0, 2, 1], [3, 0, 1, 2], [2, 3, 1, 0], [2, 3, 0, 1], [2, 1, 3, 0], [2, 1, 0, 3], [2, 0, 3, 1], [2, 0, 1, 3], [1, 3, 2, 0], [1, 3, 0, 2], [1, 2, 3, 0], [1, 2, 0, 3], [1, 0, 3, 2], [1, 0, 2, 3], [0, 3, 2, 1], [0, 3, 1, 2], [0, 2, 3, 1], [0, 2, 1, 3], [0, 1, 3, 2], [0, 1, 2, 3], [3, 3, 0, 0], [3, 0, 3, 0], [3, 0, 0, 3], [0, 3, 3, 0], [0, 3, 0, 3], [0, 0, 3, 3], [4, 1, 1, 0], [4, 1, 0, 1], [4, 0, 1, 1], [1, 4, 1, 0], [1, 4, 0, 1], [1, 1, 4, 0], [1, 1, 0, 4], [1, 0, 4, 1], [1, 0, 1, 4], [0, 4, 1, 1], [0, 1, 4, 1], [0, 1, 1, 4], [4, 2, 0, 0], [4, 0, 2, 0], [4, 0, 0, 2], [2, 4, 0, 0], [2, 0, 4, 0], [2, 0, 0, 4], [0, 4, 2, 0], [0, 4, 0, 2], [0, 2, 4, 0], [0, 2, 0, 4], [0, 0, 4, 2], [0, 0, 2, 4], [5, 1, 0, 0], [5, 0, 1, 0], [5, 0, 0, 1], [1, 5, 0, 0], [1, 0, 5, 0], [1, 0, 0, 5], [0, 5, 1, 0], [0, 5, 0, 1], [0, 1, 5, 0], [0, 1, 0, 5], [0, 0, 5, 1], [0, 0, 1, 5], [6, 0, 0, 0], [0, 6, 0, 0], [0, 0, 6, 0], [0, 0, 0, 6]] Ordered Sequences with Replacement 64 64 ['111', '211', '311', '411', '121', '221', '321', '421', '131', '231', '331', '431', '141', '241', '341', '441', '112', '212', '312', '412', '122', '222', '322', '422', '132', '232', '332', '432', '142', '242', '342', '442', '113', '213', '313', '413', '123', '223', '323', '423', '133', '233', '333', '433', '143', '243', '343', '443', '114', '214', '314', '414', '124', '224', '324', '424', '134', '234', '334', '434', '144', '244', '344', '444'] Unordered Collections with Replacement 20 20 ['111', '112', '113', '114', '122', '123', '124', '133', '134', '144', '222', '223', '224', '233', '234', '244', '333', '334', '344', '444'] Unordered Collections without Replacement 4 4 ['123', '124', '134', '234'] Choose from Overlapping Sets Spanish speaking: 0 European: 0 1 1 [''] Spanish speaking: 0 European: 1 3 3 ['France', 'Germany', 'Spain'] Spanish speaking: 0 European: 2 3 3 ['France-Germany', 'France-Spain', 'Germany-Spain'] Spanish speaking: 1 European: 0 3 3 ['Mexico', 'Cuba', 'Spain'] Spanish speaking: 1 European: 1 8 8 ['Mexico-France', 'Mexico-Germany', 'Cuba-France', 'Cuba-Germany', 'Mexico-Spain', 'Cuba-Spain', 'France-Spain', 'Germany-Spain'] Spanish speaking: 1 European: 2 7 7 ['Mexico-France-Germany', 'Cuba-France-Germany', 'Mexico-France-Spain', 'Mexico-Germany-Spain', 'Cuba-France-Spain', 'Cuba-Germany-Spain', 'France-Germany-Spain'] Spanish speaking: 2 European: 0 3 3 ['Mexico-Cuba', 'Mexico-Spain', 'Cuba-Spain'] Spanish speaking: 2 European: 1 7 7 ['Mexico-Cuba-France', 'Mexico-Cuba-Germany', 'Mexico-Cuba-Spain', 'Mexico-France-Spain', 'Mexico-Germany-Spain', 'Cuba-France-Spain', 'Cuba-Germany-Spain'] Spanish speaking: 2 European: 2 5 5 ['Mexico-Cuba-France-Germany', 'Mexico-Cuba-France-Spain', 'Mexico-Cuba-Germany-Spain', 'Mexico-France-Germany-Spain', 'Cuba-France-Germany-Spain']
\section{(Ab)using Exceptions for Type Switching} \label{sec:xpm} Several authors had noted the relationship between exception handling and type switching before~\cite{Glew99,ML2000}. Not surprisingly, the exception handling mechanism of \Cpp{} can be abused to implement the first-fit semantics of a type switch statement. The idea is to harness the fact that catch-handlers in \Cpp{} essentially use first-fit semantics to decide which one is going to handle a given exception. The only problem is to raise an exception with a static type equal to the dynamic type of the subject. To do this, we employ the \emph{polymorphic exception} idiom~\cite{PolyExcept} that introduces a virtual function \code{virtual void raise() const = 0;} into the base class, overridden by each derived class in syntactically the same way: \code{throw *this;}. The match statement then simply calls \code{raise} on its subject, while case clauses are turned into catch-handlers. The exact name of the function is not important, and is communicated to the library via \code{bindings}. The \code{raise} member function can be seen as an analog of the \code{accept} member function in the visitor design pattern, whose main purpose is to discover subject's most specific type. The analog of a call to \code{visit} to communicate that type is replaced, in this scheme, with exception unwinding mechanism. Just because we can, it does not mean we should abuse the exception handling mechanism to give us the desired control flow. In the table-driven approach commonly used in high-performance implementations of exception handling, the speed of handling an exception is sacrificed to provide a zero execution-time overhead for when exceptions are not thrown~\cite{Schilling98}. Using exception handling to implement type switching will reverse the common and exceptional cases, significantly degrading performance. As can be seen in Figure\ref{fig:DCastVis1}, matching the type of the first case clause with polymorphic exception approach takes more than 7000 cycles and then grows linearly (with the position of case clause in the match statement), making it the slowest approach. The numbers illustrate why exception handling should only be used to deal with exceptional and not common cases. Despite its total impracticality, the approach gave us a very practical idea of harnessing a \Cpp{} compiler to do \emph{redundancy checking} at compile time. \subsection{Redundancy Checking} \label{sec:redun} Redundancy checking is only applicable to first-fit semantics of the match statement, and warns the user of any case clause that will never be entered because of a preceding one being more general. We provide a library-configuration flag, which, when defined, effectively turns the entire match statement into a try-catch block with handlers accepting the target types of the case clauses. This forces the compiler to give warning when a more general catch handler preceds a more specific one effectively performing redundancy checking for us, e.g.: \begin{lstlisting} filename.cpp(55): warning C4286: 'ipr::Decl*' : is caught by base class ('ipr::Stmt*') on line 42 \end{lstlisting} \noindent Note that the message contains both the line number of the redundant case clause (55) and the line number of the case clause that makes it redundant (42). Unfortunately, the flag cannot be always enabled, as the case labels of the underlying switch statement have to be eliminated in order to render a syntactically correct program. Nevertheless, we found the redundancy checking facility of the library extremely useful when rewriting visitor-based code: even though the order of overrides in a visitor's implementation does not matter, for some reason more general ones were inclined to happen before specific ones in the code we looked at. Perhaps programmers are inclined to follow the class declaration order when defining and implementing visitors. A related \emph{completeness checking} -- test of whether a given match statement covers all possible cases -- needs to be reconsidered for extensible data types like classes, since one can always add a new variant to it. Completeness checking in this case may simply become equivalent to ensuring that there is either a default clause in the type switch or a clause with the static type of a subject as a target type. In fact, our library has an analog of a default clause called \code{Otherwise}-clause, which is implemented under the hood exactly as a regular case clause with the subject's static type as a target type.
{-# OPTIONS --show-irrelevant #-} open import Agda.Builtin.Bool open import Agda.Builtin.Equality postulate A : Set f : .(Bool → A) → Bool → A mutual X : .A → Bool → A X = _ test : (x : Bool → A) → X (x true) ≡ f x test x = refl
@testset "150.evaluate-reverse-polish-notation.jl" begin @test eval_rpn(["4", "13", "5", "/", "+"]) == 6 @test eval_rpn(["2", "1", "+", "3", "*"]) == 9 @test eval_rpn(["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]) == 22 @test eval_rpn(["2", "1", "-", "3", "*"]) == 3 end
!############################################################################## !# **************************************************************************** !# <name> stokes2d_method1_mg </name> !# **************************************************************************** !# !# <purpose> !# This module is a demonstation program how to solve a Stokes !# problem on a simple domain. !# !# The routine uses the simple-VANKA smoother for 2D saddle point problems, !# Jacobi-Type, for a multigrid solver. !# </purpose> !############################################################################## module stokes2d_method1_mg use fsystem use storage use linearsolver use boundary use cubature use derivatives use matrixfilters use vectorfilters use discretebc use bcassembly use triangulation use element use spatialdiscretisation use linearsystemscalar use linearsystemblock use coarsegridcorrection use multilevelprojection use spdiscprojection use filtersupport use scalarpde use bilinearformevaluation use linearformevaluation use discretebc use ucd use collection, only: t_collection use pprocerror use genoutput use stokes2d_callback implicit none !<types> !<typeblock description="Type block defining all information about one level"> type t_level ! An object for saving the triangulation on the domain type(t_triangulation) :: rtriangulation ! Cubature info structure which encapsules the cubature formula type(t_scalarCubatureInfo) :: rcubatureInfo ! An object specifying the discretisation (structure of the ! solution, trial/test functions,...) type(t_blockDiscretisation) :: rdiscretisation ! A system matrix for that specific level. The matrix will receive the ! discrete Laplace operator. type(t_matrixBlock) :: rmatrix ! B1-matrix for that specific level. type(t_matrixScalar) :: rmatrixB1 ! B2-matrix for that specific level. type(t_matrixScalar) :: rmatrixB2 ! A variable describing the discrete boundary conditions. type(t_discreteBC) :: rdiscreteBC ! A filter chain that describes how to filter the matrix/vector ! before/during the solution process. The filters usually implement ! boundary conditions. type(t_filterChain), dimension(1) :: RfilterChain ! Number of filters in the filter chain integer :: nfilters end type !</typeblock> !</types> contains ! *************************************************************************** !<subroutine> subroutine stokes2d_1_mg !<description> ! This is an all-in-one stokes solver for directly solving a stokes ! problem without making use of special features like collections ! and so on. The routine performs the following tasks: ! ! 1.) Read in parametrisation ! 2.) Read in triangulation ! 3.) Set up RHS ! 4.) Set up matrix ! 5.) Create solver structure ! 6.) Solve the problem ! 7.) Write solution to GMV file ! 8.) Release all variables, finish !</description> !</subroutine> ! Definitions of variables. ! ! We need a couple of variables for this problem. Let us see... ! ! An array of problem levels for the multigrid solver type(t_level), dimension(:), pointer :: Rlevels ! An object for saving the domain: type(t_boundary) :: rboundary ! An object specifying the discretisation. ! This contains also information about trial/test functions,... type(t_blockDiscretisation) :: rprjDiscretisation ! A bilinear and linear form describing the analytic problem to solve type(t_bilinearForm) :: rform type(t_linearForm) :: rlinform ! A block matrix and a couple of block vectors. These will be filled ! with data for the linear solver. type(t_vectorBlock) :: rvector,rrhs,rtempBlock,rprjVector ! A set of variables describing the analytic and discrete boundary ! conditions. type(t_boundaryRegion) :: rboundaryRegion type(t_discreteBC), target :: rprjDiscreteBC ! A solver node that accepts parameters for the linear solver type(t_linsolNode), pointer :: p_rsolverNode,p_rpreconditioner,& p_rcoarseGridSolver,p_rsmoother ! An array for the system matrix(matrices) during the initialisation of ! the linear solver. type(t_matrixBlock), dimension(:), pointer :: Rmatrices ! One level of multigrid type(t_linsolMG2LevelInfo), pointer :: p_rlevelInfo ! NLMIN receives the level of the coarse grid. integer :: NLMIN ! NLMAX receives the level where we want to solve. integer :: NLMAX ! Viscosity parameter nu = 1/Re real(DP) :: dnu ! Error indicator during initialisation of the solver integer :: ierror ! Output block for UCD output to GMV file type(t_ucdExport) :: rexport character(len=SYS_STRLEN) :: sucddir real(DP), dimension(:), pointer :: p_Ddata,p_Ddata2 ! A counter variable integer :: i ! Path to the mesh character(len=SYS_STRLEN) :: spredir ! A collection structure for post-processing type(t_collection) :: rcollection ! Error data structures for post-processing type(t_errorScVec) :: rerrorU, rerrorP ! Error arrays for post-processing real(DP), dimension(2), target :: DerrorUL2, DerrorUH1 real(DP), dimension(1), target :: DerrorPL2 ! Ok, let us start. ! ! We want to solve our Stokes problem on level... NLMIN = 2 NLMAX = 7 ! Viscosity parameter: dnu = 1.0_DP ! -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ! Read the domain, read the mesh, refine ! -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ! Allocate memory for all levels allocate(Rlevels(NLMIN:NLMAX)) ! Get the path $PREDIR from the environment, where to read .prm/.tri files ! from. If that does not exist, write to the directory "./pre". if (.not. sys_getenv_string("PREDIR", spredir)) spredir = "./pre" ! At first, read in the parametrisation of the boundary and save ! it to rboundary. call boundary_read_prm(rboundary, trim(spredir)//"/QUAD.prm") ! Now read in the basic triangulation into our coarse level. call tria_readTriFile2D (Rlevels(NLMIN)%rtriangulation, & trim(spredir)//"/QUAD.tri", rboundary) ! Refine the mesh up to the minimum level call tria_quickRefine2LevelOrdering (NLMIN-1,& Rlevels(NLMIN)%rtriangulation,rboundary) ! And create information about adjacencies and everything one needs ! from a triangulation. call tria_initStandardMeshFromRaw (Rlevels(NLMIN)%rtriangulation,& rboundary) ! Now refine the grid for the fine levels. do i = NLMIN+1, NLMAX ! Refine the grid using the 2-Level-Ordering algorithm call tria_refine2LevelOrdering(Rlevels(i-1)%rtriangulation,& Rlevels(i)%rtriangulation,rboundary) ! Create a standard mesh call tria_initStandardMeshFromRaw(Rlevels(i)%rtriangulation,& rboundary) end do ! -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ! Set up a discretisation structure which tells the code which ! finite element to use ! -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ! Now we can start to initialise the discretisation. At first, set up ! a block discretisation structure that specifies 3 blocks in the ! solution vector. do i = NLMIN, NLMAX call spdiscr_initBlockDiscr (Rlevels(i)%rdiscretisation, 3, & Rlevels(i)%rtriangulation, rboundary) end do ! rdiscretisation%RspatialDiscr is a list of scalar ! discretisation structures for every component of the solution vector. ! We have a solution vector with three components: ! Component 1 = X-velocity ! Component 2 = Y-velocity ! Component 3 = Pressure do i = NLMIN, NLMAX ! For simplicity, we set up one discretisation structure for the ! velocity... call spdiscr_initDiscr_simple (& Rlevels(i)%rdiscretisation%RspatialDiscr(1),& EL_EM30, Rlevels(i)%rtriangulation, rboundary) ! ...and copy this structure also to the discretisation structure ! of the 2nd component (Y-velocity). This needs no additional memory, ! as both structures will share the same dynamic information afterwards. call spdiscr_duplicateDiscrSc (& Rlevels(i)%rdiscretisation%RspatialDiscr(1),& Rlevels(i)%rdiscretisation%RspatialDiscr(2)) ! For the pressure (3rd component), we set up a separate discretisation ! structure, as this uses different finite elements for trial and test ! functions. call spdiscr_deriveSimpleDiscrSc (Rlevels(i)%rdiscretisation%RspatialDiscr(1), & EL_Q0, Rlevels(i)%rdiscretisation%RspatialDiscr(3)) end do ! -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ! Set up an cubature info structure to tell the code which cubature ! formula to use ! -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- do i = NLMIN, NLMAX ! Create an cubature information structure which tells the code ! the cubature formula to use. Standard: Gauss 3x3. call spdiscr_createDefCubStructure(& Rlevels(i)%rdiscretisation%RspatialDiscr(1),& Rlevels(i)%rcubatureInfo,CUB_GEN_AUTO_G3) end do ! -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ! Create a 3x3 block matrix with the operator ! -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- do i = NLMIN, NLMAX ! Initialise the block matrix with default values based on ! the discretisation. call lsysbl_createMatBlockByDiscr (Rlevels(i)%rdiscretisation,& Rlevels(i)%rmatrix) ! Inform the matrix that we build a saddle-point problem. ! Normally, imatrixSpec has the value LSYSBS_MSPEC_GENERAL, ! but probably some solvers can use the special structure later. Rlevels(i)%rmatrix%imatrixSpec = LSYSBS_MSPEC_SADDLEPOINT ! Now as the discretisation is set up, we can start to generate ! the structure of the system matrix which is to solve. ! We create that directly in the block (1,1) of the block matrix ! using the discretisation structure of the first block. ! ! Create the matrix structure of the X-velocity. call bilf_createMatrixStructure (& Rlevels(i)%rdiscretisation%RspatialDiscr(1),& LSYSSC_MATRIX9, Rlevels(i)%rmatrix%RmatrixBlock(1,1)) ! In the Stokes problem, the matrix for the Y-velocity is identical to ! the matrix for the X-velocity; both are Laplace-matrices! ! Therefore, we can simply make a copy of the matrix for the X-velocity. ! This we do later after the entries are created. ! ! In the global system, there are two coupling matrices B1 and B2. ! Both have the same structure. ! ! ( A B1 ) ! ( A B2 ) ! ( B1^T B2^T ) ! ! Create the matrices structure of the pressure using the 3rd ! spatial discretisation structure in p_rdiscretisation%RspatialDiscr. call bilf_createMatrixStructure (& Rlevels(i)%rdiscretisation%RspatialDiscr(3),& LSYSSC_MATRIX9, Rlevels(i)%rmatrixB1,& Rlevels(i)%rdiscretisation%RspatialDiscr(1)) ! Duplicate the B1 matrix structure to the B2 matrix, so use ! lsyssc_duplicateMatrix to create B2. Share the matrix ! structure between B1 and B2 (B1 is the parent and B2 the child). ! Do not create a content array yet, it will be created by ! the assembly routines later. call lsyssc_duplicateMatrix (Rlevels(i)%rmatrixB1, Rlevels(i)%rmatrixB2,& LSYSSC_DUP_COPY, LSYSSC_DUP_REMOVE) ! And now to the entries of the matrix. For assembling of the entries, ! we need a bilinear form, which first has to be set up manually. ! We specify the bilinear form (grad Psi_j, grad Phi_i) for the ! scalar system matrix in 2D. rform%itermCount = 2 rform%Idescriptors(1,1) = DER_DERIV_X rform%Idescriptors(2,1) = DER_DERIV_X rform%Idescriptors(1,2) = DER_DERIV_Y rform%Idescriptors(2,2) = DER_DERIV_Y ! In the standard case, we have constant coefficients: rform%ballCoeffConstant = .true. rform%Dcoefficients(1) = dnu rform%Dcoefficients(2) = dnu ! Now we can build the matrix entries. ! We specify the callback function coeff_Laplace for the coefficients. ! As long as we use constant coefficients, this routine is not used. ! By specifying ballCoeffConstant = .FALSE. above, ! the framework will call the callback routine to get analytical data. ! ! We pass our collection structure as well to this routine, ! so the callback routine has access to everything what is ! in the collection. ! ! Build the X-velocity matrix: call bilf_buildMatrixScalar (rform,.true.,& Rlevels(i)%rmatrix%RmatrixBlock(1,1), Rlevels(i)%rcubatureInfo, coeff_Stokes_2D) ! Duplicate the matrix to the Y-velocity matrix, share structure and ! content between them (as the matrices are the same). call lsyssc_duplicateMatrix (Rlevels(i)%rmatrix%RmatrixBlock(1,1),& Rlevels(i)%rmatrix%RmatrixBlock(2,2),LSYSSC_DUP_SHARE,LSYSSC_DUP_SHARE) ! Manually change the discretisation structure of the Y-velocity ! matrix to the Y-discretisation structure. ! Ok, we use the same discretisation structure for both, X- and Y-velocity, ! so this is not really necessary - we do this for sure... call lsyssc_assignDiscretisation (Rlevels(i)%rmatrix%RmatrixBlock(2,2),& Rlevels(i)%rdiscretisation%RspatialDiscr(2)) ! Build the first pressure matrix B1. ! Again first set up the bilinear form, then call the matrix assembly. rform%itermCount = 1 rform%Idescriptors(1,1) = DER_FUNC rform%Idescriptors(2,1) = DER_DERIV_X ! In the standard case, we have constant coefficients: rform%ballCoeffConstant = .true. rform%Dcoefficients(1) = -1.0_DP call bilf_buildMatrixScalar (rform,.true.,Rlevels(i)%rmatrixB1,& Rlevels(i)%rcubatureInfo,coeff_Pressure_2D) ! Build the second pressure matrix B2. ! Again first set up the bilinear form, then call the matrix assembly. rform%itermCount = 1 rform%Idescriptors(1,1) = DER_FUNC rform%Idescriptors(2,1) = DER_DERIV_Y ! In the standard case, we have constant coefficients: rform%ballCoeffConstant = .true. rform%Dcoefficients(1) = -1.0_DP call bilf_buildMatrixScalar (rform,.true.,Rlevels(i)%rmatrixB2,& Rlevels(i)%rcubatureInfo,coeff_Pressure_2D) ! The B1/B2 matrices exist up to now only in our local problem structure. ! Put a copy of them into the block matrix. ! ! Note that we share the structure of B1/B2 with those B1/B2 of the ! block matrix, while we create copies of the entries. The reason is ! that these matrices are modified for boundary conditions later. call lsyssc_duplicateMatrix (Rlevels(i)%rmatrixB1, & Rlevels(i)%rmatrix%RmatrixBlock(1,3),LSYSSC_DUP_SHARE,LSYSSC_DUP_COPY) call lsyssc_duplicateMatrix (Rlevels(i)%rmatrixB2, & Rlevels(i)%rmatrix%RmatrixBlock(2,3),LSYSSC_DUP_SHARE,LSYSSC_DUP_COPY) ! Furthermore, put B1^T and B2^T to the block matrix. call lsyssc_transposeMatrix (Rlevels(i)%rmatrixB1, & Rlevels(i)%rmatrix%RmatrixBlock(3,1),LSYSSC_TR_VIRTUAL) call lsyssc_transposeMatrix (Rlevels(i)%rmatrixB2, & Rlevels(i)%rmatrix%RmatrixBlock(3,2),LSYSSC_TR_VIRTUAL) end do ! -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ! Create RHS and solution vectors ! -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ! Next step: Create a RHS vector, a solution vector and a temporary ! vector. All are filled with zero. call lsysbl_createVectorBlock (Rlevels(NLMAX)%rdiscretisation,rrhs,.true.) call lsysbl_createVectorBlock (Rlevels(NLMAX)%rdiscretisation,rvector,.true.) call lsysbl_createVectorBlock (Rlevels(NLMAX)%rdiscretisation,rtempBlock,.true.) ! The vector structure is ready but the entries are missing. ! So the next thing is to calculate the content of that vector. ! ! At first set up the corresponding linear form (f,Phi_j): rlinform%itermCount = 1 rlinform%Idescriptors(1) = DER_FUNC ! ... and then discretise the RHS to the first two subvectors of ! the block vector using the discretisation structure of the ! corresponding blocks. ! ! Note that the vector is unsorted after calling this routine! call linf_buildVectorScalar (& rlinform,.true.,rrhs%RvectorBlock(1),Rlevels(NLMAX)%rcubatureInfo,coeff_RHS_X_2D) call linf_buildVectorScalar (& rlinform,.true.,rrhs%RvectorBlock(2),Rlevels(NLMAX)%rcubatureInfo,coeff_RHS_Y_2D) ! The third subvector must be zero - as it represents the RHS of ! the equation "div(u) = 0". call lsyssc_clearVector(rrhs%RvectorBlock(3)) ! Clear the solution vector on the finest level. call lsysbl_clearVector(rvector) ! -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ! Assembly of matrices/vectors finished ! -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ! Discretise the boundary conditions and apply them to the matrix/RHS/sol. ! -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- do i = NLMIN, NLMAX ! For implementing boundary conditions, we use a `filter technique with ! discretised boundary conditions`. This means, we first have to calculate ! a discrete version of the analytic BC, which we can implement into the ! solution/RHS vectors using the corresponding filter. ! ! Create a t_discreteBC structure where we store all discretised boundary ! conditions. call bcasm_initDiscreteBC(Rlevels(i)%rdiscreteBC) ! We first set up the boundary conditions for the X-velocity, then those ! of the Y-velocity. ! ! We "know" already (from the problem definition) that we have four boundary ! segments in the domain. Each of these, we want to use for enforcing ! some kind of boundary condition. ! ! We ask the boundary routines to create a "boundary region" - which is ! simply a part of the boundary corresponding to a boundary segment. ! A boundary region roughly contains the type, the min/max parameter value ! and whether the endpoints are inside the region or not. call boundary_createRegion(rboundary,1,1,rboundaryRegion) ! The endpoint of this segment should also be Dirichlet. We set this by ! changing the region properties in rboundaryRegion. rboundaryRegion%iproperties = BDR_PROP_WITHSTART + BDR_PROP_WITHEND ! We use this boundary region and specify that we want to have Dirichlet ! boundary there. The following call does the following: ! - Create Dirichlet boundary conditions on the region rboundaryRegion. ! We specify icomponent="1" to indicate that we set up the ! Dirichlet BC`s for the first (here: one and only) component in the ! solution vector. ! - Discretise the boundary condition so that the BC`s can be applied ! to matrices and vectors ! - Add the calculated discrete BC`s to Rlevels(i)%rdiscreteBC for later use. call bcasm_newDirichletBConRealBD (Rlevels(i)%rdiscretisation,1,& rboundaryRegion,Rlevels(i)%rdiscreteBC,& getBoundaryValues_2D) ! Edge 2 is Neumann boundary, so it is commented out. ! CALL boundary_createRegion(rboundary,1,2,rboundaryRegion) ! CALL bcasm_newDirichletBConRealBD (Rlevels(i)%rdiscretisation,1,& ! rboundaryRegion,Rlevels(i)%rdiscreteBC,& ! getBoundaryValues_2D) ! Edge 3 of boundary component 1. call boundary_createRegion(rboundary,1,3,rboundaryRegion) call bcasm_newDirichletBConRealBD (Rlevels(i)%rdiscretisation,1,& rboundaryRegion,Rlevels(i)%rdiscreteBC,& getBoundaryValues_2D) ! Edge 4 of boundary component 1. That is it. call boundary_createRegion(rboundary,1,4,rboundaryRegion) call bcasm_newDirichletBConRealBD (Rlevels(i)%rdiscretisation,1,& rboundaryRegion,Rlevels(i)%rdiscreteBC,& getBoundaryValues_2D) ! Now continue with defining the boundary conditions of the Y-velocity: ! ! Define edge 1. call boundary_createRegion(rboundary,1,1,rboundaryRegion) ! Edge with start- and endpoint. rboundaryRegion%iproperties = BDR_PROP_WITHSTART + BDR_PROP_WITHEND ! As we define the Y-velocity, we now set icomponent=2 in the following call. call bcasm_newDirichletBConRealBD (Rlevels(i)%rdiscretisation,2,& rboundaryRegion,Rlevels(i)%rdiscreteBC,& getBoundaryValues_2D) ! Edge 2 is Neumann boundary, so it is commented out. ! CALL boundary_createRegion(rboundary,1,2,rboundaryRegion) ! CALL bcasm_newDirichletBConRealBD (Rlevels(i)%rdiscretisation,2,& ! rboundaryRegion,Rlevels(i)%rdiscreteBC,& ! getBoundaryValues_2D) ! Edge 3 of boundary component 1. call boundary_createRegion(rboundary,1,3,rboundaryRegion) call bcasm_newDirichletBConRealBD (Rlevels(i)%rdiscretisation,2,& rboundaryRegion,Rlevels(i)%rdiscreteBC,& getBoundaryValues_2D) ! Edge 4 of boundary component 1. That is it. call boundary_createRegion(rboundary,1,4,rboundaryRegion) call bcasm_newDirichletBConRealBD (Rlevels(i)%rdiscretisation,2,& rboundaryRegion,Rlevels(i)%rdiscreteBC,& getBoundaryValues_2D) ! Next step is to implement boundary conditions into the matrix. ! This is done using a matrix filter for discrete boundary conditions. ! The discrete boundary conditions are already attached to the ! matrix. Call the appropriate matrix filter that modifies the matrix ! according to the boundary conditions. call matfil_discreteBC (Rlevels(i)%rmatrix,Rlevels(i)%rdiscreteBC) ! Create a filter chain for the solver that implements boundary conditions ! during the solution process. call filter_initFilterChain (Rlevels(i)%RfilterChain,Rlevels(i)%nfilters) call filter_newFilterDiscBCDef (& Rlevels(i)%RfilterChain,Rlevels(i)%nfilters,Rlevels(i)%rdiscreteBC) end do ! Also implement the discrete boundary conditions on the finest level ! onto our right-hand-side and solution vectors. call vecfil_discreteBCrhs (rrhs,Rlevels(NLMAX)%rdiscreteBC) call vecfil_discreteBCsol (rvector,Rlevels(NLMAX)%rdiscreteBC) ! -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ! Set up a linear solver ! -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ! Now we have to build up the level information for multigrid. ! ! Create a Multigrid-solver. Attach the above filter chain ! to the solver, so that the solver automatically filters ! the vector during the solution process. call linsol_initMultigrid2 (p_rsolverNode,NLMAX-NLMIN+1) ! Set up a BiCGStab solver with VANKA preconditioning as coarse grid solver: call linsol_initVANKA (p_rpreconditioner,1.0_DP,LINSOL_VANKA_2DNAVST) call linsol_initBiCGStab (p_rcoarseGridSolver,p_rpreconditioner,& Rlevels(NLMIN)%RfilterChain) ! The coarse grid in multigrid is always grid 1! call linsol_getMultigrid2Level (p_rsolverNode,1,p_rlevelInfo) p_rlevelInfo%p_rcoarseGridSolver => p_rcoarseGridSolver p_rlevelInfo%p_rfilterChain => Rlevels(NLMIN)%RfilterChain ! Now set up the other levels... do i = NLMIN+1, NLMAX ! Set up the VANKA smoother. call linsol_initVANKA (p_rsmoother,1.0_DP,LINSOL_VANKA_2DNAVST) ! We will use 4 smoothing steps with damping parameter 0.7 call linsol_convertToSmoother(p_rsmoother, 4, 0.7_DP) ! And add this multi-grid level. We will use the same smoother ! for pre- and post-smoothing. call linsol_getMultigrid2Level (p_rsolverNode,i-NLMIN+1,p_rlevelInfo) p_rlevelInfo%p_rpresmoother => p_rsmoother p_rlevelInfo%p_rpostsmoother => p_rsmoother p_rlevelInfo%p_rfilterChain => Rlevels(i)%RfilterChain end do ! Set the output level of the solver to 2 for some output p_rsolverNode%ioutputLevel = 2 ! Attach the system matrices to the solver. ! ! We copy our matrices to a big matrix array and transfer that ! to the setMatrices routines. This intitialises then the matrices ! on all levels according to that array. Note that this does not ! allocate new memory, we create only "links" to existing matrices ! into Rmatrices(:)! allocate(Rmatrices(NLMIN:NLMAX)) do i = NLMIN, NLMAX call lsysbl_duplicateMatrix (Rlevels(i)%rmatrix,& Rmatrices(i),LSYSSC_DUP_SHARE,LSYSSC_DUP_SHARE) end do call linsol_setMatrices(p_RsolverNode,Rmatrices(NLMIN:NLMAX)) ! We can release Rmatrices immediately -- as long as we do not ! release Rlevels(i)%rmatrix! do i=NLMIN,NLMAX call lsysbl_releaseMatrix (Rmatrices(i)) end do deallocate(Rmatrices) ! Initialise structure/data of the solver. This allows the ! solver to allocate memory / perform some precalculation ! to the problem. call linsol_initStructure (p_rsolverNode, ierror) if (ierror .ne. LINSOL_ERR_NOERROR) then call output_line("Matrix structure invalid!",OU_CLASS_ERROR) call sys_halt() end if call linsol_initData (p_rsolverNode, ierror) if (ierror .ne. LINSOL_ERR_NOERROR) then call output_line("Matrix singular!",OU_CLASS_ERROR) call sys_halt() end if ! -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ! Solve the system ! -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ! Finally solve the system. As we want to solve Ax=b with ! b being the real RHS and x being the real solution vector, ! we use linsol_solveAdaptively. If b is a defect ! RHS and x a defect update to be added to a solution vector, ! we would have to use linsol_precondDefect instead. call linsol_solveAdaptively (p_rsolverNode,rvector,rrhs,rtempBlock) ! -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ! Postprocessing of the solution ! -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ! The solution vector is probably not in the way Paraview likes it! ! Paraview for example does not understand Q1~ vectors! ! Therefore, we first have to convert the vector to a form that ! Paraview understands. ! Paraview understands only Q1 solutions! So the task is now to create ! a Q1 solution from p_rvector and write that out. ! ! For this purpose, first create a "derived" simple discretisation ! structure based on Q1 by copying the main guiding block discretisation ! structure and modifying the discretisation structures of the ! two velocity subvectors: call spdiscr_duplicateBlockDiscr (Rlevels(NLMAX)%rdiscretisation,& rprjDiscretisation) call spdiscr_deriveSimpleDiscrSc (& Rlevels(NLMAX)%rdiscretisation%RspatialDiscr(1), & EL_Q1, rprjDiscretisation%RspatialDiscr(1)) call spdiscr_deriveSimpleDiscrSc (& Rlevels(NLMAX)%rdiscretisation%RspatialDiscr(2), & EL_Q1, rprjDiscretisation%RspatialDiscr(2)) ! The pressure discretisation substructure stays the old. ! ! Now set up a new solution vector based on this discretisation, ! allocate memory. call lsysbl_createVecBlockByDiscr (rprjDiscretisation,rprjVector,.false.) ! Then take our original solution vector and convert it according to the ! new discretisation: call spdp_projectSolution (rvector,rprjVector) ! Discretise the boundary conditions according to the Q1/Q1/Q0 ! discretisation. ! ! Create a t_discreteBC structure where we store all discretised boundary ! conditions. call bcasm_initDiscreteBC(rprjDiscreteBC) ! ! Edge 1 of boundary component 1, X-velocity. call boundary_createRegion(rboundary,1,1,rboundaryRegion) ! Edge with start- and endpoint. rboundaryRegion%iproperties = BDR_PROP_WITHSTART + BDR_PROP_WITHEND call bcasm_newDirichletBConRealBD (rprjDiscretisation,1,& rboundaryRegion,rprjDiscreteBC,& getBoundaryValues_2D) ! Edge 2 is Neumann boundary, so it is commented out. ! CALL boundary_createRegion(rboundary,1,2,rboundaryRegion) ! CALL bcasm_newDirichletBConRealBD (rprjDiscretisation,1,& ! rboundaryRegion,rprjDiscreteBC,& ! getBoundaryValues_2D) ! Edge 3 of boundary component 1. call boundary_createRegion(rboundary,1,3,rboundaryRegion) call bcasm_newDirichletBConRealBD (rprjDiscretisation,1,& rboundaryRegion,rprjDiscreteBC,& getBoundaryValues_2D) ! Edge 4 of boundary component 1. That is it. call boundary_createRegion(rboundary,1,4,rboundaryRegion) call bcasm_newDirichletBConRealBD (rprjDiscretisation,1,& rboundaryRegion,rprjDiscreteBC,& getBoundaryValues_2D) ! Edge 1 of boundary component 1, Y-velocity. call boundary_createRegion(rboundary,1,1,rboundaryRegion) ! Edge with start- and endpoint. rboundaryRegion%iproperties = BDR_PROP_WITHSTART + BDR_PROP_WITHEND ! As we define the Y-velocity, we now set icomponent=2 in the following call. call bcasm_newDirichletBConRealBD (rprjDiscretisation,2,& rboundaryRegion,rprjDiscreteBC,& getBoundaryValues_2D) ! Edge 2 is Neumann boundary, so it is commented out. ! CALL boundary_createRegion(rboundary,1,2,rboundaryRegion) ! CALL bcasm_newDirichletBConRealBD (rprjDiscretisation,2,& ! rboundaryRegion,rprjDiscreteBC,& ! getBoundaryValues_2D) ! Edge 3 of boundary component 1. call boundary_createRegion(rboundary,1,3,rboundaryRegion) call bcasm_newDirichletBConRealBD (rprjDiscretisation,2,& rboundaryRegion,rprjDiscreteBC,& getBoundaryValues_2D) ! Edge 4 of boundary component 1. That is it. call boundary_createRegion(rboundary,1,4,rboundaryRegion) call bcasm_newDirichletBConRealBD (rprjDiscretisation,2,& rboundaryRegion,rprjDiscreteBC,& getBoundaryValues_2D) ! Send the vector to the boundary-condition implementation filter. ! This modifies the vector according to the discrete boundary ! conditions. call vecfil_discreteBCsol (rprjVector,rprjDiscreteBC) ! Get the path for writing postprocessing files from the environment variable ! $UCDDIR. If that does not exist, write to the directory "./gmv". if (.not. sys_getenv_string("UCDDIR", sucddir)) sucddir = "./gmv" ! Now we have a Q1/Q1/Q0 solution in rprjVector. ! We can now start the postprocessing. ! Start UCD export to VTK file: call ucd_startVTK (rexport,UCD_FLAG_STANDARD,& Rlevels(NLMAX)%rtriangulation,trim(sucddir)//"/u2d_1_mg.vtk") ! Write velocity field call lsyssc_getbase_double (rprjVector%RvectorBlock(1),p_Ddata) call lsyssc_getbase_double (rprjVector%RvectorBlock(2),p_Ddata2) ! In case we use the VTK exporter, which supports vector output, we will ! pass the X- and Y-velocity at once to the ucd module. call ucd_addVarVertBasedVec(rexport,"velocity",p_Ddata,p_Ddata2) ! If we use the GMV exporter, we might replace the line above by the ! following two lines: !CALL ucd_addVariableVertexBased (rexport,"X-vel",UCD_VAR_XVELOCITY, p_Ddata) !CALL ucd_addVariableVertexBased (rexport,"Y-vel",UCD_VAR_YVELOCITY, p_Ddata2) ! Write pressure call lsyssc_getbase_double (rprjVector%RvectorBlock(3),p_Ddata) call ucd_addVariableElementBased (rexport,"pressure",UCD_VAR_STANDARD, p_Ddata) ! Write the file to disc, that is it. call ucd_write (rexport) call ucd_release (rexport) ! Store the viscosity parameter nu in the collection"s quick access array rcollection%DquickAccess(1) = dnu ! Set up the error structure for velocity rerrorU%p_RvecCoeff => rvector%RvectorBlock(1:2) rerrorU%p_DerrorL2 => DerrorUL2 rerrorU%p_DerrorH1 => DerrorUH1 ! Set up the error structure for pressure rerrorP%p_RvecCoeff => rvector%RvectorBlock(3:3) rerrorP%p_DerrorL2 => DerrorPL2 ! Calculate errors of velocity and pressure against analytic solutions. call pperr_scalarVec(rerrorU, funcVelocity2D, rcollection, Rlevels(NLMAX)%rcubatureInfo) call pperr_scalarVec(rerrorP, funcPressure2D, rcollection, Rlevels(NLMAX)%rcubatureInfo) ! Print the errors. call output_lbrk() call output_line("|u - u_h|_L2 = " // trim(sys_sdEL(DerrorUL2(1), 10)) & // " " // trim(sys_sdEL(DerrorUL2(2), 10))) call output_line("|u - u_h|_H1 = " // trim(sys_sdEL(DerrorUH1(1), 10)) & // " " // trim(sys_sdEL(DerrorUH1(2), 10))) call output_line("|p - p_h|_L2 = " // trim(sys_sdEL(derrorPL2(1), 10))) ! -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ! Clean up ! -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ! We are finished - but not completely! ! Now, clean up so that all the memory is available again. ! ! Release solver data and structure call linsol_doneData (p_rsolverNode) call linsol_doneStructure (p_rsolverNode) ! Release the solver node and all subnodes attached to it (if at all): call linsol_releaseSolver (p_rsolverNode) ! Release the filter chain do i=NLMIN,NLMAX call filter_doneFilterChain (Rlevels(i)%RfilterChain,Rlevels(i)%nfilters) end do ! Release the block matrix/vectors call lsysbl_releaseVector (rprjVector) call lsysbl_releaseVector (rtempBlock) call lsysbl_releaseVector (rvector) call lsysbl_releaseVector (rrhs) do i = NLMAX, NLMIN, -1 call lsysbl_releaseMatrix (Rlevels(i)%rmatrix) end do ! Release B1 and B2 matrix do i = NLMAX, NLMIN, -1 call lsyssc_releaseMatrix (Rlevels(i)%rmatrixB2) call lsyssc_releaseMatrix (Rlevels(i)%rmatrixB1) end do ! Release the cubature info structures. do i = NLMAX, NLMIN, -1 call spdiscr_releaseCubStructure(Rlevels(i)%rcubatureInfo) end do ! Release our discrete version of the boundary conditions call bcasm_releaseDiscreteBC (rprjDiscreteBC) do i = NLMAX, NLMIN, -1 call bcasm_releaseDiscreteBC (Rlevels(i)%rdiscreteBC) end do ! Release the discretisation structure and all spatial discretisation ! structures in it. call spdiscr_releaseBlockDiscr(rprjDiscretisation) do i = NLMAX, NLMIN, -1 call spdiscr_releaseBlockDiscr(Rlevels(i)%rdiscretisation) end do ! Release the triangulation. do i = NLMAX, NLMIN, -1 call tria_done (Rlevels(i)%rtriangulation) end do deallocate(Rlevels) ! Finally release the domain, that is it. call boundary_release (rboundary) end subroutine end module
A ParameterFunction with a set/fixed parameter. Turns this parameter function into a unary function with the parameter fixed/locked to the specified value. param - The parameter of the parameter function.
(* This program is free software; you can redistribute it and/or *) (* modify it under the terms of the GNU Lesser General Public License *) (* as published by the Free Software Foundation; either version 2.1 *) (* of the License, or (at your option) any later version. *) (* *) (* 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 Lesser General Public *) (* License along with this program; if not, write to the Free *) (* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *) (* 02110-1301 USA *) Require Import ZArith Znumtheory. Open Scope Z_scope. (** * Euclid gcd algorithm *) (** This was previously part of Coq standard library (in Znumtheory). But the new binary algorithm used there is much faster and also easier to prove correct (for the variant that is executable in coq). *) (** In this first variant, we use an explicit measure in [nat], and we prove later that using [2(d+1)] is enough, where [d] is the number of binary digits of the first argument. *) Fixpoint Zgcdn (n:nat) : Z -> Z -> Z := fun a b => match n with | O => 1 (* arbitrary, since n should be big enough *) | S n => match a with | Z0 => Zabs b | Zpos _ => Zgcdn n (Zmod b a) a | Zneg a => Zgcdn n (Zmod b (Zpos a)) (Zpos a) end end. (* For technical reason, we don't use [Ndigit.Psize] but this ad-hoc version: [Psize p = S (Psiz p)]. *) Fixpoint Psiz (p:positive) : nat := match p with | xH => O | xI p => S (Psiz p) | xO p => S (Psiz p) end. Definition Zgcd_bound (a:Z) := match a with | Z0 => S O | Zpos p => let n := Psiz p in S (S (n+n)) | Zneg p => let n := Psiz p in S (S (n+n)) end. Definition Zgcd a b := Zgcdn (Zgcd_bound a) a b. (** A first obvious fact : [Zgcd a b] is positive. *) Lemma Zgcdn_is_pos : forall n a b, 0 <= Zgcdn n a b. Proof. induction n. simpl; auto with zarith. destruct a; simpl; intros; auto with zarith; auto. Qed. Lemma Zgcd_is_pos : forall a b, 0 <= Zgcd a b. Proof. intros; unfold Zgcd; apply Zgcdn_is_pos; auto. Qed. (** We now prove that Zgcd is indeed a gcd. *) Lemma Zis_gcd_0_abs : forall b, Zis_gcd 0 b (Zabs b) /\ Zabs b >= 0 /\ 0 = Zabs b * 0 /\ b = Zabs b * Zsgn b. Proof. intro b. elim (Z_le_lt_eq_dec _ _ (Zabs_pos b)). intros H0; split. apply Zabs_ind. intros; apply Zis_gcd_sym; apply Zis_gcd_0; auto. intros; apply Zis_gcd_opp; apply Zis_gcd_0; auto. repeat split; auto with zarith. symmetry; apply Zabs_Zsgn. intros H0; rewrite <- H0. rewrite <- (Zabs_Zsgn b); rewrite <- H0; simpl in |- *. split; [ apply Zis_gcd_0 | idtac ]; auto with zarith. Qed. (** 1) We prove a weaker & easier bound. *) Lemma Zgcdn_linear_bound : forall n a b, Zabs a < Z_of_nat n -> Zis_gcd a b (Zgcdn n a b). Proof. induction n. simpl; intros. elimtype False; generalize (Zabs_pos a); omega. destruct a; intros; simpl; [ generalize (Zis_gcd_0_abs b); intuition | | ]; unfold Zmod; generalize (Z_div_mod b (Zpos p) (refl_equal Gt)); destruct (Zdiv_eucl b (Zpos p)) as (q,r); intros (H0,H1); rewrite inj_S in H; simpl Zabs in H; assert (H2: Zabs r < Z_of_nat n) by (rewrite Zabs_eq; auto with zarith); assert (IH:=IHn r (Zpos p) H2); clear IHn; simpl in IH |- *; rewrite H0. apply Zis_gcd_for_euclid2; auto. apply Zis_gcd_minus; apply Zis_gcd_sym. apply Zis_gcd_for_euclid2; auto. Qed. (** 2) For Euclid's algorithm, the worst-case situation corresponds to Fibonacci numbers. Let's define them: *) Fixpoint fibonacci (n:nat) : Z := match n with | O => 1 | S O => 1 | S (S n as p) => fibonacci p + fibonacci n end. Lemma fibonacci_pos : forall n, 0 <= fibonacci n. Proof. cut (forall N n, (n<N)%nat -> 0<=fibonacci n). eauto. induction N. inversion 1. intros. destruct n. simpl; auto with zarith. destruct n. simpl; auto with zarith. change (0 <= fibonacci (S n) + fibonacci n). generalize (IHN n) (IHN (S n)); omega. Qed. Lemma fibonacci_incr : forall n m, (n<=m)%nat -> fibonacci n <= fibonacci m. Proof. induction 1. auto with zarith. apply Zle_trans with (fibonacci m); auto. clear. destruct m. simpl; auto with zarith. change (fibonacci (S m) <= fibonacci (S m)+fibonacci m). generalize (fibonacci_pos m); omega. Qed. (** 3) We prove that fibonacci numbers are indeed worst-case: for a given number [n], if we reach a conclusion about [gcd(a,b)] in exactly [n+1] loops, then [fibonacci (n+1)<=a /\ fibonacci(n+2)<=b] *) Lemma Zgcdn_worst_is_fibonacci : forall n a b, 0 < a < b -> Zis_gcd a b (Zgcdn (S n) a b) -> Zgcdn n a b <> Zgcdn (S n) a b -> fibonacci (S n) <= a /\ fibonacci (S (S n)) <= b. Proof. induction n. simpl; intros. destruct a; omega. intros. destruct a; [simpl in *; omega| | destruct H; discriminate]. revert H1; revert H0. set (m:=S n) in *; (assert (m=S n) by auto); clearbody m. pattern m at 2; rewrite H0. simpl Zgcdn. unfold Zmod; generalize (Z_div_mod b (Zpos p) (refl_equal Gt)). destruct (Zdiv_eucl b (Zpos p)) as (q,r). intros (H1,H2). destruct H2. destruct (Zle_lt_or_eq _ _ H2). generalize (IHn _ _ (conj H4 H3)). intros H5 H6 H7. replace (fibonacci (S (S m))) with (fibonacci (S m) + fibonacci m) by auto. assert (r = Zpos p * (-q) + b) by (rewrite H1; ring). destruct H5; auto. pattern r at 1; rewrite H8. apply Zis_gcd_sym. apply Zis_gcd_for_euclid2; auto. apply Zis_gcd_sym; auto. split; auto. rewrite H1. apply Zplus_le_compat; auto. apply Zle_trans with (Zpos p * 1); auto. ring (Zpos p * 1); auto. apply Zmult_le_compat_l. destruct q. omega. assert (0 < Zpos p0) by (compute; auto). omega. assert (Zpos p * Zneg p0 < 0) by (compute; auto). omega. compute; intros; discriminate. (* r=0 *) subst r. simpl; rewrite H0. intros. simpl in H4. simpl in H5. destruct n. simpl in H5. simpl. omega. simpl in H5. elim H5; auto. Qed. (** 3b) We reformulate the previous result in a more positive way. *) Lemma Zgcdn_ok_before_fibonacci : forall n a b, 0 < a < b -> a < fibonacci (S n) -> Zis_gcd a b (Zgcdn n a b). Proof. destruct a; [ destruct 1; elimtype False; omega | | destruct 1; discriminate]. cut (forall k n b, k = (S (nat_of_P p) - n)%nat -> 0 < Zpos p < b -> Zpos p < fibonacci (S n) -> Zis_gcd (Zpos p) b (Zgcdn n (Zpos p) b)). destruct 2; eauto. clear n; induction k. intros. assert (nat_of_P p < n)%nat by omega. apply Zgcdn_linear_bound. simpl. generalize (inj_le _ _ H2). rewrite inj_S. rewrite <- Zpos_eq_Z_of_nat_o_nat_of_P; auto. omega. intros. generalize (Zgcdn_worst_is_fibonacci n (Zpos p) b H0); intros. assert (Zis_gcd (Zpos p) b (Zgcdn (S n) (Zpos p) b)). apply IHk; auto. omega. replace (fibonacci (S (S n))) with (fibonacci (S n)+fibonacci n) by auto. generalize (fibonacci_pos n); omega. replace (Zgcdn n (Zpos p) b) with (Zgcdn (S n) (Zpos p) b); auto. generalize (H2 H3); clear H2 H3; omega. Qed. (** 4) The proposed bound leads to a fibonacci number that is big enough. *) Lemma Zgcd_bound_fibonacci : forall a, 0 < a -> a < fibonacci (Zgcd_bound a). Proof. destruct a; [omega| | intro H; discriminate]. intros _. induction p. simpl Zgcd_bound in *. rewrite Zpos_xI. rewrite plus_comm; simpl plus. set (n:=S (Psiz p+Psiz p)) in *. change (2*Zpos p+1 < fibonacci (S n) + fibonacci n + fibonacci (S n)). generalize (fibonacci_pos n). omega. simpl Zgcd_bound in *. rewrite Zpos_xO. rewrite plus_comm; simpl plus. set (n:= S (Psiz p +Psiz p)) in *. change (2*Zpos p < fibonacci (S n) + fibonacci n + fibonacci (S n)). generalize (fibonacci_pos n). omega. simpl; auto with zarith. Qed. (* 5) the end: we glue everything together and take care of situations not corresponding to [0<a<b]. *) Lemma Zgcd_is_gcd : forall a b, Zis_gcd a b (Zgcd a b). Proof. unfold Zgcd; destruct a; intros. simpl; generalize (Zis_gcd_0_abs b); intuition. (*Zpos*) generalize (Zgcd_bound_fibonacci (Zpos p)). simpl Zgcd_bound. set (n:=S (Psiz p+Psiz p)); (assert (n=S (Psiz p+Psiz p)) by auto); clearbody n. simpl Zgcdn. unfold Zmod. generalize (Z_div_mod b (Zpos p) (refl_equal Gt)). destruct (Zdiv_eucl b (Zpos p)) as (q,r). intros (H1,H2) H3. rewrite H1. apply Zis_gcd_for_euclid2. destruct H2. destruct (Zle_lt_or_eq _ _ H0). apply Zgcdn_ok_before_fibonacci; auto; omega. subst r n; simpl. apply Zis_gcd_sym; apply Zis_gcd_0. (*Zneg*) generalize (Zgcd_bound_fibonacci (Zpos p)). simpl Zgcd_bound. set (n:=S (Psiz p+Psiz p)); (assert (n=S (Psiz p+Psiz p)) by auto); clearbody n. simpl Zgcdn. unfold Zmod. generalize (Z_div_mod b (Zpos p) (refl_equal Gt)). destruct (Zdiv_eucl b (Zpos p)) as (q,r). intros (H1,H2) H3. rewrite H1. apply Zis_gcd_minus. apply Zis_gcd_sym. apply Zis_gcd_for_euclid2. destruct H2. destruct (Zle_lt_or_eq _ _ H0). apply Zgcdn_ok_before_fibonacci; auto; omega. subst r n; simpl. apply Zis_gcd_sym; apply Zis_gcd_0. Qed. (** A generalized gcd: it additionnally keeps track of the divisors. *) Fixpoint Zggcdn (n:nat) : Z -> Z -> (Z*(Z*Z)) := fun a b => match n with | O => (1,(a,b)) (*(Zabs b,(0,Zsgn b))*) | S n => match a with | Z0 => (Zabs b,(0,Zsgn b)) | Zpos _ => let (q,r) := Zdiv_eucl b a in (* b = q*a+r *) let (g,p) := Zggcdn n r a in let (rr,aa) := p in (* r = g *rr /\ a = g * aa *) (g,(aa,q*aa+rr)) | Zneg a => let (q,r) := Zdiv_eucl b (Zpos a) in (* b = q*(-a)+r *) let (g,p) := Zggcdn n r (Zpos a) in let (rr,aa) := p in (* r = g*rr /\ (-a) = g * aa *) (g,(-aa,q*aa+rr)) end end. Definition Zggcd a b : Z * (Z * Z) := Zggcdn (Zgcd_bound a) a b. (** The first component of [Zggcd] is [Zgcd] *) Lemma Zggcdn_gcdn : forall n a b, fst (Zggcdn n a b) = Zgcdn n a b. Proof. induction n; simpl; auto. destruct a; unfold Zmod; simpl; intros; auto; destruct (Zdiv_eucl b (Zpos p)) as (q,r); rewrite <- IHn; destruct (Zggcdn n r (Zpos p)) as (g,(rr,aa)); simpl; auto. Qed. Lemma Zggcd_gcd : forall a b, fst (Zggcd a b) = Zgcd a b. Proof. intros; unfold Zggcd, Zgcd; apply Zggcdn_gcdn; auto. Qed. (** [Zggcd] always returns divisors that are coherent with its first output. *) Lemma Zggcdn_correct_divisors : forall n a b, let (g,p) := Zggcdn n a b in let (aa,bb):=p in a=g*aa /\ b=g*bb. Proof. induction n. simpl. split; [destruct a|destruct b]; auto. intros. simpl. destruct a. rewrite Zmult_comm; simpl. split; auto. symmetry; apply Zabs_Zsgn. generalize (Z_div_mod b (Zpos p)); destruct (Zdiv_eucl b (Zpos p)) as (q,r). generalize (IHn r (Zpos p)); destruct (Zggcdn n r (Zpos p)) as (g,(rr,aa)). intuition. destruct H0. compute; auto. rewrite H; rewrite H1; rewrite H2; ring. generalize (Z_div_mod b (Zpos p)); destruct (Zdiv_eucl b (Zpos p)) as (q,r). destruct 1. compute; auto. generalize (IHn r (Zpos p)); destruct (Zggcdn n r (Zpos p)) as (g,(rr,aa)). intuition. destruct H0. replace (Zneg p) with (-Zpos p) by compute; auto. rewrite H4; ring. rewrite H; rewrite H4; rewrite H0; ring. Qed. Lemma Zggcd_correct_divisors : forall a b, let (g,p) := Zggcd a b in let (aa,bb):=p in a=g*aa /\ b=g*bb. Proof. unfold Zggcd; intros; apply Zggcdn_correct_divisors; auto. Qed. (** Due to the use of an explicit measure, the extraction of [Zgcd] isn't optimal. We propose here another version [Zgcd_spec] that doesn't suffer from this problem (but doesn't compute in Coq). *) Definition Zgcd_spec_pos : forall a:Z, 0 <= a -> forall b:Z, {g : Z | 0 <= a -> Zis_gcd a b g /\ g >= 0}. Proof. intros a Ha. apply (Zlt_0_rec (fun a:Z => forall b:Z, {g : Z | 0 <= a -> Zis_gcd a b g /\ g >= 0})); try assumption. intro x; case x. intros _ _ b; exists (Zabs b). generalize (Zis_gcd_0_abs b); intuition. intros p Hrec _ b. generalize (Z_div_mod b (Zpos p)). case (Zdiv_eucl b (Zpos p)); intros q r Hqr. elim Hqr; clear Hqr; intros; auto with zarith. elim (Hrec r H0 (Zpos p)); intros g Hgkl. inversion_clear H0. elim (Hgkl H1); clear Hgkl; intros H3 H4. exists g; intros. split; auto. rewrite H. apply Zis_gcd_for_euclid2; auto. intros p _ H b. elim H; auto. Defined. Definition Zgcd_spec : forall a b:Z, {g : Z | Zis_gcd a b g /\ g >= 0}. Proof. intros a; case (Z_gt_le_dec 0 a). intros; assert (0 <= - a). omega. elim (Zgcd_spec_pos (- a) H b); intros g Hgkl. exists g. intuition. intros Ha b; elim (Zgcd_spec_pos a Ha b); intros g; exists g; intuition. Defined. (** A last version aimed at extraction that also returns the divisors. *) Definition Zggcd_spec_pos : forall a:Z, 0 <= a -> forall b:Z, {p : Z*(Z*Z) | let (g,p):=p in let (aa,bb):=p in 0 <= a -> Zis_gcd a b g /\ g >= 0 /\ a=g*aa /\ b=g*bb}. Proof. intros a Ha. pattern a; apply Zlt_0_rec; try assumption. intro x; case x. intros _ _ b; exists (Zabs b,(0,Zsgn b)). intros _; apply Zis_gcd_0_abs. intros p Hrec _ b. generalize (Z_div_mod b (Zpos p)). case (Zdiv_eucl b (Zpos p)); intros q r Hqr. elim Hqr; clear Hqr; intros; auto with zarith. destruct (Hrec r H0 (Zpos p)) as ((g,(rr,pp)),Hgkl). destruct H0. destruct (Hgkl H0) as (H3,(H4,(H5,H6))). exists (g,(pp,pp*q+rr)); intros. split; auto. rewrite H. apply Zis_gcd_for_euclid2; auto. repeat split; auto. rewrite H; rewrite H6; rewrite H5; ring. intros p _ H b. elim H; auto. Defined. Definition Zggcd_spec : forall a b:Z, {p : Z*(Z*Z) | let (g,p):=p in let (aa,bb):=p in Zis_gcd a b g /\ g >= 0 /\ a=g*aa /\ b=g*bb}. Proof. intros a; case (Z_gt_le_dec 0 a). intros; assert (0 <= - a). omega. destruct (Zggcd_spec_pos (- a) H b) as ((g,(aa,bb)),Hgkl). exists (g,(-aa,bb)). intuition. rewrite <- Zopp_mult_distr_r. rewrite <- H2; auto with zarith. intros Ha b; elim (Zggcd_spec_pos a Ha b); intros p; exists p. repeat destruct p; intuition. Defined.
= = = Suggested homosexual subtext = = =
module Main import GLCore import JSArrays import Shaders import JSMatrix.JSMatrix -- Save time, just get the canvas directly by id getElemById : String -> IO Element getElemById s = do x <- mkForeign (FFun "document.getElementById(%0)" [FString] FPtr) s return (MkElem x) getElemFloatProp : String -> Element -> IO Float getElemFloatProp p (MkElem e) = mkForeign (FFun "%0[%1]" [FPtr,FString] FFloat) e p getElemStringProp : String -> Element -> IO String getElemStringProp p (MkElem e) = mkForeign (FFun "%0[%1]" [FPtr,FString] FString) e p -- Retrieve the dimensions of the canvas element canvasDimensions : Element -> IO (List Float) canvasDimensions e = do w <- getElemFloatProp "width" e h <- getElemFloatProp "height" e return [w,h] -- Shader Functions getShader : String -> IO String getShader e = getElemById e >>= getElemStringProp "textContent" -- Pyramid pyramidVertices : List Float pyramidVertices = [0.0, 1.0, 0.0, -1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, -1.0, 0.0, 1.0, 0.0, 1.0, 0.0, -1.0, -1.0, 0.0, -1.0, 0.0, 1.0, 0.0, -1.0, 0.0, -1.0, -1.0, 0.0, 1.0] pyramidColours : List Float pyramidColours = [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1] mvTranslateVect : Vect 3 Float mvTranslateVect = [0.0,0.0,-4.0] rotateVec : Vect 3 Float rotateVec = [0.0,1.0,0.0] -- Some basic settings for starting our GL env baseGLInit : GLCxt -> IO GLCxt baseGLInit c = do depthTest <- getGLProp "DEPTH_TEST" c clearColor [1.0, 1.0, 1.0, 1.0] c >>= enableGLSetting depthTest >>= glClear prepareVerticesArray : List Float -> IO F32Array prepareVerticesArray xs = createJSArray >>= fromFloatList xs >>= createF32Array -- Wrapper for finding and init'ing our GL env and context locateInitCanvas : IO GLCxt locateInitCanvas = getElemById "canvas" >>= getGLCxt >>= baseGLInit -- Wrapper for the process of assigning a shader variable the correct location -- for our program to locate vertex information when the shader runs. assignVertexPositionAttribs : String -> Int -> (GLProgram,GLCxt) -> IO (GLProgram,GLCxt) assignVertexPositionAttribs attr n glProg = do loc <- getAttribLocation attr glProg enableVertexAttribArray glProg loc >>= setVertexAttribPointer n loc translateMat : JSGLMat4 -> IO JSGLMat4 translateMat jsMat4 = createVec3FromVect mvTranslateVect >>= \v3 => translateM4 v3 jsMat4 jsMat4 printJunk : JSGLMat4 -> IO () printJunk (MkMat4 a) = mkForeign (FFun "console.log(%0)" [FPtr] FUnit) a main : IO () main = do [w,h] <- getElemById "canvas" >>= canvasDimensions verticesF32 <- prepareVerticesArray pyramidVertices coloursF32 <- prepareVerticesArray pyramidColours (vBuffer,glCxt) <- locateInitCanvas >>= flip createBindBuffer verticesF32 (cBuffer,glCxt') <- createBindBuffer glCxt coloursF32 -- Set the viewport size setViewport w h glCxt' prgCxt <- createProg glCxt' -- Pull the shaders off the DOM vshader <- [| Vertex $ getShader "vshader" |] fshader <- [| Fragment $ getShader "fshader" |] -- JS Math.Pi Value mPI <- mathPI -- Create rotation vector rotationAxis <- createVec3 rotationAxis' <- createVec3FromVect rotateVec >>= normaliseV3 rotationAxis -- Create our matrices mvMatrix <- createMat4 >>= translateMat mvMatrix' <- rotateM4 mvMatrix (mPI*2*33) rotationAxis' mvMatrix pjMatrix <- createMat4 >>= perspectiveM4 (mPI/4) (w/h) 1 100 -- Pass our shader code to be built,compiled, and linked to the GL context prgCxt' <- compileAndLinkShaders [vshader, fshader] prgCxt >>= useProg prgCxt'' <- assignVertexPositionAttribs "vertPos" 3 prgCxt' nxtPrgCxt <- assignVertexPositionAttribs "vertColor" 4 prgCxt'' mvLoc <- getUniformLocation "mvMatrix" nxtPrgCxt pjLoc <- getUniformLocation "pjMatrix" nxtPrgCxt nxtPrgCxt' <- uniformMatrix4v mvMatrix' mvLoc nxtPrgCxt >>= uniformMatrix4v pjMatrix pjLoc drawTriangles 0 12 nxtPrgCxt' putStrLn "It might have worked... who knows!"
Load LFindLoad. From lfind Require Import LFind. From QuickChick Require Import QuickChick. From adtind Require Import goal33. Derive Show for natural. Derive Arbitrary for natural. Instance Dec_Eq_natural : Dec_Eq natural. Proof. dec_eq. Qed. Lemma conj20synthconj6 : forall (lv0 : natural) (lv1 : natural) (lv2 : natural) (lv3 : natural), (@eq natural (plus (plus lv0 lv1) lv2) (plus (mult lv3 (Succ lv1)) (Succ lv1))). Admitted. QuickChick conj20synthconj6.
Since the 1980s , plans have been made to rebuild the synagogue in its original location . Due to various political circumstances , very limited progress has been made . Major disagreements exist between the government and Jewish organizations as to how much the latter should be involved in decisions about the reconstruction project , including proposed design and character of the new building .
#' Random reverse translation #' #' Randomly reverse translate an animo acid sequence into a DNA sequence according to a codon usage table and a codon table #' #' @param x a char array of animo acids (e.g., either 'G' or 'Gly' is acceptable but do not mix one letter symbols with three letter symbols in the same array) or codons (e.g., 'GGG'). The first element of the array will be used to determine the type of the input #' @param cut a named numerical array of codon usage table. Case-insensitive three letter codon names are used. Numbers could be the actuall codon counts or scaled ratios #' @param y a number denoting the codon table to be used. When \emph{cut} is specified, \emph{y} also needs to be specified. 0 = standard codon table (default), 2 = vertibrate mitchodrial and see dna2aa for more options. When an option other than those mentioned above is provided, the standard codon table will be used #' @param spp a char string of the host species name for which the codon usage table will be used: 'ecoli', E. coli; 'insect', insect; 'yeast', yeast; 'celegans', C. elegans, and see pminmax for more options. When specified, this option overides \emph{cut}. These build-in codon usage tables are taken from https://www.genscript.com/tools/codon-frequency-table. #' @return an KZsqns object of random reverse translated codons #' @examples #' #' @export rrt <- function(x, cut, y=0, spp){ switch(as.character(spp), 'ecoli' = { cft = cft_ecoli[,5] names(cft) = cft_ecoli[,1] y=0 }, 'insect' = { cft = cft_insect[,5] names(cft) = cft_insect[,1] y=0 }, 'yeast' = { cft = cft_yeast[,5] names(cft) = cft_yeast[,1] y=0 }, 'celegans' = { cft = cft_celegans[,5] names(cft) = cft_celegans[,1] y=0 }, 'drosophila' = { cft = cft_drosophila[,5] names(cft) = cft_drosophila[,1] y=0 }, 'human' = { cft = cft_human[,5] names(cft) = cft_human[,1] y=0 }, 'mouse' = { cft = cft_mouse[,5] names(cft) = cft_mouse[,1] y=0 }, 'rat' = { cft = cft_rat[,5] names(cft) = cft_rat[,1] y=0 }, 'pig' = { cft = cft_pig[,5] names(cft) = cft_pig[,1] y=0 }, 'pichia' = { cft = cft_pichia[,5] names(cft) = cft_pichia[,1] y=0 }, 'arabidopsis' = { cft = cft_arabidopsis[,5] names(cft) = cft_arabidopsis[,1] y=0 }, 'streptomyces' = { cft = cft_streptomyces[,5] names(cft) = cft_streptomyces[,1] y=0 }, 'zea' = { cft = cft_zea[,5] names(cft) = cft_zea[,1] y=0 }, 'nicotiana' = { cft = cft_nicotiana[,5] names(cft) = cft_nicotiana[,1] y=0 }, 'saccharomyces' = { cft = cft_saccharomyces[,5] names(cft) = cft_saccharomyces[,1] y=0 }, 'cricetulus' = { cft = cft_cricetulus[,5] names(cft) = cft_cricetulus[,1] y=0 }, { cft = cut }) cTable = arg_check(x, 'character', y) if(x[1]%in%cTable[,1]){ temp = dna2aa(x,1,y) } else if (x[1]%in%cTable[,2]){ temp = x } else { tabx = unique(cTable[,2:3]) tab = tabx[,1] names(tab) = tabx[,2] temp = unname(tab[x]) } nx = length(x) ans = character(nx) types = table(cTable[,2]) typename = names(types) for(i in 1:length(types)){ indx = which(temp==typename[i]) codons = cTable[cTable[,2]==typename[i],1] temp[indx] <- apply(rmultinom(length(indx), 1, cft[codons]), 2, function(x){codons[as.logical(x)]}) } attr(temp, 'class') <- "KZsqns" return(temp) }
{- Automatically generating proofs of UnivalentStr for records -} {-# OPTIONS --cubical --no-exact-split --safe #-} module Cubical.Structures.Record where open import Cubical.Foundations.Prelude open import Cubical.Foundations.Equiv open import Cubical.Foundations.Function open import Cubical.Foundations.HLevels open import Cubical.Foundations.Isomorphism open import Cubical.Foundations.SIP open import Cubical.Foundations.Structure open import Cubical.Foundations.Univalence open import Cubical.Data.Sigma open import Cubical.Data.Nat open import Cubical.Data.List as List open import Cubical.Data.Vec as Vec open import Cubical.Data.Bool open import Cubical.Data.Maybe open import Cubical.Data.Sum open import Cubical.Structures.Auto import Cubical.Structures.Macro as M import Agda.Builtin.Reflection as R open import Cubical.Reflection.Base -- Magic number private FUEL = 10000 -- Types for specifying inputs to the tactics data AutoFieldSpec : Typeω where autoFieldSpec : ∀ {ℓ ℓ₁ ℓ₂} (R : Type ℓ → Type ℓ₁) {S : Type ℓ → Type ℓ₂} → ({X : Type ℓ} → R X → S X) → AutoFieldSpec module _ {ℓ ℓ₁ ℓ₁'} where mutual data AutoFields (R : Type ℓ → Type ℓ₁) (ι : StrEquiv R ℓ₁') : Typeω where fields: : AutoFields R ι _data[_∣_] : (fs : AutoFields R ι) → ∀ {ℓ₂ ℓ₂'} {S : Type ℓ → Type ℓ₂} {ι' : StrEquiv S ℓ₂'} → (f : {X : Type ℓ} → R X → S X) → ({A B : TypeWithStr ℓ R} {e : typ A ≃ typ B} → ι A B e → ι' (map-snd f A) (map-snd f B) e) → AutoFields R ι _prop[_∣_] : (fs : AutoFields R ι) → ∀ {ℓ₂} {P : (X : Type ℓ) → GatherFields fs X → Type ℓ₂} → ({X : Type ℓ} (r : R X) → P X (projectFields fs r)) → isPropProperty R ι fs P → AutoFields R ι GatherFieldsLevel : {R : Type ℓ → Type ℓ₁} {ι : StrEquiv R ℓ₁'} → AutoFields R ι → Level GatherFieldsLevel fields: = ℓ-zero GatherFieldsLevel (_data[_∣_] fs {ℓ₂ = ℓ₂} _ _) = ℓ-max (GatherFieldsLevel fs) ℓ₂ GatherFieldsLevel (_prop[_∣_] fs {ℓ₂ = ℓ₂} _ _) = ℓ-max (GatherFieldsLevel fs) ℓ₂ GatherFields : {R : Type ℓ → Type ℓ₁} {ι : StrEquiv R ℓ₁'} (dat : AutoFields R ι) → Type ℓ → Type (GatherFieldsLevel dat) GatherFields fields: X = Unit GatherFields (_data[_∣_] fs {S = S} _ _) X = GatherFields fs X × S X GatherFields (_prop[_∣_] fs {P = P} _ _) X = Σ[ s ∈ GatherFields fs X ] (P X s) projectFields : {R : Type ℓ → Type ℓ₁} {ι : StrEquiv R ℓ₁'} (fs : AutoFields R ι) → {X : Type ℓ} → R X → GatherFields fs X projectFields fields: = _ projectFields (fs data[ f ∣ _ ]) r = projectFields fs r , f r projectFields (fs prop[ f ∣ _ ]) r = projectFields fs r , f r isPropProperty : ∀ {ℓ₂} (R : Type ℓ → Type ℓ₁) (ι : StrEquiv R ℓ₁') (fs : AutoFields R ι) (P : (X : Type ℓ) → GatherFields fs X → Type ℓ₂) → Type (ℓ-max (ℓ-suc ℓ) (ℓ-max ℓ₁ ℓ₂)) isPropProperty R ι fs P = {X : Type ℓ} (r : R X) → isProp (P X (projectFields fs r)) data AutoRecordSpec : Typeω where autoRecordSpec : (R : Type ℓ → Type ℓ₁) (ι : StrEquiv R ℓ₁') → AutoFields R ι → AutoRecordSpec -- Some reflection utilities private tApply : R.Term → List (R.Arg R.Term) → R.Term tApply t l = R.def (quote idfun) (R.unknown v∷ t v∷ l) tStrMap : R.Term → R.Term → R.Term tStrMap A f = R.def (quote map-snd) (f v∷ A v∷ []) tStrProj : R.Term → R.Name → R.Term tStrProj A sfield = tStrMap A (R.def sfield []) Fun : ∀ {ℓ ℓ'} → Type ℓ → Type ℓ' → Type (ℓ-max ℓ ℓ') Fun A B = A → B -- Helper functions used in the generated univalence proof private pathMap : ∀ {ℓ ℓ'} {S : I → Type ℓ} {T : I → Type ℓ'} (f : {i : I} → S i → T i) {x : S i0} {y : S i1} → PathP S x y → PathP T (f x) (f y) pathMap f p i = f (p i) -- Property field helper functions module _ {ℓ ℓ₁ ℓ₁' ℓ₂} (R : Type ℓ → Type ℓ₁) -- Structure record (ι : StrEquiv R ℓ₁') -- Equivalence record (fs : AutoFields R ι) -- Prior fields (P : (X : Type ℓ) → GatherFields fs X → Type ℓ₂) -- Property type (f : {X : Type ℓ} (r : R X) → P X (projectFields fs r)) -- Property projection where prev = projectFields fs Prev = GatherFields fs PropHelperCenterType : Type _ PropHelperCenterType = (A B : TypeWithStr ℓ R) (e : A .fst ≃ B .fst) (p : PathP (λ i → Prev (ua e i)) (prev (A .snd)) (prev (B .snd))) → PathP (λ i → P (ua e i) (p i)) (f (A .snd)) (f (B .snd)) PropHelperContractType : PropHelperCenterType → Type _ PropHelperContractType c = (A B : TypeWithStr ℓ R) (e : A .fst ≃ B .fst) {p₀ : PathP (λ i → Prev (ua e i)) (prev (A .snd)) (prev (B .snd))} (q : PathP (λ i → R (ua e i)) (A .snd) (B .snd)) (p : p₀ ≡ (λ i → prev (q i))) → PathP (λ k → PathP (λ i → P (ua e i) (p k i)) (f (A .snd)) (f (B .snd))) (c A B e p₀) (λ i → f (q i)) PropHelperType : Type _ PropHelperType = Σ PropHelperCenterType PropHelperContractType derivePropHelper : isPropProperty R ι fs P → PropHelperType derivePropHelper propP .fst A B e p = isOfHLevelPathP' 0 (propP _) (f (A .snd)) (f (B .snd)) .fst derivePropHelper propP .snd A B e q p = isOfHLevelPathP' 0 (isOfHLevelPathP 1 (propP _) _ _) _ _ .fst -- Build proof of univalence from an isomorphism module _ {ℓ ℓ₁ ℓ₁'} (S : Type ℓ → Type ℓ₁) (ι : StrEquiv S ℓ₁') where fwdShape : Type _ fwdShape = (A B : TypeWithStr ℓ S) (e : typ A ≃ typ B) → ι A B e → PathP (λ i → S (ua e i)) (str A) (str B) bwdShape : Type _ bwdShape = (A B : TypeWithStr ℓ S) (e : typ A ≃ typ B) → PathP (λ i → S (ua e i)) (str A) (str B) → ι A B e fwdBwdShape : fwdShape → bwdShape → Type _ fwdBwdShape fwd bwd = (A B : TypeWithStr ℓ S) (e : typ A ≃ typ B) → ∀ p → fwd A B e (bwd A B e p) ≡ p bwdFwdShape : fwdShape → bwdShape → Type _ bwdFwdShape fwd bwd = (A B : TypeWithStr ℓ S) (e : typ A ≃ typ B) → ∀ r → bwd A B e (fwd A B e r) ≡ r -- The implicit arguments A,B in UnivalentStr make some things annoying so let's avoid them ExplicitUnivalentStr : Type _ ExplicitUnivalentStr = (A B : TypeWithStr _ S) (e : typ A ≃ typ B) → ι A B e ≃ PathP (λ i → S (ua e i)) (str A) (str B) explicitUnivalentStr : (fwd : fwdShape) (bwd : bwdShape) → fwdBwdShape fwd bwd → bwdFwdShape fwd bwd → ExplicitUnivalentStr explicitUnivalentStr fwd bwd fwdBwd bwdFwd A B e = isoToEquiv isom where open Iso isom : Iso _ _ isom .fun = fwd A B e isom .inv = bwd A B e isom .rightInv = fwdBwd A B e isom .leftInv = bwdFwd A B e ExplicitUnivalentDesc : ∀ ℓ → (d : M.Desc ℓ) → Type _ ExplicitUnivalentDesc _ d = ExplicitUnivalentStr (M.MacroStructure d) (M.MacroEquivStr d) explicitUnivalentDesc : ∀ ℓ → (d : M.Desc ℓ) → ExplicitUnivalentDesc ℓ d explicitUnivalentDesc _ d A B e = M.MacroUnivalentStr d e -- Internal record specification type private record TypedTerm : Type where field type : R.Term term : R.Term record InternalDatumField : Type where field sfield : R.Name -- name of structure field efield : R.Name -- name of equivalence field record InternalPropField : Type where field sfield : R.Name -- name of structure field InternalField : Type InternalField = InternalDatumField ⊎ InternalPropField record InternalSpec (A : Type) : Type where field srec : R.Term -- structure record type erec : R.Term -- equivalence record type fields : List (InternalField × A) -- in reverse order open TypedTerm open InternalDatumField open InternalPropField -- Parse a field and record specifications private findName : R.Term → R.TC R.Name findName (R.def name _) = R.returnTC name findName (R.lam R.hidden (R.abs _ t)) = findName t findName t = R.typeError (R.strErr "Not a name + spine: " ∷ R.termErr t ∷ []) parseFieldSpec : R.Term → R.TC (R.Term × R.Term × R.Term × R.Term) parseFieldSpec (R.con (quote autoFieldSpec) (ℓ h∷ ℓ₁ h∷ ℓ₂ h∷ R v∷ S h∷ f v∷ [])) = R.reduce ℓ >>= λ ℓ → R.returnTC (ℓ , ℓ₂ , S , f) parseFieldSpec t = R.typeError (R.strErr "Malformed field specification: " ∷ R.termErr t ∷ []) parseSpec : R.Term → R.TC (InternalSpec TypedTerm) parseSpec (R.con (quote autoRecordSpec) (ℓ h∷ ℓ₁ h∷ ℓ₁' h∷ srecTerm v∷ erecTerm v∷ fs v∷ [])) = parseFields fs >>= λ fs' → R.returnTC λ { .srec → srecTerm ; .erec → erecTerm ; .fields → fs'} where open InternalSpec parseFields : R.Term → R.TC (List (InternalField × TypedTerm)) parseFields (R.con (quote fields:) _) = R.returnTC [] parseFields (R.con (quote _data[_∣_]) (ℓ h∷ ℓ₁ h∷ ℓ₁' h∷ R h∷ ι h∷ fs v∷ ℓ₂ h∷ ℓ₂' h∷ S h∷ ι' h∷ sfieldTerm v∷ efieldTerm v∷ [])) = R.reduce ℓ >>= λ ℓ → findName sfieldTerm >>= λ sfieldName → findName efieldTerm >>= λ efieldName → buildDesc FUEL ℓ ℓ₂ S >>= λ d → let f : InternalField × TypedTerm f = λ { .fst → inl λ { .sfield → sfieldName ; .efield → efieldName } ; .snd .type → R.def (quote ExplicitUnivalentDesc) (ℓ v∷ d v∷ []) ; .snd .term → R.def (quote explicitUnivalentDesc) (ℓ v∷ d v∷ []) } in liftTC (f ∷_) (parseFields fs) parseFields (R.con (quote _prop[_∣_]) (ℓ h∷ ℓ₁ h∷ ℓ₁' h∷ R h∷ ι h∷ fs v∷ ℓ₂ h∷ P h∷ fieldTerm v∷ prop v∷ [])) = findName fieldTerm >>= λ fieldName → let p : InternalField × TypedTerm p = λ { .fst → inr λ { .sfield → fieldName } ; .snd .type → R.def (quote PropHelperType) (srecTerm v∷ erecTerm v∷ fs v∷ P v∷ fieldTerm v∷ []) ; .snd .term → R.def (quote derivePropHelper) (srecTerm v∷ erecTerm v∷ fs v∷ P v∷ fieldTerm v∷ prop v∷ []) } in liftTC (p ∷_) (parseFields fs) parseFields t = R.typeError (R.strErr "Malformed autoRecord specification (1): " ∷ R.termErr t ∷ []) parseSpec t = R.typeError (R.strErr "Malformed autoRecord specification (2): " ∷ R.termErr t ∷ []) -- Build a proof of univalence from an InternalSpec module _ (spec : InternalSpec ℕ) where open InternalSpec spec private fwdDatum : Vec R.Term 4 → R.Term → InternalDatumField × ℕ → R.Term fwdDatum (A ∷ B ∷ e ∷ streq ∷ _) i (dat , n) = R.def (quote equivFun) (tApply (v n) (tStrProj A (dat .sfield) v∷ tStrProj B (dat .sfield) v∷ e v∷ []) v∷ R.def (dat .efield) (streq v∷ []) v∷ i v∷ []) fwdProperty : Vec R.Term 4 → R.Term → R.Term → InternalPropField × ℕ → R.Term fwdProperty (A ∷ B ∷ e ∷ streq ∷ _) i prevPath prop = R.def (quote fst) (v (prop .snd) v∷ A v∷ B v∷ e v∷ prevPath v∷ i v∷ []) bwdClause : Vec R.Term 4 → InternalDatumField × ℕ → R.Clause bwdClause (A ∷ B ∷ e ∷ q ∷ _) (dat , n) = R.clause [] (R.proj (dat .efield) v∷ []) (R.def (quote invEq) (tApply (v n) (tStrProj A (dat .sfield) v∷ tStrProj B (dat .sfield) v∷ e v∷ []) v∷ R.def (quote pathMap) (R.def (dat .sfield) [] v∷ q v∷ []) v∷ [])) fwdBwdDatum : Vec R.Term 4 → R.Term → R.Term → InternalDatumField × ℕ → R.Term fwdBwdDatum (A ∷ B ∷ e ∷ q ∷ _) j i (dat , n) = R.def (quote retEq) (tApply (v n) (tStrProj A (dat .sfield) v∷ tStrProj B (dat .sfield) v∷ e v∷ []) v∷ R.def (quote pathMap) (R.def (dat .sfield) [] v∷ q v∷ []) v∷ j v∷ i v∷ []) fwdBwdProperty : Vec R.Term 4 → (j i prevPath : R.Term) → InternalPropField × ℕ → R.Term fwdBwdProperty (A ∷ B ∷ e ∷ q ∷ _) j i prevPath prop = R.def (quote snd) (v (prop .snd) v∷ A v∷ B v∷ e v∷ q v∷ prevPath v∷ j v∷ i v∷ []) bwdFwdClause : Vec R.Term 4 → R.Term → InternalDatumField × ℕ → R.Clause bwdFwdClause (A ∷ B ∷ e ∷ streq ∷ _) j (dat , n) = R.clause [] (R.proj (dat .efield) v∷ []) (R.def (quote secEq) (tApply (v n) (tStrProj A (dat .sfield) v∷ tStrProj B (dat .sfield) v∷ e v∷ []) v∷ R.def (dat .efield) (streq v∷ []) v∷ j v∷ [])) makeVarsFrom : {n : ℕ} → ℕ → Vec R.Term n makeVarsFrom {zero} k = [] makeVarsFrom {suc n} k = v (n + k) ∷ (makeVarsFrom k) fwd : R.Term fwd = vlam "A" (vlam "B" (vlam "e" (vlam "streq" (vlam "i" (R.pat-lam body []))))) where -- input list is in reverse order fwdClauses : ℕ → List (InternalField × ℕ) → List (R.Name × R.Term) fwdClauses k [] = [] fwdClauses k ((inl f , n) ∷ fs) = fwdClauses k fs ∷ʳ (f .sfield , fwdDatum (makeVarsFrom k) (v 0) (map-snd (4 + k +_) (f , n))) fwdClauses k ((inr p , n) ∷ fs) = fwdClauses k fs ∷ʳ (p .sfield , fwdProperty (makeVarsFrom k) (v 0) prevPath (map-snd (4 + k +_) (p , n))) where prevPath = vlam "i" (List.foldl (λ t (_ , t') → R.con (quote _,_) (t v∷ t' v∷ [])) (R.con (quote tt) []) (fwdClauses (suc k) fs)) body = List.map (λ (n , t) → R.clause [] [ varg (R.proj n) ] t) (fwdClauses 1 fields) bwd : R.Term bwd = vlam "A" (vlam "B" (vlam "e" (vlam "q" (R.pat-lam (bwdClauses fields) [])))) where -- input is in reverse order bwdClauses : List (InternalField × ℕ) → List R.Clause bwdClauses [] = [] bwdClauses ((inl f , n) ∷ fs) = bwdClauses fs ∷ʳ bwdClause (makeVarsFrom 0) (map-snd (4 +_) (f , n)) bwdClauses ((inr p , n) ∷ fs) = bwdClauses fs fwdBwd : R.Term fwdBwd = vlam "A" (vlam "B" (vlam "e" (vlam "q" (vlam "j" (vlam "i" (R.pat-lam body [])))))) where -- input is in reverse order fwdBwdClauses : ℕ → List (InternalField × ℕ) → List (R.Name × R.Term) fwdBwdClauses k [] = [] fwdBwdClauses k ((inl f , n) ∷ fs) = fwdBwdClauses k fs ∷ʳ (f .sfield , fwdBwdDatum (makeVarsFrom k) (v 1) (v 0) (map-snd (4 + k +_) (f , n))) fwdBwdClauses k ((inr p , n) ∷ fs) = fwdBwdClauses k fs ∷ʳ ((p .sfield , fwdBwdProperty (makeVarsFrom k) (v 1) (v 0) prevPath (map-snd (4 + k +_) (p , n)))) where prevPath = vlam "j" (vlam "i" (List.foldl (λ t (_ , t') → R.con (quote _,_) (t v∷ t' v∷ [])) (R.con (quote tt) []) (fwdBwdClauses (2 + k) fs))) body = List.map (λ (n , t) → R.clause [] [ varg (R.proj n) ] t) (fwdBwdClauses 2 fields) bwdFwd : R.Term bwdFwd = vlam "A" (vlam "B" (vlam "e" (vlam "streq" (vlam "j" (R.pat-lam (bwdFwdClauses fields) []))))) where bwdFwdClauses : List (InternalField × ℕ) → List R.Clause bwdFwdClauses [] = [] bwdFwdClauses ((inl f , n) ∷ fs) = bwdFwdClauses fs ∷ʳ bwdFwdClause (makeVarsFrom 1) (v 0) (map-snd (5 +_) (f , n)) bwdFwdClauses ((inr _ , n) ∷ fs) = bwdFwdClauses fs univalentRecord : R.Term univalentRecord = R.def (quote explicitUnivalentStr) (R.unknown v∷ R.unknown v∷ fwd v∷ bwd v∷ fwdBwd v∷ bwdFwd v∷ []) macro autoFieldEquiv : R.Term → R.Term → R.Term → R.Term → R.TC Unit autoFieldEquiv spec A B hole = (R.reduce spec >>= parseFieldSpec) >>= λ (ℓ , ℓ₂ , S , f) → buildDesc FUEL ℓ ℓ₂ S >>= λ d → R.unify hole (R.def (quote M.MacroEquivStr) (d v∷ tStrMap A f v∷ tStrMap B f v∷ [])) autoUnivalentRecord : R.Term → R.Term → R.TC Unit autoUnivalentRecord t hole = (R.reduce t >>= parseSpec) >>= λ spec → -- R.typeError (R.strErr "WOW: " ∷ R.termErr (main spec) ∷ []) R.unify (main spec) hole where module _ (spec : InternalSpec TypedTerm) where open InternalSpec spec mapUp : ∀ {ℓ ℓ'} {A : Type ℓ} {B : Type ℓ'} → (ℕ → A → B) → ℕ → List A → List B mapUp f _ [] = [] mapUp f n (x ∷ xs) = f n x ∷ mapUp f (suc n) xs closureSpec : InternalSpec ℕ closureSpec .InternalSpec.srec = srec closureSpec .InternalSpec.erec = erec closureSpec .InternalSpec.fields = mapUp (λ n → map-snd (λ _ → n)) 0 fields closure : R.Term closure = iter (List.length fields) (vlam "") (univalentRecord closureSpec) env : List (R.Arg R.Term) env = List.map (varg ∘ term ∘ snd) (List.rev fields) closureTy : R.Term closureTy = List.foldr (λ ty cod → R.def (quote Fun) (ty v∷ cod v∷ [])) (R.def (quote ExplicitUnivalentStr) (srec v∷ erec v∷ [])) (List.map (type ∘ snd) (List.rev fields)) main : R.Term main = R.def (quote idfun) (closureTy v∷ closure v∷ env)
{-# OPTIONS --without-K --rewriting #-} open import HoTT module groups.Pointed where infix 60 ⊙[_,_]ᴳˢ ⊙[_,_]ᴳ record ⊙GroupStructure {i : ULevel} (GEl : Type i) : Type (lsucc i) where constructor ⊙[_,_]ᴳˢ field de⊙ᴳˢ : GroupStructure GEl ptᴳˢ : GEl open GroupStructure de⊙ᴳˢ public open ⊙GroupStructure using (de⊙ᴳˢ; ptᴳˢ) public record ⊙Group (i : ULevel) : Type (lsucc i) where constructor ⊙[_,_]ᴳ field de⊙ᴳ : Group i ptᴳ : Group.El de⊙ᴳ open Group de⊙ᴳ public ⊙exp = Group.exp de⊙ᴳ ptᴳ open ⊙Group using (de⊙ᴳ; ptᴳ) public ⊙Group₀ = ⊙Group lzero infix 0 _⊙→ᴳ_ _⊙→ᴳ_ : ∀ {i j} → ⊙Group i → ⊙Group j → Type (lmax i j) ⊙G ⊙→ᴳ ⊙H = Σ (de⊙ᴳ ⊙G →ᴳ de⊙ᴳ ⊙H) (λ φ → GroupHom.f φ (ptᴳ ⊙G) == ptᴳ ⊙H) infix 30 _⊙≃ᴳ_ _⊙≃ᴳ_ : ∀ {i j} → ⊙Group i → ⊙Group j → Type (lmax i j) ⊙G ⊙≃ᴳ ⊙H = Σ (de⊙ᴳ ⊙G ≃ᴳ de⊙ᴳ ⊙H) (λ φ → GroupIso.f φ (ptᴳ ⊙G) == ptᴳ ⊙H) infixl 120 _⊙⁻¹ᴳ _⊙⁻¹ᴳ : ∀ {i j} {⊙G : ⊙Group i} {⊙H : ⊙Group j} → ⊙G ⊙≃ᴳ ⊙H → ⊙H ⊙≃ᴳ ⊙G _⊙⁻¹ᴳ (iso , iic) = iso ⁻¹ᴳ , ! (equiv-adj (GroupIso.f-equiv iso) iic) ⊙exp-hom : ∀ {i} (⊙G : ⊙Group i) → ⊙[ ℤ-group , 1 ]ᴳ ⊙→ᴳ ⊙G ⊙exp-hom ⊙[ G , pt ]ᴳ = exp-hom G pt , idp is-struct-infinite-cyclic : ∀ {i} {El : Type i} → ⊙GroupStructure El → Type i is-struct-infinite-cyclic ⊙[ G , g ]ᴳˢ = is-equiv (GroupStructure.exp G g) is-infinite-cyclic : ∀ {i} → ⊙Group i → Type i is-infinite-cyclic ⊙[ G , g ]ᴳ = is-struct-infinite-cyclic ⊙[ Group.group-struct G , g ]ᴳˢ isomorphism-preserves-infinite-cyclic : ∀ {i j} → {⊙G : ⊙Group i} {⊙H : ⊙Group j} → ⊙G ⊙≃ᴳ ⊙H → is-infinite-cyclic ⊙G → is-infinite-cyclic ⊙H isomorphism-preserves-infinite-cyclic {⊙G = ⊙[ G , g ]ᴳ} {⊙H = ⊙[ H , h ]ᴳ} (iso , pres-pt) ⊙G-iic = is-eq _ (is-equiv.g ⊙G-iic ∘ GroupIso.g iso) to-from from-to where abstract lemma : Group.exp H h ∼ GroupIso.f iso ∘ Group.exp G g lemma i = ! $ GroupIso.f iso (Group.exp G g i) =⟨ GroupIso.pres-exp iso g i ⟩ Group.exp H (GroupIso.f iso g) i =⟨ ap (λ x → Group.exp H x i) pres-pt ⟩ Group.exp H h i =∎ to-from : ∀ x → Group.exp H h (is-equiv.g ⊙G-iic (GroupIso.g iso x)) == x to-from x = Group.exp H h (is-equiv.g ⊙G-iic (GroupIso.g iso x)) =⟨ lemma (is-equiv.g ⊙G-iic (GroupIso.g iso x)) ⟩ GroupIso.f iso (Group.exp G g (is-equiv.g ⊙G-iic (GroupIso.g iso x))) =⟨ ap (GroupIso.f iso) (is-equiv.f-g ⊙G-iic (GroupIso.g iso x)) ⟩ GroupIso.f iso (GroupIso.g iso x) =⟨ GroupIso.f-g iso x ⟩ x =∎ from-to : ∀ i → is-equiv.g ⊙G-iic (GroupIso.g iso (Group.exp H h i)) == i from-to i = is-equiv.g ⊙G-iic (GroupIso.g iso (Group.exp H h i)) =⟨ ap (is-equiv.g ⊙G-iic ∘ GroupIso.g iso) (lemma i) ⟩ is-equiv.g ⊙G-iic (GroupIso.g iso (GroupIso.f iso (Group.exp G g i))) =⟨ ap (is-equiv.g ⊙G-iic) (GroupIso.g-f iso (Group.exp G g i)) ⟩ is-equiv.g ⊙G-iic (Group.exp G g i) =⟨ is-equiv.g-f ⊙G-iic i ⟩ i =∎ isomorphism-preserves'-infinite-cyclic : ∀ {i j} → {⊙G : ⊙Group i} {⊙H : ⊙Group j} → ⊙G ⊙≃ᴳ ⊙H → is-infinite-cyclic ⊙H → is-infinite-cyclic ⊙G isomorphism-preserves'-infinite-cyclic iso iic = isomorphism-preserves-infinite-cyclic (iso ⊙⁻¹ᴳ) iic
# Kmer Iterator # ============= # # Iterator over all k-mers in a biological sequence. # # This file is a part of BioJulia. # License is MIT: https://github.com/BioJulia/Bio.jl/blob/master/LICENSE.md # Iterate through every k-mer in a nucleotide sequence immutable EachKmerIterator{T,K,S<:Sequence} seq::S step::Int end """ each(::Type{Kmer{T,k}}, seq::Sequence[, step=1]) Initialize an iterator over all k-mers in a sequence `seq` skipping ambiguous nucleotides without changing the reading frame. # Arguments * `Kmer{T,k}`: k-mer type to enumerate. * `seq`: a nucleotide sequence. * `step=1`: the number of positions between iterated k-mers # Examples ``` # iterate over DNA codons for (pos, codon) in each(DNAKmer{3}, dna"ATCCTANAGNTACT", 3) @show pos, codon end ``` """ function each{T,K}(::Type{Kmer{T,K}}, seq::Sequence, step::Integer=1) if eltype(seq) ∉ (DNA, RNA) throw(ArgumentError("element type must be either DNA or RNA nucleotide")) elseif !(0 ≤ K ≤ 32) throw(ArgumentError("k-mer length must be between 0 and 32")) elseif step < 1 throw(ArgumentError("step size must be positive")) end return EachKmerIterator{T,K,typeof(seq)}(seq, step) end eachkmer{A<:DNAAlphabet}(seq::BioSequence{A}, K::Integer, step::Integer=1) = each(DNAKmer{Int(K)}, seq, step) eachkmer{A<:RNAAlphabet}(seq::BioSequence{A}, K::Integer, step::Integer=1) = each(RNAKmer{Int(K)}, seq, step) eachkmer(seq::ReferenceSequence, K::Integer, step::Integer=1) = each(DNAKmer{Int(K)}, seq, step) Base.eltype{T,k,S}(::Type{EachKmerIterator{T,k,S}}) = Tuple{Int,Kmer{T,k}} function Base.iteratorsize{T,k,S}(::Type{EachKmerIterator{T,k,S}}) return Base.SizeUnknown() end @inline function Base.start{T,K}(it::EachKmerIterator{T,K}) nextn = find_next_ambiguous(it.seq, first(it.seq.part)) pair = Nullable{Tuple{Int,Kmer{T,K}}}() pair, nextn = nextkmer(Kmer{T,K}, it.seq, 1, it.step, nextn, pair) return pair, nextn end @inline function Base.done{T,K}(::EachKmerIterator{T,K}, state) return isnull(state[1]) end @inline function Base.next{T,K}(it::EachKmerIterator{T,K}, state) pair, nextn = state from, kmer = get(pair) return (from, kmer), nextkmer(Kmer{T,K}, it.seq, from + it.step, it.step, nextn, pair) end @inline function nextkmer{T,K}(::Type{Kmer{T,K}}, seq, i, step, nextn, kmer) # find a position from which we can extract at least K unambiguous nucleotides from = i while nextn > 0 && nextn - from < K from = nextn + 1 # align `from` since it must be a multiple of `step` r = rem(from - 1, step) if r > 0 from += step - r end nextn = find_next_ambiguous(seq, from) end if endof(seq) - from + 1 < K # no available kmer return Nullable{Tuple{Int,Kmer{T,K}}}(), nextn end newkmer = extract_kmer(Kmer{T,K}, seq, from, kmer) # update `nextn` for the next iteration if needed if nextn > 0 && nextn < from + step nextn = find_next_ambiguous(seq, from) end return Nullable((from, newkmer)), nextn end @inline function extract_kmer{K,T}(::Type{Kmer{T,K}}, seq, from, pair) if isnull(pair) || get(pair)[1] + K - 1 < from # the last kmer doesn't overlap the extracting one x = UInt64(0) for k in 1:K nt = inbounds_getindex(seq, from + k - 1) x = x << 2 | trailing_zeros(nt) end else pos, kmer = get(pair) # |<-K->| # ------- # ------- # ^ ^ # pos from n = from - pos from += K - n x = UInt64(kmer) for k in 1:n nt = inbounds_getindex(seq, from + k - 1) x = x << 2 | trailing_zeros(nt) end end return Kmer{T,K}(x) end
Require Import VST.floyd.proofauto. (* Import the Verifiable C system *) Require Import VST.progs.bin_search. (* Import the AST of this C program *) (* The next line is "boilerplate", always required after importing an AST. *) #[export] Instance CompSpecs : compspecs. make_compspecs prog. Defined. Definition Vprog : varspecs. mk_varspecs prog. Defined. Fixpoint sorted (l : list Z) : Prop := match l with | [] => True | x::rest => match rest with [] => True | y::_ => x <= y /\ sorted rest end end. (* Beginning of the API spec for the bin_search.c program *) Definition search_spec := DECLARE _search WITH a: val, sh : share, contents : list Z, tgt : Z, lo : Z, hi : Z PRE [ tptr tint, tint, tint, tint ] PROP (readable_share sh; 0 <= lo <= Int.max_signed; hi <= Zlength contents <= Int.max_signed; Int.min_signed <= hi <= Int.max_signed / 2; sorted contents; Forall (fun x => Int.min_signed <= x <= Int.max_signed) contents; Int.min_signed <= tgt <= Int.max_signed) PARAMS (a; Vint (Int.repr tgt); Vint (Int.repr lo); Vint (Int.repr hi)) SEP (data_at sh (tarray tint (Zlength contents)) (map Vint (map Int.repr contents)) a) POST [ tint ] EX i:Z, PROP (if in_dec Z.eq_dec tgt (sublist lo hi contents) then Znth i contents = tgt else i = -1) RETURN (Vint (Int.repr i)) SEP (data_at sh (tarray tint (Zlength contents)) (map Vint (map Int.repr contents)) a). (* The spec of "int main(void){}" always looks like this. *) Definition main_spec := DECLARE _main WITH gv: globals PRE [] main_pre prog tt gv POST [ tint ] main_post prog gv. (* Packaging the API spec all together. *) Definition Gprog : funspecs := ltac:(with_library prog [search_spec; main_spec]). Lemma sublist_nil1 : forall A i j (l : list A), j <= i -> sublist i j l = []. Proof. intros *. apply sublist_nil_gen. Qed. Lemma Znth_In : forall A (d: Inhabitant A) i (l : list A) x (Hrange : 0 <= i < Zlength l) (Hnth : Znth i l = x), In x l. Proof. unfold Znth; intros. destruct (Z_lt_dec i 0); [lia|]. subst; apply nth_In. rewrite Zlength_correct in Hrange; auto. rep_lia. Qed. Lemma In_Znth : forall A (d: Inhabitant A) (l : list A) x, In x l -> exists i, 0 <= i < Zlength l /\ Znth i l = x. Proof. unfold Znth; intros. apply In_nth with (d := d) in H; destruct H as (n & ? & ?). exists (Z.of_nat n); split. - rewrite Zlength_correct; lia. - destruct (Z_lt_dec (Z.of_nat n) 0); [lia|]. rewrite Nat2Z.id; auto. Qed. Lemma sublist_of_nil : forall A i j, sublist i j (nil : list A) = []. Proof. intros; unfold sublist. rewrite firstn_nil, skipn_nil; auto. Qed. Fixpoint sorted2 l := match l with | [] => True | x :: rest => Forall (fun y => x <= y) rest /\ sorted2 rest end. Lemma sorted_equiv : forall l, sorted l <-> sorted2 l. Proof. induction l; simpl. - reflexivity. - destruct l. + simpl; split; auto. + rewrite IHl; simpl; split; intros (? & Hall & ?); split3; auto. * constructor; auto. rewrite Forall_forall in *; intros ? Hin. specialize (Hall _ Hin); lia. * inversion H. auto. Qed. Lemma sorted_mono : forall l i j (Hsort : sorted l) (Hi : 0 <= i <= j) (Hj : j < Zlength l), Znth i l <= Znth j l. Proof. induction l; intros. * rewrite !Znth_nil. lia. * rewrite sorted_equiv in Hsort. destruct Hsort as [H9 Hsort]. rewrite <- sorted_equiv in Hsort. rewrite Forall_forall in H9. rewrite Zlength_cons in Hj. destruct (zeq i 0). + subst i; rewrite Znth_0_cons. destruct (zeq j 0). - subst j. rewrite Znth_0_cons. lia. - rewrite Znth_pos_cons by lia. apply H9. eapply Znth_In; [ | reflexivity]; lia. + rewrite !Znth_pos_cons by lia. apply IHl; auto; lia. Qed. Lemma In_sorted_range : forall lo hi x l (Hsort : sorted l) (Hlo : 0 <= lo <= hi) (Hhi : hi <= Zlength l) (Hin : In x (sublist lo hi l)), Znth lo l <= x <= Znth (hi - 1) l. Proof. intros. generalize (In_Znth _ _ _ _ Hin); intros (i & Hrange & Hi). rewrite Zlength_sublist in Hrange by auto. rewrite Znth_sublist in Hi by lia. subst; split; apply sorted_mono; auto; lia. Qed. Lemma In_sorted_gt : forall x i n l lo hi (Hsort : sorted l) (Hlo : lo >= 0) (Hhi : hi <= Zlength l) (Hin : In x (sublist lo hi l)) (Hi : lo <= i < hi) (Hn : Znth i l = n) (Hgt : n < x), In x (sublist (i + 1) hi l). Proof. intros. rewrite sublist_split with (mid := i + 1) in Hin; try lia. rewrite in_app in Hin; destruct Hin; auto. generalize (In_sorted_range lo (i + 1) x _ Hsort); intro X. repeat (lapply X; [clear X; intro X | lia]). replace (i + 1 - 1) with i in X by lia. specialize (X H); subst; lia. Qed. Lemma In_sorted_lt : forall x i n l lo hi (Hsort : sorted l) (Hlo : lo >= 0) (Hhi : hi <= Zlength l) (Hin : In x (sublist lo hi l)) (Hi : lo <= i < hi) (Hn : Znth i l = n) (Hgt : x < n), In x (sublist lo i l). Proof. intros. rewrite sublist_split with (mid := i) in Hin; try lia. rewrite in_app in Hin; destruct Hin; auto. generalize (In_sorted_range i hi x _ Hsort); intro X. repeat (lapply X; [clear X; intro X | lia]). specialize (X H); subst; lia. Qed. Lemma Znth_In_sublist : forall A (d: Inhabitant A) i (l : list A) lo hi (Hlo : 0 <= lo <= i) (Hhi : i < hi <= Zlength l), In (Znth i l) (sublist lo hi l). Proof. intros. apply Znth_In with (i := i - lo)(d := d). - rewrite Zlength_sublist; lia. - rewrite <- (Z.sub_simpl_r i lo) at 2. apply Znth_sublist; lia. Qed. Lemma sublist_In_sublist : forall A (l : list A) x lo hi lo' hi' (Hlo : 0 <= lo <= lo') (Hhi : hi' <= hi), In x (sublist lo' hi' l) -> In x (sublist lo hi l). Proof. intros. apply @sublist_In with (lo := lo' - lo) (hi := hi' - lo); rewrite sublist_sublist; try split; try lia. - repeat rewrite Z.sub_simpl_r; auto. - destruct (Z_le_dec hi' lo'); try lia. rewrite sublist_nil1 in *; auto; simpl in *; contradiction. Qed. Lemma body_search: semax_body Vprog Gprog f_search search_spec. Proof. start_function. destruct H0. assert (H6 := Int.min_signed_neg). forward_while (EX lo' : Z, EX hi' : Z, PROP (0 <= lo' <= Int.max_signed; Int.min_signed <= hi' <= Int.max_signed / 2; hi' <= Zlength contents; In tgt (sublist lo hi contents) <-> In tgt (sublist lo' hi' contents)) LOCAL (temp _a a; temp _tgt (Vint (Int.repr tgt)); temp _lo (Vint (Int.repr lo')); temp _hi (Vint (Int.repr hi'))) SEP (data_at sh (tarray tint (Zlength contents)) (map Vint (map Int.repr contents)) a)). * Exists lo; Exists hi; entailer!!. * entailer!!. * match goal with H : _ <-> _ |- _ => rename H into H_tgt_sublist end. forward. (* mid = (lo + hi) >> 1; *) { entailer!!. clear - H8 HRE H7. set (j := Int.max_signed / 2) in *; compute in j; subst j. set (j := Int.max_signed) in *; compute in j; subst j. set (j := Int.min_signed) in *; compute in j; subst j. lia. } rewrite add_repr, Int.shr_div_two_p. change (two_p (Int.unsigned (Int.repr 1))) with 2. assert (Hlo'hi': lo' + hi' <= Int.max_signed). { transitivity (Int.max_signed / 2 + Int.max_signed / 2). - apply Zplus_le_compat; lia. - rewrite Zplus_diag_eq_mult_2, Z.mul_comm. apply Z_mult_div_ge; lia. } rewrite !Int.signed_repr by lia. set (mid := (lo' + hi') / 2) in *. assert (H13: 0 <= mid < Zlength contents) by (subst; split; [apply Z_div_pos | apply Zdiv_lt_upper_bound]; lia). assert (H15: lo' <= mid < hi') by (split; [apply Zdiv_le_lower_bound | apply Zdiv_lt_upper_bound]; lia). assert (H16: Int.min_signed <= Znth mid contents <= Int.max_signed) by (rewrite Forall_forall in H3; apply H3; eapply Znth_In; eauto). clear H3 Hlo'hi' H H0 H1. clearbody mid. forward. (* val = a[mid]; *) autorewrite with sublist. forward_if. - forward. (* return mid; *) Exists mid; entailer!!. rewrite if_true; auto. rewrite H_tgt_sublist. apply Znth_In_sublist; lia. - forward_if. + forward. (* lo = mid + 1; *) Exists ((mid + 1), hi'); simpl fst; simpl snd; entailer!!. rewrite H_tgt_sublist. split; intro Hin'. eapply In_sorted_gt; eauto; lia. eapply sublist_In_sublist; try apply Hin'; lia. + forward. (* hi=mid; *) Exists (lo',mid). simpl fst. simpl snd. entailer!. rewrite H_tgt_sublist. split; intro Hin'. eapply In_sorted_lt; eauto; lia. eapply sublist_In_sublist; try apply Hin'; lia. * forward. (* return -1; *) Exists (-1); entailer!. rewrite if_false; auto. match goal with H : _ <-> _ |- _ => rewrite H end. rewrite sublist_nil1 by lia. clear; simpl; tauto. Qed. (* Contents of the extern global initialized array "_four" *) Definition four_contents := [1; 2; 3; 4]. Lemma body_main: semax_body Vprog Gprog f_main main_spec. Proof. start_function. forward_call (gv _four,Ews,four_contents,3,0,4). { change (Zlength four_contents) with 4. repeat constructor; computable. } Intro r; forward. Qed. #[export] Existing Instance NullExtension.Espec. Lemma prog_correct: semax_prog prog tt Vprog Gprog. Proof. prove_semax_prog. semax_func_cons body_search. semax_func_cons body_main. Qed.
{-# OPTIONS --no-copatterns #-} -- Andreas, 2015-08-26: copatterns are on by default now. -- Andreas, James, 2011-11-24 -- trigger error message 'NeedOptionCopatterns' module NeedOptionCopatterns where record Bla : Set2 where field bla : Set1 open Bla f : Bla bla f = Set -- should request option --copatterns
The dimension of the hyperplane $\{x \in \mathbb{R}^n \mid a \cdot x = 0\}$ is $n-1$.
Inductive day : Type := | monday : day | tuesday : day | wednesday : day | thursday : day | friday : day | saturday : day | sunday : day. Definition next_weekday(d:day) : day := match d with | monday => tuesday | tuesday => wednesday | wednesday => thursday | thursday => friday | friday => monday | saturday => monday | sunday => monday end. Compute (next_weekday friday). Compute (next_weekday (next_weekday saturday)). Example test_next_weekday : (next_weekday (next_weekday saturday)) = tuesday. Proof. simpl. reflexivity. Qed. Print test_next_weekday.
%WEIGHTEDMEDIANFILTER Applies weighted median filter to an image % % dst = cv.weightedMedianFilter(src, joint) % dst = cv.weightedMedianFilter(src, joint, 'OptionName',optionValue, ...) % % ## Input % * __src__ Source 8-bit or floating-point, 1-channel or 3-channel image. % * __joint__ Joint 8-bit, 1-channel or 3-channel image. % % ## Output % * __dst__ Destination image of the same size and type as `src`. % % ## Options % * __Radius__ Radius of filtering kernel, should be a positive integer. % Default 7 % * __Sigma__ Filter range standard deviation for the joint image. % Default 25.5 % * __WeightType__ The type of weight definition. Specifies weight types of % weighted median filter, default 'EXP'. One of: % * __EXP__ `exp(-|I1-I2|^2 / (2*sigma^2))` % * __IV1__ `(|I1-I2| + sigma)^-1` % * __IV2__ `(|I1-I2|^2 + sigma^2)^-1` % * __COS__ `dot(I1,I2) / (|I1|*|I2|)` % * __JAC__ `(min(r1,r2) + min(g1,g2) + min(b1,b2)) / (max(r1,r2) + max(g1,g2) + max(b1,b2))` % * __OFF__ unweighted % * __Mask__ A 0-1 mask that has the same size with `I`. This mask is used to % ignore the effect of some pixels. If the pixel value on mask is 0, the % pixel will be ignored when maintaining the joint-histogram. This is useful % for applications like optical flow occlusion handling. Not set by default. % % For more details about this implementation, please see [zhang2014100+]. % % ## References % [zhang2014100+]: % > Qi Zhang, Li Xu, and Jiaya Jia. "100+ Times Faster Weighted Median Filter % > (WMF)". In Computer Vision and Pattern Recognition (CVPR), 2014 IEEE % > Conference on, pages 2830-2837. IEEE, 2014. % % See also: cv.medianBlur, cv.jointBilateralFilter %
\section{okcounterdctl.pl \label{s:okcounterdctl}} \cc{okcounterdctl.pl} provides a convenient way to send commands to \cc{okcounterd}. \subsection{usage} To run \cc{okcounterdctl.pl} on the command line, use: \begin{lstlisting}[mathescape=true] okcounterdctl.pl [OPTION] $\ldots$ \end{lstlisting} The command line options are: \begin{description*} \item[-c \textless file\textgreater] use the specified gpscv configuration file \item[-d] run in debugging mode \item[-g \textless $0|1$\textgreater] disable/enable the system GPIO \item[-h] print help and exit \item[-c \textless $1\ldots6$\textgreater] set the PPS OUT source \item[-q] query the counter configuration \item[-v] print version information and exit \end{description*} \subsection{configuration file} \cc{okcounterdctl.pl} does't have a configuration file but uses \cc{gpscv.conf} to determine the port used by \cc{okcounterd}. \subsection{log file} \cc{okcounterdctl.pl} doesn't produce a log file.
lemma norm_mult_less: "norm x < r \<Longrightarrow> norm y < s \<Longrightarrow> norm (x * y) < r * s" for x y :: "'a::real_normed_algebra"
module GridOps import Data.Vect import src.Tensor %access public export shiftLeft : a -> Vect n a -> Vect n a shiftLeft e [] = [] shiftLeft {n = S n} e (x :: xs) = replace {P = (\x => Vect x a)} (plusCommutative n 1) (xs ++ [e]) shiftRight : a -> Vect n a -> Vect n a shiftRight e xs = reverse $ shiftLeft e $ reverse xs data Dir = Left | Right | Up | Down shift : List Dir -> a -> Vect n (Vect m a) -> Vect n (Vect m a) shift [] e xss = xss shift (Left :: ds) e xss = shift ds e (map (shiftLeft e) xss) shift (Right :: ds) e xss = shift ds e (map (shiftRight e) xss) shift (Up :: ds) e xss = shift ds e (shiftLeft (replicate _ e) xss) shift (Down :: ds) e xss = shift ds e (shiftRight (replicate _ e) xss) data Pos = First | Last | Middle toPos : Fin n -> Pos toPos {n} fin with (finToNat fin) toPos {n} fin | Z = First toPos {n} fin | n' = if n == (S n') then Last else Middle lookup : Fin n -> Fin m -> List Dir -> a -> Vect n (Vect m a) -> a lookup n m ds x xss = index n m $ shift ds x xss
At Winters & Yonker, P.A., we work quickly to protect our clients. We will begin gathering the evidence needed to build a strong case as soon as possible. We are known as “aggressive attorneys,” and indeed, our experienced and dedicated personal injury lawyers are prepared to fight for you from day one. Call us at (813) 223-6200 or schedule a free initial consultation at our Tampa offices or in your home. A serious accident can change your life in ways most people don’t understand. The daily battle with pain, the mounting medical bills and the disruption of your life can take a tremendous toll. We know how difficult this is for you. We understand how it feels to have your life turned upside down in an instant. We can help you get through this. Our attorneys help victims of a wide range of accidents. From pedestrian accidents and car wrecks to semi-truck accidents and slip-and-fall cases, we fight for victims of serious personal injuries. When our law firm represents you, we will review your medical records as soon as possible. We can most likely help you locate and gain access to well-qualified physicians, even if your health insurance coverage is limited. The quality of the care you receive in the early days after your injury can make a huge difference, both medically and legally. We will help keep communication channels open between you, your doctors and our attorneys to make sure your care is handled properly. We have refined our processes for recovering compensation for injured people after years of practice. We are known for our personalized, aggressive representation. We help clients tap into all available sources of compensation. We will help you get the money you deserve for medical expenses, lost wages, pain and suffering, property damage and more. As a lawyer, Marc is compelled by a desire to seek justice for the injured. Marc has always focused on personal injury law and feels called to help those who are battling against large insurers for the compensation they deserve. Bill began his career as a personal injury lawyer at a larger firm, where he had the opportunity to help numerous clients who were being denied their due compensation because of overreach by insurance companies. Smith finds gratitude in his work through “the ability to leave someone in a better situation than when they came to you.” He loves meeting and interacting with people, and encourages you to call him today! Mr. Seplowe is experienced in Personal Injury law. His goal is to help you understand the legal issues you face and to obtain the maximum value for your claim either through settlement or trial. During his undergrad years, Allen interned at the Palomar Medical Center in Escondido, California, assisting in the legal department, and was privy to the different obstacles clients faced after experiencing an accident. Trevor has worked in personal injury law since his graduation in 2015. He joined Winters & Yonker in 2016 and is a member of the Florida Bar Association and the American Bar Association. It was Matt’s first law class in college when he knew that he wanted to practice law and advocate for those in need of help. Matt later graduated from Stetson University College of Law in 2017. Patrick appreciates the firm’s dedication to its clients and assists in providing qualified legal advice and representation to those in need. At Winters & Yonker, Patrick serves as a mentor to the associate attorneys as they master the ropes of litigation and assist clients in finding justice.
twice : (a -> a) -> a -> a twice f x = f (f x) Shape : Type rotate : Shape -> Shape turn_around : Shape -> Shape turn_around = twice rotate
structure Graph' where V : Type E : Type init : E → V bar : E → E barInv : bar ∘ bar = id barNoFP : ∀ e: E, bar e ≠ e structure Graph(V: Type) (E: Type) where init : E → V bar : E → E barInv : bar ∘ bar = id barNoFP : ∀ e: E, bar e ≠ e @[inline] def term{V: Type}{E: Type}(graph: Graph V E): E → V := fun e => graph.init (graph.bar e) example : Graph Unit Bool:= let init : Bool → Unit := fun e => () let bar : Bool → Bool := fun e => ¬ e let barInv : bar ∘ bar = id := by apply funext ; intro x ; cases x <;> rfl let barNoFP : ∀ e: Bool, bar e ≠ e := by intro e; cases e <;> simp ⟨init, bar, barInv, barNoFP⟩ example : Graph Unit Bool:= by apply Graph.mk case init => intro x; exact () case bar => intro x exact not x case barInv => apply funext ; intro x ; cases x <;> rfl case barNoFP => intro e; cases e <;> simp inductive EdgePath{V: Type}{E: Type}(graph: Graph V E): V → V → Type where | single : (x: V) → EdgePath graph v v | cons : {x y z : V} → (e : E) → graph.init e = x → term graph e = y → EdgePath graph y z → EdgePath graph x z def length{V: Type}{E: Type}{graph: Graph V E}{x y: V}: EdgePath graph x y → Nat | EdgePath.single x => 0 | EdgePath.cons _ _ _ path => length path + 1
import order.galois_connection variables (P : Type) [partial_order P] def presheaf : Type := { s : P → Prop // ∀ a b, a ≤ b → s b → s a } variable {P} namespace presheaf instance : has_coe_to_fun (presheaf P) (λ _, P → Prop) := ⟨subtype.val⟩ @[simp] lemma coe_mk (s : P → Prop) (hs : ∀ a b, a ≤ b → s b → s a) : @coe_fn (presheaf P) _ _ (⟨s, hs⟩ : presheaf P) = s := rfl instance : partial_order (presheaf P) := { le := λ A B, ∀ x, A x → B x, le_trans := λ A B C hAB hBC x hAx, hBC _ (hAB _ hAx), le_refl := λ A x, id, le_antisymm := λ A B hAB hBA, subtype.val_injective (funext $ λ x, propext ⟨hAB _, hBA _⟩) } lemma le_def {A B : presheaf P} : A ≤ B = ∀ x, A x → B x := rfl instance : has_Inf (presheaf P) := { Inf := λ s, ⟨λ p, ∀ A : presheaf P, A ∈ s → A p, λ a b hab h A hAs, A.2 _ _ hab (h _ hAs)⟩ } instance : complete_lattice (presheaf P) := complete_lattice_of_Inf _ (λ s, begin split, { dsimp [Inf, lower_bounds], intros A hAs p h, apply h, exact hAs }, { dsimp [Inf, upper_bounds, lower_bounds], intros A h p hAp B hBs, apply h, exact hBs, exact hAp } end) lemma infi_def {ι : Sort*} (A : ι → presheaf P) : infi A = ⟨λ p, ∀ i, A i p, λ x y hxy h i, (A i).2 _ y hxy (h i)⟩ := le_antisymm (infi_le_iff.2 (λ B h p hBp i, h i _ hBp)) (le_infi (λ i p h, h _)) lemma supr_def {ι : Sort*} (A : ι → presheaf P) : supr A = ⟨λ p, ∃ i, A i p, λ x y hxy ⟨i, hi⟩, ⟨i, (A i).2 x y hxy hi⟩⟩ := le_antisymm (supr_le_iff.2 (λ i p h, ⟨i, h⟩)) (le_supr_iff.2 (λ B h p ⟨i, hi⟩, h i _ hi)) end presheaf def yoneda (a : P) : presheaf P := ⟨λ b, b ≤ a, λ b c, le_trans⟩ def yoneda_le_iff (A : presheaf P) (p : P) : yoneda p ≤ A ↔ A p := begin simp [yoneda, presheaf.le_def], split, { intro h, apply h, exact le_rfl }, { intros h x hxp, apply A.2, apply hxp, exact h } end lemma yoneda_mono {a b : P} : yoneda a ≤ yoneda b ↔ a ≤ b := begin rw yoneda_le_iff, refl, end lemma presheaf.eq_supr {A : presheaf P} : A = ⨆ (p : P) (h : A p), yoneda p := begin apply le_antisymm; simp only [le_supr_iff, supr_le_iff, yoneda_le_iff], { intros B hB p, exact hB p }, { exact λ _, id } end variable (P) def copresheaf : Type := { s : set P // ∀ a b, a ≤ b → s a → s b } variable {P} namespace copresheaf instance : has_coe_to_fun (copresheaf P) (λ _, P → Prop) := ⟨subtype.val⟩ @[simp] lemma coe_mk (s : P → Prop) (hs : ∀ a b, a ≤ b → s a → s b) : @coe_fn (copresheaf P) _ _ (⟨s, hs⟩ : copresheaf P) = s := rfl instance : partial_order (copresheaf P) := { le := λ A B, ∀ x, B x → A x, le_trans := λ A B C hAB hBC x hAx, hAB _ (hBC _ hAx), le_refl := λ A x, id, le_antisymm := λ A B hAB hBA, subtype.val_injective (funext $ λ x, propext ⟨hBA _, hAB _⟩) } instance : has_Sup (copresheaf P) := { Sup := λ s, ⟨λ p, ∀ A : copresheaf P, A ∈ s → A p, λ a b hab h A hAs, A.2 _ _ hab (h _ hAs)⟩ } instance : complete_lattice (copresheaf P) := complete_lattice_of_Sup _ (λ s, begin split, { dsimp [Sup, upper_bounds], intros A hAs p h, apply h, exact hAs }, { dsimp [Inf, upper_bounds, lower_bounds], intros A h p hAp B hBs, apply h, exact hBs, exact hAp } end) lemma infi_def {ι : Sort*} (A : ι → copresheaf P) : infi A = ⟨λ p, ∃ i, A i p, λ x y hxy ⟨i, hi⟩, ⟨i, (A i).2 x y hxy hi⟩⟩ := le_antisymm (infi_le_iff.2 (λ B h p ⟨i, hi⟩, h i _ hi)) (le_infi_iff.2 (λ i p h, ⟨i, h⟩)) lemma supr_def {ι : Sort*} (A : ι → copresheaf P) : supr A = ⟨λ p, ∀ i, A i p, λ x y hxy h i, (A i).2 _ y hxy (h i)⟩ := le_antisymm (supr_le_iff.2 (λ i p h, h _)) (le_supr_iff.2 (λ B h p hBp i, h i _ hBp)) lemma le_def {A B : copresheaf P} : A ≤ B = ∀ x, B x → A x := rfl end copresheaf def coyoneda (a : P) : copresheaf P := ⟨λ b, a ≤ b, λ b c, function.swap le_trans⟩ def le_coyoneda_iff (A : copresheaf P) (p : P) : A ≤ coyoneda p ↔ A p := begin simp [yoneda, copresheaf.le_def], split, { intro h, apply h, exact le_rfl }, { intros h x hxp, apply A.2, apply hxp, exact h } end lemma copresheaf.eq_infi {A : copresheaf P} : A = ⨅ (p : P) (h : A p), coyoneda p := begin apply le_antisymm; simp only [le_infi_iff, infi_le_iff, le_coyoneda_iff], { exact λ _, id }, { intros B hB p, exact hB p }, end lemma is_glb_yoneda {x : P} : is_glb {y | coyoneda (yoneda x) y} (yoneda x) := begin split, { dsimp [lower_bounds, yoneda, coyoneda], exact λ _, id }, { dsimp [upper_bounds, lower_bounds, yoneda, coyoneda], intros A h y hAy, exact @h (yoneda x) (λ _, id) y hAy } end lemma is_lub_coyoneda {x : P} : is_lub {y | yoneda (coyoneda x) y} (coyoneda x) := begin split, { dsimp [lower_bounds, yoneda, coyoneda], exact λ _, id }, { dsimp [upper_bounds, lower_bounds, yoneda, coyoneda], intros A h y hAy, exact @h (coyoneda x) (λ _, id) y hAy } end def u (A : presheaf P) : copresheaf P := ⟨λ p, coyoneda A (yoneda p), λ a b hab h x hxA, le_trans (h _ hxA) hab⟩ lemma u_mono : monotone (@u P _) := λ A B h p hp q hAq, hp _ (h _ hAq) def d (B : copresheaf P) : presheaf P := ⟨λ q, yoneda B (coyoneda q), λ a b hab h x hxA, le_trans hab (h _ hxA)⟩ lemma d_mono : monotone (@d P _) := λ A B h p hp q hAq, hp _ (h _ hAq) example (A : presheaf P) : d (u A) = A := begin dsimp [d, u, coyoneda, yoneda], apply subtype.ext, dsimp, apply funext, intros, simp only [presheaf.le_def, copresheaf.le_def], dsimp, apply le_antisymm, simp [presheaf.le_def], ext, rw [presheaf.le_def], end def gc : galois_connection (@u P _) d := begin intros A B, dsimp [u, d], split, { intros h x hxA y hyB, apply h, assumption, assumption }, { intros h x hxA y hyB, apply h, assumption, assumption } end lemma le_d_u (A : presheaf P) : A ≤ d (u A) := gc.le_u_l A lemma u_d_le (A : copresheaf P) : u (d A) ≤ A := gc.l_u_le A variable (P) structure completion : Type := ( to_presheaf : presheaf P ) ( to_copresheaf : copresheaf P ) ( d_to_copresheaf : d to_copresheaf = to_presheaf ) ( u_to_presheaf : u to_presheaf = to_copresheaf ) attribute [simp] completion.d_to_copresheaf completion.u_to_presheaf variable {P} instance : partial_order (completion P) := partial_order.lift completion.to_copresheaf begin rintros ⟨_, _, h₁, _⟩ ⟨_, _, h₂, _⟩, simp [← h₁, ← h₂] {contextual := tt} end @[simp] lemma u_d_u (A : presheaf P) : (u (d (u A))) = (u A) := le_antisymm begin dsimp [d, u], intros p hp, dsimp [yoneda, coyoneda, presheaf.le_def] at *, intros q h, apply h, apply hp end (gc.monotone_l (le_d_u _)) @[simp] lemma d_u_d (A : copresheaf P) : d (u (d A)) = d A := le_antisymm (gc.monotone_u (u_d_le _)) begin dsimp [d, u], intros p hp, dsimp [yoneda, coyoneda, presheaf.le_def] at *, intros q h, apply h, apply hp end @[simp] lemma u_yoneda (p : P) : u (yoneda p) = coyoneda p := begin rw [u], conv_lhs {dsimp [coyoneda]}, simp only [yoneda_le_iff], refl end @[simp] lemma d_coyoneda (p : P) : d (coyoneda p) = yoneda p := begin rw [d], conv_lhs {dsimp only [yoneda]}, simp only [le_coyoneda_iff], refl end lemma le_iff_to_copresheaf {A B : completion P} : (A ≤ B) ↔ (A.to_copresheaf ≤ B.to_copresheaf) := iff.rfl lemma le_iff_to_presheaf {A B : completion P} : (A ≤ B) ↔ (A.to_presheaf ≤ B.to_presheaf) := begin rw [le_iff_to_copresheaf], split, { intro h, rw [← completion.d_to_copresheaf, ← completion.d_to_copresheaf], exact d_mono h }, { intro h, rw [← completion.u_to_presheaf, ← completion.u_to_presheaf], exact u_mono h } end def presheaf.to_completion (A : presheaf P) : completion P := ⟨d (u A), u A, by simp, by simp⟩ def copresheaf.to_completion (A : copresheaf P) : completion P := ⟨d A, u (d A), by simp, by simp⟩ def to_completion (p : P) : completion P := ⟨yoneda p, coyoneda p, by simp, by simp⟩ @[simp] lemma presheaf.to_completion_to_presheaf (p : completion P) : p.to_presheaf.to_completion = p := begin cases p, simp [completion.to_presheaf, presheaf.to_completion, *], end @[simp] lemma copresheaf.to_completion_to_copresheaf (p : completion P) : p.to_copresheaf.to_completion = p := begin cases p, simp [completion.to_copresheaf, copresheaf.to_completion, *], end @[simp] lemma to_completion_to_presheaf (p : P) : (to_completion p).to_presheaf = yoneda p := rfl @[simp] lemma to_completion_to_copresheaf (p : P) : (to_completion p).to_copresheaf = coyoneda p := rfl variables {P} def gi : galois_insertion (@presheaf.to_completion P _) (completion.to_presheaf) := galois_connection.to_galois_insertion (λ A B, begin split, { simp [presheaf.to_completion, le_iff_to_presheaf, d, u, coyoneda, presheaf.le_def, yoneda], intros h p hAp, apply h, intros q hq, apply hq, exact hAp }, { intro h, simp [presheaf.to_completion, le_iff_to_presheaf], rw [← B.d_to_copresheaf, ← B.u_to_presheaf], refine d_mono (u_mono h) } end) (by simp [presheaf.to_completion, le_iff_to_presheaf]) def gci : galois_coinsertion (completion.to_copresheaf) (@copresheaf.to_completion P _) := galois_connection.to_galois_coinsertion (λ A B, begin split, { intro h, simp [copresheaf.to_completion, le_iff_to_copresheaf], rw [← A.u_to_presheaf, ← A.d_to_copresheaf], exact u_mono (d_mono h) }, { simp [copresheaf.to_completion, le_iff_to_copresheaf, d, u, coyoneda, copresheaf.le_def, yoneda], intros h p hAp, apply h, intros q hq, apply hq, exact hAp }, end) (by simp [copresheaf.to_completion, le_iff_to_copresheaf]) instance : complete_lattice (completion P) := galois_insertion.lift_complete_lattice gi lemma completion.supr_def {ι : Sort*} (a : ι → completion P) : (⨆ i : ι, a i).to_copresheaf = (⨆ i, (a i).to_copresheaf) := (@gci P _).gc.l_supr lemma completion.infi_def {ι : Sort*} (a : ι → completion P) : (⨅ i : ι, a i).to_presheaf = (⨅ i, (a i).to_presheaf) := (@gi P _).gc.u_infi
// Copyright (C) 2012-2015 Internet Systems Consortium, Inc. ("ISC") // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include <config.h> #include <exceptions/exceptions.h> #include <dns/name.h> #include <dns/master_loader.h> #include <dns/master_loader_callbacks.h> #include <dns/rrclass.h> #include <dns/rrcollator.h> #include <dns/rdata.h> #include <dns/rrset.h> #include <dns/rrttl.h> #include <gtest/gtest.h> #include <boost/bind.hpp> #include <sstream> #include <vector> using std::vector; using namespace isc::dns; using namespace isc::dns::rdata; namespace { typedef RRCollator::AddRRsetCallback AddRRsetCallback; void addRRset(const RRsetPtr& rrset, vector<ConstRRsetPtr>* to_append, const bool* do_throw) { if (*do_throw) { isc_throw(isc::Unexpected, "faked failure"); } to_append->push_back(rrset); } class RRCollatorTest : public ::testing::Test { protected: RRCollatorTest() : origin_("example.com"), rrclass_(RRClass::IN()), rrttl_(3600), throw_from_callback_(false), collator_(boost::bind(addRRset, _1, &rrsets_, &throw_from_callback_)), rr_callback_(collator_.getCallback()), a_rdata1_(createRdata(RRType::A(), rrclass_, "192.0.2.1")), a_rdata2_(createRdata(RRType::A(), rrclass_, "192.0.2.2")), txt_rdata_(createRdata(RRType::TXT(), rrclass_, "test")), sig_rdata1_(createRdata(RRType::RRSIG(), rrclass_, "A 5 3 3600 20000101000000 20000201000000 " "12345 example.com. FAKE")), sig_rdata2_(createRdata(RRType::RRSIG(), rrclass_, "NS 5 3 3600 20000101000000 20000201000000 " "12345 example.com. FAKE")) {} void checkRRset(const Name& expected_name, const RRClass& expected_class, const RRType& expected_type, const RRTTL& expected_ttl, const vector<ConstRdataPtr>& expected_rdatas) { SCOPED_TRACE(expected_name.toText(true) + "/" + expected_class.toText() + "/" + expected_type.toText()); // This test always clears rrsets_ to confirm RRsets are added // one-by-one ASSERT_EQ(1, rrsets_.size()); ConstRRsetPtr actual = rrsets_[0]; EXPECT_EQ(expected_name, actual->getName()); EXPECT_EQ(expected_class, actual->getClass()); EXPECT_EQ(expected_type, actual->getType()); EXPECT_EQ(expected_ttl, actual->getTTL()); ASSERT_EQ(expected_rdatas.size(), actual->getRdataCount()); vector<ConstRdataPtr>::const_iterator it = expected_rdatas.begin(); for (RdataIteratorPtr rit = actual->getRdataIterator(); !rit->isLast(); rit->next()) { EXPECT_EQ(0, rit->getCurrent().compare(**it)); ++it; } rrsets_.clear(); } const Name origin_; const RRClass rrclass_; const RRTTL rrttl_; vector<ConstRRsetPtr> rrsets_; bool throw_from_callback_; RRCollator collator_; AddRRCallback rr_callback_; const RdataPtr a_rdata1_, a_rdata2_, txt_rdata_, sig_rdata1_, sig_rdata2_; vector<ConstRdataPtr> rdatas_; // placeholder for expected data }; TEST_F(RRCollatorTest, basicCases) { // Add two RRs belonging to the same RRset. These will be buffered. rr_callback_(origin_, rrclass_, RRType::A(), rrttl_, a_rdata1_); EXPECT_TRUE(rrsets_.empty()); // not yet given as an RRset rr_callback_(origin_, rrclass_, RRType::A(), rrttl_, a_rdata2_); EXPECT_TRUE(rrsets_.empty()); // still not given // Add another type of RR. This completes the construction of the A RRset, // which will be given via the callback. rr_callback_(origin_, rrclass_, RRType::TXT(), rrttl_, txt_rdata_); rdatas_.push_back(a_rdata1_); rdatas_.push_back(a_rdata2_); checkRRset(origin_, rrclass_, RRType::A(), rrttl_, rdatas_); // Add the same type of RR but of different name. This should make another // callback for the previous TXT RR. rr_callback_(Name("txt.example.com"), rrclass_, RRType::TXT(), rrttl_, txt_rdata_); rdatas_.clear(); rdatas_.push_back(txt_rdata_); checkRRset(origin_, rrclass_, RRType::TXT(), rrttl_, rdatas_); // Add the same type and name of RR but of different class (rare case // in practice) rr_callback_(Name("txt.example.com"), RRClass::CH(), RRType::TXT(), rrttl_, txt_rdata_); rdatas_.clear(); rdatas_.push_back(txt_rdata_); checkRRset(Name("txt.example.com"), rrclass_, RRType::TXT(), rrttl_, rdatas_); // Tell the collator we are done, then we'll see the last RR as an RRset. collator_.flush(); checkRRset(Name("txt.example.com"), RRClass::CH(), RRType::TXT(), rrttl_, rdatas_); // Redundant flush() will be no-op. collator_.flush(); EXPECT_TRUE(rrsets_.empty()); } TEST_F(RRCollatorTest, minTTLFirst) { // RRs of the same RRset but has different TTLs. The first RR has // the smaller TTL, which should be used for the TTL of the RRset. rr_callback_(origin_, rrclass_, RRType::A(), RRTTL(10), a_rdata1_); rr_callback_(origin_, rrclass_, RRType::A(), RRTTL(20), a_rdata2_); rdatas_.push_back(a_rdata1_); rdatas_.push_back(a_rdata2_); collator_.flush(); checkRRset(origin_, rrclass_, RRType::A(), RRTTL(10), rdatas_); } TEST_F(RRCollatorTest, maxTTLFirst) { // RRs of the same RRset but has different TTLs. The second RR has // the smaller TTL, which should be used for the TTL of the RRset. rr_callback_(origin_, rrclass_, RRType::A(), RRTTL(20), a_rdata1_); rr_callback_(origin_, rrclass_, RRType::A(), RRTTL(10), a_rdata2_); rdatas_.push_back(a_rdata1_); rdatas_.push_back(a_rdata2_); collator_.flush(); checkRRset(origin_, rrclass_, RRType::A(), RRTTL(10), rdatas_); } TEST_F(RRCollatorTest, addRRSIGs) { // RRSIG is special; they are also distinguished by their covered types. rr_callback_(origin_, rrclass_, RRType::RRSIG(), rrttl_, sig_rdata1_); rr_callback_(origin_, rrclass_, RRType::RRSIG(), rrttl_, sig_rdata2_); rdatas_.push_back(sig_rdata1_); checkRRset(origin_, rrclass_, RRType::RRSIG(), rrttl_, rdatas_); } TEST_F(RRCollatorTest, emptyFlush) { collator_.flush(); EXPECT_TRUE(rrsets_.empty()); } TEST_F(RRCollatorTest, throwFromCallback) { // Adding an A RR rr_callback_(origin_, rrclass_, RRType::A(), rrttl_, a_rdata1_); // Adding a TXT RR, which would trigger RRset callback, but in this test // it throws. The added TXT RR will be effectively lost. throw_from_callback_ = true; EXPECT_THROW(rr_callback_(origin_, rrclass_, RRType::TXT(), rrttl_, txt_rdata_), isc::Unexpected); // We'll only see the A RR. throw_from_callback_ = false; collator_.flush(); rdatas_.push_back(a_rdata1_); checkRRset(origin_, rrclass_, RRType::A(), rrttl_, rdatas_); } TEST_F(RRCollatorTest, withMasterLoader) { // Test a simple case with MasterLoader. There shouldn't be anything // special, but that's the mainly intended usage of the collator, so we // check it explicitly. std::istringstream ss("example.com. 3600 IN A 192.0.2.1\n"); MasterLoader loader(ss, origin_, rrclass_, MasterLoaderCallbacks::getNullCallbacks(), collator_.getCallback()); loader.load(); collator_.flush(); rdatas_.push_back(a_rdata1_); checkRRset(origin_, rrclass_, RRType::A(), rrttl_, rdatas_); } }
"""Data storage container and related data classes""" import pandas as pd import numpy as np from lib.correlation import is_correlation class Region: """Geographical region""" def __init__(self, region_id: str, name: str): self.region_id = region_id self.name = name class TimeSeries: """Time series with a pandas Series object This is a "realization of a dataset for a given region" The Series should have a name equal to data_source and index named Year """ def __init__(self, data_source, dataset, region: Region, series: pd.Series): self.data_source = data_source self.dataset = dataset self.region = region self.series = series self.differenced: pd.Series = None self.normalized: pd.Series = None self.lag: int = None self.slope: float = None self.intercept: float = None self.r_value: float = None self.p_value: float = None self.std_err: float = None self.correlation: bool = None def set_correlation_regression(self, props: tuple): """Set the correlation and regression results Expects a tuple with the used lag as the first value, followed by the results of scipy.stats.linregress """ self.lag = props[0] self.slope = props[1] self.intercept = props[2] self.r_value = props[3] self.p_value = props[4] self.std_err = props[5] self.correlation = is_correlation(self.p_value) class Dataset: """Dataset with its metadata and time series""" def __init__(self, dataset_id: str, data_source, name: str, description: str, url: str, unit: str): self.dataset_id = dataset_id self.data_source = data_source self.name = name self.description = description self.url = url self.unit = unit self.time_series: dict[Region, TimeSeries] = {} """Time series from this dataset per region""" self.values_per_year: dict[str, pd.Series] = {} """Values from all time series per year with corresponding TFR values""" self.p_values_per_year: pd.Series = None """p-values for inter-region correlation per year""" self.r_values_per_year: pd.Series = None """r-values for inter-region correlation per year""" self.correlation_values_per_year: pd.Series = None """Truth values for inter-region correlation per year""" def add_time_series(self, time_series: TimeSeries): """Add time series to the dataset""" self.time_series[time_series.region] = time_series def all_series(self, regions: list[Region]) -> pd.DataFrame: """Construct a dataframe containing all time series of this dataset""" # Create a list of series ordered by regions all_series_list = [] for region in regions.values(): if region in self.time_series.keys(): all_series_list.append(self.time_series[region].series) else: all_series_list.append(pd.Series(dtype=np.float64)) # Will produce NaNs for this region in the dataframe below all_series = pd.DataFrame(all_series_list) all_series.reset_index(inplace=True) all_series.drop(columns=['index'], inplace=True) return all_series def recompute_values_per_year(self, all_tfr: pd.DataFrame, regions: list[Region], min_values: int): """Refresh values_per_year min_values: minimum number of values from time series available to include a year in values_per_year """ all_series = self.all_series(regions) for year in all_series.columns: if year in all_tfr.columns: # Add explanatory values for each region series = pd.Series(all_series[year]) # Set index to the corresponding TFR values series.index = all_tfr[year] # Remove countries for which the value is missing series.dropna(inplace=True) if series.size >= min_values: self.values_per_year[year] = series def set_inter_region_correlation_p_values(self, p_values: dict[str, float]): """Set the series of inter-region correlation p-values""" self.p_values_per_year = pd.Series(data=p_values.values(), index=p_values.keys()) def set_inter_region_correlation_r_values(self, r_values: dict[str, float]): """Set the series of inter-region correlation r-values""" self.r_values_per_year = pd.Series(data=r_values.values(), index=r_values.keys()) def set_inter_region_correlations(self, correlations: dict[str, bool]): """Set the series of inter-region correlation truth values""" self.correlation_values_per_year = pd.Series(data=correlations.values(), index=correlations.keys()) class DataSource: """Data source with its metadata and datasets""" def __init__(self, data_source_id: str, name: str, description: str, url: str): self.data_source_id = data_source_id self.name = name self.description = description self.url = url self.datasets: dict[str, Dataset] = {} def add_dataset(self, dataset: Dataset): """Add dataset to the data source""" self.datasets[dataset.dataset_id] = dataset class Storage: """Manages gathered data for providing it to the statistics engine and persistence module""" def __init__(self): self.regions: dict[str, Region] = {} self.data_sources: dict[str, DataSource] = {} self.tfr_dataset: Dataset = None def add_data_source(self, data_source: DataSource): """Add a data source""" self.data_sources[data_source.data_source_id] = data_source def add_region(self, region: Region): """Add a region""" self.regions[region.region_id] = region def add_regions(self, regions: list[Region]): """Add multiple regions""" for region in regions: self.add_region(region)
At PACT, we provide valuable assessment information specifically designed to describe how your child uses communication, motor, and sensory abilities for a variety of functional, academic and social purposes. Our therapists have extensive expertise in traditional therapy approaches, as well as how to integrate intervention goals into natural, meaningful experiences. We also encourage feedback from our families in order to help prioritize treatment goals and enhance carryover across into home, school, and community settings and situations. Feel free to ask us for information regarding our most recent trainings and certifications in new and innovative therapeutic approaches and interventions. We are constantly changing to meet the demands and priorities of our clients and their families!
Formal statement is: lemma closure_linear_image_subset: fixes f :: "'m::euclidean_space \<Rightarrow> 'n::real_normed_vector" assumes "linear f" shows "f ` (closure S) \<subseteq> closure (f ` S)" Informal statement is: If $f$ is a linear map, then the image of the closure of a set $S$ is contained in the closure of the image of $S$.
From Test Require Import tactic. Section FOFProblem. Variable Universe : Set. Variable UniverseElement : Universe. Variable wd_ : Universe -> Universe -> Prop. Variable col_ : Universe -> Universe -> Universe -> Prop. Variable col_swap1_1 : (forall A B C : Universe, (col_ A B C -> col_ B A C)). Variable col_swap2_2 : (forall A B C : Universe, (col_ A B C -> col_ B C A)). Variable col_triv_3 : (forall A B : Universe, col_ A B B). Variable wd_swap_4 : (forall A B : Universe, (wd_ A B -> wd_ B A)). Variable col_trans_5 : (forall P Q A B C : Universe, ((wd_ P Q /\ (col_ P Q A /\ (col_ P Q B /\ col_ P Q C))) -> col_ A B C)). Theorem pipo_6 : (forall A B X P Pprime Q Aprime : Universe, ((wd_ A B /\ (wd_ B X /\ (wd_ A X /\ (wd_ P X /\ (wd_ P Pprime /\ (wd_ X Pprime /\ (wd_ A P /\ (wd_ B P /\ (wd_ X Q /\ (wd_ P Q /\ (wd_ A Aprime /\ (wd_ X Aprime /\ (wd_ P Aprime /\ (wd_ Q Aprime /\ (wd_ Q B /\ (wd_ Q A /\ (col_ Aprime B X /\ (col_ A X Aprime /\ col_ P X Pprime)))))))))))))))))) -> col_ A B X)). Proof. time tac. Qed. End FOFProblem.
Railway ticket booking software is a category of software that is designed mainly to help in booking railway tickets. There is a railway ticket booking software is developed in a way such that, clients can make the ticket bookings themselves. Some railway ticket booking software can allow the travelers to book for railway tickets at whichever place they might be while others require you to be helped to make the booking at the railway station. They are developed by some software developers that are experts in coming up with them. There is a railway ticket booking software that is developed and sold while ready to use while others require the owner to specify the qualities that they expect for the software to be developed. The article breaks down the tips to picking the best railway ticket booking software. Consider the ease of use of the railway ticket booking software. Ensure that the railway ticket booking software offers easy features of booking for the tickets. Some clients like to make the booking on their own. Make sure that the railway ticket booking software you wish to buy offers all the functionalities to the user so that they will be able to book the tickets. However, the railway ticket booking software should also be interactive to the employees that work at the railway station to help other clients to book for their tickets. Choose the railway ticket booking software that contains easy navigations for the customer to make their bookings. Make sure that the railway ticket booking software you wish to purchase is easy for the customers to get help from concerning the bookings. Ensure that you choose a railway ticket booking software that all people that have booked for tickets can be able to request for help from concerning the ticket booking. Look for railway ticket booking software that can contact the customers in cases like reminding them about the departure of the train or informing them to make full payment. Choose a railway ticket booking software that can be used to communicate to the customers in different ways including texting them via the email or phone. Ask about how much it will cost for you to get the railway ticket booking software. It is essential that you choose a railway ticket booking software that has prices that are convenient for you. Only purchase the type of railway ticket booking software that will help in meeting the requirements that it has been designed for. You will find out that software developers have different costs for their railway ticket booking software.
# SMC samplers SMC samplers are SMC algorithms that sample from a sequence of target distributions. In this tutorial, these target distributions will be Bayesian posterior distributions of static models. SMC samplers are covered in Chapter 17 of the book. ## Defining a static model A static model is a Python object that represents a Bayesian model with static parameter $\theta$. One may define a static model by subclassing base class `StaticModel`, and defining method `logpyt`, which evaluates the log-likelihood of datapoint $Y_t$ (given $\theta$ and past datapoints $Y_{0:t-1}$). Here is a simple example: ```python %matplotlib inline import warnings; warnings.simplefilter('ignore') # hide warnings from matplotlib import pyplot as plt import seaborn as sb from scipy import stats import particles from particles import smc_samplers as ssp from particles import distributions as dists class ToyModel(ssp.StaticModel): def logpyt(self, theta, t): # density of Y_t given theta and Y_{0:t-1} return stats.norm.logpdf(self.data[t], loc=theta['mu'], scale = theta['sigma']) ``` In words, we are considering a model where the observations are $Y_t\sim N(\mu, \sigma^2)$. The parameter is $\theta=(\mu, \sigma)$. Class `ToyModel` contains information about the likelihood of the considered model, but not about its prior, or the considered data. First, let's define those: ```python T = 1000 my_data = stats.norm.rvs(loc=3.14, size=T) # simulated data my_prior = dists.StructDist({'mu': dists.Normal(scale=10.), 'sigma': dists.Gamma()}) ``` For more details about to define prior distributions, see the documentation of module `distributions`, or the previous [tutorial on Bayesian estimation of state-space models](Bayes_estimation_ssm.ipynb). Now that we have everything, let's specify our static model: ```python my_static_model = ToyModel(data=my_data, prior=my_prior) ``` This time, object `my_static_model` has enough information to define the posterior distribution(s) of the model (given all data, or part of the data). In fact, it inherits from `StaticModel` method `logpost`, which evaluates (for a collection of $\theta$ values) the posterior log-density at any time $t$ (meaning given data $y_{0:t}$). ```python thetas = my_prior.rvs(size=5) my_static_model.logpost(thetas, t=2) # if t is omitted, gives the full posterior ``` array([-1.16002020e+04, -1.76306582e+02, -1.53432234e+02, -5.61957138e+01, -1.09100249e+01]) The input of `logpost` (and output of `myprior.rvs()`) is a [structured array](https://docs.scipy.org/doc/numpy/user/basics.rec.html), with the same keys as the prior distribution: ```python thetas['mu'][0] ``` -2.4661701842790147 Typically, you won't need to call `logpost` yourself, this will be done by the SMC sampler for you. ## IBIS The IBIS (iterated batch importance sampling) algorithm is a SMC sampler that samples iteratively from a sequence of posterior distributions, $p(\theta|y_{0:t})$, for $t=0,1,\ldots$. Module `smc_samplers` defines `IBIS` as a subclass of `FeynmanKac`. ```python my_ibis = ssp.IBIS(my_static_model) my_alg = particles.SMC(fk=my_ibis, N=1000, store_history=True) my_alg.run() ``` Since we set `store_history` to `True`, the particles and their weights have been saved at every time (in attribute `hist`, see previous tutorials on smoothing). Let's plot the posterior distributions of $\mu$ and $\sigma$ at various times. ```python plt.style.use('ggplot') for i, p in enumerate(['mu', 'sigma']): plt.subplot(1, 2, i + 1) for t in [100, 300, 900]: plt.hist(my_alg.hist.X[t].theta[p], weights=my_alg.hist.wgts[t].W, label="t=%i" % t, alpha=0.5, density=True) plt.xlabel(p) plt.legend(); ``` As expected, the posterior distribution concentrates progressively around the true values. As before, once the algorithm is run, `my_smc.X` contains the N final particles. However, object `my_smc.X` is no longer a simple (N,) or (N,d) numpy array. It is a `ThetaParticles` object, with attributes: * theta: a structured array: as mentioned above, this is an array with fields; i.e. `my_smc.X.theta['mu']` is a (N,) array that contains the the $\mu-$component of the $N$ particles; * `lpost`: a (N,) numpy array that contains the target (posterior) log-density of each of the N particles; * `acc_rates`: a list of the acceptance rates of the resample-move steps. ```python print(["%2.2f%%" % (100 * np.mean(r)) for r in my_alg.X.acc_rates]) plt.hist(my_alg.X.lpost, 30); ``` You do not need to know much more about class `ThetaParticles` for most practical purposes (see however the documention of module `smc_samplers` if you do want to know more, e.g. in order to implement other classes of SMC samplers). ## Regarding the Metropolis steps As the text output of `my_alg.run()` suggests, the algorithm "resample-moves" whenever the ESS is below a certain threshold ($N/2$ by default). When this occurs, particles are resampled, and then moved through a certain number of Metropolis-Hastings steps. By default, the proposal is a Gaussian random walk, and both the number of steps and the covariance matrix of the random walk are chosen automatically as follows: * the covariance matrix of the random walk is set to `scale` times the empirical (weighted) covariance matrix of the particles. The default value for `scale` is $2.38 / \sqrt{d}$, where $d$ is the dimension of $\theta$. * the algorithm performs Metropolis steps until the relative increase of the average distance between the starting point and the end point is below a certain threshold $\delta$. Class `IBIS` takes as an optional argument `mh_options`, a dictionary which may contain the following (key, values) pairs: * `'type_prop'`: either `'random walk'` or `'independent`'; in the latter case, an independent Gaussian proposal is used. The mean of the Gaussian is set to the weighted mean of the particles. The variance is set to `scale` times the weighted variance of the particles. * `'scale`': the scale of the proposal (as explained above). * `'nsteps'`: number of steps. If set to `0`, the adaptive strategy described above is used. Let's illustrate all this by calling IBIS again: ```python alt_ibis = ssp.IBIS(my_static_model, mh_options={'type_prop': 'independent', 'nsteps': 10}) alt_alg = particles.SMC(fk=alt_ibis, N=1000, ESSrmin=0.2) alt_alg.run() ``` Well, apparently the algorithm did what we asked. We have also changed the threshold of Let's see how the ESS evolved: ```python plt.plot(alt_alg.summaries.ESSs) plt.xlabel('t') plt.ylabel('ESS') ``` As expected, the algorithm waits until the ESS is below 200 to trigger a resample-move step. ## SMC tempering SMC tempering is a SMC sampler that samples iteratively from the following sequence of distributions: \begin{equation} \pi_t(\theta) \propto \pi(\theta) L(\theta)^\gamma_t \end{equation} with $0=\gamma_0 < \ldots < \gamma_T = 1$. In words, this sequence is a **geometric bridge**, which interpolates between the prior and the posterior. SMC tempering implemented in the same was as IBIS: as a sub-class of `FeynmanKac`, whose `__init__` function takes as argument a `StaticModel` object. ```python fk_tempering = ssp.AdaptiveTempering(my_static_model) my_temp_alg = particles.SMC(fk=fk_tempering, N=1000, ESSrmin=1., verbose=True) my_temp_alg.run() ``` t=0, ESS=500.00, tempering exponent=3.02e-05 t=1, Metropolis acc. rate (over 5 steps): 0.243, ESS=500.00, tempering exponent=0.000328 t=2, Metropolis acc. rate (over 7 steps): 0.245, ESS=500.00, tempering exponent=0.00177 t=3, Metropolis acc. rate (over 7 steps): 0.241, ESS=500.00, tempering exponent=0.00601 t=4, Metropolis acc. rate (over 7 steps): 0.288, ESS=500.00, tempering exponent=0.0193 t=5, Metropolis acc. rate (over 6 steps): 0.333, ESS=500.00, tempering exponent=0.0637 t=6, Metropolis acc. rate (over 5 steps): 0.366, ESS=500.00, tempering exponent=0.231 t=7, Metropolis acc. rate (over 6 steps): 0.357, ESS=500.00, tempering exponent=0.77 t=8, Metropolis acc. rate (over 5 steps): 0.358, ESS=943.23, tempering exponent=1 **Note**: Recall that `SMC` resamples every time the ESS drops below value N times option `ESSrmin`; here we set it to to 1, since we want to resample at every time. This makes sense: Adaptive SMC chooses adaptively the successive values of $\gamma_t$ so that the ESS drops to $N/2$ (by default). **Note**: we use option `verbose=True` in `SMC` in order to print some information on the intermediate distributions. We have not saved the intermediate results this time (option `store_history` was not set) since they are not particularly interesting. Let's look at the final results: ```python for i, p in enumerate(['mu', 'sigma']): plt.subplot(1, 2, i + 1) sb.distplot(my_temp_alg.X.theta[p]) plt.xlabel(p) ``` This looks reasonable! You can see from the output that the algorithm automatically chooses the tempering exponents $\gamma_1, \gamma_2,\ldots$. In fact, at iteration $t$, the next value for $\gamma$ is set that the ESS drops at most to $N/2$. You can change this particular threshold by passing argument ESSrmin to TemperingSMC. (Warning: do not mistake this with the `ESSrmin` argument of class `SMC`): ```python lazy_tempering = ssp.AdaptiveTempering(my_static_model, ESSrmin = 0.1) lazy_alg = particles.SMC(fk=lazy_tempering, N=1000, verbose=True) lazy_alg.run() ``` t=0, ESS=100.00, tempering exponent=0.00104 t=1, Metropolis acc. rate (over 6 steps): 0.247, ESS=100.00, tempering exponent=0.0208 t=2, Metropolis acc. rate (over 6 steps): 0.295, ESS=100.00, tempering exponent=0.514 t=3, Metropolis acc. rate (over 6 steps): 0.370, ESS=760.26, tempering exponent=1 The algorithm progresses faster this time, but the ESS drops more between each step. Another optional argument for Class `TemperingSMC` is `options_mh`, which works exactly as for `IBIS`, see above. That is, by default, the particles are moved according to a certain (adaptative) number of random walk steps, with a variance calibrated to the particle variance.
theory RingBuffer_BD_latest_2 imports Main HOL.List begin (* W_step_side R_step_side LOCAL preserves inv (2) LOCAL preserves inv (1) LOCAL shows preW (done) LOCAL shows preR (done) GLOBAL preserves preR (done) GLOBAL preserves preW (done) *) datatype PCW = A1 | A2 | A3 | A4 | A5 | A6 | A7 | A8 | Enqueue | idleW | OOM | FinishedW | Write | BTS datatype PCR = Release | idleR | Read datatype F = W | R | Q | B | D | None datatype Pointer = Head | Tail consts N :: nat (*size of buffer, input*) consts n :: nat (*number of Arr\<^sub>W entries*) definition "F1_set={W,B,Q,R}" definition "W_pre_acquire_set={A1,A2,A3,A4,A5,A6,A7,A8,idleW,FinishedW,OOM,BTS}" definition "W_post_acquire_set={Write,Enqueue}" definition "R_pre_dequeue_set={idleR}" definition "R_post_dequeue_set={Read, Release}" lemmas sets [simp]= F1_set_def W_pre_acquire_set_def W_post_acquire_set_def R_pre_dequeue_set_def R_post_dequeue_set_def (*Recorded variables*) record rb_state = H :: nat T :: nat hW :: nat (*local copy of W*) tW :: nat (*local copy of W*) offset :: nat q :: "(nat \<times> nat) list" tempR :: "(nat \<times> nat)" (*local copy of word by R*) data_index :: "(nat \<times> nat) \<Rightarrow> nat" (*state of the buffer contents*) pcW :: PCW (*records program counter of W*) pcR :: PCR (*records program counter of W*) Data:: "nat \<Rightarrow> nat" (*returns a word Data_i*) tR :: nat numReads :: nat (* how many words the reader has read *) numWrites :: nat (* how many words the writer has written *) numEnqs :: nat (* how many words from Data the writer has enqueued *) numDeqs :: nat (* how many words from Data the reader has retrieved *) ownT :: F ownD :: "nat \<Rightarrow> F" (* ownership of Data indices *) ownB :: "nat \<Rightarrow> F" (* ownership of bytes in buffer *) definition "con_assms s \<equiv> 0 < N \<and> 0<n \<and> N>n \<and> numEnqs s\<le>n \<and> (numDeqs s\<le>numEnqs s) \<and> (\<forall>i.(i<n)\<longrightarrow>Data s i\<le>N \<and> Data s i>0 )" definition push_H :: "nat \<Rightarrow> rb_state \<Rightarrow> rb_state" ("`H := _" [200]) where "push_H v \<equiv> \<lambda>s. s \<lparr>H := v\<rparr>" definition push_T :: "nat \<Rightarrow> rb_state \<Rightarrow> rb_state" ("`T := _" [200]) where "push_T v \<equiv> \<lambda>s. s \<lparr>T := v\<rparr>" definition write_data_index :: "nat \<times> nat \<Rightarrow> nat \<Rightarrow> rb_state \<Rightarrow> rb_state" ("`B.write _ := _" [200]) where "write_data_index a v \<equiv> \<lambda>s. s \<lparr> data_index := \<lambda> x. if a = x then v else data_index s x \<rparr>" definition change_writes :: "nat \<Rightarrow> rb_state \<Rightarrow> rb_state" ("`numWrites := _" [200]) where "change_writes v \<equiv> \<lambda>s. s \<lparr>numWrites := v\<rparr>" definition change_reads :: "nat \<Rightarrow> rb_state \<Rightarrow> rb_state" ("`numReads := _" [200]) where "change_reads v \<equiv> \<lambda>s. s \<lparr>numReads := v\<rparr>" definition push_offset :: "nat \<Rightarrow> rb_state \<Rightarrow> rb_state" ("`offset := _" [200]) where "push_offset v \<equiv> \<lambda>s. s \<lparr>offset := v\<rparr>" definition trans_ownT :: "F \<Rightarrow> F \<Rightarrow> rb_state \<Rightarrow> rb_state \<Rightarrow> rb_state" ("transownT [_ _ _]" [200]) where "trans_ownT a b s \<equiv> if ownT s = a then (\<lambda>s. s \<lparr> ownT := b \<rparr>) else (\<lambda>s. s \<lparr> ownT := ownT s\<rparr>)" definition transfer_ownB :: "F \<Rightarrow> F \<Rightarrow> rb_state \<Rightarrow> rb_state" ("transownB [_ _]" [200]) where "transfer_ownB a b \<equiv> (\<lambda>s. s \<lparr> ownB := \<lambda> i. if (ownB s i = a)\<and>i\<le>N then b else (ownB s) i\<rparr>)" definition set_ownB :: "nat\<times>nat\<Rightarrow> F \<Rightarrow> rb_state \<Rightarrow> rb_state" ("setownB [_ _]" [200]) where "set_ownB x a \<equiv> (\<lambda>s. s \<lparr> ownB := \<lambda> i. if ((i\<ge>fst(x)) \<and> (i<snd(x))) then a else (ownB s) i\<rparr>)" definition transfer_ownD :: "nat\<Rightarrow> F \<Rightarrow> rb_state \<Rightarrow> rb_state" ("transownD [_ _]" [200]) where "transfer_ownD x a \<equiv> (\<lambda>s. s \<lparr> ownD := \<lambda> i. if i=x then a else (ownD s) i\<rparr>)" (*-----------------------*) definition set_hW :: "nat \<Rightarrow> rb_state \<Rightarrow> rb_state" ("`hW := _" [200]) where "set_hW v \<equiv> \<lambda>s. s \<lparr> hW := v\<rparr>" definition set_tW :: "nat \<Rightarrow> rb_state \<Rightarrow> rb_state" ("`tW := _" [200]) where "set_tW v \<equiv> \<lambda>s. s \<lparr> tW := v\<rparr>" definition set_tR :: "nat \<Rightarrow> rb_state \<Rightarrow> rb_state" ("`tR := _" [200]) where "set_tR v \<equiv> \<lambda>s. s \<lparr> tR := v\<rparr>" definition set_tempR :: "(nat \<times> nat) \<Rightarrow> rb_state \<Rightarrow> rb_state" ("`tempR := _" [200]) where "set_tempR v \<equiv> \<lambda>s. s \<lparr> tempR := v\<rparr>" definition update_numEnqs :: "nat \<Rightarrow> rb_state \<Rightarrow> rb_state" ("`numEnqs := _" [200]) where "update_numEnqs v\<equiv> \<lambda>s. s \<lparr> numEnqs := v\<rparr>" definition update_numDeqs :: "nat \<Rightarrow> rb_state \<Rightarrow> rb_state" ("`numDeqs := _" [200]) where "update_numDeqs v\<equiv> \<lambda>s. s \<lparr> numDeqs := v\<rparr>" definition update_pcW :: "PCW \<Rightarrow> rb_state \<Rightarrow> rb_state" ("`pcW := _" [200]) where "update_pcW v \<equiv> \<lambda>s. s \<lparr> pcW := v\<rparr>" definition update_pcR :: "PCR \<Rightarrow> rb_state \<Rightarrow> rb_state" ("`pcR := _" [200]) where "update_pcR v \<equiv> \<lambda>s. s \<lparr> pcR := v\<rparr>" abbreviation update_b_err :: "rb_state \<Rightarrow> rb_state" ("ERROOM") where "update_b_err \<equiv> \<lambda>s. s \<lparr> pcW := OOM \<rparr>" abbreviation update_bts_err :: "rb_state \<Rightarrow> rb_state" ("ERRBTS") where "update_bts_err \<equiv> \<lambda>s. s \<lparr> pcW := BTS \<rparr>" definition update_q :: "(nat \<times> nat) list \<Rightarrow> rb_state \<Rightarrow> rb_state" ("`q := _" [200]) where "update_q v \<equiv> \<lambda>s. s \<lparr>q := v\<rparr>" lemmas functs [simp] = push_H_def push_T_def set_hW_def set_tW_def update_numEnqs_def update_numDeqs_def set_tempR_def update_pcW_def update_pcR_def transfer_ownB_def transfer_ownD_def trans_ownT_def update_q_def push_offset_def write_data_index_def change_writes_def change_reads_def set_tR_def set_ownB_def (* Define the if statement "guards" *) definition "off bo \<equiv> fst bo" definition "len bo \<equiv> snd bo" definition "grd1 s \<equiv> (tW s = hW s) \<and> (Data s (numEnqs s) \<le> N)" definition "grd2 s \<equiv> (tW s > hW s) \<and> (Data s (numEnqs s) < (tW s - hW s))" definition "grd3 s \<equiv> tW s < hW s" definition "grd4 s \<equiv> Data s (numEnqs s) \<le> N - hW s" definition "grd5 s \<equiv> Data s (numEnqs s) < tW s" definition "no_space_for_word s \<equiv> (grd1 s \<longrightarrow> \<not>(Data s (numEnqs s) \<le> N))\<and> (grd2 s \<longrightarrow> \<not>(Data s (numEnqs s) < (tW s - hW s)))\<and> (grd3 s \<longrightarrow> \<not>(Data s (numEnqs s) \<le> N - hW s \<or> Data s (numEnqs s) < tW s))" lemmas grd_simps [simp] = off_def len_def grd1_def grd2_def grd3_def grd4_def grd5_def no_space_for_word_def (***********************************************************************) (* Initial State *) definition "init s \<equiv> (H s = 0) \<and> (T s = 0) \<and> (offset s = 0) \<and> q s = [] \<and> (hW s = 0) \<and> (tW s = 0) \<and> (tR s = 0) \<and> numReads s = 0 \<and> numWrites s = 0 \<and> (numEnqs s = 0) \<and> (numDeqs s = 0) \<and> ( pcW s = idleW) \<and> ( pcR s = idleR) \<and> (\<forall>l. (l<n) \<longrightarrow> ((Data s l > 0)\<and>(Data s l \<le> N))) \<and> (\<forall>i. (i<n) \<longrightarrow> ownD s i = W) \<and> (\<forall>i. (i<N) \<longrightarrow> ownB s i = B) \<and> (ownB s N = None) \<and> (ownT s = Q) \<and> (tempR s = (0,0)) \<and> (\<forall>i. (i\<le>N)\<longrightarrow>(\<forall>j.(j\<le>N)\<longrightarrow>data_index s (i,j) <n))" (***********************************************************************) definition "case_1 s \<equiv> \<exists>a b c d. (0\<le>a \<and> a\<le>b \<and> b\<le>c \<and> c\<le>d \<and> d\<le>N \<and>(\<forall>i.(0\<le>i \<and> i<a)\<longrightarrow>ownB s i = B) \<and>(\<forall>i.(a\<le>i \<and> i<b)\<longrightarrow>ownB s i = R) \<and>(\<forall>i.(b\<le>i \<and> i<c)\<longrightarrow>ownB s i = Q) \<and>(\<forall>i.(c\<le>i \<and> i<d)\<longrightarrow>ownB s i = W) \<and>(\<forall>i.(d\<le>i \<and> i<N)\<longrightarrow>ownB s i = B) \<and>(ownB s N = None) \<comment>\<open>general case rules\<close> \<comment>\<open>rules are simple\<close> \<comment>\<open>describe T using ownB\<close> \<and>(T s = a) \<comment>\<open>describe H using ownB\<close> \<and>(H s = d) \<comment>\<open>describe W view (tempW) using ownB\<close> \<and>(d>c\<longrightarrow>offset s=c) \<and>(d>c\<longrightarrow>Data s (numEnqs s)=d-c) \<comment>\<open>describe R view (tempR) using ownB\<close> \<and>(b>a\<longrightarrow>fst(tempR s)=a) \<and>(b>a\<longrightarrow>snd(tempR s)=b-a) \<comment>\<open>describe Q view (hd(Q), last(Q)) using ownB\<close> \<and>(length(q s)\<le>c-b) \<and>(c>b\<longrightarrow>length(q s)>0) \<and>(c>b\<longrightarrow>fst(hd(q s)) =b) \<and>(c>b\<longrightarrow>fst(last(q s))+snd(last(q s)) =c) \<comment>\<open>describe ownT using ownB\<close> \<and>(ownT s = R\<longrightarrow>b>a) \<and>((b=a\<and>c>b)\<longrightarrow>ownT s = Q) \<and>((b=a\<and>c=b)\<longrightarrow>ownT s \<in> {Q,W}) \<and> (ownT s=W\<longrightarrow>((c=0\<and>d>0)\<or>(H s=T s))) )" lemma can_a_equal_d: assumes "\<forall>i.(i<N)\<longrightarrow>ownB s i=B" and "ownT s=Q" and "H s=k" and "T s=k" and "k<N" (*this allows H=T\<noteq>N*) and "q s=[]" and "ownB s N=None" shows "case_1 s" using assms apply (simp add:case_1_def) apply (rule_tac exI [where x ="k"]) apply (rule_tac exI [where x ="k"]) apply simp apply (rule_tac exI [where x ="k"]) by simp definition "case_2 s \<equiv> \<exists>a b c d e f. (0\<le>a \<and> a\<le>b \<and> b\<le>c \<and> c<d \<and> d\<le>e \<and> e\<le>f \<and> f\<le>N \<and>(\<forall>i.(0\<le>i \<and> i<a)\<longrightarrow>ownB s i = R) \<and>(\<forall>i.(a\<le>i \<and> i<b)\<longrightarrow>ownB s i = Q) \<and>(\<forall>i.(b\<le>i \<and> i<c)\<longrightarrow>ownB s i = W) \<and>(\<forall>i.(c\<le>i \<and> i<d)\<longrightarrow>ownB s i = B) \<and>(\<forall>i.(d\<le>i \<and> i<e)\<longrightarrow>ownB s i = R) \<and>(\<forall>i.(e\<le>i \<and> i<f)\<longrightarrow>ownB s i = Q) \<and>(\<forall>i.(f\<le>i \<and> i<N)\<longrightarrow>ownB s i = D) \<and>(ownB s N = None) \<comment>\<open>general case rules\<close> \<and>(a>0\<longrightarrow>e=d) \<comment>\<open>only 1 continuous read\<close> \<and>(e>d\<longrightarrow>a=0) \<comment>\<open>only 1 continuous read\<close> \<and>(f>e\<longrightarrow>a=0) \<comment>\<open>only 1 continuous queue\<close> \<and>(c>0) \<comment>\<open>create the overlap, any way possible\<close> \<comment>\<open>describe T using ownB\<close> \<and>(T s = d) \<comment>\<open>describe H using ownB\<close> \<and>(H s = c) \<comment>\<open>describe W view (tempW) using ownB\<close> \<and>(c>b\<longrightarrow>offset s = b) \<and>(c>b\<longrightarrow>Data s (numEnqs s) = c-b) \<comment>\<open>describe R view (tempR) using ownB\<close> \<and>(a>0\<longrightarrow>fst(tempR s)=0) \<and>(a>0\<longrightarrow>snd(tempR s)=a) \<and>(e>d\<longrightarrow>fst(tempR s)=d) \<and>(e>d\<longrightarrow>snd(tempR s)=e-d) \<comment>\<open>describe Q view (hd(Q), last(Q)) using ownB\<close> \<and>(length(q s)\<le>(f-e+b-a)) \<and>((f>e\<or>b>a)\<longrightarrow>length(q s)>0) \<and>(f>e\<longrightarrow>fst(hd(q s)) =e) \<and>((f=e\<and>b>a)\<longrightarrow>fst(hd(q s)) =a) \<and>(b>a\<longrightarrow>fst(last(q s))+snd(last(q s)) =b) \<and>((b=a\<and>f>e)\<longrightarrow>fst(last(q s))+snd(last(q s)) =f) \<comment>\<open>describe ownT using ownB\<close> \<and>(ownT s = R\<longrightarrow>(a>0\<or>e>d)) \<and>((a=0\<and>e=d)\<longrightarrow>ownT s = Q) \<and>(ownT s\<noteq>W) )" lemma natural: assumes "a\<in>{0,3,4}" shows "a\<in>\<nat>" using assms apply simp by auto lemma case_split: shows "H s\<ge>T s\<Longrightarrow> (case_1 s \<or> case_2 s) \<Longrightarrow> case_1 s" apply (simp add:case_1_def case_2_def) apply clarify by linarith lemma case_split_2: shows "H s\<ge>T s\<Longrightarrow> (case_1 s \<or> case_2 s) \<Longrightarrow>\<not> case_2 s" by (simp add:case_1_def case_2_def) lemma case_split_3: shows "H s<T s\<Longrightarrow> (case_1 s \<or> case_2 s) \<Longrightarrow> case_2 s" apply (simp add:case_1_def case_2_def) apply clarify by linarith lemma case_split_4: shows "H s<T s\<Longrightarrow> (case_1 s \<or> case_2 s) \<Longrightarrow>\<not> case_1 s" by (simp add:case_1_def case_2_def) lemma case_split_5: shows "(case_1 s \<and> case_2 s) \<Longrightarrow>False" apply (simp add:case_1_def case_2_def) apply clarify apply (case_tac "H s\<ge>T s") apply(subgoal_tac "case_1 s") prefer 2 apply (metis leD) apply (metis case_split_4) apply(subgoal_tac "T s>H s") prefer 2 apply blast apply(subgoal_tac "case_2 s") prefer 2 apply (metis le_trans) using case_split_2 [where s=s] by (metis le_trans) (* declare [[show_types]] *) (* State of the queue *) (* What Q should look like *) definition "end x \<equiv> fst x + snd x" lemmas end_simp [simp] = end_def definition "Q_boundness s \<equiv> (\<forall>x. (x \<in> set (q s)) \<longrightarrow> end x \<le> N)" definition "Q_offsets_differ s \<equiv> (\<forall>i j.(i<length(q s)\<and> j<length(q s)\<and> i\<noteq>j)\<longrightarrow>(fst(q s!i)\<noteq>fst(q s!j)))" definition "Q_gap_structure s \<equiv> (\<forall>i. (i < length(q s) \<and> i > 0) \<longrightarrow>((end(q s!(i-1)) = fst(q s!i))\<or> (fst(q s!i) =0)))" definition "Q_has_no_uroboros s \<equiv> (\<forall>x. x \<in> set (q s)\<longrightarrow> fst x \<noteq> end (last (q s)))" definition "Q_has_no_overlaps s \<equiv> (\<forall> x y. (x \<in> set (q s) \<and> y \<in> set (q s)) \<longrightarrow> (fst(x) < fst(y) \<longrightarrow> end x \<le> fst y))" definition "Q_elem_size s \<equiv> \<forall>x.(x\<in>set(q s))\<longrightarrow>snd(x)>0" definition "Q_basic_struct s \<equiv> Q_boundness s \<and> Q_gap_structure s \<and> Q_offsets_differ s \<and> Q_has_no_overlaps s \<and> Q_has_no_uroboros s \<and> Q_elem_size s" lemmas Q_basic_lemmas = Q_basic_struct_def Q_has_no_overlaps_def Q_gap_structure_def Q_has_no_uroboros_def Q_boundness_def Q_offsets_differ_def Q_elem_size_def lemma proof_no_overlaps: assumes "Q_gap_structure s" and "Q_offsets_differ s" and "\<forall>i.(i<length(q s))\<longrightarrow> snd(q s!i)>0" and "length(q s)>1" and "Q_has_no_overlaps s" shows "\<forall>x y.(x\<in>set(q s)\<and>y\<in>set(q s)\<and>length(q s)>1\<and>fst(x)\<noteq>fst(y))\<longrightarrow> (\<forall>j.(fst(x)\<le>j \<and> j<end(x))\<longrightarrow>(j<fst(y)\<or>j\<ge>end(y)))" using assms apply (simp add:Q_basic_lemmas) apply safe by (smt (verit, best) bot_nat_0.not_eq_extremum diff_is_0_eq le_trans linorder_neqE_nat zero_less_diff) lemma tail_preserves_Q_boundness: assumes "Q_boundness s" and "tl(q s)\<noteq>[]" shows "(\<forall>x. (x \<in> set (tl(q s))) \<longrightarrow> end x \<le> N)" using assms apply (simp add:Q_boundness_def) by (simp add: list.set_sel(2) tl_Nil) lemma tail_preserves_Q_offsets_differ: assumes "Q_offsets_differ s" and "tl(q s)\<noteq>[]" shows "(\<forall>i j.(i<length(tl(q s))\<and> j<length(tl(q s))\<and> i\<noteq>j)\<longrightarrow>(fst((tl(q s))!i)\<noteq>fst((tl(q s))!j)))" using assms apply (simp add:Q_offsets_differ_def) by (simp add: Nitpick.size_list_simp(2) nth_tl tl_Nil) lemma tail_preserves_Q_gap_structure: assumes "Q_gap_structure s" and "tl(q s)\<noteq>[]" shows "(\<forall>i. (i < length(tl(q s)) \<and> i > 0) \<longrightarrow>((end((tl(q s))!(i-1)) = fst((tl(q s))!i))\<or> (fst((tl(q s))!i) =0)))" using assms apply (simp add:Q_gap_structure_def) by (smt (verit) One_nat_def Suc_pred add_diff_cancel_left' length_tl less_Suc_eq less_diff_conv not_less_eq nth_tl plus_1_eq_Suc) lemma tail_preserves_Q_has_no_uroboros: assumes "Q_has_no_uroboros s" and "tl(q s)\<noteq>[]" shows "(\<forall>x. x \<in> set (tl(q s)) \<longrightarrow> fst x \<noteq> end (last (tl(q s))))" using assms apply (simp add:Q_has_no_uroboros_def) by (metis last_tl list.sel(2) list.set_sel(2)) lemma tail_preserves_Q_has_no_overlaps: assumes "Q_has_no_overlaps s" and "tl(q s)\<noteq>[]" shows "(\<forall> x y. (fst(x) < fst(y) \<and> x \<in> set (tl(q s)) \<and> y \<in> set (tl(q s))) \<longrightarrow> (end x \<le> fst y))" using assms apply (simp add:Q_has_no_overlaps_def) by (metis list.sel(2) list.set_sel(2)) lemma tail_preserves_Q_basic_struct: assumes "Q_basic_struct s" and "tl(q s)\<noteq>[]" shows "(\<forall>x. (x \<in> set (tl(q s))) \<longrightarrow> end x \<le> N) \<and> (\<forall>i j.(i<length(tl(q s))\<and> j<length(tl(q s))\<and> i\<noteq>j)\<longrightarrow>(fst((tl(q s))!i)\<noteq>fst((tl(q s))!j))) \<and> (\<forall>i. (i < length(tl(q s)) \<and> i > 0) \<longrightarrow>((end((tl(q s))!(i-1)) = fst((tl(q s))!i))\<or> (fst((tl(q s))!i) =0)))\<and> (\<forall>x. x \<in> set (tl(q s)) \<longrightarrow> fst x \<noteq> end (last (tl(q s)))) \<and> (\<forall> x y. (fst(x) < fst(y) \<and> x \<in> set (tl(q s)) \<and> y \<in> set (tl(q s))) \<longrightarrow> (end x \<le> fst y))" using assms apply (simp add:Q_basic_lemmas) apply(intro conjI impI) apply (metis list.sel(2) list.set_sel(2)) using tail_preserves_Q_offsets_differ apply (metis One_nat_def Q_basic_struct_def assms(1) length_tl) using tail_preserves_Q_gap_structure apply (metis One_nat_def Q_basic_struct_def assms(1) end_simp length_tl) using tail_preserves_Q_has_no_uroboros apply (metis Q_basic_struct_def assms(1) end_simp old.prod.inject prod.collapse) by (metis list.sel(2) list.set_sel(2)) (* (*have the idea of "can fit between T-N or not"*) definition "T_is_outside_Q s \<equiv> (\<forall>i.(i<length(q s) \<and> q s\<noteq>[])\<longrightarrow>(end(q s!i)<T s))" definition "tempR_describes_T s \<equiv> ((fst(tempR s) =0) \<longrightarrow> (T s=0 \<or> T_is_outside_Q s)) \<and>((fst(tempR s) >0) \<longrightarrow> (T s=fst(tempR s)))" definition "Q_describes_T s \<equiv> ((fst(hd(q s)) =0) \<longrightarrow> (T s=0 \<or> T_is_outside_Q s)) \<and>((fst(hd(q s)) >0) \<longrightarrow> (T s=fst(hd(q s))))" *) (*have the idea of "can we describe ownB s i=R"*) (* definition "R_owns_no_bytes s \<equiv> (\<forall>i.(i\<ge>0)\<longrightarrow>ownB s i\<noteq>R)" definition "tempR_describes_ownB s \<equiv> (\<forall>i.(i<fst(tempR s))\<longrightarrow>ownB s i\<noteq>R) \<and>(\<forall>i.(i\<ge>end(tempR s))\<longrightarrow>ownB s i\<noteq>R) \<and>(\<forall>i.(fst(tempR s)\<le>i \<and> i<end(tempR s))\<longrightarrow>ownB s i=R)" *) definition "tempR_bounded s \<equiv> end(tempR s)\<le>N" definition "Q_no_overlap_tempR s\<equiv> (\<forall>x. (x \<in> set (q s))\<longrightarrow> ((fst(tempR s)<fst(x)\<and>end(tempR s)\<le> fst(x)) \<or>(fst(x)<fst(tempR s)\<and>end(x)<fst(tempR s))))" definition "Q_relates_tempR s \<equiv> (end(tempR s) = fst(hd (q s))) \<or> (fst(hd(q s)) = 0)" lemmas tmepR_extra_lemmas [simp] = tempR_bounded_def Q_no_overlap_tempR_def Q_relates_tempR_def (* Relating Q to other variables *) (* definition "Q_bytes s \<equiv> {i . \<exists> k l. (k, l) \<in> set(q s) \<and> k \<le> i \<and> i < k+l}" definition "Q_bytes_inv s \<equiv> \<forall> i. i \<in> Q_bytes s \<longleftrightarrow> ownB s i = Q" *) definition "Q_holds_bytes s \<equiv> q s\<noteq>[]\<longrightarrow>(\<forall>i.(i\<in>set(q s))\<longrightarrow>(\<forall>j.(fst(i)\<le>j \<and> j<end(i))\<longrightarrow>ownB s j=Q))" definition "Q_reflects_writes s \<equiv> (\<forall>i.(i<length(q s))\<longrightarrow>data_index s (q s!i) = ((numDeqs s) +i))" definition "Q_elem_rel s \<equiv> (\<forall>i.(i<length(q s))\<longrightarrow>snd(q s!i) =Data s ((numDeqs s) +i))" definition "Q_reflects_ownD s \<equiv> (\<forall>i.(i<length(q s))\<longrightarrow>ownD s (i+(numDeqs s)) =B)" lemma tail_preserves_Q_holds_bytes: assumes "Q_holds_bytes s" and "(tl(q s))\<noteq>[]" shows "(tl(q s))\<noteq>[]\<longrightarrow>(\<forall>i.(i\<in>set(tl(q s)))\<longrightarrow>(\<forall>j.(fst(i)\<le>j \<and> j<end(i))\<longrightarrow>ownB s j=Q))" using assms apply (simp add:Q_holds_bytes_def) by (metis list.sel(2) list.set_sel(2)) lemma tail_preserves_Q_reflects_writes: assumes "Q_reflects_writes s" and "(tl(q s))\<noteq>[]" shows "(\<forall>i.(i<length(tl(q s)))\<longrightarrow>data_index s ((tl(q s))!i) = ((numDeqs s) +i +1))" using assms apply (simp add:Q_reflects_writes_def) by (simp add: nth_tl) lemma tail_preserves_Q_elem_size: assumes "Q_elem_rel s" and "(tl(q s))\<noteq>[]" shows "(\<forall>i.(i<length(tl(q s)))\<longrightarrow>snd((tl(q s))!i) =Data s ((numDeqs s) +i +1))" using assms apply (simp add:Q_elem_size_def) by (simp add: Q_elem_rel_def nth_tl) lemma tail_preserves_Q_reflects_ownD: assumes "Q_reflects_ownD s" and "(tl(q s))\<noteq>[]" shows "(\<forall>i.(i<length(tl(q s)))\<longrightarrow>ownD s (i+(numDeqs s) +1) =B)" using assms apply (simp add:Q_reflects_ownD_def) by (metis One_nat_def Suc_eq_plus1 add.assoc less_diff_conv plus_1_eq_Suc) lemma Q_offsets_imply_tail_offsets: assumes "Q_offsets_differ s" shows "(\<forall>i j.(i<length(tl(q s))\<and> j<length(tl(q s))\<and> i\<noteq>j)\<longrightarrow>(fst(tl(q s)!i)\<noteq>fst(tl(q s)!j)))" using assms apply (simp add:Q_offsets_differ_def) by (metis (no_types, lifting) Nat.lessE One_nat_def Suc_pred length_tl less_Suc_eq_0_disj nth_tl old.nat.inject zero_less_diff) lemma Q_head_relates_tail: assumes "Q_offsets_differ s" shows "\<forall>i.(i<length(tl(q s)))\<longrightarrow>fst(q s!0)\<noteq> fst(tl(q s)!i)" using assms apply (simp add:Q_offsets_differ_def) by (metis One_nat_def Suc_pred length_tl less_Suc_eq_0_disj not_less_eq nth_tl zero_less_diff) lemma Exists_one_implies_exist_no_more: assumes "Q_offsets_differ s" and "Q_gap_structure s" shows "if \<exists>j.(fst(q s!j) =0 \<and> j<length(q s)) then (\<exists>j.(\<forall>i.(i<length(q s) \<and> i\<noteq>j \<and> i>0)\<longrightarrow>(end(q s!(i-1)) =fst(q s!i)))) else (\<forall>i.(i>0 \<and> i<length(q s))\<longrightarrow>end(q s!(i-1)) = fst(q s!i))" using assms apply (simp add:Q_basic_lemmas) apply (case_tac "\<exists>j.(fst(q s!j) =0 \<and> j<length(q s))", simp_all) apply (metis gr_implies_not0) by (metis less_nat_zero_code) lemma Q_hd_zero_implies_structure: assumes "Q_offsets_differ s" and "Q_gap_structure s" and "fst(hd(q s)) =0" shows "\<forall>i.(i>0 \<and> i<length(q s))\<longrightarrow>end(q s!(i-1)) =fst(q s!i)" using assms apply(simp add:Q_basic_lemmas) by (metis drop0 hd_drop_conv_nth less_Suc_eq_0_disj less_imp_Suc_add not_gr_zero) lemma data_index_preserved_lemma: assumes "Q_reflects_writes s" and "length(q s)>0" shows "data_index s(q s!0) = numDeqs s" using assms by (simp add:Q_reflects_writes_def) definition "Q_structure s \<equiv>q s\<noteq>[]\<longrightarrow>(Q_basic_struct s \<and> \<comment> \<open>Q_holds_bytes s \<and>\<close> Q_reflects_writes s \<and> Q_elem_rel s \<and> Q_reflects_ownD s)" lemmas Q_lemmas = Q_holds_bytes_def Q_reflects_writes_def Q_reflects_ownD_def Q_structure_def Q_relates_tempR_def Q_elem_rel_def Q_elem_size_def Q_no_overlap_tempR_def lemma head_q0: assumes "length(q s)>0" shows "hd(q s) = (q s!0)" using assms apply (simp add:Q_reflects_writes_def) by (simp add: hd_conv_nth) lemma overlap: assumes "Q_structure s \<and> length(q s)>1" shows "\<nexists>k.(\<forall>i j.(i<length(q s)\<and> j<length(q s)\<and> i\<noteq>j)\<longrightarrow>(k\<ge>fst(q s!i)\<and> k<end(q s!i)\<and>k\<ge>fst(q s!j)\<and>k<end(q s!j)))" using assms apply simp apply(simp add:Q_lemmas Q_basic_lemmas) apply(elim conjE impE) apply clarify apply simp by (smt One_nat_def Suc_lessD add_diff_cancel_left' le_0_eq le_less_trans less_numeral_extra(1) not_less nth_mem plus_1_eq_Suc prod.collapse) lemma Q_has_0_elem: assumes "Q_gap_structure s" and "Q_offsets_differ s" and "hd(q s) =(0,a)" shows "fst(hd(q s)) =0\<longrightarrow>(\<forall>i.(i<length(q s)\<and> i>0)\<longrightarrow>end(q s!(i-1)) =fst(q s!i))" using assms apply auto apply (simp add:Q_gap_structure_def Q_offsets_differ_def) by (metis gr_implies_not_zero head_q0 not_gr_zero old.prod.inject prod.collapse) lemma Q_gap_lemmas_1: assumes "Q_structure s" and "length(q s) >0" shows "last(q s)\<in>set(q s)" using assms by (simp add:con_assms_def) lemma Q_gap_lemmas_2: assumes "Q_structure s" and "length(q s) >0" shows "\<forall>i.(i<length(q s))\<longrightarrow>(q s!i)\<in>set(q s)" using assms by (simp add:con_assms_def) lemma Q_gap_lemmas_3: assumes "Q_structure s" and "length(q s) >0" shows "\<forall>x y.(x\<in>set(q s) \<and> y\<in>set(q s) \<and> fst(y)\<noteq>fst(x))\<longrightarrow>(fst(x)>fst(y)\<or>fst(y)>fst(x))" using assms apply (simp add:con_assms_def Q_lemmas Q_basic_lemmas) by linarith lemma Q_gap_lemmas_4: assumes "Q_structure s" and "length(q s) >0" shows "\<forall>x y.(x\<in>set(q s) \<and> y\<in>set(q s) \<and> fst(y)>fst(x))\<longrightarrow>end(y)>fst(x)" using assms by (simp add:con_assms_def Q_lemmas Q_basic_lemmas) lemma Q_gap_lemmas_5: assumes "Q_structure s" and "length(q s) >0" shows "\<forall>x y.(x\<in>set(q s) \<and> y\<in>set(q s) \<and> fst(y)>fst(x))\<longrightarrow>(fst(y)\<ge>end(x))" using assms by (simp add:con_assms_def Q_lemmas Q_basic_lemmas) lemma Q_gap_lemmas_6: assumes "Q_structure s" and "length(q s) >0" shows "\<forall>x y.(x\<in>set(q s) \<and> y\<in>set(q s) \<and> fst(y)>fst(x))\<longrightarrow>(end(y)>end(x))" using assms apply (simp add:con_assms_def Q_lemmas Q_basic_lemmas) by (smt (verit, best) diff_add_inverse diff_is_0_eq le_add1 le_neq_implies_less le_trans length_greater_0_conv list.size(3)) lemma Q_gap_lemmas_7: assumes "Q_structure s" and "length(q s) >0" shows "\<forall>x y.(x\<in>set(q s) \<and> y\<in>set(q s) \<and> fst(y)\<ge>end(x))\<longrightarrow>(end(y)>fst(x))" using assms apply (simp add:con_assms_def Q_lemmas Q_basic_lemmas) by (metis add_leD1 le_neq_implies_less less_add_same_cancel1 trans_less_add1) lemma Q_gap_lemmas_8: assumes "Q_structure s" and "length(q s) >0" shows "\<forall>x y.(x\<in>set(q s) \<and> y\<in>set(q s) \<and> fst(y)\<ge>end(x))\<longrightarrow>(fst(y)>fst(x))" using assms apply (simp add:con_assms_def Q_lemmas Q_basic_lemmas) by (metis add_leD1 diff_add_0 diff_add_inverse diff_diff_cancel minus_nat.diff_0 nat_less_le) lemma Q_gap_lemmas_9: assumes "Q_structure s" and "length(q s) >0" shows "\<forall>x y.(x\<in>set(q s) \<and> y\<in>set(q s) \<and> fst(y)\<ge>end(x))\<longrightarrow>(end(y)>end(x))" using assms apply (simp add:con_assms_def Q_lemmas Q_basic_lemmas) by (metis le_eq_less_or_eq less_add_same_cancel1 trans_less_add1) lemma Q_gap_lemmas_10: assumes "Q_structure s" and "length(q s) >0" shows "\<forall>x y.(x\<in>set(q s) \<and> y\<in>set(q s) \<and> end(y)>fst(x) \<and> fst(y)\<noteq>fst(x))\<longrightarrow>(fst(y)>fst(x))" using assms apply (simp add:con_assms_def Q_lemmas Q_basic_lemmas) by (metis le_antisym less_or_eq_imp_le nat_neq_iff) lemma Q_gap_lemmas_11: assumes "Q_structure s" and "length(q s) >0" shows "\<forall>x y.(x\<in>set(q s) \<and> y\<in>set(q s) \<and> end(y)>fst(x) \<and> fst(y)\<noteq>fst(x))\<longrightarrow>(end(y)>end(x))" using assms apply (simp add:con_assms_def Q_lemmas Q_basic_lemmas) by (smt (verit, ccfv_SIG) diff_add_inverse diff_is_0_eq le_antisym le_trans less_or_eq_imp_le nat_neq_iff) lemma Q_gap_lemmas_12: assumes "Q_structure s" and "length(q s) >0" shows "\<forall>x y.(x\<in>set(q s) \<and> y\<in>set(q s) \<and> end(y)>fst(x) \<and> fst(y)\<noteq>fst(x))\<longrightarrow>(fst(y)\<ge>end(x))" using assms apply (simp add:con_assms_def Q_lemmas Q_basic_lemmas) by (metis le_antisym less_or_eq_imp_le nat_neq_iff) lemma Q_gap_lemmas_13: assumes "Q_structure s" and "length(q s) >0" shows "\<forall>x y.(x\<in>set(q s) \<and> y\<in>set(q s) \<and> end(y)>end(x))\<longrightarrow>(end(y)>fst(x))" using assms by (simp add:con_assms_def Q_lemmas Q_basic_lemmas) lemma Q_gap_lemmas_14: assumes "Q_structure s" and "length(q s) >0" shows "\<forall>x y.(x\<in>set(q s) \<and> y\<in>set(q s) \<and> end(y)>end(x) \<and> fst(y)\<noteq>fst(x))\<longrightarrow>(fst(y)\<ge>end(x))" using assms apply (simp add:con_assms_def Q_lemmas Q_basic_lemmas) by (metis diff_diff_left diff_is_0_eq less_nat_zero_code linorder_neqE_nat zero_less_diff) lemma Q_gap_lemmas_15: assumes "Q_structure s" and "length(q s) >0" shows "\<forall>x y.(x\<in>set(q s) \<and> y\<in>set(q s) \<and> end(y)>end(x))\<longrightarrow>(fst(y)\<noteq>fst(x))" using assms apply (simp add:con_assms_def Q_lemmas Q_basic_lemmas) by (metis fst_conv in_set_conv_nth nat_neq_iff old.prod.inject) lemma Q_gap_lemmas_16_B: assumes "Q_structure s" and "length(q s) >0" and "x\<in>set(q s)" and "y\<in>set(q s)" and "end(y)>end(x)" shows "fst(y)\<ge>end(x)" using assms apply (simp add:con_assms_def Q_lemmas Q_basic_lemmas) using Q_gap_lemmas_14 Q_gap_lemmas_15 by (metis assms(1) assms(2) end_simp fst_conv snd_conv) lemma Q_gap_lemmas_16: assumes "Q_structure s" and "length(q s) >0" shows "\<forall>x y.(x\<in>set(q s) \<and> y\<in>set(q s) \<and> end(y)>end(x))\<longrightarrow>(fst(y)\<ge>end(x))" using Q_gap_lemmas_16_B assms by blast lemma Q_gap_lemmas_17: assumes "Q_structure s" and "length(q s) >0" shows "\<forall>x y.(x\<in>set(q s) \<and> y\<in>set(q s) \<and> end(y)>end(x))\<longrightarrow>(fst(y)>fst(x))" using assms apply (simp add:con_assms_def Q_lemmas Q_basic_lemmas) by (metis Q_gap_lemmas_15 Q_gap_lemmas_10 add_lessD1 assms(1) assms(2) end_simp fst_conv snd_conv) lemma Q_gap_lemmas_1_list: assumes "Q_structure s" and "length(q s) >0" shows "\<forall>i j.(i<length(q s) \<and> j<length(q s) \<and> i\<noteq>j)\<longrightarrow>(fst(q s!i)>fst(q s!j) \<or> fst(q s!i)<fst(q s!j))" using assms apply (simp add:con_assms_def Q_lemmas Q_basic_lemmas) by (meson nat_neq_iff) lemma Q_gap_lemmas_2_list: assumes "Q_structure s" and "length(q s) >0" shows "\<forall>i j.(i<length(q s) \<and> j<length(q s) \<and> fst(q s!i)>fst(q s!j))\<longrightarrow> (end(q s!i)>fst(q s!j))" using assms by (simp add:con_assms_def Q_lemmas Q_basic_lemmas) lemma Q_gap_lemmas_3_list: assumes "Q_structure s" and "length(q s) >0" shows "\<forall>i j.(i<length(q s) \<and> j<length(q s) \<and> fst(q s!i)>fst(q s!j))\<longrightarrow> (end(q s!i)>end(q s!j))" using assms apply (simp add:con_assms_def Q_lemmas Q_basic_lemmas) by (metis Q_gap_lemmas_6 assms(1) end_simp length_pos_if_in_set nth_mem) lemma Q_gap_lemmas_4_list: assumes "Q_structure s" and "length(q s) >0" shows "\<forall>i j.(i<length(q s) \<and> j<length(q s) \<and> fst(q s!i)>fst(q s!j))\<longrightarrow> (fst(q s!i)\<ge>end(q s!j))" using assms apply (simp add:con_assms_def Q_lemmas Q_basic_lemmas) by (metis Q_gap_lemmas_2 assms(1) assms(2) prod.collapse) lemma Q_gap_lemmas_5_list: assumes "Q_structure s" and "length(q s) >0" shows "\<forall>i j.(i<length(q s) \<and> j<length(q s) \<and> fst(q s!i)\<ge>end(q s!j))\<longrightarrow> (fst(q s!i)>fst(q s!j))" using assms apply (simp add:con_assms_def Q_lemmas Q_basic_lemmas) by (metis Q_gap_lemmas_8 assms(1) end_simp length_pos_if_in_set nth_mem) lemma Q_gap_lemmas_6_list: assumes "Q_structure s" and "length(q s) >0" shows "\<forall>i j.(i<length(q s) \<and> j<length(q s) \<and> fst(q s!i)\<ge>end(q s!j))\<longrightarrow> (end(q s!i)>fst(q s!j))" using assms apply (simp add:con_assms_def Q_lemmas Q_basic_lemmas) by (metis Q_gap_lemmas_7 assms(1) end_simp length_pos_if_in_set nth_mem) lemma Q_gap_lemmas_7_list: assumes "Q_structure s" and "length(q s) >0" shows "\<forall>i j.(i<length(q s) \<and> j<length(q s) \<and> fst(q s!i)\<ge>end(q s!j))\<longrightarrow> (end(q s!i)>end(q s!j))" using assms apply (simp add:con_assms_def Q_lemmas Q_basic_lemmas) by (metis le_eq_less_or_eq less_add_same_cancel1 nth_mem surjective_pairing trans_less_add1) lemma Q_gap_lemmas_8_list: assumes "Q_structure s" and "length(q s) >0" shows "\<forall>i j.(i<length(q s) \<and> j<length(q s) \<and> end(q s!i)>fst(q s!j) \<and> i\<noteq>j)\<longrightarrow> (fst(q s!i)>fst(q s!j))" using assms apply (simp add:con_assms_def Q_lemmas Q_basic_lemmas) using Q_gap_lemmas_10 by (metis assms(1) end_simp length_pos_if_in_set nth_mem) lemma Q_gap_lemmas_9_list_B: assumes "Q_structure s" and "length(q s) >0" and "i<length(q s)" and "j<length(q s)" and "end(q s!i)>fst(q s!j)" and "i\<noteq>j" shows "end(q s!i)>end(q s!j)" using assms apply (simp add:con_assms_def Q_lemmas Q_basic_lemmas) by (metis Q_gap_lemmas_11 assms(1) end_simp length_pos_if_in_set nth_mem) lemma Q_gap_lemmas_9_list: assumes "Q_structure s" and "length(q s) >0" shows "\<forall>i j.(i<length(q s) \<and> j<length(q s) \<and> end(q s!i)>fst(q s!j) \<and> i\<noteq>j)\<longrightarrow> (end(q s!i)>end(q s!j))" using assms Q_gap_lemmas_9_list_B by blast lemma Q_gap_lemmas_10_list: assumes "Q_structure s" and "length(q s) >0" shows "\<forall>i j.(i<length(q s) \<and> j<length(q s) \<and> end(q s!i)>fst(q s!j) \<and> i\<noteq>j)\<longrightarrow> (fst(q s!i)\<ge>end(q s!j))" using assms apply (simp add:con_assms_def Q_lemmas Q_basic_lemmas) using Q_gap_lemmas_12 by (metis assms(1) end_simp length_pos_if_in_set nth_mem) lemma Q_gap_lemmas_11_list: assumes "Q_structure s" and "length(q s) >0" shows "\<forall>i j.(i<length(q s) \<and> j<length(q s) \<and> end(q s!i)>end(q s!j))\<longrightarrow> (end(q s!i)>fst(q s!j))" using assms apply (simp add:con_assms_def Q_lemmas Q_basic_lemmas) by (metis add_lessD1) lemma Q_gap_lemmas_12_list: assumes "Q_structure s" and "length(q s) >0" shows "\<forall>i j.(i<length(q s) \<and> j<length(q s) \<and> end(q s!i)>end(q s!j))\<longrightarrow> (fst(q s!i)\<ge>end(q s!j))" using assms apply (simp add:con_assms_def Q_lemmas Q_basic_lemmas) using Q_gap_lemmas_16 by (metis Q_gap_lemmas_2 assms(1) assms(2) end_simp) lemma Q_gap_lemmas_13_list: assumes "Q_structure s" and "length(q s) >0" shows "\<forall>i j.(i<length(q s) \<and> j<length(q s) \<and> end(q s!i)>end(q s!j))\<longrightarrow> (fst(q s!i)>fst(q s!j))" using assms apply (simp add:con_assms_def Q_lemmas Q_basic_lemmas) using Q_gap_lemmas_17 by (metis Q_gap_lemmas_2 assms(1) assms(2) end_simp) (**********) lemma ownB_lemma: assumes "length(q s) =2" and "Q_holds_bytes s" and "Q_has_no_overlaps s" and "Q_offsets_differ s" and "s' = (`q:= (tl(q s)) \<circ> (setownB [(fst(hd(q s)),(end(hd(q s)))) R])) s" shows "Q_holds_bytes s' " using assms apply (simp add:Q_lemmas Q_basic_lemmas) apply (intro conjI impI) apply clarify apply safe apply simp apply simp apply auto[1] apply(case_tac "a<fst(hd(q s))", simp_all) defer apply(case_tac "fst(hd(q s))<a", simp_all) apply (smt Suc_1 head_q0 le_less_trans length_greater_0_conv list.set_sel(2) not_less nth_mem plus_1_eq_Suc prod.collapse zero_less_two) apply(case_tac "fst(hd(q s)) =fst(a,b)") apply (metis (mono_tags, hide_lams) One_nat_def Suc_1 Suc_leI diff_Suc_1 diff_is_0_eq' hd_conv_nth in_set_conv_nth length_tl lessI list.sel(2) nat.simps(3) nth_tl zero_less_Suc) apply(simp add:fst_def) apply (metis (no_types, lifting) One_nat_def Suc_1 add_diff_cancel_left' in_set_conv_nth length_tl less_one nat_neq_iff nth_tl plus_1_eq_Suc zero_less_two) apply (metis list.sel(2) list.set_sel(2)) by (metis (no_types, lifting) hd_in_set le_add_diff_inverse2 length_0_conv list.set_sel(2) prod.collapse trans_le_add2 verit_comp_simplify1(3) zero_neq_numeral) (* lemma ownB_lemma2: assumes "Q_holds_bytes s" and "Q_structure s" and "\<forall>i.(i<n)\<longrightarrow>Data s i>0" and "q s\<noteq>[]" and "s' = (`q:= (tl(q s)) \<circ> (setownB [(fst(hd(q s)),(end(hd(q s)))) R]) \<circ> (`tempR := (hd(q s))) \<circ> (transownT [Q R s]) \<circ> (`numDeqs :=(numDeqs s+1))) s" shows "Q_holds_bytes s'" using assms apply (simp add:Q_lemmas Q_basic_lemmas) apply(elim conjE impE) apply(case_tac "ownT s=Q", simp_all) apply(case_tac "length(q s) =1", simp_all) apply (metis diff_Suc_1 length_pos_if_in_set length_tl less_numeral_extra(3)) apply(case_tac "length(q s) =2", simp_all) apply (smt Suc_1 add_diff_cancel_left' fst_conv fst_def hd_conv_nth in_set_conv_nth le_less_trans length_tl less_2_cases_iff less_Suc0 nat_arith.rule0 not_less nth_tl plus_1_eq_Suc prod.collapse) apply clarify apply safe apply(case_tac "fst(hd(q s)) >a", simp add:fst_def snd_def) apply (smt fst_def hd_in_set le_imp_less_Suc le_less_trans list.set_sel(2) not_less_eq prod.collapse) defer apply(case_tac "fst(hd(q s))<a", simp add:fst_def snd_def) apply (meson list.set_sel(2)) apply (meson list.set_sel(2)) apply(case_tac "fst(hd(q s)) =fst(a,b)", simp add:fst_def snd_def) apply (smt One_nat_def Suc_mono Suc_pred fst_conv fst_def hd_conv_nth in_set_conv_nth length_greater_0_conv length_tl less_antisym not_less_zero nth_tl zero_induct) apply(simp add:fst_def snd_def) apply (smt Suc_leI fst_def hd_in_set le_trans linorder_neqE_nat list.set_sel(2) not_less_eq_eq prod.collapse snd_def) apply(simp add:fst_def snd_def) apply (meson list.set_sel(2)) apply (meson list.set_sel(2)) apply clarsimp apply (case_tac "a<fst(hd(q s))", simp_all add:fst_def snd_def) apply (case_tac "a>fst(hd(q s))", simp_all add:fst_def snd_def) apply (smt fst_def hd_in_set le_less_trans list.set_sel(2) not_less prod.collapse snd_def) by (smt One_nat_def Suc_mono Suc_pred fst_conv fst_def hd_conv_nth in_set_conv_nth length_greater_0_conv length_tl less_antisym not_less_zero nth_tl zero_induct) lemma Q_type_1: assumes "q s=[(3,2),(5,2),(0,1)] \<and> N=10" shows "Q_basic_struct s" using assms apply(simp add:Q_basic_struct_def) apply(intro conjI impI) apply(simp add:Q_boundness_def) apply(simp add:Q_gap_structure_def) using less_Suc_eq apply force apply(simp add:Q_offsets_differ_def) using less_Suc_eq apply fastforce apply(simp add:Q_has_no_overlaps_def) using less_Suc_eq apply force by(simp add:Q_has_no_uroboros_def) lemma Q_tail_props: shows "\<forall>i.(i<length(q s) \<and> i>0)\<longrightarrow>(((q s)!i) = (tl(q s)!(i-1)))" apply simp by (simp add: diff_less_mono nth_tl) lemma Q_basic_preserved: assumes "Q_basic_struct s" and "s' = (`q:= (tl(q s))) s" shows "Q_basic_struct s'" using assms apply(simp add:Q_basic_struct_def) apply(intro conjI impI) apply(simp add:Q_basic_struct_def Q_boundness_def) apply (metis list.sel(2) list.set_sel(2)) apply(simp add:Q_basic_struct_def Q_gap_structure_def) defer apply(simp add:Q_offsets_differ_def) apply (metis One_nat_def Suc_eq_plus1 diff_Suc_1 length_tl less_diff_conv nth_tl) apply(simp add:Q_has_no_overlaps_def) apply (metis list.sel(2) list.set_sel(2)) prefer 2 apply (metis One_nat_def assms(1) end_simp length_tl less_nat_zero_code list.size(3) tail_preserves_Q_basic_struct) using assms Q_tail_props apply (simp add:Q_has_no_uroboros_def Q_basic_struct_def) by (smt (z3) assms(1) empty_iff end_simp fst_conv in_set_butlastD list.set(1) tail_preserves_Q_basic_struct) (* lemma Q_basic_preserved2: assumes "Q_structure s" and "ownT s=Q" and "s' =((`q:= (tl(q s))) \<circ> (`pcR := Read) \<circ> (`tempR := (hd(q s))) \<circ> (transownT [Q R s]) \<circ> (`numDeqs :=(numDeqs s+1)) \<circ> (setownB [(fst(hd(q s)),(end(hd(q s)))) R])) s" shows "Q_structure s'" using assms apply simp apply(simp add:Q_structure_def) apply(intro conjI impI) apply(simp add:Q_basic_struct_def) apply(intro conjI impI) apply(simp add:Q_boundness_def) apply (metis list.sel(2) list.set_sel(2)) apply(simp add:Q_gap_structure_def) apply (smt One_nat_def Q_tail_props Suc_diff_le Suc_leI Suc_mono Suc_pred length_greater_0_conv less_SucI list.sel(2)) apply(simp add:Q_offsets_differ_def) apply (metis (no_types, lifting) Nitpick.size_list_simp(2) One_nat_def Suc_mono length_tl list.sel(2) nat.inject nth_tl) apply(simp add:Q_has_no_overlaps_def) apply (metis (no_types, lifting) list.sel(2) list.set_sel(2)) apply(simp add:Q_has_no_uroboros_def) apply (metis butlast_tl last_tl list.sel(2) list.set_sel(2)) using ownB_lemma2 apply (simp add:Q_holds_bytes_def) apply clarify apply safe apply simp_all apply(case_tac "fst(hd(q s))>a", simp_all) apply(simp add:Q_lemmas Q_basic_lemmas fst_def snd_def) apply (smt fst_def hd_in_set le_imp_less_Suc le_less_trans list.sel(2) list.set_sel(2) not_less_eq prod.collapse) defer apply(case_tac "fst(hd(q s))<a", simp_all) apply (metis list.sel(2) list.set_sel(2)) apply (metis list.sel(2) list.set_sel(2)) defer defer defer apply(case_tac "fst(hd(q s)) =fst(a,b)", simp add:fst_def snd_def Q_lemmas Q_basic_lemmas) apply (smt One_nat_def Suc_mono Suc_pred fst_conv fst_def hd_conv_nth in_set_conv_nth length_greater_0_conv length_tl less_antisym list.sel(2) not_less_zero nth_tl zero_induct) apply(simp add:Q_basic_struct_def Q_has_no_overlaps_def fst_def snd_def) apply clarify apply(simp add:Q_lemmas Q_basic_lemmas fst_def snd_def butlast_def) apply (smt fst_def hd_in_set le_less_trans linorder_neqE_nat list.sel(2) list.set_sel(2) not_less prod.collapse snd_def) (*finally Q_holds_bytes done*) apply(simp add:Q_reflects_writes_def) apply (simp add: nth_tl) apply(simp add:Q_elem_size_def) apply (simp add: nth_tl) apply(simp add:Q_reflects_ownD_def) using less_diff_conv by auto *) *) (*tempR used to be part of Q so:.....*) definition "tempR_boundness s \<equiv> (end (tempR s) \<le> N)" definition "tempR_offsets_differ s \<equiv> (\<forall>i.(i<length(q s))\<longrightarrow>(fst(q s!i)\<noteq>fst(tempR s)))" definition "tempR_gap_structure s \<equiv> (end(tempR s) = fst(hd(q s)))\<or> (fst(hd(q s)) =0)" definition "tempR_has_no_uroboros s \<equiv> (fst (tempR s) \<noteq> end (last (q s)))" definition "tempR_has_no_overlaps s \<equiv>(\<forall>i.(i<length(q s))\<longrightarrow>((fst(tempR s)<fst(q s!i)\<longrightarrow>end(tempR s)\<le>fst(q s!i)) \<and>(fst(tempR s)>fst(q s!i)\<longrightarrow>end(q s!i)\<le>fst(tempR s))))" definition "tempR_basic_struct s \<equiv> tempR_boundness s \<and> (q s\<noteq>[]\<longrightarrow> (tempR_gap_structure s \<and> tempR_offsets_differ s \<and> tempR_has_no_overlaps s \<and> tempR_has_no_uroboros s)) " lemmas tempR_basic_lemmas = tempR_basic_struct_def tempR_has_no_overlaps_def tempR_gap_structure_def tempR_has_no_uroboros_def tempR_boundness_def tempR_offsets_differ_def definition "tempR_holds_bytes s \<equiv> (\<forall>j.(fst(tempR s)\<le>j \<and> j<end(tempR s))\<longrightarrow>ownB s j=R)" definition "tempR_reflects_writes s \<equiv> (data_index s (tempR s) = ((numDeqs s) -1))" definition "tempR_elem_size s \<equiv> (snd(tempR s) =Data s ((numDeqs s) -1))" definition "tempR_structure s \<equiv>(tempR_basic_struct s \<and> tempR_holds_bytes s \<and> tempR_reflects_writes s \<and> tempR_elem_size s)" lemmas tempR_lemmas = tempR_holds_bytes_def tempR_reflects_writes_def tempR_elem_size_def tempR_structure_def (*tempW will be part of Q so:.....*) definition "tempW s \<equiv> (offset s, Data s (numEnqs s))" definition "tempW_boundness s \<equiv> (end (tempW s) \<le> N)" definition "tempW_offsets_differ s \<equiv> (\<forall>i.(i<length(q s))\<longrightarrow>(fst(q s!i)\<noteq>fst(tempW s)))" definition "tempW_gap_structure s \<equiv> (fst(tempW s) = end(last(q s)))\<or> (fst(tempW s) =0)" definition "tempW_has_no_uroboros s \<equiv> (end((tempW s)) \<noteq> fst (hd (q s)))" definition "tempW_has_no_overlaps s \<equiv>(\<forall>i.(i<length(q s))\<longrightarrow>((fst(tempW s)<fst(q s!i)\<longrightarrow>end(tempW s)<fst(q s!i)) \<and>(fst(tempW s)>fst(q s!i)\<longrightarrow>end(q s!i)\<le>fst(tempW s))))" definition "tempW_basic_struct s \<equiv> tempW_boundness s \<and> (q s\<noteq>[]\<longrightarrow> (tempW_gap_structure s \<and> tempW_offsets_differ s \<and> tempW_has_no_overlaps s \<and> tempW_has_no_uroboros s))" lemmas tempW_basic_lemmas = tempW_basic_struct_def tempW_has_no_overlaps_def tempW_gap_structure_def tempW_has_no_uroboros_def tempW_boundness_def tempW_offsets_differ_def tempW_def definition "tempW_holds_bytes s \<equiv> (\<forall>j.(fst(tempW s)\<le>j \<and> j<end(tempW s))\<longrightarrow>ownB s j=W)" definition "tempW_reflects_writes s \<equiv> (data_index s (offset s, Data s (numEnqs s)) = numEnqs s)" definition "tempW_structure s \<equiv>(tempW_basic_struct s \<and> tempW_holds_bytes s )" lemmas tempW_lemmas = tempW_holds_bytes_def tempW_reflects_writes_def tempW_structure_def (*Writer Thread Behaviour*) fun rbW_step :: "PCW \<Rightarrow> rb_state \<Rightarrow> rb_state" where "rbW_step A1 s = ((`hW := (H s)) \<circ> (`tW := (T s)) \<circ> (`pcW := A2)) s " | "rbW_step A2 s = (if grd1 s then ((`pcW := A3) \<circ> (transownT [Q W s])) else if grd2 s then (`pcW := A4) else if grd3 s then (`pcW := A5) else (`pcW :=A8)) s" | "rbW_step A3 s = ((`T := 0) \<circ> (`H := (Data s (numEnqs s))) \<circ> (`offset := 0) \<circ> (`pcW := Write) \<circ> setownB [(0,(Data s (numEnqs s))) W]) s" | "rbW_step A4 s = ((`H := ((hW s) + (Data s (numEnqs s)))) \<circ> (`offset := (hW s)) \<circ> (`pcW := Write) \<circ> setownB [(hW s,hW s+Data s (numEnqs s)) W]) s" | "rbW_step A5 s = (if grd4 s then (`pcW := A6) else if grd5 s then (`pcW := A7) else (`pcW := A8)) s" | "rbW_step A6 s = (`H := ((hW s) + (Data s (numEnqs s))) \<circ> (`offset := (hW s)) \<circ> (`pcW := Write) \<circ> setownB [(hW s,hW s+Data s (numEnqs s)) W]) s" | "rbW_step A7 s = ((`H := (Data s (numEnqs s))) \<circ> (`offset := 0) \<circ> (`pcW := Write) \<circ> (setownB [(hW s,N) D]) \<circ> (setownB [(0,Data s (numEnqs s)) W])) s" | "rbW_step A8 s = (if ((Data s (numEnqs s))>N) then ERRBTS s else (ERROOM \<circ> (`tW := (T s))) s)" | "rbW_step Write s = s" | "rbW_step Enqueue s = s"| "rbW_step idleW s = s" | "rbW_step FinishedW s = s"| "rbW_step BTS s = s"| "rbW_step OOM s = s" definition "B_acquire s s' \<equiv> s' = (`pcW := A1) s" definition "Q_enqueue s s' \<equiv> s' = (`q:=(append (q s) [(offset s,Data s (numEnqs s))]) \<circ> `pcW := idleW \<circ> transownB [W Q] \<circ> `numEnqs := (numEnqs s + 1) \<circ> transownT [W Q s]) s" definition "B_write s s' \<equiv> s' = ((`B.write ((offset s), (Data s (numEnqs s))):= (numEnqs s)) \<circ> (transownD [(numWrites s) B]) \<circ> `pcW := Enqueue \<circ> (`numWrites := ((numWrites s )+1))) s" definition cW_step :: "PCW \<Rightarrow> rb_state \<Rightarrow> rb_state \<Rightarrow> bool" where "cW_step pcw s s' \<equiv> case pcw of idleW \<Rightarrow> if ((numEnqs s) < n) then B_acquire s s' else s' = (`pcW := FinishedW ) s | Write \<Rightarrow> B_write s s' | Enqueue \<Rightarrow> Q_enqueue s s' | OOM \<Rightarrow> if tW s \<noteq> T s then s' = (`pcW := idleW ) s else s = s' | FinishedW \<Rightarrow> s = s' | BTS \<Rightarrow> s = s' | _ \<Rightarrow> s' = rbW_step pcw s " lemmas W_functs [simp] = B_acquire_def B_write_def Q_enqueue_def (*---------Tailored assertions to Writer-------*) definition "pre_acquire_inv s \<equiv> (\<forall>j.(j\<ge>0\<and> j\<le>N)\<longrightarrow>ownB s j\<noteq>W) \<and> (ownT s \<noteq> W) \<and> (T s=H s \<longrightarrow> (\<forall>i.(i\<ge>0 \<and> i<N)\<longrightarrow>ownB s i=B) \<and> ownT s = Q \<and> q s= [] \<and> numDeqs s = numEnqs s) \<and> (T s>H s \<longrightarrow> (\<forall>i.(i\<ge>H s \<and> i<T s)\<longrightarrow>ownB s i=B)) \<and> (T s<H s \<longrightarrow> (\<forall>i.((i\<ge>H s \<and> i<N) \<or> i<T s)\<longrightarrow>ownB s i=B)) \<and> (numWrites s=numEnqs s) \<and> (numEnqs s=0\<longrightarrow>q s=[]) \<and> (numEnqs s\<le>n) \<and> (numEnqs s>0\<longleftrightarrow>H s>0) \<and> (numEnqs s=0\<longleftrightarrow>H s=0) " definition "pre_A1_inv s \<equiv> (T s=H s\<longrightarrow>((\<forall>i.(i\<ge>0 \<and> i<N)\<longrightarrow>ownB s i=B) \<and> ownT s =Q \<and> q s=[])) \<and> (\<forall>j.(j\<ge>0\<and> j\<le>N)\<longrightarrow>ownB s j\<noteq>W) \<and> (ownT s \<noteq>W) \<and> (T s>H s \<longrightarrow> (\<forall>i.(i\<ge>H s \<and> i<T s)\<longrightarrow>ownB s i=B)) \<and> (T s<H s \<longrightarrow> (\<forall>i.((i\<ge>H s \<and> i<N) \<or> i<T s)\<longrightarrow>ownB s i=B)) \<and> (numWrites s=numEnqs s) \<and> (numEnqs s<n) \<and> (numEnqs s>0\<longleftrightarrow>H s>0) \<and> (numEnqs s=0\<longleftrightarrow>H s=0) \<and> (T s = 0 \<and> H s = 0) = (numWrites s = 0) " definition "pre_A2_inv s \<equiv> (tW s=hW s\<longrightarrow>((\<forall>i.(i\<ge>0 \<and> i<N)\<longrightarrow>ownB s i=B) \<and> ownT s =Q \<and> q s=[] \<and> tW s=T s)) \<and> (tW s>hW s \<longrightarrow> ((\<forall>i.(i\<ge>hW s \<and> i<tW s)\<longrightarrow>ownB s i=B) \<and> (T s\<ge>tW s \<or> T s\<le>H s))) \<and> (tW s<hW s \<longrightarrow> ((\<forall>i.((i\<ge>hW s \<and> i<N) \<or> i<tW s)\<longrightarrow>ownB s i=B) \<and> T s\<ge>tW s \<and> H s\<ge>T s)) \<and> (\<forall>j.(j\<ge>0\<and> j\<le>N)\<longrightarrow>ownB s j\<noteq>W) \<and> (ownT s \<noteq>W) \<and> (numWrites s=numEnqs s) \<and> (numEnqs s<n) \<and> (H s=hW s) \<and> (numEnqs s=0\<longrightarrow>q s=[]) \<and> (numEnqs s>0\<longleftrightarrow>H s>0) \<and> (numEnqs s=0\<longleftrightarrow>H s=0) \<and> (T s = 0 \<and> H s = 0) = (numWrites s = 0) " definition "pre_A3_inv s \<equiv> ((\<forall>i.(i\<ge>0 \<and> i<N)\<longrightarrow>ownB s i=B)) \<and> (grd1 s) \<and> (ownT s =W) \<and> (numWrites s=numEnqs s) \<and> (numEnqs s<n) \<and> (H s=hW s) \<and> q s=[] \<and> (numEnqs s=0\<longrightarrow>q s=[]) \<and> (numEnqs s>0\<longleftrightarrow>H s>0) \<and> (numEnqs s=0\<longleftrightarrow>H s=0) \<and> (T s=tW s) \<and> (T s = 0 \<and> H s = 0) = (numWrites s = 0) " definition "pre_A4_inv s \<equiv> (\<forall>i.(i\<ge>hW s \<and> i<tW s)\<longrightarrow>ownB s i=B) \<and> (grd2 s) \<and> (\<not>grd1 s) \<and> (\<forall>j.(j\<ge>0\<and> j\<le>N)\<longrightarrow>ownB s j\<noteq>W) \<and> (ownT s \<noteq>W) \<and> (numWrites s=numEnqs s) \<and> (numEnqs s<n) \<and> (H s=hW s) \<and> (numEnqs s=0\<longrightarrow>q s=[]) \<and> (numEnqs s>0\<longleftrightarrow>H s>0) \<and> (numEnqs s=0\<longleftrightarrow>H s=0) \<and> (T s\<ge>tW s \<or> T s\<le>H s) \<and> (T s = 0 \<and> H s = 0) = (numWrites s = 0) " definition "pre_A5_inv s \<equiv> (\<forall>i.((i\<ge>hW s \<and> i<N) \<or> i<tW s)\<longrightarrow>ownB s i=B) \<and> (grd3 s) \<and> (\<not>grd1 s) \<and> (\<not>grd2 s) \<and> (\<forall>j.(j\<ge>0\<and> j\<le>N)\<longrightarrow>ownB s j\<noteq>W) \<and> (ownT s \<noteq>W) \<and> (numWrites s=numEnqs s) \<and> (numEnqs s<n) \<and> (H s=hW s) \<and> (numEnqs s=0\<longrightarrow>q s=[]) \<and> (numEnqs s>0\<longleftrightarrow>H s>0) \<and> (numEnqs s=0\<longleftrightarrow>H s=0) \<and> (T s\<ge>tW s \<and> T s\<le>H s) \<and> (T s = 0 \<and> H s = 0) = (numWrites s = 0) " definition "pre_A6_inv s \<equiv> (\<forall>i.((i\<ge>hW s \<and> i<N) \<or> i<tW s)\<longrightarrow>ownB s i=B) \<and> (grd4 s) \<and> (grd3 s) \<and> (\<not>grd1 s) \<and> (\<not>grd2 s) \<and> (\<forall>j.(j\<ge>0\<and> j\<le>N)\<longrightarrow>ownB s j\<noteq>W) \<and> (ownT s \<noteq>W) \<and> (numWrites s=numEnqs s) \<and> (numEnqs s<n) \<and> (H s=hW s) \<and> (numEnqs s=0\<longrightarrow>q s=[]) \<and> (numEnqs s>0\<longleftrightarrow>H s>0) \<and> (numEnqs s=0\<longleftrightarrow>H s=0) \<and> (T s\<ge>tW s \<and> T s\<le>H s) \<and> (T s = 0 \<and> H s = 0) = (numWrites s = 0) " definition "pre_A7_inv s \<equiv> (\<forall>i.((i\<ge>hW s \<and> i<N) \<or> i<tW s)\<longrightarrow>ownB s i=B) \<and> (grd5 s) \<and> (grd3 s) \<and> (\<not>grd1 s) \<and> (\<not>grd2 s) \<and> (\<not>grd4 s) \<and> (\<forall>j.(j\<ge>0\<and> j\<le>N)\<longrightarrow>ownB s j\<noteq>W) \<and> (ownT s \<noteq>W) \<and> (numWrites s=numEnqs s) \<and> (numEnqs s<n) \<and> (H s=hW s) \<and> (numEnqs s=0\<longrightarrow>q s=[]) \<and> (numEnqs s>0\<longleftrightarrow>H s>0) \<and> (numEnqs s=0\<longleftrightarrow>H s=0) \<and> (T s\<ge>tW s \<and> T s\<le>H s) \<and> (T s = 0 \<and> H s = 0) = (numWrites s = 0) " definition "pre_A8_inv s \<equiv> (tW s\<le>hW s \<longrightarrow>(\<forall>i.((i\<ge>hW s \<and> i<N) \<or> i<tW s)\<longrightarrow>ownB s i=B)) \<and> (tW s>hW s \<longrightarrow>(\<forall>i.(hW s \<le>i \<and> i<tW s)\<longrightarrow>ownB s i=B)) \<and> (\<forall>j.(j\<ge>0\<and> j\<le>N)\<longrightarrow>ownB s j\<noteq>W) \<and> (ownT s \<noteq>W) \<and> (numWrites s=numEnqs s) \<and> (no_space_for_word s) \<and> (numEnqs s<n) \<and> (H s=hW s) \<and> (numEnqs s=0\<longrightarrow>q s=[]) \<and> (numEnqs s>0\<longleftrightarrow>H s>0) \<and> (numEnqs s=0\<longleftrightarrow>H s=0) \<and> (T s\<ge>tW s \<or> T s\<le>H s) \<and> (T s = 0 \<and> H s = 0) = (numWrites s = 0) " definition "pre_write_inv s \<equiv> (\<forall>i.(i\<ge>offset s \<and> i< ((offset s)+(Data s (numEnqs s))))\<longrightarrow>ownB s i=W) \<and> ((tW s>hW s)\<longrightarrow>(\<forall>i.(i\<ge>((offset s)+(Data s (numEnqs s)))\<and>i<tW s)\<longrightarrow>ownB s i =B)) \<and> ((tW s<hW s \<and> offset s\<noteq>0)\<longrightarrow>(\<forall>i.((i\<ge>((offset s)+(Data s (numEnqs s))) \<and> i<N)\<or>i<tW s)\<longrightarrow>ownB s i =B)) \<and> ((tW s<hW s \<and> offset s=0)\<longrightarrow>((\<forall>i.(i\<ge>((offset s)+(Data s (numEnqs s))) \<and> i<tW s)\<longrightarrow>ownB s i =B) \<and> (\<forall>i.(i\<ge>hW s \<and> i<N)\<longrightarrow>ownB s i=D))) \<and> (tW s=hW s\<longrightarrow>(ownT s=W \<and> q s=[])) \<and> (numWrites s=numEnqs s) \<and> (numEnqs s<n) \<and> (tempW_structure s) \<and> (ownD s(numWrites s) =W) \<and> (numEnqs s=0\<longrightarrow>q s=[]) \<and> (offset s=hW s \<or> offset s=0) \<and> (H s=offset s + Data s (numEnqs s)) " definition "pre_enqueue_inv s \<equiv> (\<forall>i.(i\<ge>offset s \<and> i< end(tempW s))\<longrightarrow>ownB s i=W) \<and> (\<forall>i.(i<offset s \<or> (i\<ge> end(tempW s)\<and>i\<le>N))\<longrightarrow>ownB s i\<noteq>W) \<and> ((tW s>hW s)\<longrightarrow>(\<forall>i.(i\<ge>end(tempW s)\<and>i<tW s)\<longrightarrow>ownB s i =B)) \<and> ((tW s<hW s \<and> offset s\<noteq>0)\<longrightarrow>(\<forall>i.((i\<ge>end(tempW s) \<and> i<N)\<or>i<tW s)\<longrightarrow>ownB s i =B)) \<and> ((tW s<hW s \<and> offset s=0)\<longrightarrow>((\<forall>i.(i\<ge>end(tempW s) \<and> i<tW s)\<longrightarrow>ownB s i =B) \<and> (\<forall>i.(i\<ge>hW s \<and> i<N)\<longrightarrow>ownB s i=D))) \<and> (tW s=hW s\<longrightarrow>(ownT s=W \<and> q s=[])) \<and> (numWrites s=numEnqs s +1) \<and> (numEnqs s<n) \<and> ((ownT s = W)\<longrightarrow>q s=[]) \<and> (tempW_structure s) \<and> (tempW_reflects_writes s) \<and> (ownD s(numEnqs s) =B) \<and> (numEnqs s=0\<longrightarrow>q s=[]) \<and> (offset s=hW s \<or> offset s=0) \<and> (H s=offset s + Data s (numEnqs s)) " definition "pre_OOM_inv s \<equiv> (\<forall>j.(j\<ge>0\<and> j\<le>N)\<longrightarrow>ownB s j\<noteq>W) \<and> (ownT s \<noteq>W) \<and> (tW s>hW s \<longrightarrow> (\<forall>i.(i\<ge>tW s \<and> i<hW s)\<longrightarrow>ownB s i=B)) \<and> (tW s<hW s \<longrightarrow> (\<forall>i.((i\<ge>hW s \<and> i<N) \<or> i<tW s)\<longrightarrow>ownB s i=B)) \<and> (numWrites s=numEnqs s) \<and> (numEnqs s<n) \<and> (H s=hW s) \<and> (numEnqs s=0\<longrightarrow>q s=[]) \<and> (numEnqs s>0\<longleftrightarrow>H s>0) \<and> (numEnqs s=0\<longleftrightarrow>H s=0) \<and> (T s = 0 \<and> H s = 0) = (numWrites s = 0) " definition "pre_finished_inv s \<equiv> (\<forall>j.(j\<ge>0\<and> j\<le>N)\<longrightarrow>ownB s j\<noteq>W) \<and> (ownT s \<noteq>W) \<and> (numWrites s=numEnqs s) \<and> (numEnqs s=n) \<and> (H s>0) " definition "pre_BTS_inv s \<equiv> (\<forall>j.(j\<ge>0\<and> j\<le>N)\<longrightarrow>ownB s j\<noteq>W) \<and> (ownT s \<noteq>W) \<and> (numWrites s=numEnqs s) \<and> (numEnqs s<n) \<and> (H s=hW s) \<and> (numEnqs s=0\<longrightarrow>q s=[]) \<and> (numEnqs s>0\<longleftrightarrow>H s>0) \<and> (numEnqs s=0\<longleftrightarrow>H s=0) \<and> (T s = 0 \<and> H s = 0) = (numWrites s = 0) " lemmas writer_lemmas = pre_A1_inv_def pre_A2_inv_def pre_A3_inv_def pre_A4_inv_def pre_A5_inv_def pre_A6_inv_def pre_A7_inv_def pre_A8_inv_def pre_BTS_inv_def pre_OOM_inv_def pre_acquire_inv_def pre_finished_inv_def pre_enqueue_inv_def pre_write_inv_def (***********************************************************************) (*Reader Thread Behaviour*) definition "B_release s s' \<equiv> s' = (`T := (end(tempR s)) \<circ> (`pcR := idleR) \<circ> (`tempR := (0,0)) \<circ> (transownB [R B]) \<circ> (if tR s\<noteq> fst(tempR s) then setownB [(tR s,N) B] else id) \<circ> transownT [R Q s]) s" definition "B_read s s' \<equiv> s' = (((transownD [(data_index s (tempR s)) R]) \<circ> (`pcR := Release)) \<circ> (`numReads := (numReads s+1)) \<circ> (`tR := (T s))) s" definition "Q_dequeue s s' \<equiv> s' = ((`q:= (tl(q s))) \<circ> (`pcR := Read) \<circ> (`tempR := (hd(q s))) \<circ> (transownT [Q R s]) \<circ> (`numDeqs :=(numDeqs s+1)) \<circ> (setownB [(off(hd(q s)),(end(hd(q s)))) R])) s" definition cR_step :: "PCR \<Rightarrow> rb_state \<Rightarrow> rb_state \<Rightarrow> bool" where "cR_step pcr s s' \<equiv> case pcr of idleR \<Rightarrow> if (q s=[]) then (s=s') else (Q_dequeue s s') | Read \<Rightarrow> B_read s s' | Release \<Rightarrow> B_release s s'" lemmas R_functs [simp] = B_release_def B_read_def Q_dequeue_def (*---------Tailored assertions to Reader-------*) definition "pre_dequeue_inv s \<equiv> (tempR s = (0,0)) \<and> (numDeqs s \<le> n) \<and> (numDeqs s \<ge> 0) \<and> (numDeqs s = numReads s) \<and> (numDeqs s \<le> numEnqs s) \<and> (pcR s = idleR) \<and> (q s\<noteq>[] \<longrightarrow> ownT s=Q) \<and> (q s\<noteq>[] \<longrightarrow> H s>0) \<and> ((T s\<noteq>fst(hd(q s))\<and>q s\<noteq>[])\<longrightarrow>(\<forall>x j.(x\<in>set(q s) \<and> j<N \<and> j\<ge>T s)\<longrightarrow>end(x)<j)) \<and> (q s\<noteq>[]\<longrightarrow>(\<forall>i.(fst(hd(q s))\<le>i \<and> i<end(hd(q s)))\<longrightarrow>ownB s i = Q)) \<and> (\<forall>i.(i<fst(tempR s) \<or> (i\<ge>end(tempR s)\<and> i\<le>N))\<longrightarrow>ownB s i \<noteq> R) " definition "pre_Read_inv s \<equiv> (snd(tempR s) = Data s (numReads s)) \<and> (numReads s=data_index s (tempR s)) \<and> (numDeqs s\<le>n) \<and> (numDeqs s\<ge>0) \<and> (numReads s+1=numDeqs s) \<and> (numDeqs s\<ge>1) \<and> (numEnqs s\<ge>numDeqs s) \<and> (pcR s=Read) \<and> (ownT s = R) \<and> (ownD s (numReads s) = B) \<and> (tempR s\<noteq>(0,0)) \<and> (tempR_structure s) \<and> (\<forall>i.(fst(tempR s)\<le>i \<and> i<end(tempR s))\<longrightarrow>ownB s i = R) \<and> (\<forall>i.(i<fst(tempR s) \<or> (i\<ge>end(tempR s)\<and> i\<le>N))\<longrightarrow>ownB s i \<noteq> R) \<and> (H s>0) " definition "pre_Release_inv s \<equiv> (snd(tempR s) = Data s (numReads s -1)) \<and> (data_index s (tempR s) = numReads s -1) \<and> (q s\<noteq>[]\<longrightarrow>(numReads s=data_index s (hd(q s)))) \<and> (ownT s = R) \<and> (numEnqs s\<ge>numDeqs s) \<and> (ownD s (numReads s -1) = R) \<and> (numDeqs s\<le>n \<and> numDeqs s\<ge>1) \<and> (numDeqs s = numReads s) \<and> (pcR s=Release) \<and> (tR s=T s) \<and> (tempR s\<noteq>(0,0)) \<and> (tempR_structure s) \<and> (\<forall>i.(fst(tempR s)\<le>i \<and> i<end(tempR s))\<longrightarrow>ownB s i = R) \<and> (\<forall>i.(i<fst(tempR s) \<or> (i\<ge>end(tempR s)\<and> i\<le>N))\<longrightarrow>ownB s i \<noteq> R) \<and> (H s>0) " lemmas reader_lemmas = pre_Release_inv_def pre_Read_inv_def pre_dequeue_inv_def (***********************************************************************) lemma Q_structure_preserved1: assumes "Q_structure s" and "pre_dequeue_inv s" and "q s\<noteq>[]" and "Q_dequeue s s'" shows "Q_structure s'" using assms apply(simp add:Q_structure_def pre_dequeue_inv_def) apply (intro conjI impI) apply(simp add:Q_basic_struct_def) apply(intro conjI impI) apply(simp add:Q_boundness_def ) apply (metis list.set_sel(2)) apply(simp add:Q_gap_structure_def) apply (metis (no_types, hide_lams) One_nat_def Q_gap_structure_def end_simp length_tl tail_preserves_Q_gap_structure) apply(simp add:Q_offsets_differ_def) apply (metis (no_types, lifting) One_nat_def add.commute add_right_cancel length_tl less_diff_conv nth_tl plus_1_eq_Suc) apply(simp add:Q_has_no_overlaps_def) apply (metis (no_types, lifting) list.set_sel(2)) apply(simp add:Q_has_no_uroboros_def) apply (metis butlast_tl last_tl list.sel(2) list.set_sel(2)) apply(simp add:Q_reflects_writes_def) apply(simp add:Q_elem_size_def) apply (meson list.set_sel(2)) apply(simp add:Q_reflects_writes_def) apply (metis One_nat_def Suc_eq_plus1 add_Suc_right length_tl less_diff_conv nth_tl) apply(simp add:Q_reflects_ownD_def) apply(simp add:Q_elem_rel_def) apply (metis (no_types, hide_lams) One_nat_def Q_structure_def Suc_eq_plus1_left add.commute assms(1) length_tl tail_preserves_Q_elem_size) apply(simp add:Q_reflects_ownD_def) by (metis Nat.add_0_right add_Suc add_Suc_right less_diff_conv) lemma Q_structure_preserved2: assumes "Q_structure s" and "ownT s=R" and "pre_Read_inv s" and "B_read s s'" shows "Q_structure s'" using assms apply(simp add:Q_structure_def) apply(intro conjI impI) apply(simp add:Q_basic_struct_def) apply(intro conjI impI) apply(simp add:Q_boundness_def) apply(simp add:Q_gap_structure_def) apply(simp add:Q_offsets_differ_def) apply(simp add:Q_has_no_overlaps_def) apply(simp add:Q_has_no_uroboros_def) apply(simp add:Q_elem_size_def) apply(simp add:Q_holds_bytes_def) apply(simp add:Q_reflects_writes_def) apply(simp add:Q_elem_size_def) apply(simp add:Q_reflects_ownD_def) apply(simp add:Q_elem_rel_def) apply(simp add:Q_reflects_ownD_def) by(simp add:Q_structure_def pre_Read_inv_def) lemma Q_structure_preserved3: assumes "Q_structure s" and "pre_Release_inv s" and "s' = (`T := (off(tempR s) +len(tempR s)) \<circ> (`pcR := idleR) \<circ> (`tempR := (0,0)) \<circ> (transownB [R B]) \<circ> (if tR s\<noteq> fst(tempR s) then setownB [(tR s,N) B] else id) \<circ> transownT [R Q s]) s" shows "Q_structure s'" using assms apply (simp add:Q_structure_def) apply(intro conjI impI) apply(simp add:Q_basic_struct_def) apply(intro conjI impI) apply(simp add:pre_Release_inv_def Q_boundness_def) apply(simp add:pre_Release_inv_def Q_gap_structure_def) apply(simp add:pre_Release_inv_def Q_offsets_differ_def) apply(simp add:pre_Release_inv_def Q_has_no_overlaps_def) apply(simp add:pre_Release_inv_def Q_has_no_uroboros_def) apply(simp add:pre_Release_inv_def Q_holds_bytes_def tempR_lemmas tempR_basic_lemmas) apply(simp add:pre_Release_inv_def Q_reflects_writes_def) apply(simp add:pre_Release_inv_def Q_elem_size_def) apply(simp add:pre_Release_inv_def Q_reflects_ownD_def) apply(simp add:pre_Release_inv_def Q_basic_lemmas) apply(simp add:pre_Release_inv_def Q_reflects_writes_def) apply(simp add:pre_Release_inv_def Q_elem_rel_def) apply(simp add:pre_Release_inv_def Q_reflects_ownD_def) apply(simp add:pre_Release_inv_def Q_basic_lemmas) apply(simp add:pre_Release_inv_def Q_reflects_writes_def) apply(simp add:pre_Release_inv_def Q_elem_rel_def) apply(simp add:pre_Release_inv_def Q_reflects_ownD_def) apply(simp add:pre_Release_inv_def Q_basic_lemmas) apply(simp add:pre_Release_inv_def Q_reflects_writes_def) apply(simp add:pre_Release_inv_def Q_elem_rel_def) apply(simp add:pre_Release_inv_def Q_reflects_ownD_def) apply(simp add:pre_Release_inv_def Q_basic_lemmas) apply(simp add:pre_Release_inv_def Q_reflects_writes_def) apply(simp add:pre_Release_inv_def Q_elem_rel_def) by(simp add:pre_Release_inv_def Q_reflects_ownD_def) definition "inRange v \<equiv> 0 \<le> v \<and> v \<le> N" definition "inRangeHT s \<equiv> inRange (H s) \<and> inRange (T s)" definition "H0_T0 s \<equiv> H s = 0 \<longrightarrow> T s = 0" definition "inRangeht s \<equiv> inRange (hW s) \<and> inRange (tW s)" definition "basic_pointer_movement s \<equiv> inRangeHT s \<and> inRangeht s \<and> H0_T0 s " lemmas basic_pointer_movement_lemmas [simp] = basic_pointer_movement_def inRangeHT_def inRangeht_def H0_T0_def inRange_def definition "mainInv s \<equiv> \<forall> i. (i<numReads s \<longrightarrow> ownD s i=R) \<and> (numReads s \<le> i \<and> i < numWrites s \<longrightarrow> ownD s i = B) \<and> (numWrites s \<le> i \<and> i < n \<longrightarrow> ownD s i = W) " definition "counter_bounds s \<equiv> numReads s \<le>n \<and> numWrites s\<le>n \<and> numEnqs s\<le>n \<and> numDeqs s \<le> n" definition "counter_q_rel s \<equiv> (numEnqs s-numDeqs s=length(q s))\<and> numWrites s\<ge>numReads s \<and> numEnqs s\<ge>numDeqs s" (*new lemmas, take 2*) definition "data_index_bouded s \<equiv> \<forall>i. (i\<le>N)\<longrightarrow>(\<forall>j.(j\<le>N)\<longrightarrow>data_index s (i,j)<n)" lemmas invariant_lemmas [simp] = con_assms_def mainInv_def counter_q_rel_def counter_bounds_def data_index_bouded_def definition "Q_ownB_rel s \<equiv> \<forall>j.(ownB s j=Q \<and> j<N)\<longrightarrow>(\<exists>a b. ((a, b)\<in>set(q s)\<and> a\<le>j \<and> j<a+b))" definition "ran_indices a b \<equiv> {i . a \<le> i \<and> i < b}" definition "Q_indices s \<equiv> \<Union> {ran_indices a (a + b) | a b. (a, b) \<in> set(q s)}" definition "Q_tail_indices s \<equiv> \<Union> {ran_indices a (a + b) | a b. (a, b) \<in> set(tl(q s))}" lemma ran_ind_imp_Q_ind: "\<forall>i a b. (i\<in> ran_indices a b \<and> (a, b)\<in>set(q s))\<longrightarrow>i\<in>Q_indices s" apply(simp add:Q_indices_def ran_indices_def) by (smt (z3) add.assoc add_lessD1 less_add_eq_less mem_Collect_eq) lemma Q_ind_imp_tail_ind_1: "tl(q s)\<noteq>[] \<Longrightarrow> hd(q s) = (q s!0)" apply (simp add:hd_def) by (metis Nil_tl hd_conv_nth hd_def) lemma Q_ind_imp_tail_ind_2: "tl(q s)\<noteq> [] \<Longrightarrow>i\<in>Q_indices s\<Longrightarrow> \<exists>a b.((a,b)\<in>set(tl(q s))\<and>a\<le>i \<and> i<b)\<Longrightarrow>i\<in>Q_tail_indices s" apply(simp add:Q_indices_def ran_indices_def Q_tail_indices_def) by (metis (no_types, lifting) leD leI le_iff_add mem_Collect_eq nat_add_left_cancel_less trans_le_add2) lemma Q_ind_imp_tail_ind_3: "tl(q s)\<noteq> [] \<Longrightarrow>i\<in>Q_indices s\<Longrightarrow> s'=(s\<lparr>ownB := \<lambda>i. if fst (hd (q s)) \<le> i \<and> i < fst (hd (q s)) + snd (hd (q s)) then R else ownB s i, numDeqs := Suc (numDeqs s), ownT := R, tempR := hd (q s), pcR := Read, q := tl (q s)\<rparr>) \<Longrightarrow>\<exists>a b.((a,b)\<in>set(tl(q s))\<and>a\<le>i \<and> i<b)\<Longrightarrow>i\<in>Q_indices s'" apply(simp add:Q_indices_def ran_indices_def Q_tail_indices_def) by (metis (no_types, lifting) leD leI le_iff_add mem_Collect_eq nat_add_left_cancel_less trans_le_add2) (* [(1, 3), (4,1)] ran_indices 1 4 = {1,2,3} ran_indicies 4,5 = {4} Q_indicies s = {1,2,3,4} *) definition "Q_owns_bytes s \<equiv> \<forall>i.(i\<in>Q_indices s)\<longleftrightarrow>(i\<le>N \<and> ownB s i=Q)" definition "Q_tail_owns_bytes s \<equiv> \<forall>i.(i\<in>Q_tail_indices s)\<longleftrightarrow>(i\<le>N \<and> ownB s i=Q \<and> i\<notin>ran_indices (fst(hd(q s))) (end(hd(q s))))" (*------------------------ Invariant ------------------------------------*) definition inv where "inv s \<equiv> basic_pointer_movement s \<and> mainInv s \<and> counter_q_rel s \<and> counter_bounds s \<and> Q_structure s \<and> data_index_bouded s \<and> (case_1 s \<or> case_2 s) \<and> Q_owns_bytes s " definition pre_W where "pre_W pcw s \<equiv> (case pcw of idleW \<Rightarrow> pre_acquire_inv s | A1 \<Rightarrow> pre_A1_inv s | A2 \<Rightarrow> pre_A2_inv s | A3 \<Rightarrow> pre_A3_inv s | A4 \<Rightarrow> pre_A4_inv s | A5 \<Rightarrow> pre_A5_inv s | A6 \<Rightarrow> pre_A6_inv s | A7 \<Rightarrow> pre_A7_inv s | A8 \<Rightarrow> pre_A8_inv s | Write \<Rightarrow> pre_write_inv s | OOM \<Rightarrow> pre_OOM_inv s | BTS \<Rightarrow> pre_BTS_inv s | Enqueue \<Rightarrow> pre_enqueue_inv s | FinishedW \<Rightarrow> pre_finished_inv s)" definition pre_R where "pre_R pcr s \<equiv> (case pcr of idleR \<Rightarrow> pre_dequeue_inv s | Read \<Rightarrow> pre_Read_inv s | Release \<Rightarrow> pre_Release_inv s)" lemmas inv_simps = inv_def cW_step_def cR_step_def init_def lemma Q_not_empty: "q s \<noteq> [] \<Longrightarrow> \<forall>x.(x\<in>set(q s))\<longrightarrow>snd(x)>0 \<Longrightarrow> Q_indices s\<noteq>{}" apply (simp add: Q_indices_def ran_indices_def) apply (rule_tac exI [where x ="{i. fst(hd(q s)) \<le> i \<and> i < end(hd(q s))}"]) apply safe defer apply(simp add:end_def) apply auto apply (metis add.commute le_refl less_add_same_cancel2 list.set_sel(1) prod.exhaust_sel) apply (rule_tac exI [where x ="fst(hd(q s))"]) apply (rule_tac exI [where x ="snd(hd(q s))"]) by simp lemma case_1_Q_struct: assumes "case_1 s" and "Q_structure s" and "Q_owns_bytes s" shows "\<forall>i.(i>0 \<and> i<length(q s))\<longrightarrow>fst(q s!i) = end(q s!(i-1))" apply (cases "q s = []") apply simp using assms apply (simp add:Q_lemmas Q_basic_lemmas case_1_def Q_owns_bytes_def Q_indices_def ran_indices_def) apply clarify apply(subgoal_tac "fst(q s!0) = b") prefer 2 apply (metis Zero_not_Suc diff_self_eq_0 hd_conv_nth le_neq_implies_less less_natE) apply(subgoal_tac "end(q s!(length(q s)-1)) = c") prefer 2 apply (metis Suc_diff_Suc Zero_not_Suc diff_0_eq_0 diff_self_eq_0 end_simp last_conv_nth le_neq_implies_less) apply(subgoal_tac "\<forall>a b aa. (a,b)\<in>set(q s) \<and> (\<exists>b.(aa, b)\<in>set(q s)) \<longrightarrow> a<aa\<longrightarrow>a+b\<le>aa") prefer 2 apply blast apply(subgoal_tac "\<forall>a b. (a,b)\<in>set(q s)\<longrightarrow>(\<exists>i.(i<length(q s) \<and> (q s!i) = (a,b)))") prefer 2 apply (metis in_set_conv_nth) apply(subgoal_tac "\<forall>i j.(i<length(q s)\<and>j<length(q s))\<longrightarrow>(\<exists>a b aa bb.((a,b)\<in>set(q s)\<and>(aa,bb)\<in>set(q s)))") prefer 2 apply (metis last_in_set surjective_pairing) apply(subgoal_tac "\<forall>i.(i<length(q s) \<and> i>0)\<longrightarrow>(fst(q s!i) = 0 \<or> fst(q s!i) = end(q s!(i-1)))") prefer 2 apply (metis (no_types, lifting) One_nat_def end_simp) apply(case_tac "ownB s 0 = Q") apply (metis (no_types, lifting) F.distinct(11) F.distinct(19) le_numeral_extra(3) length_greater_0_conv not_gr0) apply(subgoal_tac "ownB s 0\<noteq>Q") prefer 2 apply blast (*trying to use the fact that ownB s 0\<noteq>Q and Q_gap_structure to show that all Q entries start where the last left off, rather than any starting from 0*) apply(subgoal_tac "(\<exists>a b.((a,b)\<in>set(q s) \<and> a = 0))\<longrightarrow>ownB s 0=Q") prefer 2 apply (metis (no_types, lifting) add_gr_0 mem_Collect_eq nat_le_linear) apply(subgoal_tac "ownB s 0\<noteq>Q\<longrightarrow>(\<nexists>a b.((a,b)\<in>set(q s) \<and> a = 0))") prefer 2 apply meson apply(subgoal_tac "\<forall>a b.((a,b)\<in>set(q s))\<longrightarrow>a\<noteq>0") prefer 2 apply metis apply(subgoal_tac "\<forall>a b.((a,b)\<in>set(q s))\<longrightarrow>(\<exists>i.(i<length(q s) \<and> (a,b)=(q s!i)))") prefer 2 apply metis apply(subgoal_tac "\<forall>a b i.((a,b)\<in>set(q s)\<and>(q s!i) = (a, b))\<longrightarrow>a=fst(q s!i)") prefer 2 apply (metis fst_conv) apply(subgoal_tac "\<forall>i.(i<length(q s))\<longrightarrow>fst(q s!i)\<noteq>0") prefer 2 apply (metis nth_mem prod.collapse) apply(subgoal_tac "\<forall>i.(i<length(q s)\<and>i>0)\<longrightarrow>(fst(q s!i) =end(q s!(i-1)) \<or> fst(q s!i) =0)") prefer 2 apply (metis (no_types, hide_lams)) apply(subgoal_tac "(\<forall>i.(i<length(q s))\<longrightarrow>fst(q s!i)\<noteq>0) \<and> (\<forall>i.(i<length(q s)\<and>i>0)\<longrightarrow>(fst(q s!i) =end(q s!(i-1)) \<or> fst(q s!i) =0)) \<longrightarrow>(\<forall>i.(i<length(q s)\<and>i>0)\<longrightarrow>(fst(q s!i) =end(q s!(i-1))))") prefer 2 apply (metis (no_types, hide_lams)) by (metis (no_types, lifting)) lemma ran_indices_lem: "Q_structure s \<Longrightarrow> \<forall>i.(i<length(q s))\<longrightarrow> fst(q s!i) \<in> ran_indices (fst(q s ! i)) (fst(q s!i)+snd(q s!i))" apply (simp add: Q_lemmas Q_basic_lemmas ran_indices_def) by (metis bot_nat_0.not_eq_extremum length_0_conv length_pos_if_in_set nth_mem prod.exhaust_sel) lemma ran_indices_lem2: "q s \<noteq> [] \<Longrightarrow> Q_structure s \<Longrightarrow> case_1 s \<Longrightarrow> \<forall>i.(i\<ge>end(last(q s)) \<and> i\<le>N)\<longrightarrow>ownB s i\<noteq>Q" apply (simp add: Q_lemmas Q_basic_lemmas ran_indices_def case_1_def) by (metis F.distinct(19) F.distinct(21) F.distinct(23) F.distinct(3) diff_is_0_eq length_greater_0_conv less_nat_zero_code linorder_neqE_nat zero_less_diff) lemma ran_indices_lem3: "q s \<noteq> [] \<Longrightarrow> Q_structure s \<Longrightarrow> case_1 s \<Longrightarrow> end(last(q s)) \<le> N \<Longrightarrow> ownB s (end(last(q s))) \<noteq>Q" apply (simp add: Q_lemmas Q_basic_lemmas ran_indices_def case_1_def) by (metis F.distinct(19) F.distinct(23) F.distinct(3) diff_self_eq_0 eq_imp_le le_neq_implies_less le_zero_eq length_0_conv) lemma ran_indices_lem4: "q s \<noteq> [] \<Longrightarrow> Q_structure s \<Longrightarrow> case_1 s \<Longrightarrow> end(last(q s))\<le>N" by (simp add: Q_lemmas Q_basic_lemmas ran_indices_def case_1_def) lemma ran_indices_lem5: "q s\<noteq>[] \<Longrightarrow>Q_structure s \<Longrightarrow> case_1 s \<Longrightarrow> Q_owns_bytes s \<Longrightarrow> \<forall>i.(i<length(q s)) \<longrightarrow> fst(q s!i)\<in>Q_indices s" apply(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) by (metis (mono_tags, lifting) mem_Collect_eq nth_mem prod.collapse ran_indices_def ran_indices_lem) lemma case_1_Q_struct_inf: assumes "Q_structure s" and "case_1 s" and "Q_owns_bytes s" shows "\<forall>i<length (q s). fst (q s ! i) < end(q s!(length(q s)-1))" apply(case_tac "q s=[]") apply simp using assms apply(case_tac "length (q s) =1") apply(simp add:Q_lemmas Q_basic_lemmas ) apply (metis lessI nth_mem prod.collapse) apply safe[1] apply(subgoal_tac "\<forall>i.(i<N \<and> i\<ge>end(last(q s)))\<longrightarrow> ownB s i\<noteq>Q") prefer 2 apply(simp add:case_1_def) apply (metis assms(2) end_simp less_or_eq_imp_le ran_indices_lem2) apply(simp add:case_1_def) apply clarify apply(subgoal_tac "end(last(q s)) = c") prefer 2 apply (metis diff_self_eq_0 end_simp le_zero_eq nat_less_le) apply(subgoal_tac "\<forall>i.(i<length(q s))\<longrightarrow>ownB s (fst(q s!i)) = Q") prefer 2 using ran_indices_lem [where s = s] defer apply(subgoal_tac "ownB s c \<noteq>Q") prefer 2 apply (metis assms(2) ran_indices_lem3 ran_indices_lem4) apply clarify apply(subgoal_tac "\<forall>i.(ownB s i =Q \<and> i\<le>N)\<longrightarrow>i<end(last(q s))") prefer 2 apply (metis (no_types, lifting) assms(2) nat_le_linear nat_less_le ran_indices_lem2) apply(subgoal_tac "(\<forall>i.(i\<ge>end(last(q s)) \<and> i\<le>N)\<longrightarrow>ownB s i\<noteq>Q)\<longrightarrow>(\<forall>i.(ownB s i=Q \<and> i\<le>N)\<longrightarrow>i<end(last(q s)))") prefer 2 apply(unfold Q_owns_bytes_def Q_indices_def ran_indices_def)[1] apply blast apply(subgoal_tac "\<forall>i.(i<length(q s))\<longrightarrow>ownB s (fst(q s!i)) =Q") prefer 2 apply blast apply(subgoal_tac "\<forall>i.(ownB s i=Q \<and> i\<le>N)\<longrightarrow>i<end(last(q s))") prefer 2 apply blast apply(subgoal_tac "\<forall>i.(i<length(q s))\<longrightarrow>(\<exists>a b. (a,b)\<in>set(q s) \<and> a=fst(q s!i))") prefer 2 apply (metis nth_mem prod.exhaust_sel) apply(unfold Q_lemmas Q_basic_lemmas) apply(subgoal_tac "\<nexists>j.(j<length(q s) \<and> ownB s (fst(q s!j))\<noteq>Q)") prefer 2 apply metis apply(subgoal_tac "\<forall>i.(ownB s i = Q \<and> i\<le>N)\<longrightarrow>i<end(last(q s))") prefer 2 apply meson apply(subgoal_tac "\<forall>i.(i<length(q s))\<longrightarrow> fst(q s!i) \<in> {j. ownB s j = Q}") prefer 2 apply (metis (mono_tags, lifting) mem_Collect_eq) apply(subgoal_tac "\<forall>i.(i<length(q s)) \<longrightarrow> end(q s!i)\<le>N") prefer 2 apply (metis nth_mem) apply(subgoal_tac "\<forall>i.(i<length(q s))\<longrightarrow>snd(q s!i)>0") prefer 2 apply (metis nth_mem) apply(subgoal_tac "\<forall>i.(i<length(q s))\<longrightarrow>fst(q s!i)<end(q s!i)") prefer 2 apply (metis (no_types, lifting) end_simp less_add_same_cancel1) apply(subgoal_tac "\<forall>i.(i<length(q s))\<longrightarrow>fst(q s!i)<N") prefer 2 apply (metis (no_types, lifting) F.distinct(23) add_leD1 end_simp nat_less_le) apply(subgoal_tac "\<forall>i.(i<length(q s))\<longrightarrow> fst(q s!i) \<in> {j. j<N}") prefer 2 apply (metis mem_Collect_eq) apply(subgoal_tac "\<forall>i.(i<length(q s))\<longrightarrow>fst(q s!i) \<in> {j. ownB s j = Q \<and> j<N}") prefer 2 apply (metis (no_types, lifting) mem_Collect_eq) apply (metis (no_types, lifting) One_nat_def end_simp last_conv_nth less_imp_le_nat) apply clarify by (metis Q_owns_bytes_def assms(1) assms(2) ran_indices_lem5) (*******************************************************************) (**********************Supporting lemmas for LOCAL W transitions*********************************) lemma case_trans_A2_to_A3_1: shows "s'=(s\<lparr>ownT := W, pcW := A3\<rparr>) \<Longrightarrow> case_1 s \<Longrightarrow> (i\<le>N)\<longrightarrow>ownB s' i = ownB s i" by (simp add:case_1_def cW_step_def) lemma case_trans_A2_to_A3_2: shows "s'=(s\<lparr>ownT := W, pcW := A3\<rparr>) \<Longrightarrow> T s=H s\<Longrightarrow> case_1 s \<Longrightarrow> case_1 s'" apply (simp add:case_1_def cW_step_def) apply clarify by (smt (z3) diff_is_0_eq le_trans less_irrefl_nat zero_less_diff) lemma case_trans_A2_to_A4_1: shows "s'=(s\<lparr>pcW := A4\<rparr>) \<Longrightarrow> case_1 s \<Longrightarrow> (i\<le>N)\<longrightarrow>ownB s' i = ownB s i" by (simp add:case_1_def cW_step_def) lemma case_trans_A2_to_A4_2: shows "s'=(s\<lparr>pcW := A4\<rparr>) \<Longrightarrow> case_1 s \<Longrightarrow> case_1 s'" by (simp add:case_1_def cW_step_def) lemma case_trans_A2_to_A4_3: shows "s'=(s\<lparr>pcW := A4\<rparr>) \<Longrightarrow> case_2 s \<Longrightarrow> T s>H s \<Longrightarrow> case_2 s'" by (simp add:case_2_def cW_step_def) lemma case_trans_A2_to_A5_1: shows "s'=(s\<lparr>pcW := A5\<rparr>) \<Longrightarrow> case_1 s \<Longrightarrow> (i\<le>N)\<longrightarrow>ownB s' i = ownB s i" by (simp add:case_1_def cW_step_def) lemma case_trans_A2_to_A5_2: shows "s'=(s\<lparr>pcW := A5\<rparr>) \<Longrightarrow> case_1 s \<Longrightarrow> case_1 s'" by (simp add:case_1_def cW_step_def) lemma case_trans_A2_to_A5_3: shows "s'=(s\<lparr>pcW := A5\<rparr>) \<Longrightarrow> case_2 s \<Longrightarrow> T s\<le>H s \<Longrightarrow> case_2 s'" by (simp add:case_2_def cW_step_def) lemma case_trans_A2_to_A8_1: shows "s'=(s\<lparr>pcW := A8\<rparr>) \<Longrightarrow> case_1 s \<Longrightarrow> (i\<le>N)\<longrightarrow>ownB s' i = ownB s i" by (simp add:case_1_def cW_step_def) lemma case_trans_A2_to_A8_2: shows "s'=(s\<lparr>pcW := A8\<rparr>) \<Longrightarrow> case_1 s \<Longrightarrow> case_1 s'" by (simp add:case_1_def cW_step_def) lemma case_trans_A2_to_A8_3: shows "s'=(s\<lparr>pcW := A8\<rparr>) \<Longrightarrow> case_2 s \<Longrightarrow> T s\<le>H s \<Longrightarrow> case_2 s'" by (simp add:case_2_def cW_step_def) lemma case_trans_A2_to_A8_4: shows "s'=(s\<lparr>pcW := A8\<rparr>) \<Longrightarrow> case_2 s \<Longrightarrow> T s>H s \<Longrightarrow> case_2 s'" by (simp add:case_2_def cW_step_def) lemma case_trans_A3_1: shows "pre_A3_inv s \<Longrightarrow> case_2 s \<Longrightarrow> False" by (simp add:case_2_def pre_A3_inv_def) lemma case_trans_A3_2: shows "pre_A3_inv s \<Longrightarrow>con_assms s\<Longrightarrow>inv s\<Longrightarrow> case_1 s" apply (simp add:pre_A3_inv_def con_assms_def basic_pointer_movement_def inv_def) apply(subgoal_tac "H s=T s") prefer 2 apply simp apply clarify apply(subgoal_tac "\<not>case_2 s") prefer 2 apply (metis case_split_2 less_or_eq_imp_le) by blast lemma case_trans_A3_to_write_1: shows "pre_A3_inv s \<Longrightarrow>s'=(s\<lparr>ownB := \<lambda>i. if i < Data s (numEnqs s) then W else ownB s i, pcW := Write, offset := 0, H := Data s (numEnqs s), T := 0\<rparr>)\<Longrightarrow>inv s\<Longrightarrow> H s'\<ge>T s'" by (simp add:pre_A3_inv_def inv_def) lemma case_trans_A3_to_write_2: shows "pre_A3_inv s \<Longrightarrow>s'=(s\<lparr>ownB := \<lambda>i. if i < Data s (numEnqs s) then W else ownB s i, pcW := Write, offset := 0, H := Data s (numEnqs s), T := 0\<rparr>)\<Longrightarrow>inv s\<Longrightarrow> \<not>case_2 s'" by (simp add:pre_A3_inv_def inv_def case_2_def) lemma case_trans_A3_to_write_3: shows "pre_A3_inv s \<Longrightarrow>s'=(s\<lparr>ownB := \<lambda>i. if i < Data s (numEnqs s) then W else ownB s i, pcW := Write, offset := 0, H := Data s (numEnqs s), T := 0\<rparr>)\<Longrightarrow>inv s\<Longrightarrow> con_assms s\<Longrightarrow> (i\<ge>T s' \<and> i<H s')\<longrightarrow>ownB s' i=W" by (simp add:pre_A3_inv_def inv_def case_1_def) lemma case_trans_A3_to_write_4: shows "pre_A3_inv s \<Longrightarrow>s'=(s\<lparr>ownB := \<lambda>i. if i < Data s (numEnqs s) then W else ownB s i, pcW := Write, offset := 0, H := Data s (numEnqs s), T := 0\<rparr>)\<Longrightarrow>inv s\<Longrightarrow> con_assms s\<Longrightarrow> (i\<ge>H s'\<and> i<N)\<longrightarrow>ownB s' i=B" by (simp add:pre_A3_inv_def inv_def case_1_def) lemma case_trans_A3_to_write_7: shows "pre_A3_inv s \<Longrightarrow>s'=(s\<lparr>ownB := \<lambda>i. if i < Data s (numEnqs s) then W else ownB s i, pcW := Write, offset := 0, H := Data s (numEnqs s), T := 0\<rparr>)\<Longrightarrow>inv s\<Longrightarrow> con_assms s\<Longrightarrow> case_1 s'" apply (simp add:pre_A3_inv_def inv_def case_1_def) apply (rule_tac exI [where x ="0"]) apply (rule_tac exI [where x ="0"]) apply simp apply (subgoal_tac "Data s (numEnqs s)\<le>N") apply (metis case_split_2 le_refl) by blast lemma case_trans_A4_1: shows "pre_A4_inv s \<Longrightarrow> T s\<ge>tW s\<Longrightarrow> case_1 s \<Longrightarrow> False" apply (simp add:case_1_def pre_A4_inv_def) by (metis diff_is_0_eq le_trans less_nat_zero_code) lemma case_trans_A4_2: shows "pre_A4_inv s \<Longrightarrow> T s\<le>hW s\<Longrightarrow> case_2 s \<Longrightarrow> False" apply (simp add:case_2_def pre_A4_inv_def) by (metis le_antisym less_irrefl_nat less_or_eq_imp_le) lemma case_trans_A4_3: shows "pre_A4_inv s \<Longrightarrow> T s>hW s \<and> T s<tW s \<Longrightarrow> False" by (simp add:case_2_def pre_A4_inv_def) lemma case_trans_A4_4: shows "pre_A4_inv s \<Longrightarrow> inv s\<Longrightarrow> T s\<ge>tW s\<Longrightarrow> case_2 s" apply (simp add: pre_A4_inv_def inv_def) using case_trans_A4_1 [where s=s] by (metis case_split_4 less_eqE trans_less_add1) lemma case_trans_A4_5: shows "pre_A4_inv s \<Longrightarrow> inv s\<Longrightarrow> T s\<le>hW s\<Longrightarrow> case_1 s" apply (simp add: pre_A4_inv_def inv_def) using case_trans_A4_2 [where s=s] by (metis RingBuffer_BD_latest_2.case_split) lemma case_trans_A4_to_write_1: shows "pre_A4_inv s \<Longrightarrow> T s\<ge>tW s \<Longrightarrow> s'=(s\<lparr>ownB := \<lambda>i. if hW s \<le> i \<and> i < hW s + Data s (numEnqs s) then W else ownB s i, pcW := Write, offset := hW s, H := hW s + Data s (numEnqs s)\<rparr>) \<Longrightarrow> inv s \<Longrightarrow> (i<offset s')\<longrightarrow>ownB s i=ownB s' i" by (simp add:case_2_def pre_A4_inv_def inv_def) lemma case_trans_A4_to_write_2: shows "pre_A4_inv s \<Longrightarrow> T s\<ge>tW s \<Longrightarrow> s'=(s\<lparr>ownB := \<lambda>i. if hW s \<le> i \<and> i < hW s + Data s (numEnqs s) then W else ownB s i, pcW := Write, offset := hW s, H := hW s + Data s (numEnqs s)\<rparr>) \<Longrightarrow> inv s \<Longrightarrow> (i\<ge>H s')\<longrightarrow>ownB s i=ownB s' i" by (simp add:case_2_def pre_A4_inv_def inv_def) lemma case_trans_A4_to_write_3: shows "pre_A4_inv s \<Longrightarrow> T s\<ge>tW s \<Longrightarrow> s'=(s\<lparr>ownB := \<lambda>i. if hW s \<le> i \<and> i < hW s + Data s (numEnqs s) then W else ownB s i, pcW := Write, offset := hW s, H := hW s + Data s (numEnqs s)\<rparr>) \<Longrightarrow> inv s \<Longrightarrow> (hW s \<le>i \<and> i<H s')\<longrightarrow>W=ownB s' i" by (simp add:case_2_def pre_A4_inv_def inv_def) lemma case_trans_A4_to_write_4: shows "pre_A4_inv s \<Longrightarrow> T s\<ge>tW s \<Longrightarrow> s'=(s\<lparr>ownB := \<lambda>i. if hW s \<le> i \<and> i < hW s + Data s (numEnqs s) then W else ownB s i, pcW := Write, offset := hW s, H := hW s + Data s (numEnqs s)\<rparr>) \<Longrightarrow> inv s \<Longrightarrow> T s'=T s" by (simp add:case_2_def pre_A4_inv_def inv_def) lemma case_trans_A4_to_write_5: shows "pre_A4_inv s \<Longrightarrow> T s\<ge>tW s \<Longrightarrow> s'=(s\<lparr>ownB := \<lambda>i. if hW s \<le> i \<and> i < hW s + Data s (numEnqs s) then W else ownB s i, pcW := Write, offset := hW s, H := hW s + Data s (numEnqs s)\<rparr>) \<Longrightarrow> inv s \<Longrightarrow> con_assms s \<Longrightarrow> T s'> H s' \<and> H s<H s' \<and> T s=T s' \<and> offset s'=hW s \<and> Data s (numEnqs s) = Data s' (numEnqs s') \<and> H s'-H s=Data s (numEnqs s) \<and> tempR s=tempR s' \<and> q s=q s' \<and> ownT s=ownT s'" apply (simp add:case_2_def pre_A4_inv_def inv_def) by (simp add: le_Suc_ex less_diff_conv) lemma case_trans_A4_to_write_6: shows "pre_A4_inv s \<Longrightarrow> T s\<ge>tW s \<Longrightarrow> s'=(s\<lparr>ownB := \<lambda>i. if hW s \<le> i \<and> i < hW s + Data s (numEnqs s) then W else ownB s i, pcW := Write, offset := hW s, H := hW s + Data s (numEnqs s)\<rparr>) \<Longrightarrow>con_assms s \<Longrightarrow> inv s \<Longrightarrow> case_2 s" using case_trans_A4_4 [where s=s] by blast lemma case_trans_A4_to_write_7: shows "pre_A4_inv s \<Longrightarrow> T s\<ge>tW s \<Longrightarrow> s'=(s\<lparr>ownB := \<lambda>i. if hW s \<le> i \<and> i < hW s + Data s (numEnqs s) then W else ownB s i, pcW := Write, offset := hW s, H := hW s + Data s (numEnqs s)\<rparr>) \<Longrightarrow>con_assms s \<Longrightarrow> inv s \<Longrightarrow> case_2 s'" apply(subgoal_tac "H s'<T s'") prefer 2 using case_trans_A4_to_write_5 [where s=s and s'=s'] apply blast apply(subgoal_tac "H s<H s'") prefer 2 using case_trans_A4_to_write_5 [where s=s and s'=s'] apply blast apply(subgoal_tac "T s=T s'") prefer 2 using case_trans_A4_to_write_5 [where s=s and s'=s'] apply blast apply(subgoal_tac "q s=q s'") prefer 2 using case_trans_A4_to_write_5 [where s=s and s'=s'] apply blast apply(subgoal_tac "ownT s=ownT s'") prefer 2 using case_trans_A4_to_write_5 [where s=s and s'=s'] apply blast apply(subgoal_tac "Data s (numEnqs s) = Data s' (numEnqs s')") prefer 2 using case_trans_A4_to_write_5 [where s=s and s'=s'] apply blast apply(subgoal_tac "H s'-H s=Data s (numEnqs s)") prefer 2 using case_trans_A4_to_write_5 [where s=s and s'=s'] apply blast apply(subgoal_tac "\<forall>i.(i<offset s')\<longrightarrow>ownB s i=ownB s' i") prefer 2 using case_trans_A4_to_write_1 [where s=s and s'=s'] apply blast apply(subgoal_tac "\<forall>i.(hW s \<le>i \<and> i<H s')\<longrightarrow>W=ownB s' i") prefer 2 using case_trans_A4_to_write_3 [where s=s and s'=s'] apply blast apply(subgoal_tac "\<forall>i.(i\<ge>H s')\<longrightarrow>ownB s i=ownB s' i") prefer 2 using case_trans_A4_to_write_2 [where s=s and s'=s'] apply blast apply(subgoal_tac "offset s'=hW s") prefer 2 using case_trans_A4_to_write_5 [where s=s and s'=s'] apply blast apply(subgoal_tac "tempR s = tempR s'") prefer 2 using case_trans_A4_to_write_5 [where s=s and s'=s'] apply blast apply(unfold inv_def)[1] apply(subgoal_tac "case_2 s") prefer 2 using case_trans_A4_to_write_6 [where s=s and s'=s'] using RingBuffer_BD_latest_2.inv_def apply blast apply(subgoal_tac "\<not>case_1 s") prefer 2 using case_trans_A4_1 apply blast apply(unfold pre_A4_inv_def grd1_def grd2_def basic_pointer_movement_def)[1] apply(clarify) apply(thin_tac "case_2 s") apply(thin_tac "\<not>case_1 s") apply(thin_tac "mainInv s") apply(unfold case_2_def)[1] (*apply instance*) apply clarify apply(rule_tac ?x = "a" in exI) apply(rule_tac ?x = "b" in exI) apply(rule_tac exI [where x ="H s'"]) apply(rule_tac exI [where x ="T s'"]) apply(rule_tac ?x = "e" in exI) apply(rule_tac ?x = "f" in exI) apply (intro conjI impI) apply blast apply meson apply (metis le_trans less_imp_le_nat) apply meson apply metis apply blast apply meson apply clarify apply(subgoal_tac "i<a\<longrightarrow>ownB s i=R") prefer 2 apply (metis zero_le) apply(subgoal_tac "hW s = b") prefer 2 apply (metis F.distinct(17) F.distinct(23) nat_le_linear nat_less_le zero_le) apply(subgoal_tac "(i<offset s')\<longrightarrow>ownB s i=ownB s' i") prefer 2 using case_trans_A4_to_write_1 [where s=s and s'=s'] apply metis apply (metis le_trans nat_less_le) apply(subgoal_tac "i\<ge>a \<and> i<b\<longrightarrow>ownB s i=Q") prefer 2 apply (metis zero_le) apply(subgoal_tac "(i<offset s')\<longrightarrow>ownB s i=ownB s' i") prefer 2 using case_trans_A4_to_write_1 [where s=s and s'=s'] apply metis apply (metis le_trans nat_less_le) apply (metis le_eq_less_or_eq le_trans) apply(subgoal_tac "(i\<ge>H s')\<longrightarrow>ownB s i=ownB s' i") prefer 2 using case_trans_A4_to_write_1 [where s=s and s'=s'] apply metis apply (metis le_trans less_or_eq_imp_le) apply(subgoal_tac "(i\<ge>H s')\<longrightarrow>ownB s i=ownB s' i") prefer 2 using case_trans_A4_to_write_1 [where s=s and s'=s'] apply metis apply (metis le_trans less_or_eq_imp_le) apply(subgoal_tac "(i\<ge>H s')\<longrightarrow>ownB s i=ownB s' i") prefer 2 using case_trans_A4_to_write_1 [where s=s and s'=s'] apply metis apply (metis le_trans less_or_eq_imp_le) apply(subgoal_tac "(i\<ge>H s')\<longrightarrow>ownB s i=ownB s' i") prefer 2 using case_trans_A4_to_write_1 [where s=s and s'=s'] apply metis apply (metis le_trans less_or_eq_imp_le) apply(subgoal_tac "(i\<ge>H s')\<longrightarrow>ownB s i=ownB s' i") prefer 2 using case_trans_A4_to_write_1 [where s=s and s'=s'] apply metis apply (metis le_trans less_or_eq_imp_le) apply meson apply metis apply metis apply (metis gr_zeroI less_nat_zero_code) apply meson apply force apply (metis F.distinct(17) F.distinct(23) less_eq_nat.simps(1) nat_le_linear nat_less_le) apply(subgoal_tac "b=H s") prefer 2 apply (metis F.distinct(17) F.distinct(23) less_eq_nat.simps(1) nat_le_linear nat_less_le) apply(subgoal_tac "H s'-H s=Data s (numEnqs s)") prefer 2 apply meson apply metis apply metis apply metis apply metis apply metis apply metis apply metis apply metis apply metis apply metis apply metis apply metis apply metis by metis lemma case_trans_A4_to_write_8: shows "pre_A4_inv s \<Longrightarrow> T s\<le>H s \<Longrightarrow> s'=(s\<lparr>ownB := \<lambda>i. if hW s \<le> i \<and> i < hW s + Data s (numEnqs s) then W else ownB s i, pcW := Write, offset := hW s, H := hW s + Data s (numEnqs s)\<rparr>) \<Longrightarrow>con_assms s \<Longrightarrow> inv s \<Longrightarrow> case_1 s" using case_trans_A4_5 [where s=s] apply (simp add:case_1_def) by (simp add: pre_A4_inv_def) lemma case_trans_A4_to_write_9: shows "pre_A4_inv s \<Longrightarrow> T s\<le>H s \<Longrightarrow> s'=(s\<lparr>ownB := \<lambda>i. if hW s \<le> i \<and> i < hW s + Data s (numEnqs s) then W else ownB s i, pcW := Write, offset := hW s, H := hW s + Data s (numEnqs s)\<rparr>) \<Longrightarrow>con_assms s \<Longrightarrow> inv s \<Longrightarrow> case_1 s'" apply(simp add:inv_def) using case_trans_A4_to_write_8 [where s=s] apply (meson case_split_2) apply(simp add:pre_A4_inv_def) apply(simp add:case_1_def) apply(intro conjI impI) prefer 2 apply clarify apply(rule_tac ?x = "T s" in exI) apply(rule_tac ?x = b in exI) apply(intro conjI impI) prefer 2 apply(rule_tac ?x = "hW s" in exI) apply(intro conjI impI) apply(linarith) apply(linarith) apply clarify apply(intro conjI impI) apply clarify apply linarith apply metis apply (metis le_neq_implies_less le_trans less_imp_le_nat) apply (metis le_eq_less_or_eq) apply blast apply (metis add_leE) apply blast apply blast apply blast apply (metis add_diff_cancel_left') apply meson apply meson apply (metis le_refl nat_less_le) apply (metis nat_less_le) apply (metis le_neq_implies_less) apply (metis le_refl nat_less_le) apply meson apply (metis nat_less_le) apply (metis le_antisym) apply blast by (metis (no_types, lifting) add.commute add_lessD1 less_diff_conv less_eqE less_imp_add_positive not_add_less1) lemma case_trans_A5_1: shows "pre_A5_inv s \<Longrightarrow> inv s\<Longrightarrow> case_1 s" apply (simp add: pre_A5_inv_def inv_def) by (metis RingBuffer_BD_latest_2.case_split) lemma case_trans_A5_2: shows "pre_A5_inv s \<Longrightarrow> inv s\<Longrightarrow> \<not>case_2 s" apply (simp add: pre_A5_inv_def inv_def) by (metis case_split_2) lemma case_trans_A5_to_A6_1: shows "pre_A5_inv s \<Longrightarrow> s'=(s\<lparr>pcW := A6\<rparr>) \<Longrightarrow>con_assms s \<Longrightarrow> inv s \<Longrightarrow> i\<le>N\<longrightarrow>ownB s i=ownB s' i" by(simp add:case_1_def pre_A5_inv_def inv_def) lemma case_trans_A5_to_A6_2: shows "pre_A5_inv s \<Longrightarrow> s'=(s\<lparr>pcW := A6\<rparr>) \<Longrightarrow>con_assms s \<Longrightarrow> inv s \<Longrightarrow> case_1 s' = case_1 s" by(simp add:case_1_def) lemma case_trans_A5_to_A6_3: shows "pre_A5_inv s \<Longrightarrow> s'=(s\<lparr>pcW := A6\<rparr>) \<Longrightarrow>con_assms s \<Longrightarrow> inv s \<Longrightarrow> case_1 s'" using case_trans_A5_to_A6_2 [where s=s and s'=s'] using case_trans_A5_1 by blast lemma case_trans_A5_to_A6_4: shows "pre_A5_inv s \<Longrightarrow> s'=(s\<lparr>pcW := A7\<rparr>) \<Longrightarrow>con_assms s \<Longrightarrow> inv s \<Longrightarrow> i\<le>N\<longrightarrow>ownB s i=ownB s' i" by(simp add:case_1_def pre_A5_inv_def inv_def) lemma case_trans_A5_to_A6_5: shows "pre_A5_inv s \<Longrightarrow> s'=(s\<lparr>pcW := A7\<rparr>) \<Longrightarrow>con_assms s \<Longrightarrow> inv s \<Longrightarrow> case_1 s' = case_1 s" by(simp add:case_1_def) lemma case_trans_A5_to_A6_6: shows "pre_A5_inv s \<Longrightarrow> s'=(s\<lparr>pcW := A7\<rparr>) \<Longrightarrow>con_assms s \<Longrightarrow> inv s \<Longrightarrow> case_1 s'" using case_trans_A5_to_A6_5 [where s=s and s'=s'] using case_trans_A5_1 by blast lemma case_trans_A5_to_A6_7: shows "pre_A5_inv s \<Longrightarrow> s'=(s\<lparr>pcW := A8\<rparr>) \<Longrightarrow>con_assms s \<Longrightarrow> inv s \<Longrightarrow> i\<le>N\<longrightarrow>ownB s i=ownB s' i" by(simp add:case_1_def pre_A5_inv_def inv_def) lemma case_trans_A5_to_A6_8: shows "pre_A5_inv s \<Longrightarrow> s'=(s\<lparr>pcW := A8\<rparr>) \<Longrightarrow>con_assms s \<Longrightarrow> inv s \<Longrightarrow> case_1 s' = case_1 s" by(simp add:case_1_def) lemma case_trans_A5_to_A6_9: shows "pre_A5_inv s \<Longrightarrow> s'=(s\<lparr>pcW := A8\<rparr>) \<Longrightarrow>con_assms s \<Longrightarrow> inv s \<Longrightarrow> case_1 s'" using case_trans_A5_to_A6_7 [where s=s and s'=s'] by (metis case_trans_A2_to_A8_2 case_trans_A5_1) lemma case_trans_A6_1: shows "pre_A6_inv s \<Longrightarrow> inv s\<Longrightarrow> case_1 s" apply (simp add: pre_A6_inv_def inv_def) by (metis RingBuffer_BD_latest_2.case_split) lemma case_trans_A6_2: shows "pre_A6_inv s \<Longrightarrow> inv s\<Longrightarrow> case_2 s \<Longrightarrow> False" apply (simp add: pre_A6_inv_def inv_def) by (metis case_split_2) lemma case_trans_A6_to_write_1: shows "pre_A6_inv s \<Longrightarrow> s' = s \<lparr>ownB := \<lambda>i. if hW s \<le> i \<and> i < hW s + Data s (numEnqs s) then W else ownB s i, pcW := Write, offset := hW s, H := hW s + Data s (numEnqs s)\<rparr>\<Longrightarrow>inv s\<Longrightarrow> H s'\<ge>T s'" by (simp add:pre_A6_inv_def inv_def) lemma case_trans_A6_to_write_2: shows "pre_A6_inv s \<Longrightarrow> s' = s \<lparr>ownB := \<lambda>i. if hW s \<le> i \<and> i < hW s + Data s (numEnqs s) then W else ownB s i, pcW := Write, offset := hW s, H := hW s + Data s (numEnqs s)\<rparr>\<Longrightarrow>inv s\<Longrightarrow>con_assms s\<Longrightarrow> \<not>case_2 s'" by (simp add:pre_A6_inv_def inv_def case_2_def) lemma case_trans_A6_to_write_3: shows "pre_A6_inv s \<Longrightarrow> s' = s \<lparr>ownB := \<lambda>i. if hW s \<le> i \<and> i < hW s + Data s (numEnqs s) then W else ownB s i, pcW := Write, offset := hW s, H := hW s + Data s (numEnqs s)\<rparr>\<Longrightarrow>inv s\<Longrightarrow> con_assms s\<Longrightarrow> (i\<ge>hW s' \<and> i<H s')\<longrightarrow>ownB s' i=W" by (simp add:pre_A6_inv_def inv_def case_1_def) lemma case_trans_A6_to_write_4: shows "pre_A6_inv s \<Longrightarrow> s' = s \<lparr>ownB := \<lambda>i. if hW s \<le> i \<and> i < hW s + Data s (numEnqs s) then W else ownB s i, pcW := Write, offset := hW s, H := hW s + Data s (numEnqs s)\<rparr>\<Longrightarrow>inv s\<Longrightarrow> con_assms s\<Longrightarrow> (i\<ge>H s'\<and> i<N)\<longrightarrow>ownB s' i=B" by (simp add:pre_A6_inv_def inv_def case_1_def) lemma case_trans_A6_to_write_7: shows "pre_A6_inv s \<Longrightarrow> s' = s \<lparr>ownB := \<lambda>i. if hW s \<le> i \<and> i < hW s + Data s (numEnqs s) then W else ownB s i, pcW := Write, offset := hW s, H := hW s + Data s (numEnqs s)\<rparr>\<Longrightarrow>inv s\<Longrightarrow> con_assms s\<Longrightarrow> case_1 s'" apply(subgoal_tac "\<not>case_2 s") prefer 2 using case_trans_A6_to_write_2 [where s=s and s'=s'] using case_trans_A6_2 apply blast apply (simp add:pre_A6_inv_def inv_def case_1_def) apply(intro conjI impI) apply (metis (no_types, lifting) add_le_cancel_left le_add_diff_inverse le_antisym less_imp_le_nat nat_neq_iff) apply clarify apply (rule_tac exI [where x ="T s"]) apply(rule_tac ?x = "b" in exI) apply (intro conjI impI) apply blast apply(rule_tac ?x = "c" in exI) apply (intro conjI impI) apply linarith apply linarith apply (metis le_trans nat_less_le) apply (metis le_trans nat_less_le) apply (metis le_trans nat_less_le) apply (metis F.distinct(17) F.distinct(23) le_refl nat_less_le nat_neq_iff) apply (metis) apply (metis le_trans nat_less_le) apply (metis le_neq_implies_less le_refl le_trans) apply (metis Nat.add_diff_assoc2 diff_self_eq_0 le_refl le_trans nat_less_le plus_nat.add_0) apply meson apply meson apply meson apply meson apply meson apply meson apply meson apply meson by meson lemma case_trans_A7_1: shows "pre_A7_inv s \<Longrightarrow> inv s\<Longrightarrow> case_1 s" apply (simp add: pre_A7_inv_def inv_def) by (metis RingBuffer_BD_latest_2.case_split) lemma case_trans_A7_2: shows "pre_A7_inv s \<Longrightarrow> inv s\<Longrightarrow> case_2 s \<Longrightarrow> False" apply (simp add: pre_A7_inv_def inv_def) by (metis case_split_2) lemma case_trans_A7_to_write_1: shows "pre_A7_inv s \<Longrightarrow> s' = (s\<lparr>ownB := \<lambda>i. if hW s \<le> i \<and> i < N then D else ownB (s\<lparr>ownB := \<lambda>i. if i < Data s (numEnqs s) then W else ownB s i\<rparr>) i, pcW := Write, offset := 0, H := Data s (numEnqs s)\<rparr>)\<Longrightarrow>inv s\<Longrightarrow> H s'<T s'" by (simp add:pre_A7_inv_def inv_def) lemma case_trans_A7_to_write_2: shows "pre_A7_inv s \<Longrightarrow> s' = (s\<lparr>ownB := \<lambda>i. if hW s \<le> i \<and> i < N then D else ownB (s\<lparr>ownB := \<lambda>i. if i < Data s (numEnqs s) then W else ownB s i\<rparr>) i, pcW := Write, offset := 0, H := Data s (numEnqs s)\<rparr>)\<Longrightarrow>inv s\<Longrightarrow>con_assms s\<Longrightarrow> \<not>case_1 s'" by (simp add:pre_A7_inv_def inv_def case_1_def) lemma case_trans_A7_to_write_3: shows "pre_A7_inv s \<Longrightarrow> s' = (s\<lparr>ownB := \<lambda>i. if hW s \<le> i \<and> i < N then D else ownB (s\<lparr>ownB := \<lambda>i. if i < Data s (numEnqs s) then W else ownB s i\<rparr>) i, pcW := Write, offset := 0, H := Data s (numEnqs s)\<rparr>)\<Longrightarrow>inv s\<Longrightarrow> con_assms s\<Longrightarrow> (i\<ge>0 \<and> i<H s')\<longrightarrow>ownB s' i=W" by (simp add:pre_A7_inv_def inv_def case_2_def) lemma case_trans_A7_to_write_4: shows "pre_A7_inv s \<Longrightarrow> s' = (s\<lparr>ownB := \<lambda>i. if hW s \<le> i \<and> i < N then D else ownB (s\<lparr>ownB := \<lambda>i. if i < Data s (numEnqs s) then W else ownB s i\<rparr>) i, pcW := Write, offset := 0, H := Data s (numEnqs s)\<rparr>)\<Longrightarrow>inv s\<Longrightarrow> con_assms s\<Longrightarrow> (i\<ge>hW s\<and> i<N)\<longrightarrow>ownB s' i=D" by (simp add:pre_A7_inv_def inv_def case_2_def) lemma case_trans_A7_to_write_7: shows "pre_A7_inv s \<Longrightarrow> s' = (s\<lparr>ownB := \<lambda>i. if hW s \<le> i \<and> i < N then D else ownB (s\<lparr>ownB := \<lambda>i. if i < Data s (numEnqs s) then W else ownB s i\<rparr>) i, pcW := Write, offset := 0, H := Data s (numEnqs s)\<rparr>)\<Longrightarrow>inv s\<Longrightarrow> con_assms s\<Longrightarrow> case_2 s'" apply(subgoal_tac "\<not>case_2 s") prefer 2 using case_trans_A7_to_write_2 [where s=s and s'=s'] using case_trans_A7_2 apply blast apply (simp add:pre_A7_inv_def inv_def) apply(thin_tac "\<not>case_2 s") apply(simp add:case_1_def case_2_def) apply clarify apply(rule_tac ?x = "0" in exI) apply(rule_tac ?x = "0" in exI) apply (intro conjI impI) apply blast apply(rule_tac ?x = "Data s (numEnqs s)" in exI) apply (intro conjI impI) apply linarith apply(rule_tac ?x = "T s" in exI) apply (intro conjI impI) apply linarith apply(rule_tac ?x = "b" in exI) apply (intro conjI impI) apply linarith apply(rule_tac ?x = "c" in exI) apply (intro conjI impI) apply linarith apply (metis le_trans) apply blast apply blast apply blast apply (metis le_antisym le_trans nat_less_le) apply (metis le_antisym le_trans nat_less_le) apply (metis le_antisym le_trans nat_less_le) apply (metis le_trans nat_le_linear nat_less_le) apply blast apply fastforce apply blast apply blast apply metis apply blast apply blast apply blast apply (metis diff_zero) apply force apply fastforce apply meson apply meson apply (metis add_implies_diff) apply meson apply force apply meson apply force apply fastforce apply meson apply meson by (metis le_neq_implies_less) lemma case_trans_Enqueue_to_idleW_case_1_1: shows "pre_enqueue_inv s \<Longrightarrow> inv s\<Longrightarrow> s'= (s\<lparr>ownT := Q, numEnqs := Suc (numEnqs s), ownB := \<lambda>i. if ownB s i = W \<and> i \<le> N then Q else ownB (s\<lparr>ownT := Q, numEnqs := Suc (numEnqs s)\<rparr>) i, pcW := idleW, q := [(offset s, Data s (numEnqs s))]\<rparr>) \<Longrightarrow>case_1 s \<Longrightarrow> con_assms s \<Longrightarrow> H s\<ge>T s" apply (simp add: pre_enqueue_inv_def inv_def case_1_def) by (metis le_trans) lemma case_trans_Enqueue_to_idleW_case_1_2: shows "pre_enqueue_inv s \<Longrightarrow> inv s\<Longrightarrow> s'= (s\<lparr>ownT := Q, numEnqs := Suc (numEnqs s), ownB := \<lambda>i. if ownB s i = W \<and> i \<le> N then Q else ownB (s\<lparr>ownT := Q, numEnqs := Suc (numEnqs s)\<rparr>) i, pcW := idleW, q := [(offset s, Data s (numEnqs s))]\<rparr>) \<Longrightarrow>case_1 s \<Longrightarrow> con_assms s \<Longrightarrow> H s'\<ge>T s'" apply (simp add: pre_enqueue_inv_def inv_def case_1_def) by (metis le_trans) lemma case_trans_Enqueue_to_idleW_case_1_3: shows "pre_enqueue_inv s \<Longrightarrow> inv s\<Longrightarrow> s'= (s\<lparr>ownT := Q, numEnqs := Suc (numEnqs s), ownB := \<lambda>i. if ownB s i = W \<and> i \<le> N then Q else ownB (s\<lparr>ownT := Q, numEnqs := Suc (numEnqs s)\<rparr>) i, pcW := idleW, q := [(offset s, Data s (numEnqs s))]\<rparr>) \<Longrightarrow>case_1 s \<Longrightarrow> con_assms s \<Longrightarrow> i<offset s\<Longrightarrow>ownB s i=ownB s' i" by (simp add: pre_enqueue_inv_def inv_def case_1_def) lemma case_trans_Enqueue_to_idleW_case_1_4: shows "pre_enqueue_inv s \<Longrightarrow> inv s\<Longrightarrow> s'= (s\<lparr>ownT := Q, numEnqs := Suc (numEnqs s), ownB := \<lambda>i. if ownB s i = W \<and> i \<le> N then Q else ownB (s\<lparr>ownT := Q, numEnqs := Suc (numEnqs s)\<rparr>) i, pcW := idleW, q := [(offset s, Data s (numEnqs s))]\<rparr>) \<Longrightarrow>case_1 s \<Longrightarrow> con_assms s \<Longrightarrow> i\<ge>H s'\<and> i\<le>N\<Longrightarrow>ownB s i=ownB s' i" apply (simp add: pre_enqueue_inv_def inv_def case_1_def) by (metis F.distinct(5) F.distinct(9) nat_less_le) lemma case_trans_Enqueue_to_idleW_case_1_5: shows "pre_enqueue_inv s \<Longrightarrow> inv s\<Longrightarrow> s'= (s\<lparr>ownT := Q, numEnqs := Suc (numEnqs s), ownB := \<lambda>i. if ownB s i = W \<and> i \<le> N then Q else ownB (s\<lparr>ownT := Q, numEnqs := Suc (numEnqs s)\<rparr>) i, pcW := idleW, q := [(offset s, Data s (numEnqs s))]\<rparr>) \<Longrightarrow>case_1 s \<Longrightarrow> con_assms s \<Longrightarrow> offset s \<le> i \<and> i < offset s + Data s (numEnqs s) \<Longrightarrow>Q=ownB s' i" by (simp add: pre_enqueue_inv_def inv_def case_1_def tempW_def) lemma case_trans_Enqueue_to_idleW_case_1_6: shows "pre_enqueue_inv s \<Longrightarrow> inv s\<Longrightarrow> q s = [] \<Longrightarrow> s'= (s\<lparr>ownT := Q, numEnqs := Suc (numEnqs s), ownB := \<lambda>i. if ownB s i = W \<and> i \<le> N then Q else ownB (s\<lparr>ownT := Q, numEnqs := Suc (numEnqs s)\<rparr>) i, pcW := idleW, q := [(offset s, Data s (numEnqs s))]\<rparr>) \<Longrightarrow>case_1 s \<Longrightarrow> con_assms s \<Longrightarrow>case_1 s'" apply(simp add:inv_def) apply(subgoal_tac "\<not>case_2 s ") prefer 2 apply (meson case_split_5) apply(thin_tac "\<not> case_2 s") apply (simp add: pre_enqueue_inv_def inv_def case_1_def tempW_def) apply clarify apply simp apply(rule_tac ?x = "T s" in exI) apply(rule_tac ?x = "b" in exI) apply (intro conjI impI) apply meson apply(rule_tac ?x = "offset s + Data s (numEnqs s)" in exI) apply (intro conjI impI) apply (metis F.distinct(5)) apply (metis (mono_tags, hide_lams) le_trans less_or_eq_imp_le linorder_neqE_nat) apply (metis F.distinct(5)) apply (metis F.distinct(1)) apply (metis le_trans less_or_eq_imp_le) apply (metis Suc_leI not_less_eq_eq) apply blast apply (metis less_irrefl_nat) apply (metis less_irrefl_nat) apply meson apply meson apply(simp add:tempW_lemmas tempW_basic_lemmas) apply (metis F.distinct(1) F.distinct(5) Suc_pred bot_nat_0.not_eq_extremum diff_0_eq_0 diff_Suc_Suc diff_diff_cancel diff_diff_left diff_is_0_eq diff_is_0_eq' diff_self_eq_0 le_refl less_nat_zero_code linorder_neqE_nat nat_add_left_cancel_less nat_le_linear not0_implies_Suc old.nat.inject zero_less_Suc zero_less_diff) apply metis by metis lemma case_trans_Write_to_Enqueue_case_1: shows "pre_write_inv s \<Longrightarrow> inv s\<Longrightarrow> s'=s\<lparr>numWrites := Suc (numWrites s), pcW := Enqueue, ownD := \<lambda>i. if i = numWrites s then B else ownD (s\<lparr>numWrites := Suc (numWrites s), pcW := Enqueue\<rparr>) i, data_index := \<lambda>x. if (offset s, Data s (numEnqs s)) = x then numEnqs s else data_index (s\<lparr>numWrites := Suc (numWrites s), pcW := Enqueue, ownD := \<lambda>i. if i = numWrites s then B else ownD (s\<lparr>numWrites := Suc (numWrites s), pcW := Enqueue\<rparr>) i\<rparr>) x\<rparr> \<Longrightarrow>case_1 s \<Longrightarrow> con_assms s \<Longrightarrow>case_1 s'" by (simp add:pre_write_inv_def case_1_def) lemma case_trans_Write_to_Enqueue_case_2: shows "pre_write_inv s \<Longrightarrow> inv s\<Longrightarrow> s'=s\<lparr>numWrites := Suc (numWrites s), pcW := Enqueue, ownD := \<lambda>i. if i = numWrites s then B else ownD (s\<lparr>numWrites := Suc (numWrites s), pcW := Enqueue\<rparr>) i, data_index := \<lambda>x. if (offset s, Data s (numEnqs s)) = x then numEnqs s else data_index (s\<lparr>numWrites := Suc (numWrites s), pcW := Enqueue, ownD := \<lambda>i. if i = numWrites s then B else ownD (s\<lparr>numWrites := Suc (numWrites s), pcW := Enqueue\<rparr>) i\<rparr>) x\<rparr> \<Longrightarrow>case_2 s \<Longrightarrow> con_assms s \<Longrightarrow>case_2 s'" by (simp add:pre_write_inv_def case_2_def) lemma case_trans_Write_to_Enqueue_case_3: shows "pre_write_inv s \<Longrightarrow> inv s\<Longrightarrow> s'=s\<lparr>numWrites := Suc (numWrites s), pcW := Enqueue, ownD := \<lambda>i. if i = numWrites s then B else ownD (s\<lparr>numWrites := Suc (numWrites s), pcW := Enqueue\<rparr>) i, data_index := \<lambda>x. if (offset s, Data s (numEnqs s)) = x then numEnqs s else data_index (s\<lparr>numWrites := Suc (numWrites s), pcW := Enqueue, ownD := \<lambda>i. if i = numWrites s then B else ownD (s\<lparr>numWrites := Suc (numWrites s), pcW := Enqueue\<rparr>) i\<rparr>) x\<rparr> \<Longrightarrow>case_1 s \<or> case_2 s \<Longrightarrow> con_assms s \<Longrightarrow>case_1 s' \<or> case_2 s'" by (simp add:pre_write_inv_def case_1_def case_2_def) lemma case_trans_Write_to_Enqueue_case_4: shows " s'=s\<lparr>numWrites := Suc (numWrites s), pcW := Enqueue, ownD := \<lambda>i. if i = numWrites s then B else ownD (s\<lparr>numWrites := Suc (numWrites s), pcW := Enqueue\<rparr>) i, data_index := \<lambda>x. if (offset s, Data s (numEnqs s)) = x then numEnqs s else data_index (s\<lparr>numWrites := Suc (numWrites s), pcW := Enqueue, ownD := \<lambda>i. if i = numWrites s then B else ownD (s\<lparr>numWrites := Suc (numWrites s), pcW := Enqueue\<rparr>) i\<rparr>) x\<rparr> \<Longrightarrow>\<forall>i::nat. ownB s i=ownB s' i \<and> T s = T s' \<and> H s = H s' \<and> offset s = offset s' \<and> tempR s=tempR s' \<and> q s=q s'" by simp (************************************* queue transition lemmas **************************************************) lemma peculiar_1: assumes "Q_gap_structure s" and "Q_offsets_differ s" and "q s\<noteq>[]" and "tl(q s)\<noteq>[]" shows "fst(q s!1) = end(q s!0) \<or> fst(q s!1) =0" using assms apply(simp add:Q_gap_structure_def Q_offsets_differ_def Q_structure_def) by (metis One_nat_def diff_add_zero length_greater_0_conv length_tl less_numeral_extra(1) plus_1_eq_Suc zero_less_diff) lemma peculiar_2: assumes "Q_gap_structure s" and "Q_offsets_differ s" and "q s\<noteq>[]" and "tl(q s)\<noteq>[]" shows "(end(hd(q s)) = fst(hd(tl(q s)))\<and> fst(hd(tl(q s)))\<noteq>0) \<or> fst(hd(tl(q s))) =0" using assms apply(simp add:Q_gap_structure_def Q_offsets_differ_def Q_structure_def) by (metis Nitpick.size_list_simp(2) One_nat_def diff_add_zero hd_conv_nth less_Suc_eq_0_disj not_gr_zero nth_tl plus_1_eq_Suc) lemma peculiar_3: assumes "Q_structure s" and "q s\<noteq>[]" and "tl(q s)\<noteq>[]" shows "(end(hd(q s)) = fst(hd(tl(q s)))\<and> fst(hd(tl(q s)))\<noteq>0) \<or> fst(hd(tl(q s))) =0" using peculiar_1 peculiar_2 Q_structure_def Q_basic_struct_def proof - have "Q_basic_struct s" by (metis (no_types) Nil_tl Q_structure_def assms(1) assms(3)) then show ?thesis by (metis Nil_tl Q_basic_struct_def assms(3) peculiar_2) qed lemma peculiar_4: assumes "Q_offsets_differ s" and "q s\<noteq>[]" and "tl(q s)\<noteq>[]" shows "\<forall>i.(i<length(q s) \<and> i>0)\<longrightarrow>fst(q s!0) \<noteq> fst(q s!i)" using assms by (simp add:Q_offsets_differ_def) lemma peculiar_5: assumes "Q_offsets_differ s" and "q s\<noteq>[]" and "tl(q s)\<noteq>[]" shows "\<forall>i.(i<length(q s) \<and> i>0)\<longrightarrow>fst(hd(q s)) \<noteq> fst(q s!i)" using assms peculiar_4 by (simp add: peculiar_4 hd_conv_nth) lemma peculiar_6: assumes "Q_offsets_differ s" and "q s\<noteq>[]" and "tl(q s)\<noteq>[]" shows "\<forall>i.(i<length(tl(q s)))\<longrightarrow>fst(hd(q s)) \<noteq> fst(tl(q s)!i)" using peculiar_4 peculiar_5 by (simp add: Q_head_relates_tail assms(1) assms(2) hd_conv_nth) lemma peculiar_7: assumes "Q_offsets_differ s" and "q s\<noteq>[]" and "tl(q s)\<noteq>[]" shows "\<forall>i.(i<(length((q s))-1))\<longrightarrow>fst(hd(q s)) \<noteq> fst(tl(q s)!i)" using assms peculiar_6 by (simp add: peculiar_6) lemma peculiar_8: assumes "Q_has_no_overlaps s" and "Q_has_no_uroboros s" and "q s\<noteq>[]" and "tl(q s)\<noteq>[]" shows "\<forall>x.(x\<in>set(q s) \<and> x\<noteq>hd(q s) \<and> fst(hd(q s))<fst(x))\<longrightarrow>end(hd(q s))\<le>fst(x)" using assms Q_has_no_overlaps_def Q_has_no_uroboros_def using hd_in_set by blast lemma peculiar_9: assumes "Q_has_no_overlaps s" and "Q_has_no_uroboros s" and "q s\<noteq>[]" and "tl(q s)\<noteq>[]" shows "\<forall>x.(x\<in>set(tl(q s)) \<and> fst(hd(q s))<fst(x))\<longrightarrow>end(hd(q s))\<le>fst(x)" using peculiar_8 by (metis assms(1) assms(2) assms(3) assms(4) dual_order.irrefl list.set_sel(2)) lemma peculiar_10: assumes "Q_has_no_overlaps s" and "Q_has_no_uroboros s" and "q s\<noteq>[]" and "tl(q s)\<noteq>[]" shows "\<forall>i.(i<(length(q s)-1) \<and> fst(hd(q s))<fst(tl(q s)!i))\<longrightarrow>end(hd(q s))\<le>fst(tl(q s)!i)" by (metis assms(1) assms(2) assms(3) assms(4) length_tl nth_mem peculiar_9) lemma peculiar_11: assumes "Q_has_no_overlaps s" and "Q_has_no_uroboros s" and "q s\<noteq>[]" and "tl(q s)\<noteq>[]" shows "\<forall>x.(x\<in>set(q s) \<and> x\<noteq>hd(q s) \<and> fst(hd(q s))>fst(x))\<longrightarrow>fst(hd(q s))\<ge>end(x)" using assms Q_has_no_overlaps_def Q_has_no_uroboros_def using hd_in_set by blast lemma peculiar_12: assumes "Q_has_no_overlaps s" and "Q_has_no_uroboros s" and "q s\<noteq>[]" and "tl(q s)\<noteq>[]" shows "\<forall>x.(x\<in>set(tl(q s)) \<and> fst(hd(q s))>fst(x))\<longrightarrow>fst(hd(q s))\<ge>end(x)" using assms Q_has_no_overlaps_def peculiar_11 by (metis list.set_sel(2)) lemma peculiar_13: assumes "Q_has_no_overlaps s" and "Q_has_no_uroboros s" and "q s\<noteq>[]" and "tl(q s)\<noteq>[]" shows "\<forall>i.(i<(length(q s)-1) \<and> fst(hd(q s))>fst(tl(q s)!i))\<longrightarrow>fst(hd(q s))\<ge>end(tl(q s)!i)" using assms peculiar_12 by (metis length_tl nth_mem) lemma peculiar_14: assumes "Q_has_no_overlaps s" and "Q_has_no_uroboros s" and "q s\<noteq>[]" and "tl(q s)\<noteq>[]" shows "(\<forall>i.(i<(length(q s)-1) \<and> fst(hd(q s))>fst(tl(q s)!i))\<longrightarrow>fst(hd(q s))\<ge>end(tl(q s)!i)) \<and>(\<forall>i.(i<(length(q s)-1) \<and> fst(hd(q s))<fst(tl(q s)!i))\<longrightarrow>end(hd(q s))\<le>fst(tl(q s)!i))" using peculiar_13 peculiar_10 using assms(1) assms(2) assms(3) assms(4) by blast lemma peculiar_15: assumes "Q_has_no_overlaps s" and "Q_has_no_uroboros s" and "q s\<noteq>[]" and "tl(q s)\<noteq>[]" shows "\<forall>i<length (q s) - Suc 0. (fst (hd (q s)) < fst (tl (q s) ! i) \<longrightarrow> fst (hd (q s)) + snd (hd (q s)) \<le> fst (tl (q s) ! i)) \<and> (fst (tl (q s) ! i) < fst (hd (q s)) \<longrightarrow> fst (tl (q s) ! i) + snd (tl (q s) ! i) \<le> fst (hd (q s)))" using peculiar_14 by (metis One_nat_def assms(1) assms(2) assms(3) assms(4) end_simp) lemma peculiar_16: assumes "Q_structure s" and "q s\<noteq>[]" and "tl(q s)\<noteq>[]" shows "\<forall>i<length (q s) - Suc 0. (fst (hd (q s)) < fst (tl (q s) ! i) \<longrightarrow> fst (hd (q s)) + snd (hd (q s)) \<le> fst (tl (q s) ! i)) \<and> (fst (tl (q s) ! i) < fst (hd (q s)) \<longrightarrow> fst (tl (q s) ! i) + snd (tl (q s) ! i) \<le> fst (hd (q s)))" using peculiar_15 Q_structure_def using Q_basic_struct_def assms(1) assms(2) assms(3) by auto lemma peculiar_17 : assumes "inv s" and "q s\<noteq>[]" and "tl(q s)\<noteq>[]" shows "\<forall>i<length (q s) - Suc 0. (fst (hd (q s)) < fst (tl (q s) ! i) \<longrightarrow> fst (hd (q s)) + snd (hd (q s)) \<le> fst (tl (q s) ! i)) \<and> (fst (tl (q s) ! i) < fst (hd (q s)) \<longrightarrow> fst (tl (q s) ! i) + snd (tl (q s) ! i) \<le> fst (hd (q s)))" using peculiar_16 inv_def Q_structure_def using assms(1) assms(2) assms(3) by blast lemma peculiar_18: assumes "Q_has_no_uroboros s" and "q s\<noteq>[]" and "tl(q s)\<noteq>[]" shows "fst (q s!0) \<noteq> end (last (q s))" using Q_has_no_uroboros_def by (metis assms(1) assms(2) assms(3) butlast.simps(2) list.exhaust_sel list.set_intros(1) nth_Cons_0) lemma peculiar_19: assumes "Q_structure s" and "q s\<noteq>[]" and "tl(q s)\<noteq>[]" shows "fst (q s!0) \<noteq> end (last (q s))" using Q_has_no_uroboros_def Q_structure_def peculiar_18 using Q_basic_struct_def assms(1) assms(2) assms(3) by blast lemma peculiar_20: assumes "Q_structure s" and "q s\<noteq>[]" and "tl(q s)\<noteq>[]" shows "fst (hd(q s)) \<noteq> end (last (q s))" using peculiar_19 by (metis assms(1) assms(2) assms(3) hd_conv_nth) lemma peculiar_21: assumes "Q_structure s" and "q s\<noteq>[]" and "tl(q s)\<noteq>[]" shows "fst (hd(q s)) \<noteq> end (last (tl(q s)))" using peculiar_20 by (metis assms(1) assms(2) assms(3) last_tl) lemma peculiar_22: assumes "Q_structure s" and "tempR_structure s" and "fst(tempR s) =0" shows "\<forall>i.(i<length(q s)\<and> i>0)\<longrightarrow>fst(q s!i) = end(q s!(i-1))" using assms apply (simp add:Q_lemmas Q_basic_lemmas tempR_lemmas tempR_basic_lemmas) by (metis length_0_conv less_nat_zero_code) lemma peculiar_23: assumes "Q_structure s" and "tempR_structure s" and "fst(tempR s) =0" shows "\<forall>i.(i<length(q s))\<longrightarrow>fst(q s!i) >0" using assms apply (simp add:Q_lemmas Q_basic_lemmas tempR_lemmas tempR_basic_lemmas) by (metis length_0_conv less_nat_zero_code) lemma peculiar_24: assumes "Q_structure s" and "tempR_structure s" and "fst(tempR s) =0" and "q s\<noteq>[]" and "tl(q s)\<noteq>[]" shows "fst(q s!0) =end(tempR s)" using assms apply (simp add:Q_lemmas Q_basic_lemmas tempR_lemmas tempR_basic_lemmas) by (metis hd_conv_nth length_greater_0_conv zero_less_iff_neq_zero) lemma peculiar_25: assumes "Q_offsets_differ s" and "Q_gap_structure s" and "fst(hd(q s)) =0" and "tl(q s)\<noteq>[]" shows "\<forall>i.(i<length(q s)\<and>i>0)\<longrightarrow>fst(q s!i) = end(q s!(i-1))" using assms by (metis Q_hd_zero_implies_structure) lemma peculiar_26: assumes "Q_offsets_differ s" and "Q_gap_structure s" and "fst(hd(q s)) =0" and "tl(q s)\<noteq>[]" shows "\<forall>i.(i<length(q s)\<and>i>0)\<longrightarrow>(q s!i) = (tl(q s)!(i-1))" using assms apply(simp add:Q_lemmas Q_basic_lemmas) by (metis Nitpick.size_list_simp(2) Suc_pred add_less_cancel_left list.sel(2) nth_tl plus_1_eq_Suc) lemma peculiar_27: assumes "Q_offsets_differ s" and "Q_gap_structure s" and "fst(hd(q s)) =0" and "tl(q s)\<noteq>[]" shows "\<forall>i.(i<length(q s)\<and>i>1)\<longrightarrow>fst(tl(q s)!(i-1)) = end(tl(q s)!(i-2))" using assms apply(simp add:Q_lemmas Q_basic_lemmas) by (smt (verit, ccfv_SIG) Nitpick.size_list_simp(2) Suc_diff_Suc add_less_cancel_left assms(1) assms(2) diff_less less_trans_Suc list.sel(2) nth_tl numeral_1_eq_Suc_0 numeral_2_eq_2 numerals(1) peculiar_26 peculiar_5 plus_1_eq_Suc zero_less_two) lemma peculiar_28: assumes "Q_offsets_differ s" and "Q_gap_structure s" and "Q_has_no_uroboros s" and "fst(hd(q s)) =0" and "tl(q s)\<noteq>[]" and "butlast(tl(q s))\<noteq>[]" shows "last(tl(q s)) =last(q s)" using assms by (simp add: last_tl) lemma peculiar_29: assumes "Q_offsets_differ s" and "Q_gap_structure s" and "Q_has_no_uroboros s" and "fst(hd(q s)) =0" and "tl(q s)\<noteq>[]" and "butlast(tl(q s))\<noteq>[]" shows "\<forall>i.(i<length(butlast(tl(q s))))\<longrightarrow>(tl(q s)!i) = (q s!(i+1))" using assms by (simp add: peculiar_26) lemma peculiar_30: assumes "Q_offsets_differ s" and "Q_gap_structure s" and "Q_has_no_uroboros s" and "fst(hd(q s)) =0" and "tl(q s)\<noteq>[]" and "butlast(tl(q s))\<noteq>[]" shows "end(last(q s)) = end(last(tl(q s)))" using assms by (simp add: last_tl) lemma peculiar_31: assumes "Q_offsets_differ s" and "Q_gap_structure s" and "Q_has_no_uroboros s" and "fst(hd(q s)) =0" and "tl(q s)\<noteq>[]" and "butlast(tl(q s))\<noteq>[]" shows "\<forall>i.(i<(length(tl(q s))-1))\<longrightarrow>fst(tl(q s)!i) \<noteq>end(last(tl(q s)))" using assms peculiar_30 peculiar_29 apply simp unfolding Q_lemmas Q_basic_lemmas apply safe apply(subgoal_tac "last(tl(q s)) =(tl(q s)!(length(tl(q s))-1))") prefer 2 apply (simp add: last_conv_nth) apply simp by (metis One_nat_def Suc_eq_plus1 Suc_lessD assms(5) diff_Suc_eq_diff_pred in_set_conv_nth last_tl length_butlast length_tl less_diff_conv nth_butlast nth_tl prod.exhaust_sel) lemma tail_preserves_struct: "Q_gap_structure s \<Longrightarrow> fst (q s ! 0) = 0 \<Longrightarrow>\<forall> i . i<length (q s) \<longrightarrow> snd(q s ! i) > 0 \<Longrightarrow> Q_offsets_differ s \<Longrightarrow> length(q s)>0 \<Longrightarrow> \<forall> i . (i<length (q s) \<and> i>0)\<longrightarrow> fst(q s ! i) > fst (q s ! 0)" apply(simp add:Q_gap_structure_def Q_offsets_differ_def) by (metis gr_implies_not_zero not_gr_zero) lemma queue_is_finite_set: assumes "con_assms s" and "Q_structure s" shows "\<forall>a b.((a,b)\<in>set(q s))\<longleftrightarrow>(\<exists>i.(i<length(q s) \<and> (a, b) =(q s!i)))" using assms apply(simp add:Q_lemmas Q_basic_lemmas) by (metis in_set_conv_nth) (*******************************LOCAL W_step shows inv s'*************************************) lemma W_inv_A1_lemma: assumes "inv s" and "con_assms s" and "pcW s = A1" and "pre_W (pcW s) s" and "cW_step (pcW s) s s'" shows "inv s'" using assms apply(simp add:inv_def pre_W_def cW_step_def pre_A1_inv_def) apply (intro conjI impI) apply(simp add:Q_lemmas Q_basic_lemmas) apply(case_tac "case_1 s") apply(simp add:case_1_def) apply(simp add:case_2_def) by(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) lemma W_inv_A2_lemma: assumes "inv s" and "con_assms s" and "pcW s = A2" and "pre_W (pcW s) s" and "cW_step (pcW s) s s'" shows "inv s'" using assms apply(simp add:inv_def pre_W_def cW_step_def pre_A2_inv_def) apply(case_tac "tW s = hW s", simp_all) apply(intro conjI impI) apply(simp add:Q_lemmas Q_basic_lemmas) apply (elim conjE disjE) apply(case_tac "case_1 s'") using case_trans_A2_to_A3_2 [where s=s] apply blast using \<open>\<And>s'. \<lbrakk>s' = s\<lparr>ownT := W, pcW := A3\<rparr>; T s = H s; case_1 s\<rbrakk> \<Longrightarrow> case_1 s'\<close> apply presburger apply (metis case_split_2 le_refl) apply(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) apply(case_tac "hW s < tW s \<and> Data s (numEnqs s) < tW s - hW s", simp_all) apply(intro conjI impI) apply(simp add:Q_lemmas Q_basic_lemmas) apply (elim conjE disjE) apply(subgoal_tac "\<not>case_1 s") prefer 2 apply (metis case_split_4 less_eqE trans_less_add1) apply meson apply(subgoal_tac "case_2 s'") apply blast apply simp using case_trans_A2_to_A4_3 [where s=s] apply (meson case_split_2 not_less) apply (metis case_trans_A2_to_A4_2) apply (metis case_split_2) apply(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) apply(case_tac "tW s < hW s", simp_all) apply(intro conjI impI) apply(simp add:Q_lemmas Q_basic_lemmas) apply (metis case_split_2 case_trans_A2_to_A5_2) apply(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) apply(intro conjI impI) apply(simp add:Q_lemmas Q_basic_lemmas) apply (elim conjE disjE) apply (metis case_split_4 less_eqE linorder_neqE_nat trans_less_add1) apply (metis case_split_2 case_trans_A2_to_A8_4 linear nat_less_le) apply (metis case_trans_A2_to_A8_2) apply (metis case_split_2) by(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) lemma W_inv_A3_lemma: assumes "inv s" and "con_assms s" and "pcW s = A3" and "pre_W (pcW s) s" and "cW_step (pcW s) s s'" shows "inv s'" using assms apply(simp add:inv_def pre_W_def cW_step_def pre_A3_inv_def) apply(intro conjI impI) apply(simp add:Q_lemmas Q_basic_lemmas) defer apply(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) apply(subgoal_tac "case_1 s") prefer 2 apply (metis RingBuffer_BD_latest_2.case_split le_refl) apply(subgoal_tac "\<not>case_2 s'") prefer 2 using case_trans_A3_to_write_2 [where s=s and s'=s'] apply (simp add: assms(1) pre_A3_inv_def) apply simp using case_trans_A3_to_write_7 [where s=s] by (simp add: assms(1) pre_A3_inv_def) lemma W_inv_A4_lemma: assumes "inv s" and "con_assms s" and "pcW s = A4" and "pre_W (pcW s) s" and "cW_step (pcW s) s s'" shows "inv s'" using assms apply(simp add:inv_def pre_W_def cW_step_def) apply(intro conjI impI) apply(simp add:inv_def pre_W_def cW_step_def pre_A4_inv_def) apply (simp add: less_diff_conv) apply(simp add:inv_def pre_W_def cW_step_def pre_A4_inv_def) apply(simp add:Q_lemmas Q_basic_lemmas) defer apply(simp add:inv_def pre_W_def cW_step_def pre_A4_inv_def) apply(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) apply (metis (no_types, lifting) F.distinct(19) add.commute add_lessD1 canonically_ordered_monoid_add_class.lessE less_diff_conv) apply(case_tac "T s\<ge>tW s") apply(subgoal_tac "case_2 s'") prefer 2 using case_trans_A4_to_write_7 [where s=s and s'=s'] apply (simp add: assms(1) assms(2) pre_A4_inv_def) apply meson using case_trans_A4_to_write_9 [where s=s and s'=s'] using assms(1) pre_A4_inv_def by auto lemma W_inv_A5_lemma: assumes "inv s" and "con_assms s" and "pcW s = A5" and "pre_W (pcW s) s" and "cW_step (pcW s) s s'" shows "inv s'" using assms apply(simp add:inv_def pre_W_def cW_step_def pre_A5_inv_def) apply(case_tac "Data s (numEnqs s) \<le> N - hW s", simp_all) defer apply(case_tac "Data s (numEnqs s) < tW s", simp_all) defer defer apply(intro conjI impI) apply(simp add:Q_lemmas Q_basic_lemmas) prefer 2 apply(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) defer apply(intro conjI impI) apply(simp add:Q_lemmas Q_basic_lemmas) prefer 2 apply(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) apply(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) defer apply(intro conjI impI) apply(simp add:Q_lemmas Q_basic_lemmas) prefer 2 apply(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) defer using case_trans_A5_to_A6_3 [where s=s and s'=s'] apply (metis PCW.simps(187) assms(1) assms(2) assms(4) pre_W_def) using case_trans_A5_to_A6_6 [where s=s and s'=s'] apply (simp add: assms(1) pre_A5_inv_def) using case_trans_A5_to_A6_9 [where s=s and s'=s'] by (metis case_split_2 case_trans_A2_to_A8_2) lemma W_inv_A6_lemma: assumes "inv s" and "con_assms s" and "pcW s = A6" and "pre_W (pcW s) s" and "cW_step (pcW s) s s'" shows "inv s'" using assms apply(simp add:inv_def pre_W_def cW_step_def pre_A6_inv_def) apply(intro conjI impI) apply (metis Nat.le_diff_conv2 add.commute) apply(simp add:Q_lemmas Q_basic_lemmas) prefer 2 apply(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) prefer 2 using case_trans_A6_to_write_7 [where s=s and s'=s'] apply (metis (no_types, lifting) PCW.simps(188) assms(1) assms(2) assms(4) pre_W_def) by (smt (z3) F.distinct(19) diff_add_inverse le_diff_iff le_neq_implies_less le_trans less_imp_add_positive less_or_eq_imp_le not_add_less1) lemma W_inv_A7_lemma: assumes "inv s" and "con_assms s" and "pcW s = A7" and "pre_W (pcW s) s" and "cW_step (pcW s) s s'" shows "inv s'" using assms apply(simp add:inv_def pre_W_def cW_step_def pre_A7_inv_def) apply(intro conjI impI) apply(simp add:Q_lemmas Q_basic_lemmas) prefer 2 apply(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) using case_trans_A7_to_write_7 [where s=s and s'=s'] by (metis (no_types, lifting) PCW.simps(189) assms(1) assms(2) assms(4) pre_W_def) lemma W_inv_A8_lemma: assumes "inv s" and "con_assms s" and "pcW s = A8" and "pre_W (pcW s) s" and "cW_step (pcW s) s s'" shows "inv s'" using assms apply(simp add:inv_def pre_W_def cW_step_def pre_A8_inv_def) apply(intro conjI impI) apply(simp add:Q_lemmas Q_basic_lemmas) apply(case_tac "N < Data s (numEnqs s)", simp_all) apply (metis leD) apply (metis leD) apply(simp add:Q_lemmas Q_basic_lemmas) apply(case_tac "case_1 s") apply(simp) apply(simp add:case_1_def) apply(simp add:case_2_def) by(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) lemma W_inv_Enqueue_lemma: assumes "inv s" and "con_assms s" and "pcW s = Enqueue" and "pre_W (pcW s) s" and "cW_step (pcW s) s s'" shows "inv s'" using assms apply(simp add:inv_def pre_W_def cW_step_def pre_enqueue_inv_def) apply(intro conjI impI) apply (metis Suc_diff_le length_0_conv) defer defer apply(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) apply(simp add:tempW_def) apply(case_tac "case_1 s") apply simp apply(simp add:tempW_lemmas tempW_basic_lemmas) apply(simp add:case_1_def) apply clarify apply(intro conjI impI) apply (metis F.distinct(5) diff_is_0_eq' less_nat_zero_code linorder_neqE_nat nat_le_linear zero_less_diff) apply (metis (mono_tags, hide_lams) F.distinct(5) F.distinct(9) le_antisym less_Suc_eq_le minus_nat.diff_0 not_less_eq plus_nat.add_0) apply(subgoal_tac "i<N \<and> ownB s i=W\<longrightarrow>offset s\<le>i \<and> i<offset s + Data s (numEnqs s)") prefer 2 apply (metis nat_less_le) apply(subgoal_tac "i>N \<and> ownB s i=W\<longrightarrow>i>offset s + Data s (numEnqs s)") apply (metis (no_types, lifting) diff_is_0_eq le_eq_less_or_eq linorder_neqE_nat zero_less_diff) apply(subgoal_tac "end(tempW s)\<le>N", unfold tempW_def)[1] prefer 2 apply (metis end_simp fst_conv snd_conv) apply (metis (no_types, lifting) less_trans_Suc nat_less_le nat_neq_iff not_less_eq_eq) apply(subgoal_tac "case_2 s") apply simp apply(thin_tac "\<not>case_1 s")[1] prefer 2 apply blast apply(simp add:tempW_lemmas tempW_basic_lemmas) apply(simp add:case_2_def) apply clarify using Suc_diff_le apply presburger defer defer apply(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) apply clarify apply(intro conjI impI) apply(rule_tac ?x = "{i. offset s \<le> i \<and> i < offset s + Data s (numEnqs s)}" in exI) apply (intro conjI impI) apply metis apply(case_tac "case_1 s") apply(simp) apply(simp add:case_1_def) apply clarify apply(intro conjI impI) apply (metis F.distinct(5) diff_is_0_eq' less_nat_zero_code linorder_neqE_nat nat_le_linear zero_less_diff) apply (metis (no_types, lifting) Suc_le_lessD fst_conv not_less_eq_eq snd_conv tempW_def) apply(subgoal_tac "case_2 s") apply simp apply(thin_tac "\<not>case_1 s")[1] prefer 2 apply blast apply(simp add:tempW_lemmas tempW_basic_lemmas) apply(simp add:case_2_def) apply clarify apply (intro conjI impI) apply (metis le_eq_less_or_eq nat_le_linear) apply(subgoal_tac "i\<ge>H s\<and>i<T s\<longrightarrow>ownB s i=B") prefer 2 apply metis apply(subgoal_tac "i\<ge>T s\<and>i<e\<longrightarrow>ownB s i=R") prefer 2 apply metis apply(subgoal_tac "i\<ge>e\<and>i<f\<longrightarrow>ownB s i=Q") prefer 2 apply metis apply(subgoal_tac "i\<ge>f\<and>i<N\<longrightarrow>ownB s i=D") prefer 2 apply metis apply(subgoal_tac "i\<ge>H s\<and>i<N\<longrightarrow>ownB s i\<noteq>W") prefer 2 apply (metis F.distinct(1) F.distinct(3) F.distinct(5) F.distinct(7) diff_is_0_eq neq0_conv zero_less_diff) apply (metis (no_types, lifting) diff_is_0_eq gr0I zero_less_diff) apply(clarsimp) apply(intro iffI) apply clarify apply simp apply(case_tac "(a, b) \<in> set (q s)") apply simp apply (metis (no_types, lifting) mem_Collect_eq) apply(subgoal_tac "(i\<le>N \<and> ownB s i\<noteq>Q)\<longrightarrow>(\<nexists>a b. ((a,b)\<in>set(q s)\<and> a\<le>i \<and> i<a+b))") prefer 2 apply (metis fst_eqD snd_eqD tempW_def) apply(subgoal_tac "a = offset s \<and> b = Data s (numEnqs s)") prefer 2 apply meson apply(simp add:tempW_lemmas tempW_basic_lemmas) apply clarify apply simp apply(subgoal_tac "ownB s i=Q \<and> i\<le>N\<longleftrightarrow>(\<exists>x. (\<exists>a b. x = {i. a \<le> i \<and> i < a + b} \<and> (a, b) \<in> set (q s)) \<and> i \<in> x)") prefer 2 apply presburger apply simp apply metis apply clarify sorry lemma W_inv_idleW_lemma: assumes "inv s" and "con_assms s" and "pcW s = idleW" and "pre_W (pcW s) s" and "cW_step (pcW s) s s'" shows "inv s'" using assms apply(simp add:inv_def pre_W_def cW_step_def pre_acquire_inv_def) apply(intro conjI impI) apply(simp add:Q_lemmas Q_basic_lemmas) apply(case_tac "numEnqs s < n", simp_all) apply(case_tac "numEnqs s < n", simp_all) apply(case_tac "numEnqs s < n", simp_all) apply(case_tac "numEnqs s < n", simp_all) apply(case_tac "numEnqs s < n", simp_all) apply(case_tac "numEnqs s < n", simp_all) apply(case_tac "numEnqs s < n", simp_all) apply (metis leD) apply(case_tac "numEnqs s < n", simp_all) apply(case_tac "numEnqs s < n", simp_all) apply(case_tac "numEnqs s < n", simp_all) apply(case_tac "numEnqs s < n", simp_all) apply(case_tac "numEnqs s < n", simp_all) apply(case_tac "numEnqs s < n", simp_all) apply(case_tac "numEnqs s < n", simp_all) apply(simp add:Q_lemmas Q_basic_lemmas) apply(simp add:Q_lemmas Q_basic_lemmas) apply(case_tac "numEnqs s < n", simp_all) apply(case_tac "numEnqs s < n", simp_all) apply(case_tac "case_1 s") apply(simp) apply(simp add:case_1_def) apply(simp add:case_2_def) apply(case_tac "case_1 s") apply(simp) apply(simp add:case_1_def) apply(subgoal_tac "case_2 (s\<lparr>pcW := FinishedW\<rparr>)") apply blast apply simp apply(thin_tac "\<not> case_1 s ") apply(simp add:case_2_def) prefer 2 apply(case_tac "numEnqs s < n", simp_all) apply(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) apply(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) apply clarify apply(rule_tac ?x = "a" in exI) apply(rule_tac ?x = "b" in exI) apply(intro conjI impI) apply metis apply(rule_tac ?x = "H s" in exI) apply(intro conjI impI) apply blast apply(rule_tac ?x = "T s" in exI) apply(intro conjI impI) apply blast apply(rule_tac ?x = "e" in exI) apply(intro conjI impI) apply blast apply(rule_tac ?x = "f" in exI) apply(intro conjI impI) apply blast apply blast apply blast apply blast apply blast apply blast apply blast apply blast apply blast apply blast apply blast apply blast apply blast apply blast apply blast apply blast apply meson apply metis apply meson apply meson apply meson apply meson apply meson apply meson apply meson apply meson apply meson apply meson apply meson apply meson by meson lemma W_inv_OOM_lemma: assumes "inv s" and "con_assms s" and "pcW s = OOM" and "pre_W (pcW s) s" and "cW_step (pcW s) s s'" shows "inv s'" using assms apply(simp add:inv_def pre_W_def cW_step_def pre_OOM_inv_def) apply(intro conjI impI) apply(simp add:Q_lemmas Q_basic_lemmas) apply(case_tac "tW s \<noteq> T s", simp_all) apply(case_tac "tW s \<noteq> T s", simp_all) apply(case_tac "tW s \<noteq> T s", simp_all) apply(case_tac "tW s \<noteq> T s", simp_all) apply(case_tac "tW s \<noteq> T s", simp_all) apply(case_tac "tW s \<noteq> T s", simp_all) apply(case_tac "tW s \<noteq> T s", simp_all) apply(case_tac "tW s \<noteq> T s", simp_all) apply(case_tac "tW s \<noteq> T s", simp_all) apply(case_tac "tW s \<noteq> T s", simp_all) apply(case_tac "tW s \<noteq> T s", simp_all) apply(case_tac "tW s \<noteq> T s", simp_all) apply(case_tac "tW s \<noteq> T s", simp_all) apply(case_tac "tW s \<noteq> T s", simp_all) apply(simp add:Q_lemmas Q_basic_lemmas) apply(case_tac "tW s \<noteq> T s", simp_all) apply(case_tac "tW s \<noteq> T s", simp_all) apply(case_tac "case_1 s") apply simp apply(simp add:case_1_def) apply(simp add:case_2_def) apply(case_tac "tW s \<noteq> T s", simp_all) by(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) lemma W_inv_FinishedW_lemma: assumes "inv s" and "con_assms s" and "pcW s = FinishedW" and "pre_W (pcW s) s" and "cW_step (pcW s) s s'" shows "inv s'" using assms by(simp add:inv_def pre_W_def cW_step_def pre_OOM_inv_def) lemma W_inv_Write_lemma: assumes "inv s" and "con_assms s" and "pcW s = Write" and "pre_W (pcW s) s" and "cW_step (pcW s) s s'" shows "inv s'" using assms apply simp apply(subgoal_tac "case_1 s \<or> case_2 s") prefer 2 using inv_def pre_W_def apply blast apply(subgoal_tac "pre_write_inv s") prefer 2 using inv_def pre_W_def assms apply (metis PCW.simps(195)) apply(simp add:pre_W_def cW_step_def) apply(simp add:inv_def) apply(intro conjI impI) apply (simp add: pre_write_inv_def) defer apply (simp add: pre_write_inv_def) defer defer defer apply(subgoal_tac "case_1 s' \<or> case_2 s'") apply meson using case_trans_Write_to_Enqueue_case_3 [where s=s and s'=s'] using assms(1) assms(2) apply blast apply(simp add:Q_indices_def ran_indices_def Q_owns_bytes_def) sorry lemma W_inv_BTS_lemma: assumes "inv s" and "con_assms s" and "pcW s = BTS" and "pre_W (pcW s) s" and "cW_step (pcW s) s s'" shows "inv s'" using assms by(simp add:inv_def pre_W_def cW_step_def pre_OOM_inv_def) lemma local_pre_W_inv: assumes "con_assms s" and "pcw = pcW s" and "pre_W pcw s" and "inv s" and "cW_step pcw s s'" shows "inv s'" using assms apply(case_tac "pcW s") using W_inv_A1_lemma [where s=s and s'=s'] apply blast using W_inv_A2_lemma [where s=s and s'=s'] apply blast using W_inv_A3_lemma [where s=s and s'=s'] apply blast using W_inv_A4_lemma [where s=s and s'=s'] apply blast using W_inv_A5_lemma [where s=s and s'=s'] apply blast using W_inv_A6_lemma [where s=s and s'=s'] apply blast using W_inv_A7_lemma [where s=s and s'=s'] apply blast using W_inv_A8_lemma [where s=s and s'=s'] apply blast using W_inv_Enqueue_lemma [where s=s and s'=s'] apply blast (*hard- Queue*) using W_inv_idleW_lemma [where s=s and s'=s'] apply blast using W_inv_OOM_lemma [where s=s and s'=s'] apply blast using W_inv_FinishedW_lemma [where s=s and s'=s'] apply blast using W_inv_Write_lemma [where s=s and s'=s'] apply blast (*Queue*) using W_inv_BTS_lemma [where s=s and s'=s'] by blast (*******************************LOCAL W_step shows preW*************************************) lemma W_local_A1_lemma: assumes "inv s" and "con_assms s" and "pcW s = A1" and "pre_W (pcW s) s" and "cW_step (pcW s) s s'" shows "pre_W (pcW s') s'" using assms apply simp by(simp add:inv_def pre_W_def cW_step_def pre_A1_inv_def pre_A2_inv_def) lemma W_local_A2_lemma: assumes "inv s" and "con_assms s" and "pcW s = A2" and "pre_W (pcW s) s" and "cW_step (pcW s) s s'" shows "pre_W (pcW s') s'" using assms apply simp apply(simp add:inv_def pre_W_def cW_step_def pre_A2_inv_def pre_A3_inv_def) apply(case_tac "tW s = hW s") apply simp_all apply(case_tac "hW s < tW s \<and> Data s (numEnqs s) < tW s - hW s") apply(simp_all add: pre_A4_inv_def) apply metis apply(case_tac "tW s < hW s", simp_all) apply(simp add:pre_A5_inv_def) apply(simp add:pre_A8_inv_def) by metis lemma W_local_A3_lemma: assumes "inv s" and "con_assms s" and "pcW s = A3" and "pre_W (pcW s) s" and "cW_step (pcW s) s s'" shows "pre_W (pcW s') s'" using assms apply simp apply(simp add:inv_def pre_W_def cW_step_def pre_A3_inv_def pre_write_inv_def) by(simp add:tempW_lemmas tempW_basic_lemmas) lemma W_local_A4_lemma: assumes "inv s" and "con_assms s" and "pcW s = A4" and "pre_W (pcW s) s" and "cW_step (pcW s) s s'" shows "pre_W (pcW s') s'" using assms apply simp apply(simp add:inv_def pre_W_def cW_step_def pre_A4_inv_def pre_write_inv_def) apply(simp add:tempW_lemmas tempW_basic_lemmas) apply(intro conjI impI) apply (simp add: less_diff_conv) apply(case_tac "case_1 s") apply(subgoal_tac "\<not>case_2 s") apply simp apply(thin_tac "\<not> case_2 s") apply(simp add:case_1_def) apply (metis cancel_comm_monoid_add_class.diff_cancel le_eq_less_or_eq length_0_conv less_nat_zero_code) apply (metis case_split_5) apply(subgoal_tac "case_2 s") apply simp apply(thin_tac "\<not>case_1 s") apply(simp add:case_2_def) apply (metis (no_types, lifting) add_diff_cancel_left' cancel_comm_monoid_add_class.diff_cancel diff_is_0_eq diff_zero le_trans length_greater_0_conv nat_less_le) apply (metis) apply(simp add:Q_lemmas Q_basic_lemmas tempW_lemmas tempW_basic_lemmas) apply(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) apply(case_tac "case_1 s") apply(subgoal_tac "\<not>case_2 s") apply simp apply(thin_tac "\<not> case_2 s") apply(simp add:case_1_def) apply (metis (no_types, hide_lams) diff_is_0_eq' le_eq_less_or_eq length_pos_if_in_set nth_mem prod.exhaust_sel zero_less_diff) apply (metis case_split_5) apply(subgoal_tac "case_2 s") apply simp apply(thin_tac "\<not>case_1 s") apply(simp add:case_2_def) apply clarify apply(subgoal_tac "ownB s (H s) \<noteq> Q") prefer 2 apply (metis F.distinct(19) le_refl) apply(subgoal_tac "\<forall>i. (\<exists>x. (\<exists>a b. x = {i. a \<le> i \<and> i < a + b} \<and> (a, b) \<in> set (q s)) \<and> i \<in> x) = (i \<le> N \<and> ownB s i = Q)") prefer 2 apply blast apply(subgoal_tac "i<length(q s) \<longrightarrow> snd(q s!i) > 0") prefer 2 apply (metis nth_mem prod.collapse) apply(subgoal_tac "hW s = end(last(q s))") prefer 2 apply (metis add.commute add_diff_inverse_nat diff_is_0_eq' end_simp le_eq_less_or_eq le_trans minus_nat.diff_0 nat_less_le) apply (metis end_simp nth_mem prod.collapse) apply metis apply(simp add:Q_lemmas Q_basic_lemmas) (*doable*) defer apply(case_tac "case_1 s") apply(subgoal_tac "\<not>case_2 s") apply simp apply(thin_tac "\<not> case_2 s") apply(simp add:case_1_def) apply(simp add:Q_indices_def Q_owns_bytes_def ran_indices_def) apply (metis (no_types, lifting) add_leD1 cancel_comm_monoid_add_class.diff_cancel le_eq_less_or_eq le_zero_eq length_0_conv) apply (metis case_split_5) apply(subgoal_tac "case_2 s") apply simp apply(thin_tac "\<not>case_1 s") apply(simp add:case_2_def) apply(simp add:Q_indices_def Q_owns_bytes_def ran_indices_def) apply(clarify) apply(case_tac "fst(hd(q s)) = 0") apply (metis add_is_0) apply(subgoal_tac "fst(hd(q s)) = e") prefer 2 apply (metis (no_types, lifting) add_diff_cancel_right' add_lessD1 cancel_comm_monoid_add_class.diff_cancel le_neq_implies_less length_greater_0_conv not_add_less1 ordered_cancel_comm_monoid_diff_class.add_diff_inverse) apply(subgoal_tac "hW s<T s") prefer 2 apply blast apply(subgoal_tac " hW s + Data s (numEnqs s) = hW s") prefer 2 apply (metis add.commute diff_add less_diff_conv nat_less_le trans_less_add2) apply(subgoal_tac "T s \<le> fst(hd(q s))") prefer 2 apply meson apply(subgoal_tac "d> Data s (numEnqs s) + hW s ") prefer 2 apply (metis add.commute less_add_same_cancel2) apply(subgoal_tac "d=e") prefer 2 apply (metis less_add_same_cancel1) apply (metis not_add_less2) apply blast apply(clarify) apply(intro conjI impI) apply(case_tac "case_1 s") apply(subgoal_tac "\<not>case_2 s") apply simp apply(thin_tac "\<not> case_2 s") apply(simp add:case_1_def) apply(simp add:Q_indices_def Q_owns_bytes_def ran_indices_def) apply(subgoal_tac "\<forall>j. j<length(q s) \<longrightarrow> hW s > fst(q s!j)") apply (metis Suc_lessD less_natE not_add_less1) apply(subgoal_tac "\<forall> a b j. ((a,b)\<in>set(q s) \<and> a\<le>j \<and> j<a+b) \<longrightarrow> ownB s (j) = Q") prefer 2 apply (metis (no_types, lifting) mem_Collect_eq) apply(clarify) apply(subgoal_tac "\<forall>i.(ownB s i=Q \<and> i\<le>N) \<longrightarrow> i<c") prefer 2 apply (metis (no_types, lifting) F.distinct(19) F.distinct(23) le_eq_less_or_eq linorder_neqE_nat) apply(subgoal_tac "\<forall>i.(i<length(q s))\<longrightarrow> ownB s (fst(q s!0)) = Q") prefer 2 apply (metis cancel_comm_monoid_add_class.diff_cancel hd_conv_nth le_eq_less_or_eq less_nat_zero_code) apply(subgoal_tac "c\<le>hW s") prefer 2 apply blast apply(subgoal_tac "fst(q s!j) + snd(q s!j) \<le>N") prefer 2 apply (metis nth_mem prod.collapse) apply(subgoal_tac "fst(q s!j) \<le>N") prefer 2 apply (metis add_leD1) apply (metis (no_types, lifting) le_eq_less_or_eq less_add_same_cancel1 nth_mem prod.collapse) apply (metis case_split_5) apply(simp add:Q_indices_def Q_owns_bytes_def ran_indices_def) apply(case_tac "case_1 s") apply(subgoal_tac "\<not>case_2 s") apply simp apply (metis case_split_5) apply(simp add:case_2_def) apply(thin_tac "\<not> case_1 s") apply clarify apply(case_tac "H s \<ge> T s") apply (metis le_imp_less_Suc less_or_eq_imp_le not_less_eq) apply(subgoal_tac "H s < T s ") prefer 2 apply metis apply(thin_tac "\<not> T s \<le> H s") apply(subgoal_tac "\<forall>i.(hW s \<le>i \<and> i<hW s + Data s (numEnqs s)) \<longrightarrow> ownB s i = B") prefer 2 apply (metis (no_types, lifting) Suc_lessD add.commute less_diff_conv less_trans_Suc) apply(case_tac "e=f") apply(subgoal_tac "\<forall>i.(ownB s i = Q \<and> i\<le>N)\<longrightarrow>i<b") prefer 2 apply (metis (no_types, hide_lams) F.distinct(11) F.distinct(19) F.distinct(21) F.distinct(23) F.distinct(3) Suc_pred bot_nat_0.not_eq_extremum diff_Suc_Suc diff_diff_cancel diff_is_0_eq old.nat.inject zero_less_Suc zero_less_diff) apply(subgoal_tac "\<forall>a b j.((a,b)\<in>set(q s) \<and> a\<le>j \<and> j<a+b)\<longrightarrow>ownB s j = Q") prefer 2 apply (metis (no_types, lifting) mem_Collect_eq) apply(subgoal_tac "\<forall>i. i<length(q s) \<longrightarrow> (q s!i) \<in> set(q s)") prefer 2 apply (metis nth_mem) apply(subgoal_tac "fst(q s!i)< fst(q s!i) + snd(q s!i)") prefer 2 apply (metis less_add_same_cancel1 prod.collapse) apply(subgoal_tac "\<forall>a b. (a,b)\<in>set(q s) \<longrightarrow> ownB s (a) = Q") prefer 2 apply (metis (no_types, hide_lams) Nat.add_0_right le_refl nat_add_left_cancel_less) apply(subgoal_tac "\<forall>i. (i<length(q s)) \<longrightarrow> (\<exists>a b. ((a,b)\<in>set(q s) \<and> a=fst(q s!i) \<and> b = snd(q s!i)))") prefer 2 apply (metis prod.collapse) apply(subgoal_tac "\<forall>i. i<length(q s) \<longrightarrow> ownB s (fst(q s!i)) = Q") prefer 2 apply (metis (no_types, hide_lams)) apply(subgoal_tac "\<forall>i.(i<length(q s) \<and> fst(q s!i) < N)\<longrightarrow> fst(q s!i)<b") prefer 2 apply (metis less_imp_le_nat) apply(subgoal_tac "fst(q s!i) + snd(q s!i)\<le>N") prefer 2 apply (metis less_add_same_cancel1 prod.collapse) apply(subgoal_tac "\<forall>i.(i<length(q s))\<longrightarrow> fst(q s!i)<b") prefer 2 apply (metis (no_types, lifting) add_leD1) apply (metis (no_types, lifting) add_lessD1 le_imp_less_Suc less_imp_add_positive not_less_eq) apply(case_tac "fst(q s!i) < hW s") apply linarith apply(subgoal_tac "\<forall>a b j.((a,b)\<in>set(q s) \<and> a\<le>j \<and> j<a+b)\<longrightarrow>ownB s j = Q") prefer 2 apply (metis (no_types, lifting) mem_Collect_eq) apply(subgoal_tac "\<forall>i. i<length(q s) \<longrightarrow> (q s!i) \<in> set(q s)") prefer 2 apply (metis nth_mem) apply(subgoal_tac "fst(q s!i)< fst(q s!i) + snd(q s!i)") prefer 2 apply (metis less_add_same_cancel1 prod.collapse) apply(subgoal_tac "\<forall>a b. (a,b)\<in>set(q s) \<longrightarrow> ownB s (a) = Q") prefer 2 apply (metis (no_types, hide_lams) Nat.add_0_right le_refl nat_add_left_cancel_less) apply(subgoal_tac "\<forall>i. (i<length(q s)) \<longrightarrow> (\<exists>a b. ((a,b)\<in>set(q s) \<and> a=fst(q s!i) \<and> b = snd(q s!i)))") prefer 2 apply (metis prod.collapse) apply(subgoal_tac "\<forall>i. i<length(q s) \<longrightarrow> ownB s (fst(q s!i)) = Q") prefer 2 apply (metis (no_types, hide_lams)) apply(subgoal_tac "fst(q s!i) + snd(q s!i)\<le>N") prefer 2 apply (metis less_add_same_cancel1 prod.collapse) apply(subgoal_tac "fst(q s!i) \<ge>e") apply (metis (no_types, lifting) F.distinct(19) add.commute less_diff_conv less_or_eq_imp_le linorder_neqE_nat) apply (metis (no_types, hide_lams) F.distinct(11) F.distinct(19) bot_nat_0.not_eq_extremum diff_is_0_eq diff_self_eq_0 zero_less_diff) apply(simp add:Q_indices_def Q_owns_bytes_def ran_indices_def) apply(case_tac "case_1 s") apply simp apply(simp add:case_1_def) apply clarify apply(subgoal_tac "\<forall>a b j.((a,b)\<in>set(q s) \<and> a\<le>j \<and> j<a+b)\<longrightarrow>ownB s j = Q") prefer 2 apply (metis (no_types, lifting) mem_Collect_eq) apply(subgoal_tac "\<forall>i. i<length(q s) \<longrightarrow> (q s!i) \<in> set(q s)") prefer 2 apply (metis nth_mem) apply(subgoal_tac "fst(q s!i)< fst(q s!i) + snd(q s!i)") prefer 2 apply (metis less_add_same_cancel1 prod.collapse) apply(subgoal_tac "\<forall>a b. (a,b)\<in>set(q s) \<longrightarrow> ownB s (a) = Q") prefer 2 apply (metis (no_types, hide_lams) Nat.add_0_right le_refl nat_add_left_cancel_less) apply(subgoal_tac "\<forall>i. (i<length(q s)) \<longrightarrow> (\<exists>a b. ((a,b)\<in>set(q s) \<and> a=fst(q s!i) \<and> b = snd(q s!i)))") prefer 2 apply (metis prod.collapse) apply(subgoal_tac "\<forall>a b j.((a,b)\<in>set(q s) \<and> a\<le>j \<and> j\<le>a+b-1)\<longrightarrow>ownB s j = Q") prefer 2 apply (metis Suc_diff_1 add_gr_0 le_imp_less_Suc) apply(subgoal_tac "\<forall>a b.((a,b)\<in>set(q s))\<longrightarrow>a+b\<le>hW s") apply (metis (no_types, lifting) less_or_eq_imp_le) apply(subgoal_tac "\<forall>i.(ownB s i = Q \<and> i\<le>N) \<longrightarrow> i<c") prefer 2 apply (metis (no_types, lifting) F.distinct(19) F.distinct(23) le_eq_less_or_eq linorder_neqE_nat) apply(subgoal_tac "\<forall>a b.((a,b)\<in>set(q s))\<longrightarrow>a+b\<le>N") prefer 2 apply blast apply(subgoal_tac "\<forall>a b.((a,b)\<in>set(q s))\<longrightarrow>b>0") prefer 2 apply blast apply(subgoal_tac "\<forall>a b.((a,b)\<in>set(q s) \<and> a\<le>a+b-1 \<and> a+b-1\<le>a+b-1)\<longrightarrow>ownB s (a+b-1) = Q") prefer 2 apply (metis Suc_diff_1 add_gr_0 le_imp_less_Suc) apply(subgoal_tac "\<forall>a b.((a,b)\<in>set(q s))\<longrightarrow>a\<le>a+b-1 \<and> a+b-1\<le>a+b-1") prefer 2 apply (metis Suc_diff_1 add_gr_0 le_eq_less_or_eq less_Suc_eq_le less_add_same_cancel1) apply(subgoal_tac "\<forall>a b.((a,b)\<in>set(q s))\<longrightarrow>ownB s (a+b-1) = Q") prefer 2 apply (metis (no_types, lifting)) apply(subgoal_tac "\<forall>a b.((a,b)\<in>set(q s))\<longrightarrow>a+b-1 <c") prefer 2 apply (metis diff_le_self le_trans) apply(subgoal_tac "\<forall>a b.((a,b)\<in>set(q s))\<longrightarrow>a+b-1 <a+b") prefer 2 apply (metis Suc_pred' add_gr_0 lessI) apply(subgoal_tac "hW s\<ge>c") prefer 2 apply blast apply(subgoal_tac "\<forall>a b.((a,b)\<in>set(q s))\<longrightarrow>a+b-1 <hW s") prefer 2 apply (metis eq_imp_le nat_less_le) apply (metis (no_types, lifting) Suc_leI Suc_pred' add_gr_0) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply(clarify) apply(case_tac "e=f") apply(subgoal_tac "\<forall>i.(ownB s i = Q \<and> i\<le>N)\<longrightarrow>i<b") prefer 2 apply (metis (no_types, hide_lams) F.distinct(11) F.distinct(19) F.distinct(21) F.distinct(23) F.distinct(3) Suc_pred bot_nat_0.not_eq_extremum diff_Suc_Suc diff_diff_cancel diff_is_0_eq old.nat.inject zero_less_Suc zero_less_diff) apply(subgoal_tac "\<forall>a b j.((a,b)\<in>set(q s) \<and> a\<le>j \<and> j<a+b)\<longrightarrow>ownB s j = Q") prefer 2 apply (metis (no_types, lifting) mem_Collect_eq) apply(subgoal_tac "\<forall>a b j.((a,b)\<in>set(q s) \<and> a\<le>j \<and> j\<le>a+b-1)\<longrightarrow>ownB s j = Q") prefer 2 apply (metis Suc_diff_1 add_gr_0 le_imp_less_Suc) apply(subgoal_tac "\<forall>i. i<length(q s) \<longrightarrow> (q s!i) \<in> set(q s)") prefer 2 apply (metis nth_mem) apply(subgoal_tac "fst(q s!i)< fst(q s!i) + snd(q s!i)") prefer 2 apply (metis less_add_same_cancel1 prod.collapse) apply(subgoal_tac "\<forall>a b. (a,b)\<in>set(q s) \<longrightarrow> b>0") prefer 2 apply blast apply(subgoal_tac "\<forall>a b.((a,b)\<in>set(q s))\<longrightarrow>a\<le>a+b-1 \<and> a+b-1\<le>a+b") prefer 2 apply (metis Suc_diff_1 add_gr_0 diff_le_self less_Suc_eq_le less_add_same_cancel1) apply(subgoal_tac "\<forall>a b. (a,b)\<in>set(q s) \<longrightarrow> ownB s (a+b-1) = Q") prefer 2 apply (metis (no_types, hide_lams) Nat.add_0_right le_refl nat_add_left_cancel_less) apply(subgoal_tac "\<forall>i. (i<length(q s)) \<longrightarrow> (\<exists>a b. ((a,b)\<in>set(q s) \<and> a=fst(q s!i) \<and> b = snd(q s!i)))") prefer 2 apply (metis prod.collapse) apply(subgoal_tac "\<forall>i. i<length(q s) \<longrightarrow> ownB s (fst(q s!i)+snd(q s!i)-1) = Q") prefer 2 apply (metis (no_types, lifting)) apply(subgoal_tac "\<forall>i.(i<length(q s) \<and> fst(q s!i)+snd(q s!i)-1 \<le> N)\<longrightarrow> fst(q s!i)+snd(q s!i)-1<b") prefer 2 apply (metis (no_types, lifting)) apply(subgoal_tac "fst(q s!i) + snd(q s!i)\<le>N") prefer 2 apply (metis less_add_same_cancel1 prod.collapse) apply(subgoal_tac "fst(q s!i) + snd(q s!i)-1\<le>N") prefer 2 apply linarith apply(subgoal_tac "i<length(q s)") prefer 2 apply blast apply(subgoal_tac "fst(q s!i)+snd(q s!i)-1<b") prefer 2 apply (metis (no_types, lifting)) apply (metis Suc_leI diff_Suc_1 le_trans less_natE) apply(case_tac "fst(q s!i) > hW s") apply linarith apply(subgoal_tac "\<forall>a b j.((a,b)\<in>set(q s) \<and> a\<le>j \<and> j<a+b)\<longrightarrow>ownB s j = Q") prefer 2 apply (metis (no_types, lifting) mem_Collect_eq) apply(subgoal_tac "\<forall>a b j.((a,b)\<in>set(q s) \<and> a\<le>j \<and> j\<le>a+b-1)\<longrightarrow>ownB s j = Q") prefer 2 apply (metis Suc_pred' add_gr_0 le_imp_less_Suc) apply(subgoal_tac "\<forall>i. i<length(q s) \<longrightarrow> (q s!i) \<in> set(q s)") prefer 2 apply (metis nth_mem) apply(subgoal_tac "fst(q s!i)< fst(q s!i) + snd(q s!i)") prefer 2 apply (metis less_add_same_cancel1 prod.collapse) apply(subgoal_tac "\<forall>a b. (a,b)\<in>set(q s) \<longrightarrow> ownB s (a) = Q") prefer 2 apply (metis (no_types, hide_lams) Nat.add_0_right le_refl nat_add_left_cancel_less) apply(subgoal_tac "\<forall>a b. (a,b)\<in>set(q s) \<longrightarrow> b>0") prefer 2 apply meson apply(subgoal_tac "\<forall>a b.((a,b)\<in>set(q s))\<longrightarrow>a\<le>a+b-1\<and> a+b-1\<le>a+b-1") prefer 2 apply (metis Suc_diff_1 add_gr_0 le_eq_less_or_eq less_Suc_eq_le less_add_same_cancel1) apply(subgoal_tac "\<forall>a b j.((a,b)\<in>set(q s))\<longrightarrow>ownB s (a+b-1) = Q") prefer 2 apply (metis (no_types, lifting)) apply(subgoal_tac "\<forall>i. (i<length(q s)) \<longrightarrow> (\<exists>a b. ((a,b)\<in>set(q s) \<and> a=fst(q s!i) \<and> b = snd(q s!i)))") prefer 2 apply (metis prod.collapse) apply(subgoal_tac "\<forall>i. i<length(q s) \<longrightarrow> ownB s (fst(q s!i)+snd(q s!i)-1) = Q") prefer 2 apply (metis (no_types, hide_lams)) apply(subgoal_tac "fst(q s!i) + snd(q s!i)\<le>N") prefer 2 apply (metis less_add_same_cancel1 prod.collapse) apply(subgoal_tac "fst(q s!i) < hW s") prefer 2 apply blast by (metis (no_types, hide_lams) F.distinct(19) diff_is_0_eq' less_nat_zero_code linorder_neqE_nat nat_le_linear zero_less_diff) lemma W_local_A5_lemma: assumes "inv s" and "con_assms s" and "pcW s = A5" and "pre_W (pcW s) s" and "cW_step (pcW s) s s'" shows "pre_W (pcW s') s'" using assms apply simp apply(simp add:inv_def pre_W_def cW_step_def pre_A5_inv_def pre_write_inv_def) apply(case_tac "Data s (numEnqs s) \<le> N - hW s", simp_all) apply(simp_all add: pre_A6_inv_def) apply(case_tac "Data s (numEnqs s) < tW s", simp_all) apply(simp_all add: pre_A7_inv_def) by(simp_all add: pre_A8_inv_def) lemma W_local_A6_lemma: assumes "inv s" and "con_assms s" and "pcW s = A6" and "pre_W (pcW s) s" and "cW_step (pcW s) s s'" shows "pre_W (pcW s') s'" using assms apply simp apply(simp add:cW_step_def pre_W_def) apply(simp add:inv_def pre_A6_inv_def) apply(subgoal_tac "H s\<ge>T s") prefer 2 apply meson apply(subgoal_tac "\<not>case_2 s") prefer 2 apply (metis case_split_2) apply(subgoal_tac "case_1 s") prefer 2 apply blast apply(thin_tac "\<not>case_2 s") apply(simp add:pre_write_inv_def) apply(simp add:tempW_lemmas tempW_basic_lemmas) apply(intro conjI impI) apply (metis Nat.le_diff_conv2 add.commute) apply(simp add:case_1_def) apply (metis cancel_comm_monoid_add_class.diff_cancel le_eq_less_or_eq le_zero_eq length_0_conv) apply (metis (no_types, hide_lams) F.distinct(19) Q_owns_bytes_def diff_self_eq_0 le_eq_less_or_eq less_nat_zero_code ran_indices_lem5) apply(simp add:case_1_def) defer apply(simp add:case_1_def) apply (metis (no_types, lifting) cancel_comm_monoid_add_class.diff_cancel le_eq_less_or_eq le_zero_eq length_0_conv trans_le_add1) apply(simp add:Q_lemmas Q_basic_lemmas) apply(simp add:Q_indices_def Q_owns_bytes_def ran_indices_def) apply(subgoal_tac "hW s = H s") prefer 2 apply presburger apply(clarify) apply(intro conjI impI) apply(subgoal_tac "\<forall>i.(ownB s i = Q \<and> i\<le>N)\<longrightarrow>i<c") prefer 2 apply (metis (no_types, lifting) F.distinct(19) F.distinct(23) le_eq_less_or_eq linorder_neqE_nat) apply(subgoal_tac "\<forall>a b j.((a,b)\<in>set(q s)\<and>a \<le> j \<and> j<a+b ) \<longrightarrow> ownB s j = Q") prefer 2 apply (metis (no_types, lifting) mem_Collect_eq) apply(subgoal_tac "\<forall>a b.(a,b)\<in>set(q s) \<longrightarrow> ownB s (a) = Q") prefer 2 apply (metis (no_types, hide_lams) Nat.add_0_right le_refl nat_add_left_cancel_less) apply(subgoal_tac "\<forall>a b.(a,b)\<in>set(q s) \<longrightarrow> a<N") prefer 2 apply (metis F.distinct(23) add_leD1 nat_less_le) apply(subgoal_tac "\<forall>a b.(a,b)\<in>set(q s) \<longrightarrow> a<hW s") apply (metis (no_types, lifting) le_eq_less_or_eq nth_mem prod.collapse) apply (metis le_neq_implies_less less_or_eq_imp_le) apply(subgoal_tac "\<forall>i.(ownB s i = Q \<and> i\<le>N)\<longrightarrow>i<c") prefer 2 apply (metis (no_types, lifting) F.distinct(19) F.distinct(23) le_eq_less_or_eq linorder_neqE_nat) apply(subgoal_tac "\<forall>a b j.((a,b)\<in>set(q s)\<and>a \<le> j \<and> j<a+b ) \<longrightarrow> ownB s j = Q") prefer 2 apply (metis (no_types, lifting) mem_Collect_eq) apply(subgoal_tac "\<forall>a b.(a,b)\<in>set(q s)\<longrightarrow>a \<le> a+b-1 \<and> a+b-1<a+b") prefer 2 apply (metis Suc_diff_1 add_gr_0 diff_less less_Suc_eq_le less_add_same_cancel1 less_one) apply(subgoal_tac "\<forall>a b.(a,b)\<in>set(q s) \<longrightarrow> ownB s (a+b-1) = Q") prefer 2 apply (metis (no_types, lifting)) apply(subgoal_tac "\<exists>a b.((a,b)\<in>set(q s) \<and> a=fst(q s!i) \<and> b=Data s (numDeqs s + i))") prefer 2 apply (metis nth_mem prod.collapse) by (metis (no_types, hide_lams) diff_is_0_eq' linorder_neqE_nat nat_le_linear zero_less_diff) lemma W_local_A7_lemma: assumes "inv s" and "con_assms s" and "pcW s = A7" and "pre_W (pcW s) s" and "cW_step (pcW s) s s'" shows "pre_W (pcW s') s'" using assms apply simp apply(simp add:cW_step_def pre_W_def) apply(simp add:inv_def pre_A7_inv_def) apply(subgoal_tac "H s\<ge>T s") prefer 2 apply meson apply(subgoal_tac "\<not>case_2 s") prefer 2 apply (metis case_split_2) apply(subgoal_tac "case_1 s") prefer 2 apply blast apply(thin_tac "\<not>case_2 s") apply(simp add:pre_write_inv_def) apply(simp add:tempW_lemmas tempW_basic_lemmas) apply(intro conjI impI) apply (metis (no_types, hide_lams) F.distinct(19) Q_owns_bytes_def bot_nat_0.not_eq_extremum less_nat_zero_code ran_indices_lem5) apply(simp add:case_1_def) defer apply(simp add:case_1_def) apply (metis F.distinct(19) cancel_comm_monoid_add_class.diff_cancel diff_is_0_eq le_neq_implies_less le_zero_eq length_0_conv) apply(simp add:Q_lemmas Q_basic_lemmas) apply(simp add:Q_indices_def Q_owns_bytes_def ran_indices_def) apply(subgoal_tac "hW s = H s") prefer 2 apply presburger apply(clarify) apply(subgoal_tac "\<forall>i.(ownB s i = Q \<and> i\<le>N)\<longrightarrow>i\<ge>b") prefer 2 apply (metis (no_types, hide_lams) F.distinct(11) F.distinct(19) diff_is_0_eq' linorder_neqE_nat nat_le_linear zero_less_diff) apply(subgoal_tac "\<forall>a b j.((a,b)\<in>set(q s)\<and>a \<le> j \<and> j<a+b ) \<longrightarrow> ownB s j = Q") prefer 2 apply (metis (no_types, lifting) mem_Collect_eq) apply(subgoal_tac "\<forall>a b.(a,b)\<in>set(q s) \<longrightarrow> ownB s (a) = Q") prefer 2 apply (metis (no_types, hide_lams) Nat.add_0_right le_refl nat_add_left_cancel_less) apply(subgoal_tac "\<forall>a b.(a,b)\<in>set(q s) \<longrightarrow> a<N") prefer 2 apply (metis F.distinct(23) add_leD1 nat_less_le) apply(subgoal_tac "\<forall>i.(i\<le>Data s (numEnqs s))\<longrightarrow>ownB s i = B") prefer 2 apply (metis add_lessD1 nat_le_iff_add) apply(subgoal_tac "\<forall>a b.(a,b)\<in>set(q s) \<longrightarrow> a>Data s (numEnqs s)") prefer 2 apply (metis F.distinct(19) Suc_le_lessD not_less_eq_eq) by (metis nth_mem prod.collapse) lemma W_local_A8_lemma: assumes "inv s" and "con_assms s" and "pcW s = A8" and "pre_W (pcW s) s" and "cW_step (pcW s) s s'" shows "pre_W (pcW s') s'" using assms apply simp apply(simp add:cW_step_def pre_W_def) apply(simp add:inv_def pre_A8_inv_def) apply(case_tac "N < Data s (numEnqs s)") apply (metis leD) apply(intro conjI impI) apply linarith apply(simp add:pre_OOM_inv_def) apply(intro conjI impI) defer apply(case_tac "case_1 s") apply simp apply(simp add:case_1_def) apply metis apply meson apply(case_tac "case_1 s") apply simp apply(simp add:case_1_def) apply metis apply(simp add:case_2_def) by (metis le_antisym less_or_eq_imp_le) lemma W_local_Enqueue_lemma: assumes "inv s" and "con_assms s" and "pcW s = Enqueue" and "pre_W (pcW s) s" and "cW_step (pcW s) s s'" shows "pre_W (pcW s') s'" using assms apply simp apply(simp add:cW_step_def pre_W_def) apply(simp add:inv_def pre_enqueue_inv_def) apply(intro conjI impI) apply(simp add:pre_acquire_inv_def) apply(intro conjI impI) apply(case_tac "case_1 s") apply(simp) apply(simp add:case_1_def) apply(simp add:tempW_lemmas tempW_basic_lemmas) apply (metis F.distinct(5) eq_imp_le less_add_same_cancel1) apply(subgoal_tac "case_2 s") prefer 2 apply blast apply(thin_tac "\<not>case_1 s") apply(simp add:case_2_def) apply(simp add:tempW_lemmas tempW_basic_lemmas) apply clarify apply(intro conjI impI) apply(case_tac "case_1 s") apply(simp) apply(simp add:case_1_def) apply(subgoal_tac "case_2 s") prefer 2 apply blast apply(simp) apply(thin_tac "\<not>case_1 s") apply(simp add:case_2_def) apply(case_tac "case_1 s") apply(simp) apply(simp add:case_1_def) apply(subgoal_tac "case_2 s") prefer 2 apply blast apply(simp) apply(thin_tac "\<not>case_1 s") apply(simp add:case_2_def) apply(case_tac "case_1 s") apply(simp) apply(simp add:case_1_def) apply (metis add_cancel_left_left less_imp_le_nat old.prod.inject prod.collapse tempW_def) apply(subgoal_tac "case_2 s") prefer 2 apply blast apply(simp) apply(thin_tac "\<not>case_1 s") apply(simp add:case_2_def) apply(simp add:pre_acquire_inv_def) apply(intro conjI impI) apply(case_tac "case_1 s") apply(simp) apply(simp add:case_1_def) apply(simp add:tempW_lemmas tempW_basic_lemmas) apply (metis F.distinct(5) le_eq_less_or_eq less_add_same_cancel1) apply(subgoal_tac "case_2 s") prefer 2 apply blast apply(simp) apply(thin_tac "\<not>case_1 s") apply(simp add:case_2_def) apply (metis F.distinct(5) le_eq_less_or_eq less_add_same_cancel1) apply(case_tac "case_1 s") apply(simp) apply(simp add:case_1_def) apply(simp add:tempW_lemmas tempW_basic_lemmas) apply (metis F.distinct(5) le_eq_less_or_eq less_add_same_cancel1) apply(subgoal_tac "case_2 s") prefer 2 apply blast apply(simp) apply(thin_tac "\<not>case_1 s") apply(simp add:case_2_def) apply (metis F.distinct(5) le_eq_less_or_eq less_add_same_cancel1) apply(case_tac "case_1 s") apply(simp) apply(simp add:case_1_def) apply(simp add:tempW_lemmas tempW_basic_lemmas) apply (metis F.distinct(5) le_eq_less_or_eq less_add_same_cancel1) apply(subgoal_tac "case_2 s") prefer 2 apply blast apply(simp) apply(thin_tac "\<not>case_1 s") apply(simp add:case_2_def) by (metis Suc_diff_Suc Zero_not_Suc diff_is_0_eq' less_or_eq_imp_le) lemma W_local_idleW_lemma: assumes "inv s" and "con_assms s" and "pcW s = idleW" and "pre_W (pcW s) s" and "cW_step (pcW s) s s'" shows "pre_W (pcW s') s'" using assms apply simp apply(simp add:cW_step_def pre_W_def) apply(simp add:inv_def pre_acquire_inv_def) apply(case_tac " numEnqs s < n", simp_all) apply(simp add: pre_A1_inv_def) apply blast by(simp add: pre_finished_inv_def) lemma W_local_OOM_lemma: assumes "inv s" and "con_assms s" and "pcW s = OOM" and "pre_W (pcW s) s" and "cW_step (pcW s) s s'" shows "pre_W (pcW s') s'" using assms apply simp apply(simp add:cW_step_def pre_W_def) apply(simp add:inv_def pre_OOM_inv_def) apply(case_tac "tW s \<noteq> T s", simp_all) apply(simp add:inv_def pre_acquire_inv_def) apply(case_tac "case_1 s") apply(simp ) apply(simp add:case_1_def) apply(intro conjI impI) apply (metis eq_imp_le less_imp_le_nat linorder_neqE_nat) apply (metis le_neq_implies_less le_refl) apply (metis diff_self_eq_0 le_neq_implies_less le_refl le_zero_eq length_0_conv) apply (metis diff_self_eq_0 le_antisym le_refl nat_less_le zero_less_diff) apply metis apply metis apply(simp add:case_2_def) apply(intro conjI impI) apply (metis) apply (metis) apply (metis) apply (metis) apply metis apply (metis le_antisym nat_less_le) apply(simp add:pre_OOM_inv_def) by blast lemma W_local_FinishedW_lemma: assumes "inv s" and "con_assms s" and "pcW s = FinishedW" and "pre_W (pcW s) s" and "cW_step (pcW s) s s'" shows "pre_W (pcW s') s'" using assms apply simp by(simp add:cW_step_def pre_W_def) lemma W_local_Write_lemma: assumes "inv s" and "con_assms s" and "pcW s = Write" and "pre_W (pcW s) s" and "cW_step (pcW s) s s'" shows "pre_W (pcW s') s'" using assms apply simp apply(simp add:pre_W_def cW_step_def) apply(simp add:inv_def pre_write_inv_def) apply(simp add:pre_enqueue_inv_def) apply(intro conjI impI) apply clarify apply(case_tac "case_1 s") apply(simp) apply(simp add:case_1_def) apply(simp add:tempW_lemmas tempW_basic_lemmas) apply(subgoal_tac "case_2 s") prefer 2 apply blast apply(simp) apply(thin_tac "\<not>case_1 s") apply(simp add:case_2_def) apply(simp add:tempW_lemmas tempW_basic_lemmas) apply(case_tac "case_1 s") apply(simp) apply(simp add:case_1_def) apply(simp add:tempW_lemmas tempW_basic_lemmas) apply clarify apply(intro conjI impI) apply(subgoal_tac "i<T s\<longrightarrow>ownB s i=B") prefer 2 apply metis apply(subgoal_tac "T s\<le>i \<and> i<b\<longrightarrow>ownB s i = R") prefer 2 apply metis apply(subgoal_tac "b\<le>i \<and> i<c\<longrightarrow>ownB s i = Q") prefer 2 apply metis apply (metis (mono_tags, lifting) F.distinct(1) F.distinct(3) F.distinct(5) Suc_le_lessD le_eq_less_or_eq not_less_eq_eq trans_less_add1) apply(subgoal_tac "end(tempW s)\<le>i \<and> i<N\<longrightarrow> ownB s i = B") prefer 2 apply metis apply (metis F.distinct(5) F.distinct(9) le_neq_implies_less) apply(subgoal_tac "case_2 s") prefer 2 apply blast apply(simp) apply(thin_tac "\<not>case_1 s") apply(simp add:case_2_def) apply(simp add:tempW_lemmas tempW_basic_lemmas) apply(clarify) apply(intro conjI impI) apply (metis F.distinct(1) F.distinct(3) eq_imp_le linorder_neqE_nat nat_less_le trans_less_add1) apply (metis F.distinct(1) F.distinct(3) F.distinct(5) F.distinct(7) F.distinct(9) le_neq_implies_less less_or_eq_imp_le linorder_neqE_nat) apply(case_tac "case_1 s") apply(simp) apply(simp add:case_1_def) apply(simp add:tempW_lemmas tempW_basic_lemmas) apply(subgoal_tac "case_2 s") prefer 2 apply blast apply(simp) apply(thin_tac "\<not>case_1 s") apply(simp add:case_2_def) apply(simp add:tempW_lemmas tempW_basic_lemmas) apply(case_tac "case_1 s") apply(simp add:case_1_def) apply(simp add:tempW_lemmas tempW_basic_lemmas) apply(subgoal_tac "case_2 s") prefer 2 apply blast apply(simp) apply(thin_tac "\<not>case_1 s") apply(simp add:case_2_def) apply(simp add:tempW_lemmas tempW_basic_lemmas) apply(case_tac "case_1 s") apply(simp add:case_1_def) apply(simp add:tempW_lemmas tempW_basic_lemmas) apply(subgoal_tac "case_2 s") prefer 2 apply blast apply(simp) apply(thin_tac "\<not>case_1 s") apply(simp add:case_2_def) apply(simp add:tempW_lemmas tempW_basic_lemmas) apply(case_tac "case_1 s") apply(simp add:case_1_def) apply(simp add:tempW_lemmas tempW_basic_lemmas) apply (metis bot_nat_0.extremum_unique diff_is_0_eq le_trans length_0_conv) apply(subgoal_tac "case_2 s") prefer 2 apply blast apply(simp) apply(thin_tac "\<not>case_1 s") apply(simp add:case_2_def) apply(simp add:tempW_lemmas tempW_basic_lemmas) by(simp add:tempW_lemmas tempW_basic_lemmas) lemma W_local_BTS_lemma: assumes "inv s" and "con_assms s" and "pcW s = BTS" and "pre_W (pcW s) s" and "cW_step (pcW s) s s'" shows "pre_W (pcW s') s'" using assms apply simp by(simp add:cW_step_def pre_W_def) lemma local_pre_W_pre: assumes "con_assms s" and "pcw = pcW s" and "pre_W pcw s" and "inv s" and "cW_step pcw s s'" shows "pre_W (pcW s') s'" using assms apply(case_tac "pcW s") using W_local_A1_lemma [where s=s and s'=s'] apply blast using W_local_A2_lemma [where s=s and s'=s'] apply blast using W_local_A3_lemma [where s=s and s'=s'] apply blast using W_local_A4_lemma [where s=s and s'=s'] apply blast using W_local_A5_lemma [where s=s and s'=s'] apply blast using W_local_A6_lemma [where s=s and s'=s'] apply blast using W_local_A7_lemma [where s=s and s'=s'] apply blast using W_local_A8_lemma [where s=s and s'=s'] apply blast using W_local_Enqueue_lemma [where s=s and s'=s'] apply blast using W_local_idleW_lemma [where s=s and s'=s'] apply blast using W_local_OOM_lemma [where s=s and s'=s'] apply blast using W_local_FinishedW_lemma [where s=s and s'=s'] apply blast using W_local_Write_lemma [where s=s and s'=s'] apply blast using W_local_BTS_lemma [where s=s and s'=s'] by blast (**********************Supporting lemmas for R trans*********************************) lemma R_idle_to_nidle_lemma_case_1_1: "case_1 s\<Longrightarrow>con_assms s \<Longrightarrow> pcR s = idleR\<Longrightarrow>pre_R (pcR s) s \<Longrightarrow>s'=(s\<lparr>ownB := \<lambda>i. if fst (hd (q s)) \<le> i \<and> i < fst (hd (q s)) + snd (hd (q s)) then R else ownB s i, numDeqs := Suc (numDeqs s), ownT := R, tempR := hd (q s), pcR := Read, q := tl (q s)\<rparr>) \<Longrightarrow>inv s \<Longrightarrow>i<fst(hd(q s))\<longrightarrow>ownB s i=ownB s' i" by(simp add:case_1_def) lemma R_idle_to_nidle_lemma_case_1_2: "case_1 s\<Longrightarrow>con_assms s \<Longrightarrow> pcR s = idleR\<Longrightarrow>pre_R (pcR s) s \<Longrightarrow>s'=(s\<lparr>ownB := \<lambda>i. if fst (hd (q s)) \<le> i \<and> i < fst (hd (q s)) + snd (hd (q s)) then R else ownB s i, numDeqs := Suc (numDeqs s), ownT := R, tempR := hd (q s), pcR := Read, q := tl (q s)\<rparr>) \<Longrightarrow>inv s \<Longrightarrow>i>end(hd(q s))\<longrightarrow>ownB s i=ownB s' i" by(simp add:case_1_def) lemma R_idle_to_nidle_lemma_case_1_3: "case_1 s\<Longrightarrow>con_assms s \<Longrightarrow> pcR s = idleR\<Longrightarrow>pre_R (pcR s) s \<Longrightarrow>s'=(s\<lparr>ownB := \<lambda>i. if fst (hd (q s)) \<le> i \<and> i < fst (hd (q s)) + snd (hd (q s)) then R else ownB s i, numDeqs := Suc (numDeqs s), ownT := R, tempR := hd (q s), pcR := Read, q := tl (q s)\<rparr>) \<Longrightarrow>inv s \<Longrightarrow>fst(hd(q s))\<le>i \<and> i<end(hd(q s))\<longrightarrow>R=ownB s' i" by(simp add:case_1_def) lemma R_idle_to_nidle_lemma_case_1_4: "case_1 s\<Longrightarrow>con_assms s \<Longrightarrow> pcR s = idleR\<Longrightarrow>pre_R (pcR s) s \<Longrightarrow>s'=(s\<lparr>ownB := \<lambda>i. if fst (hd (q s)) \<le> i \<and> i < fst (hd (q s)) + snd (hd (q s)) then R else ownB s i, numDeqs := Suc (numDeqs s), ownT := R, tempR := hd (q s), pcR := Read, q := tl (q s)\<rparr>) \<Longrightarrow>inv s \<Longrightarrow>T s=T s'\<and>H s=H s'\<and>offset s=offset s'\<and>ownT s'=R" by(simp add:case_1_def) lemma sum_of_things: "q s!0 = (2,3) \<Longrightarrow> (length(q s) = 1)\<longrightarrow>\<Sum>{j. j=(snd(q s!0))} = 3" by simp lemma sum_of_things_2: "q s=[(0,1)] \<Longrightarrow> length(q s) = 1" by simp lemma sum_of_things_3: " length(q s)>0 \<Longrightarrow> \<forall>i. i<length(q s) \<longrightarrow> snd(q s!i) =1\<Longrightarrow> (\<Sum>i::nat=0..length(q s)-1. 1) = length(q s)" by auto lemma sum_of_things_4: " length(q s)>1 \<Longrightarrow> \<forall>i. i<length(q s) \<longrightarrow> snd(q s!i) =1\<Longrightarrow> (\<Sum>i::nat=0..(length(q s)-1). snd(q s!i)) = length(q s)" by auto lemma sum_of_things_5: "n>0\<Longrightarrow> (\<Sum>i::nat=0..n. k) = (\<Sum>i::nat=1..n. k) + k " proof (induct n) show "0 = n \<Longrightarrow> 0 < n \<Longrightarrow> (\<Sum>i = 0..n. k) = (\<Sum>i = 1..n. k) + k" by simp next show "\<And>x. (x = n \<Longrightarrow> 0 < n \<Longrightarrow> (\<Sum>i = 0..n. k) = (\<Sum>i = 1..n. k) + k) \<Longrightarrow> Suc x = n \<Longrightarrow> 0 < n \<Longrightarrow> (\<Sum>i = 0..n. k) = (\<Sum>i = 1..n. k) + k" by (metis add.commute add_diff_cancel_left' le_add1 plus_1_eq_Suc sum.atLeast0_atMost_Suc_shift sum.atLeastAtMost_shift_0) qed lemma sum_of_things_6: "length(q s) =n+2\<Longrightarrow> (\<Sum>i::nat=0..(length(q s)-1). 1) = (\<Sum>i::nat=1..(length(q s)-1). 1) + 1 " apply auto proof (induct n) case 0 then show ?case by simp next case (Suc x) then show ?case by (metis add.commute add.right_neutral nat.distinct(1) not_gr_zero plus_1_eq_Suc sum_of_things_5) qed lemma sum_of_things_7: "length(q s) =n+2\<Longrightarrow> \<forall>i. (i<length(q s)) \<longrightarrow> snd(q s!i) =1\<Longrightarrow> (\<Sum>i::nat=0..(length(q s)-1). snd(q s!i)) = (\<Sum>i::nat=1..(length(q s)-1). snd(q s!i)) + snd(q s!0) " by auto lemma sum_of_things_8: "length(q s) =n+2\<Longrightarrow> (\<Sum>i::nat=0..(length(q s)-1). snd(q s!i)) = (\<Sum>i::nat=1..(length(q s)-1). snd(q s!i)) + snd(q s!0) " apply auto proof (induct n) case 0 then show ?case by auto next case (Suc x) then show ?case by (simp add: sum.atLeast_Suc_atMost) qed lemma sum_of_things_9: " length(q s)=n+2 \<Longrightarrow> \<forall>i. (i<length(q s) \<and> i>0) \<longrightarrow> snd(q s!i) =1\<Longrightarrow> (\<Sum>i::nat=0..(length(q s)-1). snd(q s!i)) = (\<Sum>i::nat=1..(length(q s)-1). snd(q s!i)) + snd(q s!0) " apply auto proof (induct n) case 0 then show ?case by auto next case (Suc x) then show ?case by (simp add: sum.atLeast_Suc_atMost) qed lemma sum_of_things_10: " length(q s)\<ge>2 \<Longrightarrow> \<forall>i. (i<length(q s) \<and> i>0) \<longrightarrow> snd(q s!i) =1\<Longrightarrow> (\<Sum>i::nat=0..(length(q s)-1). snd(q s!i)) = (\<Sum>i::nat=1..(length(q s)-1). snd(q s!i)) + snd(q s!0) " apply auto by (metis add.commute sum.atLeast_Suc_atMost zero_le) lemma sum_of_things_11: " length(q s) = n+2 \<Longrightarrow> \<forall>i. (i<length(q s) \<and> i>0) \<longrightarrow> snd(q s!i) =1\<Longrightarrow> (\<Sum>i::nat=0..(length(q s)-1). snd(q s!i)) = length(q s)-1 + snd(q s!0) " apply auto proof (induct n) case 0 then show ?case by auto next case (Suc x) then show ?case by (simp add: sum.atLeast_Suc_atMost) qed lemma sum_of_things_12: " length(q s) = n+2 \<Longrightarrow> \<forall>i. (i<length(q s) \<and> i>0) \<longrightarrow> snd(q s!i) =1\<Longrightarrow> (\<Sum>i::nat=1..(length(q s)-1). snd(q s!i)) = length(q s)-1 " by auto lemma sum_of_things_13: " \<forall>n.(n\<ge>0) \<longrightarrow>length(q s) = n+2 \<Longrightarrow> \<forall>i. (i<length(q s) \<and> i>0) \<longrightarrow> snd(q s!i) =1\<Longrightarrow> (\<Sum>i::nat=1..(length(q s)-1). snd(q s!i)) = length(q s)-1 " using sum_of_things_12 [where s=s] by blast lemma sum_of_things_14: " \<forall>k.(k\<ge>2)\<longrightarrow>length(q s) = k \<Longrightarrow> \<forall>i. (i<length(q s) \<and> i>0) \<longrightarrow> snd(q s!i) =1\<Longrightarrow> (\<Sum>i::nat=1..(length(q s)-1). snd(q s!i)) = length(q s)-1 " using sum_of_things_13 [where s=s] using le_add2 by blast lemma R_idle_to_nidle_lemma_case_1_5_preliminary: "case_1 s\<Longrightarrow>con_assms s \<Longrightarrow> pcR s = idleR\<Longrightarrow>pre_R (pcR s) s \<Longrightarrow>inv s \<Longrightarrow>q s\<noteq>[] \<Longrightarrow> tl(q s)\<noteq>[] \<Longrightarrow>length (q s) - Suc 0 \<le> end(last(q s)) - end(hd (q s))" apply(simp add:inv_def Q_lemmas Q_basic_lemmas) apply(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) apply(simp add:pre_R_def pre_dequeue_inv_def) apply(simp add:case_1_def) apply clarify apply(subgoal_tac "i<length(q s) \<and> j<length(q s) \<and> fst(q s!j)>fst(q s!i)\<longrightarrow> fst(q s!j)\<ge>end(q s!i)") prefer 2 apply (metis (no_types, lifting) end_simp nth_mem prod.collapse) apply(subgoal_tac "\<nexists>i.(ownB s i = Q \<and> i<b)") prefer 2 apply (metis F.distinct(19) le_neq_implies_less) apply(subgoal_tac "\<forall>a b j. ((a,b)\<in>set(q s) \<and> j\<ge>a \<and> j<a+b) \<longrightarrow> ownB s (j) = Q") prefer 2 apply (metis (no_types, lifting) mem_Collect_eq) apply(subgoal_tac "\<forall>a b j. ((a,b)\<in>set(q s) \<and> j=a ) \<longrightarrow> ownB s (j) = Q") prefer 2 apply (metis (no_types, hide_lams) Nat.add_0_right le_refl nat_add_left_cancel_less) apply(subgoal_tac "\<forall>a b.(a,b)\<in>set(q s) \<longrightarrow> (\<exists>i.(i<length(q s) \<and> fst(q s!i) = a))") prefer 2 apply (metis fst_conv in_set_conv_nth) apply(subgoal_tac "(i<length(q s)) \<longrightarrow> ownB s (fst(q s!i)) =Q") prefer 2 apply (metis nth_mem prod.collapse) apply(subgoal_tac "i<length(q s) \<and> i>0 \<longrightarrow> fst(q s!0) < fst(q s!i)") prefer 2 apply (metis (no_types, lifting) Q_ind_imp_tail_ind_1 diff_self_eq_0 le_0_eq le_eq_less_or_eq nat_neq_iff) apply(subgoal_tac "i<length(q s) \<and> i>0 \<longrightarrow> end(q s!0) \<le> fst(q s!i)") prefer 2 apply (metis (no_types, lifting) Q_ind_imp_tail_ind_1 end_simp list.set_sel(1) nth_mem prod.collapse) apply(subgoal_tac "length(q s)>1") prefer 2 apply (metis Suc_le_eq diff_is_0_eq length_0_conv length_tl not_less_eq_eq) apply(subgoal_tac "\<forall>i.(i<length(q s)) \<longrightarrow> ownB s (fst(q s!i)) = Q") prefer 2 apply (metis nth_mem prod.collapse) apply(subgoal_tac "\<forall>i.(i<length(q s)\<and> i>0)\<longrightarrow>fst(q s!i)>fst(q s!0)") prefer 2 apply (metis (no_types, lifting) Q_ind_imp_tail_ind_1 diff_self_eq_0 le_neq_implies_less less_nat_zero_code linorder_neqE_nat) apply(subgoal_tac "\<forall>i.(i<length(q s)\<and> i>0)\<longrightarrow>fst(q s!i)\<ge>end(q s!0)") prefer 2 apply (metis (no_types, lifting) Q_ind_imp_tail_ind_1 end_simp list.set_sel(1) nth_mem prod.collapse) apply(subgoal_tac "i<length(q s) \<longrightarrow> ownB s (fst(q s!i)) = Q") prefer 2 apply blast (*split cases for ownB s 0 = Q and ownB s 0 \<noteq> Q*) apply(case_tac "b=0") apply(subgoal_tac "ownB s 0 = Q") prefer 2 apply (metis le_neq_implies_less less_nat_zero_code minus_nat.diff_0) apply(subgoal_tac "fst(q s!0) = 0") prefer 2 apply (metis F.distinct(3) Q_ind_imp_tail_ind_1 le_neq_implies_less) apply(subgoal_tac "\<forall>i. i < length (q s) \<and> 0 < i \<longrightarrow> fst (q s ! (i - Suc 0)) + snd (q s ! (i - Suc 0)) = fst (q s ! i)") prefer 2 apply (metis (no_types, lifting)) apply(thin_tac "\<forall>i. i < length (q s) \<and> 0 < i \<longrightarrow> fst (q s ! (i - Suc 0)) + snd (q s ! (i - Suc 0)) = fst (q s ! i) \<or>fst (q s ! i) = 0") sorry lemma R_idle_to_nidle_lemma_case_1_5: "case_1 s\<Longrightarrow>con_assms s \<Longrightarrow> pcR s = idleR\<Longrightarrow>pre_R (pcR s) s \<Longrightarrow>s'=(s\<lparr>ownB := \<lambda>i. if fst (hd (q s)) \<le> i \<and> i < fst (hd (q s)) + snd (hd (q s)) then R else ownB s i, numDeqs := Suc (numDeqs s), ownT := R, tempR := hd (q s), pcR := Read, q := tl (q s)\<rparr>) \<Longrightarrow>inv s \<Longrightarrow>q s\<noteq>[] \<Longrightarrow>case_1 s'" apply(simp add:case_1_def inv_def) apply(clarify) apply(intro conjI impI) apply(simp add:Q_lemmas Q_basic_lemmas) apply(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) apply(subgoal_tac "c\<le>N") prefer 2 apply linarith apply(subgoal_tac "q s\<noteq>[]\<longrightarrow>hd(q s) \<in>set(q s)") prefer 2 apply (metis list.set_sel(1)) apply(subgoal_tac "q s\<noteq>[]") prefer 2 apply blast apply (metis diff_is_0_eq less_nat_zero_code prod.collapse zero_less_diff) apply(simp add:Q_lemmas Q_basic_lemmas) apply(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) apply(rule_tac ?x = "T s" in exI) apply(rule_tac ?x = "end(hd(q s))" in exI) apply(intro conjI impI) apply (metis cancel_comm_monoid_add_class.diff_cancel end_simp le_0_eq le_neq_implies_less length_0_conv trans_le_add1) apply(rule_tac ?x = "c" in exI) apply(simp add:pre_R_def pre_dequeue_inv_def) apply(intro conjI impI) apply (metis (no_types, lifting) F.distinct(19) F.distinct(3) diff_is_0_eq le_0_eq le_neq_implies_less length_0_conv nat_le_linear) apply (metis Suc_leI diff_is_0_eq' le_0_eq le_neq_implies_less le_trans length_0_conv not_less_eq_eq) apply (metis (no_types, lifting) cancel_comm_monoid_add_class.diff_cancel end_simp le_0_eq le_neq_implies_less length_0_conv nat_le_linear) apply (metis diff_is_0_eq end_simp le_0_eq le_add1 le_eq_less_or_eq le_trans length_0_conv zero_less_diff) apply (metis (no_types, hide_lams) F.distinct(3)) apply (metis (no_types, hide_lams) F.distinct(19)) apply (metis diff_self_eq_0 le_0_eq le_eq_less_or_eq length_0_conv) apply (metis diff_add_inverse diff_self_eq_0 le_0_eq le_eq_less_or_eq length_0_conv) defer defer apply(subgoal_tac "i<(length(q s))\<and>i>0\<longrightarrow> fst(q s!(i-1)) + snd(q s!(i-1)) = fst(q s!i) \<or> fst(q s!i) = 0") prefer 2 apply (metis (no_types, lifting) One_nat_def) apply(subgoal_tac "T s \<ge> 0") prefer 2 apply blast apply(subgoal_tac "hd(tl(q s)) = q s!1") prefer 2 apply (metis (no_types, lifting) One_nat_def bot_nat_0.extremum_uniqueI diff_add_inverse2 diff_self_eq_0 hd_conv_nth last_conv_nth le_neq_implies_less length_greater_0_conv length_tl less_diff_conv list.size(3) nth_tl) apply(subgoal_tac "hd(q s) = q s!0") prefer 2 apply (metis hd_conv_nth) apply(case_tac "b = 0") apply(subgoal_tac "fst(hd(q s)) = 0") prefer 2 apply force apply(subgoal_tac "i<length(q s) \<and> j<length(q s) \<and> i\<noteq>j \<longrightarrow> fst(q s!i) \<noteq>fst(q s!j)") prefer 2 apply (metis (no_types, lifting)) apply(subgoal_tac "i<(length(q s))\<and>i>0\<and> fst(q s!0) = 0\<longrightarrow> fst(q s!(i-1)) + snd(q s!(i-1)) = fst(q s!i)") prefer 2 apply (metis (no_types, lifting) length_greater_0_conv) apply(case_tac "length(q s) > 1") apply(subgoal_tac "fst(q s!0) = 0\<longrightarrow> fst(q s!(0)) + snd(q s!(0)) = fst(q s!1)") prefer 2 apply (metis (no_types, lifting) One_nat_def diff_Suc_1 length_greater_0_conv less_one) apply presburger apply (metis diff_self_eq_0 last_conv_nth length_0_conv less_nat_zero_code less_one nat_neq_iff) apply(subgoal_tac "b>0") prefer 2 apply force apply(subgoal_tac "ownB s 0 \<noteq> Q") prefer 2 apply (metis F.distinct(19) le_neq_implies_less) apply(subgoal_tac " \<forall>i. (\<exists>x. (\<exists>a b. x = {i. a \<le> i \<and> i < a + b} \<and> (a, b) \<in> set (q s)) \<and> i \<in> x) = (i \<le> N \<and> ownB s i = Q)") prefer 2 apply blast apply(subgoal_tac "0\<le>N") prefer 2 apply blast apply(subgoal_tac "(\<nexists>x. (\<exists>a b. x = {i. a \<le> i \<and> i < a + b} \<and> (a, b) \<in> set (q s)) \<and> 0 \<in> x)") prefer 2 apply presburger apply(subgoal_tac "\<nexists>a b. (a,b) \<in> set(q s) \<and> a=0") prefer 2 apply (metis (no_types, lifting) bot_nat_0.extremum mem_Collect_eq plus_nat.add_0) apply(subgoal_tac "i<length(q s) \<longrightarrow> (q s!i) \<in> set(q s)") prefer 2 apply (metis nth_mem) apply(subgoal_tac "(sta,wlength)\<in>set(q s) \<longrightarrow> (\<exists>i.(i<length(q s) \<and> (sta,wlength) = q s!i))") prefer 2 apply (metis in_set_conv_nth) apply(subgoal_tac "\<forall>sta wlength. (sta,wlength)\<in>set(q s) \<longrightarrow> sta\<noteq>0") prefer 2 apply metis apply(subgoal_tac "i<length(q s) \<longrightarrow>fst(q s!i)\<noteq>0") prefer 2 apply (metis prod.collapse) apply(subgoal_tac "i<(length(q s))\<and>i>0\<longrightarrow> fst(q s!(i-1)) + snd(q s!(i-1)) = fst(q s!i)") prefer 2 apply (metis prod.collapse) apply(case_tac "length(q s)>1") apply (metis (no_types, lifting) One_nat_def diff_Suc_1 less_one nth_mem prod.collapse) apply(case_tac "length(q s) = 0") apply fastforce apply(subgoal_tac "length(q s) = 1") prefer 2 apply linarith apply(subgoal_tac "length(tl(q s)) = 0") prefer 2 apply (metis diff_self_eq_0 length_tl) apply (metis diff_self_eq_0 last_conv_nth le_neq_implies_less less_irrefl_nat not_one_le_zero) apply(case_tac "length(q s) \<le>1") apply (metis bot_nat_0.extremum_uniqueI diff_add_inverse2 diff_is_0_eq' head_q0 last_conv_nth le_neq_implies_less length_greater_0_conv less_diff_conv less_numeral_extra(3)) apply (metis (no_types, lifting) One_nat_def diff_is_0_eq last_tl le_Suc_eq le_neq_implies_less length_tl list.size(3)) apply (metis (no_types, lifting) diff_add_inverse diff_is_0_eq' le_0_eq le_eq_less_or_eq length_0_conv linorder_neqE_nat list.set_sel(1) nat_less_le not_add_less1 prod.collapse) apply (metis diff_add_inverse diff_is_0_eq' le_eq_less_or_eq less_nat_zero_code list.set_sel(1) prod.collapse) apply (metis diff_is_0_eq le_zero_eq length_0_conv) defer apply(subgoal_tac "i\<ge>end(hd(q s)) \<and> i<c \<longrightarrow> ownB s i = Q \<and> i\<le>N") prefer 2 apply (metis add_leD1 diff_self_eq_0 end_simp le_0_eq le_eq_less_or_eq le_trans length_0_conv) apply(subgoal_tac "\<forall>i. (\<exists>x. (\<exists>a b. x = {i. a \<le> i \<and> i < a + b} \<and> (a, b) \<in> set (q s)) \<and> i \<in> x) = (i \<le> N \<and> ownB s i = Q)") prefer 2 apply blast apply(subgoal_tac "ownB s (end(hd(q s))) = Q") prefer 2 apply (metis diff_self_eq_0 end_simp le_0_eq le_add1 le_eq_less_or_eq length_0_conv) (*difficult and time consuming, need help here*) apply(subgoal_tac "numEnqs s - numDeqs s >1") using One_nat_def apply presburger apply(case_tac "tl(q s) = []") apply (metis bot_nat_0.extremum_uniqueI diff_add_inverse2 diff_self_eq_0 hd_conv_nth last_conv_nth le_neq_implies_less length_0_conv length_tl less_diff_conv) apply (metis Suc_le_eq diff_is_0_eq length_0_conv length_tl not_less_eq_eq) apply(case_tac "tl(q s) = []") apply (metis Nitpick.size_list_simp(2) diff_0_eq_0 diff_Suc_Suc zero_le) apply(subgoal_tac "i\<ge>end(hd(q s)) \<and> i<c \<longrightarrow> ownB s i = Q \<and> i\<le>N") prefer 2 apply (metis add_leD1 diff_self_eq_0 end_simp le_0_eq le_eq_less_or_eq le_trans length_0_conv) apply(subgoal_tac "\<forall>i. (\<exists>x. (\<exists>a b. x = {i. a \<le> i \<and> i < a + b} \<and> (a, b) \<in> set (q s)) \<and> i \<in> x) = (i \<le> N \<and> ownB s i = Q)") prefer 2 apply blast (*difficult and time consuming, need help here*) apply(subgoal_tac "numEnqs s - numDeqs s >1") prefer 2 apply (metis Suc_le_eq diff_is_0_eq length_0_conv length_tl not_less_eq_eq) apply(subgoal_tac "hd(q s) \<in> set(q s) \<and> hd(q s) = (q s!0)") prefer 2 apply (metis Q_ind_imp_tail_ind_1 list.set_sel(1)) apply(subgoal_tac "\<forall>i.(i<length(q s) \<and> i>0) \<longrightarrow> end((q s)!(i-1)) = fst(q s!i) \<or> fst(q s!i) = 0") prefer 2 apply (metis (no_types, lifting) One_nat_def end_simp) apply(subgoal_tac "\<forall>i. (i\<le>N \<and> ownB s i = Q)\<longrightarrow> i\<ge>0") prefer 2 apply blast apply(case_tac "ownB s 0 = Q") apply(subgoal_tac "fst(q s!0) = 0") prefer 2 apply (metis F.distinct(19) bot_nat_0.not_eq_extremum diff_0_eq_0 le_eq_less_or_eq) apply(subgoal_tac "i<length(q s) \<and> i>0 \<longrightarrow> fst(q s!i) > 0") prefer 2 apply (metis (no_types, lifting) gr0I length_greater_0_conv) apply(subgoal_tac "(a,wlen)\<in>set(q s) \<and> (aa,bb)\<in>set(q s) \<and> aa>a\<longrightarrow> a+wlen\<le>aa") prefer 2 apply (metis (no_types, lifting)) apply(subgoal_tac "length(q s) = length(tl(q s)) + 1") prefer 2 apply (metis Nat.add_0_right One_nat_def Suc_diff_1 add_Suc_right length_pos_if_in_set length_tl) apply(subgoal_tac "tl(q s) \<noteq> []") prefer 2 apply blast apply(subgoal_tac "c = end(last(q s))") prefer 2 apply (metis diff_self_eq_0 end_simp le_neq_implies_less less_nat_zero_code) sorry lemma R_idle_to_nidle_lemma_case_1_6: "case_2 s\<Longrightarrow>con_assms s \<Longrightarrow> pcR s = idleR\<Longrightarrow>pre_R (pcR s) s \<Longrightarrow>s'=(s\<lparr>ownB := \<lambda>i. if fst (hd (q s)) \<le> i \<and> i < fst (hd (q s)) + snd (hd (q s)) then R else ownB s i, numDeqs := Suc (numDeqs s), ownT := R, tempR := hd (q s), pcR := Read, q := tl (q s)\<rparr>) \<Longrightarrow>inv s \<Longrightarrow>q s\<noteq>[] \<Longrightarrow>case_2 s'" apply(simp add:case_2_def inv_def) apply(simp add:Q_lemmas Q_basic_lemmas) apply(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) apply(clarify) apply(intro conjI impI) apply (metis (no_types, lifting) le_antisym less_imp_le_nat list.set_sel(1) nat_neq_iff prod.collapse) sorry lemma R_idle_to_nidle_lemma_case_1_7: "con_assms s \<Longrightarrow> pcR s = idleR\<Longrightarrow>pre_R (pcR s) s \<Longrightarrow>s'=(s\<lparr>ownB := \<lambda>i. if fst (hd (q s)) \<le> i \<and> i < fst (hd (q s)) + snd (hd (q s)) then R else ownB s i, numDeqs := Suc (numDeqs s), ownT := R, tempR := hd (q s), pcR := Read, q := tl (q s)\<rparr>) \<Longrightarrow>inv s \<Longrightarrow>q s\<noteq>[] \<Longrightarrow>Q_owns_bytes s'" sorry lemma R_read_to_release_lemma_1: "con_assms s \<Longrightarrow> pcR s = Read\<Longrightarrow>pre_Read_inv s \<Longrightarrow>s'=(s\<lparr>tR := T s, numReads := Suc (data_index s (tempR s)), pcR := Release, ownD := \<lambda>i. if i = data_index s (tempR s) then R else ownD (s\<lparr>tR := T s, numReads := Suc (data_index s (tempR s)), pcR := Release\<rparr>) i\<rparr>) \<Longrightarrow>inv s \<Longrightarrow>i>0\<longrightarrow>ownB s' i = ownB s i \<and> T s = T s' \<and> H s = H s' \<and> tempR s = tempR s' \<and> offset s = offset s' \<and> Data s (numEnqs s) = Data s' (numEnqs s') \<and> q s = q s' \<and> ownT s = ownT s'" by simp lemma R_read_to_release_lemma_case_1: "con_assms s \<Longrightarrow> pcR s = Read\<Longrightarrow>pre_Read_inv s \<Longrightarrow>s'=(s\<lparr>tR := T s, numReads := Suc (data_index s (tempR s)), pcR := Release, ownD := \<lambda>i. if i = data_index s (tempR s) then R else ownD (s\<lparr>tR := T s, numReads := Suc (data_index s (tempR s)), pcR := Release\<rparr>) i\<rparr>) \<Longrightarrow>inv s \<Longrightarrow>case_1 s \<Longrightarrow>case_1 s'" by(simp add:case_1_def) lemma R_read_to_release_lemma_case_2: "con_assms s \<Longrightarrow> pcR s = Read\<Longrightarrow>pre_Read_inv s \<Longrightarrow>s'=(s\<lparr>tR := T s, numReads := Suc (data_index s (tempR s)), pcR := Release, ownD := \<lambda>i. if i = data_index s (tempR s) then R else ownD (s\<lparr>tR := T s, numReads := Suc (data_index s (tempR s)), pcR := Release\<rparr>) i\<rparr>) \<Longrightarrow>inv s \<Longrightarrow>case_2 s \<Longrightarrow>case_2 s'" by(simp add:case_2_def) lemma R_read_to_release_lemma_2: "con_assms s \<Longrightarrow> pcR s = Read\<Longrightarrow>pre_Read_inv s \<Longrightarrow>s'=(s\<lparr>tR := T s, numReads := Suc (data_index s (tempR s)), pcR := Release, ownD := \<lambda>i. if i = data_index s (tempR s) then R else ownD (s\<lparr>tR := T s, numReads := Suc (data_index s (tempR s)), pcR := Release\<rparr>) i\<rparr>) \<Longrightarrow>inv s \<Longrightarrow>Q_owns_bytes s \<Longrightarrow>Q_owns_bytes s'" by(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) lemma T_modification_rule: "s'=(s\<lparr>T := fst (tempR s) + Data s (numReads s - Suc 0)\<rparr>) \<Longrightarrow> T s' = fst (tempR s) + Data s (numReads s - Suc 0)" by simp lemma T_modification_rule_2: "s'=(s\<lparr>ownT := Q, ownB := \<lambda>i. if (if T s \<le> i \<and> i < N then B else ownB (s\<lparr>ownT := Q\<rparr>) i) = R \<and> i \<le> N then B else ownB (setownB [(tR s, N) B] (s\<lparr>ownT := Q\<rparr>)) i, tempR := (0, 0), pcR := idleR, T := fst (tempR s) + Data s (numReads s - Suc 0)\<rparr>) \<Longrightarrow> T s' = fst (tempR s) + Data s (numReads s - Suc 0)" by simp lemma T_push: " T s = fst (tempR s) \<Longrightarrow>s'=s \<lparr>ownT := Q, ownB := \<lambda>i. if ownB s i = R \<and> i \<le> N then B else ownB ((if T s \<noteq> fst (tempR s) then setownB [(tR s, N) B] else id) (s\<lparr>ownT := Q\<rparr>)) i, tempR := (0, 0), pcR := idleR, T := fst (tempR s) + Data s (numReads s - Suc 0)\<rparr> \<Longrightarrow> T s' = fst (tempR s) + Data s (numReads s - Suc 0)" by simp lemma T_push_2 : " T s = fst (tempR s) \<Longrightarrow>s'=(s\<lparr>ownT := Q, ownB := \<lambda>i. if ownB s i = R \<and> i \<le> N then B else ownB (id (s\<lparr>ownT := Q\<rparr>)) i, tempR := (0, 0), pcR := idleR, T := fst (tempR s) + Data s (numReads s - Suc 0)\<rparr>) \<Longrightarrow> T s' = fst (tempR s) + Data s (numReads s - Suc 0)" by simp lemma R_release_to_idle_lemma_1: "con_assms s \<Longrightarrow> pcR s = Release \<Longrightarrow> pre_Release_inv s \<Longrightarrow> s'=s \<lparr>ownT := Q, ownB := \<lambda>i. if ownB s i = R \<and> i \<le> N then B else ownB ((if T s \<noteq> fst (tempR s) then setownB [(tR s, N) B] else id) (s\<lparr>ownT := Q\<rparr>)) i, tempR := (0, 0), pcR := idleR, T := fst (tempR s) + Data s (numReads s - Suc 0)\<rparr> \<Longrightarrow>inv s \<Longrightarrow> T s = fst (tempR s) \<Longrightarrow>case_1 s \<Longrightarrow>case_1 s'" apply (simp add:inv_def) apply(simp add:pre_Release_inv_def tempR_lemmas tempR_basic_lemmas) apply(subgoal_tac "T s' = fst (tempR s) + Data s (numReads s - Suc 0)") prefer 2 using T_push [where s =s and s'=s'] apply fastforce apply(simp add:case_1_def) apply clarify apply(rule_tac ?x = "b" in exI) apply(rule_tac ?x = "b" in exI) apply(intro conjI impI) apply fastforce apply(rule_tac ?x = "c" in exI) apply(intro conjI impI) apply blast apply blast apply (metis (no_types, lifting) le_trans less_or_eq_imp_le linorder_neqE_nat) apply (metis Suc_leI not_less_eq_eq) apply (metis F.distinct(11)) apply (metis F.distinct(1)) apply metis apply meson apply (metis le_add_diff_inverse) apply meson apply meson apply fastforce apply blast apply blast apply meson apply meson by meson lemma R_release_nequal_case_2: "con_assms s \<Longrightarrow> pcR s = Release \<Longrightarrow> pre_Release_inv s \<Longrightarrow>inv s \<Longrightarrow> T s \<noteq> fst (tempR s) \<Longrightarrow>case_2 s" apply (simp add:inv_def) apply(simp add:pre_Release_inv_def tempR_lemmas tempR_basic_lemmas) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply(subgoal_tac "H s>T s") prefer 2 apply metis apply(simp add:case_2_def) by metis lemma R_release_nequal_case_2_2: "con_assms s \<Longrightarrow> pcR s = Release \<Longrightarrow> pre_Release_inv s \<Longrightarrow>inv s \<Longrightarrow> T s \<noteq> fst (tempR s) \<Longrightarrow> s' = s \<lparr>ownT := Q, ownB := \<lambda>i. if (if T s \<le> i \<and> i < N then B else ownB (s\<lparr>ownT := Q\<rparr>) i) = R \<and> i \<le> N then B else ownB ((if T s \<noteq> fst (tempR s) then setownB [(tR s, N) B] else id) (s\<lparr>ownT := Q\<rparr>)) i, tempR := (0, 0), pcR := idleR, T := fst (tempR s) + Data s (numReads s - Suc 0)\<rparr> \<Longrightarrow>case_1 s'" apply(subgoal_tac "case_2 s") prefer 2 using R_release_nequal_case_2 [where s=s] apply blast apply (simp add:inv_def) apply(simp add:pre_Release_inv_def tempR_lemmas tempR_basic_lemmas) apply(subgoal_tac "H s < T s") prefer 2 apply(simp add:case_2_def) apply meson apply(simp add:case_2_def case_1_def) apply clarify apply(rule_tac ?x = "a" in exI) apply(rule_tac ?x = "a" in exI) apply(intro conjI impI) apply blast apply(rule_tac ?x = "b" in exI) apply(intro conjI impI) apply blast apply blast apply (metis add_cancel_left_left le_trans less_or_eq_imp_le) apply (metis le_antisym less_irrefl_nat less_or_eq_imp_le) apply (metis F.distinct(11) F.distinct(21) gr0_conv_Suc nat.discI nat_less_le) apply (metis F.distinct(1)) apply (metis nat_le_linear nat_less_le) apply meson apply (metis add_cancel_right_left) apply fastforce apply meson apply force apply blast apply (metis add_cancel_left_left diff_self_eq_0 le_neq_implies_less) apply meson apply (metis le_neq_implies_less) by meson lemma R_release_nequal_case_1_1: "con_assms s \<Longrightarrow> pcR s = Release \<Longrightarrow> pre_Release_inv s \<Longrightarrow>inv s \<Longrightarrow> T s = fst (tempR s) \<Longrightarrow> s'=(s\<lparr>ownT := Q, ownB := \<lambda>i. if ownB s i = R \<and> i \<le> N then B else ownB (id (s\<lparr>ownT := Q\<rparr>)) i, tempR := (0, 0), pcR := idleR, T := fst (tempR s) + Data s (numReads s - Suc 0)\<rparr>) \<Longrightarrow> case_1 s \<Longrightarrow>case_1 s'" apply (simp add:inv_def) apply(simp add:pre_Release_inv_def tempR_lemmas tempR_basic_lemmas) apply(subgoal_tac "T s' = fst (tempR s) + Data s (numReads s - Suc 0)") prefer 2 using T_push_2 [where s=s and s'=s'] apply fastforce apply(simp add:case_1_def) apply clarify apply(rule_tac ?x = "b" in exI) apply(rule_tac ?x = "b" in exI) apply(intro conjI impI) apply fastforce apply(rule_tac ?x = "c" in exI) apply(intro conjI impI) apply blast apply blast apply (metis diff_commute diff_diff_cancel diff_is_0_eq' less_nat_zero_code linorder_neqE_nat nat_le_linear zero_less_diff) apply (metis le_imp_less_Suc not_less_eq) apply (metis F.distinct(11)) apply (metis F.distinct(1)) apply metis apply blast apply (metis le_add_diff_inverse) apply meson apply fastforce apply fastforce apply force apply blast apply meson apply fastforce by meson lemma R_release_equal_case_2_3: "con_assms s \<Longrightarrow> pcR s = Release \<Longrightarrow> pre_Release_inv s \<Longrightarrow>inv s \<Longrightarrow> T s = fst (tempR s) \<Longrightarrow> s'=(s\<lparr>ownT := Q, ownB := \<lambda>i. if ownB s i = R \<and> i \<le> N then B else ownB (id (s\<lparr>ownT := Q\<rparr>)) i, tempR := (0, 0), pcR := idleR, T := fst (tempR s) + Data s (numReads s - Suc 0)\<rparr>) \<Longrightarrow> case_2 s \<Longrightarrow>case_2 s'" apply (simp add:inv_def) apply(simp add:pre_Release_inv_def tempR_lemmas tempR_basic_lemmas) apply(subgoal_tac "T s' = fst (tempR s) + Data s (numReads s - Suc 0)") prefer 2 using T_push_2 [where s =s and s'=s'] apply fastforce apply(simp_all) apply(simp add:case_2_def) apply clarify apply(rule_tac ?x = "0" in exI) apply(rule_tac ?x = "b" in exI) apply(intro conjI impI) apply fastforce apply(rule_tac ?x = "H s" in exI) apply(intro conjI impI) apply fastforce apply(rule_tac ?x = "e" in exI) apply(intro conjI impI) apply (metis le_add_diff_inverse trans_less_add1) apply(rule_tac ?x = "e" in exI) apply(intro conjI impI) apply fastforce apply(rule_tac ?x = "f" in exI) apply(intro conjI impI) apply fastforce apply blast apply blast apply (metis F.distinct(11) less_nat_zero_code) apply (metis F.distinct(1)) apply (metis (mono_tags, hide_lams) diff_is_0_eq' le_trans linorder_neqE_nat nat_le_linear zero_less_diff) apply (metis le_imp_less_Suc not_less_eq) apply (metis F.distinct(11)) apply (metis F.distinct(15)) apply fastforce apply blast apply blast apply blast apply blast apply (metis gr_implies_not_zero le_add_diff_inverse) apply blast apply meson apply meson apply blast apply fastforce apply blast apply (metis less_nat_zero_code) apply meson apply (metis less_nat_zero_code) apply meson apply (metis less_nat_zero_code) apply (metis less_nat_zero_code) by force lemma Q_continues_to_own_through_release: "Q_owns_bytes s \<Longrightarrow> inv s \<Longrightarrow> cR_step (pcR s) s s' \<Longrightarrow> pcR s = Release \<Longrightarrow> pre_Release_inv s \<Longrightarrow> Q_owns_bytes s'" apply simp apply(simp add:Q_lemmas Q_basic_lemmas inv_def pre_Release_inv_def) apply(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) apply(simp add:cR_step_def) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "ownT s = R", simp_all) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply metis apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") by (metis F.distinct(21) nat_less_le) lemma Q_structure_continues_to_own_through_release: "Q_structure s \<Longrightarrow> inv s \<Longrightarrow> cR_step (pcR s) s s' \<Longrightarrow> pcR s = Release \<Longrightarrow> pre_Release_inv s \<Longrightarrow> Q_structure s'" apply simp apply(simp add:Q_lemmas Q_basic_lemmas inv_def pre_Release_inv_def) by(simp add:cR_step_def) (************************************Local R_step shows inv *********************************************) lemma R_local_release_lemma: assumes "inv s" and "con_assms s" and "pcR s = Release" and "pre_R (pcR s) s" and "cR_step (pcR s) s s'" shows "inv s'" using assms apply simp apply(subgoal_tac "Q_owns_bytes s") prefer 2 using inv_def apply blast apply(subgoal_tac "inv s") prefer 2 apply blast apply(subgoal_tac "cR_step (pcR s) s s'") prefer 2 apply metis apply(subgoal_tac "pcR s = Release ") prefer 2 apply metis apply(subgoal_tac "pre_Release_inv s") prefer 2 apply(simp add:pre_R_def) apply(subgoal_tac "Q_owns_bytes s'") prefer 2 using Q_continues_to_own_through_release [where s=s and s'=s'] apply blast apply(subgoal_tac "Q_structure s") prefer 2 using inv_def apply blast apply(subgoal_tac "Q_structure s'") prefer 2 using Q_structure_continues_to_own_through_release [where s=s and s'=s'] apply blast (*prelimiaries go here*) apply(simp add:inv_def) apply(subgoal_tac "inv s") prefer 2 using assms(1) apply linarith apply(simp add:pre_R_def) apply(subgoal_tac "B_release s s'") prefer 2 using B_release_def [where s=s and s'=s'] apply (metis PCR.simps(7) cR_step_def) apply(subgoal_tac "ownT s = R") prefer 2 using pre_Release_inv_def [where s=s] apply presburger apply(subgoal_tac "Q_structure s'") using Q_structure_preserved3 [where s=s and s'=s'] prefer 2 apply (metis \<open>B_release s s' \<equiv> s' = (`T := end (tempR s) \<circ> `pcR := idleR \<circ> `tempR := (0, 0) \<circ> transownB [R B] \<circ> (if tR s \<noteq> fst (tempR s) then setownB [(tR s, N) B] else id) \<circ> transownT [R Q s]) s\<close> end_simp len_def off_def) apply(simp add:pre_Release_inv_def) apply(intro conjI impI) apply(simp add:tempR_lemmas tempR_basic_lemmas) prefer 2 apply(simp add:tempR_lemmas tempR_basic_lemmas) apply(case_tac "T s \<noteq> fst (tempR s)", simp_all) apply(subgoal_tac "T s \<noteq> fst (tempR s)") prefer 2 apply blast apply(subgoal_tac "pre_R Release s") prefer 2 using assms apply presburger apply(simp add:pre_R_def) apply(subgoal_tac "pre_Release_inv s") prefer 2 apply blast apply(subgoal_tac "case_2 s") prefer 2 using R_release_nequal_case_2 [where s=s] using assms(2) apply fastforce apply(simp_all) apply(subgoal_tac "case_1 s'") prefer 2 using R_release_nequal_case_2_2 [where s'=s' and s=s] using assms(2) apply blast apply presburger apply(case_tac "case_1 s", simp_all) apply(case_tac[!] "T s = fst(tempR s)") apply(simp_all) apply(subgoal_tac "case_1 s'") using R_release_nequal_case_1_1 [where s=s and s'=s'] apply presburger apply(subgoal_tac "pre_R (pcR s) s") prefer 2 using assms(4) apply blast apply(simp add:pre_R_def) apply(subgoal_tac "pre_Release_inv s") prefer 2 apply blast using R_release_nequal_case_1_1 [where s=s and s'=s'] using assms(2) apply presburger apply(subgoal_tac "case_2 s'") using R_release_equal_case_2_3 [where s=s and s'=s'] apply presburger apply(subgoal_tac "pre_R (pcR s) s") prefer 2 using assms(4) apply blast apply(simp add:pre_R_def) apply(subgoal_tac "pre_Release_inv s") prefer 2 apply blast using R_release_equal_case_2_3 [where s=s and s'=s'] using assms(2) by presburger lemma R_local_idle_lemma: assumes "inv s" and "con_assms s" and "pcR s = idleR" and "pre_R (pcR s) s" and "cR_step (pcR s) s s'" shows "inv s'" using assms apply simp apply(simp add:pre_R_def cR_step_def) apply(case_tac "q s=[]") apply(case_tac "pcR s'") apply (simp,simp,simp) apply(subgoal_tac "Q_structure s'") prefer 2 using Q_structure_preserved1 [where s=s and s'=s'] inv_def apply meson apply (simp add: RingBuffer_BD_latest_2.inv_def) apply simp apply(simp add:pre_dequeue_inv_def) apply(subgoal_tac "s'=(s\<lparr>ownB := \<lambda>i. if fst (hd (q s)) \<le> i \<and> i < fst (hd (q s)) + snd (hd (q s)) then R else ownB s i, numDeqs := Suc (numDeqs s), ownT := R, tempR := hd (q s), pcR := Read, q := tl (q s)\<rparr>) ") prefer 2 apply presburger apply(subgoal_tac "Q_owns_bytes s'") prefer 2 using R_idle_to_nidle_lemma_case_1_7 [where s=s and s'=s'] assms apply fastforce apply(simp add:inv_def) apply(clarify) apply(intro conjI impI) apply (metis add.right_neutral add_Suc_right diff_diff_left) apply (metis diff_is_0_eq length_0_conv not_less_eq_eq) apply (metis diff_is_0_eq' le_trans length_0_conv not_less_eq_eq) apply(case_tac "case_1 s") apply simp apply(subgoal_tac "case_1 s'\<longrightarrow>case_1 s' \<or> case_2 s'") prefer 2 apply linarith apply(subgoal_tac "case_1 s'") apply blast apply simp using R_idle_to_nidle_lemma_case_1_5 [where s=s and s'=s'] using assms(1) assms(2) assms(4) apply presburger apply(subgoal_tac "case_2 s") prefer 2 apply blast apply(thin_tac "\<not>case_1 s") apply simp using R_idle_to_nidle_lemma_case_1_6 [where s=s and s'=s'] using assms(1) assms(2) assms(4) by presburger lemma R_local_read_lemma: assumes "inv s" and "con_assms s" and "pcR s = Read" and "pre_R (pcR s) s" and "cR_step (pcR s) s s'" shows "inv s'" using assms apply simp apply(simp add:inv_def) apply(simp add:pre_R_def) apply(subgoal_tac "B_read s s'") prefer 2 using B_read_def [where s=s and s'=s'] apply (metis PCR.simps(9) cR_step_def) apply(subgoal_tac "ownT s = R") prefer 2 using pre_Read_inv_def [where s=s] apply presburger apply(subgoal_tac "Q_structure s'") using Q_structure_preserved2 [where s=s and s'=s'] prefer 2 apply blast apply(simp add:pre_Read_inv_def) apply(intro conjI impI) apply (metis F.distinct(5) le_antisym le_eq_less_or_eq not_less_eq_eq) apply (metis F.distinct(5) Suc_leI le_eq_less_or_eq not_less_eq_eq) apply(case_tac "case_1 s") apply(subgoal_tac "case_1 s'") apply fastforce apply(subgoal_tac "pre_Read_inv s") prefer 2 apply (metis PCR.simps(9) assms(4) pre_R_def) using R_read_to_release_lemma_case_1 [where s=s and s'=s'] using assms(1) assms(2) apply fastforce apply(subgoal_tac "case_2 s") prefer 2 apply blast apply(thin_tac "\<not>case_1 s") apply(subgoal_tac "case_2 s'") apply force using R_read_to_release_lemma_case_2 [where s=s and s'=s'] apply (metis PCR.simps(9) assms(1) assms(2) assms(4) pre_R_def) using R_read_to_release_lemma_2 [where s=s and s'=s'] by (metis PCR.simps(9) assms(1) assms(2) assms(4) pre_R_def) lemma R_step_preserves_inv: assumes "inv s" and "con_assms s" and "pre_R (pcR s) s" and "cR_step (pcR s) s s'" shows "inv s'" using assms apply(case_tac "pcR s") using R_local_release_lemma [where s=s and s'=s'] apply blast (*done*) using R_local_idle_lemma [where s=s and s'=s'] apply blast (*done, check preliminaries*) using R_local_read_lemma [where s=s and s'=s'] by blast (*done*) (*******************************Local R pre post lemmas*************************************) lemma R_local_release_pre_lemma: assumes "inv s" and "con_assms s" and "pcR s = Release" and "pre_R (pcR s) s" and "cR_step (pcR s) s s'" shows "pre_R (pcR s') s'" using assms apply(simp add:pre_R_def) apply clarify apply(subgoal_tac "ownT s' \<noteq> R") prefer 2 apply(simp add:pre_dequeue_inv_def) apply(simp add:cR_step_def) apply(subgoal_tac "ownT s = R") prefer 2 apply(simp add:pre_Release_inv_def) apply(simp add:cR_step_def) apply(case_tac "tR s = fst(tempR s)") apply simp_all apply(simp add:pre_dequeue_inv_def) apply(intro conjI impI) apply(simp add:pre_Release_inv_def) apply(simp add:pre_Release_inv_def) apply(simp add:pre_Release_inv_def tempR_lemmas tempR_basic_lemmas) apply(simp add:inv_def Q_lemmas Q_basic_lemmas) apply(subgoal_tac "hd(q s)\<in>set(q s)") prefer 2 apply (metis hd_in_set) apply(subgoal_tac "fst(q s!0) = 0") prefer 2 apply (metis hd_conv_nth) apply(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) apply(case_tac "case_1 s ") apply simp apply(simp add:case_1_def) apply (metis diff_self_eq_0 le_neq_implies_less length_pos_if_in_set less_nat_zero_code) apply(simp) apply(thin_tac "\<not> case_1 s") apply(simp add:case_2_def) apply(clarify) apply(subgoal_tac "e=f") prefer 2 apply (metis gr_implies_not0 le_neq_implies_less) apply(subgoal_tac "(i<N \<and> ownB s i = Q )\<longrightarrow> i<ba") prefer 2 apply (metis (mono_tags, hide_lams) F.distinct(11) F.distinct(19) F.distinct(21) F.distinct(3) diff_is_0_eq neq0_conv zero_less_diff) apply(subgoal_tac "aa=0") prefer 2 apply (metis gr_implies_not0) apply(subgoal_tac "a+b\<le>ba") apply (metis (no_types, lifting) Suc_le_eq le_add1 le_trans not_less_eq_eq) apply(subgoal_tac "(a\<le>i \<and> i<a+b) \<longrightarrow> (ownB s i = Q)") prefer 2 apply (metis (no_types, lifting) mem_Collect_eq) apply(subgoal_tac "a = i\<longrightarrow> ownB s i = Q") prefer 2 apply (metis le_refl less_add_same_cancel1) apply(subgoal_tac "fst(tempR s) = T s \<longrightarrow> ownB s (T s) =R") prefer 2 apply (metis gr_implies_not0 le_refl) apply(subgoal_tac "T s > ba") prefer 2 apply (metis le0 less_nat_zero_code nat_neq_iff) apply(subgoal_tac "a=i\<longrightarrow>i<ba") prefer 2 apply (metis (no_types, lifting) F.distinct(23) le_add1 le_neq_implies_less le_trans) apply(subgoal_tac "a+b-1 = i \<longrightarrow>ownB s i=Q") prefer 2 apply (metis Suc_diff_1 add_gr_0 lessI less_Suc_eq_le less_add_same_cancel1) apply(subgoal_tac "\<nexists>i.(i\<ge>ba \<and> ownB s i = Q \<and> i\<le>N)") prefer 2 apply (metis (no_types, hide_lams) F.distinct(11) F.distinct(19) F.distinct(21) F.distinct(23) F.distinct(3) bot_nat_0.not_eq_extremum diff_diff_cancel diff_is_0_eq diff_self_eq_0 zero_less_diff) apply(subgoal_tac "a=i \<and> ownB s i = Q \<longrightarrow> i<ba") prefer 2 apply meson defer defer apply(simp add:pre_dequeue_inv_def) apply(intro conjI impI) apply(simp add:pre_Release_inv_def) apply(simp add:pre_Release_inv_def) apply(simp add:pre_Release_inv_def tempR_lemmas tempR_basic_lemmas) apply(simp add:inv_def Q_lemmas Q_basic_lemmas) apply(subgoal_tac "fst(hd(q s)) = 0") prefer 2 apply blast apply(case_tac "case_1 s") apply(simp) apply(simp add:case_1_def) apply metis apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply (metis head_q0 length_greater_0_conv) prefer 3 apply(simp add:inv_def) apply(case_tac "case_1 s") apply(simp) apply(simp add:case_1_def pre_Release_inv_def) apply(simp add:inv_def Q_lemmas Q_basic_lemmas) apply(simp add:pre_Release_inv_def tempR_lemmas tempR_basic_lemmas) apply(simp add:Q_indices_def Q_owns_bytes_def ran_indices_def) apply(clarify) apply(intro conjI impI) apply (metis (no_types, lifting) bot_nat_0.extremum_uniqueI diff_self_eq_0 le_neq_implies_less length_0_conv) apply(subgoal_tac "hd(q s) \<in> set(q s)") prefer 2 apply (metis hd_in_set) apply(subgoal_tac "i\<le>N") prefer 2 apply (metis (no_types, lifting) le_trans less_or_eq_imp_le prod.collapse) apply(subgoal_tac "\<forall>i. (\<exists>x. (\<exists>a b. x = {i. a \<le> i \<and> i < a + b} \<and> (a, b) \<in> set (q s)) \<and> i \<in> x) = (i \<le> N \<and> ownB s i = Q)") prefer 2 apply blast apply(subgoal_tac "\<forall>a b i.((a,b)\<in>set(q s) \<and> i\<ge>a \<and> i<a+b) \<longrightarrow> ownB s i=Q") prefer 2 apply (metis (no_types, lifting) mem_Collect_eq) apply (metis (no_types, lifting) prod.collapse) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply(simp add:case_1_def pre_Release_inv_def) apply(simp add:inv_def Q_lemmas Q_basic_lemmas) apply(simp add:pre_Release_inv_def tempR_lemmas tempR_basic_lemmas) apply(simp add:Q_indices_def Q_owns_bytes_def ran_indices_def) apply(clarify) apply(intro conjI impI) apply(subgoal_tac "\<forall>i. (\<exists>x. (\<exists>a b. x = {i. a \<le> i \<and> i < a + b} \<and> (a, b) \<in> set (q s)) \<and> i \<in> x) = (i \<le> N \<and> ownB s i = Q)") prefer 2 apply blast apply(subgoal_tac "hd(q s) \<in> set(q s)") prefer 2 apply (metis hd_in_set) apply(subgoal_tac "a = 0") prefer 2 apply (metis less_nat_zero_code) apply(case_tac "fst(hd(q s)) = e") apply (metis gr_implies_not0) apply(subgoal_tac "fst(hd(q s)) = 0") prefer 2 apply metis apply(subgoal_tac "b\<le>H s") prefer 2 apply fastforce apply(subgoal_tac "H s< T s") prefer 2 apply fastforce apply(subgoal_tac "b< T s") prefer 2 apply (metis le0 le_refl less_nat_zero_code nat_neq_iff) apply(subgoal_tac "i\<ge>end(hd(q s))") apply (metis Suc_leI end_simp not_less_eq_eq) apply(subgoal_tac "e = f") prefer 2 apply (metis le_neq_implies_less) apply(subgoal_tac "\<forall>a b i.((a,b)\<in>set(q s) \<and> i\<ge>a \<and> i<a+b) \<longrightarrow> ownB s i=Q") prefer 2 apply (metis (no_types, lifting) mem_Collect_eq) apply(subgoal_tac "i\<ge>T s") prefer 2 apply (metis less_Suc_eq_le not_less_eq) apply(subgoal_tac "\<forall>i.(i\<ge>a \<and> i<end(hd(q s))) \<longrightarrow> ownB s i = Q") prefer 2 apply (metis (no_types, lifting) end_simp prod.collapse) apply (metis F.distinct(11) less_Suc_eq_le not_less_eq) apply(subgoal_tac "\<forall>a b i.((a,b)\<in>set(q s) \<and> i\<ge>a \<and> i<a+b) \<longrightarrow> ownB s i=Q") prefer 2 apply (metis (no_types, lifting) mem_Collect_eq) apply (metis (no_types, lifting) list.set_sel(1) prod.collapse) apply(simp add:inv_def) apply(case_tac "case_1 s") apply simp apply(simp add:case_1_def pre_Release_inv_def) apply(simp add:inv_def Q_lemmas Q_basic_lemmas) apply(simp add:pre_Release_inv_def tempR_lemmas tempR_basic_lemmas) apply(simp add:Q_indices_def Q_owns_bytes_def ran_indices_def) apply metis apply(simp add:case_2_def pre_Release_inv_def) apply(thin_tac "\<not>case_1 s") apply(simp add:inv_def Q_lemmas Q_basic_lemmas) apply(simp add:pre_Release_inv_def tempR_lemmas tempR_basic_lemmas) apply(simp add:Q_indices_def Q_owns_bytes_def ran_indices_def) apply(clarify) apply(intro conjI impI) apply(subgoal_tac "\<forall>a b i.((a,b)\<in>set(q s) \<and> i\<ge>a \<and> i<a+b) \<longrightarrow> ownB s i=Q") prefer 2 apply (metis (no_types, lifting) mem_Collect_eq) apply (metis (no_types, hide_lams) F.distinct(21) less_imp_Suc_add list.set_sel(1) nat.distinct(1) nat_less_le prod.exhaust_sel) apply (metis head_q0 length_greater_0_conv) apply(subgoal_tac "\<forall>a b i.((a,b)\<in>set(q s) \<and> i\<ge>a \<and> i<a+b) \<longrightarrow> ownB s i=Q") prefer 2 apply (metis (no_types, lifting) mem_Collect_eq) apply (metis (no_types, lifting) list.set_sel(1) prod.collapse) apply(subgoal_tac "\<forall>a b i.((a,b)\<in>set(q s) \<and> i\<ge>a \<and> i<a+b) \<longrightarrow> ownB s i=Q") prefer 2 apply (metis (no_types, lifting) mem_Collect_eq) apply(subgoal_tac "aa=0") prefer 2 apply blast apply(subgoal_tac "\<forall>a b.((a,b)\<in>set(q s)) \<longrightarrow> a+b\<le>N") prefer 2 apply meson apply(subgoal_tac "\<forall>a b i.((a,b)\<in>set(q s) \<and> i\<ge>a \<and> i<a+b) \<longrightarrow> ownB s i=Q") prefer 2 apply (metis (no_types, lifting) mem_Collect_eq) apply(subgoal_tac "\<forall>j.(a\<le>j \<and> j<b+a) \<longrightarrow> ownB s j = Q") prefer 2 apply (metis add.commute) by (metis (no_types, hide_lams) Suc_eq_plus1 add_diff_inverse_nat add_leD1 diff_add_inverse2 diff_le_self less_eq_Suc_le zero_less_diff) lemma R_local_idle_pre_lemma: assumes "inv s" and "con_assms s" and "pcR s = idleR" and "pre_R (pcR s) s" and "cR_step (pcR s) s s'" shows "pre_R (pcR s') s'" using assms apply(simp add:pre_R_def) apply clarify apply(case_tac "q s=[]") using cR_step_def apply auto[1] apply(subgoal_tac "ownT s = Q") prefer 2 apply(simp add:pre_dequeue_inv_def) apply(simp add:cR_step_def) apply(simp add:pre_Read_inv_def) apply(intro conjI impI) apply(simp add:inv_def) apply(simp add:Q_lemmas Q_basic_lemmas) apply(simp add:pre_dequeue_inv_def) apply (metis add_cancel_right_right head_q0 length_greater_0_conv) apply(simp add:inv_def) apply(simp add:Q_lemmas Q_basic_lemmas) apply(simp add:pre_dequeue_inv_def) apply (metis add_cancel_right_right head_q0 length_greater_0_conv) apply(simp add:inv_def) apply(simp add:Q_lemmas Q_basic_lemmas) apply(simp add:pre_dequeue_inv_def) apply (metis diff_is_0_eq' le_trans length_0_conv not_less_eq_eq) apply(simp add:inv_def) apply(simp add:Q_lemmas Q_basic_lemmas) apply(simp add:pre_dequeue_inv_def) apply(simp add:inv_def) apply(simp add:Q_lemmas Q_basic_lemmas) apply(simp add:pre_dequeue_inv_def) apply (metis diff_is_0_eq' length_0_conv not_less_eq_eq) apply(simp add:inv_def) apply(simp add:Q_lemmas Q_basic_lemmas) apply(simp add:pre_dequeue_inv_def) apply (metis length_greater_0_conv plus_nat.add_0) apply(simp add:inv_def) apply(simp add:Q_lemmas Q_basic_lemmas) apply(simp add:pre_dequeue_inv_def) apply (metis hd_in_set less_nat_zero_code) apply(simp add:inv_def) apply(simp add:Q_lemmas Q_basic_lemmas) apply(simp add:pre_dequeue_inv_def) apply(simp add:tempR_lemmas tempR_basic_lemmas) apply(intro conjI impI) apply(subgoal_tac "(\<forall>i. i < length (q s) \<and> 0 < i \<longrightarrow> fst (q s ! (i - Suc 0)) + snd (q s ! (i - Suc 0)) = fst (q s ! i) \<or> fst (q s ! i) = 0)") prefer 2 apply presburger apply(subgoal_tac "fst(hd(q s)) = fst(q s!0)") prefer 2 apply (metis Q_ind_imp_tail_ind_1) apply(subgoal_tac "fst(hd(tl(q s))) = fst(q s!1)") prefer 2 apply (metis One_nat_def hd_conv_nth length_greater_0_conv nth_tl) apply (metis (no_types, lifting) One_nat_def Q_ind_imp_tail_ind_1 diff_Suc_1 length_greater_0_conv length_tl less_one zero_less_diff) apply(subgoal_tac "fst(hd(q s)) = fst(q s!0)") prefer 2 apply (metis Q_ind_imp_tail_ind_1) apply(subgoal_tac "fst(hd(tl(q s))) = fst(q s!1)") prefer 2 apply (metis One_nat_def hd_conv_nth length_greater_0_conv nth_tl) apply (metis (no_types, lifting) One_nat_def Suc_eq_plus1 Suc_neq_Zero length_greater_0_conv length_tl less_diff_conv nth_tl) apply(subgoal_tac "fst(hd(q s)) = fst(q s!0)") prefer 2 apply (metis Q_ind_imp_tail_ind_1) apply(subgoal_tac "fst(hd(tl(q s))) = fst(q s!1)") prefer 2 apply (metis One_nat_def hd_conv_nth length_greater_0_conv nth_tl) apply(subgoal_tac "i<length(q s) - Suc 0 \<longrightarrow> (tl (q s) ! i )\<in>set (q s)") prefer 2 apply (metis One_nat_def length_tl list.set_sel(2) nth_mem) apply(subgoal_tac "(hd (q s))\<in>set (q s)") prefer 2 apply (metis hd_in_set) apply simp apply clarify apply (intro conjI impI) apply(subgoal_tac "snd(hd(q s)) = snd(q s!0)") prefer 2 apply (metis Q_ind_imp_tail_ind_1) apply simp apply(subgoal_tac "\<forall>a b aa. (a, b) \<in> set (q s) \<and> (\<exists>b. (aa, b) \<in> set (q s)) \<longrightarrow> a < aa \<longrightarrow> a + b \<le> aa") prefer 2 apply blast apply(subgoal_tac "\<forall>i.(i<length(q s) -1)\<longrightarrow>(tl(q s)!i)\<in>set(q s)") prefer 2 apply (metis length_tl list.set_sel(2) nth_mem) apply(subgoal_tac "tl(q s)!ia \<in>set(q s)") prefer 2 apply (metis One_nat_def) apply(subgoal_tac "fst(tl(q s)!ia) >fst(hd(q s))") prefer 2 apply presburger apply (metis (no_types, lifting) list.set_sel(1) prod.collapse) apply(subgoal_tac "\<forall>a b aa. (a, b) \<in> set (q s) \<and> (\<exists>b. (aa, b) \<in> set (q s)) \<longrightarrow> a < aa \<longrightarrow> a + b \<le> aa") prefer 2 apply blast apply(subgoal_tac "\<forall>i.(i<length(q s) -1)\<longrightarrow>(tl(q s)!i)\<in>set(q s)") prefer 2 apply (metis length_tl list.set_sel(2) nth_mem) apply(subgoal_tac "tl(q s)!ia \<in>set(q s)") prefer 2 apply (metis One_nat_def) apply(subgoal_tac "fst(tl(q s)!ia) <fst(hd(q s))") prefer 2 apply presburger apply (metis (no_types, lifting) list.set_sel(1) prod.collapse) apply(subgoal_tac "hd(q s)\<in>set(q s)") prefer 2 apply (metis hd_in_set) apply(subgoal_tac "last (tl (q s))\<in>set(q s)") prefer 2 apply (metis last_in_set last_tl) apply (metis fst_conv last_tl surj_pair) apply (metis Nat.add_0_right hd_conv_nth length_greater_0_conv) apply (metis add_cancel_right_right head_q0 length_greater_0_conv) defer apply(simp add:inv_def) apply(case_tac "case_1 s") apply(simp) apply(simp add:case_1_def) apply (metis bot_nat_0.extremum_uniqueI bot_nat_0.not_eq_extremum diff_is_0_eq' length_greater_0_conv) apply(simp) apply(thin_tac "\<not> case_1 s") apply(simp add:case_2_def) apply meson apply(simp add:inv_def) apply(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) apply(subgoal_tac "hd(q s)\<in>set(q s)") prefer 2 apply (metis hd_in_set) apply(case_tac "case_1 s") apply simp apply(simp add:case_1_def) apply(simp add:pre_dequeue_inv_def) apply (metis F.distinct(13) bot_nat_0.extremum_uniqueI diff_self_eq_0 le_neq_implies_less length_0_conv) apply simp apply(thin_tac "\<not>case_1 s") apply(simp add:case_2_def) apply(simp add:pre_dequeue_inv_def) by (metis diff_self_eq_0 fst_conv le0 le_trans length_greater_0_conv nat_less_le plus_nat.add_0 snd_conv) lemma R_local_read_pre_lemma: assumes "inv s" and "con_assms s" and "pcR s = Read" and "pre_R (pcR s) s" and "cR_step (pcR s) s s'" shows "pre_R (pcR s') s'" using assms apply(simp add:pre_R_def) apply clarify apply(simp add:cR_step_def) apply(simp add:pre_Release_inv_def) apply(intro conjI impI) apply(simp add:pre_Read_inv_def) apply(simp add:pre_Read_inv_def) apply(simp add:inv_def) apply(simp add:Q_lemmas Q_basic_lemmas) apply(subgoal_tac "hd(q s)\<in>set(q s)") prefer 2 apply (meson list.set_sel(1)) apply (metis Nat.add_0_right hd_conv_nth length_pos_if_in_set) apply(simp add:pre_Read_inv_def) apply(simp add:pre_Read_inv_def) apply(simp add:pre_Read_inv_def) apply(simp add:pre_Read_inv_def) apply(simp add:tempR_lemmas tempR_basic_lemmas) apply(intro conjI impI) apply(simp add:pre_Read_inv_def tempR_lemmas tempR_basic_lemmas) apply(simp add:pre_Read_inv_def tempR_lemmas tempR_basic_lemmas) apply(subgoal_tac "snd (tempR s) = Data s (numDeqs s - Suc 0)") prefer 2 apply blast apply metis apply(simp add:pre_Read_inv_def tempR_lemmas tempR_basic_lemmas) apply(simp add:pre_Read_inv_def tempR_lemmas tempR_basic_lemmas) apply(subgoal_tac "snd (tempR s) = Data s (numDeqs s - Suc 0)") prefer 2 apply blast apply force apply(simp add:pre_Read_inv_def tempR_lemmas tempR_basic_lemmas) apply(simp add:pre_Read_inv_def tempR_lemmas tempR_basic_lemmas) apply(simp add:pre_Read_inv_def tempR_lemmas tempR_basic_lemmas) apply(simp add:pre_Read_inv_def tempR_lemmas tempR_basic_lemmas) apply(simp add:pre_Read_inv_def tempR_lemmas tempR_basic_lemmas) apply(simp add:pre_Read_inv_def tempR_lemmas tempR_basic_lemmas) apply(simp add:pre_Read_inv_def tempR_lemmas tempR_basic_lemmas) by(simp add:pre_Read_inv_def tempR_lemmas tempR_basic_lemmas) lemma R_local_pre_lemma: assumes "inv s" and "con_assms s" and "pre_R (pcR s) s" and "cR_step (pcR s) s s'" shows "pre_R (pcR s') s'" using assms apply(case_tac "pcR s") using R_local_release_pre_lemma [where s=s and s'=s'] apply blast (*done*) using R_local_idle_pre_lemma [where s=s and s'=s'] apply blast (*done*) using R_local_read_pre_lemma [where s=s and s'=s'] by blast (*done*) (*******************************GLOBAL W_step shows preR*************************************) lemma pcR_doesnt_change_with_W: assumes "inv s" and "con_assms s" and "pre_R (pcR s) s" and "pre_W (pcW s) s" and "cW_step (pcW s) s s'" shows "pcR s'=pcR s" using assms apply simp apply(case_tac "pcW s ", simp add:cW_step_def) apply(simp add:cW_step_def) apply(simp add:cW_step_def) apply(simp add:cW_step_def) apply(simp add:cW_step_def) apply(simp add:cW_step_def) apply(simp add:cW_step_def) apply(simp add:cW_step_def) apply(simp add:cW_step_def) apply(simp add:cW_step_def) apply(cases "numEnqs s < n") apply(simp add:B_acquire_def) apply(simp add:B_acquire_def) apply(simp add:cW_step_def) apply(cases "tW s \<noteq> T s") apply(simp add:cW_step_def) apply(simp add:cW_step_def) apply(simp add:cW_step_def) apply(simp add:cW_step_def) by(simp add:cW_step_def) lemma supporting_strange: "\<forall>i<(length (q s)). (fst (tempR s) < fst ((q s @ [(offset s, Data s (numEnqs s))]) ! i) \<longrightarrow> fst (tempR s) + snd (tempR s) \<le> fst ((q s @ [(offset s, Data s (numEnqs s))]) ! i)) \<and> (fst ((q s @ [(offset s, Data s (numEnqs s))]) ! i) < fst (tempR s) \<longrightarrow> fst ((q s @ [(offset s, Data s (numEnqs s))]) ! i) + snd ((q s @ [(offset s, Data s (numEnqs s))]) ! i) \<le> fst (tempR s)) \<Longrightarrow> (fst (tempR s) < fst ((offset s, Data s (numEnqs s))) \<longrightarrow> fst (tempR s) + snd (tempR s) \<le> fst ((offset s, Data s (numEnqs s)))) \<and> (fst ((offset s, Data s (numEnqs s))) < fst (tempR s) \<longrightarrow> fst ((offset s, Data s (numEnqs s))) + snd ((offset s, Data s (numEnqs s))) \<le> fst (tempR s)) \<Longrightarrow> \<forall>i<Suc (length (q s)). (fst (tempR s) < fst ((q s @ [(offset s, Data s (numEnqs s))]) ! i) \<longrightarrow> fst (tempR s) + snd (tempR s) \<le> fst ((q s @ [(offset s, Data s (numEnqs s))]) ! i)) \<and> (fst ((q s @ [(offset s, Data s (numEnqs s))]) ! i) < fst (tempR s) \<longrightarrow> fst ((q s @ [(offset s, Data s (numEnqs s))]) ! i) + snd ((q s @ [(offset s, Data s (numEnqs s))]) ! i) \<le> fst (tempR s))" by (metis less_SucE nth_append_length) lemma preRead_doesnt_change_with_W: assumes "inv s" and "con_assms s" and "pre_Read_inv s" and "pre_W (pcW s) s" and "cW_step (pcW s) s s'" shows "pre_Read_inv s'" using assms apply simp apply(simp add:pre_Read_inv_def) apply(intro conjI impI) apply(simp add:pre_W_def) apply(simp add:tempR_lemmas tempR_basic_lemmas) apply(cases "pcW s", simp_all) apply(simp_all add:cW_step_def) apply(cases "numEnqs s<n", simp_all) apply(cases "tW s \<noteq> T s", simp_all) apply(simp add:pre_W_def) apply(simp add:tempR_lemmas tempR_basic_lemmas) apply(cases "pcW s", simp_all) apply(cases "numEnqs s<n", simp_all) apply(cases "tW s \<noteq> T s", simp_all) apply(simp add:pre_write_inv_def) apply(simp add:tempW_lemmas tempW_basic_lemmas) apply(simp add:inv_def) apply (metis F.distinct(1) eq_imp_le fst_eqD less_add_same_cancel1 snd_eqD) apply(cases "pcW s", simp_all) apply(cases "numEnqs s<n", simp_all) apply(cases "tW s \<noteq> T s", simp_all) apply(cases "pcW s", simp_all) apply(cases "numEnqs s<n", simp_all) apply(cases "tW s \<noteq> T s", simp_all) apply(cases "pcW s", simp_all) apply(cases "numEnqs s<n", simp_all) apply(cases "tW s \<noteq> T s", simp_all) apply(cases "pcW s", simp_all) apply(cases "numEnqs s<n", simp_all) apply(cases "tW s \<noteq> T s", simp_all) apply(cases "pcW s", simp_all) apply(cases "numEnqs s<n", simp_all) apply(cases "tW s \<noteq> T s", simp_all) apply(cases "pcW s", simp_all) apply(cases "numEnqs s<n", simp_all) apply(cases "tW s \<noteq> T s", simp_all) apply(cases "pcW s", simp_all) apply metis apply(case_tac "tW s = hW s \<and> Data s (numEnqs s) \<le> N", simp_all) apply metis apply(case_tac " hW s < tW s \<and> Data s (numEnqs s) < tW s - hW s", simp_all, metis) apply(case_tac "tW s < hW s", simp_all, metis, metis, metis, metis) apply(case_tac " Data s (numEnqs s) \<le> N - hW s", simp_all, metis) apply(case_tac " Data s (numEnqs s) < tW s", simp_all, metis, metis, metis, metis, metis, metis) apply(case_tac "numEnqs s < n", simp_all, metis, metis) apply(cases "tW s \<noteq> T s", simp_all, metis, metis, metis, metis, metis) apply(case_tac "pcW s", simp_all add:cW_step_def) apply(case_tac "numEnqs s < n", simp_all) apply(cases "tW s \<noteq> T s", simp_all) apply(cases "pcW s", simp_all) apply(simp add:tempR_lemmas tempR_basic_lemmas) apply metis apply(case_tac " tW s = hW s \<and> Data s (numEnqs s) \<le> N", simp_all) apply(simp add:tempR_lemmas tempR_basic_lemmas) apply metis apply(case_tac "hW s < tW s \<and> Data s (numEnqs s) < tW s - hW s", simp_all) apply(simp add:tempR_lemmas tempR_basic_lemmas) apply metis apply(case_tac "tW s < hW s", simp_all) apply(simp add:tempR_lemmas tempR_basic_lemmas) apply metis apply(simp add:tempR_lemmas tempR_basic_lemmas) apply metis apply(simp add:tempR_lemmas tempR_basic_lemmas) apply(intro conjI impI) apply metis apply (metis (no_types, lifting)) apply(simp add:pre_W_def pre_A3_inv_def) apply(simp add:tempR_lemmas tempR_basic_lemmas) apply(intro conjI impI) apply metis apply (metis (no_types, lifting)) apply(simp add:pre_W_def pre_A4_inv_def) apply (metis (no_types, lifting) F.distinct(13) Suc_lessD add.commute less_diff_conv less_trans_Suc) apply(case_tac " Data s (numEnqs s) \<le> N - hW s", simp_all) apply(simp add:tempR_lemmas tempR_basic_lemmas) apply(simp add:pre_W_def pre_A5_inv_def) apply metis apply(case_tac "Data s (numEnqs s) < tW s", simp_all) apply(simp add:tempR_lemmas tempR_basic_lemmas) apply(simp add:pre_W_def pre_A5_inv_def) apply metis apply(simp add:pre_W_def pre_A5_inv_def) apply(simp add:tempR_lemmas tempR_basic_lemmas) apply metis apply(simp add:pre_W_def pre_A6_inv_def) apply(simp add:tempR_lemmas tempR_basic_lemmas) apply(intro conjI impI) apply metis apply (metis (no_types, lifting)) apply (metis (mono_tags, hide_lams) F.distinct(13) le_trans less_or_eq_imp_le nat_neq_iff) apply(simp add:pre_W_def pre_A7_inv_def) apply(simp add:tempR_lemmas tempR_basic_lemmas) apply(intro conjI impI) apply metis apply (metis (no_types, lifting)) apply(clarify) apply(intro conjI impI) apply (metis F.distinct(13) Suc_lessD less_trans_Suc) apply (metis (mono_tags, hide_lams) F.distinct(13) le_trans less_or_eq_imp_le linorder_neqE_nat) apply(case_tac "N < Data s (numEnqs s)", simp_all) apply(simp add:pre_W_def pre_A8_inv_def) apply(simp add:tempR_lemmas tempR_basic_lemmas) apply metis apply(simp add:tempR_lemmas tempR_basic_lemmas) apply metis apply(simp add:pre_W_def pre_A8_inv_def) defer apply(cases "numEnqs s < n", simp_all) apply(simp add:pre_W_def pre_acquire_inv_def) apply(simp add:tempR_lemmas tempR_basic_lemmas) apply metis apply(simp add:pre_W_def pre_acquire_inv_def) apply(simp add:tempR_lemmas tempR_basic_lemmas) apply metis apply(simp add:pre_W_def pre_OOM_inv_def) apply(simp add:tempR_lemmas tempR_basic_lemmas) apply(cases "tW s \<noteq> T s", simp_all) apply metis apply metis apply(simp add:pre_W_def pre_write_inv_def) apply(simp add:tempR_lemmas tempR_basic_lemmas) apply (metis (no_types, lifting) F.distinct(1) Nat.add_0_right eq_imp_le fst_eqD nat_add_left_cancel_less snd_eqD) defer defer defer apply(simp add:pre_W_def pre_enqueue_inv_def) apply(simp add:tempR_lemmas tempR_basic_lemmas) apply(intro conjI impI) apply(simp add: tempW_def) apply(case_tac "q s\<noteq>[]") apply (metis (no_types, hide_lams) hd_append2) apply(subgoal_tac "q s=[]") prefer 2 apply force apply(subgoal_tac "tempR s \<noteq>(0,0)") prefer 2 apply blast apply(case_tac "offset s = 0") apply (metis append_Nil fst_conv list.sel(1)) apply(simp add:inv_def) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply clarify apply(subgoal_tac "c=b") prefer 2 apply (metis le_neq_implies_less) apply(subgoal_tac "end(tempR s) = b") prefer 2 apply (metis end_simp le_add_diff_inverse) apply(subgoal_tac "offset s = hW s") prefer 2 apply meson apply(subgoal_tac "i\<ge>c \<and> i<H s \<longrightarrow>ownB s i = W") prefer 2 apply metis apply(subgoal_tac "H s\<le>N") prefer 2 apply metis apply(subgoal_tac "(i<c \<or> i\<ge>H s \<and> i\<le>N) \<longrightarrow>ownB s i\<noteq>W") prefer 2 apply (metis F.distinct(1) F.distinct(5) bot_nat_0.not_eq_extremum diff_is_0_eq zero_less_diff) apply (metis F.distinct(1) add_leD1 end_simp le_eq_less_or_eq linorder_neqE_nat nat_less_le) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply clarify apply (metis eq_imp_le le_add1 le_neq_implies_less plus_nat.add_0) apply(simp add: tempW_def) apply(case_tac "q s=[]") apply (metis (no_types, lifting) F.distinct(1) Nat.add_0_right Suc_le_lessD Suc_lessD Suc_pred add_lessD1 fst_eqD le_add_diff_inverse less_Suc0 less_Suc_eq_le less_add_same_cancel1 list.size(3) nat_add_left_cancel_le nth_Cons_0 self_append_conv2) apply(subgoal_tac "q s\<noteq>[]") prefer 2 apply blast apply(subgoal_tac "\<forall>i<length (q s). fst ((q s) ! i) \<noteq> fst (tempR s)") prefer 2 apply presburger apply(subgoal_tac "fst((offset s, Data s (numEnqs s))) \<noteq> fst(tempR s)") apply (metis less_SucE nth_append nth_append_length) apply(subgoal_tac "offset s \<noteq> fst(tempR s)") prefer 2 apply (metis (no_types, lifting) F.distinct(1) Suc_le_lessD Suc_lessD Suc_pred add_lessD1 le_add_diff_inverse le_refl less_add_same_cancel1) apply(case_tac "case_1 s", simp_all) apply(subgoal_tac "Data s (numReads s) = snd(tempR s)") prefer 2 apply presburger apply(subgoal_tac "Data s (numDeqs s - Suc 0) = snd(tempR s)") prefer 2 apply presburger apply(simp add:inv_def Q_lemmas Q_basic_lemmas) apply(subgoal_tac "\<forall>i<length (q s). (fst (tempR s) < fst ((q s ) ! i) \<longrightarrow> fst (tempR s) + Data s (numDeqs s - Suc 0) \<le> fst ((q s ) ! i)) \<and> (fst ((q s) ! i) < fst (tempR s) \<longrightarrow> fst ((q s) ! i) + snd ((q s ) ! i) \<le> fst (tempR s))") prefer 2 apply (metis (no_types, lifting) gr_implies_not0 length_0_conv) apply(subgoal_tac "(fst (tempR s) < fst(offset s, Data s (numEnqs s)) \<longrightarrow> fst (tempR s) + Data s (numDeqs s - Suc 0) \<le> fst(offset s, Data s (numEnqs s))) \<and> (fst(offset s, Data s (numEnqs s)) < fst (tempR s) \<longrightarrow> fst(offset s, Data s (numEnqs s)) + snd(offset s, Data s (numEnqs s)) \<le> fst (tempR s))") apply(subgoal_tac "((q s @ [(offset s, Data s (numEnqs s))]) ! length (q s)) = (offset s, Data s (numEnqs s))") prefer 2 apply (metis nth_append_length) apply(subgoal_tac "\<forall>i<(length (q s)). (fst (tempR s) < fst ((q s @ [(offset s, Data s (numEnqs s))]) ! i) \<longrightarrow> fst (tempR s) + snd (tempR s) \<le> fst ((q s @ [(offset s, Data s (numEnqs s))]) ! i)) \<and> (fst ((q s @ [(offset s, Data s (numEnqs s))]) ! i) < fst (tempR s) \<longrightarrow> fst ((q s @ [(offset s, Data s (numEnqs s))]) ! i) + snd ((q s @ [(offset s, Data s (numEnqs s))]) ! i) \<le> fst (tempR s))") prefer 2 apply (metis (no_types, hide_lams) nth_append) using supporting_strange [where s=s] apply presburger apply(intro conjI impI) apply (metis (no_types, lifting) Nat.add_0_right fst_eqD le_eq_less_or_eq less_add_same_cancel1 less_nat_zero_code nat_neq_iff snd_eqD tempW_def) apply(simp add:inv_def) apply(case_tac "case_1 s", simp_all) apply (simp add:case_1_def) apply(clarify) apply (metis (no_types, lifting) F.distinct(1) diff_is_0_eq le_refl less_imp_le_nat not_gr0 prod.collapse prod.inject tempW_def zero_less_diff) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply clarify apply (metis less_or_eq_imp_le zero_less_iff_neq_zero) apply(simp add: tempW_def) apply(subgoal_tac "fst((offset s, Data s (numEnqs s))) + snd((offset s, Data s (numEnqs s))) \<noteq> fst(tempR s)") apply (metis fst_eqD snd_eqD) apply(subgoal_tac "offset s \<noteq> fst(tempR s)") prefer 2 apply (metis (no_types, lifting) F.distinct(1) Suc_le_lessD Suc_lessD Suc_pred add_lessD1 le_add_diff_inverse le_refl less_add_same_cancel1) apply(simp add:inv_def) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply(clarify) apply linarith apply(simp add:case_2_def) apply (thin_tac "\<not>case_1 s") apply(clarify) apply (metis add_gr_0 nat_neq_iff) apply(case_tac "pcW s", simp_all add:inv_def) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply(simp add:pre_W_def pre_A3_inv_def) apply(simp add:case_2_def) apply(simp add:pre_W_def pre_A3_inv_def) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply(simp add:pre_W_def pre_A4_inv_def) apply (metis (no_types, lifting) le_add_diff_inverse le_eq_less_or_eq less_trans_Suc not_less_eq_eq) apply(simp add:case_2_def) apply(thin_tac "\<not> case_1 s") apply(simp add:pre_W_def pre_A4_inv_def) apply(simp add:tempR_lemmas tempR_basic_lemmas) apply(clarify) apply(subgoal_tac "fst(tempR s) = 0 \<or> fst(tempR s) = T s") prefer 2 apply meson apply(case_tac "fst(tempR s) = T s") apply(subgoal_tac "hW s = b") prefer 2 apply (metis le_imp_less_Suc le_refl le_trans not_less_less_Suc_eq) apply(subgoal_tac "T s > hW s + Data s (numEnqs s)") prefer 2 apply(subgoal_tac "ownB s (T s) = R") prefer 2 apply (metis gr_implies_not0 le_refl) apply(subgoal_tac "tW s = T s") prefer 2 apply (metis (no_types, lifting) add.commute le_trans less_diff_conv nat_less_le) apply(subgoal_tac "Data s (numEnqs s) < (tW s - hW s)") prefer 2 apply fastforce apply (metis add.commute less_diff_conv) apply (metis Suc_leI le_trans less_or_eq_imp_le not_less_eq_eq) apply(subgoal_tac "fst(tempR s) = 0") prefer 2 apply fastforce apply(subgoal_tac "end(tempR s) = a") prefer 2 apply (metis add_cancel_left_left end_simp) apply(subgoal_tac "hW s\<ge>a") prefer 2 apply (metis le_trans) apply (metis Suc_leI end_simp le_trans not_less_eq_eq) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply(simp add:pre_W_def pre_A6_inv_def) apply (metis le_add_diff_inverse le_trans less_or_eq_imp_le) apply(simp add:case_2_def) apply(simp add:pre_W_def pre_A6_inv_def) apply (metis Suc_leI not_less_eq_eq) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply(simp add:pre_W_def pre_A7_inv_def) apply clarify apply(intro conjI impI) apply linarith apply (metis le_add_diff_inverse le_trans less_or_eq_imp_le) apply(simp add:case_2_def) apply(simp add:pre_W_def pre_A7_inv_def) apply clarify apply(intro conjI impI) apply linarith apply (metis Suc_leI not_less_eq_eq) apply(case_tac "numEnqs s < n", simp_all) apply(case_tac "tW s \<noteq> T s", simp_all) prefer 2 apply(case_tac "pcW s", simp_all) apply(simp add:pre_W_def pre_A3_inv_def) apply(simp add:pre_W_def pre_A4_inv_def) apply(simp add:pre_W_def pre_A6_inv_def) apply(simp add:pre_W_def pre_A7_inv_def) apply(case_tac "numEnqs s < n", simp_all) apply(case_tac "tW s \<noteq> T s", simp_all) apply(case_tac "pcW s ", simp_all) apply(case_tac "numEnqs s < n", simp_all) by(case_tac "tW s \<noteq> T s", simp_all) lemma preIdleR_doesnt_change_with_W: assumes "inv s" and "con_assms s" and "pre_dequeue_inv s" and "pre_W (pcW s) s" and "cW_step (pcW s) s s'" shows "pre_dequeue_inv s'" using assms apply simp apply(simp add:pre_dequeue_inv_def) apply(intro conjI impI) apply(simp add:pre_W_def) apply(cases "pcW s", simp_all add:cW_step_def B_acquire_def) apply(cases "numEnqs s < n", simp_all) apply(cases "tW s \<noteq> T s", simp_all) apply(cases "pcW s", simp_all add:cW_step_def B_acquire_def) apply(cases "numEnqs s < n", simp_all) apply(cases "tW s \<noteq> T s", simp_all) apply(cases "pcW s", simp_all add:cW_step_def B_acquire_def) apply(cases "numEnqs s < n", simp_all) apply(cases "tW s \<noteq> T s", simp_all) apply(cases "pcW s", simp_all add:cW_step_def B_acquire_def) apply(cases "numEnqs s < n", simp_all) apply(cases "tW s \<noteq> T s", simp_all) apply(cases "pcW s", simp_all add:cW_step_def B_acquire_def) apply(cases "numEnqs s < n", simp_all) apply(cases "tW s \<noteq> T s", simp_all) apply(cases "pcW s", simp_all add:cW_step_def B_acquire_def pre_W_def) apply(cases "tW s = hW s \<and> Data s (numEnqs s) \<le> N", simp_all) apply(cases "ownT s = Q", simp_all) apply(simp add:pre_A2_inv_def) apply(cases "hW s < tW s \<and> Data s (numEnqs s) < tW s - hW s", simp_all) apply(cases "tW s < hW s", simp_all) apply(cases "Data s (numEnqs s) \<le> N - hW s", simp_all) apply(cases "Data s (numEnqs s) < tW s", simp_all) apply(cases "N < Data s (numEnqs s)", simp_all) apply(cases "ownT s = W", simp_all add:pre_enqueue_inv_def inv_def) apply(case_tac "case_1 s") apply simp apply(simp add:case_1_def) apply (metis nat_less_le) apply simp apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply (metis nat_less_le) apply(cases "numEnqs s < n", simp_all) apply(cases "tW s \<noteq> T s", simp_all) apply(cases "pcW s", simp_all add:cW_step_def B_acquire_def) apply(cases "tW s = hW s \<and> Data s (numEnqs s) \<le> N", simp_all) apply(cases "ownT s = W", simp_all add:pre_enqueue_inv_def inv_def) apply(cases "ownT s = W", simp_all add:pre_A2_inv_def inv_def) apply(cases "hW s < tW s \<and> Data s (numEnqs s) < tW s - hW s", simp_all) apply(cases "tW s < hW s", simp_all) apply(simp add:pre_A3_inv_def) apply(simp add:pre_A4_inv_def) apply(simp add:pre_A5_inv_def) apply(simp add:pre_A6_inv_def) apply(simp add:pre_A7_inv_def) apply(simp add:pre_A8_inv_def) apply(cases "N < Data s (numEnqs s)", simp_all) apply(simp add:pre_acquire_inv_def) apply(cases "numEnqs s < n", simp_all) apply(cases "tW s \<noteq> T s", simp_all) defer apply(cases "pcW s", simp_all add:cW_step_def B_acquire_def) apply(cases "tW s = hW s \<and> Data s (numEnqs s) \<le> N", simp_all add:pre_enqueue_inv_def inv_def) apply(cases "ownT s = W", simp_all add:pre_A2_inv_def inv_def) apply(cases "hW s < tW s \<and> Data s (numEnqs s) < tW s - hW s", simp_all) apply(cases "tW s < hW s", simp_all) apply(simp add:pre_A3_inv_def) apply(simp add:pre_A4_inv_def) apply (metis (no_types, lifting) F.distinct(19) add.commute add_lessD1 less_diff_conv less_imp_add_positive) apply(simp add:pre_A5_inv_def) apply(cases "Data s (numEnqs s) \<le> N - hW s", simp_all) apply(cases "Data s (numEnqs s) < tW s", simp_all) apply(simp add:pre_A6_inv_def) apply(simp add:Q_lemmas Q_basic_lemmas) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply clarify apply(subgoal_tac "offset s = hW s") prefer 2 apply (metis (no_types, lifting) F.distinct(19) F.distinct(23) add_lessD1 diff_is_0_eq' le_0_eq le_eq_less_or_eq length_0_conv nat_le_iff_add) apply (metis (no_types, lifting) F.distinct(19) add_lessD1 diff_self_eq_0 le_0_eq le_add_diff_inverse le_neq_implies_less length_0_conv) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply (metis Suc_leI not_less_eq_eq) apply(simp add:pre_A7_inv_def) apply(simp add:Q_lemmas Q_basic_lemmas) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply clarify apply (metis (no_types, lifting) F.distinct(19) F.distinct(23) add_lessD1 diff_is_0_eq' le_0_eq le_eq_less_or_eq length_0_conv nat_le_iff_add) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply (metis Suc_leI not_less_eq_eq) apply(simp add:pre_A8_inv_def) apply(cases "N < Data s (numEnqs s)", simp_all) apply(cases "ownT s = W", simp_all) apply (metis fst_conv le_trans nat_less_le snd_conv tempW_def) apply(simp add:Q_lemmas Q_basic_lemmas Q_indices_def Q_owns_bytes_def ran_indices_def) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply(simp add:tempW_lemmas tempW_basic_lemmas) apply(case_tac "q s=[]") apply(subgoal_tac "fst(hd (q s @ [(offset s, Data s (numEnqs s))])) = offset s") prefer 2 apply (metis append_self_conv2 list.sel(1) old.prod.inject prod.collapse) apply(subgoal_tac "snd(hd (q s @ [(offset s, Data s (numEnqs s))])) = Data s (numEnqs s)") prefer 2 apply (metis append_self_conv2 list.sel(1) old.prod.inject prod.collapse) apply (metis le_trans less_imp_le_nat) apply(subgoal_tac "fst(hd (q s @ [(offset s, Data s (numEnqs s))])) = fst(hd(q s))") prefer 2 apply (metis (no_types, lifting) hd_append2) apply(subgoal_tac "snd(hd (q s @ [(offset s, Data s (numEnqs s))])) = snd(hd(q s))") prefer 2 apply (metis (no_types, lifting) hd_append2) apply presburger apply(simp add:case_2_def) apply(simp add:tempW_lemmas tempW_basic_lemmas) apply(case_tac "q s=[]") apply(subgoal_tac "fst(hd (q s @ [(offset s, Data s (numEnqs s))])) = offset s") prefer 2 apply (metis append_self_conv2 list.sel(1) old.prod.inject prod.collapse) apply(subgoal_tac "snd(hd (q s @ [(offset s, Data s (numEnqs s))])) = Data s (numEnqs s)") prefer 2 apply (metis append_self_conv2 list.sel(1) old.prod.inject prod.collapse) apply (metis le_trans less_imp_le_nat) apply(subgoal_tac "fst(hd (q s @ [(offset s, Data s (numEnqs s))])) = fst(hd(q s))") prefer 2 apply (metis (no_types, lifting) hd_append2) apply(subgoal_tac "snd(hd (q s @ [(offset s, Data s (numEnqs s))])) = snd(hd(q s))") prefer 2 apply (metis (no_types, lifting) hd_append2) apply presburger apply(case_tac "numEnqs s< n", simp_all) apply(case_tac "tW s \<noteq> T s", simp_all) apply(case_tac "pcW s", simp_all) apply(case_tac "numEnqs s< n", simp_all) apply(case_tac "tW s \<noteq> T s", simp_all) apply(case_tac "pcW s", simp_all) apply(case_tac "tW s = hW s \<and> Data s (numEnqs s) \<le> N", simp_all) apply(case_tac "ownT s = Q", simp_all) apply(case_tac " hW s < tW s \<and> Data s (numEnqs s) < tW s - hW s ", simp_all) apply(case_tac "tW s < hW s", simp_all) apply(simp add:Q_lemmas Q_basic_lemmas Q_indices_def Q_owns_bytes_def ran_indices_def) apply (simp add: pre_A3_inv_def) apply(case_tac " Data s (numEnqs s) \<le> N - hW s", simp_all) apply(case_tac "Data s (numEnqs s) < tW s", simp_all) apply(case_tac "N < Data s (numEnqs s)", simp_all) apply(case_tac "ownT s = W", simp_all) apply(simp add:Q_lemmas Q_basic_lemmas Q_indices_def Q_owns_bytes_def ran_indices_def) apply(simp add:pre_enqueue_inv_def) apply(simp add:tempW_lemmas tempW_basic_lemmas) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply clarify apply (metis (no_types, hide_lams) Nat.add_0_right diff_is_0_eq le_refl nat_add_left_cancel_less nat_neq_iff zero_less_diff) apply(simp add:case_2_def) apply(simp add:Q_lemmas Q_basic_lemmas Q_indices_def Q_owns_bytes_def ran_indices_def) apply(simp add:pre_enqueue_inv_def) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply clarify apply (metis (no_types, hide_lams) diff_self_eq_0 fst_eqD hd_append le_zero_eq length_0_conv less_add_same_cancel1 less_or_eq_imp_le list.sel(1) nat_less_le snd_eqD tempW_def) apply(simp add:case_2_def) apply(subgoal_tac "\<forall>a b j. ((a, b) \<in> set (q s)) \<and> j < N \<and> T s \<le> j \<longrightarrow> a + b < j") prefer 2 apply (metis (no_types, lifting) hd_append length_greater_0_conv length_pos_if_in_set) apply(simp add:tempW_lemmas tempW_basic_lemmas) apply(subgoal_tac "offset s + Data s (numEnqs s)<T s") prefer 2 apply force apply(subgoal_tac "\<forall> j. T s \<le> j \<longrightarrow> offset s + Data s (numEnqs s) < j") prefer 2 apply (metis (mono_tags, hide_lams) diff_is_0_eq le_trans nat_less_le zero_less_diff) apply (metis (no_types, lifting)) apply(case_tac "numEnqs s < n", simp_all) by(case_tac "tW s \<noteq> T s", simp_all) lemma preRelease_doesnt_change_with_W: assumes "inv s" and "con_assms s" and "pre_Release_inv s" and "pre_W (pcW s) s" and "cW_step (pcW s) s s'" shows "pre_Release_inv s'" using assms apply simp apply(simp add:pre_Release_inv_def) apply(intro conjI impI) apply(simp add:cW_step_def) apply(cases "pcW s", simp_all) apply(cases "numEnqs s < n", simp_all) apply(cases "tW s \<noteq> T s", simp_all) apply(simp_all add:cW_step_def) apply(cases "pcW s", simp_all) apply(cases "numEnqs s < n", simp_all) apply(cases "tW s \<noteq> T s", simp_all) apply(simp add:pre_W_def pre_write_inv_def) apply (metis F.distinct(1) fst_eqD less_add_same_cancel1 nat_le_linear snd_eqD) apply(cases "pcW s", simp_all) apply(cases "tW s = hW s \<and> Data s (numEnqs s) \<le> N", simp_all) apply(cases "hW s < tW s \<and> Data s (numEnqs s) < tW s - hW s", simp_all) apply(cases "tW s < hW s", simp_all) apply(case_tac "Data s (numEnqs s) \<le> N - hW s", simp_all) apply(case_tac "Data s (numEnqs s) < tW s", simp_all) apply(case_tac "N < Data s (numEnqs s)", simp_all) apply(simp add:pre_W_def pre_enqueue_inv_def) apply(simp add:inv_def Q_lemmas Q_basic_lemmas) apply (metis Nat.le_imp_diff_is_add hd_append length_0_conv list.sel(1) plus_nat.add_0 tempW_reflects_writes_def) apply(cases "numEnqs s < n", simp_all) apply(cases "tW s \<noteq> T s", simp_all) apply(simp add:pre_W_def pre_write_inv_def) apply(simp add:inv_def Q_lemmas Q_basic_lemmas) apply(simp add:tempW_lemmas tempW_basic_lemmas) apply (metis fst_eqD head_q0 length_greater_0_conv) apply(cases "pcW s", simp_all) apply(cases "numEnqs s < n", simp_all) apply(cases "tW s \<noteq> T s", simp_all) apply(cases "pcW s", simp_all) apply(cases "numEnqs s < n", simp_all) apply(cases "tW s \<noteq> T s", simp_all) apply(cases "pcW s", simp_all) apply(cases "numEnqs s < n", simp_all) apply(cases "tW s \<noteq> T s", simp_all) apply(simp add:pre_W_def pre_write_inv_def) apply (metis F.distinct(1)) apply(cases "pcW s", simp_all) apply(cases "numEnqs s < n", simp_all) apply(cases "tW s \<noteq> T s", simp_all) apply(cases "pcW s", simp_all) apply(cases "numEnqs s < n", simp_all) apply(cases "tW s \<noteq> T s", simp_all) apply(cases "pcW s", simp_all) apply(cases "numEnqs s < n", simp_all) apply(cases "tW s \<noteq> T s", simp_all) apply(cases "pcW s", simp_all) apply(cases "numEnqs s < n", simp_all) apply(cases "tW s \<noteq> T s", simp_all) apply(cases "pcW s", simp_all) apply(simp add:pre_W_def pre_A3_inv_def) apply(cases "numEnqs s < n", simp_all) apply(cases "tW s \<noteq> T s", simp_all) apply(cases "pcW s", simp_all) apply(cases "numEnqs s < n", simp_all) apply(cases "tW s \<noteq> T s", simp_all) defer apply(cases "pcW s", simp_all) apply(simp add:pre_W_def pre_A3_inv_def) apply(simp add:pre_W_def pre_A4_inv_def) apply(simp add:tempR_lemmas tempR_basic_lemmas) apply (metis (no_types, lifting) F.distinct(13) Suc_lessD add.commute less_diff_conv less_trans_Suc) apply(simp add:pre_W_def pre_A6_inv_def) apply(simp add:tempR_lemmas tempR_basic_lemmas) apply (metis (mono_tags, hide_lams) F.distinct(13) le_antisym le_trans less_or_eq_imp_le nat_neq_iff) apply(simp add:pre_W_def pre_A7_inv_def) apply(simp add:tempR_lemmas tempR_basic_lemmas) apply (metis (no_types, hide_lams) F.distinct(13) Suc_lessD less_trans_Suc) apply(cases "numEnqs s < n", simp_all) apply(cases "tW s \<noteq> T s", simp_all) apply(cases "pcW s", simp_all) apply(cases "numEnqs s < n", simp_all) apply(cases "tW s \<noteq> T s", simp_all) apply(cases "pcW s", simp_all) apply(simp add:pre_W_def pre_A3_inv_def) apply(simp add:pre_W_def pre_A4_inv_def) apply(simp add:pre_W_def pre_A6_inv_def) apply(simp add:pre_W_def pre_A7_inv_def) apply(cases "numEnqs s < n", simp_all) apply(cases "tW s \<noteq> T s", simp_all) (*tempR doesnt change:*) apply(cases "pcW s", simp_all) apply(simp add:tempR_lemmas tempR_basic_lemmas) apply metis apply(case_tac " tW s = hW s \<and> Data s (numEnqs s) \<le> N", simp_all) apply(simp add:tempR_lemmas tempR_basic_lemmas) apply metis apply(case_tac "hW s < tW s \<and> Data s (numEnqs s) < tW s - hW s", simp_all) apply(simp add:tempR_lemmas tempR_basic_lemmas) apply metis apply(case_tac "tW s < hW s", simp_all) apply(simp add:tempR_lemmas tempR_basic_lemmas) apply metis apply(simp add:tempR_lemmas tempR_basic_lemmas) apply metis apply(simp add:tempR_lemmas tempR_basic_lemmas) apply(intro conjI impI) apply metis apply (metis (no_types, lifting)) apply(simp add:pre_W_def pre_A3_inv_def) apply(simp add:tempR_lemmas tempR_basic_lemmas) apply(intro conjI impI) apply metis apply (metis (no_types, lifting)) apply(simp add:pre_W_def pre_A4_inv_def) apply (metis (no_types, lifting) F.distinct(13) Suc_lessD add.commute less_diff_conv less_trans_Suc) apply(case_tac " Data s (numEnqs s) \<le> N - hW s", simp_all) apply(simp add:tempR_lemmas tempR_basic_lemmas) apply(simp add:pre_W_def pre_A5_inv_def) apply metis apply(case_tac "Data s (numEnqs s) < tW s", simp_all) apply(simp add:tempR_lemmas tempR_basic_lemmas) apply(simp add:pre_W_def pre_A5_inv_def) apply metis apply(simp add:pre_W_def pre_A5_inv_def) apply(simp add:tempR_lemmas tempR_basic_lemmas) apply metis apply(simp add:pre_W_def pre_A6_inv_def) apply(simp add:tempR_lemmas tempR_basic_lemmas) apply(intro conjI impI) apply metis apply (metis (no_types, lifting)) apply (metis (mono_tags, hide_lams) F.distinct(13) le_trans less_or_eq_imp_le nat_neq_iff) apply(simp add:pre_W_def pre_A7_inv_def) apply(simp add:tempR_lemmas tempR_basic_lemmas) apply(intro conjI impI) apply metis apply (metis (no_types, lifting)) apply(clarify) apply(intro conjI impI) apply (metis F.distinct(13) Suc_lessD less_trans_Suc) apply (metis (mono_tags, hide_lams) F.distinct(13) le_trans less_or_eq_imp_le linorder_neqE_nat) apply(case_tac "N < Data s (numEnqs s)", simp_all) apply(simp add:pre_W_def pre_A8_inv_def) apply(simp add:tempR_lemmas tempR_basic_lemmas) apply metis apply(simp add:tempR_lemmas tempR_basic_lemmas) apply metis apply(simp add:pre_W_def pre_A8_inv_def) defer apply(cases "numEnqs s < n", simp_all) apply(simp add:pre_W_def pre_acquire_inv_def) apply(simp add:tempR_lemmas tempR_basic_lemmas) apply metis apply(simp add:pre_W_def pre_acquire_inv_def) apply(simp add:tempR_lemmas tempR_basic_lemmas) apply metis apply(simp add:pre_W_def pre_OOM_inv_def) apply(simp add:tempR_lemmas tempR_basic_lemmas) apply(cases "tW s \<noteq> T s", simp_all) apply metis apply metis apply(simp add:pre_W_def pre_write_inv_def) apply(simp add:tempR_lemmas tempR_basic_lemmas) apply (metis (no_types, lifting) F.distinct(1) Nat.add_0_right eq_imp_le fst_eqD nat_add_left_cancel_less snd_eqD) apply(simp add:pre_W_def pre_enqueue_inv_def) apply(simp add:tempR_lemmas tempR_basic_lemmas) apply(intro conjI impI) (*solved trivially by case ownership observation*) apply(simp add: tempW_def) apply(case_tac "q s\<noteq>[]") apply (metis (no_types, hide_lams) hd_append2) apply(subgoal_tac "q s=[]") prefer 2 apply force apply(subgoal_tac "tempR s \<noteq>(0,0)") prefer 2 apply blast apply(case_tac "offset s = 0") apply (metis append_Nil fst_conv list.sel(1)) apply(simp add:inv_def) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply clarify apply(subgoal_tac "c=b") prefer 2 apply (metis le_neq_implies_less) apply(subgoal_tac "end(tempR s) = b") prefer 2 apply (metis end_simp le_add_diff_inverse) apply(subgoal_tac "offset s = hW s") prefer 2 apply meson apply(subgoal_tac "i\<ge>c \<and> i<H s \<longrightarrow>ownB s i = W") prefer 2 apply metis apply(subgoal_tac "H s\<le>N") prefer 2 apply metis apply(subgoal_tac "(i<c \<or> i\<ge>H s \<and> i\<le>N) \<longrightarrow>ownB s i\<noteq>W") prefer 2 apply (metis F.distinct(1) F.distinct(5) bot_nat_0.not_eq_extremum diff_is_0_eq zero_less_diff) apply (metis F.distinct(1) add_leD1 end_simp le_eq_less_or_eq linorder_neqE_nat nat_less_le) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply clarify apply (metis eq_imp_le le_add1 le_neq_implies_less plus_nat.add_0) apply(simp add: tempW_def) apply(case_tac "q s=[]") apply (metis (no_types, lifting) F.distinct(1) Nat.add_0_right Suc_le_lessD Suc_lessD Suc_pred add_lessD1 fst_eqD le_add_diff_inverse less_Suc0 less_Suc_eq_le less_add_same_cancel1 list.size(3) nat_add_left_cancel_le nth_Cons_0 self_append_conv2) apply(subgoal_tac "q s\<noteq>[]") prefer 2 apply blast apply(subgoal_tac "\<forall>i<length (q s). fst ((q s) ! i) \<noteq> fst (tempR s)") prefer 2 apply presburger apply(subgoal_tac "fst((offset s, Data s (numEnqs s))) \<noteq> fst(tempR s)") apply (metis less_SucE nth_append nth_append_length) apply(subgoal_tac "offset s \<noteq> fst(tempR s)") prefer 2 apply (metis (no_types, lifting) F.distinct(1) Suc_le_lessD Suc_lessD Suc_pred add_lessD1 le_add_diff_inverse le_refl less_add_same_cancel1) apply(case_tac "case_1 s", simp_all) apply(subgoal_tac "\<forall>i<length (q s). (fst (tempR s) < fst ((q s ) ! i) \<longrightarrow> fst (tempR s) + Data s (numReads s - Suc 0) \<le> fst ((q s ) ! i)) \<and> (fst ((q s) ! i) < fst (tempR s) \<longrightarrow> fst ((q s) ! i) + snd ((q s ) ! i) \<le> fst (tempR s))") prefer 2 apply (metis (no_types, lifting) gr_implies_not0 length_0_conv) apply(subgoal_tac "(fst (tempR s) < fst(offset s, Data s (numEnqs s)) \<longrightarrow> fst (tempR s) + Data s (numReads s - Suc 0) \<le> fst(offset s, Data s (numEnqs s))) \<and> (fst(offset s, Data s (numEnqs s)) < fst (tempR s) \<longrightarrow> end(offset s, Data s (numEnqs s)) \<le> fst (tempR s))") apply (smt (z3) end_simp less_SucE nth_append nth_append_length) apply(intro conjI impI) apply (metis (no_types, lifting) Nat.add_0_right fst_eqD le_eq_less_or_eq less_add_same_cancel1 less_nat_zero_code nat_neq_iff snd_eqD tempW_def) apply(simp add:inv_def) apply(case_tac "case_1 s", simp_all) apply (simp add:case_1_def) apply(clarify) apply (metis (no_types, lifting) F.distinct(1) diff_is_0_eq le_refl less_imp_le_nat not_gr0 prod.collapse prod.inject tempW_def zero_less_diff) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply clarify apply (metis less_or_eq_imp_le zero_less_iff_neq_zero) apply(simp add: tempW_def) apply(subgoal_tac "end((offset s, Data s (numEnqs s))) \<noteq> fst(tempR s)") apply (metis end_simp fst_conv snd_conv) apply(subgoal_tac "offset s \<noteq> fst(tempR s)") prefer 2 apply (metis (no_types, lifting) F.distinct(1) Suc_le_lessD Suc_lessD Suc_pred add_lessD1 le_add_diff_inverse le_refl less_add_same_cancel1) apply(simp add:inv_def) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply(clarify) apply linarith apply(simp add:case_2_def) apply (thin_tac "\<not>case_1 s") apply(clarify) by (metis add_gr_0 nat_neq_iff) lemma GLOBAL_W_step_shows_preR: assumes "inv s" and "con_assms s" and "pre_R (pcR s) s" and "pre_W (pcW s) s" and "cW_step (pcW s) s s'" shows "pre_R (pcR s') s'" using assms apply simp apply(subgoal_tac "pcR s' = pcR s") prefer 2 using pcR_doesnt_change_with_W [where s=s and s'=s'] apply simp apply(simp add:pre_R_def) apply(case_tac "pcR s") apply simp_all using preRelease_doesnt_change_with_W [where s=s and s'=s'] apply simp using preIdleR_doesnt_change_with_W [where s=s and s'=s'] apply simp using preRead_doesnt_change_with_W [where s=s and s'=s'] by simp (*******************************GLOBAL R_step shows preW*************************************) lemma pcW_doesnt_change_with_R: assumes "inv s" and "con_assms s" and "pre_R (pcR s) s" and "pre_W (pcW s) s" and "cR_step (pcR s) s s'" shows "pcW s'=pcW s" using assms apply simp apply(case_tac "pcR s ", simp_all add:cR_step_def) by(case_tac "q s=[]", simp_all) lemma ownB_by_W_doesnt_change_after_release: "inv s \<Longrightarrow> con_assms s \<Longrightarrow> pre_Release_inv s \<Longrightarrow> cR_step Release s s' \<Longrightarrow>ownB s i = W \<and> i\<le>N \<Longrightarrow> ownB s' i = W \<and> i\<le>N" apply(simp add:inv_def) apply(simp add:cR_step_def) apply(simp add:pre_Release_inv_def) apply(case_tac "T s \<noteq> fst (tempR s)") apply(case_tac "case_1 s") apply simp apply(simp add:case_1_def) apply metis apply simp apply(simp add:case_2_def) apply (metis F.distinct(7) nat_less_le) apply(case_tac "case_1 s") apply simp by(simp add:case_1_def) lemma ownB_not_by_W_doesnt_change_after_release: "inv s \<Longrightarrow> con_assms s \<Longrightarrow> pre_Release_inv s \<Longrightarrow> cR_step Release s s' \<Longrightarrow>ownB s i \<noteq> W \<and> i\<le>N \<Longrightarrow> ownB s' i \<noteq> W \<and> i\<le>N" apply(simp add:inv_def) by(simp add:cR_step_def) lemma ownB_by_W_doesnt_change_after_read: "inv s \<Longrightarrow> con_assms s \<Longrightarrow> pre_Read_inv s \<Longrightarrow> cR_step Read s s' \<Longrightarrow>ownB s i = W \<and> i\<le>N \<Longrightarrow> ownB s' i = W \<and> i\<le>N" apply(simp add:inv_def) by(simp add:cR_step_def) lemma ownB_not_by_W_doesnt_change_after_read: "inv s \<Longrightarrow> con_assms s \<Longrightarrow> pre_Read_inv s \<Longrightarrow> cR_step Read s s' \<Longrightarrow>ownB s i \<noteq> W \<and> i\<le>N \<Longrightarrow> ownB s' i \<noteq> W \<and> i\<le>N" apply(simp add:inv_def) by(simp add:cR_step_def) lemma ownB_by_W_doesnt_change_after_dequeue: "inv s \<Longrightarrow> con_assms s \<Longrightarrow> pre_dequeue_inv s \<Longrightarrow> cR_step idleR s s' \<Longrightarrow>ownB s i = W \<and> i\<le>N \<Longrightarrow> ownB s' i = W \<and> i\<le>N" apply(simp add:inv_def) apply(simp add:cR_step_def) apply(simp add:pre_dequeue_inv_def) apply(case_tac "q s=[]") apply presburger apply(case_tac "case_1 s") apply simp apply(simp add:case_1_def) apply (metis (no_types, hide_lams) F.distinct(3)) apply simp apply(simp add:case_2_def) by (metis (no_types, hide_lams) F.distinct(3)) lemma ownB_not_by_W_doesnt_change_after_dequeue: "inv s \<Longrightarrow> con_assms s \<Longrightarrow> pre_dequeue_inv s \<Longrightarrow> cR_step idleR s s' \<Longrightarrow>ownB s i \<noteq> W \<and> i\<le>N \<Longrightarrow> ownB s' i \<noteq> W \<and> i\<le>N" apply(simp add:inv_def) apply(simp add:cR_step_def) apply(simp add:pre_dequeue_inv_def) apply(case_tac "q s=[]") apply presburger apply(case_tac "case_1 s") apply simp by(simp add:case_1_def) lemma ownB_by_W_doesnt_change_with_R: "inv s \<Longrightarrow> con_assms s \<Longrightarrow> cR_step (pcR s) s s' \<Longrightarrow> pcR s = Release \<longrightarrow> pre_Release_inv s \<Longrightarrow> pcR s = Read \<longrightarrow> pre_Read_inv s \<Longrightarrow> pcR s = idleR \<longrightarrow> pre_dequeue_inv s \<Longrightarrow>ownB s i = W \<and> i\<le>N \<Longrightarrow> ownB s' i = W \<and> i\<le>N" apply(case_tac "pcR s ") apply simp_all using ownB_by_W_doesnt_change_after_release [where s=s and s'=s' and i=i] apply auto[1] using ownB_by_W_doesnt_change_after_dequeue [where s=s and s'=s' and i=i] apply auto[1] using ownB_by_W_doesnt_change_after_read [where s=s and s'=s' and i=i] by auto[1] lemma ownB_not_by_W_doesnt_change_with_R: "inv s \<Longrightarrow> con_assms s \<Longrightarrow> cR_step (pcR s) s s' \<Longrightarrow> pcR s = Release \<longrightarrow> pre_Release_inv s \<Longrightarrow> pcR s = Read \<longrightarrow> pre_Read_inv s \<Longrightarrow> pcR s = idleR \<longrightarrow> pre_dequeue_inv s \<Longrightarrow>ownB s i \<noteq> W \<and> i\<le>N \<Longrightarrow> ownB s' i \<noteq> W \<and> i\<le>N" apply(case_tac "pcR s ") apply simp_all using ownB_not_by_W_doesnt_change_after_release [where s=s and s'=s' and i=i] apply auto[1] using ownB_not_by_W_doesnt_change_after_dequeue [where s=s and s'=s' and i=i] apply auto[1] using ownB_not_by_W_doesnt_change_after_read [where s=s and s'=s' and i=i] by auto[1] lemma ownB_by_B_doesnt_change_after_release: "inv s \<Longrightarrow> con_assms s \<Longrightarrow> pre_Release_inv s \<Longrightarrow> cR_step Release s s' \<Longrightarrow>ownB s i = B \<and> i\<le>N \<Longrightarrow> ownB s' i = B \<and> i\<le>N" apply(simp add:inv_def) by(simp add:cR_step_def) lemma ownB_by_B_doesnt_change_after_read: "inv s \<Longrightarrow> con_assms s \<Longrightarrow> pre_Read_inv s \<Longrightarrow> cR_step Read s s' \<Longrightarrow>ownB s i = B \<and> i\<le>N \<Longrightarrow> ownB s' i = B \<and> i\<le>N" apply(simp add:inv_def) by(simp add:cR_step_def) lemma ownB_by_B_doesnt_change_after_dequeue: "inv s \<Longrightarrow> con_assms s \<Longrightarrow> pre_dequeue_inv s \<Longrightarrow> cR_step idleR s s' \<Longrightarrow>ownB s i = B \<and> i\<le>N \<Longrightarrow> ownB s' i = B \<and> i\<le>N" apply(simp add:inv_def) apply(simp add:cR_step_def) apply(simp add:pre_dequeue_inv_def) apply(case_tac "q s=[]") apply presburger apply(case_tac "case_1 s") apply simp apply(simp add:case_1_def) apply (metis (no_types, hide_lams) F.distinct(19)) apply(case_tac "q s=[]", simp_all) by force lemma ownB_by_B_doesnt_change_with_R: "inv s \<Longrightarrow> con_assms s \<Longrightarrow> cR_step (pcR s) s s' \<Longrightarrow> pcR s = Release \<longrightarrow> pre_Release_inv s \<Longrightarrow> pcR s = Read \<longrightarrow> pre_Read_inv s \<Longrightarrow> pcR s = idleR \<longrightarrow> pre_dequeue_inv s \<Longrightarrow>ownB s i = B \<and> i\<le>N \<Longrightarrow> ownB s' i = B \<and> i\<le>N" apply(case_tac "pcR s ") apply simp_all using ownB_by_B_doesnt_change_after_release [where s=s and s'=s' and i=i] apply auto[1] using ownB_by_B_doesnt_change_after_dequeue [where s=s and s'=s' and i=i] apply auto[1] using ownB_by_B_doesnt_change_after_read [where s=s and s'=s' and i=i] by auto[1] lemma ownB_by_D_doesnt_change_after_release: "inv s \<Longrightarrow> con_assms s \<Longrightarrow> pre_Release_inv s \<Longrightarrow> cR_step Release s s' \<Longrightarrow>tR s = fst(tempR s) \<Longrightarrow>ownB s i = D \<and> i\<le>N \<Longrightarrow> ownB s' i = D \<and> i\<le>N" apply(simp add:inv_def) by(simp add:cR_step_def) lemma ownB_by_D_doesnt_change_after_read: "inv s \<Longrightarrow> con_assms s \<Longrightarrow> pre_Read_inv s \<Longrightarrow> cR_step Read s s' \<Longrightarrow>ownB s i = D \<and> i\<le>N \<Longrightarrow> ownB s' i = D \<and> i\<le>N" apply(simp add:inv_def) by(simp add:cR_step_def) lemma ownB_by_D_doesnt_change_after_dequeue: "inv s \<Longrightarrow> con_assms s \<Longrightarrow> pre_dequeue_inv s \<Longrightarrow> cR_step idleR s s' \<Longrightarrow>ownB s i = D \<and> i\<le>N \<Longrightarrow> ownB s' i = D \<and> i\<le>N" apply(simp add:inv_def) apply(simp add:cR_step_def) apply(simp add:pre_dequeue_inv_def) apply(case_tac "q s=[]", simp_all) by force lemma W_items_dont_change_with_R: "cR_step (pcR s) s s' \<Longrightarrow>offset s = offset s' \<and> Data s (numEnqs s) = Data s' (numEnqs s') \<and> numEnqs s = numEnqs s' " apply(case_tac "pcR s ") apply simp_all apply(simp_all add:cR_step_def) by(cases "q s=[]", simp_all) lemma W_items_dont_change_with_R_2: "cR_step (pcR s) s s' \<Longrightarrow>tempW s = tempW s' \<and> tW s = tW s' \<and> hW s = hW s' \<and> data_index s = data_index s'" apply(case_tac "pcR s ") apply simp_all apply(simp_all add:cR_step_def tempW_def) by(cases "q s=[]", simp_all) lemma W_items_dont_change_with_R_3: "cR_step (pcR s) s s' \<Longrightarrow>numWrites s=numWrites s' \<and> H s= H s'" apply(case_tac "pcR s ") apply simp_all apply(simp_all add:cR_step_def tempW_def) by(cases "q s=[]", simp_all) lemma ownB_by_D_relation_with_R: "inv s \<Longrightarrow>con_assms s \<Longrightarrow> pre_Read_inv s \<Longrightarrow> pre_enqueue_inv s \<Longrightarrow> offset s \<noteq> fst(tempR s)" apply (simp add:inv_def pre_Read_inv_def pre_enqueue_inv_def) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply(clarify) apply(case_tac "q s=[]") apply(subgoal_tac "b=c") prefer 2 apply (metis nat_less_le) apply(unfold tempW_lemmas tempW_basic_lemmas) apply(subgoal_tac "offset s = c") prefer 2 apply (metis F.distinct(1) F.distinct(5) fst_conv le_iff_add less_or_eq_imp_le nat_less_le snd_conv) apply(subgoal_tac "offset s = b") prefer 2 apply force apply(subgoal_tac "fst(tempR s )\<ge>T s") prefer 2 apply linarith apply(unfold tempR_lemmas tempR_basic_lemmas) apply(subgoal_tac "snd( tempR s )>0") apply metis apply metis apply(subgoal_tac "b<c") prefer 2 apply (metis diff_self_eq_0 le_zero_eq length_0_conv nat_less_le) apply(subgoal_tac "offset s = c") prefer 2 apply (metis F.distinct(1) F.distinct(5) fst_conv le_iff_add less_or_eq_imp_le nat_less_le snd_conv) apply(subgoal_tac "snd(tempR s)>0") apply (metis end_simp) apply (metis end_simp) apply simp apply(simp add:case_2_def) apply clarify apply(case_tac "q s=[]") apply(subgoal_tac "d = fst(tempR s)") prefer 2 apply (metis F.distinct(1) Nat.add_0_right le0 less_nat_zero_code nat_add_left_cancel_less) apply(subgoal_tac "fst(tempW s) = b") prefer 2 apply (metis F.distinct(1) diff_is_0_eq le0 nat_neq_iff zero_less_diff) apply(subgoal_tac "snd(tempW s) > 0") prefer 2 apply (metis snd_eqD tempW_def) apply (metis fst_eqD le_neq_implies_less tempW_def) by (metis F.distinct(1) add_gr_0 le0) lemma R_doesnt_change_q_read_release: "inv s \<Longrightarrow> cR_step (pcR s) s s' \<Longrightarrow> pcR s\<noteq>idleR \<Longrightarrow> q s=q s'" apply(simp add:inv_def cR_step_def) by(case_tac "pcR s", simp_all) lemma R_changes_q_dequeue: "inv s \<Longrightarrow> cR_step (pcR s) s s' \<Longrightarrow> pcR s=idleR \<Longrightarrow>q s\<noteq>[] \<Longrightarrow> tl(q s)=q s'" by(simp add:inv_def cR_step_def) lemma strange_but_Q_1: "q s\<noteq>[] \<Longrightarrow> hd(q s) = q s!0" by (simp add: hd_conv_nth) lemma strange_but_Q_2: "length(q s)>1 \<Longrightarrow>hd(tl(q s)) = tl(q s)!0" by (metis One_nat_def hd_conv_nth length_tl less_nat_zero_code list.size(3) zero_less_diff) lemma strange_but_Q_3: "length(q s)>1 \<Longrightarrow>tl(q s)\<noteq>[]" by (metis Nitpick.size_list_simp(2) One_nat_def less_numeral_extra(4) not_one_less_zero) lemma strange_but_Q_4: "length(q s)>1 \<Longrightarrow>hd(tl(q s)) = q s!1" by (simp add: nth_tl strange_but_Q_2) lemma R_doesnt_change_ownD_release_dequeue: "cR_step (pcR s) s s'\<Longrightarrow> pcR s\<noteq>Read \<Longrightarrow> ownD s= ownD s'" apply(simp add: cR_step_def) apply(case_tac "pcR s", simp_all) by(case_tac "q s=[]", simp_all) lemma R_doesnt_change_ownD_read_except: "cR_step (pcR s) s s'\<Longrightarrow> pcR s=Read \<Longrightarrow> i\<ge>0 \<and> i\<noteq> data_index s (tempR s) \<longrightarrow> ownD s i= ownD s' i" by(simp add: cR_step_def) lemma Q_empty_R_step_result: "cR_step (pcR s) s s' \<Longrightarrow> q s=[] \<Longrightarrow> pcR s=idleR \<Longrightarrow> q s'=[]" by (simp add:cR_step_def) lemma Q_W_relation_through_R_1: "cR_step (pcR s) s s' \<Longrightarrow> q s'\<noteq>[] \<Longrightarrow> q s\<noteq>[] \<Longrightarrow> pcR s = idleR \<Longrightarrow> \<forall>i<length (q s). (offset s < fst (q s ! i) \<longrightarrow> offset s + Data s (numEnqs s) < fst (q s ! i)) \<and> (fst (q s ! i) < offset s \<longrightarrow> fst (q s ! i) + snd (q s ! i) \<le> offset s) \<Longrightarrow> \<forall>i<length (q s'). (offset s' < fst (q s' ! i) \<longrightarrow> offset s' + Data s' (numEnqs s') < fst (q s' ! i)) \<and> (fst (q s' ! i) < offset s' \<longrightarrow> fst (q s' ! i) + snd (q s' ! i) \<le> offset s')" apply(simp add:cR_step_def) by (simp add: length_greater_0_conv nth_tl) lemma Q_W_relation_through_R_2: "cR_step (pcR s) s s' \<Longrightarrow> pcR s = Read \<Longrightarrow> \<forall>i<length (q s). (offset s < fst (q s ! i) \<longrightarrow> offset s + Data s (numEnqs s) < fst (q s ! i)) \<and> (fst (q s ! i) < offset s \<longrightarrow> fst (q s ! i) + snd (q s ! i) \<le> offset s) \<Longrightarrow> \<forall>i<length (q s'). (offset s' < fst (q s' ! i) \<longrightarrow> offset s' + Data s' (numEnqs s') < fst (q s' ! i)) \<and> (fst (q s' ! i) < offset s' \<longrightarrow> fst (q s' ! i) + snd (q s' ! i) \<le> offset s')" by(simp add:cR_step_def) lemma Q_W_relation_through_R_3: "cR_step (pcR s) s s' \<Longrightarrow> pcR s = Release \<Longrightarrow> \<forall>i<length (q s). (offset s < fst (q s ! i) \<longrightarrow> offset s + Data s (numEnqs s) < fst (q s ! i)) \<and> (fst (q s ! i) < offset s \<longrightarrow> fst (q s ! i) + snd (q s ! i) \<le> offset s) \<Longrightarrow> \<forall>i<length (q s'). (offset s' < fst (q s' ! i) \<longrightarrow> offset s' + Data s' (numEnqs s') < fst (q s' ! i)) \<and> (fst (q s' ! i) < offset s' \<longrightarrow> fst (q s' ! i) + snd (q s' ! i) \<le> offset s')" by(simp add:cR_step_def) lemma pre_write_doesnt_change_with_R: assumes "inv s" and "con_assms s" and "pre_write_inv s" and "pre_R (pcR s) s" and "cR_step (pcR s) s s'" shows "pre_write_inv s'" using assms apply simp apply(simp add:pre_write_inv_def) apply(subgoal_tac "end(tempW s )\<le>N") prefer 2 apply(simp_all add:tempW_lemmas tempW_basic_lemmas) apply(simp add:pre_R_def) apply(intro conjI impI) apply(case_tac[!] "pcR s") apply simp_all apply(subgoal_tac "\<forall>i. offset s \<le> i \<and> i < fst (tempW s) + snd (tempW s) \<longrightarrow> ownB s i = W") prefer 2 apply (metis fst_eqD snd_eqD tempW_def) apply(subgoal_tac "hW s = hW s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] using PCR.distinct(1) PCR.distinct(3) assms(2) apply presburger apply(subgoal_tac "tW s = tW s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] using PCR.distinct(1) PCR.distinct(3) assms(2) apply presburger using ownB_by_W_doesnt_change_after_release [where s=s and s'=s'] using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply (metis W_items_dont_change_with_R assms(2) le_trans less_or_eq_imp_le) using ownB_by_W_doesnt_change_with_R [where s=s and s'=s'] using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply (metis PCR.distinct(1) PCR.distinct(5) W_items_dont_change_with_R assms(2) le_trans less_or_eq_imp_le) using ownB_by_W_doesnt_change_with_R [where s=s and s'=s'] using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply (metis PCR.distinct(3) PCR.distinct(5) W_items_dont_change_with_R assms(2) le_trans less_or_eq_imp_le) apply(subgoal_tac "hW s = hW s' \<and> tW s = tW s' \<and> tempW s = tempW s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] using PCR.distinct(1) PCR.distinct(3) assms(2) apply presburger apply(subgoal_tac "tW s \<le>N") prefer 2 apply(simp add:tempW_lemmas tempW_basic_lemmas) apply (metis RingBuffer_BD_latest_2.inv_def basic_pointer_movement_def inRange_def inRangeht_def) using ownB_by_B_doesnt_change_with_R [where s=s and s'=s'] using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply (smt (z3) PCR.distinct(1) PCR.distinct(3) W_items_dont_change_with_R assms(2) le_trans less_or_eq_imp_le) apply(subgoal_tac "hW s = hW s' \<and> tW s = tW s' \<and> tempW s = tempW s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] using PCR.distinct(1) PCR.distinct(5) assms(2) apply presburger apply(subgoal_tac "tW s \<le>N") prefer 2 apply(simp add:tempW_lemmas tempW_basic_lemmas) apply (metis RingBuffer_BD_latest_2.inv_def basic_pointer_movement_def inRange_def inRangeht_def) using ownB_by_B_doesnt_change_with_R [where s=s and s'=s'] using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply (smt (z3) PCR.distinct(1) PCR.distinct(5) W_items_dont_change_with_R assms(2) le_trans less_or_eq_imp_le) apply(subgoal_tac "hW s = hW s' \<and> tW s = tW s' \<and> tempW s = tempW s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] using PCR.distinct(3) PCR.distinct(5) assms(2) apply presburger apply(subgoal_tac "tW s \<le>N") prefer 2 apply(simp add:tempW_lemmas tempW_basic_lemmas) apply (metis RingBuffer_BD_latest_2.inv_def basic_pointer_movement_def inRange_def inRangeht_def) using ownB_by_B_doesnt_change_with_R [where s=s and s'=s'] using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply (smt (z3) PCR.distinct(3) PCR.distinct(5) W_items_dont_change_with_R assms(2) le_trans less_or_eq_imp_le) apply clarify apply(intro conjI impI) apply(subgoal_tac "hW s = hW s' \<and> tW s = tW s' \<and> tempW s = tempW s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] using PCR.distinct(1) PCR.distinct(3) assms(2) apply presburger apply(subgoal_tac "tW s \<le>N") prefer 2 apply(simp add:tempW_lemmas tempW_basic_lemmas) apply(simp add:inv_def) using ownB_by_B_doesnt_change_with_R [where s=s and s'=s'] apply (metis PCR.distinct(1) PCR.distinct(3) W_items_dont_change_with_R assms(1) assms(2) less_or_eq_imp_le) using ownB_by_B_doesnt_change_with_R [where s=s and s'=s'] using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply (smt (z3) PCR.distinct(1) PCR.distinct(3) W_items_dont_change_with_R assms(2) le_add_same_cancel1 le_trans less_or_eq_imp_le not_gr_zero) apply clarify apply(intro conjI impI) apply(subgoal_tac "hW s = hW s' \<and> tW s = tW s' \<and> tempW s = tempW s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] using PCR.distinct(1) PCR.distinct(5) assms(2) apply presburger apply(subgoal_tac "tW s \<le>N") prefer 2 apply(simp add:tempW_lemmas tempW_basic_lemmas) apply(simp add:inv_def) apply (metis assms(1) assms(2) less_or_eq_imp_le ownB_by_B_doesnt_change_after_dequeue prod.inject tempW_def) using ownB_by_B_doesnt_change_with_R [where s=s and s'=s'] using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply (metis PCR.distinct(1) PCR.distinct(5) add_leD1 assms(2) fst_conv less_le_not_le order_trans tempW_def) apply clarify apply(intro conjI impI) apply(subgoal_tac "hW s = hW s' \<and> tW s = tW s' \<and> tempW s = tempW s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] using PCR.distinct(3) PCR.distinct(5) assms(2) apply presburger apply(subgoal_tac "tW s \<le>N") prefer 2 apply(simp add:tempW_lemmas tempW_basic_lemmas) apply(simp add:inv_def) apply (metis assms(1) assms(2) less_or_eq_imp_le ownB_by_B_doesnt_change_after_read prod.inject tempW_def) using ownB_by_B_doesnt_change_with_R [where s=s and s'=s'] using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply (metis PCR.distinct(3) PCR.distinct(5) add_leD1 assms(2) fst_conv less_le_not_le order_trans tempW_def) apply clarify apply(subgoal_tac "hW s = hW s' \<and> tW s = tW s' \<and> tempW s = tempW s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] using PCR.distinct(1) PCR.distinct(3) assms(2) apply presburger apply(subgoal_tac "tW s \<le>N") prefer 2 apply(simp add:tempW_lemmas tempW_basic_lemmas) apply(simp add:inv_def) using ownB_by_B_doesnt_change_with_R [where s=s and s'=s'] using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply (smt (z3) PCR.distinct(1) PCR.distinct(3) W_items_dont_change_with_R assms(2) le_trans less_or_eq_imp_le) apply clarify apply(subgoal_tac "hW s = hW s' \<and> tW s = tW s' \<and> tempW s = tempW s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] using PCR.distinct(1) PCR.distinct(5) assms(2) apply presburger apply(subgoal_tac "tW s \<le>N") prefer 2 apply(simp add:tempW_lemmas tempW_basic_lemmas) apply(simp add:inv_def) using ownB_by_B_doesnt_change_with_R [where s=s and s'=s'] using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply (smt (z3) PCR.distinct(1) PCR.distinct(5) W_items_dont_change_with_R assms(2) le_trans less_or_eq_imp_le) apply clarify apply(subgoal_tac "hW s = hW s' \<and> tW s = tW s' \<and> tempW s = tempW s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] using PCR.distinct(3) PCR.distinct(5) assms(2) apply presburger apply(subgoal_tac "tW s \<le>N") prefer 2 apply(simp add:tempW_lemmas tempW_basic_lemmas) apply(simp add:inv_def) using ownB_by_B_doesnt_change_with_R [where s=s and s'=s'] using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply (smt (z3) PCR.distinct(3) PCR.distinct(5) W_items_dont_change_with_R assms(2) le_trans less_or_eq_imp_le) apply(case_tac "tR s = fst(tempR s)") using ownB_by_D_doesnt_change_after_release [where s=s and s'=s'] apply (metis W_items_dont_change_with_R \<open>cR_step (pcR s) s s' \<Longrightarrow> tempW s = tempW s' \<and> tW s = tW s' \<and> hW s = hW s' \<and> data_index s = data_index s'\<close> assms(2) nat_less_le) apply (simp add:inv_def) apply(case_tac "case_1 s", simp_all) apply(simp add: case_1_def) apply (metis (no_types, hide_lams) F.distinct(25) F.distinct(7) \<open>cR_step (pcR s) s s' \<Longrightarrow> tempW s = tempW s' \<and> tW s = tW s' \<and> hW s = hW s' \<and> data_index s = data_index s'\<close> le0 le_refl nat_less_le nat_neq_iff prod.inject tempW_def) apply(thin_tac "\<not>case_1 s") apply(simp add:pre_Release_inv_def) apply(subgoal_tac "T s\<noteq>fst(tempR s)") prefer 2 apply blast apply(simp add:case_2_def) apply clarify apply(subgoal_tac "fst(tempR s) = T s \<or> fst(tempR s) = 0") prefer 2 apply meson apply(subgoal_tac "fst(tempR s) = 0") prefer 2 apply presburger apply(subgoal_tac "ownB s (fst(tempR s)) = R") prefer 2 apply metis apply(subgoal_tac "ownB s (offset s) = W") prefer 2 apply (metis Nat.add_0_right le_refl nat_add_left_cancel_less) apply (metis F.distinct(1) W_items_dont_change_with_R) using ownB_by_D_doesnt_change_after_dequeue [where s=s and s'=s'] using W_items_dont_change_with_R \<open>cR_step (pcR s) s s' \<Longrightarrow> tempW s = tempW s' \<and> tW s = tW s' \<and> hW s = hW s' \<and> data_index s = data_index s'\<close> assms(2) less_or_eq_imp_le apply presburger using ownB_by_D_doesnt_change_after_read [where s=s and s'=s'] using W_items_dont_change_with_R \<open>cR_step (pcR s) s s' \<Longrightarrow> tempW s = tempW s' \<and> tW s = tW s' \<and> hW s = hW s' \<and> data_index s = data_index s'\<close> assms(2) less_or_eq_imp_le apply presburger apply(subgoal_tac "hW s = hW s' \<and> tW s = tW s' \<and> tempW s = tempW s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] using PCR.distinct(1) PCR.distinct(3) assms(2) apply presburger apply (simp add: pre_Release_inv_def) apply(subgoal_tac "hW s = hW s' \<and> tW s = tW s' \<and> tempW s = tempW s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] using PCR.distinct(1) PCR.distinct(5) assms(2) apply presburger apply (simp add: pre_dequeue_inv_def inv_def Q_lemmas Q_basic_lemmas cR_step_def) apply(subgoal_tac "hW s = hW s' \<and> tW s = tW s' \<and> tempW s = tempW s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] using PCR.distinct(3) PCR.distinct(5) assms(2) apply presburger apply(simp add: pre_Read_inv_def) apply(simp add:cR_step_def) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "ownT s = R", simp_all) apply(case_tac "ownT s = R", simp_all) apply(simp add:cR_step_def) apply(case_tac "q s=[]", simp_all) apply(case_tac "ownT s = Q", simp_all) apply(simp add:cR_step_def) apply(simp add:cR_step_def) apply(simp add:cR_step_def) apply(case_tac "q s=[]", simp_all) apply(simp add:cR_step_def) apply(simp add:cR_step_def) apply(simp add:cR_step_def) apply(case_tac "q s=[]", simp_all) apply(simp add:cR_step_def) apply(simp add:cR_step_def) apply(simp add:cR_step_def) apply(case_tac "q s=[]", simp_all) apply(simp add:cR_step_def) apply(simp add:cR_step_def) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "ownT s = R", simp_all) apply(case_tac "ownT s = R", simp_all) apply(simp add:cR_step_def) apply(case_tac "q s=[]", simp_all) apply(case_tac "ownT s = Q", simp_all) apply (metis last_tl) apply (metis last_tl) apply(simp add:cR_step_def) apply(simp add:cR_step_def) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "ownT s = R", simp_all) apply(case_tac "ownT s = R", simp_all) apply(simp add:cR_step_def) apply(case_tac "q s=[]", simp_all) apply(case_tac "ownT s = Q", simp_all) apply(subgoal_tac "hW s = hW s' \<and> tW s = tW s' \<and> tempW s = tempW s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply (metis assms(5)) apply(subgoal_tac "(\<forall>i<length (q s). fst (q s ! i) \<noteq> offset s)") prefer 2 apply presburger apply(subgoal_tac "(\<forall>i<length (tl(q s)). fst (tl(q s) ! i) \<noteq> offset s)") prefer 2 apply (metis Suc_diff_Suc diff_Suc_eq_diff_pred diff_add_0 length_tl linordered_semidom_class.add_diff_inverse nat.discI nth_tl) apply(subgoal_tac "length(q s) - Suc 0 = length(tl(q s))") prefer 2 apply (metis One_nat_def length_tl) apply presburger apply(subgoal_tac "hW s = hW s' \<and> tW s = tW s' \<and> tempW s = tempW s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply (metis assms(5)) apply(subgoal_tac "(\<forall>i<length (q s). fst (q s ! i) \<noteq> offset s)") prefer 2 apply presburger apply(subgoal_tac "(\<forall>i<length (tl(q s)). fst (tl(q s) ! i) \<noteq> offset s)") prefer 2 apply (metis Suc_diff_Suc diff_Suc_eq_diff_pred diff_add_0 length_tl linordered_semidom_class.add_diff_inverse nat.discI nth_tl) apply (metis One_nat_def length_tl) apply(subgoal_tac "hW s = hW s' \<and> tW s = tW s' \<and> tempW s = tempW s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply (metis assms(5)) apply(subgoal_tac "(\<forall>i<length (q s). fst (q s ! i) \<noteq> offset s)") prefer 2 apply (metis length_0_conv less_nat_zero_code) apply(subgoal_tac "offset s' = offset s") prefer 2 apply (metis fst_conv tempW_def) apply(subgoal_tac "q s= q s'") apply metis using R_doesnt_change_q_read_release [where s=s and s'=s'] apply (metis PCR.distinct(5) assms(5)) using Q_W_relation_through_R_3 [where s=s and s'=s'] apply (simp add: \<open>\<lbrakk>RingBuffer_BD_latest_2.inv s; cR_step (pcR s) s s'; pcR s \<noteq> idleR\<rbrakk> \<Longrightarrow> q s = q s'\<close>) apply(subgoal_tac "q s\<noteq>[]") prefer 2 apply (metis Q_empty_R_step_result) using Q_W_relation_through_R_1 [where s=s and s'=s'] apply presburger using Q_W_relation_through_R_2 [where s=s and s'=s'] apply (simp add: \<open>\<lbrakk>RingBuffer_BD_latest_2.inv s; cR_step (pcR s) s s'; pcR s \<noteq> idleR\<rbrakk> \<Longrightarrow> q s = q s'\<close>) apply(subgoal_tac "q s=q s'") prefer 2 using R_doesnt_change_q_read_release [where s=s and s'=s'] using PCR.distinct(1) apply presburger apply(subgoal_tac "offset s + Data s (numEnqs s) \<noteq> fst (hd (q s))") prefer 2 apply metis apply(subgoal_tac "tempW s=tempW s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply (metis) apply (metis W_items_dont_change_with_R) apply(subgoal_tac "offset s + Data s (numEnqs s) \<noteq> fst (hd (q s))") prefer 2 using cR_step_def apply force apply(subgoal_tac "i<length(q s)\<longrightarrow>offset s + Data s (numEnqs s) \<noteq> fst(q s ! i)") prefer 2 apply (metis diff_add_zero length_0_conv less_irrefl_nat less_nat_zero_code linordered_semidom_class.add_diff_inverse) apply(subgoal_tac "q s\<noteq>[]") prefer 2 using PCR.simps(8) cR_step_def apply force apply(subgoal_tac "fst(hd(q s')) = fst(hd(tl(q s)))") prefer 2 using R_changes_q_dequeue apply presburger apply(subgoal_tac "tempW s=tempW s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] using PCR.distinct(1) PCR.distinct(5) assms(2) apply presburger apply(subgoal_tac "offset s' = offset s") prefer 2 apply (metis fst_conv tempW_def) apply(subgoal_tac "fst(hd(tl(q s))) = fst(q s!1)") prefer 2 using strange_but_Q_4 [where s=s] fst_def apply (metis R_changes_q_dequeue length_greater_0_conv length_tl zero_less_diff) apply (metis R_changes_q_dequeue cancel_comm_monoid_add_class.diff_cancel le_iff_add length_0_conv length_tl less_one linorder_neqE_nat nat_less_le snd_conv tempW_def) apply(subgoal_tac "q s=q s'") prefer 2 using R_doesnt_change_q_read_release [where s=s and s'=s'] using PCR.distinct(5) apply presburger apply(subgoal_tac "offset s + Data s (numEnqs s) \<noteq> fst (hd (q s))") prefer 2 apply metis apply(subgoal_tac "tempW s=tempW s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply (metis) apply (metis W_items_dont_change_with_R) apply clarify using W_items_dont_change_with_R [where s=s and s'=s'] using W_items_dont_change_with_R_2 [where s=s and s'=s'] using ownB_by_W_doesnt_change_with_R [where s=s and s'=s' and i=j] apply (metis \<open>\<And>i. \<lbrakk>RingBuffer_BD_latest_2.inv s; con_assms s; pre_Release_inv s; cR_step Release s s'; ownB s i = W \<and> i \<le> N\<rbrakk> \<Longrightarrow> ownB s' i = W \<and> i \<le> N\<close> assms(1) assms(2) le_trans less_imp_le_nat) apply clarify using W_items_dont_change_with_R [where s=s and s'=s'] using W_items_dont_change_with_R_2 [where s=s and s'=s'] using ownB_by_W_doesnt_change_with_R [where s=s and s'=s' and i=j] apply (metis PCR.distinct(1) PCR.distinct(5) \<open>\<And>i. \<lbrakk>RingBuffer_BD_latest_2.inv s; con_assms s; cR_step (pcR s) s s'; pcR s = Release \<longrightarrow> pre_Release_inv s; pcR s = Read \<longrightarrow> pre_Read_inv s; pcR s = idleR \<longrightarrow> pre_dequeue_inv s; ownB s i = W \<and> i \<le> N\<rbrakk> \<Longrightarrow> ownB s' i = W \<and> i \<le> N\<close> assms(2) le_trans less_imp_le_nat) using W_items_dont_change_with_R [where s=s and s'=s'] using W_items_dont_change_with_R_2 [where s=s and s'=s'] using ownB_by_W_doesnt_change_with_R [where s=s and s'=s' and i=j] apply (metis PCR.distinct(3) PCR.distinct(5) \<open>\<And>i. \<lbrakk>RingBuffer_BD_latest_2.inv s; con_assms s; cR_step (pcR s) s s'; pcR s = Release \<longrightarrow> pre_Release_inv s; pcR s = Read \<longrightarrow> pre_Read_inv s; pcR s = idleR \<longrightarrow> pre_dequeue_inv s; ownB s i = W \<and> i \<le> N\<rbrakk> \<Longrightarrow> ownB s' i = W \<and> i \<le> N\<close> assms(2) le_trans less_imp_le_nat) apply(subgoal_tac "numWrites s= numWrites s'") prefer 2 apply (metis W_items_dont_change_with_R_3 assms(5)) using R_doesnt_change_ownD_release_dequeue [where s=s and s'=s'] apply (metis PCR.distinct(3)) apply(subgoal_tac "numWrites s= numWrites s'") prefer 2 apply (metis W_items_dont_change_with_R_3 assms(5)) using R_doesnt_change_ownD_release_dequeue [where s=s and s'=s'] apply (metis PCR.distinct(5)) apply(subgoal_tac "numWrites s= numWrites s'") prefer 2 apply (metis W_items_dont_change_with_R_3 assms(5)) apply(subgoal_tac "numWrites s \<noteq> data_index s (tempR s) ") prefer 2 apply(simp add:pre_Read_inv_def) using R_doesnt_change_ownD_read_except [where s=s and s'=s'] apply (metis less_eq_nat.simps(1)) apply(subgoal_tac "q s=q s'") prefer 2 using R_doesnt_change_q_read_release [where s=s and s'=s'] using PCR.distinct(1) apply presburger apply (metis W_items_dont_change_with_R) apply(simp add:inv_def pre_dequeue_inv_def) apply(subgoal_tac "numEnqs s= 0") prefer 2 using W_items_dont_change_with_R apply presburger apply(subgoal_tac "numDeqs s = 0") prefer 2 apply (metis less_nat_zero_code nat_less_le) apply(subgoal_tac "q s=[]") prefer 2 apply meson apply(simp add:cR_step_def) apply(subgoal_tac "q s=q s'") prefer 2 using R_doesnt_change_q_read_release [where s=s and s'=s'] using PCR.distinct(5) apply presburger apply (metis W_items_dont_change_with_R) using W_items_dont_change_with_R [where s=s and s'=s'] using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply metis using W_items_dont_change_with_R [where s=s and s'=s'] using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply metis using W_items_dont_change_with_R [where s=s and s'=s'] using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply metis using W_items_dont_change_with_R [where s=s and s'=s'] using W_items_dont_change_with_R_2 [where s=s and s'=s'] using W_items_dont_change_with_R_3 [where s=s and s'=s'] apply (metis) using W_items_dont_change_with_R [where s=s and s'=s'] using W_items_dont_change_with_R_2 [where s=s and s'=s'] using W_items_dont_change_with_R_3 [where s=s and s'=s'] apply (metis) using W_items_dont_change_with_R [where s=s and s'=s'] using W_items_dont_change_with_R_2 [where s=s and s'=s'] using W_items_dont_change_with_R_3 [where s=s and s'=s'] by (metis) lemma pre_enqueue_doesnt_change_with_R: assumes "inv s" and "con_assms s" and "pre_enqueue_inv s" and "pre_R (pcR s) s" and "cR_step (pcR s) s s'" shows "pre_enqueue_inv s'" using assms apply simp apply(simp add:pre_enqueue_inv_def) apply(subgoal_tac "end(tempW s )\<le>N") prefer 2 apply(simp add:tempW_lemmas tempW_basic_lemmas) apply(simp add:pre_R_def) apply(intro conjI impI) apply(case_tac[!] "pcR s") apply simp_all apply(subgoal_tac "\<forall>i. offset s \<le> i \<and> i < fst (tempW s) + snd (tempW s) \<longrightarrow> ownB s i = W") prefer 2 apply metis apply(subgoal_tac "\<forall>i. offset s > i \<or> i \<ge> fst (tempW s) + snd (tempW s) \<and> i\<le>N \<longrightarrow> ownB s i \<noteq> W") prefer 2 apply metis apply(subgoal_tac "hW s = hW s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] using PCR.distinct(1) PCR.distinct(3) assms(2) apply presburger apply(subgoal_tac "tW s = tW s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] using PCR.distinct(1) PCR.distinct(3) assms(2) apply presburger using ownB_by_W_doesnt_change_after_release [where s=s and s'=s'] using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply (metis PCR.distinct(1) PCR.distinct(3) W_items_dont_change_with_R assms(2) end_simp le_trans less_or_eq_imp_le) using ownB_by_W_doesnt_change_with_R [where s=s and s'=s'] using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply (metis PCR.distinct(1) PCR.distinct(5) W_items_dont_change_with_R assms(2) le_trans less_or_eq_imp_le) using ownB_by_W_doesnt_change_with_R [where s=s and s'=s'] using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply (metis PCR.distinct(3) PCR.distinct(5) W_items_dont_change_with_R assms(2) le_trans less_or_eq_imp_le) apply clarify apply (intro conjI impI) using ownB_not_by_W_doesnt_change_with_R [where s=s and s'=s'] using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply (metis PCR.distinct(1) PCR.distinct(3) add_leD1 assms(2) fst_conv less_le_not_le order_trans tempW_def) using ownB_not_by_W_doesnt_change_with_R [where s=s and s'=s'] using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply (metis PCR.distinct(1) PCR.distinct(3) add_leD1 assms(2) fst_conv less_le_not_le order_trans tempW_def) using ownB_not_by_W_doesnt_change_with_R [where s=s and s'=s'] using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply clarify apply (intro conjI impI) using ownB_not_by_W_doesnt_change_with_R [where s=s and s'=s'] using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply (metis PCR.distinct(1) PCR.distinct(5) add_leD1 assms(2) fst_conv le_imp_less_Suc nat_le_linear not_less_eq order_trans tempW_def) using ownB_not_by_W_doesnt_change_with_R [where s=s and s'=s'] using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply (metis PCR.distinct(1) PCR.distinct(5) add_leD1 assms(2) fst_conv le_imp_less_Suc nat_le_linear not_less_eq order_trans tempW_def) apply clarify apply (intro conjI impI) apply(subgoal_tac "i<offset s \<longrightarrow>ownB s i\<noteq>W") prefer 2 apply presburger apply(subgoal_tac "offset s = offset s'") prefer 2 using PCR.distinct(3) PCR.distinct(5) W_items_dont_change_with_R assms(2) apply presburger using ownB_not_by_W_doesnt_change_with_R [where s=s and s'=s'] using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply (metis PCR.distinct(3) PCR.distinct(5) add_leD1 assms(2) fst_conv less_le_not_le order_trans tempW_def) using ownB_not_by_W_doesnt_change_with_R [where s=s and s'=s'] using W_items_dont_change_with_R_2 [where s=s and s'=s'] using PCR.distinct(3) PCR.distinct(5) assms(2) apply presburger apply(subgoal_tac "hW s = hW s' \<and> tW s = tW s' \<and> tempW s = tempW s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] using PCR.distinct(1) PCR.distinct(3) assms(2) apply presburger apply(subgoal_tac "tW s \<le>N") prefer 2 apply(simp add:tempW_lemmas tempW_basic_lemmas) apply (metis RingBuffer_BD_latest_2.inv_def basic_pointer_movement_def inRange_def inRangeht_def) using ownB_by_B_doesnt_change_with_R [where s=s and s'=s'] using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply (metis PCR.distinct(1) PCR.distinct(3) assms(2) le_trans less_or_eq_imp_le) apply(subgoal_tac "hW s = hW s' \<and> tW s = tW s' \<and> tempW s = tempW s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] using PCR.distinct(1) PCR.distinct(5) assms(2) apply presburger apply(subgoal_tac "tW s \<le>N") prefer 2 apply(simp add:tempW_lemmas tempW_basic_lemmas) apply (metis RingBuffer_BD_latest_2.inv_def basic_pointer_movement_def inRange_def inRangeht_def) using ownB_by_B_doesnt_change_with_R [where s=s and s'=s'] using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply (metis PCR.distinct(1) PCR.distinct(5) assms(2) le_trans less_or_eq_imp_le) apply(subgoal_tac "hW s = hW s' \<and> tW s = tW s' \<and> tempW s = tempW s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] using PCR.distinct(3) PCR.distinct(5) assms(2) apply presburger apply(subgoal_tac "tW s \<le>N") prefer 2 apply(simp add:tempW_lemmas tempW_basic_lemmas) apply (metis RingBuffer_BD_latest_2.inv_def basic_pointer_movement_def inRange_def inRangeht_def) using ownB_by_B_doesnt_change_with_R [where s=s and s'=s'] using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply (metis PCR.distinct(3) PCR.distinct(5) assms(2) le_trans less_or_eq_imp_le) apply clarify apply(intro conjI impI) apply(subgoal_tac "hW s = hW s' \<and> tW s = tW s' \<and> tempW s = tempW s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] using PCR.distinct(1) PCR.distinct(3) assms(2) apply presburger apply(subgoal_tac "tW s \<le>N") prefer 2 apply(simp add:tempW_lemmas tempW_basic_lemmas) apply(simp add:inv_def) apply (metis assms(1) assms(2) less_or_eq_imp_le ownB_by_B_doesnt_change_after_release prod.inject tempW_def) using ownB_by_B_doesnt_change_with_R [where s=s and s'=s'] using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply (metis PCR.distinct(1) PCR.distinct(3) add_leD1 assms(2) fst_conv less_le_not_le order_trans tempW_def) apply clarify apply(intro conjI impI) apply(subgoal_tac "hW s = hW s' \<and> tW s = tW s' \<and> tempW s = tempW s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] using PCR.distinct(1) PCR.distinct(5) assms(2) apply presburger apply(subgoal_tac "tW s \<le>N") prefer 2 apply(simp add:tempW_lemmas tempW_basic_lemmas) apply(simp add:inv_def) apply (metis assms(1) assms(2) less_or_eq_imp_le ownB_by_B_doesnt_change_after_dequeue prod.inject tempW_def) using ownB_by_B_doesnt_change_with_R [where s=s and s'=s'] using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply (metis PCR.distinct(1) PCR.distinct(5) add_leD1 assms(2) fst_conv less_le_not_le order_trans tempW_def) apply clarify apply(intro conjI impI) apply(subgoal_tac "hW s = hW s' \<and> tW s = tW s' \<and> tempW s = tempW s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] using PCR.distinct(3) PCR.distinct(5) assms(2) apply presburger apply(subgoal_tac "tW s \<le>N") prefer 2 apply(simp add:tempW_lemmas tempW_basic_lemmas) apply(simp add:inv_def) apply (metis assms(1) assms(2) less_or_eq_imp_le ownB_by_B_doesnt_change_after_read prod.inject tempW_def) using ownB_by_B_doesnt_change_with_R [where s=s and s'=s'] using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply (metis PCR.distinct(3) PCR.distinct(5) add_leD1 assms(2) fst_conv less_le_not_le order_trans tempW_def) apply clarify apply(subgoal_tac "hW s = hW s' \<and> tW s = tW s' \<and> tempW s = tempW s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] using PCR.distinct(1) PCR.distinct(3) assms(2) apply presburger apply(subgoal_tac "tW s \<le>N") prefer 2 apply(simp add:tempW_lemmas tempW_basic_lemmas) apply(simp add:inv_def) using ownB_by_B_doesnt_change_with_R [where s=s and s'=s'] using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply (metis PCR.distinct(1) PCR.distinct(3) add_leD1 assms(2) fst_conv less_le_not_le order_trans tempW_def) apply clarify apply(subgoal_tac "hW s = hW s' \<and> tW s = tW s' \<and> tempW s = tempW s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] using PCR.distinct(1) PCR.distinct(5) assms(2) apply presburger apply(subgoal_tac "tW s \<le>N") prefer 2 apply(simp add:tempW_lemmas tempW_basic_lemmas) apply(simp add:inv_def) using ownB_by_B_doesnt_change_with_R [where s=s and s'=s'] using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply (metis PCR.distinct(1) PCR.distinct(5) add_leD1 assms(2) fst_conv less_le_not_le order_trans tempW_def) apply clarify apply(subgoal_tac "hW s = hW s' \<and> tW s = tW s' \<and> tempW s = tempW s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] using PCR.distinct(3) PCR.distinct(5) assms(2) apply presburger apply(subgoal_tac "tW s \<le>N") prefer 2 apply(simp add:tempW_lemmas tempW_basic_lemmas) apply(simp add:inv_def) using ownB_by_B_doesnt_change_with_R [where s=s and s'=s'] using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply (metis PCR.distinct(3) PCR.distinct(5) add_leD1 assms(2) fst_conv less_le_not_le order_trans tempW_def) apply(case_tac "tR s = fst(tempR s)") using ownB_by_D_doesnt_change_after_release [where s=s and s'=s'] apply (metis W_items_dont_change_with_R \<open>cR_step (pcR s) s s' \<Longrightarrow> tempW s = tempW s' \<and> tW s = tW s' \<and> hW s = hW s' \<and> data_index s = data_index s'\<close> assms(2) nat_less_le) apply (simp add:inv_def) apply(case_tac "case_1 s", simp_all) apply(simp add: case_1_def) apply (metis F.distinct(15) F.distinct(21) F.distinct(25) F.distinct(7) W_items_dont_change_with_R \<open>cR_step (pcR s) s s' \<Longrightarrow> tempW s = tempW s' \<and> tW s = tW s' \<and> hW s = hW s' \<and> data_index s = data_index s'\<close> less_eq_Suc_le not_less_eq_eq) apply(thin_tac "\<not>case_1 s") apply(simp add:pre_Release_inv_def) apply(subgoal_tac "T s\<noteq>fst(tempR s)") prefer 2 apply blast apply(simp add:case_2_def) apply clarify apply(subgoal_tac "fst(tempR s) = T s \<or> fst(tempR s) = 0") prefer 2 apply meson apply(subgoal_tac "fst(tempR s) = 0") prefer 2 apply presburger apply(subgoal_tac "ownB s (fst(tempR s)) = R") prefer 2 apply metis apply(subgoal_tac "ownB s (offset s) = W") prefer 2 apply (metis \<open>cR_step (pcR s) s s' \<Longrightarrow> tempW s = tempW s' \<and> tW s = tW s' \<and> hW s = hW s' \<and> data_index s = data_index s'\<close> fst_eqD nat_le_iff_add plus_nat.add_0 snd_eqD tempW_def) apply (metis F.distinct(1) W_items_dont_change_with_R) using ownB_by_D_doesnt_change_after_dequeue [where s=s and s'=s'] using W_items_dont_change_with_R \<open>cR_step (pcR s) s s' \<Longrightarrow> tempW s = tempW s' \<and> tW s = tW s' \<and> hW s = hW s' \<and> data_index s = data_index s'\<close> assms(2) less_or_eq_imp_le apply presburger using ownB_by_D_doesnt_change_after_read [where s=s and s'=s'] using W_items_dont_change_with_R \<open>cR_step (pcR s) s s' \<Longrightarrow> tempW s = tempW s' \<and> tW s = tW s' \<and> hW s = hW s' \<and> data_index s = data_index s'\<close> assms(2) less_or_eq_imp_le apply presburger apply(subgoal_tac "hW s = hW s' \<and> tW s = tW s' \<and> tempW s = tempW s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] using PCR.distinct(1) PCR.distinct(3) assms(2) apply presburger apply (simp add: pre_Release_inv_def) apply(subgoal_tac "hW s = hW s' \<and> tW s = tW s' \<and> tempW s = tempW s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] using PCR.distinct(1) PCR.distinct(5) assms(2) apply presburger apply (simp add: pre_dequeue_inv_def inv_def Q_lemmas Q_basic_lemmas cR_step_def) apply(subgoal_tac "hW s = hW s' \<and> tW s = tW s' \<and> tempW s = tempW s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] using PCR.distinct(3) PCR.distinct(5) assms(2) apply presburger apply(simp add: pre_Read_inv_def) apply(simp add:cR_step_def) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "ownT s = R", simp_all) apply(case_tac "ownT s = R", simp_all) apply(simp add:cR_step_def) apply(case_tac "q s=[]", simp_all) apply(case_tac "ownT s = Q", simp_all) apply(simp add:cR_step_def) apply(simp add:cR_step_def) apply(simp add:cR_step_def) apply(case_tac "q s=[]", simp_all) apply(simp add:cR_step_def) apply(simp add:cR_step_def) apply(simp add:cR_step_def) apply(case_tac "q s=[]", simp_all) apply(simp add:cR_step_def) apply(simp add:cR_step_def) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "ownT s = R", simp_all) apply(case_tac "ownT s = R", simp_all) apply(simp add:cR_step_def) apply(case_tac "q s=[]", simp_all) apply(case_tac "ownT s = Q", simp_all) apply(simp add:cR_step_def) apply(simp add:tempW_lemmas tempW_basic_lemmas) apply(intro conjI impI) apply(subgoal_tac "hW s = hW s' \<and> tW s = tW s' \<and> tempW s = tempW s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] using PCR.distinct(1) PCR.distinct(3) assms(2) apply presburger apply (metis fst_conv snd_conv tempW_def) apply (metis PCR.distinct(1) R_doesnt_change_q_read_release W_items_dont_change_with_R) apply (metis PCR.distinct(1) R_doesnt_change_q_read_release W_items_dont_change_with_R) apply (metis (no_types, lifting) PCR.distinct(1) R_doesnt_change_q_read_release W_items_dont_change_with_R assms(1) assms(5)) apply (metis PCR.distinct(1) R_doesnt_change_q_read_release W_items_dont_change_with_R) apply (metis W_items_dont_change_with_R \<open>\<And>i. \<lbrakk>RingBuffer_BD_latest_2.inv s; con_assms s; pre_Release_inv s; cR_step Release s s'; ownB s i = W \<and> i \<le> N\<rbrakk> \<Longrightarrow> ownB s' i = W \<and> i \<le> N\<close> assms(2) le_trans less_imp_le_nat) prefer 2 apply(simp add:tempW_lemmas tempW_basic_lemmas) apply(intro conjI impI) apply(subgoal_tac "hW s = hW s' \<and> tW s = tW s' \<and> tempW s = tempW s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] using PCR.distinct(1) PCR.distinct(3) assms(2) apply presburger apply (metis fst_conv snd_conv tempW_def) apply (metis PCR.distinct(5) R_doesnt_change_q_read_release W_items_dont_change_with_R) apply (metis PCR.distinct(5) R_doesnt_change_q_read_release W_items_dont_change_with_R) apply (metis (no_types, lifting) PCR.distinct(5) R_doesnt_change_q_read_release W_items_dont_change_with_R assms(1) assms(5)) apply (metis PCR.distinct(5) R_doesnt_change_q_read_release W_items_dont_change_with_R) apply (metis PCR.distinct(3) PCR.distinct(5) W_items_dont_change_with_R \<open>\<And>i. \<lbrakk>RingBuffer_BD_latest_2.inv s; con_assms s; cR_step (pcR s) s s'; pcR s = Release \<longrightarrow> pre_Release_inv s; pcR s = Read \<longrightarrow> pre_Read_inv s; pcR s = idleR \<longrightarrow> pre_dequeue_inv s; ownB s i = W \<and> i \<le> N\<rbrakk> \<Longrightarrow> ownB s' i = W \<and> i \<le> N\<close> \<open>\<And>i. \<lbrakk>RingBuffer_BD_latest_2.inv s; con_assms s; cR_step (pcR s) s s'; pcR s = Release \<longrightarrow> pre_Release_inv s; pcR s = Read \<longrightarrow> pre_Read_inv s; pcR s = idleR \<longrightarrow> pre_dequeue_inv s; ownB s i \<noteq> W \<and> i \<le> N\<rbrakk> \<Longrightarrow> ownB s' i \<noteq> W \<and> i \<le> N\<close> assms(2) le_trans less_imp_le_nat) apply(simp add:tempW_lemmas tempW_basic_lemmas) apply(intro conjI impI) apply(simp add:pre_dequeue_inv_def) apply(subgoal_tac "hW s = hW s' \<and> tW s = tW s' \<and> tempW s = tempW s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply presburger apply (metis fst_conv snd_conv tempW_def) apply(case_tac "length(q s)>1", simp_all) apply(subgoal_tac "last(q s) = last(tl(q s))") prefer 2 apply (metis R_changes_q_dequeue last_tl) apply(subgoal_tac "hW s = hW s' \<and> tW s = tW s' \<and> tempW s = tempW s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply presburger apply(subgoal_tac "q s\<noteq>[]") prefer 2 apply (metis length_0_conv less_nat_zero_code) apply (simp add: R_changes_q_dequeue W_items_dont_change_with_R) apply(subgoal_tac "hW s = hW s' \<and> tW s = tW s' \<and> tempW s = tempW s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply presburger apply(subgoal_tac "length(q s) = 1 \<longrightarrow> tl(q s) = []") prefer 2 apply (metis cancel_comm_monoid_add_class.diff_cancel length_greater_0_conv length_tl not_gr0) apply(case_tac "q s=[]") prefer 2 apply (metis One_nat_def R_changes_q_dequeue Suc_lessI length_greater_0_conv) apply(simp add:pre_dequeue_inv_def) apply(subgoal_tac "q s= []") prefer 2 apply blast apply(subgoal_tac "q s'=[]") prefer 2 using Q_empty_R_step_result [where s=s and s'=s'] apply presburger apply linarith apply(subgoal_tac "q s\<noteq>[]") prefer 2 using \<open>\<lbrakk>cR_step (pcR s) s s'; q s = []; pcR s = idleR\<rbrakk> \<Longrightarrow> q s' = []\<close> apply presburger apply(subgoal_tac "q s'= tl(q s)") prefer 2 using R_changes_q_dequeue apply presburger apply(subgoal_tac "hW s = hW s' \<and> tW s = tW s' \<and> tempW s = tempW s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply presburger apply (metis in_set_conv_nth list.set_sel(2) prod.inject tempW_def) using Q_W_relation_through_R_1 [where s=s and s'=s'] using \<open>\<lbrakk>cR_step (pcR s) s s'; q s = []; pcR s = idleR\<rbrakk> \<Longrightarrow> q s' = []\<close> apply presburger apply(subgoal_tac "hW s = hW s' \<and> tW s = tW s' \<and> tempW s = tempW s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply presburger apply(subgoal_tac "q s'= tl(q s)") prefer 2 using R_changes_q_dequeue using \<open>\<lbrakk>cR_step (pcR s) s s'; q s = []; pcR s = idleR\<rbrakk> \<Longrightarrow> q s' = []\<close> apply presburger apply(subgoal_tac "offset s = offset s' \<and> numEnqs s = numEnqs s'") prefer 2 using W_items_dont_change_with_R [where s=s and s'=s'] apply presburger apply (metis Nat.add_0_right \<open>\<lbrakk>cR_step (pcR s) s s'; q s = []; pcR s = idleR\<rbrakk> \<Longrightarrow> q s' = []\<close> \<open>cR_step (pcR s) s s' \<Longrightarrow> offset s = offset s' \<and> Data s (numEnqs s) = Data s' (numEnqs s') \<and> numEnqs s = numEnqs s'\<close> hd_in_set in_set_conv_nth less_not_refl list.set_sel(2) nat_add_left_cancel_less) apply(subgoal_tac "hW s = hW s' \<and> tW s = tW s' \<and> tempW s = tempW s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply presburger apply(subgoal_tac "offset s = offset s'") prefer 2 using \<open>cR_step (pcR s) s s' \<Longrightarrow> offset s = offset s' \<and> Data s (numEnqs s) = Data s' (numEnqs s') \<and> numEnqs s = numEnqs s'\<close> apply presburger apply(subgoal_tac "Data s' (numEnqs s') = Data s (numEnqs s)") prefer 2 apply (metis \<open>cR_step (pcR s) s s' \<Longrightarrow> offset s = offset s' \<and> Data s (numEnqs s) = Data s' (numEnqs s') \<and> numEnqs s = numEnqs s'\<close>) apply(subgoal_tac "\<forall>j. offset s \<le> j \<and> j < offset s + Data s (numEnqs s) \<longrightarrow> ownB s j = W") prefer 2 apply presburger apply(clarify) using ownB_by_W_doesnt_change_after_dequeue [where s=s and s'=s' and i=j] apply (metis PCR.distinct(1) PCR.distinct(5) \<open>\<And>i. \<lbrakk>RingBuffer_BD_latest_2.inv s; con_assms s; cR_step (pcR s) s s'; pcR s = Release \<longrightarrow> pre_Release_inv s; pcR s = Read \<longrightarrow> pre_Read_inv s; pcR s = idleR \<longrightarrow> pre_dequeue_inv s; ownB s i = W \<and> i \<le> N\<rbrakk> \<Longrightarrow> ownB s' i = W \<and> i \<le> N\<close> assms(2) le_trans less_or_eq_imp_le) apply(simp add:tempW_reflects_writes_def) apply(subgoal_tac "hW s = hW s' \<and> tW s = tW s' \<and> tempW s = tempW s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] using PCR.distinct(1) PCR.distinct(3) assms(2) apply presburger apply(simp add: pre_Read_inv_def) apply(subgoal_tac "data_index s (offset s, Data s (numEnqs s)) = numEnqs s") prefer 2 apply meson apply(subgoal_tac "data_index s = data_index s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] using PCR.distinct(1) PCR.distinct(3) assms(2) apply presburger using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply (metis W_items_dont_change_with_R) apply(simp add:tempW_reflects_writes_def) apply(subgoal_tac "hW s = hW s' \<and> tW s = tW s' \<and> tempW s = tempW s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] using PCR.distinct(1) PCR.distinct(5) assms(2) apply presburger apply(simp add: pre_Read_inv_def) apply(subgoal_tac "data_index s (offset s, Data s (numEnqs s)) = numEnqs s") prefer 2 apply meson apply(subgoal_tac "data_index s = data_index s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] using PCR.distinct(1) PCR.distinct(5) assms(2) apply presburger using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply (metis W_items_dont_change_with_R) apply(simp add:tempW_reflects_writes_def) apply(subgoal_tac "hW s = hW s' \<and> tW s = tW s' \<and> tempW s = tempW s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] using PCR.distinct(3) PCR.distinct(5) assms(2) apply presburger apply(simp add: pre_Read_inv_def) apply(subgoal_tac "data_index s (offset s, Data s (numEnqs s)) = numEnqs s") prefer 2 apply meson apply(subgoal_tac "data_index s = data_index s'") prefer 2 using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply (metis) using W_items_dont_change_with_R_2 [where s=s and s'=s'] apply (metis W_items_dont_change_with_R) apply(simp add:cR_step_def) apply(simp add:cR_step_def) apply(case_tac "q s=[]", simp_all) apply(simp add:cR_step_def) apply(simp add:pre_Read_inv_def) apply(simp add:cR_step_def) apply(case_tac " tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac " ownT s = R", simp_all) apply(case_tac " ownT s = R", simp_all) apply(simp add:cR_step_def) apply(case_tac "q s=[]", simp_all) apply(case_tac " ownT s = Q", simp_all) apply(simp add:cR_step_def) apply(simp add:cR_step_def) apply(simp add:cR_step_def) apply(case_tac "q s=[]", simp_all) apply(simp add:cR_step_def) apply(simp add:cR_step_def) apply(simp add:cR_step_def) apply(case_tac "q s=[]", simp_all) by(simp add:cR_step_def) lemma pre_A1_doesnt_change_with_R: assumes "inv s" and "con_assms s" and "pre_A1_inv s" and "pre_R (pcR s) s" and "cR_step (pcR s) s s'" shows "pre_A1_inv s'" using assms apply simp apply(simp add:pre_A1_inv_def) apply(intro conjI impI) apply(simp add:cR_step_def) apply(cases "pcR s", simp_all) apply(cases " tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "ownT s = R", simp_all) apply(simp add:pre_R_def pre_Release_inv_def inv_def) apply(case_tac "case_1 s") apply simp apply(simp add:case_1_def) apply metis apply(simp) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply (metis (no_types, hide_lams) diff_is_0_eq le0 nat_neq_iff zero_less_diff) apply(simp add:pre_R_def pre_Release_inv_def inv_def) apply(simp add:pre_R_def pre_Release_inv_def inv_def) apply(case_tac "case_1 s") apply simp apply(simp add:case_1_def) apply (metis Nat.add_diff_assoc diff_diff_left diff_is_0_eq' linorder_neqE_nat nat_le_linear zero_less_diff) apply(simp) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply (metis not_add_less1) apply(case_tac "q s = []", simp_all) apply(case_tac " ownT s = Q ", simp_all) apply(simp add:pre_R_def pre_Release_inv_def inv_def) apply(cases "pcR s", simp_all) apply(simp add:cR_step_def) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "ownT s = R", simp_all) apply(simp add:pre_R_def pre_Release_inv_def inv_def) apply(case_tac "ownT s = R", simp_all) apply(simp add:pre_R_def pre_Release_inv_def inv_def) apply(simp add:pre_R_def pre_dequeue_inv_def inv_def) apply(simp add:cR_step_def) apply(case_tac "q s = []", simp_all) apply(simp add:pre_R_def pre_Read_inv_def inv_def cR_step_def) apply(simp add:pre_R_def pre_Read_inv_def inv_def cR_step_def) apply(cases "pcR s", simp_all) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "ownT s = R", simp_all) apply(simp add:pre_R_def pre_Release_inv_def inv_def cR_step_def) apply(case_tac "case_1 s") apply simp apply(simp add:case_1_def) apply metis apply(simp) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply (metis diff_self_eq_0 le_antisym le_neq_implies_less length_greater_0_conv less_imp_Suc_add nat.distinct(1) plus_nat.add_0) apply(simp add:pre_R_def pre_Release_inv_def inv_def cR_step_def) apply(case_tac "ownT s = R", simp_all) apply(simp add:pre_R_def pre_Release_inv_def inv_def cR_step_def) apply(case_tac "case_1 s") apply simp apply(simp add:case_1_def) apply (metis bot_nat_0.extremum_uniqueI diff_self_eq_0 le_add_diff_inverse le_antisym length_0_conv) apply(simp) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply (metis not_add_less1) apply(simp add:pre_R_def pre_Release_inv_def inv_def cR_step_def) apply(case_tac "q s = []", simp_all) apply(case_tac " ownT s = Q ", simp_all) apply(simp add:pre_R_def pre_Release_inv_def inv_def cR_step_def) apply(cases "pcR s", simp_all) apply(case_tac "q s = []", simp_all) apply(simp add:pre_R_def pre_Release_inv_def inv_def cR_step_def) apply(cases "pcR s", simp_all) apply(case_tac "q s = []", simp_all) apply(simp add:pre_R_def pre_Release_inv_def inv_def cR_step_def) apply(cases "pcR s", simp_all) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "ownT s = R", simp_all) apply(simp add:pre_R_def pre_Release_inv_def inv_def cR_step_def) apply(case_tac "case_1 s") apply simp apply(simp add:case_1_def) apply metis apply(simp) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply (metis add_cancel_right_left le_refl) apply(simp add:pre_R_def pre_Release_inv_def inv_def cR_step_def) apply(case_tac "ownT s = R", simp_all) apply(simp add:pre_R_def pre_Release_inv_def inv_def cR_step_def) apply(case_tac "case_1 s") apply simp apply(simp add:case_1_def) apply (metis le_add_diff_inverse le_eq_less_or_eq) apply(simp) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply (metis (no_types, hide_lams) le_add_diff_inverse le_trans less_or_eq_imp_le linorder_neqE_nat nat_less_le) apply(simp add:pre_R_def pre_Release_inv_def inv_def cR_step_def) apply(case_tac "q s = []", simp_all) apply(case_tac " ownT s = Q ", simp_all) apply(simp add:pre_R_def pre_dequeue_inv_def inv_def) apply(case_tac "case_1 s") apply simp apply(simp add:case_1_def) apply (metis le_antisym nat_less_le) apply(simp) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply (metis (no_types, lifting) F.distinct(19)) apply(case_tac "case_1 s") apply simp apply(simp add:case_1_def) apply (metis F.distinct(13) F.distinct(17) le_eq_less_or_eq) apply(simp) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply(simp add:pre_R_def pre_dequeue_inv_def inv_def) apply(simp add:pre_R_def pre_Release_inv_def inv_def cR_step_def) apply(cases "pcR s", simp_all) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "ownT s = R", simp_all) apply(simp add:pre_R_def pre_Release_inv_def inv_def cR_step_def) apply(case_tac "case_1 s") apply simp apply(simp add:case_1_def) apply (metis le_add_diff_inverse le_eq_less_or_eq) apply(simp) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply (metis (no_types, hide_lams) le_add_diff_inverse le_trans less_or_eq_imp_le linorder_neqE_nat nat_less_le) apply(simp add:pre_R_def pre_Release_inv_def inv_def cR_step_def) apply(case_tac "ownT s = R", simp_all) apply(simp add:pre_R_def pre_Release_inv_def inv_def cR_step_def) apply (metis le_eq_less_or_eq nat_le_linear) apply(simp add:pre_R_def pre_Release_inv_def inv_def cR_step_def) apply(case_tac "q s = []", simp_all) apply(case_tac " ownT s = Q ", simp_all) apply(simp add:pre_R_def pre_dequeue_inv_def inv_def) apply (metis (no_types, hide_lams) F.distinct(19)) apply(simp add:pre_R_def pre_dequeue_inv_def inv_def) apply(simp add:pre_R_def pre_Release_inv_def inv_def cR_step_def) apply(cases "pcR s", simp_all) apply(case_tac "q s = []", simp_all) apply(simp add:pre_R_def pre_Release_inv_def inv_def cR_step_def) apply(cases "pcR s", simp_all) apply(case_tac "q s = []", simp_all) apply(simp add:pre_R_def pre_Release_inv_def inv_def cR_step_def) apply(cases "pcR s", simp_all) apply(case_tac "q s = []", simp_all) apply(simp add:pre_R_def pre_Release_inv_def inv_def cR_step_def) apply(cases "pcR s", simp_all) apply(case_tac "q s = []", simp_all) apply(simp add:pre_R_def pre_Release_inv_def inv_def cR_step_def) apply(cases "pcR s", simp_all) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "ownT s = R", simp_all) apply(simp add:pre_R_def pre_Release_inv_def inv_def cR_step_def) apply(case_tac "ownT s = R", simp_all) apply(simp add:pre_R_def pre_Release_inv_def inv_def cR_step_def) by(case_tac "q s = []", simp_all) lemma pre_A2_doesnt_change_with_R: assumes "inv s" and "con_assms s" and "pre_A2_inv s" and "pre_R (pcR s) s" and "cR_step (pcR s) s s'" shows "pre_A2_inv s'" using assms apply simp apply(simp add:pre_A2_inv_def) apply(intro conjI impI) apply(simp_all add:pre_R_def pre_Release_inv_def inv_def cR_step_def) apply(case_tac[!] "pcR s", simp_all) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "ownT s = R", simp_all) apply(case_tac "ownT s = R", simp_all) apply(case_tac "q s = []", simp_all) apply(case_tac "ownT s = Q", simp_all) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "ownT s = R", simp_all) apply(case_tac "ownT s = R", simp_all) apply(case_tac "q s = []", simp_all) apply(case_tac "ownT s = Q", simp_all) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "ownT s = R", simp_all) apply(case_tac "ownT s = R", simp_all) apply(case_tac "q s = []", simp_all) apply(case_tac "ownT s = Q", simp_all) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "ownT s = R", simp_all) apply(simp_all add:pre_R_def pre_Release_inv_def inv_def cR_step_def) apply(case_tac "q s = []", simp_all) apply(case_tac "ownT s = Q", simp_all) apply(case_tac "q s = []", simp_all) apply(case_tac "ownT s = Q", simp_all) apply(simp_all add:pre_R_def pre_dequeue_inv_def inv_def cR_step_def) apply (metis (no_types, hide_lams) F.distinct(19)) apply(case_tac "T s \<noteq> fst (tempR s)", simp_all) apply(simp add:tempR_lemmas tempR_basic_lemmas Q_lemmas Q_basic_lemmas) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply metis apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply (metis add_cancel_right_left le_trans) apply(simp add:tempR_lemmas tempR_basic_lemmas Q_lemmas Q_basic_lemmas) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply (metis (no_types, lifting) F.distinct(13) eq_imp_le less_imp_le_nat linorder_neqE_nat trans_le_add1) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply (metis Suc_leI not_less_eq_eq trans_le_add1) apply(case_tac "q s = []", simp_all) apply metis apply metis apply metis apply(case_tac "T s \<noteq> fst (tempR s)", simp_all) apply(case_tac "q s = []", simp_all) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply (metis (no_types, lifting) F.distinct(19)) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply (metis Suc_leI not_less_eq_eq trans_le_add1) apply(case_tac "T s \<noteq> fst (tempR s)", simp_all) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply (metis (no_types, lifting) F.distinct(19)) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply (metis Suc_leI not_less_eq_eq trans_le_add1) apply(case_tac "q s = []", simp_all) apply(case_tac "T s \<noteq> fst (tempR s)", simp_all) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply (metis (no_types, lifting) F.distinct(19)) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply (metis Suc_leI not_less_eq_eq trans_le_add1) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply (metis le_add_diff_inverse le_eq_less_or_eq) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply (metis Suc_leI not_less_eq_eq) apply(case_tac "q s = []", simp_all) apply(case_tac "q s = []", simp_all) apply(case_tac "q s = []", simp_all) apply(case_tac "q s = []", simp_all) apply(case_tac "q s = []", simp_all) apply(case_tac "q s = []", simp_all) apply(case_tac "T s \<noteq> fst (tempR s)", simp_all) apply(case_tac "q s = []", simp_all) apply(case_tac "q s = []", simp_all) apply(case_tac "q s = []", simp_all) apply(case_tac "q s = []", simp_all) apply blast by(simp_all add:pre_R_def pre_Read_inv_def inv_def cR_step_def) lemma pre_A3_doesnt_change_with_R: assumes "inv s" and "con_assms s" and "pre_A3_inv s" and "pre_R (pcR s) s" and "cR_step (pcR s) s s'" shows "pre_A3_inv s'" using assms apply simp apply(simp add:pre_A3_inv_def) apply(intro conjI impI) apply(simp_all add:pre_R_def pre_Release_inv_def inv_def cR_step_def) apply(case_tac[!] "pcR s", simp_all) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) by(simp_all add:pre_R_def pre_Release_inv_def inv_def cR_step_def) lemma pre_A4_doesnt_change_with_R: assumes "inv s" and "con_assms s" and "pre_A4_inv s" and "pre_R (pcR s) s" and "cR_step (pcR s) s s'" shows "pre_A4_inv s'" using assms apply simp apply(simp add:pre_A4_inv_def) apply(intro conjI impI) apply(simp_all add:pre_R_def pre_Release_inv_def inv_def cR_step_def) apply(case_tac[!] "pcR s", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "ownT s = Q", simp_all) apply(simp_all add:pre_R_def pre_dequeue_inv_def inv_def cR_step_def) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply (metis (no_types, lifting) F.distinct(19)) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply (metis (no_types, hide_lams) F.distinct(19)) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "ownT s =R", simp_all) apply(case_tac "ownT s = R", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "ownT s =R", simp_all) apply(case_tac "ownT s =R", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "ownT s =R", simp_all) apply(simp_all add:pre_R_def pre_Release_inv_def inv_def cR_step_def) apply(simp add:tempR_lemmas tempR_basic_lemmas Q_lemmas Q_basic_lemmas) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply (metis (no_types, lifting) F.distinct(19)) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply (metis add_cancel_right_left le_trans) apply(simp add:tempR_lemmas tempR_basic_lemmas Q_lemmas Q_basic_lemmas) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply (metis F.distinct(13) eq_imp_le less_imp_le_nat linorder_neqE_nat trans_le_add1) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply (metis Suc_leI not_less_eq_eq trans_le_add1) apply(case_tac "q s=[]", simp_all) apply metis+ apply(case_tac "q s=[]", simp_all) by metis+ lemma pre_A5_doesnt_change_with_R: assumes "inv s" and "con_assms s" and "pre_A5_inv s" and "pre_R (pcR s) s" and "cR_step (pcR s) s s'" shows "pre_A5_inv s'" using assms apply simp apply(simp add:pre_A5_inv_def) apply(intro conjI impI) apply(simp_all add:pre_R_def pre_Release_inv_def inv_def cR_step_def) apply(case_tac[!] "pcR s", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "ownT s = Q", simp_all) apply(simp_all add:pre_R_def pre_dequeue_inv_def inv_def cR_step_def) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply (metis (no_types, lifting) F.distinct(19)) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply (metis (no_types, hide_lams) F.distinct(19)) apply(case_tac "q s=[]", simp_all) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "ownT s =R", simp_all) apply(case_tac "ownT s = R", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "ownT s =R", simp_all) apply(case_tac "ownT s =R", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "ownT s =R", simp_all) apply(simp_all add:pre_R_def pre_Release_inv_def inv_def cR_step_def) apply(simp add:tempR_lemmas tempR_basic_lemmas Q_lemmas Q_basic_lemmas) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply (metis (no_types, lifting) F.distinct(19)) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply (metis add_cancel_right_left le_trans) apply(case_tac "q s=[]", simp_all) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(simp add:tempR_lemmas tempR_basic_lemmas Q_lemmas Q_basic_lemmas) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply (metis F.distinct(13) eq_imp_le less_imp_le_nat linorder_neqE_nat trans_le_add1) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply (metis Suc_leI not_less_eq_eq trans_le_add1) apply(simp add:tempR_lemmas tempR_basic_lemmas Q_lemmas Q_basic_lemmas) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply (metis le_add_diff_inverse le_trans) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply (metis Suc_leI not_less_eq_eq) apply(case_tac "q s=[]", simp_all) by(case_tac "q s=[]", simp_all) lemma pre_A6_doesnt_change_with_R: assumes "inv s" and "con_assms s" and "pre_A6_inv s" and "pre_R (pcR s) s" and "cR_step (pcR s) s s'" shows "pre_A6_inv s'" using assms apply simp apply(simp add:pre_A6_inv_def) apply(intro conjI impI) apply(simp_all add:pre_R_def pre_Release_inv_def inv_def cR_step_def) apply(case_tac[!] "pcR s", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "ownT s = Q", simp_all) apply(simp_all add:pre_R_def pre_dequeue_inv_def inv_def cR_step_def) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply (metis (no_types, lifting) F.distinct(19)) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply (metis (no_types, hide_lams) F.distinct(19)) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "ownT s =R", simp_all) apply(case_tac "ownT s = R", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "ownT s =R", simp_all) apply(case_tac "ownT s =R", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "ownT s =R", simp_all) apply(simp_all add:pre_R_def pre_Release_inv_def inv_def cR_step_def) apply(simp add:tempR_lemmas tempR_basic_lemmas Q_lemmas Q_basic_lemmas) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply (metis (no_types, lifting) F.distinct(19)) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply (metis add_cancel_right_left le_trans) apply(case_tac "q s=[]", simp_all) apply(case_tac "T s \<noteq> fst (tempR s)", simp_all) apply(simp add:tempR_lemmas tempR_basic_lemmas Q_lemmas Q_basic_lemmas) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply (metis F.distinct(13) eq_imp_le less_imp_le_nat linorder_neqE_nat trans_le_add1) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply (metis Suc_leI not_less_eq_eq trans_le_add1) apply(simp add:tempR_lemmas tempR_basic_lemmas Q_lemmas Q_basic_lemmas) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply (metis le_add_diff_inverse le_trans) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply (metis Suc_leI not_less_eq_eq) apply(case_tac "q s=[]", simp_all) by(case_tac "q s=[]", simp_all) lemma pre_A7_doesnt_change_with_R: assumes "inv s" and "con_assms s" and "pre_A7_inv s" and "pre_R (pcR s) s" and "cR_step (pcR s) s s'" shows "pre_A7_inv s'" using assms apply simp apply(simp add:pre_A7_inv_def) apply(intro conjI impI) apply(simp_all add:pre_R_def pre_Release_inv_def inv_def cR_step_def) apply(case_tac[!] "pcR s", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "ownT s = Q", simp_all) apply(simp_all add:pre_R_def pre_dequeue_inv_def inv_def cR_step_def) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply (metis (no_types, lifting) F.distinct(19)) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply (metis (no_types, hide_lams) F.distinct(19)) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "ownT s =R", simp_all) apply(case_tac "ownT s = R", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "ownT s =R", simp_all) apply(case_tac "ownT s =R", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "ownT s =R", simp_all) apply(simp_all add:pre_R_def pre_Release_inv_def inv_def cR_step_def) apply(simp add:tempR_lemmas tempR_basic_lemmas Q_lemmas Q_basic_lemmas) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply (metis (no_types, lifting) F.distinct(19)) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply (metis add_cancel_right_left le_trans) apply(case_tac "q s=[]", simp_all) apply(case_tac "T s \<noteq> fst (tempR s)", simp_all) apply(simp add:tempR_lemmas tempR_basic_lemmas Q_lemmas Q_basic_lemmas) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply (metis F.distinct(13) eq_imp_le less_imp_le_nat linorder_neqE_nat trans_le_add1) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply (metis Suc_leI not_less_eq_eq trans_le_add1) apply(simp add:tempR_lemmas tempR_basic_lemmas Q_lemmas Q_basic_lemmas) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply (metis le_add_diff_inverse le_trans) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply (metis Suc_leI not_less_eq_eq) apply(case_tac "q s=[]", simp_all) by(case_tac "q s=[]", simp_all) lemma pre_A8_doesnt_change_with_R: assumes "inv s" and "con_assms s" and "pre_A8_inv s" and "pre_R (pcR s) s" and "cR_step (pcR s) s s'" shows "pre_A8_inv s'" using assms apply simp apply(simp add:pre_A8_inv_def) apply(intro conjI impI) apply(simp_all add:pre_R_def pre_Release_inv_def inv_def cR_step_def) apply(case_tac[!] "pcR s", simp_all) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "ownT s =R", simp_all) apply(case_tac "ownT s =R", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "ownT s = Q", simp_all) apply(simp_all add:pre_R_def pre_dequeue_inv_def inv_def cR_step_def) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply (metis (no_types, lifting) F.distinct(19)) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply (metis (no_types, hide_lams) F.distinct(19)) apply(case_tac "q s=[]", simp_all) apply (metis (no_types, lifting) F.distinct(19)) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "ownT s =R", simp_all) apply metis apply metis apply(case_tac "ownT s = R", simp_all) apply metis apply metis apply(case_tac "q s=[]", simp_all) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "ownT s =R", simp_all) apply(case_tac "ownT s =R", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "ownT s =R", simp_all) apply(case_tac "ownT s =R", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "ownT s =R", simp_all) apply(case_tac "ownT s =R", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "ownT s =R", simp_all) apply(case_tac "ownT s =R", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "ownT s =R", simp_all) apply(case_tac "ownT s =R", simp_all) apply(simp_all add:pre_R_def pre_Release_inv_def inv_def cR_step_def) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply (metis (no_types, lifting) F.distinct(19)) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply (metis add_cancel_right_left le_trans) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply (metis le_add_diff_inverse le_eq_less_or_eq) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply (metis Suc_leI not_less_eq_eq trans_le_add1) apply(case_tac "q s=[]", simp_all) apply metis+ apply(case_tac "q s=[]", simp_all) by metis+ lemma pre_acquire_doesnt_change_with_R: assumes "inv s" and "con_assms s" and "pre_acquire_inv s" and "pre_R (pcR s) s" and "cR_step (pcR s) s s'" shows "pre_acquire_inv s'" using assms apply simp apply(simp add:pre_acquire_inv_def) apply(intro conjI impI) apply(simp_all add:pre_R_def pre_Release_inv_def inv_def cR_step_def) apply(case_tac[!] "pcR s", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "ownT s =R", simp_all) apply(case_tac "ownT s = R", simp_all) apply(simp_all add:pre_R_def pre_Release_inv_def inv_def cR_step_def) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply metis apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply (metis eq_imp_le less_imp_le_nat linorder_neqE_nat plus_nat.add_0) apply(case_tac "ownT s =R", simp_all) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply (metis diff_is_0_eq' linorder_neqE_nat nat_le_linear zero_less_diff) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply (metis eq_imp_le less_imp_le_nat linorder_neqE_nat plus_nat.add_0) apply(case_tac "q s=[]", simp_all) apply(case_tac "ownT s = Q", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "ownT s = Q", simp_all) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "ownT s =R", simp_all) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply (metis diff_is_0_eq' linorder_neqE_nat nat_le_linear zero_less_diff) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply (metis add_cancel_right_left diff_add_inverse2 le_0_eq le_antisym length_0_conv nat_less_le) apply(case_tac "ownT s = R", simp_all) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply (metis bot_nat_0.extremum_uniqueI diff_self_eq_0 le_add_diff_inverse le_antisym length_0_conv) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply (metis not_add_less1) apply(case_tac "q s=[]", simp_all) apply(case_tac "ownT s = Q", simp_all) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "ownT s =R", simp_all) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply (metis bot_nat_0.extremum_uniqueI diff_self_eq_0 le_add_diff_inverse le_antisym length_0_conv) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply (metis le_antisym le_neq_implies_less less_imp_Suc_add nat.distinct(1) ordered_cancel_comm_monoid_diff_class.le_imp_diff_is_add plus_nat.add_0) apply(case_tac "ownT s =R", simp_all) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply (metis Nat.add_0_right diff_self_eq_0 le_add_diff_inverse le_antisym le_zero_eq) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply (metis not_add_less1) apply(case_tac "q s=[]", simp_all) apply(case_tac "ownT s = Q", simp_all) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply (metis bot_nat_0.extremum_uniqueI diff_self_eq_0 le_add_diff_inverse le_antisym length_0_conv) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply (metis less_or_eq_imp_le plus_nat.add_0) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply (metis le_add_diff_inverse le_eq_less_or_eq) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply (metis le_add_diff_inverse le_trans less_nat_zero_code less_or_eq_imp_le nat_less_le nat_neq_iff) apply(case_tac "q s=[]", simp_all) apply(case_tac "ownT s = Q", simp_all) apply(simp add:pre_dequeue_inv_def) apply (metis (mono_tags, hide_lams) F.distinct(19)) apply(simp add:pre_dequeue_inv_def) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply (metis le_add_diff_inverse le_eq_less_or_eq) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply (metis plus_nat.add_0) apply (metis le_add_diff_inverse le_trans less_nat_zero_code less_or_eq_imp_le nat_less_le nat_neq_iff) apply(case_tac "q s=[]", simp_all) apply(case_tac "ownT s = Q", simp_all) apply(simp add:pre_dequeue_inv_def) apply (metis (mono_tags, hide_lams) F.distinct(19)) apply(simp add:pre_dequeue_inv_def) apply(case_tac "q s=[]", simp_all) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "ownT s = Q", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) by(case_tac "q s=[]", simp_all) lemma pre_OOM_doesnt_change_with_R: assumes "inv s" and "con_assms s" and "pre_OOM_inv s" and "pre_R (pcR s) s" and "cR_step (pcR s) s s'" shows "pre_OOM_inv s'" using assms apply simp apply(simp add:pre_OOM_inv_def) apply(intro conjI impI) apply(simp_all add:pre_R_def pre_Release_inv_def inv_def cR_step_def) apply(case_tac[!] "pcR s", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "ownT s =R", simp_all) apply(case_tac "ownT s = R", simp_all) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "ownT s = R", simp_all) apply(case_tac "ownT s = R", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "ownT s = Q", simp_all) apply(simp_all add:pre_R_def pre_dequeue_inv_def inv_def cR_step_def) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "ownT s =R", simp_all) apply(case_tac "ownT s =R", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "ownT s =R", simp_all) apply(case_tac "case_1 s", simp_all) apply(simp add:case_1_def) apply(case_tac "ownT s =R", simp_all) apply(simp add:case_2_def) apply(thin_tac "\<not>case_1 s") apply(case_tac "ownT s =R", simp_all) apply(simp_all add:pre_R_def pre_Release_inv_def inv_def cR_step_def) apply(case_tac "q s=[]", simp_all) apply (metis (no_types, lifting) F.distinct(19)) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "T s \<noteq> fst (tempR s)", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply blast by(simp_all add:pre_R_def pre_Read_inv_def inv_def cR_step_def) lemma pre_finished_doesnt_change_with_R: assumes "inv s" and "con_assms s" and "pre_finished_inv s" and "pre_R (pcR s) s" and "cR_step (pcR s) s s'" shows "pre_finished_inv s'" using assms apply simp apply(simp add:pre_finished_inv_def) apply(intro conjI impI) apply(simp_all add:pre_R_def pre_Release_inv_def inv_def cR_step_def) apply(case_tac[!] "pcR s", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) by(case_tac "q s=[]", simp_all) lemma pre_BTS_doesnt_change_with_R: assumes "inv s" and "con_assms s" and "pre_BTS_inv s" and "pre_R (pcR s) s" and "cR_step (pcR s) s s'" shows "pre_BTS_inv s'" using assms apply simp apply(simp add:pre_BTS_inv_def) apply(intro conjI impI) apply(simp_all add:pre_R_def pre_Release_inv_def inv_def cR_step_def) apply(case_tac[!] "pcR s", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "ownT s =R", simp_all) apply(case_tac "ownT s = R", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "ownT s = Q", simp_all) apply(simp_all add:pre_R_def pre_dequeue_inv_def inv_def cR_step_def) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply(case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply(case_tac "ownT s = R", simp_all) apply(simp_all add:pre_R_def pre_Release_inv_def inv_def cR_step_def) apply(case_tac "q s=[]", simp_all) apply blast by(simp_all add:pre_R_def pre_Read_inv_def inv_def cR_step_def) (*******************************GLOBAL R_step preserves preW*************************************) lemma GLOBAL_R_step_shows_preW: assumes "inv s" and "con_assms s" and "pre_R (pcR s) s" and "pre_W (pcW s) s" and "cR_step (pcR s) s s'" shows "pre_W (pcW s') s'" using assms apply simp apply(subgoal_tac "pcW s' = pcW s") prefer 2 using pcW_doesnt_change_with_R [where s=s and s'=s'] apply simp apply(simp add:pre_W_def) apply(case_tac "pcW s") apply simp_all using pre_A1_doesnt_change_with_R [where s=s and s'=s'] apply simp using pre_A2_doesnt_change_with_R [where s=s and s'=s'] apply simp using pre_A3_doesnt_change_with_R [where s=s and s'=s'] apply simp using pre_A4_doesnt_change_with_R [where s=s and s'=s'] apply simp using pre_A5_doesnt_change_with_R [where s=s and s'=s'] apply simp using pre_A6_doesnt_change_with_R [where s=s and s'=s'] apply simp using pre_A7_doesnt_change_with_R [where s=s and s'=s'] apply simp using pre_A8_doesnt_change_with_R [where s=s and s'=s'] apply simp using pre_enqueue_doesnt_change_with_R [where s=s and s'=s'] apply simp using pre_acquire_doesnt_change_with_R [where s=s and s'=s'] apply simp using pre_OOM_doesnt_change_with_R [where s=s and s'=s'] apply simp using pre_finished_doesnt_change_with_R [where s=s and s'=s'] apply simp using pre_write_doesnt_change_with_R [where s=s and s'=s'] apply simp using pre_BTS_doesnt_change_with_R [where s=s and s'=s'] by simp (*writer side enqueue------------------------*) lemma enqueue_preserves_Q_n_n: assumes "q s\<noteq>[]" and "Q_structure s" and "Q_enqueue s s'" and "numDeqs s<numEnqs s" and "length(q s) = numEnqs s-numDeqs s" and "pre_enqueue_inv s" and "ownD s(numEnqs s) =B" and "ownT s \<noteq>W" and "numWrites s\<ge>numReads s" shows "Q_structure s'" using assms apply (simp) apply (case_tac "ownT s = W", simp_all) apply(simp add:Q_structure_def) apply(intro conjI impI) apply(simp add:Q_basic_lemmas) apply(intro conjI impI) apply(simp add:pre_enqueue_inv_def) apply(simp add:tempW_lemmas tempW_basic_lemmas) apply(simp add:pre_enqueue_inv_def) apply(simp add:tempW_lemmas tempW_basic_lemmas) apply(subgoal_tac "\<forall>i. i < length (q s) \<and> 0 < i \<longrightarrow> fst ((q s @ [(offset s, Data s (numEnqs s))]) ! (i - Suc 0)) + snd ((q s @ [(offset s, Data s (numEnqs s))]) ! (i - Suc 0)) = fst ((q s @ [(offset s, Data s (numEnqs s))]) ! i) \<or> fst ((q s @ [(offset s, Data s (numEnqs s))]) ! i) = 0") prefer 2 apply clarify apply (smt (z3) Suc_lessD Suc_pred nat_neq_iff nth_append) apply(subgoal_tac "fst(tempW s) =end(last(q s)) \<or> fst(tempW s) =0") prefer 2 apply (metis end_simp fst_conv tempW_def) apply(subgoal_tac "last(q s) =(q s!(length(q s)-1))") prefer 2 apply (metis last_conv_nth) apply clarify apply(subgoal_tac "offset s =0\<longrightarrow>(\<forall>i.(i<length(q s))\<longrightarrow>fst(q s!i)\<noteq>0)") prefer 2 apply metis apply(subgoal_tac "(\<exists>i.(i<length(q s)\<and>fst(q s!i) =0))\<longrightarrow>offset s\<noteq>0") prefer 2 apply blast apply(case_tac "offset s=0") apply (metis (no_types, lifting) One_nat_def diff_Suc_less end_simp less_antisym nat_neq_iff nth_append nth_append_length tempW_def) apply (metis (no_types, lifting) One_nat_def diff_Suc_less end_simp less_antisym nat_neq_iff nth_append nth_append_length tempW_def) apply(simp add:pre_enqueue_inv_def) apply(simp add:tempW_lemmas tempW_basic_lemmas) apply (smt (z3) less_antisym nth_append nth_append_length prod.collapse prod.inject) apply(simp add:pre_enqueue_inv_def) apply(simp add:tempW_lemmas tempW_basic_lemmas) apply clarify apply(case_tac "a = offset s \<and> b = Data s (numEnqs s)", simp_all) apply(simp add:Q_lemmas Q_basic_lemmas) apply (metis (no_types, lifting) fst_eqD in_set_conv_nth less_imp_le_nat) apply(simp add:Q_lemmas Q_basic_lemmas) apply(case_tac "aa = offset s \<and> ba = Data s (numEnqs s)", simp_all) apply (metis (no_types, lifting) fst_conv in_set_conv_nth snd_conv) apply (metis (no_types, hide_lams)) apply(simp add:pre_enqueue_inv_def) apply(simp add:tempW_lemmas tempW_basic_lemmas) apply(simp add:Q_lemmas Q_basic_lemmas) apply (metis (no_types, lifting) fst_eqD in_set_conv_nth nat_neq_iff not_add_less1) apply(simp add:pre_enqueue_inv_def) apply(simp add:tempW_lemmas tempW_basic_lemmas) apply(simp add:Q_lemmas Q_basic_lemmas) apply(simp add:pre_enqueue_inv_def) apply(simp add:tempW_lemmas tempW_basic_lemmas) apply(simp add:Q_lemmas Q_basic_lemmas) apply(subgoal_tac "\<forall>i<length (q s). data_index s ((q s) ! i) = numDeqs s + i") prefer 2 apply presburger apply(subgoal_tac " data_index s ((offset s, Data s (numEnqs s))) = numDeqs s + length (q s)") apply (simp add: nth_append) apply (metis le_add_diff_inverse less_SucE less_imp_le_nat) apply (metis le_add_diff_inverse less_imp_le_nat) apply(simp add:pre_enqueue_inv_def) apply(simp add:tempW_lemmas tempW_basic_lemmas) apply(simp add:Q_lemmas Q_basic_lemmas) apply (metis (no_types, lifting) le_add_diff_inverse less_SucE less_imp_le_nat nth_append nth_append_length snd_eqD) apply(simp add:pre_enqueue_inv_def) apply(simp add:tempW_lemmas tempW_basic_lemmas) apply(simp add:Q_lemmas Q_basic_lemmas) by (metis le_add_diff_inverse2 less_SucE less_imp_le_nat) lemma enqueue_preserves_Q_n_o: assumes "q s\<noteq>[] \<and> Q_structure s \<and> Q_enqueue s s' \<and> numDeqs s<numEnqs s \<and> numWrites s\<ge>numReads s \<and> length(q s) = numEnqs s-numDeqs s \<and> pre_enqueue_inv s \<and> ownD s(numEnqs s) =B \<and> ownT s =W" shows "Q_structure s'" using assms apply (simp) apply (case_tac "ownT s = W", simp_all) apply(simp add:Q_structure_def) apply(intro conjI impI) apply(simp add:Q_basic_lemmas) apply(intro conjI impI) apply(simp add:pre_enqueue_inv_def) apply blast apply(simp add:pre_enqueue_inv_def) apply blast apply(simp add:pre_enqueue_inv_def) apply blast apply(simp add:pre_enqueue_inv_def) apply(simp add:pre_enqueue_inv_def) apply(simp add:pre_enqueue_inv_def) apply meson apply(simp add:pre_enqueue_inv_def) apply blast apply(simp add:pre_enqueue_inv_def) apply blast apply(simp add:pre_enqueue_inv_def) by blast lemma enqueue_preserves_Q_e_o: assumes "q s=[] \<and> Q_structure s \<and> Q_enqueue s s' \<and> numDeqs s=numEnqs s \<and> length(q s) = numEnqs s-numDeqs s \<and> pre_enqueue_inv s \<and> numWrites s\<ge>numReads s \<and> ownD s(numEnqs s) =B \<and> ownT s =W" shows "Q_structure s'" using assms apply simp apply(case_tac "ownT s = W", simp_all) apply(simp add:Q_structure_def) apply(intro conjI impI) apply(simp add:Q_basic_lemmas) apply(intro conjI impI) apply(simp add:pre_enqueue_inv_def tempW_lemmas tempW_basic_lemmas) apply(simp add:pre_enqueue_inv_def tempW_lemmas tempW_basic_lemmas) apply (metis gr0I) apply(simp add:pre_enqueue_inv_def tempW_lemmas tempW_basic_lemmas) apply(simp add:Q_holds_bytes_def) apply(simp add:pre_enqueue_inv_def tempW_lemmas tempW_basic_lemmas) apply(simp add:Q_reflects_writes_def) apply(simp add:pre_enqueue_inv_def tempW_lemmas tempW_basic_lemmas) apply(simp add:Q_elem_size_def) apply(simp add:pre_enqueue_inv_def tempW_lemmas tempW_basic_lemmas) by(simp add:Q_reflects_ownD_def) lemma enqueue_preserves_Q_e_n: assumes "q s=[] \<and> Q_structure s \<and> Q_enqueue s s' \<and> numDeqs s=numEnqs s \<and> length(q s) = numEnqs s-numDeqs s \<and> pre_enqueue_inv s \<and> numWrites s\<ge>numReads s \<and> ownD s(numEnqs s) =B \<and> ownT s \<noteq>W" shows "Q_structure s'" using assms apply simp apply(case_tac "ownT s = W", simp_all) apply(simp add:Q_structure_def) apply(intro conjI impI) apply(simp add:Q_basic_lemmas) apply(intro conjI impI) apply(simp add:pre_enqueue_inv_def tempW_lemmas tempW_basic_lemmas) apply(simp add:pre_enqueue_inv_def tempW_lemmas tempW_basic_lemmas) apply (metis gr0I) apply(simp add:pre_enqueue_inv_def tempW_lemmas tempW_basic_lemmas) apply(simp add:Q_holds_bytes_def) apply(simp add:pre_enqueue_inv_def tempW_lemmas tempW_basic_lemmas) apply(simp add:Q_reflects_writes_def) apply(simp add:pre_enqueue_inv_def tempW_lemmas tempW_basic_lemmas) apply(simp add:Q_elem_size_def) apply(simp add:pre_enqueue_inv_def tempW_lemmas tempW_basic_lemmas) by(simp add:Q_reflects_ownD_def) lemma enqueue_preserves_Q: assumes "Q_structure s \<and> Q_enqueue s s' \<and> length(q s) = numEnqs s-numDeqs s \<and> pre_enqueue_inv s \<and> numWrites s\<ge>numReads s \<and> numEnqs s\<ge>numDeqs s \<and> ownD s(numEnqs s) =B" shows "Q_structure s'" using assms apply simp apply(case_tac "q s=[]") apply(case_tac[!] "ownT s = W", simp_all) defer defer defer (*4*) apply(subgoal_tac "q s\<noteq>[] \<and> Q_structure s \<and> Q_enqueue s s' \<and> numDeqs s<numEnqs s \<and> length(q s) = numEnqs s-numDeqs s \<and> pre_enqueue_inv s \<and> numWrites s\<ge>numReads s \<and> ownD s(numEnqs s) =B \<and> ownT s \<noteq>W") using enqueue_preserves_Q_n_n apply presburger apply (metis assms length_greater_0_conv zero_less_diff) defer defer (*3*) apply(subgoal_tac "q s\<noteq>[] \<and> Q_structure s \<and> Q_enqueue s s' \<and> numDeqs s<numEnqs s \<and> length(q s) = numEnqs s-numDeqs s \<and> pre_enqueue_inv s \<and> numWrites s\<ge>numReads s \<and> ownD s(numEnqs s) =B \<and> ownT s =W") prefer 2 apply (metis assms length_greater_0_conv zero_less_diff) using enqueue_preserves_Q_n_o proof - assume a1: "Q_structure s \<and> s' = s \<lparr>ownT := Q, numEnqs := Suc (numEnqs s), ownB := \<lambda>i. if ownB s i = W then Q else ownB ((if ownT s = W then ownT_update (\<lambda>_. Q) else (\<lambda>s. s\<lparr>ownT := ownT s\<rparr>)) s \<lparr>numEnqs := Suc (numEnqs s)\<rparr>) i, pcW := idleW, q := q s @ [(offset s, Data s (numEnqs s))]\<rparr> \<and> length (q s) = numEnqs s - numDeqs s \<and> pre_enqueue_inv s \<and> numReads s \<le> numWrites s \<and> numDeqs s \<le> numEnqs s \<and> ownD s (numEnqs s) = B" assume "q s \<noteq> []" assume a2: "ownT s = W" assume a3: "q s \<noteq> [] \<and> Q_structure s \<and> Q_enqueue s s' \<and> numDeqs s < numEnqs s \<and> length (q s) = numEnqs s - numDeqs s \<and> pre_enqueue_inv s \<and> numReads s \<le> numWrites s \<and> ownD s (numEnqs s) = B \<and> ownT s = W" have "\<forall>r. W \<noteq> ownT s \<or> B \<noteq> ownD s (numEnqs s) \<or> \<not> pre_enqueue_inv s \<or> Q_structure r \<or> \<not> numReads s \<le> numWrites s \<or> \<not> numDeqs s < numEnqs s \<or> \<not> Q_enqueue s r \<or> \<not> Q_structure s \<or> [] = q s" using a1 by (smt (z3) enqueue_preserves_Q_n_o) then have "Q_structure (s\<lparr>ownT := Q, numEnqs := Suc (numEnqs s), ownB := \<lambda>n. if ownB s n = W then Q else ownB ((if ownT s = W then ownT_update (\<lambda>f. Q) else (\<lambda>r. r\<lparr>ownT := ownT r\<rparr>)) s \<lparr>numEnqs := Suc (numEnqs s)\<rparr>) n, pcW := idleW, q := q s @ [(offset s, Data s (numEnqs s))]\<rparr>)" using a3 a1 by (metis (full_types)) then show "Q_structure (s\<lparr>ownT := Q, numEnqs := Suc (numEnqs s), ownB := \<lambda>n. if ownB s n = W then Q else ownB (s\<lparr>ownT := Q, numEnqs := Suc (numEnqs s)\<rparr>) n, pcW := idleW, q := q s @ [(offset s, Data s (numEnqs s))]\<rparr>)" using a2 by presburger next show "Q_structure s \<and> s' = s \<lparr>numEnqs := Suc (numEnqs s), ownB := \<lambda>i. if ownB s i = W then Q else ownB ((if ownT s = W then ownT_update (\<lambda>_. Q) else (\<lambda>s. s\<lparr>ownT := ownT s\<rparr>)) s \<lparr>numEnqs := Suc (numEnqs s)\<rparr>) i, pcW := idleW, q := [(offset s, Data s (numEnqs s))]\<rparr> \<and> numEnqs s \<le> numDeqs s \<and> pre_enqueue_inv s \<and> numReads s \<le> numWrites s \<and> numDeqs s \<le> numEnqs s \<and> ownD s (numEnqs s) = B \<Longrightarrow> q s = [] \<Longrightarrow> ownT s \<noteq> W \<Longrightarrow> (\<And>s s'. q s \<noteq> [] \<and> Q_structure s \<and> Q_enqueue s s' \<and> numDeqs s < numEnqs s \<and> numReads s \<le> numWrites s \<and> length (q s) = numEnqs s - numDeqs s \<and> pre_enqueue_inv s \<and> ownD s (numEnqs s) = B \<and> ownT s = W \<Longrightarrow> Q_structure s') \<Longrightarrow> Q_structure (s\<lparr>numEnqs := Suc (numEnqs s), ownB := \<lambda>i. if ownB s i = W then Q else ownB (s\<lparr>ownT := ownT s, numEnqs := Suc (numEnqs s)\<rparr>) i, pcW := idleW, q := [(offset s, Data s (numEnqs s))]\<rparr>)" (*2*) apply(subgoal_tac "q s=[] \<and> Q_structure s \<and> Q_enqueue s s' \<and> numEnqs s = numDeqs s \<and> length(q s) = numEnqs s-numDeqs s \<and> pre_enqueue_inv s \<and> numWrites s\<ge>numReads s \<and> ownD s(numEnqs s) =B \<and> ownT s \<noteq>W") prefer 2 apply(subgoal_tac "q s=[]") prefer 2 apply blast apply(subgoal_tac "ownT s \<noteq>W") prefer 2 apply blast apply(subgoal_tac "ownD s(numEnqs s) =B") prefer 2 apply blast apply(subgoal_tac "pre_enqueue_inv s") prefer 2 apply blast apply(subgoal_tac "length(q s) = numEnqs s-numDeqs s") prefer 2 using assms apply blast apply(subgoal_tac "Q_structure s") prefer 2 apply blast apply(subgoal_tac "Q_enqueue s s'") prefer 2 using assms apply blast apply(subgoal_tac "q s=[]\<longrightarrow>length(q s) = 0") prefer 2 apply blast apply(subgoal_tac "numEnqs s = numDeqs s") apply blast apply(subgoal_tac "q s\<noteq>[]\<longrightarrow>length(q s)\<ge>0") prefer 2 apply blast apply(subgoal_tac "q s=[]\<longrightarrow>length(q s) =0") prefer 2 apply blast apply(subgoal_tac "length(q s)\<ge>0") prefer 2 apply blast apply(subgoal_tac "numEnqs s \<ge>0") prefer 2 apply blast apply(subgoal_tac "numDeqs s \<ge>0") prefer 2 apply blast apply(subgoal_tac "(length(q s) = numEnqs s-numDeqs s \<and> length(q s)\<ge>0 \<and> numEnqs s\<ge>0 \<and> numDeqs s\<ge>0 \<and> length(q s) = 0)\<longrightarrow>numEnqs s-numDeqs s=0") prefer 2 apply presburger using dual_order.antisym apply blast using enqueue_preserves_Q_e_n proof - assume a1: "Q_structure s \<and> s' = s \<lparr>numEnqs := Suc (numEnqs s), ownB := \<lambda>i. if ownB s i = W then Q else ownB ((if ownT s = W then ownT_update (\<lambda>_. Q) else (\<lambda>s. s\<lparr>ownT := ownT s\<rparr>)) s \<lparr>numEnqs := Suc (numEnqs s)\<rparr>) i, pcW := idleW, q := [(offset s, Data s (numEnqs s))]\<rparr> \<and> numEnqs s \<le> numDeqs s \<and> pre_enqueue_inv s \<and> numReads s \<le> numWrites s \<and> numDeqs s \<le> numEnqs s \<and> ownD s (numEnqs s) = B" assume "q s = []" assume a2: "ownT s \<noteq> W" assume a3: "q s = [] \<and> Q_structure s \<and> Q_enqueue s s' \<and> numEnqs s = numDeqs s \<and> length (q s) = numEnqs s - numDeqs s \<and> pre_enqueue_inv s \<and> numReads s \<le> numWrites s \<and> ownD s (numEnqs s) = B \<and> ownT s \<noteq> W" then have "\<forall>r. numDeqs s - numDeqs s \<noteq> length (q s) \<or> B \<noteq> ownD s (numEnqs s) \<or> Q_structure r \<or> \<not> Q_enqueue s r \<or> [] \<noteq> q s" by (metis (full_types) enqueue_preserves_Q_e_n) then have "Q_structure (s\<lparr>numEnqs := Suc (numEnqs s), ownB := \<lambda>n. if ownB s n = W then Q else ownB ((if ownT s = W then ownT_update (\<lambda>f. Q) else (\<lambda>r. r\<lparr>ownT := ownT r\<rparr>)) s \<lparr>numEnqs := Suc (numEnqs s)\<rparr>) n, pcW := idleW, q := [(offset s, Data s (numEnqs s))]\<rparr>)" using a3 a1 by (metis (full_types)) then show ?thesis using a2 by presburger qed next (*1*) show "Q_structure s \<and> s' = s \<lparr>ownT := Q, numEnqs := Suc (numEnqs s), ownB := \<lambda>i. if ownB s i = W then Q else ownB ((if ownT s = W then ownT_update (\<lambda>_. Q) else (\<lambda>s. s\<lparr>ownT := ownT s\<rparr>)) s \<lparr>numEnqs := Suc (numEnqs s)\<rparr>) i, pcW := idleW, q := [(offset s, Data s (numEnqs s))]\<rparr> \<and> numEnqs s \<le> numDeqs s \<and> pre_enqueue_inv s \<and> numReads s \<le> numWrites s \<and> numDeqs s \<le> numEnqs s \<and> ownD s (numEnqs s) = B \<Longrightarrow> q s = [] \<Longrightarrow> ownT s = W \<Longrightarrow> (\<And>s s'. q s \<noteq> [] \<and> Q_structure s \<and> Q_enqueue s s' \<and> numDeqs s < numEnqs s \<and> numReads s \<le> numWrites s \<and> length (q s) = numEnqs s - numDeqs s \<and> pre_enqueue_inv s \<and> ownD s (numEnqs s) = B \<and> ownT s = W \<Longrightarrow> Q_structure s') \<Longrightarrow> Q_structure (s\<lparr>ownT := Q, numEnqs := Suc (numEnqs s), ownB := \<lambda>i. if ownB s i = W then Q else ownB (s\<lparr>ownT := Q, numEnqs := Suc (numEnqs s)\<rparr>) i, pcW := idleW, q := [(offset s, Data s (numEnqs s))]\<rparr>)" apply(subgoal_tac "q s=[] \<and> Q_structure s \<and> Q_enqueue s s' \<and> numDeqs s=numEnqs s \<and> length(q s) = numEnqs s-numDeqs s \<and> pre_enqueue_inv s \<and> ownD s(numEnqs s) =B \<and> ownT s =W") prefer 2 using assms verit_la_disequality apply blast using enqueue_preserves_Q_e_o proof - assume a1: "Q_structure s \<and> s' = s \<lparr>ownT := Q, numEnqs := Suc (numEnqs s), ownB := \<lambda>i. if ownB s i = W then Q else ownB ((if ownT s = W then ownT_update (\<lambda>_. Q) else (\<lambda>s. s\<lparr>ownT := ownT s\<rparr>)) s \<lparr>numEnqs := Suc (numEnqs s)\<rparr>) i, pcW := idleW, q := [(offset s, Data s (numEnqs s))]\<rparr> \<and> numEnqs s \<le> numDeqs s \<and> pre_enqueue_inv s \<and> numReads s \<le> numWrites s \<and> numDeqs s \<le> numEnqs s \<and> ownD s (numEnqs s) = B" assume "q s = []" assume a2: "ownT s = W" assume a3: "q s = [] \<and> Q_structure s \<and> Q_enqueue s s' \<and> numDeqs s = numEnqs s \<and> length (q s) = numEnqs s - numDeqs s \<and> pre_enqueue_inv s \<and> ownD s (numEnqs s) = B \<and> ownT s = W" then have "\<forall>r. B \<noteq> ownD s (numEnqs s) \<or> Q_structure r \<or> \<not> Q_enqueue s r" using a1 enqueue_preserves_Q_e_o by blast then have "Q_structure (s\<lparr>ownT := Q, numEnqs := Suc (numEnqs s), ownB := \<lambda>n. if ownB s n = W then Q else ownB ((if ownT s = W then ownT_update (\<lambda>f. Q) else (\<lambda>r. r\<lparr>ownT := ownT r\<rparr>)) s \<lparr>numEnqs := Suc (numEnqs s)\<rparr>) n, pcW := idleW, q := [(offset s, Data s (numEnqs s))]\<rparr>)" using a3 a1 by (metis (full_types)) then show ?thesis using a2 by presburger qed qed (*----------enqueue end-----------------------*) (*****************old stuff************************************************************) (* lemma Q_no_buffer_overlap_lemma_2: assumes "Q_structure s" and "length(q s) >0" and "con_assms s" and "case_1 s" shows "\<exists>b c.(b<c\<and> c\<le>N \<and> (\<forall>i.(b\<ge>i\<and>c<i)\<longrightarrow>ownB s i=Q) \<and> b=fst(q s ! 0) \<and> c=end(last(q s)))" using assms apply simp apply (simp add:con_assms_def Q_lemmas Q_basic_lemmas case_1_def) by (metis (no_types, lifting) assms(2) diff_is_0_eq' head_q0 le_eq_less_or_eq less_trans_Suc not_less_eq_eq) lemma Q_no_buffer_overlap_lemma_3: assumes "Q_structure s" and "length(q s) >0" and "con_assms s" and "case_1 s" shows "fst(hd(q s))<end(last(q s))" using assms apply simp apply (simp add:con_assms_def Q_lemmas Q_basic_lemmas case_1_def) by (metis (no_types, lifting) assms(2) diff_is_0_eq' head_q0 le_eq_less_or_eq less_trans_Suc not_less_eq_eq) lemma Q_no_buffer_overlap_lemma_4: assumes "Q_structure s" and "length(q s) >0" and "con_assms s" and "case_1 s" and "ownB s 0 = Q" shows "\<forall>i.(i<length(q s) \<and> i>0)\<longrightarrow>fst(q s!i) = end(q s!(i-1))" using assms apply simp apply (simp add:con_assms_def Q_lemmas Q_basic_lemmas case_1_def) by (metis F.distinct(11) F.distinct(19) F.distinct(3) assms(2) head_q0 le_add2 le_add_same_cancel2 not_gr0) lemma Q_no_buffer_overlap_lemma_5: assumes "Q_structure s" and "length(q s) >0" and "inv s" and "con_assms s" and "case_1 s" shows "\<forall>i.(i<length(q s) \<and> i>0)\<longrightarrow>fst(q s!i) = end(q s!(i-1))" using assms apply simp apply (simp add:con_assms_def Q_lemmas Q_basic_lemmas case_1_def inv_def) using case_1_Q_struct [where s=s] by (metis One_nat_def assms(1) assms(5) end_simp) lemma Q_no_buffer_overlap_lemma_6: assumes "Q_structure s" and "length(q s)>0" and "inv s" and "con_assms s" and "case_1 s" shows "\<forall>i j.(i=j+1 \<and> i<length(q s) \<and> j\<ge>0)\<longrightarrow>fst(q s!i) = end(q s!j)" using Q_no_buffer_overlap_lemma_5 by (metis add_diff_cancel_right' add_nonneg_pos assms(1) assms(2) assms(3) assms(4) assms(5) zero_less_one) lemma Q_no_buffer_overlap_lemma_7: assumes "Q_structure s" and "length(q s)>0" and "inv s" and "con_assms s" and "case_1 s" shows "\<forall>i j.(i=j+1 \<and> i<length(q s) \<and> j\<ge>0)\<longrightarrow>fst(q s!i) > fst(q s!j)" by (metis Q_gap_lemmas_5_list Q_no_buffer_overlap_lemma_6 add_lessD1 assms(1) assms(2) assms(3) assms(4) assms(5) nat_le_linear) lemma Q_no_buffer_overlap_lemma_8: assumes "Q_structure s" and "length(q s)>0" and "inv s" and "con_assms s" and "case_1 s" shows "\<forall>i j.( i<length(q s) \<and> j>0 \<and> i>j \<and> fst(q s!i)>fst(q s!j))\<longrightarrow>fst(q s!i) > fst(q s!(j-1))" using Q_no_buffer_overlap_lemma_5 assms(1) assms(3) assms(4) assms(5) by fastforce lemma Q_no_buffer_overlap_lemma_9: assumes "Q_structure s" and "length(q s)>0" and "inv s" and "con_assms s" and "case_1 s" shows "\<forall>i.(ownB s i = Q \<and> i<N)\<longrightarrow>(\<exists>a b.((a,b)\<in>set(q s)\<and> a\<le>i \<and> i<a+b))" using assms apply simp apply(simp add:inv_def Q_lemmas Q_basic_lemmas con_assms_def case_1_def) apply(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def butlast_def) by (metis (no_types, lifting) mem_Collect_eq) lemma Q_overlap_lemma_1: assumes "Q_structure s" and "length(q s)>0" and "inv s" and "con_assms s" shows "\<forall>i.(ownB s i = Q \<and> i<N)\<longrightarrow>(\<exists>a b.((a,b)\<in>set(q s)\<and> a\<le>i \<and> i<a+b))" using assms apply simp apply(simp add:inv_def Q_lemmas Q_basic_lemmas con_assms_def case_1_def) apply(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def butlast_def) by (metis (no_types, lifting) mem_Collect_eq) lemma Q_overlap_lemma_2: assumes "Q_structure s" and "length(q s)>0" and "inv s" and "con_assms s" and "case_1 s" shows "\<forall>a b.((a,b)\<in>set(q s))\<longrightarrow>(\<forall>j.(a\<le>j \<and> j<a+b)\<longrightarrow>ownB s j = Q)" using assms apply simp apply(simp add:inv_def Q_lemmas Q_basic_lemmas con_assms_def case_1_def) apply(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def butlast_def) by (metis (no_types, lifting) mem_Collect_eq) lemma Q_overlap_lemma_3: assumes "Q_structure s" and "length(q s)>0" and "inv s" and "con_assms s" and "case_2 s" shows "\<forall>a b.((a,b)\<in>set(q s))\<longrightarrow>(\<forall>j.(a\<le>j \<and> j<a+b)\<longrightarrow>ownB s j = Q)" using assms apply simp apply(simp add:inv_def Q_lemmas Q_basic_lemmas con_assms_def case_2_def) apply(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def butlast_def) by (metis (no_types, lifting) mem_Collect_eq) lemma Q_overlap_lemma_4_B: assumes "Q_structure s" and "length(q s)>0" and "inv s" and "con_assms s" and "(a,b)\<in>set(q s)" and "a\<le>j" and "j<a+b" shows "ownB s j = Q" using assms apply (simp add:inv_def) apply(case_tac "case_1 s") using Q_overlap_lemma_2 [where s=s] using assms(3) assms(4) apply blast using Q_overlap_lemma_3 [where s=s] using assms(3) assms(4) by blast lemma Q_overlap_lemma_4: assumes "Q_structure s" and "length(q s)>0" and "inv s" and "con_assms s" shows "\<forall>a b.((a,b)\<in>set(q s))\<longrightarrow>(\<forall>j.(a\<le>j \<and> j<a+b)\<longrightarrow>ownB s j = Q)" using Q_overlap_lemma_4_B using assms(1) assms(2) assms(3) assms(4) by blast lemma Q_overlap_lemma_5: assumes "Q_structure s" and "length(q s)>0" and "inv s" and "con_assms s" shows "\<forall>i.(i<length(q s))\<longrightarrow>(\<forall>j.(fst(q s!i)\<le>j \<and> j<end(q s!i))\<longrightarrow>ownB s j = Q)" using assms Q_overlap_lemma_4 [where s=s] by (metis Q_gap_lemmas_2 end_simp prod.collapse) lemma Q_buffer_overlap_lemma_A4_1: assumes "inv s" and "con_assms s" and "Q_structure s" and "case_2 s" and "length(q s)>0" shows "\<forall>i j.(i<length(q s) \<and> j<length(q s)\<and>fst(q s!i)<fst(q s!j))\<longrightarrow>end(q s!i)\<le>fst(q s!j)" using Q_gap_lemmas_4_list assms(3) assms(5) by auto lemma Q_buffer_overlap_lemma_A4_2: assumes "inv s" and "con_assms s" and "Q_structure s" and "case_2 s" and "pcW s = A4" and "pre_A4_inv s" and "length(q s)>0" shows "hW s = end(last(q s))" using assms apply(simp add:inv_def pre_A4_inv_def case_2_def) by (metis (no_types, hide_lams) F.distinct(23) assms(7) diff_add_inverse2 le_antisym le_eq_less_or_eq linorder_neqE_nat zero_less_iff_neq_zero) lemma Q_buffer_overlap_lemma_A4_3: assumes "inv s" and "con_assms s" and "Q_structure s" and "case_2 s" and "pcW s = A4" and "pre_A4_inv s" and "length(q s)>0" shows "tW s>hW s" using assms by(simp add:inv_def pre_A4_inv_def case_2_def) lemma Q_buffer_overlap_lemma_A4_4: assumes "con_assms s" and "Q_structure s" and "case_2 s" and "pcW s = A4" and "pre_A4_inv s" and "length(q s)>0" shows "(\<exists>i.(ownB s i=R\<and>i<N))\<longrightarrow>ownB s (T s) = R" using assms apply(simp add:inv_def pre_A4_inv_def case_2_def) apply clarify apply(subgoal_tac "T s=c") prefer 2 apply (metis F.distinct(13) bot_nat_0.extremum bot_nat_0.not_eq_extremum) apply clarify apply(case_tac "T s \<noteq>d") prefer 2 apply (metis F.distinct(13) F.distinct(15) diff_is_0_eq' linorder_neqE_nat nat_le_linear zero_less_diff) by (metis le_neq_implies_less le_refl) lemma Q_buffer_overlap_lemma_A4_5: assumes "con_assms s" and "Q_structure s" and "case_2 s" and "pcW s = A4" and "pre_A4_inv s" and "length(q s)>0" shows "\<forall>i j.(j<fst(q s!i)\<and>i<length(q s))\<longrightarrow>j<end(q s!i)" using assms by(simp add:inv_def pre_A4_inv_def case_2_def) lemma Q_buffer_overlap_lemma_A4_6: assumes "con_assms s" and "Q_structure s" and "case_2 s" and "pcW s = A4" and "pre_A4_inv s" and "length(q s)>0" shows "\<forall>a b.((a,b)\<in>set(q s))\<longrightarrow>a\<in>ran_indices a (a+b)" by (metis assms(2) fst_conv in_set_conv_nth ran_indices_lem snd_conv) lemma Q_buffer_overlap_lemma_A4_7: assumes "con_assms s" and "Q_structure s" and "case_2 s" and "pcW s = A4" and "pre_A4_inv s" and "length(q s)>0" shows "\<forall>a b.((a,b)\<in>set(q s))\<longrightarrow>a\<in>Q_indices s" using assms apply(simp add:inv_def pre_A4_inv_def case_2_def) apply(simp add:Q_lemmas Q_basic_lemmas) apply(simp add:Q_indices_def ran_indices_def) apply(subgoal_tac "\<exists>l k.((l,k)\<in>set(q s))") prefer 2 apply (metis list.set_sel(1) surjective_pairing) using Q_buffer_overlap_lemma_A4_6 by (metis assms(1) assms(2) assms(3) assms(5) assms(6) ran_indices_def) lemma Q_buffer_overlap_lemma_A4_8: assumes "con_assms s" and "Q_structure s" and "case_2 s" and "pcW s = A4" and "pre_A4_inv s" and "length(q s)>0" and "Q_owns_bytes s" shows "\<forall>a b.((a,b)\<in>set(q s))\<longrightarrow>ownB s a=Q" using assms apply(simp add:inv_def pre_A4_inv_def case_2_def) apply(simp add:Q_lemmas Q_basic_lemmas) using Q_buffer_overlap_lemma_A4_7 by (metis Q_owns_bytes_def assms(1) assms(2) assms(3) assms(5) assms(6)) lemma Q_buffer_overlap_lemma_A4_9: assumes "con_assms s" and "Q_structure s" and "case_2 s" and "pcW s = A4" and "pre_A4_inv s" and "length(q s)>0" and "Q_owns_bytes s" and "t<N" and "ownB s t \<noteq> Q" shows "t\<notin>Q_indices s" using assms apply(simp add:inv_def pre_A4_inv_def case_2_def) apply(simp add:Q_lemmas Q_basic_lemmas) using Q_owns_bytes_def by metis lemma Q_buffer_overlap_lemma_A4_10: assumes "con_assms s" and "Q_structure s" and "case_2 s" and "pcW s = A4" and "pre_A4_inv s" and "length(q s)>0" and "Q_owns_bytes s" and "t<N" and "ownB s t \<noteq> Q" shows "\<forall>a b.((a,b)\<in>set(q s))\<longrightarrow>(a>t\<or>t>a)" using assms apply(simp add:inv_def pre_A4_inv_def case_2_def) apply(simp add:Q_lemmas Q_basic_lemmas) using Q_buffer_overlap_lemma_A4_9 Q_buffer_overlap_lemma_A4_7 Q_buffer_overlap_lemma_A4_8 Q_owns_bytes_def Q_indices_def by (metis assms(1) assms(2) assms(3) assms(5) assms(6) linorder_neqE_nat) lemma Q_buffer_overlap_lemma_A4_11: assumes "con_assms s" and "Q_structure s" and "case_2 s" and "pcW s = A4" and "pre_A4_inv s" and "length(q s)>0" and "Q_owns_bytes s" shows "\<forall>a b j.((a,b)\<in>set(q s) \<and> a\<le>j \<and> j<(a+b))\<longrightarrow>j\<in>ran_indices a (a+b)" using assms apply(simp add:inv_def pre_A4_inv_def case_2_def) by(simp add:Q_lemmas Q_basic_lemmas ran_indices_def) lemma Q_buffer_overlap_lemma_A4_12: assumes "con_assms s" and "Q_structure s" and "case_2 s" and "pcW s = A4" and "pre_A4_inv s" and "length(q s)>0" and "Q_owns_bytes s" shows "\<forall>a b j.((a,b)\<in>set(q s) \<and> a\<le>j \<and> j<(a+b))\<longrightarrow>j\<in>Q_indices s" using assms apply(simp add:inv_def pre_A4_inv_def case_2_def) apply(simp add:Q_lemmas Q_basic_lemmas) apply(simp add: Q_owns_bytes_def Q_indices_def ran_indices_def) by (metis (no_types, lifting) mem_Collect_eq) lemma Q_buffer_overlap_lemma_A4_13: assumes "con_assms s" and "Q_structure s" and "case_2 s" and "pcW s = A4" and "pre_A4_inv s" and "length(q s)>0" and "Q_owns_bytes s" shows "\<forall>a b j.((a,b)\<in>set(q s) \<and> a\<le>j \<and> j<(a+b))\<longrightarrow>ownB s j=Q" using assms apply(simp add:inv_def pre_A4_inv_def case_2_def) apply(simp add:Q_lemmas Q_basic_lemmas) apply(simp add: Q_owns_bytes_def Q_indices_def ran_indices_def) by (metis (no_types, lifting) mem_Collect_eq) lemma Q_buffer_overlap_lemma_A4_14: assumes "con_assms s" and "Q_structure s" and "case_2 s" and "pcW s = A4" and "pre_A4_inv s" and "length(q s)>0" and "Q_owns_bytes s" shows "\<forall>a b j.((a,b)\<in>set(q s) \<and> a\<le>j \<and> j<(a+b))\<longrightarrow>ownB s j=Q" using assms apply(simp add:inv_def pre_A4_inv_def case_2_def) apply(simp add:Q_lemmas Q_basic_lemmas) apply(simp add: Q_owns_bytes_def Q_indices_def ran_indices_def) by (metis (no_types, lifting) mem_Collect_eq) lemma Q_buffer_overlap_lemma_A4_15: assumes "con_assms s" and "Q_structure s" and "case_2 s" and "pcW s = A4" and "pre_A4_inv s" and "length(q s)>0" and "Q_owns_bytes s" and "t<N" and "ownB s t \<noteq> Q" shows "\<forall>a b.((a,b)\<in>set(q s))\<longrightarrow>t\<notin>Q_indices s" using assms apply(simp add:inv_def pre_A4_inv_def case_2_def) apply(simp add:Q_lemmas Q_basic_lemmas) by(simp add: Q_owns_bytes_def Q_indices_def ran_indices_def) lemma Q_buffer_overlap_lemma_A4_16: assumes "con_assms s" and "Q_structure s" and "case_2 s" and "pcW s = A4" and "pre_A4_inv s" and "length(q s)>0" and "Q_owns_bytes s" and "t<N" and "ownB s t \<noteq> Q" shows "\<forall>a b.((a,b)\<in>set(q s))\<longrightarrow>t\<notin>ran_indices a (a+b)" using assms apply(simp add:inv_def pre_A4_inv_def case_2_def) apply(simp add:Q_lemmas Q_basic_lemmas) apply(simp add: Q_owns_bytes_def Q_indices_def ran_indices_def) by (metis (no_types, lifting) mem_Collect_eq) lemma if_not_in_ran_indices_then: assumes "i<N" and "l<N" and "k<N" and "i\<notin>ran_indices l k" shows "i\<ge>k \<or> i<l" using assms apply(simp add:ran_indices_def) by auto lemma Q_buffer_overlap_lemma_A4_17: assumes "con_assms s" and "Q_structure s" and "case_2 s" and "pcW s = A4" and "pre_A4_inv s" and "length(q s)>0" and "Q_owns_bytes s" and "t<N" and "ownB s t \<noteq> Q" shows "\<forall>a b.((a,b)\<in>set(q s)\<and> t\<notin>ran_indices a (a+b))\<longrightarrow>(t<a \<or> t\<ge>(a+b))" using assms apply(simp add:inv_def pre_A4_inv_def case_2_def) apply(simp add:Q_lemmas Q_basic_lemmas) apply(simp add: Q_owns_bytes_def Q_indices_def ran_indices_def) by (metis Suc_le_lessD not_less_eq_eq) lemma Q_buffer_overlap_lemma_A4_18: assumes "con_assms s" and "Q_structure s" and "case_2 s" and "pcW s = A4" and "pre_A4_inv s" and "length(q s)>0" and "Q_owns_bytes s" and "t<N" and "ownB s t \<noteq> Q" shows "\<forall>a b.((a,b)\<in>set(q s))\<longrightarrow>(t<a \<or> t\<ge>(a+b))" using assms apply(simp add:inv_def pre_A4_inv_def case_2_def) apply(simp add:Q_lemmas Q_basic_lemmas) apply(simp add: Q_owns_bytes_def Q_indices_def ran_indices_def) using Q_buffer_overlap_lemma_A4_16 Q_buffer_overlap_lemma_A4_17 by (metis (no_types, lifting) assms(1) assms(2) assms(3) assms(5) assms(6) assms(7)) lemma Q_no_buffer_overlap_lemma_19: assumes "con_assms s" and "Q_structure s" and "hW s>tW s" and "length(q s)>0" and "Q_owns_bytes s" shows "\<forall>j.(ownB s j=Q \<and> j<N)\<longrightarrow>(j\<in>Q_indices s)" using assms apply simp apply(simp add:Q_lemmas Q_basic_lemmas) by(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) lemma Q_buffer_overlap_lemma_20: assumes "con_assms s" and "Q_structure s" and "hW s>tW s" and "length(q s)>0" and "Q_owns_bytes s" shows "\<forall>a b j.((a,b)\<in>set(q s)\<and>a\<le>j \<and> j<a+b)\<longrightarrow>j\<in>ran_indices a (a+b)" using assms apply simp apply(simp add:Q_lemmas Q_basic_lemmas) by(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) lemma Q_buffer_overlap_lemma_21_B: assumes "con_assms s" and "Q_structure s" and "hW s>tW s" and "length(q s)>0" and "Q_owns_bytes s" and "(a,b)\<in>set(q s)" and "j\<in>ran_indices a (a+b)" shows "j\<in>Q_indices s" using assms apply simp apply(simp add:Q_lemmas Q_basic_lemmas) apply(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) by auto lemma Q_buffer_overlap_lemma_21: assumes "con_assms s" and "Q_structure s" and "hW s>tW s" and "length(q s)>0" and "Q_owns_bytes s" shows "\<forall>a b j.((a,b)\<in>set(q s)\<and>j\<in>ran_indices a (a+b))\<longrightarrow>j\<in>Q_indices s" using Q_buffer_overlap_lemma_21_B assms(1) assms(2) assms(3) assms(4) assms(5) by blast lemma Q_buffer_overlap_lemma_22: assumes "con_assms s" and "Q_structure s" and "hW s>tW s" and "length(q s)>0" and "Q_owns_bytes s" shows "\<forall>a b j.((a,b)\<in>set(q s)\<and>j\<in>ran_indices a (a+b))\<longrightarrow>ownB s j=Q" using assms apply simp apply(simp add:Q_lemmas Q_basic_lemmas) apply(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) by auto lemma Q_buffer_overlap_lemma_23: assumes "con_assms s" and "Q_structure s" and "hW s>tW s" and "length(q s)>0" and "Q_owns_bytes s" shows "\<forall>a b j.((a,b)\<in>set(q s)\<and>ownB s j=Q\<and>j\<in>ran_indices a (a+b))\<longrightarrow>j<N" using assms apply simp apply(simp add:Q_lemmas Q_basic_lemmas) apply(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) by (metis le_antisym le_neq_implies_less le_trans less_or_eq_imp_le) lemma Q_buffer_overlap_lemma_24: assumes "con_assms s" and "Q_structure s" and "hW s>tW s" and "length(q s)>0" and "Q_owns_bytes s" shows "\<forall>j.(j\<in>Q_indices s\<and>j<N)\<longrightarrow>(\<exists>a b.((a,b)\<in>set(q s)\<and> a\<le>j \<and> j<(a+b)))" using assms apply simp apply(simp add:Q_lemmas Q_basic_lemmas) apply(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) by (metis (mono_tags, lifting) mem_Collect_eq) lemma Q_buffer_overlap_lemma_25: assumes "con_assms s" and "Q_structure s" and "hW s>tW s" and "length(q s)>0" and "Q_owns_bytes s" shows "\<forall>j a b.((a,b)\<in>set(q s)\<and> a\<le>j \<and> j<(a+b))\<longrightarrow>j<N" using assms apply simp apply(simp add:Q_lemmas Q_basic_lemmas) apply(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) by (metis le_antisym le_neq_implies_less le_trans less_or_eq_imp_le) lemma Q_buffer_overlap_lemma_26: assumes "con_assms s" and "Q_structure s" and "hW s>tW s" and "length(q s)>0" and "Q_owns_bytes s" shows "\<forall>j.(j\<in>Q_indices s)\<longrightarrow>(\<exists>a b.((a,b)\<in>set(q s)\<and> a\<le>j \<and> j<(a+b)))" using assms apply simp apply(simp add:Q_lemmas Q_basic_lemmas) apply(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) by (metis (mono_tags, lifting) mem_Collect_eq) lemma Q_buffer_overlap_lemma_27: assumes "con_assms s" and "Q_structure s" and "hW s>tW s" and "length(q s)>0" and "Q_owns_bytes s" shows "\<forall>j.(j\<in>Q_indices s)\<longrightarrow>(j<N)" using assms apply simp using Q_buffer_overlap_lemma_26 [where s=s] using Q_buffer_overlap_lemma_25 [where s=s] using assms(1) by blast lemma Q_buffer_overlap_lemma_28: assumes "con_assms s" and "Q_structure s" and "hW s>tW s" and "length(q s)>0" and "Q_owns_bytes s" shows "\<forall>j.(j\<in>Q_indices s)\<longrightarrow>(ownB s j=Q)" using assms apply simp using Q_buffer_overlap_lemma_26 [where s=s] using Q_buffer_overlap_lemma_25 [where s=s] using assms(1) using Q_owns_bytes_def by blast lemma Q_buffer_overlap_lemma_29: assumes "con_assms s" and "Q_structure s" and "hW s>tW s" and "length(q s)>0" and "Q_owns_bytes s" shows "\<forall>j.(j\<notin>Q_indices s\<and>j<N)\<longrightarrow>(ownB s j\<noteq>Q)" using assms apply simp using Q_buffer_overlap_lemma_26 [where s=s] using Q_buffer_overlap_lemma_25 [where s=s] using assms(1) using Q_owns_bytes_def by blast lemma Q_buffer_overlap_lemma_35: assumes "con_assms s" and "Q_structure s" and "case_1 s" and "hW s>tW s" and "\<forall>i.(i<N)\<longrightarrow>ownB s i\<noteq>W" and "length(q s)>0" and "Q_owns_bytes s" and "hW s=H s" shows "\<forall>i.(i\<ge>hW s \<and> i<N)\<longrightarrow>ownB s i\<noteq>Q" using assms apply simp apply(simp add:case_1_def) apply clarify by (metis F.distinct(19) F.distinct(21) diff_is_0_eq less_nat_zero_code linorder_neqE_nat zero_less_diff) lemma Q_buffer_overlap_lemma_36: assumes "con_assms s" and "Q_structure s" and "case_1 s" and "pre_A6_inv s" and "\<forall>i.(i<N)\<longrightarrow>ownB s i\<noteq>W" and "length(q s)>0" and "Q_owns_bytes s" and "hW s=H s" shows "\<forall>i.(i<tW s)\<longrightarrow>ownB s i\<noteq>Q" using assms apply simp apply(simp add:case_1_def) apply clarify by (smt (z3) F.distinct(19) pre_A6_inv_def) lemma Q_buffer_overlap_lemma_37: assumes "con_assms s" and "Q_structure s" and "case_1 s" and "pre_A6_inv s" and "length(q s)>0" and "Q_owns_bytes s" and "hW s=H s" shows "\<forall>i.(ownB s i=Q)\<longrightarrow>i\<ge>tW s" using Q_buffer_overlap_lemma_36 [where s=s] assms apply simp by (smt (verit, best) F.distinct(19) leI pre_A6_inv_def) lemma Q_buffer_overlap_lemma_38: assumes "con_assms s" and "Q_structure s" and "pre_A6_inv s" and "length(q s)>0" and "Q_owns_bytes s" and "hW s=H s" shows "\<forall>i.(ownB s i=Q \<and> i<N)\<longrightarrow>i\<in>Q_indices s" using Q_buffer_overlap_lemma_36 [where s=s] assms apply simp using Q_owns_bytes_def by auto lemma Q_buffer_overlap_lemma_39: assumes "con_assms s" and "Q_structure s" and "pre_A6_inv s" and "length(q s)>0" and "Q_owns_bytes s" and "hW s=H s" shows "\<forall>i.(i\<in>Q_indices s)\<longrightarrow>(ownB s i=Q \<and> i<N)" using Q_buffer_overlap_lemma_36 [where s=s] assms apply simp by (smt (verit, ccfv_SIG) Q_buffer_overlap_lemma_27 Q_owns_bytes_def assms(1) assms(4) grd3_def pre_A6_inv_def) lemma Q_buffer_overlap_lemma_40: assumes "con_assms s" and "Q_structure s" and "case_1 s" and "pre_A6_inv s" and "length(q s)>0" and "Q_owns_bytes s" and "hW s=H s" shows "\<forall>i.(i\<ge>hW s \<and> i<tW s)\<longrightarrow>ownB s i = B" using Q_buffer_overlap_lemma_36 [where s=s] assms apply simp using pre_A6_inv_def by auto lemma Q_buffer_overlap_lemma_41: assumes "con_assms s" and "Q_structure s" and "case_1 s" and "pre_A6_inv s" and "length(q s)>0" and "Q_owns_bytes s" and "hW s=H s" shows "\<forall>i j.(i<length(q s) \<and> j\<ge>fst(q s!i) \<and> j<end(q s!i))\<longrightarrow>ownB s j = Q" using Q_buffer_overlap_lemma_36 [where s=s] assms apply simp apply(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) apply(subgoal_tac "\<forall>a b i.((a,b)\<in>set(q s) \<and> i\<ge>a \<and> i<(a+b))\<longrightarrow>ownB s i=Q") prefer 2 apply blast by (metis (mono_tags, hide_lams) nth_mem prod.collapse) lemma Q_buffer_overlap_lemma_42: assumes "con_assms s" and "Q_structure s" and "case_1 s" and "pre_A6_inv s" and "length(q s)>0" and "Q_owns_bytes s" and "hW s=H s" shows "\<forall>i j.(i<length(q s) \<and> j<end(q s!i) \<and> ownB s j \<noteq> Q)\<longrightarrow>j<fst(q s!i)" using Q_buffer_overlap_lemma_36 [where s=s] assms apply simp apply(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) apply(subgoal_tac "\<forall>a b i.((a,b)\<in>set(q s) \<and> i\<ge>a \<and> i<(a+b))\<longrightarrow>ownB s i=Q") prefer 2 apply blast by (metis (mono_tags, lifting) eq_imp_le less_imp_le_nat linorder_neqE_nat nth_mem surjective_pairing) lemma Q_buffer_overlap_lemma_43: assumes "con_assms s" and "Q_structure s" and "case_1 s" and "pre_A6_inv s" and "length(q s)>0" and "Q_owns_bytes s" and "hW s=H s" shows "\<forall>i j.(i<length(q s) \<and> j\<ge>fst(q s!i) \<and> ownB s j \<noteq> Q)\<longrightarrow>j\<ge>end(q s!i)" using Q_buffer_overlap_lemma_36 [where s=s] assms apply simp apply(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) apply(subgoal_tac "\<forall>a b i.((a,b)\<in>set(q s) \<and> i\<ge>a \<and> i<(a+b))\<longrightarrow>ownB s i=Q") prefer 2 apply blast by (metis (mono_tags, lifting) eq_imp_le less_imp_le_nat linorder_neqE_nat nth_mem surjective_pairing) lemma Q_buffer_overlap_lemma_44: assumes "con_assms s" and "Q_structure s" and "case_1 s" and "pre_A6_inv s" and "length(q s)>0" and "Q_owns_bytes s" and "hW s=H s" shows "\<forall>i j.(i<length(q s) \<and> ownB s j \<noteq> Q \<and> hW s < end(q s!i) \<and> j> hW s)\<longrightarrow>j<fst(q s!i)" using Q_buffer_overlap_lemma_36 [where s=s] assms apply simp apply(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) apply(subgoal_tac "\<forall>a b i.((a,b)\<in>set(q s) \<and> i\<ge>a \<and> i<(a+b))\<longrightarrow>ownB s i=Q") prefer 2 apply blast apply(simp add:pre_A6_inv_def case_1_def) apply clarify apply(subgoal_tac "hW s = c") prefer 2 apply (metis le_neq_implies_less le_refl le_trans) apply(subgoal_tac "\<forall>i.(i>hW s \<and> i<N)\<longrightarrow>ownB s i\<noteq>Q") prefer 2 apply (metis F.distinct(19) less_imp_le_nat) apply(subgoal_tac "\<forall>i.(i<length(q s))\<longrightarrow>fst(q s!i)<hW s") prefer 2 apply (metis (no_types, lifting) F.distinct(19) Q_buffer_overlap_lemma_39 assms(1) assms(3) assms(4) assms(5) assms(6) linorder_neqE_nat ran_indices_lem5) using Q_buffer_overlap_lemma_35 [where s=s] Q_gap_lemmas_2 assms(1) assms(3) assms(6) proof - fix a :: nat and b :: nat and i :: nat and j :: nat and c :: nat and d :: nat and e :: nat assume a1: "hW s = H s" assume a2: "\<forall>a b i. (a, b) \<in> set (q s) \<and> a \<le> i \<and> i < a + b \<longrightarrow> ownB s i = Q" assume a3: "\<forall>i. (H s \<le> i \<and> i < N \<longrightarrow> ownB s i = B) \<and> (i < tW s \<longrightarrow> ownB s i = B)" assume a4: "Data s (numEnqs s) \<le> N - H s" assume a5: "\<forall>i<n. Data s i \<le> N \<and> 0 < Data s i" assume a6: "c \<le> H s" assume a7: "H s \<le> e" assume a8: "e \<le> N" assume a9: "numEnqs s < n" assume a10: "\<forall>i. H s \<le> i \<and> i < e \<longrightarrow> ownB s i = B" assume a11: "e < N \<longrightarrow> 0 < H s \<and> H s < e \<and> a = 0" assume a12: "i < length (q s)" assume a13: "H s < fst (q s ! i) + snd (q s ! i)" assume a14: "hW s = c" assume a15: "\<forall>i<length (q s). fst (q s ! i) < hW s" have f16: "H s = c" using a14 a1 by metis then have f17: "Q = ownB s c" using a15 a14 a13 a12 a2 by (metis nat_less_le nth_mem prod.collapse) then have f18: "N = e" using f16 a11 a10 a8 a6 by (metis (no_types) F.distinct(19) nat_less_le) then have "c = e" using f17 f16 a7 a6 a3 by (metis (no_types) F.distinct(19) nat_less_le) then have "0 = Data s (numEnqs s)" using f18 f16 a4 by simp then show "j < fst (q s ! i)" using a9 a5 nat_less_le by blast qed lemma Q_buffer_overlap_lemma_45: assumes "con_assms s" and "Q_structure s" and "case_1 s" and "pre_A6_inv s" and "length(q s)>0" and "Q_owns_bytes s" and "hW s=H s" shows "\<forall>i j.(i<length(q s) \<and> hW s < end(q s!i))\<longrightarrow>hW s<fst(q s!i)" using Q_buffer_overlap_lemma_36 [where s=s] assms apply simp apply(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) apply(subgoal_tac "\<forall>a b i.((a,b)\<in>set(q s) \<and> i\<ge>a \<and> i<(a+b))\<longrightarrow>ownB s i=Q") prefer 2 apply blast apply(simp add:pre_A6_inv_def case_1_def) apply clarify apply(subgoal_tac "hW s = c") prefer 2 apply (metis le_neq_implies_less le_refl le_trans) apply(subgoal_tac "\<forall>i.(i>hW s \<and> i<N)\<longrightarrow>ownB s i\<noteq>Q") prefer 2 apply (metis F.distinct(19) less_imp_le_nat) apply(subgoal_tac "\<forall>i.(i<length(q s))\<longrightarrow>fst(q s!i)<hW s") prefer 2 apply (metis (no_types, lifting) F.distinct(19) Q_buffer_overlap_lemma_39 assms(1) assms(3) assms(4) assms(5) assms(6) linorder_neqE_nat ran_indices_lem5) by (metis (no_types, lifting) F.distinct(19) Q_buffer_overlap_lemma_25 Q_gap_lemmas_2 assms(1) assms(3) assms(5) assms(6) less_imp_le_nat prod.collapse) lemma Q_buffer_overlap_lemma_46: assumes "con_assms s" and "Q_structure s" and "case_1 s" and "pre_A6_inv s" and "length(q s)>0" and "Q_owns_bytes s" and "hW s=H s" shows "\<forall>i j.(i<length(q s) \<and> hW s < fst(q s!i))\<longrightarrow>hW s + Data s (numEnqs s)<fst(q s!i)" using Q_buffer_overlap_lemma_36 [where s=s] assms apply simp apply(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) apply(subgoal_tac "\<forall>a b i.((a,b)\<in>set(q s) \<and> i\<ge>a \<and> i<(a+b))\<longrightarrow>ownB s i=Q") prefer 2 apply blast apply(simp add:pre_A6_inv_def case_1_def) apply clarify apply(subgoal_tac "hW s = c") prefer 2 apply (metis le_neq_implies_less le_refl le_trans) apply(subgoal_tac "\<forall>i.(i>hW s \<and> i<N)\<longrightarrow>ownB s i\<noteq>Q") prefer 2 apply (metis F.distinct(19) less_imp_le_nat) apply(subgoal_tac "\<forall>i.(i<length(q s))\<longrightarrow>fst(q s!i)<hW s") prefer 2 apply (metis (no_types, lifting) F.distinct(19) Q_buffer_overlap_lemma_39 assms(1) assms(3) assms(4) assms(5) assms(6) linorder_neqE_nat ran_indices_lem5) by (metis less_imp_add_positive not_add_less1) lemma Q_buffer_overlap_lemma_47: assumes "con_assms s" and "Q_structure s" and "case_2 s" and "pre_A6_inv s" and "length(q s)>0" and "Q_owns_bytes s" and "hW s=H s" shows "\<forall>i j.(i<length(q s) \<and> j\<ge>fst(q s!i) \<and> j<end(q s!i))\<longrightarrow>ownB s j = Q" using Q_buffer_overlap_lemma_36 [where s=s] assms apply simp apply(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) apply(subgoal_tac "\<forall>a b i.((a,b)\<in>set(q s) \<and> i\<ge>a \<and> i<(a+b))\<longrightarrow>ownB s i=Q") prefer 2 apply blast by (metis (mono_tags, hide_lams) nth_mem prod.collapse) lemma Q_buffer_overlap_lemma_48: assumes "con_assms s" and "Q_structure s" and "case_2 s" and "pre_A6_inv s" and "length(q s)>0" and "Q_owns_bytes s" and "hW s=H s" shows "\<forall>i j.(i<length(q s) \<and> j<end(q s!i) \<and> ownB s j \<noteq> Q)\<longrightarrow>j<fst(q s!i)" using Q_buffer_overlap_lemma_36 [where s=s] assms apply simp apply(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) apply(subgoal_tac "\<forall>a b i.((a,b)\<in>set(q s) \<and> i\<ge>a \<and> i<(a+b))\<longrightarrow>ownB s i=Q") prefer 2 apply blast by (metis (mono_tags, lifting) eq_imp_le less_imp_le_nat linorder_neqE_nat nth_mem surjective_pairing) lemma Q_buffer_overlap_lemma_49: assumes "con_assms s" and "Q_structure s" and "case_2 s" and "pre_A6_inv s" and "length(q s)>0" and "Q_owns_bytes s" and "hW s=H s" shows "\<forall>i j.(i<length(q s) \<and> j\<ge>fst(q s!i) \<and> ownB s j \<noteq> Q)\<longrightarrow>j\<ge>end(q s!i)" using Q_buffer_overlap_lemma_36 [where s=s] assms apply simp apply(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) apply(subgoal_tac "\<forall>a b i.((a,b)\<in>set(q s) \<and> i\<ge>a \<and> i<(a+b))\<longrightarrow>ownB s i=Q") prefer 2 apply blast by (metis (mono_tags, lifting) eq_imp_le less_imp_le_nat linorder_neqE_nat nth_mem surjective_pairing) lemma Q_buffer_overlap_lemma_50: assumes "con_assms s" and "Q_structure s" and "case_2 s" and "pre_A6_inv s" and "length(q s)>0" and "Q_owns_bytes s" and "hW s=H s" shows "\<forall>i.(i\<ge> hW s)\<longrightarrow>ownB s i\<noteq>Q" using Q_buffer_overlap_lemma_36 [where s=s] assms apply simp apply(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) by (smt (verit) F.distinct(19) Q_buffer_overlap_lemma_39 Q_owns_bytes_def assms(1) assms(5) assms(6) pre_A6_inv_def) lemma Q_buffer_overlap_lemma_51: assumes "con_assms s" and "Q_structure s" and "case_2 s" and "pre_A6_inv s" and "length(q s)>0" and "Q_owns_bytes s" and "hW s=H s" shows "\<forall>a b.((a,b)\<in>set(q s))\<longrightarrow>(\<forall>j.(a\<le>j \<and> j<a+b)\<longrightarrow>ownB s j = Q)" using Q_buffer_overlap_lemma_36 [where s=s] assms apply simp apply(simp add:Q_owns_bytes_def Q_indices_def ran_indices_def) using Q_overlap_lemma_4 [where s=s] using assms(1) by blast lemma Q_buffer_overlap_lemma_52: assumes "con_assms s" and "Q_structure s" and "case_2 s" and "pre_A6_inv s" and "length(q s)>0" and "Q_owns_bytes s" and "hW s=H s" shows "\<forall>a b j.((a,b)\<in>set(q s) \<and> (a\<le>j \<and> j<a+b) )\<longrightarrow>ownB s j = Q" using Q_buffer_overlap_lemma_51 [where s=s] assms by blast lemma Q_buffer_overlap_lemma_53: assumes "con_assms s" and "Q_structure s" and "case_2 s" and "pre_A6_inv s" and "length(q s)>0" and "Q_owns_bytes s" and "hW s=H s" shows "\<forall>a b.((a,b)\<in>set(q s) \<and> b>0)\<longrightarrow>ownB s a = Q" using Q_buffer_overlap_lemma_52 [where s=s] assms apply simp by (meson le_refl less_add_same_cancel1) lemma Q_buffer_overlap_lemma_54: assumes "con_assms s" and "Q_structure s" and "case_2 s" and "pre_A6_inv s" and "length(q s)>0" and "Q_owns_bytes s" and "hW s=H s" shows "\<forall>a b.((a,b)\<in>set(q s))\<longrightarrow>b>0" using Q_buffer_overlap_lemma_52 [where s=s] assms apply simp by(simp add:Q_lemmas Q_basic_lemmas) lemma Q_buffer_overlap_lemma_55: assumes "con_assms s" and "Q_structure s" and "case_2 s" and "pre_A6_inv s" and "length(q s)>0" and "Q_owns_bytes s" and "hW s=H s" shows "\<forall>a b.((a,b)\<in>set(q s))\<longrightarrow>ownB s a = Q" using Q_buffer_overlap_lemma_52 [where s=s] Q_buffer_overlap_lemma_54 [where s=s] assms by (meson le_refl less_add_same_cancel1) lemma Q_buffer_overlap_lemma_56: assumes "con_assms s" and "Q_structure s" and "case_2 s" and "pre_A6_inv s" and "length(q s)>0" and "Q_owns_bytes s" and "hW s=H s" shows "\<forall>a b j.((a,b)\<in>set(q s) \<and> ownB s j\<noteq> Q )\<longrightarrow>a\<noteq>j" using Q_buffer_overlap_lemma_52 [where s=s] Q_buffer_overlap_lemma_54 [where s=s] assms by (meson le_refl less_add_same_cancel1) lemma Q_buffer_overlap_lemma_57: assumes "con_assms s" and "Q_structure s" and "case_2 s" and "pre_A6_inv s" and "length(q s)>0" and "Q_owns_bytes s" and "hW s=H s" shows "\<forall>a b j.((a,b)\<in>set(q s) \<and> ownB s j\<noteq> Q \<and> j\<ge>hW s \<and> j<hW s + Data s (numEnqs s))\<longrightarrow>a\<noteq>j" using Q_buffer_overlap_lemma_52 [where s=s] Q_buffer_overlap_lemma_54 [where s=s] assms by (meson le_refl less_add_same_cancel1) lemma Q_buffer_overlap_lemma_58: assumes "con_assms s" and "Q_structure s" and "case_2 s" and "pre_A6_inv s" and "length(q s)>0" and "Q_owns_bytes s" and "hW s=H s" shows "\<forall>a b j.((a,b)\<in>set(q s) \<and> ownB s j\<noteq> Q \<and> j\<ge>hW s \<and> j<hW s + Data s (numEnqs s))\<longrightarrow>a>j \<or> a<j" using Q_buffer_overlap_lemma_57 [where s=s] Q_buffer_overlap_lemma_54 [where s=s] assms using less_linear by blast lemma Q_buffer_overlap_lemma_59: assumes "con_assms s" and "Q_structure s" and "case_2 s" and "pre_A6_inv s" and "length(q s)>0" and "Q_owns_bytes s" and "hW s=H s" shows "\<forall>a b j.((a,b)\<in>set(q s) \<and> ownB s j\<noteq> Q \<and> j\<ge>hW s \<and> j<hW s + Data s (numEnqs s))\<longrightarrow>a>j \<or> a<j" using Q_buffer_overlap_lemma_57 [where s=s] Q_buffer_overlap_lemma_54 [where s=s] assms using less_linear by blast *) (*local W case split*) (* lemma A6_case2_hW_fst: assumes "case_2 s" and "tW s<hW s" and "(\<forall>i.((i\<ge>hW s \<and> i<N) \<or> i<tW s)\<longrightarrow>ownB s i=B)" shows "tW s=0" using assms apply(simp add:case_2_def) apply(clarify) apply(subgoal_tac "\<forall>i.(i>a\<and>i<N)\<longrightarrow>ownB s i=B") prefer 2 sledgehammer *) (* lemma inv_holds_for_W: assumes "con_assms s" and "pcw = pcW s" and "pre_W pcw s" and "inv s" and "cW_step pcw s s'" shows "inv s'" using assms apply(simp add:inv_def) apply(intro conjI impI) apply(simp add:Q_lemmas Q_basic_lemmas cW_step_def) apply(case_tac "pcW s", simp_all) apply (metis (no_types, hide_lams) F.distinct(3) PCW.simps(185) pre_A3_inv_def pre_W_def) apply(simp add:pre_W_def pre_A4_inv_def) apply (simp add: le_add_diff_inverse2 less_diff_conv) apply(simp add:pre_W_def pre_A6_inv_def) apply (metis Nat.le_diff_conv2 add.commute) apply(simp add:pre_W_def pre_A7_inv_def) apply(case_tac "numEnqs s<n", simp_all) apply(case_tac "tW s \<noteq> T s", simp_all) apply(simp add:pre_W_def pre_A7_inv_def) apply(simp add:Q_lemmas Q_basic_lemmas cW_step_def) apply(case_tac "pcW s", simp_all) apply(case_tac "numEnqs s<n", simp_all) apply(case_tac "tW s \<noteq> T s", simp_all) apply(simp add:pre_W_def pre_A7_inv_def) apply(simp add:Q_lemmas Q_basic_lemmas cW_step_def) apply(case_tac "pcW s", simp_all) apply(case_tac "numEnqs s<n", simp_all) apply(case_tac "tW s \<noteq> T s", simp_all) apply(simp add:pre_W_def pre_A7_inv_def) apply(simp add:Q_lemmas Q_basic_lemmas cW_step_def) apply(case_tac "pcW s", simp_all) apply(case_tac "numEnqs s<n", simp_all) apply(case_tac "tW s \<noteq> T s", simp_all) apply(simp add:pre_W_def pre_A7_inv_def) apply(simp add:Q_lemmas Q_basic_lemmas cW_step_def) (*11*) apply(case_tac "pcW s", simp_all) apply(case_tac "tW s = hW s \<and> Data s (numEnqs s) \<le> N", simp_all) apply(case_tac "ownT s = Q", simp_all) apply(case_tac "hW s < tW s \<and> Data s (numEnqs s) < tW s - hW s", simp_all) apply(case_tac "tW s < hW s", simp_all) apply (metis pre_A4_inv_def) apply(case_tac "Data s (numEnqs s) \<le> N - hW s", simp_all) apply(case_tac "Data s (numEnqs s) < tW s", simp_all) apply (simp add: pre_A6_inv_def) apply (simp add: pre_A7_inv_def) apply (simp add: pre_A8_inv_def) apply(case_tac "N < Data s (numEnqs s)", simp_all) apply(case_tac "ownT s = W", simp_all) apply(case_tac "numEnqs s < n", simp_all) apply(case_tac " tW s \<noteq> T s", simp_all) (*10*) apply(simp add:pre_W_def pre_A7_inv_def) apply(simp add:Q_lemmas Q_basic_lemmas cW_step_def) apply(case_tac "pcW s", simp_all) apply(case_tac "numEnqs s < n", simp_all) apply(case_tac " tW s \<noteq> T s", simp_all) apply(simp add:pre_W_def pre_A7_inv_def) (*9*) apply(simp add:Q_lemmas Q_basic_lemmas cW_step_def) apply(case_tac "pcW s", simp_all) apply(case_tac "ownT s = W", simp_all) using Suc_diff_le apply presburger using Suc_diff_le apply presburger apply(case_tac "numEnqs s < n", simp_all) apply(case_tac " tW s \<noteq> T s", simp_all) (*8*) apply(simp add:pre_W_def pre_A7_inv_def) apply(simp add:cW_step_def) apply(case_tac "pcW s", simp_all) apply(case_tac "numEnqs s < n", simp_all) apply(case_tac " tW s \<noteq> T s", simp_all) (*7*) apply(simp add:pre_W_def pre_A7_inv_def) apply(simp add:cW_step_def) apply(case_tac "pcW s", simp_all) apply(case_tac "numEnqs s < n", simp_all) apply(case_tac " tW s \<noteq> T s", simp_all) (*6*) apply(simp add:pre_W_def pre_write_inv_def) apply(simp add:cW_step_def) apply(case_tac "pcW s", simp_all) apply(case_tac "numEnqs s < n", simp_all) apply(case_tac " tW s \<noteq> T s", simp_all) (*5*) apply(simp add:pre_W_def cW_step_def) apply(case_tac "pcW s", simp_all) apply(case_tac "numEnqs s < n", simp_all) apply(case_tac "tW s \<noteq> T s", simp_all) apply(simp add:pre_write_inv_def) (*4*) apply(simp add:pre_W_def pre_write_inv_def) apply(simp add:cW_step_def) apply(case_tac "pcW s", simp_all) apply(case_tac "ownT s = W", simp_all) apply(simp add:pre_enqueue_inv_def) apply(simp add:pre_enqueue_inv_def) apply(case_tac "numEnqs s < n", simp_all) apply(case_tac " tW s \<noteq> T s", simp_all) (*3*) apply(simp add:pre_W_def pre_write_inv_def) apply(simp add:cW_step_def) apply(case_tac "pcW s", simp_all) apply(case_tac "numEnqs s < n", simp_all) apply(case_tac " tW s \<noteq> T s", simp_all) (*2*) defer apply(simp add:cW_step_def) apply(simp add:pre_W_def) apply(case_tac "pcW s", simp_all) apply(case_tac "numEnqs s < n", simp_all) apply(case_tac "tW s \<noteq> T s", simp_all) using pre_write_inv_def apply auto[1] (*1*) apply(simp add:cW_step_def) apply(case_tac "pcW s", simp_all) apply(simp add:pre_W_def pre_A1_inv_def) apply(subgoal_tac "Q_structure s=Q_structure s'") apply meson apply(simp add:Q_lemmas Q_basic_lemmas) apply(simp add:pre_W_def pre_A2_inv_def) apply(case_tac "tW s = hW s", simp_all) apply(subgoal_tac "Q_structure s=Q_structure s'") apply meson apply(simp add:Q_lemmas Q_basic_lemmas) apply(case_tac "hW s < tW s \<and> Data s (numEnqs s) < tW s - hW s", simp_all) apply(simp add:Q_lemmas Q_basic_lemmas) apply(case_tac " tW s < hW s", simp_all) apply(simp add:Q_lemmas Q_basic_lemmas) apply(simp add:Q_lemmas Q_basic_lemmas) apply(simp add:pre_W_def pre_A3_inv_def) apply(simp add:Q_lemmas Q_basic_lemmas) apply (metis F.distinct(3)) apply(simp add:pre_W_def pre_A4_inv_def) apply(simp add:Q_lemmas Q_basic_lemmas) apply (metis (no_types, lifting) F.distinct(11) Suc_lessD add.commute less_diff_conv less_trans_Suc) apply(case_tac "Data s (numEnqs s) \<le> N - hW s", simp_all) apply(simp add:pre_W_def pre_A5_inv_def) apply(simp add:Q_lemmas Q_basic_lemmas) apply(simp add:Q_lemmas Q_basic_lemmas) apply(simp add:pre_W_def pre_A6_inv_def) apply(simp add:Q_lemmas Q_basic_lemmas) apply (metis F.distinct(11) le_trans less_eq_Suc_le) apply(simp add:pre_W_def pre_A7_inv_def) apply(simp add:Q_lemmas Q_basic_lemmas) apply (metis (no_types, hide_lams) F.distinct(11) less_Suc_eq less_trans_Suc not_less_eq) apply(case_tac "N < Data s (numEnqs s)", simp_all) apply(simp add:pre_W_def pre_A8_inv_def) apply (metis leD) apply(simp add:pre_W_def pre_A8_inv_def) apply(simp add:Q_lemmas Q_basic_lemmas) defer apply(case_tac "numEnqs s < n", simp_all) apply(simp add:pre_W_def pre_acquire_inv_def) apply(simp add:Q_lemmas Q_basic_lemmas) apply(simp add:pre_W_def pre_acquire_inv_def) apply(simp add:Q_lemmas Q_basic_lemmas) apply(case_tac "tW s \<noteq> T s", simp_all) apply(simp add:pre_W_def pre_OOM_inv_def) apply(simp add:Q_lemmas Q_basic_lemmas) (*this case is concerning pre_write *) apply(simp add:pre_W_def pre_write_inv_def) apply(subgoal_tac "con_assms s \<and> pcw = Write \<and> pre_write_inv s \<and> Q_structure s \<and> numEnqs s - numDeqs s = length (q s) \<and> (\<forall>i. (i < numReads s \<longrightarrow> ownD s i = R) \<and> (numReads s \<le> i \<and> i < numWrites s \<longrightarrow> ownD s i = B) \<and> (numWrites s \<le> i \<and> i < n \<longrightarrow> ownD s i = W)) \<and> numReads s \<le> numWrites s \<and> numReads s \<le> n \<and> numWrites s \<le> n \<and> B_write s s' \<and> tempW_structure s") using write_doesnt_change_Q_struct apply (metis (no_types, lifting)) apply (intro conjI impI) using assms(1) apply blast using assms(1) apply blast apply (metis (mono_tags, hide_lams) PCW.simps(195) assms(3) pre_W_def) apply meson apply fastforce apply presburger using less_imp_le_nat apply presburger apply meson apply simp prefer 2 apply meson apply(simp add:B_write_def) apply presburger (*last subgoal!!! apply (insert data_index_reduce2[where s = s]) *) apply(subgoal_tac "Q_structure s \<and> Q_enqueue s s' \<and> length(q s) = numEnqs s-numDeqs s \<and> pre_enqueue_inv s \<and> numWrites s\<ge>numReads s \<and> numEnqs s\<ge>numDeqs s \<and> ownD s(numEnqs s) =B") prefer 2 apply(intro conjI impI) apply blast apply simp apply presburger apply (simp add: pre_W_def) apply blast apply blast apply (simp add: pre_W_def pre_enqueue_inv_def) apply(intro conjI impI) apply(case_tac "ownT s = W ", simp_all) apply(case_tac[!] "q s=[]", simp_all ) defer defer defer (*4*) apply(subgoal_tac "q s\<noteq>[] \<and> Q_structure s \<and> Q_enqueue s s' \<and> numDeqs s<numEnqs s \<and> length(q s) = numEnqs s-numDeqs s \<and> pre_enqueue_inv s \<and> numWrites s\<ge>numReads s \<and> ownD s(numEnqs s) =B \<and> ownT s \<noteq>W") using enqueue_preserves_Q_n_n apply presburger apply(intro conjI impI) apply blast apply blast apply simp apply (metis length_greater_0_conv zero_less_diff) apply linarith apply blast apply blast apply blast apply blast defer (*3*) apply(subgoal_tac "q s\<noteq>[] \<and> Q_structure s \<and> Q_enqueue s s' \<and> numDeqs s<numEnqs s \<and> length(q s) = numEnqs s-numDeqs s \<and> pre_enqueue_inv s \<and> numWrites s\<ge>numReads s \<and> ownD s(numEnqs s) =B \<and> ownT s =W") prefer 2 apply(intro conjI impI) apply blast apply blast apply simp apply (simp add: pre_enqueue_inv_def) apply linarith apply blast apply linarith apply linarith apply blast using enqueue_preserves_Q_n_o proof - assume a1: "s' = s \<lparr>ownT := Q, numEnqs := Suc (numEnqs s), ownB := \<lambda>i. if ownB s i = W then Q else ownB ((if ownT s = W then ownT_update (\<lambda>_. Q) else (\<lambda>s. s\<lparr>ownT := ownT s\<rparr>)) s \<lparr>numEnqs := Suc (numEnqs s)\<rparr>) i, pcW := idleW, q := q s @ [(offset s, Data s (numEnqs s))]\<rparr>" assume "Q_structure s \<and> length (q s) = numEnqs s - numDeqs s \<and> pre_enqueue_inv s \<and> numReads s \<le> numWrites s \<and> numDeqs s \<le> numEnqs s \<and> ownD s (numEnqs s) = B" assume a2: "ownT s = W" assume "q s \<noteq> []" assume "q s \<noteq> [] \<and> Q_structure s \<and> Q_enqueue s s' \<and> numDeqs s < numEnqs s \<and> length (q s) = numEnqs s - numDeqs s \<and> pre_enqueue_inv s \<and> numReads s \<le> numWrites s \<and> ownD s (numEnqs s) = B \<and> ownT s = W" then have "Q_structure (s\<lparr>ownT := Q, numEnqs := Suc (numEnqs s), ownB := \<lambda>n. if ownB s n = W then Q else ownB ((if ownT s = W then ownT_update (\<lambda>f. Q) else (\<lambda>r. r\<lparr>ownT := ownT r\<rparr>)) s \<lparr>numEnqs := Suc (numEnqs s)\<rparr>) n, pcW := idleW, q := q s @ [(offset s, Data s (numEnqs s))]\<rparr>)" using a1 enqueue_preserves_Q_n_o by blast then show "Q_structure (s\<lparr>ownT := Q, numEnqs := Suc (numEnqs s), ownB := \<lambda>n. if ownB s n = W then Q else ownB (s\<lparr>ownT := Q, numEnqs := Suc (numEnqs s)\<rparr>) n, pcW := idleW, q := q s @ [(offset s, Data s (numEnqs s))]\<rparr>)" using a2 by presburger next show "0 < N \<and> 0 < n \<and> n < N \<and> numEnqs s \<le> n \<and> (\<forall>i<n. Data s i \<le> N \<and> 0 < Data s i) \<Longrightarrow> pcw = Enqueue \<Longrightarrow> pre_W Enqueue s \<Longrightarrow> H s \<le> N \<and> T s \<le> N \<and> hW s \<le> N \<and> tW s \<le> N \<and> (H s = 0 \<longrightarrow> T s = 0) \<and> (\<forall>i. (i < numReads s \<longrightarrow> ownD s i = R) \<and> (numReads s \<le> i \<and> i < numWrites s \<longrightarrow> ownD s i = B) \<and> (numWrites s \<le> i \<and> i < n \<longrightarrow> ownD s i = W)) \<and> numReads s \<le> n \<and> numWrites s \<le> n \<and> (\<forall>i\<le>N. \<forall>j\<le>N. data_index s (i, j) < n) \<Longrightarrow> s' = s \<lparr>numEnqs := Suc (numEnqs s), ownB := \<lambda>i. if ownB s i = W then Q else ownB (s\<lparr>numEnqs := Suc (numEnqs s)\<rparr>) i, pcW := idleW, q := [(offset s, Data s (numEnqs s))]\<rparr> \<Longrightarrow> pcW s = Enqueue \<Longrightarrow> Q_structure s \<and> s\<lparr>numEnqs := Suc (numEnqs s), ownB := \<lambda>i. if ownB s i = W then Q else ownB ((if ownT s = W then ownT_update (\<lambda>_. Q) else (\<lambda>s. s\<lparr>ownT := ownT s\<rparr>)) s \<lparr>numEnqs := Suc (numEnqs s)\<rparr>) i, pcW := idleW, q := [(offset s, Data s (numEnqs s))]\<rparr> = s\<lparr>numEnqs := Suc (numEnqs s), ownB := \<lambda>i. if ownB s i = W then Q else ownB (s\<lparr>numEnqs := Suc (numEnqs s)\<rparr>) i, pcW := idleW, q := [(offset s, Data s (numEnqs s))]\<rparr> \<and> numEnqs s \<le> numDeqs s \<and> pre_enqueue_inv s \<and> numReads s \<le> numWrites s \<and> numDeqs s \<le> numEnqs s \<and> ownD s (numEnqs s) = B \<Longrightarrow> ownT s \<noteq> W \<Longrightarrow> q s = [] \<Longrightarrow> Q_structure (s\<lparr>numEnqs := Suc (numEnqs s), ownB := \<lambda>i. if ownB s i = W then Q else ownB (s\<lparr>ownT := ownT s, numEnqs := Suc (numEnqs s)\<rparr>) i, pcW := idleW, q := [(offset s, Data s (numEnqs s))]\<rparr>)" (*2*) apply(subgoal_tac "q s=[] \<and> Q_structure s \<and> Q_enqueue s s' \<and> numEnqs s = numDeqs s \<and> length(q s) = numEnqs s-numDeqs s \<and> pre_enqueue_inv s \<and> numWrites s\<ge>numReads s \<and> ownD s(numEnqs s) =B \<and> ownT s \<noteq>W") prefer 2 apply(intro conjI impI) apply blast apply blast apply simp apply linarith apply (metis diff_is_0_eq' list.size(3)) apply linarith apply blast apply blast apply blast using enqueue_preserves_Q_e_n proof - assume a1: "s' = s \<lparr>numEnqs := Suc (numEnqs s), ownB := \<lambda>i. if ownB s i = W then Q else ownB (s\<lparr>numEnqs := Suc (numEnqs s)\<rparr>) i, pcW := idleW, q := [(offset s, Data s (numEnqs s))]\<rparr>" assume a2: "Q_structure s \<and> s\<lparr>numEnqs := Suc (numEnqs s), ownB := \<lambda>i. if ownB s i = W then Q else ownB ((if ownT s = W then ownT_update (\<lambda>_. Q) else (\<lambda>s. s\<lparr>ownT := ownT s\<rparr>)) s \<lparr>numEnqs := Suc (numEnqs s)\<rparr>) i, pcW := idleW, q := [(offset s, Data s (numEnqs s))]\<rparr> = s\<lparr>numEnqs := Suc (numEnqs s), ownB := \<lambda>i. if ownB s i = W then Q else ownB (s\<lparr>numEnqs := Suc (numEnqs s)\<rparr>) i, pcW := idleW, q := [(offset s, Data s (numEnqs s))]\<rparr> \<and> numEnqs s \<le> numDeqs s \<and> pre_enqueue_inv s \<and> numReads s \<le> numWrites s \<and> numDeqs s \<le> numEnqs s \<and> ownD s (numEnqs s) = B" assume a3: "ownT s \<noteq> W" assume "q s = []" assume a4: "q s = [] \<and> Q_structure s \<and> Q_enqueue s s' \<and> numEnqs s = numDeqs s \<and> length (q s) = numEnqs s - numDeqs s \<and> pre_enqueue_inv s \<and> numReads s \<le> numWrites s \<and> ownD s (numEnqs s) = B \<and> ownT s \<noteq> W" then have "\<forall>r. numDeqs s - numDeqs s \<noteq> length (q s) \<or> B \<noteq> ownD s (numEnqs s) \<or> Q_structure r \<or> \<not> Q_enqueue s r \<or> [] \<noteq> q s" by (metis (no_types) enqueue_preserves_Q_e_n) then have "Q_structure (s\<lparr>numEnqs := Suc (numEnqs s), ownB := \<lambda>n. if ownB s n = W then Q else ownB ((if ownT s = W then ownT_update (\<lambda>f. Q) else (\<lambda>r. r\<lparr>ownT := ownT r\<rparr>)) s \<lparr>numEnqs := Suc (numEnqs s)\<rparr>) n, pcW := idleW, q := [(offset s, Data s (numEnqs s))]\<rparr>)" using a4 a2 a1 by metis then show ?thesis using a3 by presburger next qed (*1*) show "0 < N \<and> 0 < n \<and> n < N \<and> numEnqs s \<le> n \<and> (\<forall>i<n. Data s i \<le> N \<and> 0 < Data s i) \<Longrightarrow> pcw = Enqueue \<Longrightarrow> pre_W Enqueue s \<Longrightarrow> H s \<le> N \<and> T s \<le> N \<and> hW s \<le> N \<and> tW s \<le> N \<and> (H s = 0 \<longrightarrow> T s = 0) \<and> (\<forall>i. (i < numReads s \<longrightarrow> ownD s i = R) \<and> (numReads s \<le> i \<and> i < numWrites s \<longrightarrow> ownD s i = B) \<and> (numWrites s \<le> i \<and> i < n \<longrightarrow> ownD s i = W)) \<and> numReads s \<le> n \<and> numWrites s \<le> n \<and> (\<forall>i\<le>N. \<forall>j\<le>N. data_index s (i, j) < n) \<Longrightarrow> s' = s \<lparr>ownT := Q, numEnqs := Suc (numEnqs s), ownB := \<lambda>i. if ownB s i = W then Q else ownB ((if ownT s = W then ownT_update (\<lambda>_. Q) else (\<lambda>s. s\<lparr>ownT := ownT s\<rparr>)) s \<lparr>numEnqs := Suc (numEnqs s)\<rparr>) i, pcW := idleW, q := [(offset s, Data s (numEnqs s))]\<rparr> \<Longrightarrow> pcW s = Enqueue \<Longrightarrow> Q_structure s \<and> numEnqs s \<le> numDeqs s \<and> pre_enqueue_inv s \<and> numReads s \<le> numWrites s \<and> numDeqs s \<le> numEnqs s \<and> ownD s (numEnqs s) = B \<Longrightarrow> ownT s = W \<Longrightarrow> q s = [] \<Longrightarrow> Q_structure (s\<lparr>ownT := Q, numEnqs := Suc (numEnqs s), ownB := \<lambda>i. if ownB s i = W then Q else ownB (s\<lparr>ownT := Q, numEnqs := Suc (numEnqs s)\<rparr>) i, pcW := idleW, q := [(offset s, Data s (numEnqs s))]\<rparr>)" apply(subgoal_tac "q s=[] \<and> Q_structure s \<and> Q_enqueue s s' \<and> numDeqs s=numEnqs s \<and> length(q s) = numEnqs s-numDeqs s \<and> pre_enqueue_inv s \<and> ownD s(numEnqs s) =B \<and> ownT s =W") prefer 2 apply(intro conjI impI) apply blast apply blast apply simp apply linarith apply (metis diff_is_0_eq' list.size(3)) apply linarith apply blast apply blast using enqueue_preserves_Q_e_o proof - assume a1: "s' = s \<lparr>ownT := Q, numEnqs := Suc (numEnqs s), ownB := \<lambda>i. if ownB s i = W then Q else ownB ((if ownT s = W then ownT_update (\<lambda>_. Q) else (\<lambda>s. s\<lparr>ownT := ownT s\<rparr>)) s \<lparr>numEnqs := Suc (numEnqs s)\<rparr>) i, pcW := idleW, q := [(offset s, Data s (numEnqs s))]\<rparr>" assume a2: "Q_structure s \<and> numEnqs s \<le> numDeqs s \<and> pre_enqueue_inv s \<and> numReads s \<le> numWrites s \<and> numDeqs s \<le> numEnqs s \<and> ownD s (numEnqs s) = B" assume a3: "ownT s = W" assume "q s = []" assume "q s = [] \<and> Q_structure s \<and> Q_enqueue s s' \<and> numDeqs s = numEnqs s \<and> length (q s) = numEnqs s - numDeqs s \<and> pre_enqueue_inv s \<and> ownD s (numEnqs s) = B \<and> ownT s = W" then have "Q_structure (s\<lparr>ownT := Q, numEnqs := Suc (numEnqs s), ownB := \<lambda>n. if ownB s n = W then Q else ownB ((if ownT s = W then ownT_update (\<lambda>f. Q) else (\<lambda>r. r\<lparr>ownT := ownT r\<rparr>)) s \<lparr>numEnqs := Suc (numEnqs s)\<rparr>) n, pcW := idleW, q := [(offset s, Data s (numEnqs s))]\<rparr>)" using a2 a1 by (meson enqueue_preserves_Q_e_o) then show ?thesis using a3 by presburger qed qed *) (* lemma local_pre_R: assumes "con_assms s" and "pcr = pcR s" and "pre_R pcr s" and "inv s" and "cR_step pcr s s'" shows "pre_R (pcR s') s'" proof (cases "pcR s") case Release then show ?thesis apply (simp add: pre_R_def) proof (cases "pcR s'") show "pcR s = Release \<Longrightarrow> pcR s' = Release \<Longrightarrow> case pcR s' of Release \<Rightarrow> pre_Release_inv s' | idleR \<Rightarrow> pre_dequeue_inv s' | Read \<Rightarrow> pre_Read_inv s'" using assms by(simp add:cR_step_def pre_Read_inv_def pre_Release_inv_def pre_dequeue_inv_def) next show "pcR s = Release \<Longrightarrow> pcR s' = Read \<Longrightarrow> case pcR s' of Release \<Rightarrow> pre_Release_inv s' | idleR \<Rightarrow> pre_dequeue_inv s' | Read \<Rightarrow> pre_Read_inv s'" using assms by(simp add:cR_step_def pre_Read_inv_def pre_Release_inv_def pre_dequeue_inv_def) next show "pcR s = Release \<Longrightarrow> pcR s' = idleR \<Longrightarrow> case pcR s' of Release \<Rightarrow> pre_Release_inv s' | idleR \<Rightarrow> pre_dequeue_inv s' | Read \<Rightarrow> pre_Read_inv s'" using assms apply(simp add:cR_step_def pre_Read_inv_def pre_Release_inv_def pre_dequeue_inv_def) apply (case_tac "tR s \<noteq> fst (tempR s)", simp_all) apply (case_tac[!] "ownT s = R", simp_all) apply (intro conjI impI) apply(simp add:cR_step_def pre_Read_inv_def pre_Release_inv_def pre_dequeue_inv_def RingBuffer_BD.inv_def pre_R_def) apply(simp add:cR_step_def pre_Read_inv_def pre_Release_inv_def pre_dequeue_inv_def RingBuffer_BD.inv_def pre_R_def) apply(simp add:cR_step_def pre_Read_inv_def pre_Release_inv_def pre_dequeue_inv_def RingBuffer_BD.inv_def pre_R_def) apply(simp add:Q_lemmas Q_basic_lemmas) apply(subgoal_tac "(\<forall>a b j. (a, b) \<in> set (q s) \<and> j < N \<and> tR s \<le> j \<longrightarrow> a + b < j)") prefer 2 apply presburger apply(subgoal_tac "end(tempR s)<T s") prefer 2 apply (metis end_simp) apply(simp add:tempR_lemmas tempR_basic_lemmas) apply (metis add_lessD1 hd_conv_nth length_pos_if_in_set less_irrefl_nat less_nat_zero_code linorder_neqE_nat tempR_describes_T_def) apply(simp add:Q_describes_T_def) apply(simp add:cR_step_def pre_Read_inv_def pre_Release_inv_def pre_dequeue_inv_def RingBuffer_BD.inv_def pre_R_def) apply(simp add:tempR_lemmas tempR_basic_lemmas) apply (metis bot_nat_0.not_eq_extremum hd_conv_nth length_greater_0_conv not_add_less1 tempR_describes_T_def) apply(simp add:R_owns_no_bytes_def) apply(simp add:Tail_and_ownB_idleR_def) apply(simp add:cR_step_def pre_Read_inv_def pre_Release_inv_def pre_dequeue_inv_def RingBuffer_BD.inv_def pre_R_def) apply(simp add:Q_lemmas Q_basic_lemmas) apply(simp add:tempR_lemmas tempR_basic_lemmas) apply safe[1] apply (metis add_less_same_cancel1 less_nat_zero_code tempR_describes_T_def) apply (metis end_simp tempR_describes_ownB_def) apply (metis not_add_less1 tempR_describes_T_def) apply (metis not_add_less1 tempR_describes_T_def) apply (metis end_simp tempR_describes_ownB_def) apply (metis not_add_less1 tempR_describes_T_def) apply clarsimp apply(simp add:Tail_and_ownB_not_idleR_1_def Tail_and_ownB_not_idleR_2_def) apply(simp add:tempR_describes_T_def T_is_outside_Q_def tempR_describes_ownB_def) apply clarify apply(subgoal_tac "fst(q s!0) = end(tempR s)") prefer 2 apply (metis end_simp hd_conv_nth plus_nat.add_0) apply(subgoal_tac "\<forall>i. i < length (q s) \<and> 0 < i \<longrightarrow> fst (q s ! (i - Suc 0)) + snd (q s ! (i - Suc 0)) = fst (q s ! i)") prefer 2 apply (metis (no_types, lifting) less_irrefl_nat) apply(subgoal_tac "fst(q s!(length(q s)-1)) = fst(last(q s))") prefer 2 apply (metis last_conv_nth) apply (subgoal_tac "fst (last (q s)) + snd (last (q s)) > fst (hd (q s))") apply (meson less_or_eq_imp_le) apply (metis (no_types, lifting) diff_less le_add1 le_trans length_greater_0_conv less_one) apply (metis end_simp tempR_describes_ownB_def) apply(simp add:tempR_describes_ownB_def tempR_describes_T_def T_is_outside_Q_def Tail_and_ownB_not_idleR_1_def Tail_and_ownB_not_idleR_2_def) apply clarify apply(subgoal_tac "\<forall>i. i < length (q s) \<and> 0 < i \<longrightarrow> fst (q s ! (i - Suc 0)) + snd (q s ! (i - Suc 0)) = fst (q s ! i)") prefer 2 apply (metis (no_types, lifting) gr_implies_not0) defer apply (metis (mono_tags, hide_lams) add_less_same_cancel1 hd_conv_nth length_0_conv less_nat_zero_code linorder_neqE_nat tempR_describes_T_def) apply (metis end_simp tempR_describes_ownB_def) apply (metis diff_less_Suc hd_conv_nth length_0_conv less_diff_conv linorder_neqE_nat not_less_eq tempR_describes_T_def zero_less_diff) apply(simp add:inv_def pre_R_def pre_Release_inv_def) prefer 2 apply(simp add:inv_def pre_R_def pre_Release_inv_def) apply(intro conjI impI) apply(simp add:inv_def pre_R_def pre_Release_inv_def) apply(simp add:inv_def pre_R_def pre_Release_inv_def) apply(subgoal_tac "con_assms s \<and> q s\<noteq>[] \<and> fst(hd(q s)) =0 \<and> fst(tempR s) \<noteq>0 \<and> pre_Release_inv s \<and> snd(tempR s) = Data s (numReads s -1) \<and> data_index s (tempR s) = numReads s -1 \<and> ownT s = R \<and> numEnqs s\<ge>numDeqs s \<and> ownD s (numReads s -1) = R \<and> numDeqs s\<le>n \<and> numDeqs s\<ge>1 \<and> numDeqs s = numReads s \<and> pcR s=Release \<and> tR s=T s \<and> tempR_structure s \<and> Q_structure s \<and> B_release s s'") apply(unfold pre_Release_inv_def)[1] using Release_wrap_1 inv_def apply (smt (z3) add_diff_inverse_nat add_lessD1 le_add_diff_inverse not_add_less1 struct_of_wrap_1) apply(intro conjI impI) using assms(1) apply blast using assms(1) apply blast apply(simp add:inv_def pre_R_def pre_Release_inv_def tempR_lemmas) apply (metis end_simp tempR_basic_struct_def tempR_gap_structure_def) apply(simp add:inv_def pre_R_def pre_Release_inv_def tempR_lemmas tempR_describes_T_def T_is_outside_Q_def) apply (metis end_simp head_q0 length_0_conv less_nat_zero_code linorder_neqE_nat tempR_basic_struct_def tempR_gap_structure_def tempR_offsets_differ_def) apply (metis PCR.simps(7) pre_R_def) apply(simp add:inv_def pre_R_def pre_Release_inv_def tempR_lemmas tempR_describes_T_def T_is_outside_Q_def) apply(simp add:inv_def pre_R_def pre_Release_inv_def tempR_lemmas tempR_describes_T_def T_is_outside_Q_def) apply(simp add:inv_def pre_R_def pre_Release_inv_def tempR_lemmas tempR_describes_T_def T_is_outside_Q_def) apply(simp add:inv_def pre_R_def pre_Release_inv_def tempR_lemmas tempR_describes_T_def T_is_outside_Q_def) apply(simp add:inv_def pre_R_def pre_Release_inv_def tempR_lemmas tempR_describes_T_def T_is_outside_Q_def) apply(simp add:inv_def pre_R_def pre_Release_inv_def tempR_lemmas tempR_describes_T_def T_is_outside_Q_def) apply(simp add:inv_def pre_R_def pre_Release_inv_def tempR_lemmas tempR_describes_T_def T_is_outside_Q_def) apply(simp add:inv_def pre_R_def pre_Release_inv_def tempR_lemmas tempR_describes_T_def T_is_outside_Q_def) apply(simp add:inv_def pre_R_def pre_Release_inv_def tempR_lemmas tempR_describes_T_def T_is_outside_Q_def) apply(simp add:inv_def pre_R_def pre_Release_inv_def tempR_lemmas tempR_describes_T_def T_is_outside_Q_def) apply(simp add:inv_def pre_R_def pre_Release_inv_def tempR_lemmas tempR_describes_T_def T_is_outside_Q_def) apply(simp add:inv_def pre_R_def pre_Release_inv_def tempR_lemmas tempR_describes_T_def T_is_outside_Q_def) apply (metis (no_types, lifting) PCR.simps(7) assms(5) cR_step_def) (**) defer apply(simp add:R_owns_no_bytes_def) apply(simp add:Tail_and_ownB_idleR_def) apply(intro conjI impI) apply clarify apply(intro conjI impI) apply(simp add:pre_R_def pre_Release_inv_def) apply (metis end_simp tempR_describes_ownB_def) apply(simp add:pre_R_def pre_Release_inv_def tempR_describes_ownB_def Tail_and_ownB_not_idleR_1_def Tail_and_ownB_not_idleR_2_def) apply(subgoal_tac "fst (last (q s)) + snd (last (q s)) < T s") apply presburger apply(simp add:inv_def Q_lemmas Q_basic_lemmas tempR_lemmas tempR_basic_lemmas) apply clarify apply(subgoal_tac "end(q s!(length(q s)-1)) = end(last(q s))") prefer 2 apply (metis last_conv_nth) (*should be solved by: apply (smt (z3) Nat.add_0_right diff_add_inverse diff_is_0_eq' diff_less last_conv_nth le_neq_implies_less le_trans length_greater_0_conv less_numeral_extra(1) less_or_eq_imp_le nat_neq_iff) so defer*) defer apply simp apply(subgoal_tac "end(last(q s)) = (T s -1)") apply (metis Suc_diff_1 Suc_leI bot_nat_0.extremum bot_nat_0.not_eq_extremum end_simp le_trans) apply (metis add_lessD1 diff_Suc_1 gr0_conv_Suc last_conv_nth le_less_Suc_eq length_greater_0_conv less_or_eq_imp_le) (*1st subgoal is left to check, should be trivially solved outside of the proof*) sorry qed next case Read then show ?thesis using assms apply (simp add:pre_R_def inv_def pre_Read_inv_def) apply(case_tac "pcR s'", simp_all add:cR_step_def) apply(simp add:pre_Release_inv_def) apply(intro conjI impI) apply(simp add:Q_lemmas Q_basic_lemmas) apply (metis Nat.add_0_right hd_conv_nth length_greater_0_conv) apply(simp add:Q_lemmas Q_basic_lemmas tempR_lemmas tempR_basic_lemmas) apply (metis (no_types, hide_lams)) apply(simp add:tempR_describes_T_def T_is_outside_Q_def) apply(simp add:tempR_describes_ownB_def) apply(simp add:Tail_and_ownB_not_idleR_1_def) apply(simp add:Tail_and_ownB_not_idleR_2_def) by metis next case idleR then show ?thesis using assms apply (simp add:pre_R_def inv_def pre_dequeue_inv_def) apply(case_tac "pcR s'", simp_all add:cR_step_def Q_dequeue_def) apply(case_tac "q s=[]", simp_all) apply(case_tac "q s=[]", simp_all) apply (metis assms(1) con_assms_def le_antisym less_eq_nat.simps(1) pre_dequeue_inv_def) apply(case_tac "q s=[]", simp_all) apply(simp add:pre_Read_inv_def) apply(intro conjI impI) apply(simp add:Q_lemmas Q_basic_lemmas) apply (simp add: hd_conv_nth) apply(simp add:Q_lemmas Q_basic_lemmas) apply (simp add: hd_conv_nth) apply (metis diff_is_0_eq' le_trans length_0_conv not_less_eq_eq) apply (metis Suc_leI length_greater_0_conv zero_less_diff) apply (metis Q_reflects_ownD_def Q_structure_def le_iff_add length_0_conv nat_less_le plus_nat.add_0) apply (metis Q_elem_size_def Q_reflects_writes_def Q_structure_def head_q0 length_pos_if_in_set less_SucI list.set_sel(1) not_less_eq snd_conv zero_le) apply(simp add:tempR_structure_def) apply(intro conjI impI) apply(simp add:tempR_basic_struct_def) apply(intro conjI impI) apply(simp add:Q_lemmas Q_basic_lemmas tempR_basic_lemmas) apply(simp add:Q_lemmas Q_basic_lemmas tempR_basic_lemmas) apply(subgoal_tac "hd(q s) = (q s!0) \<and> hd(tl(q s)) = (q s!1)") apply (metis (no_types, lifting) One_nat_def diff_Suc_1 length_greater_0_conv length_tl less_one zero_less_diff) apply (metis One_nat_def hd_conv_nth length_greater_0_conv nth_tl) apply(simp add:tempR_offsets_differ_def) apply(simp add:Q_lemmas Q_basic_lemmas tempR_basic_lemmas) apply(subgoal_tac "\<forall>i.(i<(length(q s)-1))\<longrightarrow>fst(tl(q s)!i) = fst(q s!(i+1))") apply (metis (no_types, lifting) One_nat_def add_diff_inverse_nat hd_conv_nth length_greater_0_conv lessI less_add_eq_less less_diff_conv less_nat_zero_code less_numeral_extra(3)) apply (metis Suc_eq_plus1 length_tl nth_tl) apply(simp add:tempR_has_no_overlaps_def) using peculiar_16 apply auto[1] apply(simp add:tempR_has_no_uroboros_def) using peculiar_21 apply auto[1] apply(simp add:tempR_holds_bytes_def) apply(simp add:tempR_reflects_writes_def) apply(simp add:Q_lemmas Q_basic_lemmas tempR_basic_lemmas) apply (metis Nat.add_0_right hd_conv_nth length_greater_0_conv) apply(simp add:tempR_elem_size_def) apply(simp add:Q_lemmas Q_basic_lemmas tempR_basic_lemmas) apply (metis add_cancel_right_right hd_conv_nth length_greater_0_conv) apply(simp add:tempR_describes_T_def T_is_outside_Q_def Q_describes_T_def) apply(simp add:Q_lemmas Q_basic_lemmas tempR_basic_lemmas) apply(case_tac "fst(hd(q s)) \<noteq>0") apply blast apply clarify apply(simp add: Tail_and_ownB_idleR_def) apply(subgoal_tac "fst(hd(q s)) \<noteq> T s") prefer 2 apply linarith apply(subgoal_tac "last(q s) = (q s!(length(q s)-1))") prefer 2 apply (metis last_conv_nth) apply (metis (no_types, lifting) One_nat_def Q_tail_props add_diff_cancel_right' add_gr_0 less_diff_conv zero_less_Suc) apply(simp add:tempR_describes_ownB_def) apply (metis R_owns_no_bytes_def zero_le) apply(simp add:Tail_and_ownB_not_idleR_1_def Tail_and_ownB_idleR_def R_owns_no_bytes_def Q_lemmas Q_basic_lemmas) apply clarify apply(intro conjI impI) apply (metis (no_types, lifting) hd_in_set less_Suc_eq not_less_eq prod.collapse) apply(simp add:Q_describes_T_def) apply(simp add:Tail_and_ownB_not_idleR_2_def Tail_and_ownB_idleR_def Q_describes_T_def R_owns_no_bytes_def Q_lemmas Q_basic_lemmas) apply (metis (no_types, lifting) add_leD1 add_less_same_cancel2 bot_nat_0.not_eq_extremum last_tl not_add_less2) apply (meson list.set_sel(2)) apply(simp add:Q_lemmas Q_basic_lemmas Q_describes_T_def T_is_outside_Q_def) by (metis hd_conv_nth length_greater_0_conv plus_nat.add_0) qed *) (*(* (*------------------------showing progress----------------------*) (* lemma tries_are_bounded: assumes "con_assms s" and "cW_step pcw s s'" and "inv pcw pcr s" shows "tries s'\<le>N" using assms apply (simp_all add:cW_step_def) using less_le_trans apply auto[1] apply (case_tac "pcw", simp_all) using less_imp_le_nat apply blast using less_imp_le_nat apply blast using less_imp_le_nat apply blast using less_imp_le_nat apply blast using less_imp_le_nat apply blast using less_imp_le_nat apply blast using less_imp_le_nat apply blast using less_imp_le_nat apply blast apply(case_tac "numEnqs s < n", simp_all add:less_imp_le) apply(case_tac "tW s \<noteq> T s", simp_all) using Suc_leI apply blast by (meson less_imp_le_nat) lemma when_W_moves_prog_less: assumes "con_assms s" and "inv (pcW s) (pcR s) s" and "cW_step (pcW s) s s'" shows "lex_prog s s'" proof - from assms(1) have sp1: "numEnqs s \<le> n \<and> numDeqs s \<le> n" using con_assms_def by auto from assms show ?thesis apply (simp_all add:cW_step_def inv_def progress_lemmas tries_left_def) apply(case_tac "pcW s", simp_all) apply(case_tac[!] "pcR s", simp_all) apply (simp_all add: diff_less_mono2) apply (case_tac[!] "tW s = T s", simp_all add:cW_step_def) apply(case_tac[1-6] "numEnqs s < n", simp_all) using diff_less_mono2 by auto qed lemma W_counter_implies_notown: assumes "con_assms s" and "mainInv s" shows "\<forall>i.(i<numEnqs s)\<longrightarrow>ownD s i \<in> {R,B}" using assms apply (simp_all add:inv_def) by (meson le_less_linear) lemma least_prog_W_implies: assumes "con_assms s" and "inv (pcW s) pcr s" and "cW_step (pcW s) s s'" and "inv (pcW s') pcr s'" and "lex_prog s s'" shows "end_W_prog s'=True\<longrightarrow>end_W_prog s \<or> ((\<forall>i.(i<n)\<longrightarrow>ownD s' i\<noteq>W) \<and> (pcW s=idleW) \<and> numEnqs s=n)" using assms W_counter_implies_notown apply (simp_all add: end_W_prog_def progress_lemmas tries_left_def cW_step_def inv_def) apply (case_tac "pcW s", simp_all) apply(case_tac "numEnqs s < n", simp_all) apply(case_tac "pcr", simp_all) apply (metis F.distinct(1) F.distinct(5) le_less_linear) apply (metis F.distinct(1) F.distinct(5) le_less_linear) apply (metis F.distinct(1) F.distinct(5) le_less_linear) by(case_tac "tW s \<noteq> T s", simp_all) lemma when_R_moves_prog_less: assumes "con_assms s" and "inv (pcW s) (pcR s) s" and "cR_step (pcR s) s s'" shows "lex_prog s s'" using assms apply (simp_all add:inv_def cR_step_def progress_lemmas) apply(case_tac "pcR s", simp_all add:tries_left_def) apply(case_tac[!] "pcW s", simp_all) apply(case_tac[!] "q s=[]", simp_all add: Let_def) apply clarify oops apply(case_tac " T s < fst (hd (q s)) + snd (hd (q s))", simp_all) apply(case_tac " T s < fst (hd (q s)) + snd (hd (q s))", simp_all) apply (metis (no_types, lifting) add_less_mono diff_less_mono2 diff_self_eq_0 length_greater_0_conv lessI less_le_trans mult_2 nat_add_left_cancel_less nat_less_le) apply (metis (no_types, lifting) add_less_mono diff_less_mono2 diff_self_eq_0 length_greater_0_conv lessI less_le_trans mult_2 nat_add_left_cancel_less nat_less_le) apply(case_tac " T s < fst (hd (q s)) + snd (hd (q s))", simp_all) apply (metis diff_less_mono2 length_greater_0_conv lessI zero_less_diff) apply (metis diff_less_mono2 diff_self_eq_0 le_eq_less_or_eq length_0_conv lessI) sorry lemma least_prog_R_implies: assumes "con_assms s" and "inv (pcW s) (pcR s) s" and "cR_step (pcR s) s s'" and "inv (pcW s) (pcR s) s'" and "lex_prog s s'" shows "end_R_prog s'=True\<longrightarrow>(end_R_prog s \<or> ((\<forall>i.(i<n)\<longrightarrow>ownD s' i=R) \<and> pcR s=Release))\<and>end_W_prog s" using assms apply (simp_all add: end_R_prog_def end_W_prog_def tries_left_def cR_step_def inv_def) apply(case_tac "pcR s", simp_all) by(case_tac "q s=[]", simp_all add:Let_def) lemma initial_progress: assumes "cR_step (pcR s) s s' \<or> cW_step (pcW s) s s'" and "inv (pcW s) (pcR s) s" and "init s'" and "con_assms s" shows "lex_prog s s'\<longrightarrow>s=s'" using assms apply(simp_all add:cR_step_def cW_step_def init_def progress_lemmas tries_left_def inv_def) apply(case_tac "pcR s", simp_all) apply(case_tac "pcW s", simp_all) apply (metis add.commute add_less_mono diff_less less_le_trans less_nat_zero_code mult.commute mult_2_right nat_le_iff_add order_less_irrefl zero_less_iff_neq_zero) apply (metis add.commute add_cancel_right_left add_cancel_right_right add_is_0 diff_less diff_zero le_iff_add length_0_conv length_greater_0_conv less_add_eq_less less_irrefl_nat less_le_trans mult.commute mult_2_right nat_diff_split zero_less_iff_neq_zero) apply (metis (no_types, hide_lams) add.commute diff_less le_iff_add le_less_trans less_eq_nat.simps(1) less_le_trans mult.commute mult_2_right order_less_irrefl trans_less_add2) apply (metis add.commute add_strict_mono diff_less le_iff_add less_le_trans less_nat_zero_code less_not_refl mult.commute mult_2_right zero_less_iff_neq_zero) apply (metis add_is_0 diff_diff_cancel diff_le_self nat_0_less_mult_iff nat_less_le not_le zero_less_diff zero_less_numeral) apply (metis add.commute diff_less le0 le_less_trans less_le_trans mult.commute mult_2_right nat_le_iff_add order_less_irrefl trans_less_add2) apply (metis add.commute diff_less le_iff_add le_less_trans less_eq_nat.simps(1) less_le_trans less_not_refl mult.commute mult_2_right trans_less_add2) apply (metis add.commute diff_less le0 le_less_trans less_le_trans less_not_refl mult.commute mult_2_right nat_le_iff_add trans_less_add1) apply (metis add.commute add_cancel_right_right diff_less gr_implies_not0 le0 le_iff_add le_less_trans le_neq_implies_less less_add_eq_less less_le_trans mult.commute mult_2_right order_less_irrefl zero_le) apply (metis add_is_0 diff_diff_cancel diff_self_eq_0 nat_0_less_mult_iff nat_less_le zero_less_diff zero_less_numeral) apply (metis add.commute diff_less le_iff_add le_less_trans less_le_trans mult.commute mult_2_right order_less_irrefl trans_less_add2 zero_le) apply (metis diff_add_zero diff_diff_cancel less_numeral_extra(3) mult_2) apply (metis add.commute diff_less le_iff_add less_le_trans mult.commute mult_2_right order_less_irrefl) apply (metis add.commute diff_less le_iff_add less_le_trans less_not_refl mult.commute mult_2_right) apply (simp add: leD) by (simp add: leD) (*--------------------------------------------------------------*) (*--------------lexicographical progress------------------------------*) definition "ltpcW i j \<equiv> (i \<noteq> j \<and> (i=FinishedW) \<or>(i \<in> {Enqueue, OOM, BTS} \<and> j\<noteq>FinishedW) \<or> (i \<in> {A8, Write} \<and> j \<notin> {Enqueue, OOM, BTS, FinishedW}) \<or> (i \<in> {A6, A7} \<and> j \<in> {idleW, A1, A2, A3, A4, A5}) \<or> (i \<in> {A3, A4, A5} \<and> j \<in> {idleW, A1, A2}) \<or> (i = A2 \<and> j \<in> {idleW, A1}) \<or> (i = A1 \<and> j = idleW)) " definition "ltpcR i j \<equiv> i = idleR \<and> j =Release \<or> i=Release \<and> j=Read \<or> i=Read \<and> j=idleR" definition "state_pv s \<equiv> (2*n - numEnqs s - numDeqs s)" definition "tries_left s \<equiv> N-tries s" definition "lex_prog s s' \<equiv> s = s' \<or> (state_pv s' < state_pv s \<or> (state_pv s' = state_pv s \<and> tries_left s' < tries_left s) \<or> (state_pv s' = state_pv s \<and> tries_left s' = tries_left s \<and> ltpcR (pcR s') (pcR s)) \<or> (state_pv s' = state_pv s \<and> tries_left s' = tries_left s \<and> ltpcW (pcW s') (pcW s)))" lemmas progress_lemmas = ltpcW_def ltpcR_def state_pv_def lex_prog_def definition "end_W_prog s \<equiv> ((n-numEnqs s)=0) \<and> tries_left s=N \<and> pcW s=FinishedW" definition "end_R_prog s \<equiv> end_W_prog s\<and> pcR s=idleR \<and> numDeqs s=numEnqs s" definition "start_state_prog s\<equiv> state_pv s=2*n \<and> pcR s=idleR \<and> pcW s=idleW \<and> tries_left s=N" *) (*a \<and> right_to_addresses s \<and> no_ownB s \<and> H_T_ownB s \<and> Buff_entries_transfer_numDeqs s*)*)*)
!======================================================================== ! ! S P E C F E M 2 D Version 7 . 0 ! -------------------------------- ! ! Main historical authors: Dimitri Komatitsch and Jeroen Tromp ! Princeton University, USA ! and CNRS / University of Marseille, France ! (there are currently many more authors!) ! (c) Princeton University and CNRS / University of Marseille, April 2014 ! ! This software is a computer program whose purpose is to solve ! the two-dimensional viscoelastic anisotropic or poroelastic wave equation ! using a spectral-element method (SEM). ! ! This software is governed by the CeCILL license under French law and ! abiding by the rules of distribution of free software. You can use, ! modify and/or redistribute the software under the terms of the CeCILL ! license as circulated by CEA, CNRS and Inria at the following URL ! "http://www.cecill.info". ! ! As a counterpart to the access to the source code and rights to copy, ! modify and redistribute granted by the license, users are provided only ! with a limited warranty and the software's author, the holder of the ! economic rights, and the successive licensors have only limited ! liability. ! ! In this respect, the user's attention is drawn to the risks associated ! with loading, using, modifying and/or developing or reproducing the ! software by the user in light of its specific status of free software, ! that may mean that it is complicated to manipulate, and that also ! therefore means that it is reserved for developers and experienced ! professionals having in-depth computer knowledge. Users are therefore ! encouraged to load and test the software's suitability as regards their ! requirements in conditions enabling the security of their systems and/or ! data to be ensured and, more generally, to use and operate it in the ! same conditions as regards security. ! ! The full text of the license is available in file "LICENSE". ! !======================================================================== double precision function hgll(I,Z,ZGLL,NZ) !------------------------------------------------------------- ! ! Compute the value of the Lagrangian interpolant L through ! the NZ Gauss-Lobatto Legendre points ZGLL at point Z ! !------------------------------------------------------------- implicit none integer i,nz double precision z double precision ZGLL(0:nz-1) integer n double precision EPS,DZ,ALFAN double precision, external :: PNLEG,PNDLEG EPS = 1.d-5 DZ = Z - ZGLL(I) if(abs(DZ) < EPS) then HGLL = 1.d0 return endif N = NZ - 1 ALFAN = dble(N)*(dble(N)+1.d0) HGLL = - (1.d0-Z*Z)*PNDLEG(Z,N)/ (ALFAN*PNLEG(ZGLL(I),N)*(Z-ZGLL(I))) end function hgll ! !===================================================================== ! double precision function hglj(I,Z,ZGLJ,NZ) !------------------------------------------------------------- ! ! Compute the value of the Lagrangian interpolant L through ! the NZ Gauss-Lobatto Jacobi points ZGLJ at point Z ! !------------------------------------------------------------- implicit none integer i,nz double precision z double precision ZGLJ(0:nz-1) integer n double precision EPS,DZ,ALFAN double precision, external :: PNGLJ,PNDGLJ EPS = 1.d-5 DZ = Z - ZGLJ(I) if(abs(DZ) < EPS) then HGLJ = 1.d0 return endif N = NZ - 1 ALFAN = dble(N)*(dble(N)+2.d0) HGLJ = - (1.d0-Z*Z)*PNDGLJ(Z,N)/ (ALFAN*PNGLJ(ZGLJ(I),N)*(Z-ZGLJ(I))) end function hglj ! !===================================================================== ! subroutine lagrange_any(xi,NGLL,xigll,h,hprime) ! subroutine to compute the Lagrange interpolants based upon the GLL points ! and their first derivatives at any point xi in [-1,1] implicit none integer NGLL double precision xi,xigll(NGLL),h(NGLL),hprime(NGLL) integer dgr,i,j double precision prod1,prod2 do dgr=1,NGLL prod1 = 1.0d0 prod2 = 1.0d0 do i=1,NGLL if(i /= dgr) then prod1 = prod1*(xi-xigll(i)) prod2 = prod2*(xigll(dgr)-xigll(i)) endif enddo h(dgr)=prod1/prod2 hprime(dgr)=0.0d0 do i=1,NGLL if(i /= dgr) then prod1=1.0d0 do j=1,NGLL if(j /= dgr .and. j /= i) prod1 = prod1*(xi-xigll(j)) enddo hprime(dgr) = hprime(dgr)+prod1 endif enddo hprime(dgr) = hprime(dgr)/prod2 enddo end subroutine lagrange_any ! !===================================================================== ! ! subroutine to compute the derivative of the Lagrange interpolants ! at the GLL points at any given GLL point double precision function lagrange_deriv_GLL(I,j,ZGLL,NZ) !------------------------------------------------------------------------ ! ! Compute the value of the derivative of the I-th ! Lagrange interpolant through the ! NZ Gauss-Lobatto Legendre points ZGLL at point ZGLL(j) ! !------------------------------------------------------------------------ implicit none integer i,j,nz double precision zgll(0:nz-1) integer degpoly double precision, external :: pnleg,pndleg degpoly = nz - 1 if (i == 0 .and. j == 0) then lagrange_deriv_GLL = - dble(degpoly)*(dble(degpoly)+1.d0) / 4.d0 else if (i == degpoly .and. j == degpoly) then lagrange_deriv_GLL = dble(degpoly)*(dble(degpoly)+1.d0) / 4.d0 else if (i == j) then lagrange_deriv_GLL = 0.d0 else lagrange_deriv_GLL = pnleg(zgll(j),degpoly) / & (pnleg(zgll(i),degpoly)*(zgll(j)-zgll(i))) & + (1.d0-zgll(j)*zgll(j))*pndleg(zgll(j),degpoly) / (dble(degpoly)* & (dble(degpoly)+1.d0)*pnleg(zgll(i),degpoly)*(zgll(j)-zgll(i))*(zgll(j)-zgll(i))) endif end function lagrange_deriv_GLL ! !======================================================================= ! ! subroutine to compute the derivative of the interpolants of the GLJ ! quadrature at the GLJ points at any given GLJ point double precision function poly_deriv_GLJ(I,j,ZGLJ,NZ) !------------------------------------------------------------------------ ! ! Compute the value of the derivative of the I-th ! polynomial interpolant of the GLJ quadrature through the ! NZ Gauss-Lobatto-Jacobi (0,1) points ZGLJ at point ZGLJ(j) ! !------------------------------------------------------------------------ implicit none integer i,j,nz double precision zglj(0:nz-1) integer degpoly double precision, external :: pnglj degpoly = nz - 1 if (i == 0 .and. j == 0) then ! Case 1 poly_deriv_GLJ = -dble(degpoly)*(dble(degpoly)+2.d0)/6.d0 else if (i == 0 .and. 0 < j .and. j < degpoly) then ! Case 2 poly_deriv_GLJ = 2.d0*(-1)**degpoly*pnglj(zglj(j),degpoly)/((1.d0+zglj(j))*(dble(degpoly)+1.d0)) else if (i == 0 .and. j == degpoly) then ! Case 3 poly_deriv_GLJ = (-1)**degpoly/(dble(degpoly)+1.d0) else if (0 < i .and. i < degpoly .and. j == 0) then ! Case 4 poly_deriv_GLJ = (-1)**(degpoly+1)*(dble(degpoly)+1.d0)/(2.d0*pnglj(zglj(i),degpoly)*(1.d0+zglj(i))) else if (0 < i .and. i < degpoly .and. 0 < j .and. j < degpoly .and. i /= j) then ! Case 5 poly_deriv_GLJ = 1.d0/(zglj(j)-zglj(i))*pnglj(zglj(j),degpoly)/pnglj(zglj(i),degpoly) else if (0 < i .and. i < degpoly .and. i == j) then ! Case 6 poly_deriv_GLJ = -1.d0/(2.d0*(1.d0+zglj(i))) else if (0 < i .and. i < degpoly .and. j == degpoly) then ! Case 7 poly_deriv_GLJ = 1.d0/(pnglj(zglj(i),degpoly)*(1.d0-zglj(i))) else if (i == degpoly .and. j == 0) then ! Case 8 poly_deriv_GLJ = (-1)**(degpoly+1)*(dble(degpoly)+1.d0)/4.d0 else if (i == degpoly .and. 0 < j .and. j < degpoly) then ! Case 9 poly_deriv_GLJ = -1.d0/(1.d0-zglj(j))*pnglj(zglj(j),degpoly) else if (i == degpoly .and. j == degpoly) then ! Case 10 poly_deriv_GLJ = (dble(degpoly)*(dble(degpoly)+2.d0)-1.d0)/4.d0 else call exit_MPI('Problem in poly_deriv_GLJ: in a perfect world this would NEVER appear') endif end function poly_deriv_GLJ
[STATEMENT] lemma backflows_filternew_flows_state: "backflows (filternew_flows_state \<T>) = (backflows (flows_state \<T>)) - (flows_fix \<T>)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. backflows (filternew_flows_state \<T>) = backflows (flows_state \<T>) - flows_fix \<T> [PROOF STEP] by(simp add: filternew_flows_state_alt backflows_minus_backflows)
function w = Lambert_W(x,branch) % Lambert_W Functional inverse of x = w*exp(w). % w = Lambert_W(x), same as Lambert_W(x,0) % w = Lambert_W(x,0) Primary or upper branch, W_0(x) % w = Lambert_W(x,-1) Lower branch, W_{-1}(x) % % See: http://blogs.mathworks.com/cleve/2013/09/02/the-lambert-w-function/ % Copyright 2013 The MathWorks, Inc. % Effective starting guess if nargin < 2 || branch ~= -1 w = ones(size(x)); % Start above -1 else w = -2*ones(size(x)); % Start below -1 end v = inf*w; % Haley's method while any(abs(w - v)./abs(w) > 1.e-8) v = w; e = exp(w); f = w.*e - x; % Iterate to make this quantity zero w = w - f./((e.*(w+1) - (w+2).*f./(2*w+2))); end
% Black-Scholes implied vol % % sigma=impvol(C,S,K,r,t,T,q,tol) % % C: call price (scalar or vector) % S: Stock price (scalar or vector) % K: Strike price (scalar or vector) % r: Interest rate (scalar or vector) % t: Time now (scalar or vector) % T: Maturity date (scalar or vector) % [q]: Dividend yield (scalar or vector). Default=0; % [tol]: Tolerance. Default=1e-6 function sigma=impvol(C,S,K,r,t,T,q,tol) T=T-t; if nargin<8 tol=1e-6; end if nargin<7 || isempty(q) q=0; end F=S*exp((r-q).*T); G=C.*exp(r.*T); alpha=log(F./K)./sqrt(T); beta=0.5*sqrt(T); % Now we need to solve G=F Phi(d1)- K Phi(d2) where % d1=alpha/sigma+beta and d2=alpha/sigma-beta a=beta.*(F+K); b=sqrt(2*pi)*(0.5*(F-K)-G); c=alpha.*(F-K); disc=max(0,b.^2-4*a.*c); sigma0=(-b+sqrt(disc))./(2*a); sigma=NewtonMethod(sigma0); function s1=NewtonMethod(s0) s1=s0; count=0; f=@(x) call(S,K,r,x,0,T,q)-C; fprime=@(x) call_vega(S,K,r,x,0,T,q); max_count=1e3; while max(abs(f(s1)))>tol && count<max_count count=count+1; s0=s1; s1=s0-f(s0)./fprime(s0); end if max(abs(f(s1)))>tol disp('Newton method did not converge') end end end
""" greenseltype(::Type{DQMC}, m::Model) Returns the type of the elements of the Green's function matrix. Defaults to `ComplexF64`. """ greenseltype(::Type{DQMC}, m::Model) = ComplexF64 """ hoppingeltype(::Type{DQMC}, m::Model) Returns the type of the elements of the hopping matrix. Defaults to `Float64`. """ hoppingeltype(::Type{DQMC}, m::Model) = Float64 """ interaction_matrix_type(T::Type{DQMC}, m::Model) Returns the (matrix) type of the interaction matrix. Defaults to `Matrix{greenseltype(T, m)}`. """ interaction_matrix_type(T::Type{DQMC}, m::Model) = Matrix{greenseltype(T, m)} """ hopping_matrix_type(T::Type{DQMC}, m::Model) Returns the (matrix) type of the hopping matrix. Defaults to `Matrix{hoppingeltype(T, m)}`. """ hopping_matrix_type(T::Type{DQMC}, m::Model) = Matrix{hoppingeltype(T, m)} """ greens_matrix_type(T::Type{DQMC}, m::Model) Returns the (matrix) type of the greens and most work matrices. Defaults to `Matrix{greenseltype(T, m)}`. """ greens_matrix_type(T::Type{DQMC}, m::Model) = Matrix{greenseltype(T, m)} """ init_interaction_matrix(m::Model) Initializes the interaction matrix. """ function init_interaction_matrix(m::Model) N = length(lattice(m)) flv = nflavors(m) zeros(greenseltype(DQMC, m), N*flv, N*flv) end """ energy_boson(mc::DQMC, m::Model, conf) Calculate bosonic part (non-Green's function determinant part) of energy for configuration `conf` for Model `m`. This is required for global and parallel updates as well as boson energy measurements. """ energy_boson(mc::DQMC, m::Model, conf) = throw(MethodError(energy_boson, (mc, m, conf)))
-- Andreas, 2014-03-27 fixed issue {-# OPTIONS --copatterns --sized-types #-} open import Common.Size record R (i : Size) : Set where inductive constructor c field j : Size< i r : R j data ⊥ : Set where elim : (i : Size) → R i → ⊥ elim i (c j r) = elim j r -- elim should be rejected by termination checker. -- Being accepted, its is translated into -- -- elim i x = elim (R.j x) (R.r x) -- -- which is making reduceHead in the injectivity checker -- produce larger and larger applications of elim. -- Leading to a stack overflow. inh : R ∞ R.j inh = ∞ R.r inh = inh -- inh should also be rejected
[GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝³ : MeasurableSpace α inst✝² : MeasurableSpace β inst✝¹ : MeasurableSpace γ inst✝ : MeasurableSpace δ μ : Measure α ν : Measure β f : α → γ g : β → γ u : γ → δ h : IdentDistrib f g hu : AEMeasurable u ⊢ AEMeasurable (u ∘ g) [PROOFSTEP] rw [h.map_eq] at hu [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝³ : MeasurableSpace α inst✝² : MeasurableSpace β inst✝¹ : MeasurableSpace γ inst✝ : MeasurableSpace δ μ : Measure α ν : Measure β f : α → γ g : β → γ u : γ → δ h : IdentDistrib f g hu : AEMeasurable u ⊢ AEMeasurable (u ∘ g) [PROOFSTEP] exact hu.comp_aemeasurable h.aemeasurable_snd [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝³ : MeasurableSpace α inst✝² : MeasurableSpace β inst✝¹ : MeasurableSpace γ inst✝ : MeasurableSpace δ μ : Measure α ν : Measure β f : α → γ g : β → γ u : γ → δ h : IdentDistrib f g hu : AEMeasurable u ⊢ Measure.map (u ∘ f) μ = Measure.map (u ∘ g) ν [PROOFSTEP] rw [← AEMeasurable.map_map_of_aemeasurable hu h.aemeasurable_fst, ← AEMeasurable.map_map_of_aemeasurable _ h.aemeasurable_snd, h.map_eq] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝³ : MeasurableSpace α inst✝² : MeasurableSpace β inst✝¹ : MeasurableSpace γ inst✝ : MeasurableSpace δ μ : Measure α ν : Measure β f : α → γ g : β → γ u : γ → δ h : IdentDistrib f g hu : AEMeasurable u ⊢ AEMeasurable u [PROOFSTEP] rwa [← h.map_eq] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝³ : MeasurableSpace α inst✝² : MeasurableSpace β inst✝¹ : MeasurableSpace γ inst✝ : MeasurableSpace δ μ : Measure α ν : Measure β f : α → γ g : β → γ h : IdentDistrib f g s : Set γ hs : MeasurableSet s ⊢ ↑↑μ (f ⁻¹' s) = ↑↑ν (g ⁻¹' s) [PROOFSTEP] rw [← Measure.map_apply_of_aemeasurable h.aemeasurable_fst hs, ← Measure.map_apply_of_aemeasurable h.aemeasurable_snd hs, h.map_eq] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝³ : MeasurableSpace α inst✝² : MeasurableSpace β inst✝¹ : MeasurableSpace γ inst✝ : MeasurableSpace δ μ : Measure α ν : Measure β f : α → γ g : β → γ h : IdentDistrib f g p : γ → Prop pmeas : MeasurableSet {x | p x} hp : ∀ᵐ (x : α) ∂μ, p (f x) ⊢ ∀ᵐ (x : β) ∂ν, p (g x) [PROOFSTEP] apply (ae_map_iff h.aemeasurable_snd pmeas).1 [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝³ : MeasurableSpace α inst✝² : MeasurableSpace β inst✝¹ : MeasurableSpace γ inst✝ : MeasurableSpace δ μ : Measure α ν : Measure β f : α → γ g : β → γ h : IdentDistrib f g p : γ → Prop pmeas : MeasurableSet {x | p x} hp : ∀ᵐ (x : α) ∂μ, p (f x) ⊢ ∀ᵐ (y : γ) ∂Measure.map g ν, p y [PROOFSTEP] rw [← h.map_eq] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝³ : MeasurableSpace α inst✝² : MeasurableSpace β inst✝¹ : MeasurableSpace γ inst✝ : MeasurableSpace δ μ : Measure α ν : Measure β f : α → γ g : β → γ h : IdentDistrib f g p : γ → Prop pmeas : MeasurableSet {x | p x} hp : ∀ᵐ (x : α) ∂μ, p (f x) ⊢ ∀ᵐ (y : γ) ∂Measure.map f μ, p y [PROOFSTEP] exact (ae_map_iff h.aemeasurable_fst pmeas).2 hp [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace γ inst✝³ : MeasurableSpace δ μ : Measure α ν : Measure β f : α → γ g : β → γ inst✝² : TopologicalSpace γ inst✝¹ : MetrizableSpace γ inst✝ : BorelSpace γ h : IdentDistrib f g hf : AEStronglyMeasurable f μ ⊢ AEStronglyMeasurable g ν [PROOFSTEP] refine' aestronglyMeasurable_iff_aemeasurable_separable.2 ⟨h.aemeasurable_snd, _⟩ [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace γ inst✝³ : MeasurableSpace δ μ : Measure α ν : Measure β f : α → γ g : β → γ inst✝² : TopologicalSpace γ inst✝¹ : MetrizableSpace γ inst✝ : BorelSpace γ h : IdentDistrib f g hf : AEStronglyMeasurable f μ ⊢ ∃ t, IsSeparable t ∧ ∀ᵐ (x : β) ∂ν, g x ∈ t [PROOFSTEP] rcases(aestronglyMeasurable_iff_aemeasurable_separable.1 hf).2 with ⟨t, t_sep, ht⟩ [GOAL] case intro.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace γ inst✝³ : MeasurableSpace δ μ : Measure α ν : Measure β f : α → γ g : β → γ inst✝² : TopologicalSpace γ inst✝¹ : MetrizableSpace γ inst✝ : BorelSpace γ h : IdentDistrib f g hf : AEStronglyMeasurable f μ t : Set γ t_sep : IsSeparable t ht : ∀ᵐ (x : α) ∂μ, f x ∈ t ⊢ ∃ t, IsSeparable t ∧ ∀ᵐ (x : β) ∂ν, g x ∈ t [PROOFSTEP] refine' ⟨closure t, t_sep.closure, _⟩ [GOAL] case intro.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace γ inst✝³ : MeasurableSpace δ μ : Measure α ν : Measure β f : α → γ g : β → γ inst✝² : TopologicalSpace γ inst✝¹ : MetrizableSpace γ inst✝ : BorelSpace γ h : IdentDistrib f g hf : AEStronglyMeasurable f μ t : Set γ t_sep : IsSeparable t ht : ∀ᵐ (x : α) ∂μ, f x ∈ t ⊢ ∀ᵐ (x : β) ∂ν, g x ∈ closure t [PROOFSTEP] apply h.ae_mem_snd isClosed_closure.measurableSet [GOAL] case intro.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace γ inst✝³ : MeasurableSpace δ μ : Measure α ν : Measure β f : α → γ g : β → γ inst✝² : TopologicalSpace γ inst✝¹ : MetrizableSpace γ inst✝ : BorelSpace γ h : IdentDistrib f g hf : AEStronglyMeasurable f μ t : Set γ t_sep : IsSeparable t ht : ∀ᵐ (x : α) ∂μ, f x ∈ t ⊢ ∀ᵐ (x : α) ∂μ, f x ∈ closure t [PROOFSTEP] filter_upwards [ht] with x hx using subset_closure hx [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁷ : MeasurableSpace α inst✝⁶ : MeasurableSpace β inst✝⁵ : MeasurableSpace γ inst✝⁴ : MeasurableSpace δ μ : Measure α ν : Measure β f : α → γ g : β → γ inst✝³ : ConditionallyCompleteLinearOrder γ inst✝² : TopologicalSpace γ inst✝¹ : OpensMeasurableSpace γ inst✝ : OrderClosedTopology γ h : IdentDistrib f g ⊢ essSup f μ = essSup g ν [PROOFSTEP] have I : ∀ a, μ {x : α | a < f x} = ν {x : β | a < g x} := fun a => h.measure_mem_eq measurableSet_Ioi [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁷ : MeasurableSpace α inst✝⁶ : MeasurableSpace β inst✝⁵ : MeasurableSpace γ inst✝⁴ : MeasurableSpace δ μ : Measure α ν : Measure β f : α → γ g : β → γ inst✝³ : ConditionallyCompleteLinearOrder γ inst✝² : TopologicalSpace γ inst✝¹ : OpensMeasurableSpace γ inst✝ : OrderClosedTopology γ h : IdentDistrib f g I : ∀ (a : γ), ↑↑μ {x | a < f x} = ↑↑ν {x | a < g x} ⊢ essSup f μ = essSup g ν [PROOFSTEP] simp_rw [essSup_eq_sInf, I] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝³ : MeasurableSpace α inst✝² : MeasurableSpace β inst✝¹ : MeasurableSpace γ inst✝ : MeasurableSpace δ μ : Measure α ν : Measure β f✝ : α → γ g✝ : β → γ f : α → ℝ≥0∞ g : β → ℝ≥0∞ h : IdentDistrib f g ⊢ ∫⁻ (x : α), f x ∂μ = ∫⁻ (x : β), g x ∂ν [PROOFSTEP] change ∫⁻ x, id (f x) ∂μ = ∫⁻ x, id (g x) ∂ν [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝³ : MeasurableSpace α inst✝² : MeasurableSpace β inst✝¹ : MeasurableSpace γ inst✝ : MeasurableSpace δ μ : Measure α ν : Measure β f✝ : α → γ g✝ : β → γ f : α → ℝ≥0∞ g : β → ℝ≥0∞ h : IdentDistrib f g ⊢ ∫⁻ (x : α), id (f x) ∂μ = ∫⁻ (x : β), id (g x) ∂ν [PROOFSTEP] rw [← lintegral_map' aemeasurable_id h.aemeasurable_fst, ← lintegral_map' aemeasurable_id h.aemeasurable_snd, h.map_eq] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace γ inst✝³ : MeasurableSpace δ μ : Measure α ν : Measure β f : α → γ g : β → γ inst✝² : NormedAddCommGroup γ inst✝¹ : NormedSpace ℝ γ inst✝ : BorelSpace γ h : IdentDistrib f g ⊢ ∫ (x : α), f x ∂μ = ∫ (x : β), g x ∂ν [PROOFSTEP] by_cases hf : AEStronglyMeasurable f μ [GOAL] case pos α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace γ inst✝³ : MeasurableSpace δ μ : Measure α ν : Measure β f : α → γ g : β → γ inst✝² : NormedAddCommGroup γ inst✝¹ : NormedSpace ℝ γ inst✝ : BorelSpace γ h : IdentDistrib f g hf : AEStronglyMeasurable f μ ⊢ ∫ (x : α), f x ∂μ = ∫ (x : β), g x ∂ν [PROOFSTEP] have A : AEStronglyMeasurable id (Measure.map f μ) := by rw [aestronglyMeasurable_iff_aemeasurable_separable] rcases(aestronglyMeasurable_iff_aemeasurable_separable.1 hf).2 with ⟨t, t_sep, ht⟩ refine' ⟨aemeasurable_id, ⟨closure t, t_sep.closure, _⟩⟩ rw [ae_map_iff h.aemeasurable_fst] · filter_upwards [ht] with x hx using subset_closure hx · exact isClosed_closure.measurableSet [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace γ inst✝³ : MeasurableSpace δ μ : Measure α ν : Measure β f : α → γ g : β → γ inst✝² : NormedAddCommGroup γ inst✝¹ : NormedSpace ℝ γ inst✝ : BorelSpace γ h : IdentDistrib f g hf : AEStronglyMeasurable f μ ⊢ AEStronglyMeasurable id (Measure.map f μ) [PROOFSTEP] rw [aestronglyMeasurable_iff_aemeasurable_separable] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace γ inst✝³ : MeasurableSpace δ μ : Measure α ν : Measure β f : α → γ g : β → γ inst✝² : NormedAddCommGroup γ inst✝¹ : NormedSpace ℝ γ inst✝ : BorelSpace γ h : IdentDistrib f g hf : AEStronglyMeasurable f μ ⊢ AEMeasurable id ∧ ∃ t, IsSeparable t ∧ ∀ᵐ (x : γ) ∂Measure.map f μ, id x ∈ t [PROOFSTEP] rcases(aestronglyMeasurable_iff_aemeasurable_separable.1 hf).2 with ⟨t, t_sep, ht⟩ [GOAL] case intro.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace γ inst✝³ : MeasurableSpace δ μ : Measure α ν : Measure β f : α → γ g : β → γ inst✝² : NormedAddCommGroup γ inst✝¹ : NormedSpace ℝ γ inst✝ : BorelSpace γ h : IdentDistrib f g hf : AEStronglyMeasurable f μ t : Set γ t_sep : IsSeparable t ht : ∀ᵐ (x : α) ∂μ, f x ∈ t ⊢ AEMeasurable id ∧ ∃ t, IsSeparable t ∧ ∀ᵐ (x : γ) ∂Measure.map f μ, id x ∈ t [PROOFSTEP] refine' ⟨aemeasurable_id, ⟨closure t, t_sep.closure, _⟩⟩ [GOAL] case intro.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace γ inst✝³ : MeasurableSpace δ μ : Measure α ν : Measure β f : α → γ g : β → γ inst✝² : NormedAddCommGroup γ inst✝¹ : NormedSpace ℝ γ inst✝ : BorelSpace γ h : IdentDistrib f g hf : AEStronglyMeasurable f μ t : Set γ t_sep : IsSeparable t ht : ∀ᵐ (x : α) ∂μ, f x ∈ t ⊢ ∀ᵐ (x : γ) ∂Measure.map f μ, id x ∈ closure t [PROOFSTEP] rw [ae_map_iff h.aemeasurable_fst] [GOAL] case intro.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace γ inst✝³ : MeasurableSpace δ μ : Measure α ν : Measure β f : α → γ g : β → γ inst✝² : NormedAddCommGroup γ inst✝¹ : NormedSpace ℝ γ inst✝ : BorelSpace γ h : IdentDistrib f g hf : AEStronglyMeasurable f μ t : Set γ t_sep : IsSeparable t ht : ∀ᵐ (x : α) ∂μ, f x ∈ t ⊢ ∀ᵐ (x : α) ∂μ, id (f x) ∈ closure t [PROOFSTEP] filter_upwards [ht] with x hx using subset_closure hx [GOAL] case intro.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace γ inst✝³ : MeasurableSpace δ μ : Measure α ν : Measure β f : α → γ g : β → γ inst✝² : NormedAddCommGroup γ inst✝¹ : NormedSpace ℝ γ inst✝ : BorelSpace γ h : IdentDistrib f g hf : AEStronglyMeasurable f μ t : Set γ t_sep : IsSeparable t ht : ∀ᵐ (x : α) ∂μ, f x ∈ t ⊢ MeasurableSet {x | id x ∈ closure t} [PROOFSTEP] exact isClosed_closure.measurableSet [GOAL] case pos α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace γ inst✝³ : MeasurableSpace δ μ : Measure α ν : Measure β f : α → γ g : β → γ inst✝² : NormedAddCommGroup γ inst✝¹ : NormedSpace ℝ γ inst✝ : BorelSpace γ h : IdentDistrib f g hf : AEStronglyMeasurable f μ A : AEStronglyMeasurable id (Measure.map f μ) ⊢ ∫ (x : α), f x ∂μ = ∫ (x : β), g x ∂ν [PROOFSTEP] change ∫ x, id (f x) ∂μ = ∫ x, id (g x) ∂ν [GOAL] case pos α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace γ inst✝³ : MeasurableSpace δ μ : Measure α ν : Measure β f : α → γ g : β → γ inst✝² : NormedAddCommGroup γ inst✝¹ : NormedSpace ℝ γ inst✝ : BorelSpace γ h : IdentDistrib f g hf : AEStronglyMeasurable f μ A : AEStronglyMeasurable id (Measure.map f μ) ⊢ ∫ (x : α), id (f x) ∂μ = ∫ (x : β), id (g x) ∂ν [PROOFSTEP] rw [← integral_map h.aemeasurable_fst A] [GOAL] case pos α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace γ inst✝³ : MeasurableSpace δ μ : Measure α ν : Measure β f : α → γ g : β → γ inst✝² : NormedAddCommGroup γ inst✝¹ : NormedSpace ℝ γ inst✝ : BorelSpace γ h : IdentDistrib f g hf : AEStronglyMeasurable f μ A : AEStronglyMeasurable id (Measure.map f μ) ⊢ ∫ (y : γ), id y ∂Measure.map f μ = ∫ (x : β), id (g x) ∂ν [PROOFSTEP] rw [h.map_eq] at A [GOAL] case pos α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace γ inst✝³ : MeasurableSpace δ μ : Measure α ν : Measure β f : α → γ g : β → γ inst✝² : NormedAddCommGroup γ inst✝¹ : NormedSpace ℝ γ inst✝ : BorelSpace γ h : IdentDistrib f g hf : AEStronglyMeasurable f μ A : AEStronglyMeasurable id (Measure.map g ν) ⊢ ∫ (y : γ), id y ∂Measure.map f μ = ∫ (x : β), id (g x) ∂ν [PROOFSTEP] rw [← integral_map h.aemeasurable_snd A, h.map_eq] [GOAL] case neg α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace γ inst✝³ : MeasurableSpace δ μ : Measure α ν : Measure β f : α → γ g : β → γ inst✝² : NormedAddCommGroup γ inst✝¹ : NormedSpace ℝ γ inst✝ : BorelSpace γ h : IdentDistrib f g hf : ¬AEStronglyMeasurable f μ ⊢ ∫ (x : α), f x ∂μ = ∫ (x : β), g x ∂ν [PROOFSTEP] rw [integral_non_aestronglyMeasurable hf] [GOAL] case neg α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace γ inst✝³ : MeasurableSpace δ μ : Measure α ν : Measure β f : α → γ g : β → γ inst✝² : NormedAddCommGroup γ inst✝¹ : NormedSpace ℝ γ inst✝ : BorelSpace γ h : IdentDistrib f g hf : ¬AEStronglyMeasurable f μ ⊢ 0 = ∫ (x : β), g x ∂ν [PROOFSTEP] rw [h.aestronglyMeasurable_iff] at hf [GOAL] case neg α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace γ inst✝³ : MeasurableSpace δ μ : Measure α ν : Measure β f : α → γ g : β → γ inst✝² : NormedAddCommGroup γ inst✝¹ : NormedSpace ℝ γ inst✝ : BorelSpace γ h : IdentDistrib f g hf : ¬AEStronglyMeasurable g ν ⊢ 0 = ∫ (x : β), g x ∂ν [PROOFSTEP] rw [integral_non_aestronglyMeasurable hf] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁵ : MeasurableSpace α inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace γ inst✝² : MeasurableSpace δ μ : Measure α ν : Measure β f : α → γ g : β → γ inst✝¹ : NormedAddCommGroup γ inst✝ : OpensMeasurableSpace γ h : IdentDistrib f g p : ℝ≥0∞ ⊢ snorm f p μ = snorm g p ν [PROOFSTEP] by_cases h0 : p = 0 [GOAL] case pos α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁵ : MeasurableSpace α inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace γ inst✝² : MeasurableSpace δ μ : Measure α ν : Measure β f : α → γ g : β → γ inst✝¹ : NormedAddCommGroup γ inst✝ : OpensMeasurableSpace γ h : IdentDistrib f g p : ℝ≥0∞ h0 : p = 0 ⊢ snorm f p μ = snorm g p ν [PROOFSTEP] simp [h0] [GOAL] case neg α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁵ : MeasurableSpace α inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace γ inst✝² : MeasurableSpace δ μ : Measure α ν : Measure β f : α → γ g : β → γ inst✝¹ : NormedAddCommGroup γ inst✝ : OpensMeasurableSpace γ h : IdentDistrib f g p : ℝ≥0∞ h0 : ¬p = 0 ⊢ snorm f p μ = snorm g p ν [PROOFSTEP] by_cases h_top : p = ∞ [GOAL] case pos α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁵ : MeasurableSpace α inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace γ inst✝² : MeasurableSpace δ μ : Measure α ν : Measure β f : α → γ g : β → γ inst✝¹ : NormedAddCommGroup γ inst✝ : OpensMeasurableSpace γ h : IdentDistrib f g p : ℝ≥0∞ h0 : ¬p = 0 h_top : p = ⊤ ⊢ snorm f p μ = snorm g p ν [PROOFSTEP] simp only [h_top, snorm, snormEssSup, ENNReal.top_ne_zero, eq_self_iff_true, if_true, if_false] [GOAL] case pos α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁵ : MeasurableSpace α inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace γ inst✝² : MeasurableSpace δ μ : Measure α ν : Measure β f : α → γ g : β → γ inst✝¹ : NormedAddCommGroup γ inst✝ : OpensMeasurableSpace γ h : IdentDistrib f g p : ℝ≥0∞ h0 : ¬p = 0 h_top : p = ⊤ ⊢ essSup (fun x => ↑‖f x‖₊) μ = essSup (fun x => ↑‖g x‖₊) ν [PROOFSTEP] apply essSup_eq [GOAL] case pos.h α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁵ : MeasurableSpace α inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace γ inst✝² : MeasurableSpace δ μ : Measure α ν : Measure β f : α → γ g : β → γ inst✝¹ : NormedAddCommGroup γ inst✝ : OpensMeasurableSpace γ h : IdentDistrib f g p : ℝ≥0∞ h0 : ¬p = 0 h_top : p = ⊤ ⊢ IdentDistrib (fun x => ↑‖f x‖₊) fun x => ↑‖g x‖₊ [PROOFSTEP] exact h.comp (measurable_coe_nnreal_ennreal.comp measurable_nnnorm) [GOAL] case neg α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁵ : MeasurableSpace α inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace γ inst✝² : MeasurableSpace δ μ : Measure α ν : Measure β f : α → γ g : β → γ inst✝¹ : NormedAddCommGroup γ inst✝ : OpensMeasurableSpace γ h : IdentDistrib f g p : ℝ≥0∞ h0 : ¬p = 0 h_top : ¬p = ⊤ ⊢ snorm f p μ = snorm g p ν [PROOFSTEP] simp only [snorm_eq_snorm' h0 h_top, snorm', one_div] [GOAL] case neg α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁵ : MeasurableSpace α inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace γ inst✝² : MeasurableSpace δ μ : Measure α ν : Measure β f : α → γ g : β → γ inst✝¹ : NormedAddCommGroup γ inst✝ : OpensMeasurableSpace γ h : IdentDistrib f g p : ℝ≥0∞ h0 : ¬p = 0 h_top : ¬p = ⊤ ⊢ (∫⁻ (a : α), ↑‖f a‖₊ ^ ENNReal.toReal p ∂μ) ^ (ENNReal.toReal p)⁻¹ = (∫⁻ (a : β), ↑‖g a‖₊ ^ ENNReal.toReal p ∂ν) ^ (ENNReal.toReal p)⁻¹ [PROOFSTEP] congr 1 [GOAL] case neg.e_a α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁵ : MeasurableSpace α inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace γ inst✝² : MeasurableSpace δ μ : Measure α ν : Measure β f : α → γ g : β → γ inst✝¹ : NormedAddCommGroup γ inst✝ : OpensMeasurableSpace γ h : IdentDistrib f g p : ℝ≥0∞ h0 : ¬p = 0 h_top : ¬p = ⊤ ⊢ ∫⁻ (a : α), ↑‖f a‖₊ ^ ENNReal.toReal p ∂μ = ∫⁻ (a : β), ↑‖g a‖₊ ^ ENNReal.toReal p ∂ν [PROOFSTEP] apply lintegral_eq [GOAL] case neg.e_a.h α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁵ : MeasurableSpace α inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace γ inst✝² : MeasurableSpace δ μ : Measure α ν : Measure β f : α → γ g : β → γ inst✝¹ : NormedAddCommGroup γ inst✝ : OpensMeasurableSpace γ h : IdentDistrib f g p : ℝ≥0∞ h0 : ¬p = 0 h_top : ¬p = ⊤ ⊢ IdentDistrib (fun x => ↑‖f x‖₊ ^ ENNReal.toReal p) fun x => ↑‖g x‖₊ ^ ENNReal.toReal p [PROOFSTEP] exact h.comp (Measurable.pow_const (measurable_coe_nnreal_ennreal.comp measurable_nnnorm) p.toReal) [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁵ : MeasurableSpace α inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace γ inst✝² : MeasurableSpace δ μ : Measure α ν : Measure β f : α → γ g : β → γ inst✝¹ : NormedAddCommGroup γ inst✝ : BorelSpace γ p : ℝ≥0∞ h : IdentDistrib f g hf : Memℒp f p ⊢ Memℒp g p [PROOFSTEP] refine' ⟨h.aestronglyMeasurable_snd hf.aestronglyMeasurable, _⟩ [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁵ : MeasurableSpace α inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace γ inst✝² : MeasurableSpace δ μ : Measure α ν : Measure β f : α → γ g : β → γ inst✝¹ : NormedAddCommGroup γ inst✝ : BorelSpace γ p : ℝ≥0∞ h : IdentDistrib f g hf : Memℒp f p ⊢ snorm g p ν < ⊤ [PROOFSTEP] rw [← h.snorm_eq] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁵ : MeasurableSpace α inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace γ inst✝² : MeasurableSpace δ μ : Measure α ν : Measure β f : α → γ g : β → γ inst✝¹ : NormedAddCommGroup γ inst✝ : BorelSpace γ p : ℝ≥0∞ h : IdentDistrib f g hf : Memℒp f p ⊢ snorm f p μ < ⊤ [PROOFSTEP] exact hf.2 [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁵ : MeasurableSpace α inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace γ inst✝² : MeasurableSpace δ μ : Measure α ν : Measure β f : α → γ g : β → γ inst✝¹ : NormedAddCommGroup γ inst✝ : BorelSpace γ h : IdentDistrib f g hf : Integrable f ⊢ Integrable g [PROOFSTEP] rw [← memℒp_one_iff_integrable] at hf ⊢ [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁵ : MeasurableSpace α inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace γ inst✝² : MeasurableSpace δ μ : Measure α ν : Measure β f : α → γ g : β → γ inst✝¹ : NormedAddCommGroup γ inst✝ : BorelSpace γ h : IdentDistrib f g hf : Memℒp f 1 ⊢ Memℒp g 1 [PROOFSTEP] exact h.memℒp_snd hf [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝³ : MeasurableSpace α inst✝² : MeasurableSpace β inst✝¹ : MeasurableSpace γ inst✝ : MeasurableSpace δ μ : Measure α ν : Measure β f✝ : α → γ g✝ : β → γ f : α → ℝ g : β → ℝ h : IdentDistrib f g ⊢ evariance f μ = evariance g ν [PROOFSTEP] convert (h.sub_const (∫ x, f x ∂μ)).nnnorm.coe_nnreal_ennreal.sq.lintegral_eq [GOAL] case h.e'_3 α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝³ : MeasurableSpace α inst✝² : MeasurableSpace β inst✝¹ : MeasurableSpace γ inst✝ : MeasurableSpace δ μ : Measure α ν : Measure β f✝ : α → γ g✝ : β → γ f : α → ℝ g : β → ℝ h : IdentDistrib f g ⊢ evariance g ν = ∫⁻ (x : β), ↑‖g x - ∫ (x : α), f x ∂μ‖₊ ^ 2 ∂ν [PROOFSTEP] rw [h.integral_eq] [GOAL] case h.e'_3 α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝³ : MeasurableSpace α inst✝² : MeasurableSpace β inst✝¹ : MeasurableSpace γ inst✝ : MeasurableSpace δ μ : Measure α ν : Measure β f✝ : α → γ g✝ : β → γ f : α → ℝ g : β → ℝ h : IdentDistrib f g ⊢ evariance g ν = ∫⁻ (x : β), ↑‖g x - ∫ (x : β), g x ∂ν‖₊ ^ 2 ∂ν [PROOFSTEP] rfl [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝³ : MeasurableSpace α inst✝² : MeasurableSpace β inst✝¹ : MeasurableSpace γ inst✝ : MeasurableSpace δ μ : Measure α ν : Measure β f✝ : α → γ g✝ : β → γ f : α → ℝ g : β → ℝ h : IdentDistrib f g ⊢ variance f μ = variance g ν [PROOFSTEP] rw [variance, h.evariance_eq] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝³ : MeasurableSpace α inst✝² : MeasurableSpace β inst✝¹ : MeasurableSpace γ inst✝ : MeasurableSpace δ μ : Measure α ν : Measure β f✝ : α → γ g✝ : β → γ f : α → ℝ g : β → ℝ h : IdentDistrib f g ⊢ ENNReal.toReal (evariance g ν) = variance g ν [PROOFSTEP] rfl [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace β inst✝⁶ : MeasurableSpace γ inst✝⁵ : MeasurableSpace δ E : Type u_5 inst✝⁴ : MeasurableSpace E inst✝³ : NormedAddCommGroup E inst✝² : BorelSpace E inst✝¹ : SecondCountableTopology E μ : Measure α inst✝ : IsFiniteMeasure μ ι : Type u_6 f : ι → α → E j : ι p : ℝ≥0∞ hp : 1 ≤ p hp' : p ≠ ⊤ hℒp : Memℒp (f j) p hfmeas : ∀ (i : ι), StronglyMeasurable (f i) hf : ∀ (i : ι), IdentDistrib (f i) (f j) ⊢ UniformIntegrable f p μ [PROOFSTEP] refine' uniformIntegrable_of' hp hp' hfmeas fun ε hε => _ [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace β inst✝⁶ : MeasurableSpace γ inst✝⁵ : MeasurableSpace δ E : Type u_5 inst✝⁴ : MeasurableSpace E inst✝³ : NormedAddCommGroup E inst✝² : BorelSpace E inst✝¹ : SecondCountableTopology E μ : Measure α inst✝ : IsFiniteMeasure μ ι : Type u_6 f : ι → α → E j : ι p : ℝ≥0∞ hp : 1 ≤ p hp' : p ≠ ⊤ hℒp : Memℒp (f j) p hfmeas : ∀ (i : ι), StronglyMeasurable (f i) hf : ∀ (i : ι), IdentDistrib (f i) (f j) ε : ℝ hε : 0 < ε ⊢ ∃ C, ∀ (i : ι), snorm (Set.indicator {x | C ≤ ‖f i x‖₊} (f i)) p μ ≤ ENNReal.ofReal ε [PROOFSTEP] by_cases hι : Nonempty ι [GOAL] case pos α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace β inst✝⁶ : MeasurableSpace γ inst✝⁵ : MeasurableSpace δ E : Type u_5 inst✝⁴ : MeasurableSpace E inst✝³ : NormedAddCommGroup E inst✝² : BorelSpace E inst✝¹ : SecondCountableTopology E μ : Measure α inst✝ : IsFiniteMeasure μ ι : Type u_6 f : ι → α → E j : ι p : ℝ≥0∞ hp : 1 ≤ p hp' : p ≠ ⊤ hℒp : Memℒp (f j) p hfmeas : ∀ (i : ι), StronglyMeasurable (f i) hf : ∀ (i : ι), IdentDistrib (f i) (f j) ε : ℝ hε : 0 < ε hι : Nonempty ι ⊢ ∃ C, ∀ (i : ι), snorm (Set.indicator {x | C ≤ ‖f i x‖₊} (f i)) p μ ≤ ENNReal.ofReal ε case neg α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace β inst✝⁶ : MeasurableSpace γ inst✝⁵ : MeasurableSpace δ E : Type u_5 inst✝⁴ : MeasurableSpace E inst✝³ : NormedAddCommGroup E inst✝² : BorelSpace E inst✝¹ : SecondCountableTopology E μ : Measure α inst✝ : IsFiniteMeasure μ ι : Type u_6 f : ι → α → E j : ι p : ℝ≥0∞ hp : 1 ≤ p hp' : p ≠ ⊤ hℒp : Memℒp (f j) p hfmeas : ∀ (i : ι), StronglyMeasurable (f i) hf : ∀ (i : ι), IdentDistrib (f i) (f j) ε : ℝ hε : 0 < ε hι : ¬Nonempty ι ⊢ ∃ C, ∀ (i : ι), snorm (Set.indicator {x | C ≤ ‖f i x‖₊} (f i)) p μ ≤ ENNReal.ofReal ε [PROOFSTEP] swap [GOAL] case neg α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace β inst✝⁶ : MeasurableSpace γ inst✝⁵ : MeasurableSpace δ E : Type u_5 inst✝⁴ : MeasurableSpace E inst✝³ : NormedAddCommGroup E inst✝² : BorelSpace E inst✝¹ : SecondCountableTopology E μ : Measure α inst✝ : IsFiniteMeasure μ ι : Type u_6 f : ι → α → E j : ι p : ℝ≥0∞ hp : 1 ≤ p hp' : p ≠ ⊤ hℒp : Memℒp (f j) p hfmeas : ∀ (i : ι), StronglyMeasurable (f i) hf : ∀ (i : ι), IdentDistrib (f i) (f j) ε : ℝ hε : 0 < ε hι : ¬Nonempty ι ⊢ ∃ C, ∀ (i : ι), snorm (Set.indicator {x | C ≤ ‖f i x‖₊} (f i)) p μ ≤ ENNReal.ofReal ε [PROOFSTEP] exact ⟨0, fun i => False.elim (hι <| Nonempty.intro i)⟩ [GOAL] case pos α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace β inst✝⁶ : MeasurableSpace γ inst✝⁵ : MeasurableSpace δ E : Type u_5 inst✝⁴ : MeasurableSpace E inst✝³ : NormedAddCommGroup E inst✝² : BorelSpace E inst✝¹ : SecondCountableTopology E μ : Measure α inst✝ : IsFiniteMeasure μ ι : Type u_6 f : ι → α → E j : ι p : ℝ≥0∞ hp : 1 ≤ p hp' : p ≠ ⊤ hℒp : Memℒp (f j) p hfmeas : ∀ (i : ι), StronglyMeasurable (f i) hf : ∀ (i : ι), IdentDistrib (f i) (f j) ε : ℝ hε : 0 < ε hι : Nonempty ι ⊢ ∃ C, ∀ (i : ι), snorm (Set.indicator {x | C ≤ ‖f i x‖₊} (f i)) p μ ≤ ENNReal.ofReal ε [PROOFSTEP] obtain ⟨C, hC₁, hC₂⟩ := hℒp.snorm_indicator_norm_ge_pos_le μ (hfmeas _) hε [GOAL] case pos.intro.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace β inst✝⁶ : MeasurableSpace γ inst✝⁵ : MeasurableSpace δ E : Type u_5 inst✝⁴ : MeasurableSpace E inst✝³ : NormedAddCommGroup E inst✝² : BorelSpace E inst✝¹ : SecondCountableTopology E μ : Measure α inst✝ : IsFiniteMeasure μ ι : Type u_6 f : ι → α → E j : ι p : ℝ≥0∞ hp : 1 ≤ p hp' : p ≠ ⊤ hℒp : Memℒp (f j) p hfmeas : ∀ (i : ι), StronglyMeasurable (f i) hf : ∀ (i : ι), IdentDistrib (f i) (f j) ε : ℝ hε : 0 < ε hι : Nonempty ι C : ℝ hC₁ : 0 < C hC₂ : snorm (Set.indicator {x | C ≤ ↑‖f j x‖₊} (f j)) p μ ≤ ENNReal.ofReal ε ⊢ ∃ C, ∀ (i : ι), snorm (Set.indicator {x | C ≤ ‖f i x‖₊} (f i)) p μ ≤ ENNReal.ofReal ε [PROOFSTEP] refine' ⟨⟨C, hC₁.le⟩, fun i => le_trans (le_of_eq _) hC₂⟩ [GOAL] case pos.intro.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace β inst✝⁶ : MeasurableSpace γ inst✝⁵ : MeasurableSpace δ E : Type u_5 inst✝⁴ : MeasurableSpace E inst✝³ : NormedAddCommGroup E inst✝² : BorelSpace E inst✝¹ : SecondCountableTopology E μ : Measure α inst✝ : IsFiniteMeasure μ ι : Type u_6 f : ι → α → E j : ι p : ℝ≥0∞ hp : 1 ≤ p hp' : p ≠ ⊤ hℒp : Memℒp (f j) p hfmeas : ∀ (i : ι), StronglyMeasurable (f i) hf : ∀ (i : ι), IdentDistrib (f i) (f j) ε : ℝ hε : 0 < ε hι : Nonempty ι C : ℝ hC₁ : 0 < C hC₂ : snorm (Set.indicator {x | C ≤ ↑‖f j x‖₊} (f j)) p μ ≤ ENNReal.ofReal ε i : ι ⊢ snorm (Set.indicator {x | { val := C, property := (_ : 0 ≤ C) } ≤ ‖f i x‖₊} (f i)) p μ = snorm (Set.indicator {x | C ≤ ↑‖f j x‖₊} (f j)) p μ [PROOFSTEP] have : {x : α | (⟨C, hC₁.le⟩ : ℝ≥0) ≤ ‖f i x‖₊}.indicator (f i) = (fun x : E => if (⟨C, hC₁.le⟩ : ℝ≥0) ≤ ‖x‖₊ then x else 0) ∘ f i := by ext x simp only [Set.indicator, Set.mem_setOf_eq]; norm_cast [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace β inst✝⁶ : MeasurableSpace γ inst✝⁵ : MeasurableSpace δ E : Type u_5 inst✝⁴ : MeasurableSpace E inst✝³ : NormedAddCommGroup E inst✝² : BorelSpace E inst✝¹ : SecondCountableTopology E μ : Measure α inst✝ : IsFiniteMeasure μ ι : Type u_6 f : ι → α → E j : ι p : ℝ≥0∞ hp : 1 ≤ p hp' : p ≠ ⊤ hℒp : Memℒp (f j) p hfmeas : ∀ (i : ι), StronglyMeasurable (f i) hf : ∀ (i : ι), IdentDistrib (f i) (f j) ε : ℝ hε : 0 < ε hι : Nonempty ι C : ℝ hC₁ : 0 < C hC₂ : snorm (Set.indicator {x | C ≤ ↑‖f j x‖₊} (f j)) p μ ≤ ENNReal.ofReal ε i : ι ⊢ Set.indicator {x | { val := C, property := (_ : 0 ≤ C) } ≤ ‖f i x‖₊} (f i) = (fun x => if { val := C, property := (_ : 0 ≤ C) } ≤ ‖x‖₊ then x else 0) ∘ f i [PROOFSTEP] ext x [GOAL] case h α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace β inst✝⁶ : MeasurableSpace γ inst✝⁵ : MeasurableSpace δ E : Type u_5 inst✝⁴ : MeasurableSpace E inst✝³ : NormedAddCommGroup E inst✝² : BorelSpace E inst✝¹ : SecondCountableTopology E μ : Measure α inst✝ : IsFiniteMeasure μ ι : Type u_6 f : ι → α → E j : ι p : ℝ≥0∞ hp : 1 ≤ p hp' : p ≠ ⊤ hℒp : Memℒp (f j) p hfmeas : ∀ (i : ι), StronglyMeasurable (f i) hf : ∀ (i : ι), IdentDistrib (f i) (f j) ε : ℝ hε : 0 < ε hι : Nonempty ι C : ℝ hC₁ : 0 < C hC₂ : snorm (Set.indicator {x | C ≤ ↑‖f j x‖₊} (f j)) p μ ≤ ENNReal.ofReal ε i : ι x : α ⊢ Set.indicator {x | { val := C, property := (_ : 0 ≤ C) } ≤ ‖f i x‖₊} (f i) x = ((fun x => if { val := C, property := (_ : 0 ≤ C) } ≤ ‖x‖₊ then x else 0) ∘ f i) x [PROOFSTEP] simp only [Set.indicator, Set.mem_setOf_eq] [GOAL] case h α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace β inst✝⁶ : MeasurableSpace γ inst✝⁵ : MeasurableSpace δ E : Type u_5 inst✝⁴ : MeasurableSpace E inst✝³ : NormedAddCommGroup E inst✝² : BorelSpace E inst✝¹ : SecondCountableTopology E μ : Measure α inst✝ : IsFiniteMeasure μ ι : Type u_6 f : ι → α → E j : ι p : ℝ≥0∞ hp : 1 ≤ p hp' : p ≠ ⊤ hℒp : Memℒp (f j) p hfmeas : ∀ (i : ι), StronglyMeasurable (f i) hf : ∀ (i : ι), IdentDistrib (f i) (f j) ε : ℝ hε : 0 < ε hι : Nonempty ι C : ℝ hC₁ : 0 < C hC₂ : snorm (Set.indicator {x | C ≤ ↑‖f j x‖₊} (f j)) p μ ≤ ENNReal.ofReal ε i : ι x : α ⊢ (if { val := C, property := (_ : 0 ≤ C) } ≤ ‖f i x‖₊ then f i x else 0) = ((fun x => if { val := C, property := (_ : 0 ≤ C) } ≤ ‖x‖₊ then x else 0) ∘ f i) x [PROOFSTEP] norm_cast [GOAL] case pos.intro.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace β inst✝⁶ : MeasurableSpace γ inst✝⁵ : MeasurableSpace δ E : Type u_5 inst✝⁴ : MeasurableSpace E inst✝³ : NormedAddCommGroup E inst✝² : BorelSpace E inst✝¹ : SecondCountableTopology E μ : Measure α inst✝ : IsFiniteMeasure μ ι : Type u_6 f : ι → α → E j : ι p : ℝ≥0∞ hp : 1 ≤ p hp' : p ≠ ⊤ hℒp : Memℒp (f j) p hfmeas : ∀ (i : ι), StronglyMeasurable (f i) hf : ∀ (i : ι), IdentDistrib (f i) (f j) ε : ℝ hε : 0 < ε hι : Nonempty ι C : ℝ hC₁ : 0 < C hC₂ : snorm (Set.indicator {x | C ≤ ↑‖f j x‖₊} (f j)) p μ ≤ ENNReal.ofReal ε i : ι this : Set.indicator {x | { val := C, property := (_ : 0 ≤ C) } ≤ ‖f i x‖₊} (f i) = (fun x => if { val := C, property := (_ : 0 ≤ C) } ≤ ‖x‖₊ then x else 0) ∘ f i ⊢ snorm (Set.indicator {x | { val := C, property := (_ : 0 ≤ C) } ≤ ‖f i x‖₊} (f i)) p μ = snorm (Set.indicator {x | C ≤ ↑‖f j x‖₊} (f j)) p μ [PROOFSTEP] simp_rw [coe_nnnorm, this] [GOAL] case pos.intro.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace β inst✝⁶ : MeasurableSpace γ inst✝⁵ : MeasurableSpace δ E : Type u_5 inst✝⁴ : MeasurableSpace E inst✝³ : NormedAddCommGroup E inst✝² : BorelSpace E inst✝¹ : SecondCountableTopology E μ : Measure α inst✝ : IsFiniteMeasure μ ι : Type u_6 f : ι → α → E j : ι p : ℝ≥0∞ hp : 1 ≤ p hp' : p ≠ ⊤ hℒp : Memℒp (f j) p hfmeas : ∀ (i : ι), StronglyMeasurable (f i) hf : ∀ (i : ι), IdentDistrib (f i) (f j) ε : ℝ hε : 0 < ε hι : Nonempty ι C : ℝ hC₁ : 0 < C hC₂ : snorm (Set.indicator {x | C ≤ ↑‖f j x‖₊} (f j)) p μ ≤ ENNReal.ofReal ε i : ι this : Set.indicator {x | { val := C, property := (_ : 0 ≤ C) } ≤ ‖f i x‖₊} (f i) = (fun x => if { val := C, property := (_ : 0 ≤ C) } ≤ ‖x‖₊ then x else 0) ∘ f i ⊢ snorm ((fun x => if { val := C, property := (_ : 0 ≤ C) } ≤ ‖x‖₊ then x else 0) ∘ f i) p μ = snorm (Set.indicator {x | C ≤ ‖f j x‖} (f j)) p μ [PROOFSTEP] rw [← snorm_map_measure _ (hf i).aemeasurable_fst, (hf i).map_eq, snorm_map_measure _ (hf j).aemeasurable_fst] [GOAL] case pos.intro.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace β inst✝⁶ : MeasurableSpace γ inst✝⁵ : MeasurableSpace δ E : Type u_5 inst✝⁴ : MeasurableSpace E inst✝³ : NormedAddCommGroup E inst✝² : BorelSpace E inst✝¹ : SecondCountableTopology E μ : Measure α inst✝ : IsFiniteMeasure μ ι : Type u_6 f : ι → α → E j : ι p : ℝ≥0∞ hp : 1 ≤ p hp' : p ≠ ⊤ hℒp : Memℒp (f j) p hfmeas : ∀ (i : ι), StronglyMeasurable (f i) hf : ∀ (i : ι), IdentDistrib (f i) (f j) ε : ℝ hε : 0 < ε hι : Nonempty ι C : ℝ hC₁ : 0 < C hC₂ : snorm (Set.indicator {x | C ≤ ↑‖f j x‖₊} (f j)) p μ ≤ ENNReal.ofReal ε i : ι this : Set.indicator {x | { val := C, property := (_ : 0 ≤ C) } ≤ ‖f i x‖₊} (f i) = (fun x => if { val := C, property := (_ : 0 ≤ C) } ≤ ‖x‖₊ then x else 0) ∘ f i ⊢ snorm ((fun x => if { val := C, property := (_ : 0 ≤ C) } ≤ ‖x‖₊ then x else 0) ∘ f j) p μ = snorm (Set.indicator {x | C ≤ ‖f j x‖} (f j)) p μ [PROOFSTEP] rfl [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace β inst✝⁶ : MeasurableSpace γ inst✝⁵ : MeasurableSpace δ E : Type u_5 inst✝⁴ : MeasurableSpace E inst✝³ : NormedAddCommGroup E inst✝² : BorelSpace E inst✝¹ : SecondCountableTopology E μ : Measure α inst✝ : IsFiniteMeasure μ ι : Type u_6 f : ι → α → E j : ι p : ℝ≥0∞ hp : 1 ≤ p hp' : p ≠ ⊤ hℒp : Memℒp (f j) p hfmeas : ∀ (i : ι), StronglyMeasurable (f i) hf : ∀ (i : ι), IdentDistrib (f i) (f j) ε : ℝ hε : 0 < ε hι : Nonempty ι C : ℝ hC₁ : 0 < C hC₂ : snorm (Set.indicator {x | C ≤ ↑‖f j x‖₊} (f j)) p μ ≤ ENNReal.ofReal ε i : ι this : Set.indicator {x | { val := C, property := (_ : 0 ≤ C) } ≤ ‖f i x‖₊} (f i) = (fun x => if { val := C, property := (_ : 0 ≤ C) } ≤ ‖x‖₊ then x else 0) ∘ f i ⊢ AEStronglyMeasurable (fun x => if { val := C, property := (_ : 0 ≤ C) } ≤ ‖x‖₊ then x else 0) (Measure.map (f j) μ) α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace β inst✝⁶ : MeasurableSpace γ inst✝⁵ : MeasurableSpace δ E : Type u_5 inst✝⁴ : MeasurableSpace E inst✝³ : NormedAddCommGroup E inst✝² : BorelSpace E inst✝¹ : SecondCountableTopology E μ : Measure α inst✝ : IsFiniteMeasure μ ι : Type u_6 f : ι → α → E j : ι p : ℝ≥0∞ hp : 1 ≤ p hp' : p ≠ ⊤ hℒp : Memℒp (f j) p hfmeas : ∀ (i : ι), StronglyMeasurable (f i) hf : ∀ (i : ι), IdentDistrib (f i) (f j) ε : ℝ hε : 0 < ε hι : Nonempty ι C : ℝ hC₁ : 0 < C hC₂ : snorm (Set.indicator {x | C ≤ ↑‖f j x‖₊} (f j)) p μ ≤ ENNReal.ofReal ε i : ι this : Set.indicator {x | { val := C, property := (_ : 0 ≤ C) } ≤ ‖f i x‖₊} (f i) = (fun x => if { val := C, property := (_ : 0 ≤ C) } ≤ ‖x‖₊ then x else 0) ∘ f i ⊢ AEStronglyMeasurable (fun x => if { val := C, property := (_ : 0 ≤ C) } ≤ ‖x‖₊ then x else 0) (Measure.map (f i) μ) [PROOFSTEP] all_goals exact_mod_cast aestronglyMeasurable_id.indicator (measurableSet_le measurable_const measurable_nnnorm) [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace β inst✝⁶ : MeasurableSpace γ inst✝⁵ : MeasurableSpace δ E : Type u_5 inst✝⁴ : MeasurableSpace E inst✝³ : NormedAddCommGroup E inst✝² : BorelSpace E inst✝¹ : SecondCountableTopology E μ : Measure α inst✝ : IsFiniteMeasure μ ι : Type u_6 f : ι → α → E j : ι p : ℝ≥0∞ hp : 1 ≤ p hp' : p ≠ ⊤ hℒp : Memℒp (f j) p hfmeas : ∀ (i : ι), StronglyMeasurable (f i) hf : ∀ (i : ι), IdentDistrib (f i) (f j) ε : ℝ hε : 0 < ε hι : Nonempty ι C : ℝ hC₁ : 0 < C hC₂ : snorm (Set.indicator {x | C ≤ ↑‖f j x‖₊} (f j)) p μ ≤ ENNReal.ofReal ε i : ι this : Set.indicator {x | { val := C, property := (_ : 0 ≤ C) } ≤ ‖f i x‖₊} (f i) = (fun x => if { val := C, property := (_ : 0 ≤ C) } ≤ ‖x‖₊ then x else 0) ∘ f i ⊢ AEStronglyMeasurable (fun x => if { val := C, property := (_ : 0 ≤ C) } ≤ ‖x‖₊ then x else 0) (Measure.map (f j) μ) [PROOFSTEP] exact_mod_cast aestronglyMeasurable_id.indicator (measurableSet_le measurable_const measurable_nnnorm) [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace β inst✝⁶ : MeasurableSpace γ inst✝⁵ : MeasurableSpace δ E : Type u_5 inst✝⁴ : MeasurableSpace E inst✝³ : NormedAddCommGroup E inst✝² : BorelSpace E inst✝¹ : SecondCountableTopology E μ : Measure α inst✝ : IsFiniteMeasure μ ι : Type u_6 f : ι → α → E j : ι p : ℝ≥0∞ hp : 1 ≤ p hp' : p ≠ ⊤ hℒp : Memℒp (f j) p hfmeas : ∀ (i : ι), StronglyMeasurable (f i) hf : ∀ (i : ι), IdentDistrib (f i) (f j) ε : ℝ hε : 0 < ε hι : Nonempty ι C : ℝ hC₁ : 0 < C hC₂ : snorm (Set.indicator {x | C ≤ ↑‖f j x‖₊} (f j)) p μ ≤ ENNReal.ofReal ε i : ι this : Set.indicator {x | { val := C, property := (_ : 0 ≤ C) } ≤ ‖f i x‖₊} (f i) = (fun x => if { val := C, property := (_ : 0 ≤ C) } ≤ ‖x‖₊ then x else 0) ∘ f i ⊢ AEStronglyMeasurable (fun x => if { val := C, property := (_ : 0 ≤ C) } ≤ ‖x‖₊ then x else 0) (Measure.map (f i) μ) [PROOFSTEP] exact_mod_cast aestronglyMeasurable_id.indicator (measurableSet_le measurable_const measurable_nnnorm) [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace β inst✝⁶ : MeasurableSpace γ inst✝⁵ : MeasurableSpace δ E : Type u_5 inst✝⁴ : MeasurableSpace E inst✝³ : NormedAddCommGroup E inst✝² : BorelSpace E inst✝¹ : SecondCountableTopology E μ : Measure α inst✝ : IsFiniteMeasure μ ι : Type u_6 f : ι → α → E j : ι p : ℝ≥0∞ hp : 1 ≤ p hp' : p ≠ ⊤ hℒp : Memℒp (f j) p hf : ∀ (i : ι), IdentDistrib (f i) (f j) ⊢ UniformIntegrable f p μ [PROOFSTEP] have hfmeas : ∀ i, AEStronglyMeasurable (f i) μ := fun i => (hf i).aestronglyMeasurable_iff.2 hℒp.1 [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace β inst✝⁶ : MeasurableSpace γ inst✝⁵ : MeasurableSpace δ E : Type u_5 inst✝⁴ : MeasurableSpace E inst✝³ : NormedAddCommGroup E inst✝² : BorelSpace E inst✝¹ : SecondCountableTopology E μ : Measure α inst✝ : IsFiniteMeasure μ ι : Type u_6 f : ι → α → E j : ι p : ℝ≥0∞ hp : 1 ≤ p hp' : p ≠ ⊤ hℒp : Memℒp (f j) p hf : ∀ (i : ι), IdentDistrib (f i) (f j) hfmeas : ∀ (i : ι), AEStronglyMeasurable (f i) μ ⊢ UniformIntegrable f p μ [PROOFSTEP] set g : ι → α → E := fun i => (hfmeas i).choose [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace β inst✝⁶ : MeasurableSpace γ inst✝⁵ : MeasurableSpace δ E : Type u_5 inst✝⁴ : MeasurableSpace E inst✝³ : NormedAddCommGroup E inst✝² : BorelSpace E inst✝¹ : SecondCountableTopology E μ : Measure α inst✝ : IsFiniteMeasure μ ι : Type u_6 f : ι → α → E j : ι p : ℝ≥0∞ hp : 1 ≤ p hp' : p ≠ ⊤ hℒp : Memℒp (f j) p hf : ∀ (i : ι), IdentDistrib (f i) (f j) hfmeas : ∀ (i : ι), AEStronglyMeasurable (f i) μ g : ι → α → E := fun i => Exists.choose (_ : AEStronglyMeasurable (f i) μ) ⊢ UniformIntegrable f p μ [PROOFSTEP] have hgmeas : ∀ i, StronglyMeasurable (g i) := fun i => (Exists.choose_spec <| hfmeas i).1 [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace β inst✝⁶ : MeasurableSpace γ inst✝⁵ : MeasurableSpace δ E : Type u_5 inst✝⁴ : MeasurableSpace E inst✝³ : NormedAddCommGroup E inst✝² : BorelSpace E inst✝¹ : SecondCountableTopology E μ : Measure α inst✝ : IsFiniteMeasure μ ι : Type u_6 f : ι → α → E j : ι p : ℝ≥0∞ hp : 1 ≤ p hp' : p ≠ ⊤ hℒp : Memℒp (f j) p hf : ∀ (i : ι), IdentDistrib (f i) (f j) hfmeas : ∀ (i : ι), AEStronglyMeasurable (f i) μ g : ι → α → E := fun i => Exists.choose (_ : AEStronglyMeasurable (f i) μ) hgmeas : ∀ (i : ι), StronglyMeasurable (g i) ⊢ UniformIntegrable f p μ [PROOFSTEP] have hgeq : ∀ i, g i =ᵐ[μ] f i := fun i => (Exists.choose_spec <| hfmeas i).2.symm [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace β inst✝⁶ : MeasurableSpace γ inst✝⁵ : MeasurableSpace δ E : Type u_5 inst✝⁴ : MeasurableSpace E inst✝³ : NormedAddCommGroup E inst✝² : BorelSpace E inst✝¹ : SecondCountableTopology E μ : Measure α inst✝ : IsFiniteMeasure μ ι : Type u_6 f : ι → α → E j : ι p : ℝ≥0∞ hp : 1 ≤ p hp' : p ≠ ⊤ hℒp : Memℒp (f j) p hf : ∀ (i : ι), IdentDistrib (f i) (f j) hfmeas : ∀ (i : ι), AEStronglyMeasurable (f i) μ g : ι → α → E := fun i => Exists.choose (_ : AEStronglyMeasurable (f i) μ) hgmeas : ∀ (i : ι), StronglyMeasurable (g i) hgeq : ∀ (i : ι), g i =ᵐ[μ] f i ⊢ UniformIntegrable f p μ [PROOFSTEP] have hgℒp : Memℒp (g j) p μ := hℒp.ae_eq (hgeq j).symm [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace β inst✝⁶ : MeasurableSpace γ inst✝⁵ : MeasurableSpace δ E : Type u_5 inst✝⁴ : MeasurableSpace E inst✝³ : NormedAddCommGroup E inst✝² : BorelSpace E inst✝¹ : SecondCountableTopology E μ : Measure α inst✝ : IsFiniteMeasure μ ι : Type u_6 f : ι → α → E j : ι p : ℝ≥0∞ hp : 1 ≤ p hp' : p ≠ ⊤ hℒp : Memℒp (f j) p hf : ∀ (i : ι), IdentDistrib (f i) (f j) hfmeas : ∀ (i : ι), AEStronglyMeasurable (f i) μ g : ι → α → E := fun i => Exists.choose (_ : AEStronglyMeasurable (f i) μ) hgmeas : ∀ (i : ι), StronglyMeasurable (g i) hgeq : ∀ (i : ι), g i =ᵐ[μ] f i hgℒp : Memℒp (g j) p ⊢ UniformIntegrable f p μ [PROOFSTEP] exact UniformIntegrable.ae_eq (Memℒp.uniformIntegrable_of_identDistrib_aux hp hp' hgℒp hgmeas fun i => (IdentDistrib.of_ae_eq (hgmeas i).aemeasurable (hgeq i)).trans ((hf i).trans <| IdentDistrib.of_ae_eq (hfmeas j).aemeasurable (hgeq j).symm)) hgeq
Formal statement is: lemma enum_strict_mono: "i \<le> n \<Longrightarrow> j \<le> n \<Longrightarrow> enum i < enum j \<longleftrightarrow> i < j" Informal statement is: If $i \leq n$ and $j \leq n$, then $i < j$ if and only if $enum(i) < enum(j)$.
# --- # title: 300. Longest Increasing Subsequence # id: problem300 # author: Tian Jun # date: 2020-10-31 # difficulty: Medium # categories: Binary Search, Dynamic Programming # link: <https://leetcode.com/problems/longest-increasing-subsequence/description/> # hidden: true # --- # # Given an integer array `nums`, return the length of the longest strictly # increasing subsequence. # # A **subsequence** is a sequence that can be derived from an array by deleting # some or no elements without changing the order of the remaining elements. For # example, `[3,6,2,7]` is a subsequence of the array `[0,3,1,6,2,2,7]`. # # # # **Example 1:** # # # # Input: nums = [10,9,2,5,3,7,101,18] # Output: 4 # Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. # # # **Example 2:** # # # # Input: nums = [0,1,0,3,2,3] # Output: 4 # # # **Example 3:** # # # # Input: nums = [7,7,7,7,7,7,7] # Output: 1 # # # # # **Constraints:** # # * `1 <= nums.length <= 2500` # * `-104 <= nums[i] <= 104` # # # # **Follow up:** # # * Could you come up with the `O(n2)` solution? # * Could you improve it to `O(n log(n))` time complexity? # # ## @lc code=start using LeetCode ## add your code here: ## @lc code=end