Datasets:
AI4M
/

text
stringlengths
0
3.34M
#include <boost/test/unit_test.hpp> #include "test_utils.hpp" #include <moreorg/utils/CoalitionStructureGeneration.hpp> using namespace multiagent::utils; void updateCostMap(std::map<Coalition, double>& costMap, const std::string& desc, double cost) { Coalition c; for(size_t i = 0; i < desc.size(); ++i) { std::string name = desc.substr(i,1); c.push_back(name); } std::sort(c.begin(), c.end()); costMap[c] = cost; } double coalitionValueFunction(const Coalition& coalition) { // return coalition.size(); Coalition c = coalition; std::sort(c.begin(), c.end()); std::map<Coalition, double> costMap; updateCostMap(costMap, "a", 125.0); updateCostMap(costMap, "b", 50.0); updateCostMap(costMap, "c", 75.0); updateCostMap(costMap, "d", 150); for(char i = 'e'; i < 'z'; ++i) { updateCostMap(costMap, std::string(1, i), 100); } updateCostMap(costMap, "ab", 176); updateCostMap(costMap, "ac", 150); updateCostMap(costMap, "ad", 100); updateCostMap(costMap, "bc", 150); updateCostMap(costMap, "bd", 200); updateCostMap(costMap, "cd", 125); updateCostMap(costMap, "de", 425); updateCostMap(costMap, "abc", 200); updateCostMap(costMap, "abd", 150); updateCostMap(costMap, "acd", 220); updateCostMap(costMap, "bcd", 150); updateCostMap(costMap, "abcd", 325); updateCostMap(costMap, "efghijklm", 1400); updateCostMap(costMap, "opqr", 5400); updateCostMap(costMap, "stuvwxyz", 15400); // std::map<Coalition, double>::const_iterator cit = costMap.begin(); // for(; cit != costMap.end(); ++cit) // { // Coalition c = cit->first; // std::string s; // for(size_t i = 0; i < c.size(); ++i) // { // s += c[i]; // } // BOOST_TEST_MESSAGE("Return value: " << cit->second << " for " << s); // } std::map<Coalition, double>::const_iterator cit = costMap.find(coalition); if(cit != costMap.end()) { return cit->second; } else { double value = coalition.size()*coalition.size(); return value; } } double coalitionStructureValueFunction(const CoalitionStructure& c) { double value = 0.0; for(int i = 0; i < c.size(); ++i) { value += coalitionValueFunction( c[i] ); } return value; } BOOST_AUTO_TEST_CASE(it_should_compute_csg) { AgentList agents; char numberOfAgents = 3; for(char a = 'a'; a < 'a' + numberOfAgents; ++a) { std::stringstream ss; ss << a; agents.push_back(ss.str()); } CoalitionStructureGeneration csg(agents, coalitionValueFunction, coalitionStructureValueFunction); BOOST_TEST_MESSAGE("Preparation done: " << csg.toString()); csg.anytimeSearch(1.0); while(!csg.anytimeSearchCompleted()) { sleep(1); BOOST_TEST_MESSAGE("Intermediate result: " << CoalitionStructureGeneration::toString( csg.currentBestSolution()) << ", value: " << coalitionStructureValueFunction(csg.currentBestSolution()) << ", quality: " << csg.currentBestSolutionQuality() ); } BOOST_TEST_MESSAGE("Final result: " << CoalitionStructureGeneration::toString(csg.currentBestSolution()) << ", value: " << coalitionStructureValueFunction(csg.currentBestSolution()) ); csg.reset(); BOOST_TEST_MESSAGE("Reset done: " << csg.toString()); CoalitionStructure cs = csg.findBest(1.0); BOOST_TEST_MESSAGE("Found best: " << CoalitionStructureGeneration::toString(cs) << ", value: " << coalitionStructureValueFunction(cs)); } BOOST_AUTO_TEST_CASE(it_should_compute_csg_anytime) { AgentList agents; char numberOfAgents = 8; for(char a = 'a'; a < 'a' + numberOfAgents; ++a) { std::stringstream ss; ss << a; agents.push_back(ss.str()); } CoalitionStructureGeneration csg(agents, coalitionValueFunction, coalitionStructureValueFunction); BOOST_TEST_MESSAGE("Preparation done: " << csg.toString()); csg.anytimeSearch(1.0); while(!csg.anytimeSearchCompleted()) { sleep(1); BOOST_TEST_MESSAGE("Intermediate result: " << CoalitionStructureGeneration::toString( csg.currentBestSolution()) << ", value: " << coalitionStructureValueFunction(csg.currentBestSolution()) << ", quality: " << csg.currentBestSolutionQuality() ); BOOST_TEST_MESSAGE(" " << csg.getStatistics().toString()); } BOOST_TEST_MESSAGE("Final result: " << CoalitionStructureGeneration::toString(csg.currentBestSolution()) << ", value: " << coalitionStructureValueFunction(csg.currentBestSolution()) ); }
# coding=utf-8 from contracts import check, contract import numpy as np # TODO: write tests @contract(X='array[KxN],K>=2,K<N', Y='array[KxN]', returns='array[KxK],orthogonal') def best_orthogonal_transform(X, Y): ''' Finds the best orthogonal transform R between X and Y, such that R X ~= Y. ''' YX = np.dot(Y, X.T) check('array[KxK]', YX) U, _, V = np.linalg.svd(YX) best = np.dot(U, V) return best @contract(M='array[NxN]', returns='array[NxN],orthogonal') def closest_orthogonal_matrix(M): ''' Finds the closest orthogonal matrix to M. ''' U, _, V = np.linalg.svd(M) R = np.dot(U, V) return R # TODO: write tests @contract(X='array[KxN],K>=2,K<N', Y='array[KxN]', returns='tuple( (array[KxK],orthogonal), array[Kx1])') def best_similarity_transform(X, Y): ''' Finds the best transform (R,t) between X and Y, such that R X + t ~= Y. ''' K = X.shape[0] Xm = X.mean(axis=1).reshape(K, 1) Ym = Y.mean(axis=1).reshape(K, 1) X = X - Xm Y = Y - Ym # assert_allclose(X.mean(axis=1), 0, atol=1e-8) # assert_allclose(Y.mean(axis=1), 0, atol=1e-8) YX = np.dot(Y, X.T) check('array[KxK]', YX) U, _, V = np.linalg.svd(YX) R = np.dot(U, V) t = Ym - np.dot(R, Xm) return R, t
module MapsMocks using CellwiseValues export MockMap export TestMap import CellwiseValues: evaluate! import CellwiseValues: return_size struct MockMap{P} <: Map{P,1,P,1} val::P end function evaluate!( this::MockMap{P}, points::AbstractVector{P}, v::AbstractVector{P}) where P for (i,qi) in enumerate(points) v[i] = qi+this.val end end return_size(::MockMap, psize::Tuple{Int}) = psize struct TestMap{P} <: Map{P,1,P,2} val::P dim::Int end function evaluate!( this::TestMap{P}, points::AbstractVector{P}, v::AbstractMatrix{P}) where P for j in 1:this.dim for (i,qi) in enumerate(points) v[j,i] = j*qi+this.val end end end return_size(this::TestMap, psize::Tuple{Int}) = (this.dim, psize[1]) end # module
Require Import Mem. Require Import Word. Require Import Ascii. Require Import String. Require Import Dir. Require Import Omega. Require Import Prog. Require Import BasicProg. Require Import Pred PredCrash. Require Import Hoare. Require Import SepAuto. Require Import Log. Require Import BFile. Require Import GenSepN. Require Import ListPred. Require Import MemMatch. Require Import FunctionalExtensionality. Require Import ListUtils. Require Import AsyncDisk. Require Import Errno. Require Import DirName. Require Import Structures.OrderedType. Require Import Structures.OrderedTypeEx. Require Import StringUtils. Require Import MapUtils. Require List. Set Implicit Arguments. Module CacheOneDir. Notation MSLL := BFILE.MSLL. Notation MSAlloc := BFILE.MSAlloc. Notation MSCache := BFILE.MSCache. Notation MSAllocC := BFILE.MSAllocC. Notation MSIAllocC := BFILE.MSIAllocC. Notation MSDBlocks := BFILE.MSDBlocks. Definition empty_cache : Dcache_type := Dcache.empty _. Fixpoint fill_cache' (files: (list (string * (addr * bool)))) ocache : Dcache_type := match files with | nil => ocache | f::files' => fill_cache' files' (Dcache.add (fst f) (snd f) ocache) end. Definition fill_cache files := fill_cache' files empty_cache. Definition init_cache lxp ixp dnum ms := let^ (ms, files) <- SDIR.readdir lxp ixp dnum ms; let ocache := fill_cache files in ms <- BFILE.cache_put dnum (ocache, 0) ms; AlertModified;; Ret ^(ms, (ocache, 0)). Definition get_dcache' (lxp:FSLayout.log_xparams) (ixp:Inode.INODE.IRecSig.xparams) dnum ms := let^ (ms, ocache) <- BFILE.cache_get dnum ms; match ocache with | None => ms <- BFILE.cache_put dnum (Dcache.empty _, 0) ms; Ret ^(ms, (Dcache.empty _, 0)) | Some r => Ret ^(ms, r) end. Definition get_dcache lxp ixp dnum ms := let^ (ms, ocache) <- BFILE.cache_get dnum ms; match ocache with | None => let^ (ms, r0) <- init_cache lxp ixp dnum ms; Ret ^(ms, r0) | Some r => Ret ^(ms, r) end. Definition lookup lxp ixp dnum name ms := let^ (ms, cache) <- get_dcache lxp ixp dnum ms; let r := Dcache.find name (fst cache) in Ret ^(ms, r). Definition unlink lxp ixp dnum name ms := let^ (ms, cache) <- get_dcache lxp ixp dnum ms; match (Dcache.find name (fst cache)) with | None => Ret ^(ms, Err ENOENT) | Some _ => let^ (ms, ix, r) <- SDIR.unlink lxp ixp dnum name ms; ms <- BFILE.cache_put dnum (Dcache.remove name (fst cache), ix) ms; Ret ^(ms, r) end. (* link assuming no name conflict *) Definition link' lxp bxp ixp dnum name inum isdir ms := let^ (ms, cache) <- get_dcache lxp ixp dnum ms; let^ (ms, ix, r) <- SDIR.link lxp bxp ixp dnum name inum isdir (snd cache) ms; match r with | Err _ => Ret ^(ms, r) | OK _ => ms <- BFILE.cache_put dnum (Dcache.add name (inum, isdir) (fst cache), ix) ms; Ret ^(ms, r) end. Definition link lxp bxp ixp dnum name inum isdir ms := let^ (ms, lookup_res) <- lookup lxp ixp dnum name ms; match lookup_res with | Some _ => Ret ^(ms, Err EEXIST) | None => let^ (ms, r) <- link' lxp bxp ixp dnum name inum isdir ms; Ret ^(ms, r) end. Definition readdir lxp ixp dnum ms := let^ (ms, r) <- SDIR.readdir lxp ixp dnum ms; Ret ^(ms, r). Definition rep f (dsmap : @mem string string_dec (addr * bool)) : Prop := SDIR.rep f dsmap /\ (forall cache hint, BFILE.BFCache f = Some (cache, hint) -> forall name, Dcache.find name cache = dsmap name). Definition rep_macro Fi Fm m bxp ixp (inum : addr) dsmap ilist frees f ms sm : @pred _ addr_eq_dec valuset := (exists flist, [[[ m ::: Fm * BFILE.rep bxp sm ixp flist ilist frees (BFILE.MSAllocC ms) (BFILE.MSCache ms) (BFILE.MSICache ms) (BFILE.MSDBlocks ms) ]]] * [[[ flist ::: Fi * inum |-> f ]]] * [[ rep f dsmap ]])%pred. Local Hint Unfold rep rep_macro SDIR.rep_macro : hoare_unfold. Lemma rep_mem_eq : forall f m1 m2, rep f m1 -> rep f m2 -> m1 = m2. Proof. unfold rep. intuition eauto using SDIR.rep_mem_eq. Qed. Theorem bfile0_empty : rep BFILE.bfile0 empty_mem. Proof. unfold rep; intuition. apply SDIR.bfile0_empty. cbn in *. congruence. Qed. Theorem crash_rep : forall f f' m, BFILE.file_crash f f' -> rep f m -> rep f' m. Proof. unfold rep; intuition. eapply SDIR.crash_rep; eauto. inversion H; intuition subst; cbn in *. congruence. Qed. Hint Resolve Dcache.find_2. Lemma readmatch_neq: forall F a b m, (F * SDIR.readmatch a * SDIR.readmatch b)%pred m -> fst a <> fst b. Proof. unfold_sep_star. unfold SDIR.readmatch, ptsto. destruct a, b; cbn. intros. repeat deex. apply mem_disjoint_union in H. contradiction H. eauto. Qed. Lemma fill_cache'_add_comm : forall entries a cache F, F * listpred SDIR.readmatch (a :: entries) =p=> F * listpred SDIR.readmatch (a :: entries) * [[ Dcache.Equal (fill_cache' (a :: entries) cache) (Dcache.add (fst a) (snd a) (fill_cache' entries cache)) ]]. Proof. unfold Dcache.Equal; simpl. induction entries; intros; simpl. cancel. do 2 intro; pred_apply; cancel. enough (fst a <> fst a0). all : repeat match goal with | _ => reflexivity | [ H: _ |- _ ] => rewrite H; clear H | [ |- context [Dcache.find ?k1 (Dcache.add ?k2 _ _)] ] => progress (rewrite ?DcacheDefs.MapFacts.add_eq_o, ?DcacheDefs.MapFacts.add_neq_o by auto) || destruct (string_dec k1 k2); subst | [ |- context [Dcache.find _ (fill_cache' _ (Dcache.add (fst ?a) _ _))] ] => eapply pimpl_trans in H as ?; [ | | apply (IHentries a)]; try cancel; destruct_lifts end. eapply readmatch_neq with (m := m). pred_apply; cancel. Qed. Lemma fill_cache_correct: forall entries dmap, let cache := (fill_cache entries) in listpred SDIR.readmatch entries dmap -> forall name, Dcache.find name cache = dmap name. Proof. unfold fill_cache. induction entries; cbn; intros. intuition congruence. eapply pimpl_trans in H; [ | | apply fill_cache'_add_comm with (F := emp)]; try cancel. destruct_lifts. revert H. unfold_sep_star. unfold SDIR.readmatch at 1, ptsto. intros. repeat deex; cbn in *. rewrite H2. rewrite DcacheDefs.MapFacts.add_o. destruct string_dec; subst. erewrite mem_union_addr; eauto. rewrite mem_union_sel_r; eauto. Qed. Ltac subst_cache := repeat match goal with | [ H : Some _ = Some _ |- _ ] => inversion H; clear H; subst | [ H1 : BFILE.BFCache ?f = _ , H2 : BFILE.BFCache ?F = _ |- _ ] => rewrite H1 in H2 end. Theorem init_cache_ok : forall bxp lxp ixp dnum ms, {< F Fi Fm m0 sm m dmap ilist frees f, PRE:hm LOG.rep lxp F (LOG.ActiveTxn m0 m) (MSLL ms) sm hm * rep_macro Fi Fm m bxp ixp dnum dmap ilist frees f ms sm POST:hm' RET:^(ms', cache) exists f', LOG.rep lxp F (LOG.ActiveTxn m0 m) (MSLL ms') sm hm' * rep_macro Fi Fm m bxp ixp dnum dmap ilist frees f' ms' sm * [[ BFILE.BFCache f' = Some cache ]] * [[ MSAlloc ms' = MSAlloc ms ]] * [[ MSAllocC ms' = MSAllocC ms ]] * [[ MSIAllocC ms' = MSIAllocC ms ]] * [[ MSDBlocks ms' = MSDBlocks ms ]] CRASH:hm' LOG.intact lxp F m0 sm hm' >} init_cache lxp ixp dnum ms. Proof. unfold init_cache, rep_macro. hoare. msalloc_eq. cancel. cbn in *. subst_cache. eauto using fill_cache_correct. Qed. Hint Extern 1 ({{_}} Bind (init_cache _ _ _ _) _) => apply init_cache_ok : prog. Theorem get_dcache_ok : forall lxp ixp dnum ms, {< F Fi Fm m0 sm m dmap ilist frees bxp f, PRE:hm LOG.rep lxp F (LOG.ActiveTxn m0 m) (MSLL ms) sm hm * rep_macro Fi Fm m bxp ixp dnum dmap ilist frees f ms sm POST:hm' RET:^(ms', cache) exists f', LOG.rep lxp F (LOG.ActiveTxn m0 m) (MSLL ms') sm hm' * rep_macro Fi Fm m bxp ixp dnum dmap ilist frees f' ms' sm * [[ MSAlloc ms' = MSAlloc ms ]] * [[ MSAllocC ms' = MSAllocC ms ]] * [[ MSIAllocC ms' = MSIAllocC ms ]] * [[ MSDBlocks ms' = MSDBlocks ms ]] * [[ BFILE.BFCache f' = Some cache ]] CRASH:hm' LOG.intact lxp F m0 sm hm' >} get_dcache lxp ixp dnum ms. Proof. unfold get_dcache, rep_macro. hoare. Unshelve. all: eauto. Qed. Hint Extern 1 ({{_}} Bind (get_dcache _ _ _ _) _) => apply get_dcache_ok : prog. Theorem lookup_ok : forall lxp bxp ixp dnum name ms, {< F Fi Fm m0 sm m dmap ilist frees f, PRE:hm LOG.rep lxp F (LOG.ActiveTxn m0 m) (MSLL ms) sm hm * rep_macro Fi Fm m bxp ixp dnum dmap ilist frees f ms sm POST:hm' RET:^(ms', r) exists f', LOG.rep lxp F (LOG.ActiveTxn m0 m) (MSLL ms') sm hm' * rep_macro Fi Fm m bxp ixp dnum dmap ilist frees f' ms' sm * [[ MSAlloc ms' = MSAlloc ms ]] * [[ MSAllocC ms' = MSAllocC ms ]] * [[ MSIAllocC ms' = MSIAllocC ms ]] * [[ MSDBlocks ms' = MSDBlocks ms ]] * ( [[ r = None /\ notindomain name dmap ]] \/ exists inum isdir Fd, [[ r = Some (inum, isdir) /\ inum <> 0 /\ (Fd * name |-> (inum, isdir))%pred dmap ]]) * [[ True ]] CRASH:hm' LOG.intact lxp F m0 sm hm' >} lookup lxp ixp dnum name ms. Proof. unfold lookup. hoare. subst_cache. denote (Dcache.find) as Hf. denote (BFILE.BFCache _ = _) as Hb. erewrite Hf in * by eauto. destruct (dmap name) eqn:?; [ or_r | or_l ]. assert (fst p <> 0). destruct p; cbn in *. intro; subst; eauto using SDIR.rep_no_0_inum. repeat ( denote! (SDIR.rep _ _) as Hx; clear Hx ). cancel. eauto using any_sep_star_ptsto. cancel. Unshelve. all: repeat (solve [eauto] || constructor). Qed. Hint Extern 1 ({{_}} Bind (lookup _ _ _ _ _) _) => apply lookup_ok : prog. Theorem readdir_ok : forall lxp bxp ixp dnum ms, {< F Fi Fm m0 sm m dmap ilist frees f, PRE:hm LOG.rep lxp F (LOG.ActiveTxn m0 m) (MSLL ms) sm hm * rep_macro Fi Fm m bxp ixp dnum dmap ilist frees f ms sm POST:hm' RET:^(ms', r) rep_macro Fi Fm m bxp ixp dnum dmap ilist frees f ms' sm * LOG.rep lxp F (LOG.ActiveTxn m0 m) (MSLL ms') sm hm' * [[ listpred SDIR.readmatch r dmap ]] * [[ MSAlloc ms' = MSAlloc ms ]] * [[ MSCache ms' = MSCache ms ]] * [[ MSAllocC ms' = MSAllocC ms ]] * [[ MSIAllocC ms' = MSIAllocC ms ]] * [[ True ]] CRASH:hm' exists ms', LOG.rep lxp F (LOG.ActiveTxn m0 m) (MSLL ms') sm hm' >} readdir lxp ixp dnum ms. Proof. unfold readdir, rep_macro, rep. intros. ProgMonad.monad_simpl_one. eapply pimpl_ok2. eauto with prog. unfold SDIR.rep_macro. cancel; eauto. step. Qed. Theorem unlink_ok : forall lxp bxp ixp dnum name ms, {< F Fi Fm m0 sm m dmap ilist frees f, PRE:hm LOG.rep lxp F (LOG.ActiveTxn m0 m) (MSLL ms) sm hm * rep_macro Fi Fm m bxp ixp dnum dmap ilist frees f ms sm POST:hm' RET:^(ms', r) exists m' dmap' f', LOG.rep lxp F (LOG.ActiveTxn m0 m') (MSLL ms') sm hm' * rep_macro Fi Fm m' bxp ixp dnum dmap' ilist frees f' ms' sm * [[ dmap' = mem_except dmap name ]] * [[ notindomain name dmap' ]] * [[ r = OK tt -> indomain name dmap ]] * [[ MSAlloc ms' = MSAlloc ms ]] * [[ MSAllocC ms' = MSAllocC ms ]] * [[ MSIAllocC ms' = MSIAllocC ms ]] * [[ True ]] CRASH:hm' LOG.intact lxp F m0 sm hm' >} unlink lxp ixp dnum name ms. Proof. unfold unlink. hoare; msalloc_eq; cbn in *; subst_cache. - cancel. - unfold mem_except; cbn [fst snd]. rewrite DcacheDefs.MapFacts.remove_o. denote (Dcache.find) as Hf. repeat destruct string_dec; (congruence || eauto). - cbn in *. rewrite mem_except_none; eauto. denote (Dcache.find) as Hf. erewrite Hf in *; eauto. - intros m' ?. replace m' with dmap in * by (eauto using SDIR.rep_mem_eq). denote (Dcache.find) as Hf. erewrite Hf in *; eauto. Unshelve. all: eauto. Qed. Lemma sdir_rep_cache : forall f c m, SDIR.rep f m -> SDIR.rep {| BFILE.BFData := BFILE.BFData f; BFILE.BFAttr := BFILE.BFAttr f; BFILE.BFCache := c |} m. Proof. unfold SDIR.rep, DIR.rep, DIR.Dent.rep, DIR.Dent.items_valid, DIR.Dent.RA.RALen; eauto. Qed. Hint Resolve sdir_rep_cache. Theorem link'_ok : forall lxp bxp ixp dnum name inum isdir ms, {< F Fi Fm m0 sm m dmap ilist frees f, PRE:hm LOG.rep lxp F (LOG.ActiveTxn m0 m) (MSLL ms) sm hm * rep_macro Fi Fm m bxp ixp dnum dmap ilist frees f ms sm * [[ notindomain name dmap ]] * [[ goodSize addrlen inum ]] * [[ inum <> 0 ]] POST:hm' RET:^(ms', r) exists m', [[ MSAlloc ms' = MSAlloc ms ]] * [[ MSIAllocC ms' = MSIAllocC ms ]] * (([[ isError r ]] * LOG.rep lxp F (LOG.ActiveTxn m0 m') (MSLL ms') sm hm') \/ ([[ r = OK tt ]] * exists dmap' Fd ilist' frees' f', LOG.rep lxp F (LOG.ActiveTxn m0 m') (MSLL ms') sm hm' * rep_macro Fi Fm m' bxp ixp dnum dmap' ilist' frees' f' ms' sm * [[ dmap' = Mem.upd dmap name (inum, isdir) ]] * [[ (Fd * name |-> (inum, isdir))%pred dmap' ]] * [[ (Fd dmap /\ notindomain name dmap) ]] * [[ BFILE.ilist_safe ilist (BFILE.pick_balloc frees (MSAlloc ms')) ilist' (BFILE.pick_balloc frees' (MSAlloc ms')) ]] * [[ BFILE.treeseq_ilist_safe dnum ilist ilist' ]] )) CRASH:hm' LOG.intact lxp F m0 sm hm' >} link' lxp bxp ixp dnum name inum isdir ms. Proof. unfold link'. hoare. msalloc_eq. subst_cache. or_r. cancel; eauto. cbn in *; subst_cache. cbv [fst snd upd]. rewrite DcacheDefs.MapFacts.add_o. repeat destruct string_dec; (congruence || eauto). Unshelve. all : try exact Balloc.BALLOCC.Alloc.freelist0. all : eauto. Qed. Hint Extern 0 ({{ _ }} Bind (link' _ _ _ _ _ _ _ _) _) => apply link'_ok : prog. Theorem link_ok : forall lxp bxp ixp dnum name inum isdir ms, {< F Fi Fm m0 sm m dmap ilist frees f, PRE:hm LOG.rep lxp F (LOG.ActiveTxn m0 m) (MSLL ms) sm hm * rep_macro Fi Fm m bxp ixp dnum dmap ilist frees f ms sm * [[ goodSize addrlen inum ]] * [[ inum <> 0 ]] POST:hm' RET:^(ms', r) exists m', [[ MSAlloc ms' = MSAlloc ms ]] * [[ MSIAllocC ms' = MSIAllocC ms ]] * (([[ isError r ]] * LOG.rep lxp F (LOG.ActiveTxn m0 m') (MSLL ms') sm hm') \/ ([[ r = OK tt ]] * exists dmap' Fd ilist' frees' f', LOG.rep lxp F (LOG.ActiveTxn m0 m') (MSLL ms') sm hm' * rep_macro Fi Fm m' bxp ixp dnum dmap' ilist' frees' f' ms' sm * [[ dmap' = Mem.upd dmap name (inum, isdir) ]] * [[ (Fd * name |-> (inum, isdir))%pred dmap' ]] * [[ (Fd dmap /\ notindomain name dmap) ]] * [[ BFILE.ilist_safe ilist (BFILE.pick_balloc frees (MSAlloc ms')) ilist' (BFILE.pick_balloc frees' (MSAlloc ms')) ]] * [[ BFILE.treeseq_ilist_safe dnum ilist ilist' ]] )) CRASH:hm' LOG.intact lxp F m0 sm hm' >} link lxp bxp ixp dnum name inum isdir ms. Proof. unfold link. hoare. Unshelve. all: eauto. Qed. Hint Extern 1 ({{_}} Bind (unlink _ _ _ _ _) _) => apply unlink_ok : prog. Hint Extern 1 ({{_}} Bind (link _ _ _ _ _ _ _ _) _) => apply link_ok : prog. Hint Extern 1 ({{_}} Bind (readdir _ _ _ _) _) => apply readdir_ok : prog. End CacheOneDir.
''' Crop an image Author: Filippo Aleotti Mail: [email protected] ''' from general.filter import GeneralFilter import tensorflow as tf import numpy as np class Cropper(GeneralFilter): def __init__(self, params): super(Cropper, self).__init__(params) self.crop_width = self.filter_params[self.name]['width'] self.crop_height =self.filter_params[self.name]['height'] self.final_dimensions = self.filter_params[self.name]['final_dimensions'] def filter(self, list_of_samples): ''' Crop a list of samples ''' with tf.variable_scope('cropper_filter'): summed_dimension = np.sum(self.final_dimensions) crops = tf.random_crop(tf.concat([sample for sample in list_of_samples], -1), [self.crop_height, self.crop_width, summed_dimension]) splits = tf.split(crops, self.final_dimensions, -1) with tf.variable_scope('set_shapes'): splits[0].set_shape([self.crop_height, self.crop_width, self.final_dimensions[0]]) #left_t0 splits[1].set_shape([self.crop_height, self.crop_width, self.final_dimensions[1]]) #right_t0 splits[2].set_shape([self.crop_height, self.crop_width, self.final_dimensions[2]]) #left_t1 splits[3].set_shape([self.crop_height, self.crop_width, self.final_dimensions[3]]) #right_t1 splits[4].set_shape([self.crop_height, self.crop_width, self.final_dimensions[4]]) #disp_t0 splits[5].set_shape([self.crop_height, self.crop_width, self.final_dimensions[5]]) #disp_t01 splits[6].set_shape([self.crop_height, self.crop_width, self.final_dimensions[6]]) #gt_flow return splits def _set_name(self): return 'cropping_params'
{-# OPTIONS --safe #-} module Cubical.Algebra.Lattice.Properties where open import Cubical.Foundations.Prelude open import Cubical.Foundations.Equiv open import Cubical.Foundations.Equiv.HalfAdjoint open import Cubical.Foundations.HLevels open import Cubical.Foundations.Isomorphism open import Cubical.Foundations.Univalence open import Cubical.Foundations.Transport open import Cubical.Foundations.SIP open import Cubical.Data.Sigma open import Cubical.Structures.Axioms open import Cubical.Structures.Auto open import Cubical.Structures.Macro open import Cubical.Algebra.Semigroup open import Cubical.Algebra.Monoid open import Cubical.Algebra.CommMonoid open import Cubical.Algebra.Semilattice open import Cubical.Algebra.Lattice.Base open import Cubical.Relation.Binary.Poset private variable ℓ : Level module LatticeTheory (L' : Lattice ℓ) where private L = fst L' open LatticeStr (snd L') 0lLeftAnnihilates∧l : ∀ (x : L) → 0l ∧l x ≡ 0l 0lLeftAnnihilates∧l x = 0l ∧l x ≡⟨ cong (0l ∧l_) (sym (∨lLid _)) ⟩ 0l ∧l (0l ∨l x) ≡⟨ ∧lAbsorb∨l _ _ ⟩ 0l ∎ 0lRightAnnihilates∧l : ∀ (x : L) → x ∧l 0l ≡ 0l 0lRightAnnihilates∧l _ = ∧lComm _ _ ∙ 0lLeftAnnihilates∧l _ 1lLeftAnnihilates∨l : ∀ (x : L) → 1l ∨l x ≡ 1l 1lLeftAnnihilates∨l x = 1l ∨l x ≡⟨ cong (1l ∨l_) (sym (∧lLid _)) ⟩ 1l ∨l (1l ∧l x) ≡⟨ ∨lAbsorb∧l _ _ ⟩ 1l ∎ 1lRightAnnihilates∨l : ∀ (x : L) → x ∨l 1l ≡ 1l 1lRightAnnihilates∨l _ = ∨lComm _ _ ∙ 1lLeftAnnihilates∨l _ module Order (L' : Lattice ℓ) where private L = fst L' open LatticeStr (snd L') open JoinSemilattice (Lattice→JoinSemilattice L') renaming (_≤_ to _≤j_ ; IndPoset to JoinPoset) open MeetSemilattice (Lattice→MeetSemilattice L') renaming (_≤_ to _≤m_ ; IndPoset to MeetPoset) ≤j→≤m : ∀ x y → x ≤j y → x ≤m y ≤j→≤m x y x∨ly≡y = x ∧l y ≡⟨ cong (x ∧l_) (sym x∨ly≡y) ⟩ x ∧l (x ∨l y) ≡⟨ ∧lAbsorb∨l _ _ ⟩ x ∎ ≤m→≤j : ∀ x y → x ≤m y → x ≤j y ≤m→≤j x y x∧ly≡x = x ∨l y ≡⟨ ∨lComm _ _ ⟩ y ∨l x ≡⟨ cong (y ∨l_) (sym x∧ly≡x) ⟩ y ∨l (x ∧l y) ≡⟨ cong (y ∨l_) (∧lComm _ _) ⟩ y ∨l (y ∧l x) ≡⟨ ∨lAbsorb∧l _ _ ⟩ y ∎ ≤Equiv : ∀ (x y : L) → (x ≤j y) ≃ (x ≤m y) ≤Equiv x y = propBiimpl→Equiv (isSetLattice L' _ _) (isSetLattice L' _ _) (≤j→≤m x y) (≤m→≤j x y) IndPosetPath : JoinPoset ≡ MeetPoset IndPosetPath = PosetPath _ _ .fst ((idEquiv _) , isposetequiv ≤Equiv ) -- transport inequalities from ≤m to ≤j ∧lIsMinJoin : ∀ x y z → z ≤j x → z ≤j y → z ≤j x ∧l y ∧lIsMinJoin _ _ _ z≤jx z≤jy = ≤m→≤j _ _ (∧lIsMin _ _ _ (≤j→≤m _ _ z≤jx) (≤j→≤m _ _ z≤jy)) ∧≤LCancelJoin : ∀ x y → x ∧l y ≤j y ∧≤LCancelJoin x y = ≤m→≤j _ _ (∧≤LCancel x y) module _ {L M : Lattice ℓ} (φ ψ : LatticeHom L M) where open LatticeStr ⦃...⦄ open IsLatticeHom private instance _ = L _ = M _ = snd L _ = snd M LatticeHom≡f : fst φ ≡ fst ψ → φ ≡ ψ LatticeHom≡f = Σ≡Prop λ f → isPropIsLatticeHom _ f _
#include <boost/test/data/index_sequence.hpp>
SUBROUTINE chstwo(bins1,bins2,nbins,knstrn,df,chsq,prob) INTEGER knstrn,nbins REAL*8 :: chsq,df,prob,bins1(nbins),bins2(nbins) !CU USES gammq INTEGER j REAL gammq df=nbins-knstrn chsq=0. do j=1,nbins if(bins1(j).eq.0..and.bins2(j).eq.0.)then df=df-1. else chsq=chsq+(bins1(j)-bins2(j))**2/(bins1(j)+bins2(j)) endif enddo prob=gammq(0.5*df,0.5*chsq) return END
Require Import Reals. Set Implicit Arguments. Open Local Scope R_scope. (* We require CR because we use it for Time. Todo: Take an arbitrary (C)Ring/(C)Field for Time, so that the classical development does not need a separate concrete module. *) Let Time := R. Let Duration := { r: R | r >= 0 }. Program Definition immediately: Duration := 0. Next Obligation. right. reflexivity. Defined. Program Definition duration_plus (d d': Duration): Duration := d + d'. Next Obligation. destruct d. destruct d'. simpl. replace 0 with (0+0). apply Rplus_ge_compat; auto. field. Qed. Record Flow (X: Set): Type := { flow_fun:> X -> Time -> X ; flow_zero: forall x, flow_fun x 0 = x ; flow_additive: forall x t t', flow_fun x (t + t') = flow_fun (flow_fun x t) t' }. Section product_flow. Variables (X Y: Set) (fx: Flow X) (fy: Flow Y). Let f (xy: X * Y) (t: Time): X * Y := (fx (fst xy) t, fy (snd xy) t). Definition product_flow: Flow (X * Y). Proof with auto. apply (Build_Flow f); destruct x; unfold f; simpl; intros. do 2 rewrite flow_zero... do 2 rewrite flow_additive... Defined. End product_flow.
-- Andreas, 2014-01-21, Issue 1209 reported by Andrea {-# OPTIONS --cubical-compatible #-} {-# OPTIONS --copatterns #-} {-# OPTIONS --sized-types #-} open import Common.Size record R (i : Size) : Set where coinductive field force : (j : Size< i) → R j postulate f : ∀ {i} → R i → R i t : (i : Size) → R i R.force (t i) j = f (t j) -- should termination check
module ia_vdw_m !! Routines to evaulate pairwise potentials and their derivative. !! !! The following styles are available: !! !! * Style 1. 12-6 LJ. See [[vdw_lj_set]]. !! * Style 2. Gaussian. See [[vdw_gaussian_set]]. !! * Style 3. Cosine. See [[vdw_cosine_set]]. !! * Style 4. Screened Coulomb + LJ. See [[vdw_lj_coul_debye_set]]. !! * Style 5. Coulomb + LJ. See [[vdw_lj_coul_set]]. !! * Style 6. Standard DPD. See [[vdw_dpd_set]]. use constants_m use atmcfg_m implicit none private public :: ia_vdw_setup, ia_get_vdw_force contains !****************************************************************************** subroutine ia_vdw_setup(num_vdw_types, vdw_styles, vdw_params) !! Sets up parameters for vdw potentials integer, intent(in) :: num_vdw_types !! Number of types of vdw interactions integer, dimension(:), intent(in) :: vdw_styles !! Styles for each type real(rp), dimension(:,:), intent(in out) :: vdw_params !! Parameters for each type, depending on style integer :: i, sty !Set vdw interactions do i = 1, num_vdw_types sty = vdw_styles(i) select case(sty) case(1) call vdw_lj_set(vdw_params(:,i)) case(2) call vdw_gaussian_set(vdw_params(:,i)) case(3) call vdw_cosine_set(vdw_params(:,i)) case(4) call vdw_lj_coul_debye_set(vdw_params(:,i)) case(5) call vdw_lj_coul_set(vdw_params(:,i)) case(6) call vdw_dpd_set(vdw_params(:,i)) case default continue end select end do end subroutine !****************************************************************************** subroutine ia_get_vdw_force(rij_mag, qi, qj, sty, params, enrg, frc, ierr) !! Calculates the energy & its derivative due to a single interacting pair of atoms. real(rp), intent(in) :: rij_mag !! Distance between two atoms real(rp), intent(in) :: qi !! Charge on atom i real(rp), intent(in) :: qj !! Charge on atom j integer, intent(in) :: sty !! Style of vdw interaction real(rp), dimension(:), intent(in) :: params !! Parameters for vdw interaction real(rp), intent(out) :: enrg !! Energy real(rp), intent(out) :: frc !! Derivative of the potential. This is the magnitude of force due to !! this potential. integer, intent(out) :: ierr !! Error flag ierr = 0; enrg = 0.0_rp; frc = 0.0_rp select case(sty) case(1) call vdw_lj(rij_mag, params, enrg, frc) case(2) call vdw_gaussian(rij_mag, params, enrg, frc) case(3) call vdw_cosine(rij_mag, params, enrg, frc) case(4) call vdw_lj_coul_debye(rij_mag, qi*qj, params, enrg, frc) case(5) call vdw_lj_coul(rij_mag, qi*qj, params, enrg, frc) case(6) call vdw_dpd(rij_mag, params, enrg, frc) case default continue end select end subroutine !****************************************************************************** subroutine vdw_lj_set(params, eps, sigma, rcut) !! Setter for 12-6 LJ (truncated & force-shifted) interaction. !! !! The potential `U` is given by: !!``` !! V = 4*eps*[(r/sigma)^12 - (r/sigma)^6] !! U = V - V(rcut) - (r - rcut)*dV/dr, r < rcut, !! 0, r >= rcut !!``` !! where `dV/dr` is evaluated at `r = rcut`. !! !! User-set parameters: !! !! * params(1) = `eps` !! * params(2) = `sigma` !! * params(3) = `rcut` !! !! Internally stored parameters: !! !! * params(4) = `V(rcut)` !! * params(5) = `dV/dr(rcut)` real(rp), dimension(:), intent(in out) :: params real(rp), intent(in), optional :: eps real(rp), intent(in), optional :: sigma real(rp), intent(in), optional :: rcut real(rp) :: eps_, sigma_, rcut_ real(rp) :: pot_rcut, pot_deriv_rcut real(rp) :: sir, sir2, sir6, sir12 if (present(eps)) params(1) = eps if (present(sigma)) params(2) = sigma if (present(rcut)) params(3) = rcut eps_ = params(1); sigma_ = params(2); rcut_ = params(3) sir = sigma_/rcut_ sir2 = sir*sir; sir6 = sir2*sir2*sir2; sir12 = sir6*sir6 pot_rcut = 4*eps_*(sir12 - sir6) pot_deriv_rcut = -24*eps_*(2*sir12 - sir6)/rcut_ params(4) = pot_rcut params(5) = pot_deriv_rcut end subroutine !****************************************************************************** pure subroutine vdw_lj(r, params, enrg, frc) !! Evaluates the potential and its derivative for LJ interaction. See !! [[vdw_lj_set]]. real(rp), intent(in) :: r real(rp), dimension(:), intent(in) :: params real(rp), intent(out) :: enrg real(rp), intent(out) :: frc real(rp) :: eps, sigma, rcut real(rp) :: pot_rcut, pot_deriv_rcut real(rp) :: sir, sir2, sir6, sir12 enrg = 0.0_rp; frc = 0.0_rp eps = params(1); sigma = params(2); rcut = params(3) pot_rcut = params(4) pot_deriv_rcut = params(5) if ( r < rcut ) then sir = sigma/r sir2 = sir*sir; sir6 = sir2*sir2*sir2; sir12 = sir6*sir6 enrg = 4*eps*(sir12 - sir6) - pot_rcut - (r - rcut)*pot_deriv_rcut frc = -24*eps*(2*sir12 - sir6)/r - pot_deriv_rcut end if end subroutine !****************************************************************************** subroutine vdw_gaussian_set(params, A, B, rcut) !! Setter for gaussian interaction. The potential is truncated and !! force-shifted. !! !! The potential `U` is given by: !!``` !! V = A*exp(-B*r^2) !! U = V - V(rcut) - (r - rcut)*dV/dr, r < rcut !! 0, r >= rcut, !!``` !! where `dV/dr` is evaluated at `r = rcut`. !! !! User-set parameters: !! !! * params(1) = `A` !! * params(2) = `B` !! * params(3) = `rcut` !! !! Internally stored parameters: !! !! * params(4) = `V(rcut)` !! * params(5) = `dV/dr(rcut)` real(rp), dimension(:), intent(in out) :: params real(rp), intent(in), optional :: A real(rp), intent(in), optional :: B real(rp), intent(in), optional :: rcut real(rp) :: pot_rcut, pot_deriv_rcut if (present(A)) params(1) = A if (present(B)) params(2) = B if (present(rcut)) params(3) = rcut pot_rcut = params(1)*exp(-params(2)*params(3)**2) pot_deriv_rcut = -2.0_rp*params(1)*params(2)*params(3) & * exp(-params(2)*params(3)**2) params(4) = pot_rcut params(5) = pot_deriv_rcut end subroutine !****************************************************************************** pure subroutine vdw_gaussian(r, params, enrg, frc) !! Calculates energy & its derivative for gaussian interaction. See !! [[vdw_gaussian_set]]. real(rp), intent(in) :: r real(rp), dimension(:), intent(in) :: params real(rp), intent(out) :: enrg real(rp), intent(out) :: frc real(rp) :: A, B, rcut, pot_rcut, pot_deriv_rcut real(rp) :: exrs enrg = 0.0_rp; frc = 0.0_rp A = params(1); B = params(2); rcut = params(3) pot_rcut = params(4); pot_deriv_rcut = params(5) if ( r < rcut ) then exrs = exp(-B*r*r) enrg = A*exrs - pot_rcut - (r - rcut)*pot_deriv_rcut frc = -2*A*B*r*exrs - pot_deriv_rcut end if end subroutine !****************************************************************************** subroutine vdw_cosine_set(params, A, rcut) !! Setter for cosine interaction. !! !! The potential `U` is given by: !!``` !! U = A*[1 + cos(pi*r/rcut)], r < rcut !! 0, r >= rcut !!``` !! The potential as well as its derivative is zero at `r = rcut`. !! !! User-set parameters: !! !! * params(1) = `A` !! * params(2) = `rcut` !! !! Internally stored parameters: !! !! * None real(rp), dimension(:), intent(in out) :: params real(rp), intent(in), optional :: A real(rp), intent(in), optional :: rcut if (present(A)) params(1) = A if (present(rcut)) params(2) = rcut end subroutine !****************************************************************************** pure subroutine vdw_cosine(r, params, enrg, frc) !! Evaluates the potential and its derivative for cosine interaction. !! See [[vdw_cosine_set]]. real(rp), intent(in) :: r real(rp), dimension(:), intent(in) :: params real(rp), intent(out) :: enrg real(rp), intent(out) :: frc real(rp) :: A, rcut, pf, pr enrg = 0.0_rp; frc = 0.0_rp A = params(1); rcut = params(2) pf = math_pi/rcut; pr = pf*r if ( r < rcut ) then enrg = A*( 1.0_rp + cos(pr) ) frc = -A*pf*sin(pr) end if end subroutine !****************************************************************************** subroutine vdw_lj_coul_debye_set(params, eps, sigma, rcut, rcut_coul, C, kappa) !! Setter for 12-6 LJ with screened Coulombic interaction. !! !! The potential `U` is given by: !!``` !! V = 4*eps*[(r/sigma)^12 - (r/sigma)^6] !! W = C*qi*qj*exp(-kappa*r)/r !! if rcut_coul > 0: !! U = V - V(rcut) + W - W(rcut_coul), r < rcut !! W - W(rcut_coul), rcut <= r < rcut_coul !! 0, r >= rcut_coul !! if rcut_coul <= 0: !! U = V - V(rcut) + W, r < rcut !! W, r >= rcut !!``` !! !!- The LJ potential `V` is cut & shifted at `r = rcut`. !!- If `rcut_coul > 0`, the screened Coulombic potential `W` is cut & shifted !! at `r = rcut_coul`. !!- If `rcut_coul <= 0`, no cutoff is applied on `W`. !!- `rcut_coul` must be >= `rcut`. !! !! User-set parameters: !! !! * params(1) = `eps` !! * params(2) = `sigma` !! * params(3) = `rcut` !! * params(4) = `rcut_coul` !! * params(5) = `C` !! * params(6) = `kappa` !! !! Internally stored parameters: !! !! * params(7) = `V(rcut)` !! * params(8) = `C*exp(-kappa*rcut_coul)/rcut_coul` real(rp), dimension(:), intent(in out) :: params real(rp), intent(in), optional :: eps real(rp), intent(in), optional :: sigma real(rp), intent(in), optional :: rcut real(rp), intent(in), optional :: rcut_coul real(rp), intent(in), optional :: C real(rp), intent(in), optional :: kappa real(rp) :: eps_, sigma_, rcut_, rcut_coul_, C_, kappa_ real(rp) :: pot_rcut, pot_rcut_coul real(rp) :: sir, sir2, sir6, sir12 if (present(eps)) params(1) = eps if (present(sigma)) params(2) = sigma if (present(rcut)) params(3) = rcut if (present(rcut_coul)) params(4) = rcut_coul if (present(C)) params(5) = C if (present(kappa)) params(6) = kappa eps_ = params(1); sigma_ = params(2); rcut_ = params(3) rcut_coul_ = params(4); C_ = params(5); kappa_ = params(6) sir = sigma_/rcut_ sir2 = sir*sir; sir6 = sir2*sir2*sir2; sir12 = sir6*sir6 pot_rcut = 4*eps_*(sir12 - sir6) if (rcut_coul_ > 0.0_rp) then pot_rcut_coul = C_*exp(-kappa_*rcut_coul_)/rcut_coul_ else pot_rcut_coul = 0.0_rp end if params(7) = pot_rcut params(8) = pot_rcut_coul end subroutine !****************************************************************************** pure subroutine vdw_lj_coul_debye(r, qiqj, params, enrg, frc) !!Evaluates the potential and its derivative for screened Coulombic interaction !!combined with 12-6 LJ (cut & shifted). See [[vdw_lj_coul_debye_set]]. real(rp), intent(in) :: r real(rp), intent(in) :: qiqj real(rp), dimension(:), intent(in) :: params real(rp), intent(out) :: enrg real(rp), intent(out) :: frc real(rp) :: eps, sigma, rcut, rcut_coul, C, kappa real(rp) :: pot_rcut, pot_rcut_coul real(rp) :: sir, sir2, sir6, sir12, ekr enrg = 0.0_rp; frc = 0.0_rp eps = params(1); sigma = params(2); rcut = params(3) rcut_coul = params(4); C = params(5); kappa = params(6) pot_rcut = params(7); pot_rcut_coul = params(8) ekr = C*qiqj*exp(-kappa*r)/r if (rcut_coul > 0.0_rp) then !Coulombic cutoff at rcut_coul if ( r < rcut_coul ) then enrg = ekr - qiqj*pot_rcut_coul frc = -ekr*(1+kappa*r)/r end if else !No Coulombic cutoff enrg = ekr frc = -ekr*(1+kappa*r)/r end if if ( r < rcut ) then sir = sigma/r sir2 = sir*sir; sir6 = sir2*sir2*sir2; sir12 = sir6*sir6 enrg = enrg + 4*eps*(sir12 - sir6) - pot_rcut frc = frc - 24*eps*(2*sir12 - sir6)/r end if end subroutine !****************************************************************************** subroutine vdw_lj_coul_set(params, eps, sigma, rcut, rcut_coul, C) !! Setter for 12-6 LJ with Coulombic interaction. !! !! The potential `U` is given by: !!``` !! V = 4*eps*[(r/sigma)^12 - (r/sigma)^6] !! W = C*qi*qj/r !! if rcut_coul > 0: !! U = V - V(rcut) + W - W(rcut_coul), r < rcut !! W - W(rcut_coul), rcut <= r < rcut_coul !! 0, r >= rcut_coul !! if rcut_coul <= 0: !! U = V - V(rcut) + W, r < rcut !! W, r >= rcut !!``` !! - The LJ potential `V` is cut & shifted at `r = rcut`. !! - If `rcut_coul > 0`, the Coulombic potential `W` is cut & shifted at `r = rcut_coul`. !! - If `rcut_coul <= 0`, no cutoff is applied on `W`. !! - `rcut_coul` must be >= `rcut`. !! !! User-set parameters: !! !! * params(1) = `eps` !! * params(2) = `sigma` !! * params(3) = `rcut` !! * params(4) = `rcut_coul` !! * params(5) = `C` !! !! Internally stored parameters: !! !! * params(6) = `V(rcut)` !! * params(7) = `C/rcut_coul` real(rp), dimension(:), intent(in out) :: params real(rp), intent(in), optional :: eps real(rp), intent(in), optional :: sigma real(rp), intent(in), optional :: rcut real(rp), intent(in), optional :: rcut_coul real(rp), intent(in), optional :: C real(rp) :: eps_, sigma_, rcut_, rcut_coul_, C_ real(rp) :: pot_rcut, pot_rcut_coul real(rp) :: sir, sir2, sir6, sir12 if (present(eps)) params(1) = eps if (present(sigma)) params(2) = sigma if (present(rcut)) params(3) = rcut if (present(rcut_coul)) params(4) = rcut_coul if (present(C)) params(5) = C eps_ = params(1); sigma_ = params(2); rcut_ = params(3) rcut_coul_ = params(4); C_ = params(5) sir = sigma_/rcut_ sir2 = sir*sir; sir6 = sir2*sir2*sir2; sir12 = sir6*sir6 pot_rcut = 4*eps_*(sir12 - sir6) if (rcut_coul_ > 0.0_rp) then pot_rcut_coul = C_/rcut_coul_ else pot_rcut_coul = 0.0_rp end if params(6) = pot_rcut params(7) = pot_rcut_coul end subroutine !****************************************************************************** pure subroutine vdw_lj_coul(r, qiqj, params, enrg, frc) !! Evaluates the potential and its derivative for Coulombic interaction !! combined with 12-6 LJ (cut & shifted). See [[vdw_lj_coul_set]]. real(rp), intent(in) :: r real(rp), intent(in) :: qiqj real(rp), dimension(:), intent(in) :: params real(rp), intent(out) :: enrg real(rp), intent(out) :: frc real(rp) :: eps, sigma, rcut, rcut_coul, C real(rp) :: pot_rcut, pot_rcut_coul real(rp) :: sir, sir2, sir6, sir12, ekr enrg = 0.0_rp; frc = 0.0_rp eps = params(1); sigma = params(2); rcut = params(3) rcut_coul = params(4); C = params(5) pot_rcut = params(6); pot_rcut_coul = params(7) ekr = C*qiqj/r if (rcut_coul > 0.0_rp) then !Coulombic cutoff at rcut_coul if ( r < rcut_coul ) then enrg = ekr - qiqj*pot_rcut_coul frc = -ekr/r end if else !No Coulombic cutoff enrg = ekr frc = -ekr/r end if if ( r < rcut ) then sir = sigma/r sir2 = sir*sir; sir6 = sir2*sir2*sir2; sir12 = sir6*sir6 enrg = enrg + 4*eps*(sir12 - sir6) - pot_rcut frc = frc - 24*eps*(2*sir12 - sir6)/r end if end subroutine !****************************************************************************** subroutine vdw_dpd_set(params, A, rcut) !! Setter for standard DPD interaction. !! !! The potential `U` is given by: !!``` !! U = (A/2)*rcut*(1 - (r/rcut))^2, r < rcut ! 0, r >= rcut !!``` !! !! User-set parameters: !! !! * params(1) = `A` !! * params(2) = `rcut` !! !! Internally stored parameters: !! !! * None real(rp), dimension(:), intent(in out) :: params real(rp), intent(in), optional :: A real(rp), intent(in), optional :: rcut if (present(A)) params(1) = A if (present(rcut)) params(2) = rcut end subroutine !****************************************************************************** pure subroutine vdw_dpd(r, params, enrg, frc) !! Evaluates the potential and its derivative for standard DPD interaction. !! See [[vdw_dpd_set]]. real(rp), intent(in) :: r real(rp), dimension(:), intent(in) :: params real(rp), intent(out) :: enrg real(rp), intent(out) :: frc real(rp) :: A, rcut, ir enrg = 0.0_rp; frc = 0.0_rp A = params(1); rcut = params(2) ir = 1.0_rp - (r/rcut) if ( r < rcut ) then enrg = 0.5_rp*A*rcut*ir*ir frc = -A*ir end if end subroutine !****************************************************************************** end module ia_vdw_m
module Data.Num.Maximum where open import Data.Num.Core open import Data.Nat open import Data.Nat.Properties open import Data.Nat.Properties.Simple open import Data.Nat.Properties.Extra open import Data.Fin as Fin using (Fin; fromℕ≤; inject≤) renaming (zero to z; suc to s) open import Data.Fin.Properties using (toℕ-fromℕ≤; bounded) open import Data.Product open import Function open import Relation.Nullary.Decidable open import Relation.Nullary open import Relation.Nullary.Negation open import Relation.Binary open import Relation.Binary.PropositionalEquality open ≡-Reasoning open ≤-Reasoning renaming (begin_ to start_; _∎ to _□; _≡⟨_⟩_ to _≈⟨_⟩_) open DecTotalOrder decTotalOrder using (reflexive) renaming (refl to ≤-refl) ------------------------------------------------------------------------ Maximum : ∀ {b d o} → (xs : Numeral b d o) → Set Maximum {b} {d} {o} xs = (ys : Numeral b d o) → ⟦ xs ⟧ ≥ ⟦ ys ⟧ -- Maximum-unique : ∀ {b d o} -- → (max xs : Numeral b d o) -- → Maximum max -- → Maximum xs -- → ⟦ max ⟧ ≡ ⟦ xs ⟧ -- Maximum-unique max xs max-max xs-max = IsPartialOrder.antisym isPartialOrder -- (xs-max max) -- (max-max xs) Maximum-NullBase-Greatest : ∀ {d} {o} → (xs : Numeral 0 (suc d) o) → Greatest (lsd xs) → Maximum xs Maximum-NullBase-Greatest {_} {o} (x ∙) greatest (y ∙) = greatest-of-all o x y greatest Maximum-NullBase-Greatest {_} {o} (x ∙) greatest (y ∷ ys) = start Fin.toℕ y + o + ⟦ ys ⟧ * 0 ≈⟨ toℕ-NullBase y ys ⟩ Fin.toℕ y + o ≤⟨ greatest-of-all o x y greatest ⟩ Fin.toℕ x + o □ Maximum-NullBase-Greatest {_} {o} (x ∷ xs) greatest (y ∙) = start Fin.toℕ y + o ≤⟨ greatest-of-all o x y greatest ⟩ Fin.toℕ x + o ≈⟨ sym (toℕ-NullBase x xs) ⟩ Fin.toℕ x + o + ⟦ xs ⟧ * 0 □ Maximum-NullBase-Greatest {_} {o} (x ∷ xs) greatest (y ∷ ys) = start ⟦ y ∷ ys ⟧ ≈⟨ toℕ-NullBase y ys ⟩ Fin.toℕ y + o ≤⟨ greatest-of-all o x y greatest ⟩ Fin.toℕ x + o ≈⟨ sym (toℕ-NullBase x xs) ⟩ ⟦ x ∷ xs ⟧ □ Maximum⇒Greatest-LSD : ∀ {b} {d} {o} → (xs : Numeral b d o) → Maximum xs → Greatest (lsd xs) Maximum⇒Greatest-LSD xs max with Greatest? (lsd xs) Maximum⇒Greatest-LSD xs max | yes greatest = greatest Maximum⇒Greatest-LSD {b} {zero} xs max | no ¬greatest = NoDigits-explode xs Maximum⇒Greatest-LSD {b} {suc d} {o} (x ∙) max | no ¬greatest = contradiction p ¬p where ys : Numeral b (suc d) o ys = greatest-digit d ∙ p : Digit-toℕ x o ≥ ⟦ ys ⟧ p = max ys ¬p : Digit-toℕ x o ≱ ⟦ ys ⟧ ¬p = <⇒≱ $ start suc (Digit-toℕ x o) ≤⟨ +n-mono o (≤-pred (≤∧≢⇒< (bounded x) ¬greatest)) ⟩ d + o ≈⟨ sym (greatest-digit-toℕ (Fin.fromℕ d) (greatest-digit-is-the-Greatest d)) ⟩ Digit-toℕ (greatest-digit d) o ≈⟨ refl ⟩ ⟦ ys ⟧ □ Maximum⇒Greatest-LSD {b} {suc d} {o} (x ∷ xs) max | no ¬greatest = contradiction p ¬p where ys : Numeral b (suc d) o ys = greatest-digit d ∷ xs p : ⟦ x ∷ xs ⟧ ≥ ⟦ ys ⟧ p = max ys ¬p : ⟦ x ∷ xs ⟧ ≱ ⟦ ys ⟧ ¬p = <⇒≱ $ +n-mono (⟦ xs ⟧ * b) $ start suc (Digit-toℕ x o) ≤⟨ +n-mono o (≤-pred (≤∧≢⇒< (bounded x) ¬greatest)) ⟩ d + o ≈⟨ sym (greatest-digit-toℕ (Fin.fromℕ d) (greatest-digit-is-the-Greatest d)) ⟩ (Digit-toℕ (greatest-digit d) o) □ Maximum-NullBase : ∀ {d} {o} → (xs : Numeral 0 (suc d) o) → Dec (Maximum xs) Maximum-NullBase xs with Greatest? (lsd xs) Maximum-NullBase xs | yes greatest = yes (Maximum-NullBase-Greatest xs greatest) Maximum-NullBase xs | no ¬greatest = no (contraposition (Maximum⇒Greatest-LSD xs) ¬greatest) Maximum-AllZeros : ∀ {b} → (xs : Numeral b 1 0) → Maximum xs Maximum-AllZeros xs ys = reflexive $ begin ⟦ ys ⟧ ≡⟨ toℕ-AllZeros ys ⟩ zero ≡⟨ sym (toℕ-AllZeros xs) ⟩ ⟦ xs ⟧ ∎ Maximum-Proper : ∀ {b d o} → (xs : Numeral (suc b) (suc d) o) → (proper : 2 ≤ suc (d + o)) → ¬ (Maximum xs) Maximum-Proper {b} {d} {o} xs proper claim = contradiction p ¬p where p : ⟦ xs ⟧ ≥ ⟦ greatest-digit d ∷ xs ⟧ p = claim (greatest-digit d ∷ xs) ¬p : ⟦ xs ⟧ ≱ ⟦ greatest-digit d ∷ xs ⟧ ¬p = <⇒≱ $ start suc ⟦ xs ⟧ ≈⟨ cong suc (sym (*-right-identity ⟦ xs ⟧)) ⟩ suc (⟦ xs ⟧ * 1) ≤⟨ s≤s (n*-mono ⟦ xs ⟧ (s≤s z≤n)) ⟩ suc (⟦ xs ⟧ * suc b) ≤⟨ +n-mono (⟦ xs ⟧ * suc b) (≤-pred proper) ⟩ d + o + ⟦ xs ⟧ * suc b ≈⟨ cong (λ w → w + ⟦ xs ⟧ * suc b) (sym (greatest-digit-toℕ (Fin.fromℕ d) (greatest-digit-is-the-Greatest d))) ⟩ ⟦ greatest-digit d ∷ xs ⟧ □ Maximum? : ∀ {b d o} → (xs : Numeral b d o) → Dec (Maximum xs) Maximum? {b} {d} {o} xs with numView b d o Maximum? xs | NullBase d o = Maximum-NullBase xs Maximum? xs | NoDigits b o = no (NoDigits-explode xs) Maximum? xs | AllZeros b = yes (Maximum-AllZeros xs) Maximum? xs | Proper b d o proper = no (Maximum-Proper xs proper)
(*Generated by Sail from cheri128.*) Require Import Sail.Base. Require Import Sail.Real. Require Import cheri128_types. Require Import mips_extras. Import ListNotations. Open Scope string. Open Scope bool. Open Scope Z. Definition trace : bool := false. Hint Unfold trace : sail. Definition eq_unit (_ : unit) (_ : unit) : {_bool : bool & ArithFact (_bool)} := build_ex (true). Definition neq_int (x : Z) (y : Z) : {_bool : bool & ArithFact (Bool.eqb (negb (x =? y)) _bool)} := build_ex (negb (Z.eqb x y)). Definition neq_bool (x : bool) (y : bool) : bool := negb (Bool.eqb x y). Definition __id (x : Z) : {_retval : Z & ArithFact (_retval =? x)} := build_ex (x). Definition _shl_int_general (m : Z) (n : Z) : Z := if sumbool_of_bool (Z.geb n 0) then shl_int m n else shr_int m (Z.opp n). Definition _shr_int_general (m : Z) (n : Z) : Z := if sumbool_of_bool (Z.geb n 0) then shr_int m n else shl_int m (Z.opp n). Definition fdiv_int (n : Z) (m : Z) : Z := if sumbool_of_bool (andb (Z.ltb n 0) (Z.gtb m 0)) then Z.sub (Z.quot (Z.add n 1) m) 1 else if sumbool_of_bool (andb (Z.gtb n 0) (Z.ltb m 0)) then Z.sub (Z.quot (Z.sub n 1) m) 1 else Z.quot n m. Definition fmod_int (n : Z) (m : Z) : Z := Z.sub n (Z.mul m (fdiv_int n m)). Definition undefined_option {a : Type} (typ_a : a) : M (option a) := (undefined_unit tt) >>= fun u_0 : unit => let u_1 : a := typ_a in (internal_pick [Some u_1; None]) : M (option a). Definition is_none {a : Type} (opt : option a) : bool := match opt with | Some _ => false | None => true end. Definition is_some {a : Type} (opt : option a) : bool := match opt with | Some _ => true | None => false end. Definition sail_mask {v0 : Z} (len : Z) (v : mword v0) `{ArithFact ((len >=? 0) && (v0 >=? 0))} : mword len := if sumbool_of_bool (Z.leb len (length_mword v)) then vector_truncate v len else zero_extend v len. Definition sail_ones (n : Z) `{ArithFact (n >=? 0)} : mword n := not_vec (zeros n). Definition slice_mask (n : Z) (i : Z) (l : Z) `{ArithFact (n >=? 0)} : mword n := if sumbool_of_bool (Z.geb l n) then shiftl (sail_ones n) i else let one : bits n := sail_mask n ('b"1" : bits 1) in shiftl (sub_vec (shiftl one l) one) i. Definition concat_str_bits {n : Z} (str : string) (x : mword n) : string := String.append str (string_of_bits x). Definition concat_str_dec (str : string) (x : Z) : string := String.append str (dec_str x). Definition cast_unit_vec (b : bitU) : mword 1 := match b with | B0 => 'b"0" : mword 1 | _ => 'b"1" : mword 1 end. Definition __MIPS_write (addr : mword 64) (width : Z) (data : mword (8 * width)) : M (unit) := (write_ram 64 width (Ox"0000000000000000" : mword 64) addr data) >> returnm tt. Definition __MIPS_read (addr : mword 64) (width : Z) `{ArithFact (width >=? 0)} : M (mword (8 * width)) := (read_ram 64 width (Ox"0000000000000000" : mword 64) addr) : M (mword (8 * width)). Definition zopz0zQzQ {n0 : Z} (bs : mword n0) (n : Z) `{ArithFact (n >=? 0)} : mword (n0 * n) := replicate_bits bs n. Definition undefined_exception '(tt : unit) : M (exception) := (undefined_string tt) >>= fun u_0 : string => (undefined_unit tt) >>= fun u_1 : unit => (internal_pick [ISAException u_1; Error_not_implemented u_0; Error_misaligned_access u_1; Error_EBREAK u_1; Error_internal_error u_1]) : M (exception). Definition mips_sign_extend {n : Z} (m : Z) (v : mword n) `{ArithFact (m >=? n)} : mword m := sign_extend v m. Definition mips_zero_extend {n : Z} (m : Z) (v : mword n) `{ArithFact (m >=? n)} : mword m := zero_extend v m. Definition zeros_implicit (n : Z) (_ : unit) `{ArithFact (n >=? 0)} : mword n := zeros n. Definition ones_implicit (n : Z) (_ : unit) `{ArithFact (n >=? 0)} : mword n := sail_ones n. Definition zopz0zI_s {n : Z} (x : mword n) (y : mword n) `{ArithFact (n >? 0)} : bool := Z.ltb (projT1 (sint x)) (projT1 (sint y)). Definition zopz0zKzJ_s {n : Z} (x : mword n) (y : mword n) `{ArithFact (n >? 0)} : bool := Z.geb (projT1 (sint x)) (projT1 (sint y)). Definition zopz0zI_u {n : Z} (x : mword n) (y : mword n) `{ArithFact (n >=? 0)} : bool := Z.ltb (projT1 (uint x)) (projT1 (uint y)). Definition zopz0zKzJ_u {n : Z} (x : mword n) (y : mword n) `{ArithFact (n >=? 0)} : bool := Z.geb (projT1 (uint x)) (projT1 (uint y)). Definition bool_to_bits (x : bool) : mword 1 := if sumbool_of_bool x then 'b"1" : mword 1 else 'b"0" : mword 1. Definition bool_to_bit (x : bool) : bitU := if sumbool_of_bool x then B1 else B0. Definition bit_to_bool (b : bitU) : bool := match b with | B1 => true | _ => false end. Definition bits_to_bool (x : mword 1) : bool := bit_to_bool (access_vec_dec x 0). Definition to_bits (l : Z) (n : Z) `{ArithFact (l >=? 0)} : mword l := get_slice_int l n 0. Definition mask {m : Z} (n : Z) (bs : mword m) `{ArithFact ((m >=? n) && (n >? 0))} : mword n := autocast (subrange_vec_dec bs (Z.sub n 1) 0). Definition undefined_CauseReg '(tt : unit) : M (CauseReg) := (undefined_bitvector 32) >>= fun w__0 : mword 32 => returnm ({| CauseReg_CauseReg_chunk_0 := w__0 |}). Definition Mk_CauseReg (v : mword 32) : CauseReg := {| CauseReg_CauseReg_chunk_0 := (subrange_vec_dec v 31 0) |}. Definition _get_CauseReg_bits (v : CauseReg) : mword 32 := subrange_vec_dec v.(CauseReg_CauseReg_chunk_0) 31 0. Definition _set_CauseReg_bits (r_ref : register_ref regstate register_value CauseReg) (v : mword 32) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with CauseReg_CauseReg_chunk_0 := (update_subrange_vec_dec r.(CauseReg_CauseReg_chunk_0) 31 0 (subrange_vec_dec v 31 0)) ]} : CauseReg in write_reg r_ref r : M (unit). Definition _update_CauseReg_bits (v : CauseReg) (x : mword 32) : CauseReg := {[ v with CauseReg_CauseReg_chunk_0 := (update_subrange_vec_dec v.(CauseReg_CauseReg_chunk_0) 31 0 (subrange_vec_dec x 31 0)) ]}. Definition _get_CauseReg_BD (v : CauseReg) : mword 1 := subrange_vec_dec v.(CauseReg_CauseReg_chunk_0) 31 31. Definition _set_CauseReg_BD (r_ref : register_ref regstate register_value CauseReg) (v : mword 1) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with CauseReg_CauseReg_chunk_0 := (update_subrange_vec_dec r.(CauseReg_CauseReg_chunk_0) 31 31 (subrange_vec_dec v 0 0)) ]} : CauseReg in write_reg r_ref r : M (unit). Definition _update_CauseReg_BD (v : CauseReg) (x : mword 1) : CauseReg := {[ v with CauseReg_CauseReg_chunk_0 := (update_subrange_vec_dec v.(CauseReg_CauseReg_chunk_0) 31 31 (subrange_vec_dec x 0 0)) ]}. Definition _get_CauseReg_CE (v : CauseReg) : mword 2 := subrange_vec_dec v.(CauseReg_CauseReg_chunk_0) 29 28. Definition _set_CauseReg_CE (r_ref : register_ref regstate register_value CauseReg) (v : mword 2) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with CauseReg_CauseReg_chunk_0 := (update_subrange_vec_dec r.(CauseReg_CauseReg_chunk_0) 29 28 (subrange_vec_dec v 1 0)) ]} : CauseReg in write_reg r_ref r : M (unit). Definition _update_CauseReg_CE (v : CauseReg) (x : mword 2) : CauseReg := {[ v with CauseReg_CauseReg_chunk_0 := (update_subrange_vec_dec v.(CauseReg_CauseReg_chunk_0) 29 28 (subrange_vec_dec x 1 0)) ]}. Definition _get_CauseReg_IV (v : CauseReg) : mword 1 := subrange_vec_dec v.(CauseReg_CauseReg_chunk_0) 23 23. Definition _set_CauseReg_IV (r_ref : register_ref regstate register_value CauseReg) (v : mword 1) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with CauseReg_CauseReg_chunk_0 := (update_subrange_vec_dec r.(CauseReg_CauseReg_chunk_0) 23 23 (subrange_vec_dec v 0 0)) ]} : CauseReg in write_reg r_ref r : M (unit). Definition _update_CauseReg_IV (v : CauseReg) (x : mword 1) : CauseReg := {[ v with CauseReg_CauseReg_chunk_0 := (update_subrange_vec_dec v.(CauseReg_CauseReg_chunk_0) 23 23 (subrange_vec_dec x 0 0)) ]}. Definition _get_CauseReg_WP (v : CauseReg) : mword 1 := subrange_vec_dec v.(CauseReg_CauseReg_chunk_0) 22 22. Definition _set_CauseReg_WP (r_ref : register_ref regstate register_value CauseReg) (v : mword 1) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with CauseReg_CauseReg_chunk_0 := (update_subrange_vec_dec r.(CauseReg_CauseReg_chunk_0) 22 22 (subrange_vec_dec v 0 0)) ]} : CauseReg in write_reg r_ref r : M (unit). Definition _update_CauseReg_WP (v : CauseReg) (x : mword 1) : CauseReg := {[ v with CauseReg_CauseReg_chunk_0 := (update_subrange_vec_dec v.(CauseReg_CauseReg_chunk_0) 22 22 (subrange_vec_dec x 0 0)) ]}. Definition _get_CauseReg_IP (v : CauseReg) : mword 8 := subrange_vec_dec v.(CauseReg_CauseReg_chunk_0) 15 8. Definition _set_CauseReg_IP (r_ref : register_ref regstate register_value CauseReg) (v : mword 8) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with CauseReg_CauseReg_chunk_0 := (update_subrange_vec_dec r.(CauseReg_CauseReg_chunk_0) 15 8 (subrange_vec_dec v 7 0)) ]} : CauseReg in write_reg r_ref r : M (unit). Definition _update_CauseReg_IP (v : CauseReg) (x : mword 8) : CauseReg := {[ v with CauseReg_CauseReg_chunk_0 := (update_subrange_vec_dec v.(CauseReg_CauseReg_chunk_0) 15 8 (subrange_vec_dec x 7 0)) ]}. Definition _get_CauseReg_ExcCode (v : CauseReg) : mword 5 := subrange_vec_dec v.(CauseReg_CauseReg_chunk_0) 6 2. Definition _set_CauseReg_ExcCode (r_ref : register_ref regstate register_value CauseReg) (v : mword 5) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with CauseReg_CauseReg_chunk_0 := (update_subrange_vec_dec r.(CauseReg_CauseReg_chunk_0) 6 2 (subrange_vec_dec v 4 0)) ]} : CauseReg in write_reg r_ref r : M (unit). Definition _update_CauseReg_ExcCode (v : CauseReg) (x : mword 5) : CauseReg := {[ v with CauseReg_CauseReg_chunk_0 := (update_subrange_vec_dec v.(CauseReg_CauseReg_chunk_0) 6 2 (subrange_vec_dec x 4 0)) ]}. Definition undefined_TLBEntryLoReg '(tt : unit) : M (TLBEntryLoReg) := (undefined_bitvector 64) >>= fun w__0 : mword 64 => returnm ({| TLBEntryLoReg_TLBEntryLoReg_chunk_0 := w__0 |}). Definition Mk_TLBEntryLoReg (v : mword 64) : TLBEntryLoReg := {| TLBEntryLoReg_TLBEntryLoReg_chunk_0 := (subrange_vec_dec v 63 0) |}. Definition _get_TLBEntryLoReg_bits (v : TLBEntryLoReg) : mword 64 := subrange_vec_dec v.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 63 0. Definition _set_TLBEntryLoReg_bits (r_ref : register_ref regstate register_value TLBEntryLoReg) (v : mword 64) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with TLBEntryLoReg_TLBEntryLoReg_chunk_0 := (update_subrange_vec_dec r.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 63 0 (subrange_vec_dec v 63 0)) ]} : TLBEntryLoReg in write_reg r_ref r : M (unit). Definition _update_TLBEntryLoReg_bits (v : TLBEntryLoReg) (x : mword 64) : TLBEntryLoReg := {[ v with TLBEntryLoReg_TLBEntryLoReg_chunk_0 := (update_subrange_vec_dec v.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 63 0 (subrange_vec_dec x 63 0)) ]}. Definition _get_TLBEntryLoReg_CapS (v : TLBEntryLoReg) : mword 1 := subrange_vec_dec v.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 63 63. Definition _set_TLBEntryLoReg_CapS (r_ref : register_ref regstate register_value TLBEntryLoReg) (v : mword 1) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with TLBEntryLoReg_TLBEntryLoReg_chunk_0 := (update_subrange_vec_dec r.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 63 63 (subrange_vec_dec v 0 0)) ]} : TLBEntryLoReg in write_reg r_ref r : M (unit). Definition _update_TLBEntryLoReg_CapS (v : TLBEntryLoReg) (x : mword 1) : TLBEntryLoReg := {[ v with TLBEntryLoReg_TLBEntryLoReg_chunk_0 := (update_subrange_vec_dec v.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 63 63 (subrange_vec_dec x 0 0)) ]}. Definition _get_TLBEntryLoReg_CapL (v : TLBEntryLoReg) : mword 1 := subrange_vec_dec v.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 62 62. Definition _set_TLBEntryLoReg_CapL (r_ref : register_ref regstate register_value TLBEntryLoReg) (v : mword 1) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with TLBEntryLoReg_TLBEntryLoReg_chunk_0 := (update_subrange_vec_dec r.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 62 62 (subrange_vec_dec v 0 0)) ]} : TLBEntryLoReg in write_reg r_ref r : M (unit). Definition _update_TLBEntryLoReg_CapL (v : TLBEntryLoReg) (x : mword 1) : TLBEntryLoReg := {[ v with TLBEntryLoReg_TLBEntryLoReg_chunk_0 := (update_subrange_vec_dec v.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 62 62 (subrange_vec_dec x 0 0)) ]}. Definition _get_TLBEntryLoReg_CapLG (v : TLBEntryLoReg) : mword 1 := subrange_vec_dec v.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 61 61. Definition _set_TLBEntryLoReg_CapLG (r_ref : register_ref regstate register_value TLBEntryLoReg) (v : mword 1) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with TLBEntryLoReg_TLBEntryLoReg_chunk_0 := (update_subrange_vec_dec r.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 61 61 (subrange_vec_dec v 0 0)) ]} : TLBEntryLoReg in write_reg r_ref r : M (unit). Definition _update_TLBEntryLoReg_CapLG (v : TLBEntryLoReg) (x : mword 1) : TLBEntryLoReg := {[ v with TLBEntryLoReg_TLBEntryLoReg_chunk_0 := (update_subrange_vec_dec v.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 61 61 (subrange_vec_dec x 0 0)) ]}. Definition _get_TLBEntryLoReg_PFN (v : TLBEntryLoReg) : mword 24 := subrange_vec_dec v.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 29 6. Definition _set_TLBEntryLoReg_PFN (r_ref : register_ref regstate register_value TLBEntryLoReg) (v : mword 24) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with TLBEntryLoReg_TLBEntryLoReg_chunk_0 := (update_subrange_vec_dec r.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 29 6 (subrange_vec_dec v 23 0)) ]} : TLBEntryLoReg in write_reg r_ref r : M (unit). Definition _update_TLBEntryLoReg_PFN (v : TLBEntryLoReg) (x : mword 24) : TLBEntryLoReg := {[ v with TLBEntryLoReg_TLBEntryLoReg_chunk_0 := (update_subrange_vec_dec v.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 29 6 (subrange_vec_dec x 23 0)) ]}. Definition _get_TLBEntryLoReg_C (v : TLBEntryLoReg) : mword 3 := subrange_vec_dec v.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 5 3. Definition _set_TLBEntryLoReg_C (r_ref : register_ref regstate register_value TLBEntryLoReg) (v : mword 3) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with TLBEntryLoReg_TLBEntryLoReg_chunk_0 := (update_subrange_vec_dec r.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 5 3 (subrange_vec_dec v 2 0)) ]} : TLBEntryLoReg in write_reg r_ref r : M (unit). Definition _update_TLBEntryLoReg_C (v : TLBEntryLoReg) (x : mword 3) : TLBEntryLoReg := {[ v with TLBEntryLoReg_TLBEntryLoReg_chunk_0 := (update_subrange_vec_dec v.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 5 3 (subrange_vec_dec x 2 0)) ]}. Definition _get_TLBEntryLoReg_D (v : TLBEntryLoReg) : mword 1 := subrange_vec_dec v.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 2 2. Definition _set_TLBEntryLoReg_D (r_ref : register_ref regstate register_value TLBEntryLoReg) (v : mword 1) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with TLBEntryLoReg_TLBEntryLoReg_chunk_0 := (update_subrange_vec_dec r.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 2 2 (subrange_vec_dec v 0 0)) ]} : TLBEntryLoReg in write_reg r_ref r : M (unit). Definition _update_TLBEntryLoReg_D (v : TLBEntryLoReg) (x : mword 1) : TLBEntryLoReg := {[ v with TLBEntryLoReg_TLBEntryLoReg_chunk_0 := (update_subrange_vec_dec v.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 2 2 (subrange_vec_dec x 0 0)) ]}. Definition _get_TLBEntryLoReg_V (v : TLBEntryLoReg) : mword 1 := subrange_vec_dec v.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 1 1. Definition _set_TLBEntryLoReg_V (r_ref : register_ref regstate register_value TLBEntryLoReg) (v : mword 1) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with TLBEntryLoReg_TLBEntryLoReg_chunk_0 := (update_subrange_vec_dec r.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 1 1 (subrange_vec_dec v 0 0)) ]} : TLBEntryLoReg in write_reg r_ref r : M (unit). Definition _update_TLBEntryLoReg_V (v : TLBEntryLoReg) (x : mword 1) : TLBEntryLoReg := {[ v with TLBEntryLoReg_TLBEntryLoReg_chunk_0 := (update_subrange_vec_dec v.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 1 1 (subrange_vec_dec x 0 0)) ]}. Definition _get_TLBEntryLoReg_G (v : TLBEntryLoReg) : mword 1 := subrange_vec_dec v.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 0 0. Definition _set_TLBEntryLoReg_G (r_ref : register_ref regstate register_value TLBEntryLoReg) (v : mword 1) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with TLBEntryLoReg_TLBEntryLoReg_chunk_0 := (update_subrange_vec_dec r.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 0 0 (subrange_vec_dec v 0 0)) ]} : TLBEntryLoReg in write_reg r_ref r : M (unit). Definition _update_TLBEntryLoReg_G (v : TLBEntryLoReg) (x : mword 1) : TLBEntryLoReg := {[ v with TLBEntryLoReg_TLBEntryLoReg_chunk_0 := (update_subrange_vec_dec v.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 0 0 (subrange_vec_dec x 0 0)) ]}. Definition undefined_TLBEntryHiReg '(tt : unit) : M (TLBEntryHiReg) := (undefined_bitvector 64) >>= fun w__0 : mword 64 => returnm ({| TLBEntryHiReg_TLBEntryHiReg_chunk_0 := w__0 |}). Definition Mk_TLBEntryHiReg (v : mword 64) : TLBEntryHiReg := {| TLBEntryHiReg_TLBEntryHiReg_chunk_0 := (subrange_vec_dec v 63 0) |}. Definition _get_TLBEntryHiReg_bits (v : TLBEntryHiReg) : mword 64 := subrange_vec_dec v.(TLBEntryHiReg_TLBEntryHiReg_chunk_0) 63 0. Definition _set_TLBEntryHiReg_bits (r_ref : register_ref regstate register_value TLBEntryHiReg) (v : mword 64) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with TLBEntryHiReg_TLBEntryHiReg_chunk_0 := (update_subrange_vec_dec r.(TLBEntryHiReg_TLBEntryHiReg_chunk_0) 63 0 (subrange_vec_dec v 63 0)) ]} : TLBEntryHiReg in write_reg r_ref r : M (unit). Definition _update_TLBEntryHiReg_bits (v : TLBEntryHiReg) (x : mword 64) : TLBEntryHiReg := {[ v with TLBEntryHiReg_TLBEntryHiReg_chunk_0 := (update_subrange_vec_dec v.(TLBEntryHiReg_TLBEntryHiReg_chunk_0) 63 0 (subrange_vec_dec x 63 0)) ]}. Definition _get_TLBEntryHiReg_R (v : TLBEntryHiReg) : mword 2 := subrange_vec_dec v.(TLBEntryHiReg_TLBEntryHiReg_chunk_0) 63 62. Definition _set_TLBEntryHiReg_R (r_ref : register_ref regstate register_value TLBEntryHiReg) (v : mword 2) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with TLBEntryHiReg_TLBEntryHiReg_chunk_0 := (update_subrange_vec_dec r.(TLBEntryHiReg_TLBEntryHiReg_chunk_0) 63 62 (subrange_vec_dec v 1 0)) ]} : TLBEntryHiReg in write_reg r_ref r : M (unit). Definition _update_TLBEntryHiReg_R (v : TLBEntryHiReg) (x : mword 2) : TLBEntryHiReg := {[ v with TLBEntryHiReg_TLBEntryHiReg_chunk_0 := (update_subrange_vec_dec v.(TLBEntryHiReg_TLBEntryHiReg_chunk_0) 63 62 (subrange_vec_dec x 1 0)) ]}. Definition _get_TLBEntryHiReg_CLGK (v : TLBEntryHiReg) : mword 1 := subrange_vec_dec v.(TLBEntryHiReg_TLBEntryHiReg_chunk_0) 61 61. Definition _set_TLBEntryHiReg_CLGK (r_ref : register_ref regstate register_value TLBEntryHiReg) (v : mword 1) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with TLBEntryHiReg_TLBEntryHiReg_chunk_0 := (update_subrange_vec_dec r.(TLBEntryHiReg_TLBEntryHiReg_chunk_0) 61 61 (subrange_vec_dec v 0 0)) ]} : TLBEntryHiReg in write_reg r_ref r : M (unit). Definition _update_TLBEntryHiReg_CLGK (v : TLBEntryHiReg) (x : mword 1) : TLBEntryHiReg := {[ v with TLBEntryHiReg_TLBEntryHiReg_chunk_0 := (update_subrange_vec_dec v.(TLBEntryHiReg_TLBEntryHiReg_chunk_0) 61 61 (subrange_vec_dec x 0 0)) ]}. Definition _get_TLBEntryHiReg_CLGS (v : TLBEntryHiReg) : mword 1 := subrange_vec_dec v.(TLBEntryHiReg_TLBEntryHiReg_chunk_0) 60 60. Definition _set_TLBEntryHiReg_CLGS (r_ref : register_ref regstate register_value TLBEntryHiReg) (v : mword 1) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with TLBEntryHiReg_TLBEntryHiReg_chunk_0 := (update_subrange_vec_dec r.(TLBEntryHiReg_TLBEntryHiReg_chunk_0) 60 60 (subrange_vec_dec v 0 0)) ]} : TLBEntryHiReg in write_reg r_ref r : M (unit). Definition _update_TLBEntryHiReg_CLGS (v : TLBEntryHiReg) (x : mword 1) : TLBEntryHiReg := {[ v with TLBEntryHiReg_TLBEntryHiReg_chunk_0 := (update_subrange_vec_dec v.(TLBEntryHiReg_TLBEntryHiReg_chunk_0) 60 60 (subrange_vec_dec x 0 0)) ]}. Definition _get_TLBEntryHiReg_CLGU (v : TLBEntryHiReg) : mword 1 := subrange_vec_dec v.(TLBEntryHiReg_TLBEntryHiReg_chunk_0) 59 59. Definition _set_TLBEntryHiReg_CLGU (r_ref : register_ref regstate register_value TLBEntryHiReg) (v : mword 1) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with TLBEntryHiReg_TLBEntryHiReg_chunk_0 := (update_subrange_vec_dec r.(TLBEntryHiReg_TLBEntryHiReg_chunk_0) 59 59 (subrange_vec_dec v 0 0)) ]} : TLBEntryHiReg in write_reg r_ref r : M (unit). Definition _update_TLBEntryHiReg_CLGU (v : TLBEntryHiReg) (x : mword 1) : TLBEntryHiReg := {[ v with TLBEntryHiReg_TLBEntryHiReg_chunk_0 := (update_subrange_vec_dec v.(TLBEntryHiReg_TLBEntryHiReg_chunk_0) 59 59 (subrange_vec_dec x 0 0)) ]}. Definition _get_TLBEntryHiReg_VPN2 (v : TLBEntryHiReg) : mword 27 := subrange_vec_dec v.(TLBEntryHiReg_TLBEntryHiReg_chunk_0) 39 13. Definition _set_TLBEntryHiReg_VPN2 (r_ref : register_ref regstate register_value TLBEntryHiReg) (v : mword 27) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with TLBEntryHiReg_TLBEntryHiReg_chunk_0 := (update_subrange_vec_dec r.(TLBEntryHiReg_TLBEntryHiReg_chunk_0) 39 13 (subrange_vec_dec v 26 0)) ]} : TLBEntryHiReg in write_reg r_ref r : M (unit). Definition _update_TLBEntryHiReg_VPN2 (v : TLBEntryHiReg) (x : mword 27) : TLBEntryHiReg := {[ v with TLBEntryHiReg_TLBEntryHiReg_chunk_0 := (update_subrange_vec_dec v.(TLBEntryHiReg_TLBEntryHiReg_chunk_0) 39 13 (subrange_vec_dec x 26 0)) ]}. Definition _get_TLBEntryHiReg_ASID (v : TLBEntryHiReg) : mword 8 := subrange_vec_dec v.(TLBEntryHiReg_TLBEntryHiReg_chunk_0) 7 0. Definition _set_TLBEntryHiReg_ASID (r_ref : register_ref regstate register_value TLBEntryHiReg) (v : mword 8) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with TLBEntryHiReg_TLBEntryHiReg_chunk_0 := (update_subrange_vec_dec r.(TLBEntryHiReg_TLBEntryHiReg_chunk_0) 7 0 (subrange_vec_dec v 7 0)) ]} : TLBEntryHiReg in write_reg r_ref r : M (unit). Definition _update_TLBEntryHiReg_ASID (v : TLBEntryHiReg) (x : mword 8) : TLBEntryHiReg := {[ v with TLBEntryHiReg_TLBEntryHiReg_chunk_0 := (update_subrange_vec_dec v.(TLBEntryHiReg_TLBEntryHiReg_chunk_0) 7 0 (subrange_vec_dec x 7 0)) ]}. Definition undefined_ContextReg '(tt : unit) : M (ContextReg) := (undefined_bitvector 64) >>= fun w__0 : mword 64 => returnm ({| ContextReg_ContextReg_chunk_0 := w__0 |}). Definition Mk_ContextReg (v : mword 64) : ContextReg := {| ContextReg_ContextReg_chunk_0 := (subrange_vec_dec v 63 0) |}. Definition _get_ContextReg_bits (v : ContextReg) : mword 64 := subrange_vec_dec v.(ContextReg_ContextReg_chunk_0) 63 0. Definition _set_ContextReg_bits (r_ref : register_ref regstate register_value ContextReg) (v : mword 64) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with ContextReg_ContextReg_chunk_0 := (update_subrange_vec_dec r.(ContextReg_ContextReg_chunk_0) 63 0 (subrange_vec_dec v 63 0)) ]} : ContextReg in write_reg r_ref r : M (unit). Definition _update_ContextReg_bits (v : ContextReg) (x : mword 64) : ContextReg := {[ v with ContextReg_ContextReg_chunk_0 := (update_subrange_vec_dec v.(ContextReg_ContextReg_chunk_0) 63 0 (subrange_vec_dec x 63 0)) ]}. Definition _get_ContextReg_PTEBase (v : ContextReg) : mword 41 := subrange_vec_dec v.(ContextReg_ContextReg_chunk_0) 63 23. Definition _set_ContextReg_PTEBase (r_ref : register_ref regstate register_value ContextReg) (v : mword 41) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with ContextReg_ContextReg_chunk_0 := (update_subrange_vec_dec r.(ContextReg_ContextReg_chunk_0) 63 23 (subrange_vec_dec v 40 0)) ]} : ContextReg in write_reg r_ref r : M (unit). Definition _update_ContextReg_PTEBase (v : ContextReg) (x : mword 41) : ContextReg := {[ v with ContextReg_ContextReg_chunk_0 := (update_subrange_vec_dec v.(ContextReg_ContextReg_chunk_0) 63 23 (subrange_vec_dec x 40 0)) ]}. Definition _get_ContextReg_BadVPN2 (v : ContextReg) : mword 19 := subrange_vec_dec v.(ContextReg_ContextReg_chunk_0) 22 4. Definition _set_ContextReg_BadVPN2 (r_ref : register_ref regstate register_value ContextReg) (v : mword 19) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with ContextReg_ContextReg_chunk_0 := (update_subrange_vec_dec r.(ContextReg_ContextReg_chunk_0) 22 4 (subrange_vec_dec v 18 0)) ]} : ContextReg in write_reg r_ref r : M (unit). Definition _update_ContextReg_BadVPN2 (v : ContextReg) (x : mword 19) : ContextReg := {[ v with ContextReg_ContextReg_chunk_0 := (update_subrange_vec_dec v.(ContextReg_ContextReg_chunk_0) 22 4 (subrange_vec_dec x 18 0)) ]}. Definition undefined_XContextReg '(tt : unit) : M (XContextReg) := (undefined_bitvector 64) >>= fun w__0 : mword 64 => returnm ({| XContextReg_XContextReg_chunk_0 := w__0 |}). Definition Mk_XContextReg (v : mword 64) : XContextReg := {| XContextReg_XContextReg_chunk_0 := (subrange_vec_dec v 63 0) |}. Definition _get_XContextReg_bits (v : XContextReg) : mword 64 := subrange_vec_dec v.(XContextReg_XContextReg_chunk_0) 63 0. Definition _set_XContextReg_bits (r_ref : register_ref regstate register_value XContextReg) (v : mword 64) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with XContextReg_XContextReg_chunk_0 := (update_subrange_vec_dec r.(XContextReg_XContextReg_chunk_0) 63 0 (subrange_vec_dec v 63 0)) ]} : XContextReg in write_reg r_ref r : M (unit). Definition _update_XContextReg_bits (v : XContextReg) (x : mword 64) : XContextReg := {[ v with XContextReg_XContextReg_chunk_0 := (update_subrange_vec_dec v.(XContextReg_XContextReg_chunk_0) 63 0 (subrange_vec_dec x 63 0)) ]}. Definition _get_XContextReg_XPTEBase (v : XContextReg) : mword 31 := subrange_vec_dec v.(XContextReg_XContextReg_chunk_0) 63 33. Definition _set_XContextReg_XPTEBase (r_ref : register_ref regstate register_value XContextReg) (v : mword 31) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with XContextReg_XContextReg_chunk_0 := (update_subrange_vec_dec r.(XContextReg_XContextReg_chunk_0) 63 33 (subrange_vec_dec v 30 0)) ]} : XContextReg in write_reg r_ref r : M (unit). Definition _update_XContextReg_XPTEBase (v : XContextReg) (x : mword 31) : XContextReg := {[ v with XContextReg_XContextReg_chunk_0 := (update_subrange_vec_dec v.(XContextReg_XContextReg_chunk_0) 63 33 (subrange_vec_dec x 30 0)) ]}. Definition _get_XContextReg_XR (v : XContextReg) : mword 2 := subrange_vec_dec v.(XContextReg_XContextReg_chunk_0) 32 31. Definition _set_XContextReg_XR (r_ref : register_ref regstate register_value XContextReg) (v : mword 2) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with XContextReg_XContextReg_chunk_0 := (update_subrange_vec_dec r.(XContextReg_XContextReg_chunk_0) 32 31 (subrange_vec_dec v 1 0)) ]} : XContextReg in write_reg r_ref r : M (unit). Definition _update_XContextReg_XR (v : XContextReg) (x : mword 2) : XContextReg := {[ v with XContextReg_XContextReg_chunk_0 := (update_subrange_vec_dec v.(XContextReg_XContextReg_chunk_0) 32 31 (subrange_vec_dec x 1 0)) ]}. Definition _get_XContextReg_XBadVPN2 (v : XContextReg) : mword 27 := subrange_vec_dec v.(XContextReg_XContextReg_chunk_0) 30 4. Definition _set_XContextReg_XBadVPN2 (r_ref : register_ref regstate register_value XContextReg) (v : mword 27) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with XContextReg_XContextReg_chunk_0 := (update_subrange_vec_dec r.(XContextReg_XContextReg_chunk_0) 30 4 (subrange_vec_dec v 26 0)) ]} : XContextReg in write_reg r_ref r : M (unit). Definition _update_XContextReg_XBadVPN2 (v : XContextReg) (x : mword 27) : XContextReg := {[ v with XContextReg_XContextReg_chunk_0 := (update_subrange_vec_dec v.(XContextReg_XContextReg_chunk_0) 30 4 (subrange_vec_dec x 26 0)) ]}. Definition TLBNumEntries := 64. Hint Unfold TLBNumEntries : sail. Definition TLBIndexMax : TLBIndexT := 'b"111111" : mword 6. Hint Unfold TLBIndexMax : sail. Definition MAX (n : Z) `{ArithFact (n >=? 0)} : {_retval : Z & ArithFact (_retval =? (2 ^ n - 1))} := build_ex (Z.sub (projT1 (pow2 n)) 1). Definition MAX_U64 := projT1 (MAX 64). Hint Unfold MAX_U64 : sail. Definition MAX_VA := projT1 (MAX 40). Hint Unfold MAX_VA : sail. Definition MAX_PA := projT1 (MAX 36). Hint Unfold MAX_PA : sail. Definition undefined_TLBEntry '(tt : unit) : M (TLBEntry) := (undefined_bitvector 55) >>= fun w__0 : mword 55 => (undefined_bitvector 64) >>= fun w__1 : mword 64 => returnm ({| TLBEntry_TLBEntry_chunk_1 := w__0; TLBEntry_TLBEntry_chunk_0 := w__1 |}). Definition Mk_TLBEntry (v : mword 119) : TLBEntry := {| TLBEntry_TLBEntry_chunk_1 := (subrange_vec_dec v 118 64); TLBEntry_TLBEntry_chunk_0 := (subrange_vec_dec v 63 0) |}. Definition _get_TLBEntry_bits (v : TLBEntry) : mword 119 := concat_vec (subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_1) 54 0) (subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 63 0). Definition _set_TLBEntry_bits (r_ref : register_ref regstate register_value TLBEntry) (v : mword 119) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with TLBEntry_TLBEntry_chunk_1 := (update_subrange_vec_dec r.(TLBEntry_TLBEntry_chunk_1) 54 0 (subrange_vec_dec v 118 64)) ]} : TLBEntry in let r := {[ r with TLBEntry_TLBEntry_chunk_0 := (update_subrange_vec_dec r.(TLBEntry_TLBEntry_chunk_0) 63 0 (subrange_vec_dec v 63 0)) ]} : TLBEntry in write_reg r_ref r : M (unit). Definition _update_TLBEntry_bits (v : TLBEntry) (x : mword 119) : TLBEntry := let v := {[ v with TLBEntry_TLBEntry_chunk_1 := (update_subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_1) 54 0 (subrange_vec_dec x 118 64)) ]} in {[ v with TLBEntry_TLBEntry_chunk_0 := (update_subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 63 0 (subrange_vec_dec x 63 0)) ]}. Definition _get_TLBEntry_pagemask (v : TLBEntry) : mword 16 := subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_1) 54 39. Definition _set_TLBEntry_pagemask (r_ref : register_ref regstate register_value TLBEntry) (v : mword 16) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with TLBEntry_TLBEntry_chunk_1 := (update_subrange_vec_dec r.(TLBEntry_TLBEntry_chunk_1) 54 39 (subrange_vec_dec v 15 0)) ]} : TLBEntry in write_reg r_ref r : M (unit). Definition _update_TLBEntry_pagemask (v : TLBEntry) (x : mword 16) : TLBEntry := {[ v with TLBEntry_TLBEntry_chunk_1 := (update_subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_1) 54 39 (subrange_vec_dec x 15 0)) ]}. Definition _get_TLBEntry_r (v : TLBEntry) : mword 2 := subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_1) 38 37. Definition _set_TLBEntry_r (r_ref : register_ref regstate register_value TLBEntry) (v : mword 2) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with TLBEntry_TLBEntry_chunk_1 := (update_subrange_vec_dec r.(TLBEntry_TLBEntry_chunk_1) 38 37 (subrange_vec_dec v 1 0)) ]} : TLBEntry in write_reg r_ref r : M (unit). Definition _update_TLBEntry_r (v : TLBEntry) (x : mword 2) : TLBEntry := {[ v with TLBEntry_TLBEntry_chunk_1 := (update_subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_1) 38 37 (subrange_vec_dec x 1 0)) ]}. Definition _get_TLBEntry_vpn2 (v : TLBEntry) : mword 27 := subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_1) 36 10. Definition _set_TLBEntry_vpn2 (r_ref : register_ref regstate register_value TLBEntry) (v : mword 27) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with TLBEntry_TLBEntry_chunk_1 := (update_subrange_vec_dec r.(TLBEntry_TLBEntry_chunk_1) 36 10 (subrange_vec_dec v 26 0)) ]} : TLBEntry in write_reg r_ref r : M (unit). Definition _update_TLBEntry_vpn2 (v : TLBEntry) (x : mword 27) : TLBEntry := {[ v with TLBEntry_TLBEntry_chunk_1 := (update_subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_1) 36 10 (subrange_vec_dec x 26 0)) ]}. Definition _get_TLBEntry_asid (v : TLBEntry) : mword 8 := subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_1) 9 2. Definition _set_TLBEntry_asid (r_ref : register_ref regstate register_value TLBEntry) (v : mword 8) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with TLBEntry_TLBEntry_chunk_1 := (update_subrange_vec_dec r.(TLBEntry_TLBEntry_chunk_1) 9 2 (subrange_vec_dec v 7 0)) ]} : TLBEntry in write_reg r_ref r : M (unit). Definition _update_TLBEntry_asid (v : TLBEntry) (x : mword 8) : TLBEntry := {[ v with TLBEntry_TLBEntry_chunk_1 := (update_subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_1) 9 2 (subrange_vec_dec x 7 0)) ]}. Definition _get_TLBEntry_g (v : TLBEntry) : mword 1 := subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_1) 1 1. Definition _set_TLBEntry_g (r_ref : register_ref regstate register_value TLBEntry) (v : mword 1) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with TLBEntry_TLBEntry_chunk_1 := (update_subrange_vec_dec r.(TLBEntry_TLBEntry_chunk_1) 1 1 (subrange_vec_dec v 0 0)) ]} : TLBEntry in write_reg r_ref r : M (unit). Definition _update_TLBEntry_g (v : TLBEntry) (x : mword 1) : TLBEntry := {[ v with TLBEntry_TLBEntry_chunk_1 := (update_subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_1) 1 1 (subrange_vec_dec x 0 0)) ]}. Definition _get_TLBEntry_valid (v : TLBEntry) : mword 1 := subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_1) 0 0. Definition _set_TLBEntry_valid (r_ref : register_ref regstate register_value TLBEntry) (v : mword 1) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with TLBEntry_TLBEntry_chunk_1 := (update_subrange_vec_dec r.(TLBEntry_TLBEntry_chunk_1) 0 0 (subrange_vec_dec v 0 0)) ]} : TLBEntry in write_reg r_ref r : M (unit). Definition _update_TLBEntry_valid (v : TLBEntry) (x : mword 1) : TLBEntry := {[ v with TLBEntry_TLBEntry_chunk_1 := (update_subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_1) 0 0 (subrange_vec_dec x 0 0)) ]}. Definition _get_TLBEntry_caplg1 (v : TLBEntry) : mword 1 := subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 63 63. Definition _set_TLBEntry_caplg1 (r_ref : register_ref regstate register_value TLBEntry) (v : mword 1) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with TLBEntry_TLBEntry_chunk_0 := (update_subrange_vec_dec r.(TLBEntry_TLBEntry_chunk_0) 63 63 (subrange_vec_dec v 0 0)) ]} : TLBEntry in write_reg r_ref r : M (unit). Definition _update_TLBEntry_caplg1 (v : TLBEntry) (x : mword 1) : TLBEntry := {[ v with TLBEntry_TLBEntry_chunk_0 := (update_subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 63 63 (subrange_vec_dec x 0 0)) ]}. Definition _get_TLBEntry_caps1 (v : TLBEntry) : mword 1 := subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 62 62. Definition _set_TLBEntry_caps1 (r_ref : register_ref regstate register_value TLBEntry) (v : mword 1) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with TLBEntry_TLBEntry_chunk_0 := (update_subrange_vec_dec r.(TLBEntry_TLBEntry_chunk_0) 62 62 (subrange_vec_dec v 0 0)) ]} : TLBEntry in write_reg r_ref r : M (unit). Definition _update_TLBEntry_caps1 (v : TLBEntry) (x : mword 1) : TLBEntry := {[ v with TLBEntry_TLBEntry_chunk_0 := (update_subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 62 62 (subrange_vec_dec x 0 0)) ]}. Definition _get_TLBEntry_capl1 (v : TLBEntry) : mword 1 := subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 61 61. Definition _set_TLBEntry_capl1 (r_ref : register_ref regstate register_value TLBEntry) (v : mword 1) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with TLBEntry_TLBEntry_chunk_0 := (update_subrange_vec_dec r.(TLBEntry_TLBEntry_chunk_0) 61 61 (subrange_vec_dec v 0 0)) ]} : TLBEntry in write_reg r_ref r : M (unit). Definition _update_TLBEntry_capl1 (v : TLBEntry) (x : mword 1) : TLBEntry := {[ v with TLBEntry_TLBEntry_chunk_0 := (update_subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 61 61 (subrange_vec_dec x 0 0)) ]}. Definition _get_TLBEntry_pfn1 (v : TLBEntry) : mword 24 := subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 60 37. Definition _set_TLBEntry_pfn1 (r_ref : register_ref regstate register_value TLBEntry) (v : mword 24) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with TLBEntry_TLBEntry_chunk_0 := (update_subrange_vec_dec r.(TLBEntry_TLBEntry_chunk_0) 60 37 (subrange_vec_dec v 23 0)) ]} : TLBEntry in write_reg r_ref r : M (unit). Definition _update_TLBEntry_pfn1 (v : TLBEntry) (x : mword 24) : TLBEntry := {[ v with TLBEntry_TLBEntry_chunk_0 := (update_subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 60 37 (subrange_vec_dec x 23 0)) ]}. Definition _get_TLBEntry_c1 (v : TLBEntry) : mword 3 := subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 36 34. Definition _set_TLBEntry_c1 (r_ref : register_ref regstate register_value TLBEntry) (v : mword 3) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with TLBEntry_TLBEntry_chunk_0 := (update_subrange_vec_dec r.(TLBEntry_TLBEntry_chunk_0) 36 34 (subrange_vec_dec v 2 0)) ]} : TLBEntry in write_reg r_ref r : M (unit). Definition _update_TLBEntry_c1 (v : TLBEntry) (x : mword 3) : TLBEntry := {[ v with TLBEntry_TLBEntry_chunk_0 := (update_subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 36 34 (subrange_vec_dec x 2 0)) ]}. Definition _get_TLBEntry_d1 (v : TLBEntry) : mword 1 := subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 33 33. Definition _set_TLBEntry_d1 (r_ref : register_ref regstate register_value TLBEntry) (v : mword 1) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with TLBEntry_TLBEntry_chunk_0 := (update_subrange_vec_dec r.(TLBEntry_TLBEntry_chunk_0) 33 33 (subrange_vec_dec v 0 0)) ]} : TLBEntry in write_reg r_ref r : M (unit). Definition _update_TLBEntry_d1 (v : TLBEntry) (x : mword 1) : TLBEntry := {[ v with TLBEntry_TLBEntry_chunk_0 := (update_subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 33 33 (subrange_vec_dec x 0 0)) ]}. Definition _get_TLBEntry_v1 (v : TLBEntry) : mword 1 := subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 32 32. Definition _set_TLBEntry_v1 (r_ref : register_ref regstate register_value TLBEntry) (v : mword 1) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with TLBEntry_TLBEntry_chunk_0 := (update_subrange_vec_dec r.(TLBEntry_TLBEntry_chunk_0) 32 32 (subrange_vec_dec v 0 0)) ]} : TLBEntry in write_reg r_ref r : M (unit). Definition _update_TLBEntry_v1 (v : TLBEntry) (x : mword 1) : TLBEntry := {[ v with TLBEntry_TLBEntry_chunk_0 := (update_subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 32 32 (subrange_vec_dec x 0 0)) ]}. Definition _get_TLBEntry_caplg0 (v : TLBEntry) : mword 1 := subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 31 31. Definition _set_TLBEntry_caplg0 (r_ref : register_ref regstate register_value TLBEntry) (v : mword 1) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with TLBEntry_TLBEntry_chunk_0 := (update_subrange_vec_dec r.(TLBEntry_TLBEntry_chunk_0) 31 31 (subrange_vec_dec v 0 0)) ]} : TLBEntry in write_reg r_ref r : M (unit). Definition _update_TLBEntry_caplg0 (v : TLBEntry) (x : mword 1) : TLBEntry := {[ v with TLBEntry_TLBEntry_chunk_0 := (update_subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 31 31 (subrange_vec_dec x 0 0)) ]}. Definition _get_TLBEntry_caps0 (v : TLBEntry) : mword 1 := subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 30 30. Definition _set_TLBEntry_caps0 (r_ref : register_ref regstate register_value TLBEntry) (v : mword 1) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with TLBEntry_TLBEntry_chunk_0 := (update_subrange_vec_dec r.(TLBEntry_TLBEntry_chunk_0) 30 30 (subrange_vec_dec v 0 0)) ]} : TLBEntry in write_reg r_ref r : M (unit). Definition _update_TLBEntry_caps0 (v : TLBEntry) (x : mword 1) : TLBEntry := {[ v with TLBEntry_TLBEntry_chunk_0 := (update_subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 30 30 (subrange_vec_dec x 0 0)) ]}. Definition _get_TLBEntry_capl0 (v : TLBEntry) : mword 1 := subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 29 29. Definition _set_TLBEntry_capl0 (r_ref : register_ref regstate register_value TLBEntry) (v : mword 1) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with TLBEntry_TLBEntry_chunk_0 := (update_subrange_vec_dec r.(TLBEntry_TLBEntry_chunk_0) 29 29 (subrange_vec_dec v 0 0)) ]} : TLBEntry in write_reg r_ref r : M (unit). Definition _update_TLBEntry_capl0 (v : TLBEntry) (x : mword 1) : TLBEntry := {[ v with TLBEntry_TLBEntry_chunk_0 := (update_subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 29 29 (subrange_vec_dec x 0 0)) ]}. Definition _get_TLBEntry_pfn0 (v : TLBEntry) : mword 24 := subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 28 5. Definition _set_TLBEntry_pfn0 (r_ref : register_ref regstate register_value TLBEntry) (v : mword 24) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with TLBEntry_TLBEntry_chunk_0 := (update_subrange_vec_dec r.(TLBEntry_TLBEntry_chunk_0) 28 5 (subrange_vec_dec v 23 0)) ]} : TLBEntry in write_reg r_ref r : M (unit). Definition _update_TLBEntry_pfn0 (v : TLBEntry) (x : mword 24) : TLBEntry := {[ v with TLBEntry_TLBEntry_chunk_0 := (update_subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 28 5 (subrange_vec_dec x 23 0)) ]}. Definition _get_TLBEntry_c0 (v : TLBEntry) : mword 3 := subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 4 2. Definition _set_TLBEntry_c0 (r_ref : register_ref regstate register_value TLBEntry) (v : mword 3) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with TLBEntry_TLBEntry_chunk_0 := (update_subrange_vec_dec r.(TLBEntry_TLBEntry_chunk_0) 4 2 (subrange_vec_dec v 2 0)) ]} : TLBEntry in write_reg r_ref r : M (unit). Definition _update_TLBEntry_c0 (v : TLBEntry) (x : mword 3) : TLBEntry := {[ v with TLBEntry_TLBEntry_chunk_0 := (update_subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 4 2 (subrange_vec_dec x 2 0)) ]}. Definition _get_TLBEntry_d0 (v : TLBEntry) : mword 1 := subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 1 1. Definition _set_TLBEntry_d0 (r_ref : register_ref regstate register_value TLBEntry) (v : mword 1) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with TLBEntry_TLBEntry_chunk_0 := (update_subrange_vec_dec r.(TLBEntry_TLBEntry_chunk_0) 1 1 (subrange_vec_dec v 0 0)) ]} : TLBEntry in write_reg r_ref r : M (unit). Definition _update_TLBEntry_d0 (v : TLBEntry) (x : mword 1) : TLBEntry := {[ v with TLBEntry_TLBEntry_chunk_0 := (update_subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 1 1 (subrange_vec_dec x 0 0)) ]}. Definition _get_TLBEntry_v0 (v : TLBEntry) : mword 1 := subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 0 0. Definition _set_TLBEntry_v0 (r_ref : register_ref regstate register_value TLBEntry) (v : mword 1) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with TLBEntry_TLBEntry_chunk_0 := (update_subrange_vec_dec r.(TLBEntry_TLBEntry_chunk_0) 0 0 (subrange_vec_dec v 0 0)) ]} : TLBEntry in write_reg r_ref r : M (unit). Definition _update_TLBEntry_v0 (v : TLBEntry) (x : mword 1) : TLBEntry := {[ v with TLBEntry_TLBEntry_chunk_0 := (update_subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 0 0 (subrange_vec_dec x 0 0)) ]}. Definition TLBEntries : vec (register_ref regstate register_value TLBEntry) 64 := vec_of_list_len [TLBEntry63_ref;TLBEntry62_ref;TLBEntry61_ref;TLBEntry60_ref;TLBEntry59_ref; TLBEntry58_ref;TLBEntry57_ref;TLBEntry56_ref;TLBEntry55_ref;TLBEntry54_ref; TLBEntry53_ref;TLBEntry52_ref;TLBEntry51_ref;TLBEntry50_ref;TLBEntry49_ref; TLBEntry48_ref;TLBEntry47_ref;TLBEntry46_ref;TLBEntry45_ref;TLBEntry44_ref; TLBEntry43_ref;TLBEntry42_ref;TLBEntry41_ref;TLBEntry40_ref;TLBEntry39_ref; TLBEntry38_ref;TLBEntry37_ref;TLBEntry36_ref;TLBEntry35_ref;TLBEntry34_ref; TLBEntry33_ref;TLBEntry32_ref;TLBEntry31_ref;TLBEntry30_ref;TLBEntry29_ref; TLBEntry28_ref;TLBEntry27_ref;TLBEntry26_ref;TLBEntry25_ref;TLBEntry24_ref; TLBEntry23_ref;TLBEntry22_ref;TLBEntry21_ref;TLBEntry20_ref;TLBEntry19_ref; TLBEntry18_ref;TLBEntry17_ref;TLBEntry16_ref;TLBEntry15_ref;TLBEntry14_ref; TLBEntry13_ref;TLBEntry12_ref;TLBEntry11_ref;TLBEntry10_ref;TLBEntry09_ref; TLBEntry08_ref;TLBEntry07_ref;TLBEntry06_ref;TLBEntry05_ref;TLBEntry04_ref; TLBEntry03_ref;TLBEntry02_ref;TLBEntry01_ref;TLBEntry00_ref]. Hint Unfold TLBEntries : sail. Definition undefined_StatusReg '(tt : unit) : M (StatusReg) := (undefined_bitvector 32) >>= fun w__0 : mword 32 => returnm ({| StatusReg_StatusReg_chunk_0 := w__0 |}). Definition Mk_StatusReg (v : mword 32) : StatusReg := {| StatusReg_StatusReg_chunk_0 := (subrange_vec_dec v 31 0) |}. Definition _get_StatusReg_bits (v : StatusReg) : mword 32 := subrange_vec_dec v.(StatusReg_StatusReg_chunk_0) 31 0. Definition _set_StatusReg_bits (r_ref : register_ref regstate register_value StatusReg) (v : mword 32) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with StatusReg_StatusReg_chunk_0 := (update_subrange_vec_dec r.(StatusReg_StatusReg_chunk_0) 31 0 (subrange_vec_dec v 31 0)) ]} : StatusReg in write_reg r_ref r : M (unit). Definition _update_StatusReg_bits (v : StatusReg) (x : mword 32) : StatusReg := {[ v with StatusReg_StatusReg_chunk_0 := (update_subrange_vec_dec v.(StatusReg_StatusReg_chunk_0) 31 0 (subrange_vec_dec x 31 0)) ]}. Definition _get_StatusReg_CU (v : StatusReg) : mword 4 := subrange_vec_dec v.(StatusReg_StatusReg_chunk_0) 31 28. Definition _set_StatusReg_CU (r_ref : register_ref regstate register_value StatusReg) (v : mword 4) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with StatusReg_StatusReg_chunk_0 := (update_subrange_vec_dec r.(StatusReg_StatusReg_chunk_0) 31 28 (subrange_vec_dec v 3 0)) ]} : StatusReg in write_reg r_ref r : M (unit). Definition _update_StatusReg_CU (v : StatusReg) (x : mword 4) : StatusReg := {[ v with StatusReg_StatusReg_chunk_0 := (update_subrange_vec_dec v.(StatusReg_StatusReg_chunk_0) 31 28 (subrange_vec_dec x 3 0)) ]}. Definition _get_StatusReg_BEV (v : StatusReg) : mword 1 := subrange_vec_dec v.(StatusReg_StatusReg_chunk_0) 22 22. Definition _set_StatusReg_BEV (r_ref : register_ref regstate register_value StatusReg) (v : mword 1) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with StatusReg_StatusReg_chunk_0 := (update_subrange_vec_dec r.(StatusReg_StatusReg_chunk_0) 22 22 (subrange_vec_dec v 0 0)) ]} : StatusReg in write_reg r_ref r : M (unit). Definition _update_StatusReg_BEV (v : StatusReg) (x : mword 1) : StatusReg := {[ v with StatusReg_StatusReg_chunk_0 := (update_subrange_vec_dec v.(StatusReg_StatusReg_chunk_0) 22 22 (subrange_vec_dec x 0 0)) ]}. Definition _get_StatusReg_IM (v : StatusReg) : mword 8 := subrange_vec_dec v.(StatusReg_StatusReg_chunk_0) 15 8. Definition _set_StatusReg_IM (r_ref : register_ref regstate register_value StatusReg) (v : mword 8) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with StatusReg_StatusReg_chunk_0 := (update_subrange_vec_dec r.(StatusReg_StatusReg_chunk_0) 15 8 (subrange_vec_dec v 7 0)) ]} : StatusReg in write_reg r_ref r : M (unit). Definition _update_StatusReg_IM (v : StatusReg) (x : mword 8) : StatusReg := {[ v with StatusReg_StatusReg_chunk_0 := (update_subrange_vec_dec v.(StatusReg_StatusReg_chunk_0) 15 8 (subrange_vec_dec x 7 0)) ]}. Definition _get_StatusReg_KX (v : StatusReg) : mword 1 := subrange_vec_dec v.(StatusReg_StatusReg_chunk_0) 7 7. Definition _set_StatusReg_KX (r_ref : register_ref regstate register_value StatusReg) (v : mword 1) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with StatusReg_StatusReg_chunk_0 := (update_subrange_vec_dec r.(StatusReg_StatusReg_chunk_0) 7 7 (subrange_vec_dec v 0 0)) ]} : StatusReg in write_reg r_ref r : M (unit). Definition _update_StatusReg_KX (v : StatusReg) (x : mword 1) : StatusReg := {[ v with StatusReg_StatusReg_chunk_0 := (update_subrange_vec_dec v.(StatusReg_StatusReg_chunk_0) 7 7 (subrange_vec_dec x 0 0)) ]}. Definition _get_StatusReg_SX (v : StatusReg) : mword 1 := subrange_vec_dec v.(StatusReg_StatusReg_chunk_0) 6 6. Definition _set_StatusReg_SX (r_ref : register_ref regstate register_value StatusReg) (v : mword 1) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with StatusReg_StatusReg_chunk_0 := (update_subrange_vec_dec r.(StatusReg_StatusReg_chunk_0) 6 6 (subrange_vec_dec v 0 0)) ]} : StatusReg in write_reg r_ref r : M (unit). Definition _update_StatusReg_SX (v : StatusReg) (x : mword 1) : StatusReg := {[ v with StatusReg_StatusReg_chunk_0 := (update_subrange_vec_dec v.(StatusReg_StatusReg_chunk_0) 6 6 (subrange_vec_dec x 0 0)) ]}. Definition _get_StatusReg_UX (v : StatusReg) : mword 1 := subrange_vec_dec v.(StatusReg_StatusReg_chunk_0) 5 5. Definition _set_StatusReg_UX (r_ref : register_ref regstate register_value StatusReg) (v : mword 1) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with StatusReg_StatusReg_chunk_0 := (update_subrange_vec_dec r.(StatusReg_StatusReg_chunk_0) 5 5 (subrange_vec_dec v 0 0)) ]} : StatusReg in write_reg r_ref r : M (unit). Definition _update_StatusReg_UX (v : StatusReg) (x : mword 1) : StatusReg := {[ v with StatusReg_StatusReg_chunk_0 := (update_subrange_vec_dec v.(StatusReg_StatusReg_chunk_0) 5 5 (subrange_vec_dec x 0 0)) ]}. Definition _get_StatusReg_KSU (v : StatusReg) : mword 2 := subrange_vec_dec v.(StatusReg_StatusReg_chunk_0) 4 3. Definition _set_StatusReg_KSU (r_ref : register_ref regstate register_value StatusReg) (v : mword 2) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with StatusReg_StatusReg_chunk_0 := (update_subrange_vec_dec r.(StatusReg_StatusReg_chunk_0) 4 3 (subrange_vec_dec v 1 0)) ]} : StatusReg in write_reg r_ref r : M (unit). Definition _update_StatusReg_KSU (v : StatusReg) (x : mword 2) : StatusReg := {[ v with StatusReg_StatusReg_chunk_0 := (update_subrange_vec_dec v.(StatusReg_StatusReg_chunk_0) 4 3 (subrange_vec_dec x 1 0)) ]}. Definition _get_StatusReg_ERL (v : StatusReg) : mword 1 := subrange_vec_dec v.(StatusReg_StatusReg_chunk_0) 2 2. Definition _set_StatusReg_ERL (r_ref : register_ref regstate register_value StatusReg) (v : mword 1) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with StatusReg_StatusReg_chunk_0 := (update_subrange_vec_dec r.(StatusReg_StatusReg_chunk_0) 2 2 (subrange_vec_dec v 0 0)) ]} : StatusReg in write_reg r_ref r : M (unit). Definition _update_StatusReg_ERL (v : StatusReg) (x : mword 1) : StatusReg := {[ v with StatusReg_StatusReg_chunk_0 := (update_subrange_vec_dec v.(StatusReg_StatusReg_chunk_0) 2 2 (subrange_vec_dec x 0 0)) ]}. Definition _get_StatusReg_EXL (v : StatusReg) : mword 1 := subrange_vec_dec v.(StatusReg_StatusReg_chunk_0) 1 1. Definition _set_StatusReg_EXL (r_ref : register_ref regstate register_value StatusReg) (v : mword 1) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with StatusReg_StatusReg_chunk_0 := (update_subrange_vec_dec r.(StatusReg_StatusReg_chunk_0) 1 1 (subrange_vec_dec v 0 0)) ]} : StatusReg in write_reg r_ref r : M (unit). Definition _update_StatusReg_EXL (v : StatusReg) (x : mword 1) : StatusReg := {[ v with StatusReg_StatusReg_chunk_0 := (update_subrange_vec_dec v.(StatusReg_StatusReg_chunk_0) 1 1 (subrange_vec_dec x 0 0)) ]}. Definition _get_StatusReg_IE (v : StatusReg) : mword 1 := subrange_vec_dec v.(StatusReg_StatusReg_chunk_0) 0 0. Definition _set_StatusReg_IE (r_ref : register_ref regstate register_value StatusReg) (v : mword 1) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with StatusReg_StatusReg_chunk_0 := (update_subrange_vec_dec r.(StatusReg_StatusReg_chunk_0) 0 0 (subrange_vec_dec v 0 0)) ]} : StatusReg in write_reg r_ref r : M (unit). Definition _update_StatusReg_IE (v : StatusReg) (x : mword 1) : StatusReg := {[ v with StatusReg_StatusReg_chunk_0 := (update_subrange_vec_dec v.(StatusReg_StatusReg_chunk_0) 0 0 (subrange_vec_dec x 0 0)) ]}. Definition execute_branch_mips (pc : mword 64) : M (unit) := write_reg DelayedPC_ref pc >> write_reg BranchPending_ref ('b"1" : mword 1) >> write_reg NextInBranchDelay_ref ('b"1" : mword 1) : M (unit). Definition NotWordVal (word : mword 64) : bool := neq_vec (zopz0zQzQ (cast_unit_vec (access_vec_dec word 31)) 32) (subrange_vec_dec word 63 32). Definition rGPR (idx : mword 5) : M (mword 64) := let i := projT1 (uint idx) in (if sumbool_of_bool (Z.eqb i 0) then returnm (Ox"0000000000000000" : mword 64) else read_reg GPR_ref >>= fun w__0 : vec (mword 64) 32 => returnm (vec_access_dec w__0 i)) : M (mword 64). Definition wGPR (idx : mword 5) (v : mword 64) : M (unit) := let i := projT1 (uint idx) in (if sumbool_of_bool (projT1 (neq_int i 0)) then let '_ := (if sumbool_of_bool trace then let '_ := (prerr (string_of_int i)) : unit in prerr_bits " <- " v else tt) : unit in read_reg GPR_ref >>= fun w__0 : vec (mword 64) 32 => write_reg GPR_ref (vec_update_dec w__0 i v) : M (unit) else returnm tt) : M (unit). Definition Exception_of_num (arg_ : Z) `{ArithFact ((0 <=? arg_) && (arg_ <=? 18))} : Exception := let l__140 := arg_ in if sumbool_of_bool (Z.eqb l__140 0) then Interrupt else if sumbool_of_bool (Z.eqb l__140 1) then TLBMod else if sumbool_of_bool (Z.eqb l__140 2) then TLBL else if sumbool_of_bool (Z.eqb l__140 3) then TLBS else if sumbool_of_bool (Z.eqb l__140 4) then AdEL else if sumbool_of_bool (Z.eqb l__140 5) then AdES else if sumbool_of_bool (Z.eqb l__140 6) then Sys else if sumbool_of_bool (Z.eqb l__140 7) then Bp else if sumbool_of_bool (Z.eqb l__140 8) then ResI else if sumbool_of_bool (Z.eqb l__140 9) then CpU else if sumbool_of_bool (Z.eqb l__140 10) then Ov else if sumbool_of_bool (Z.eqb l__140 11) then Tr else if sumbool_of_bool (Z.eqb l__140 12) then C2E else if sumbool_of_bool (Z.eqb l__140 13) then C2Trap else if sumbool_of_bool (Z.eqb l__140 14) then XTLBRefillL else if sumbool_of_bool (Z.eqb l__140 15) then XTLBRefillS else if sumbool_of_bool (Z.eqb l__140 16) then XTLBInvL else if sumbool_of_bool (Z.eqb l__140 17) then XTLBInvS else MCheck. Definition num_of_Exception (arg_ : Exception) : {e : Z & ArithFact ((0 <=? e) && (e <=? 18))} := build_ex ( match arg_ with | Interrupt => 0 | TLBMod => 1 | TLBL => 2 | TLBS => 3 | AdEL => 4 | AdES => 5 | Sys => 6 | Bp => 7 | ResI => 8 | CpU => 9 | Ov => 10 | Tr => 11 | C2E => 12 | C2Trap => 13 | XTLBRefillL => 14 | XTLBRefillS => 15 | XTLBInvL => 16 | XTLBInvS => 17 | MCheck => 18 end ). Definition undefined_Exception '(tt : unit) : M (Exception) := (internal_pick [Interrupt; TLBMod; TLBL; TLBS; AdEL; AdES; Sys; Bp; ResI; CpU; Ov; Tr; C2E; C2Trap; XTLBRefillL; XTLBRefillS; XTLBInvL; XTLBInvS; MCheck]) : M (Exception). Definition ExceptionCode (ex : Exception) : mword 5 := let x : bits 8 := match ex with | Interrupt => Ox"00" : mword 8 | TLBMod => Ox"01" : mword 8 | TLBL => Ox"02" : mword 8 | TLBS => Ox"03" : mword 8 | AdEL => Ox"04" : mword 8 | AdES => Ox"05" : mword 8 | Sys => Ox"08" : mword 8 | Bp => Ox"09" : mword 8 | ResI => Ox"0A" : mword 8 | CpU => Ox"0B" : mword 8 | Ov => Ox"0C" : mword 8 | Tr => Ox"0D" : mword 8 | C2E => Ox"12" : mword 8 | C2Trap => Ox"12" : mword 8 | XTLBRefillL => Ox"02" : mword 8 | XTLBRefillS => Ox"03" : mword 8 | XTLBInvL => Ox"02" : mword 8 | XTLBInvS => Ox"03" : mword 8 | MCheck => Ox"18" : mword 8 end in subrange_vec_dec x 4 0. Definition string_of_exception (ex : Exception) : string := match ex with | Interrupt => "Interrupt" | TLBMod => "TLBMod" | TLBL => "TLBL" | TLBS => "TLBS" | AdEL => "AdEL" | AdES => "AdES" | Sys => "Sys" | Bp => "Bp " | ResI => "ResI" | CpU => "CpU" | Ov => "Ov" | Tr => "Tr" | C2E => "C2E" | C2Trap => "C2Trap" | XTLBRefillL => "XTLBRefillL" | XTLBRefillS => "XTLBRefillS" | XTLBInvL => "XTLBInvL" | XTLBInvS => "XTLBInvS" | MCheck => "MCheck" end. Definition traceException (ex : Exception) : unit := if sumbool_of_bool trace then let '_ := (prerr " EXCEPTION ") : unit in prerr_endline (string_of_exception ex) else tt. Definition exceptionVectorOffset (ex : Exception) : M (mword 12) := read_reg CP0Status_ref >>= fun w__0 : StatusReg => returnm (if (bits_to_bool (_get_StatusReg_EXL w__0)) : bool then Ox"180" : mword 12 else if orb (generic_eq ex XTLBRefillL) (generic_eq ex XTLBRefillS) then Ox"080" : mword 12 else if generic_eq ex C2Trap then Ox"280" : mword 12 else Ox"180" : mword 12). Definition exceptionVectorBase '(tt : unit) : M (mword 64) := read_reg CP0Status_ref >>= fun w__0 : StatusReg => returnm (if (bits_to_bool (_get_StatusReg_BEV w__0)) : bool then Ox"FFFFFFFFBFC00200" : mword 64 else Ox"FFFFFFFF80000000" : mword 64). Definition updateBadInstr '(tt : unit) : M (unit) := ((read_reg InBranchDelay_ref) : M (mword 1)) >>= fun w__0 : mword 1 => (if (bit_to_bool (access_vec_dec w__0 0)) : bool then ((read_reg LastInstrBits_ref) : M (mword 32)) >>= fun w__1 : mword 32 => write_reg CP0BadInstrP_ref w__1 : M (unit) else returnm tt) >> ((read_reg CurrentInstrBits_ref) : M (mword 32)) >>= fun w__2 : mword 32 => write_reg CP0BadInstr_ref w__2 : M (unit). Definition undefined_Capability '(tt : unit) : M (Capability) := (undefined_bool tt) >>= fun w__0 : bool => (undefined_bitvector 4) >>= fun w__1 : mword 4 => (undefined_bool tt) >>= fun w__2 : bool => (undefined_bool tt) >>= fun w__3 : bool => (undefined_bool tt) >>= fun w__4 : bool => (undefined_bool tt) >>= fun w__5 : bool => (undefined_bool tt) >>= fun w__6 : bool => (undefined_bool tt) >>= fun w__7 : bool => (undefined_bool tt) >>= fun w__8 : bool => (undefined_bool tt) >>= fun w__9 : bool => (undefined_bool tt) >>= fun w__10 : bool => (undefined_bool tt) >>= fun w__11 : bool => (undefined_bool tt) >>= fun w__12 : bool => (undefined_bool tt) >>= fun w__13 : bool => (undefined_bitvector 3) >>= fun w__14 : mword 3 => (undefined_bool tt) >>= fun w__15 : bool => (undefined_bitvector 6) >>= fun w__16 : mword 6 => (undefined_bool tt) >>= fun w__17 : bool => (undefined_bitvector 14) >>= fun w__18 : mword 14 => (undefined_bitvector 14) >>= fun w__19 : mword 14 => (undefined_bitvector 18) >>= fun w__20 : mword 18 => (undefined_bitvector 64) >>= fun w__21 : mword 64 => returnm ({| Capability_tag := w__0; Capability_uperms := w__1; Capability_permit_set_CID := w__2; Capability_access_system_regs := w__3; Capability_permit_unseal := w__4; Capability_permit_ccall := w__5; Capability_permit_seal := w__6; Capability_permit_store_local_cap := w__7; Capability_permit_store_cap := w__8; Capability_permit_load_cap := w__9; Capability_permit_store := w__10; Capability_permit_load := w__11; Capability_permit_execute := w__12; Capability_global := w__13; Capability_reserved := w__14; Capability_internal_e := w__15; Capability_E := w__16; Capability_sealed := w__17; Capability_B := w__18; Capability_T := w__19; Capability_otype := w__20; Capability_address := w__21 |}). Definition getCapBounds (c : Capability) : ({rangevar : Z & ArithFact ((0 <=? rangevar) && (rangevar <=? (2 ^ 64 - 1)))} * {rangevar : Z & ArithFact ((0 <=? rangevar) && (rangevar <=? (2 ^ 65)))}) := let E := projT1 (uint c.(Capability_E)) in let a : bits 64 := c.(Capability_address) in let a3 := vector_truncate (shiftr a (Z.add E 11)) 3 in let B3 := vector_truncateLSB c.(Capability_B) 3 in let T3 := vector_truncateLSB c.(Capability_T) 3 in let R3 := sub_vec B3 ('b"001" : mword 3) in let aHi := if zopz0zI_u a3 R3 then 1 else 0 in let bHi := if zopz0zI_u B3 R3 then 1 else 0 in let tHi := if zopz0zI_u T3 R3 then 1 else 0 in let correction_base := Z.sub bHi aHi in let correction_top := Z.sub tHi aHi in let a_top := shiftr a (Z.add E 14) in let base : bits 65 := vector_truncate (concat_vec (add_vec_int a_top correction_base) (concat_vec c.(Capability_B) (zeros E))) 65 in let top : bits 65 := vector_truncate (concat_vec (add_vec_int a_top correction_top) (concat_vec c.(Capability_T) (zeros E))) 65 in let top : mword 65 := if eq_bit (access_vec_dec base 64) B1 then update_vec_dec top 64 (if sumbool_of_bool (andb (Z.eqb aHi 1) (Z.eqb tHi 1)) then B1 else B0) else top in (build_ex (projT1 (uint (subrange_vec_dec base 63 0))), build_ex (projT1 (uint top))). Definition getCapBase (c : Capability) : {rangevar : Z & ArithFact ((0 <=? rangevar) && (rangevar <=? (2 ^ 64 - 1)))} := build_ex ( let '(existT _ base _, existT _ _ _) := getCapBounds c in base ). Definition capBoundsEqual (c1 : Capability) (c2 : Capability) : bool := let '(existT _ base1 _, existT _ top1 _) := getCapBounds c1 in let '(existT _ base2 _, existT _ top2 _) := getCapBounds c2 in andb (Z.eqb base1 base2) (Z.eqb top1 top2). Definition setCapOffset (c : Capability) (offset : mword 64) : (bool * Capability) := let base64 : bits 64 := to_bits 64 (projT1 (getCapBase c)) in let newAddress : bits 64 := add_vec base64 offset in let newCap := {[ c with Capability_address := newAddress ]} in let representable := capBoundsEqual c newCap in (representable, newCap). Definition set_next_pcc (newPCC : Capability) : M (unit) := write_reg NextPCC_ref newPCC >> write_reg DelayedPCC_ref newPCC : M (unit). Definition unrepCap (cap : Capability) : Capability := {[ cap with Capability_tag := false ]}. Definition SignalException {o : Type} (ex : Exception) : M (o) := let '_ := (traceException ex) : unit in read_reg CP0Status_ref >>= fun w__0 : StatusReg => (if negb (bits_to_bool (_get_StatusReg_EXL w__0)) then ((read_reg InBranchDelay_ref) : M (mword 1)) >>= fun w__1 : mword 1 => (if (bit_to_bool (access_vec_dec w__1 0)) : bool then (_set_CauseReg_BD CP0Cause_ref ('b"1" : mword 1)) >> ((read_reg PC_ref) : M (mword 64)) >>= fun w__2 : mword 64 => returnm (sub_vec_int w__2 4) else (_set_CauseReg_BD CP0Cause_ref ('b"0" : mword 1)) >> ((read_reg PC_ref) : M (mword 64)) : M (mword 64)) >>= fun epc : bits 64 => read_reg PCC_ref >>= fun w__4 : Capability => let '(representable, newEPCC) := setCapOffset w__4 epc in let '_ := (if sumbool_of_bool (negb representable) then print_endline "UNREPRESENTABLE EPCC!" else tt) : unit in let '_ := (if newEPCC.(Capability_sealed) then print_endline "SEALED PCC!" else tt) : unit in write_reg EPCC_ref (if sumbool_of_bool (andb representable (negb newEPCC.(Capability_sealed))) then newEPCC else unrepCap newEPCC) : M (unit) else returnm tt) >> (updateBadInstr tt) >> (exceptionVectorOffset ex) >>= fun vectorOffset => (exceptionVectorBase tt) >>= fun vectorBase => read_reg KCC_ref >>= fun w__5 : Capability => let kccBase := projT1 (getCapBase w__5) in write_reg NextPC_ref (sub_vec (add_vec vectorBase (mips_zero_extend 64 vectorOffset)) (to_bits 64 kccBase)) >> read_reg KCC_ref >>= fun w__6 : Capability => (set_next_pcc w__6) >> (_set_CauseReg_ExcCode CP0Cause_ref (ExceptionCode ex)) >> (_set_StatusReg_EXL CP0Status_ref ('b"1" : mword 1)) >> throw (ISAException tt). Definition SignalExceptionBadAddr {o : Type} (ex : Exception) (badAddr : mword 64) : M (o) := write_reg CP0BadVAddr_ref badAddr >> (SignalException ex) : M (o). Definition SignalExceptionTLB {o : Type} (ex : Exception) (badAddr : mword 64) : M (o) := write_reg CP0BadVAddr_ref badAddr >> (_set_ContextReg_BadVPN2 TLBContext_ref (subrange_vec_dec badAddr 31 13)) >> (_set_XContextReg_XBadVPN2 TLBXContext_ref (subrange_vec_dec badAddr 39 13)) >> (_set_XContextReg_XR TLBXContext_ref (subrange_vec_dec badAddr 63 62)) >> (_set_TLBEntryHiReg_R TLBEntryHi_ref (subrange_vec_dec badAddr 63 62)) >> (_set_TLBEntryHiReg_VPN2 TLBEntryHi_ref (subrange_vec_dec badAddr 39 13)) >> (SignalException ex) : M (o). Definition MemAccessType_of_num (arg_ : Z) `{ArithFact ((0 <=? arg_) && (arg_ <=? 2))} : MemAccessType := let l__138 := arg_ in if sumbool_of_bool (Z.eqb l__138 0) then Instruction else if sumbool_of_bool (Z.eqb l__138 1) then LoadData else StoreData. Definition num_of_MemAccessType (arg_ : MemAccessType) : {e : Z & ArithFact ((0 <=? e) && (e <=? 2))} := build_ex (match arg_ with | Instruction => 0 | LoadData => 1 | StoreData => 2 end). Definition undefined_MemAccessType '(tt : unit) : M (MemAccessType) := (internal_pick [Instruction; LoadData; StoreData]) : M (MemAccessType). Definition MemAccessCapRestriction_of_num (arg_ : Z) `{ArithFact ((0 <=? arg_) && (arg_ <=? 2))} : MemAccessCapRestriction := let l__136 := arg_ in if sumbool_of_bool (Z.eqb l__136 0) then Unrestricted else if sumbool_of_bool (Z.eqb l__136 1) then Trap else Clear. Definition num_of_MemAccessCapRestriction (arg_ : MemAccessCapRestriction) : {e : Z & ArithFact ((0 <=? e) && (e <=? 2))} := build_ex (match arg_ with | Unrestricted => 0 | Trap => 1 | Clear => 2 end). Definition undefined_MemAccessCapRestriction '(tt : unit) : M (MemAccessCapRestriction) := (internal_pick [Unrestricted; Trap; Clear]) : M (MemAccessCapRestriction). Definition AccessLevel_of_num (arg_ : Z) `{ArithFact ((0 <=? arg_) && (arg_ <=? 2))} : AccessLevel := let l__134 := arg_ in if sumbool_of_bool (Z.eqb l__134 0) then User else if sumbool_of_bool (Z.eqb l__134 1) then Supervisor else Kernel. Definition num_of_AccessLevel (arg_ : AccessLevel) : {e : Z & ArithFact ((0 <=? e) && (e <=? 2))} := build_ex (match arg_ with | User => 0 | Supervisor => 1 | Kernel => 2 end). Definition undefined_AccessLevel '(tt : unit) : M (AccessLevel) := (internal_pick [User; Supervisor; Kernel]) : M (AccessLevel). Definition int_of_AccessLevel (level : AccessLevel) : {n : Z & ArithFact (member_Z_list n [0; 1; 2])} := build_ex (match level with | User => 0 | Supervisor => 1 | Kernel => 2 end). Definition grantsAccess (currentLevel : AccessLevel) (requiredLevel : AccessLevel) : bool := Z.geb (projT1 (int_of_AccessLevel currentLevel)) (projT1 (int_of_AccessLevel requiredLevel)). Definition getAccessLevel '(tt : unit) : M (AccessLevel) := (or_boolM (read_reg CP0Status_ref >>= fun w__0 : StatusReg => returnm ((bits_to_bool (_get_StatusReg_EXL w__0)) : bool)) (read_reg CP0Status_ref >>= fun w__1 : StatusReg => returnm ((bits_to_bool (_get_StatusReg_ERL w__1)) : bool))) >>= fun w__2 : bool => (if sumbool_of_bool w__2 then returnm Kernel else read_reg CP0Status_ref >>= fun w__3 : StatusReg => let p__158 := _get_StatusReg_KSU w__3 in let b__0 := p__158 in returnm (if eq_vec b__0 ('b"00" : mword 2) then Kernel else if eq_vec b__0 ('b"01" : mword 2) then Supervisor else if eq_vec b__0 ('b"10" : mword 2) then User else User)) : M (AccessLevel). Definition pcc_access_system_regs '(tt : unit) : M (bool) := read_reg PCC_ref >>= fun w__0 : Capability => returnm w__0.(Capability_access_system_regs). Definition undefined_CapCauseReg '(tt : unit) : M (CapCauseReg) := (undefined_bitvector 16) >>= fun w__0 : mword 16 => returnm ({| CapCauseReg_CapCauseReg_chunk_0 := w__0 |}). Definition CapExCode (ex : CapEx) : mword 8 := match ex with | CapEx_None => Ox"00" : mword 8 | CapEx_LengthViolation => Ox"01" : mword 8 | CapEx_TagViolation => Ox"02" : mword 8 | CapEx_SealViolation => Ox"03" : mword 8 | CapEx_TypeViolation => Ox"04" : mword 8 | CapEx_CallTrap => Ox"05" : mword 8 | CapEx_ReturnTrap => Ox"06" : mword 8 | CapEx_TSSUnderFlow => Ox"07" : mword 8 | CapEx_UserDefViolation => Ox"08" : mword 8 | CapEx_TLBNoStoreCap => Ox"09" : mword 8 | CapEx_InexactBounds => Ox"0A" : mword 8 | CapEx_TLBLoadCap => Ox"0C" : mword 8 | CapEx_GlobalViolation => Ox"10" : mword 8 | CapEx_PermitExecuteViolation => Ox"11" : mword 8 | CapEx_PermitLoadViolation => Ox"12" : mword 8 | CapEx_PermitStoreViolation => Ox"13" : mword 8 | CapEx_PermitLoadCapViolation => Ox"14" : mword 8 | CapEx_PermitStoreCapViolation => Ox"15" : mword 8 | CapEx_PermitStoreLocalCapViolation => Ox"16" : mword 8 | CapEx_PermitSealViolation => Ox"17" : mword 8 | CapEx_AccessSystemRegsViolation => Ox"18" : mword 8 | CapEx_PermitCCallViolation => Ox"19" : mword 8 | CapEx_AccessCCallIDCViolation => Ox"1A" : mword 8 | CapEx_PermitUnsealViolation => Ox"1B" : mword 8 | CapEx_PermitSetCIDViolation => Ox"1C" : mword 8 end. Definition _set_CapCauseReg_ExcCode (r_ref : register_ref regstate register_value CapCauseReg) (v : mword 8) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with CapCauseReg_CapCauseReg_chunk_0 := (update_subrange_vec_dec r.(CapCauseReg_CapCauseReg_chunk_0) 15 8 (subrange_vec_dec v 7 0)) ]} : CapCauseReg in write_reg r_ref r : M (unit). Definition _set_CapCauseReg_RegNum (r_ref : register_ref regstate register_value CapCauseReg) (v : mword 8) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with CapCauseReg_CapCauseReg_chunk_0 := (update_subrange_vec_dec r.(CapCauseReg_CapCauseReg_chunk_0) 7 0 (subrange_vec_dec v 7 0)) ]} : CapCauseReg in write_reg r_ref r : M (unit). Definition string_of_capex (ex : CapEx) : string := match ex with | CapEx_None => "None" | CapEx_LengthViolation => "LengthViolation" | CapEx_TagViolation => "TagViolation" | CapEx_SealViolation => "SealViolation" | CapEx_TypeViolation => "TypeViolation" | CapEx_CallTrap => "CallTrap" | CapEx_ReturnTrap => "ReturnTrap" | CapEx_TSSUnderFlow => "TSSUnderFlow" | CapEx_UserDefViolation => "UserDefViolation" | CapEx_TLBNoStoreCap => "TLBNoStoreCap" | CapEx_InexactBounds => "InexactBounds" | CapEx_GlobalViolation => "GlobalViolation" | CapEx_PermitExecuteViolation => "PermitExecuteViolation" | CapEx_PermitLoadViolation => "PermitLoadViolation" | CapEx_PermitStoreViolation => "PermitStoreViolation" | CapEx_PermitLoadCapViolation => "PermitLoadCapViolation" | CapEx_PermitStoreCapViolation => "PermitStoreCapViolation" | CapEx_PermitStoreLocalCapViolation => "PermitStoreLocalCapViolation" | CapEx_PermitSealViolation => "PermitSealViolation" | CapEx_AccessSystemRegsViolation => "AccessSystemRegsViolation" | CapEx_PermitCCallViolation => "PermitCCallViolation" | CapEx_AccessCCallIDCViolation => "AccessCCallIDCViolation" | CapEx_PermitUnsealViolation => "PermitUnsealViolation" | CapEx_PermitSetCIDViolation => "PermitSetCIDViolation" | CapEx_TLBLoadCap => "TLBLoadCap" end. Definition raise_c2_exception8 {o : Type} (capEx : CapEx) (regnum : mword 8) : M (o) := let '_ := (if sumbool_of_bool trace then let '_ := (prerr " C2Ex ") : unit in let '_ := (prerr (string_of_capex capEx)) : unit in let '_ := (prerr " reg: ") : unit in prerr_endline (string_of_bits regnum) else tt) : unit in (_set_CapCauseReg_ExcCode CapCause_ref (CapExCode capEx)) >> (_set_CapCauseReg_RegNum CapCause_ref regnum) >> let mipsEx := if orb (generic_eq capEx CapEx_CallTrap) (generic_eq capEx CapEx_ReturnTrap) then C2Trap else C2E in (SignalException mipsEx) : M (o). Definition raise_c2_exception_noreg {o : Type} (capEx : CapEx) : M (o) := (raise_c2_exception8 capEx (Ox"FF" : mword 8)) : M (o). Definition checkCP0AccessHook '(tt : unit) : M (unit) := (pcc_access_system_regs tt) >>= fun w__0 : bool => (if sumbool_of_bool (negb w__0) then (raise_c2_exception_noreg CapEx_AccessSystemRegsViolation) : M (unit) else returnm tt) : M (unit). Definition checkCP0Access '(tt : unit) : M (unit) := (getAccessLevel tt) >>= fun accessLevel => (and_boolM (returnm ((generic_neq accessLevel Kernel) : bool)) (read_reg CP0Status_ref >>= fun w__0 : StatusReg => returnm ((negb (bit_to_bool (access_vec_dec (_get_StatusReg_CU w__0) 0))) : bool))) >>= fun w__1 : bool => (if sumbool_of_bool w__1 then (_set_CauseReg_CE CP0Cause_ref ('b"00" : mword 2)) >> (SignalException CpU) : M (unit) else returnm tt) >> (checkCP0AccessHook tt) : M (unit). Definition incrementCP0Count '(tt : unit) : M (unit) := ((read_reg TLBRandom_ref) : M (mword 6)) >>= fun w__0 : mword 6 => ((read_reg TLBWired_ref) : M (mword 6)) >>= fun w__1 : mword 6 => (if eq_vec w__0 w__1 then returnm TLBIndexMax else ((read_reg TLBRandom_ref) : M (mword 6)) >>= fun w__2 : mword 6 => returnm (sub_vec_int w__2 1)) >>= fun w__3 : mword 6 => write_reg TLBRandom_ref w__3 >> ((read_reg CP0Count_ref) : M (mword 32)) >>= fun w__4 : mword 32 => write_reg CP0Count_ref (add_vec_int w__4 1) >> ((read_reg CP0Count_ref) : M (mword 32)) >>= fun w__5 : mword 32 => ((read_reg CP0Compare_ref) : M (mword 32)) >>= fun w__6 : mword 32 => (if eq_vec w__5 w__6 then read_reg CP0Cause_ref >>= fun w__7 : CauseReg => (_set_CauseReg_IP CP0Cause_ref (or_vec (_get_CauseReg_IP w__7) (Ox"80" : mword 8))) : M (unit) else returnm tt) >> read_reg CP0Status_ref >>= fun w__8 : StatusReg => let ims := _get_StatusReg_IM w__8 in read_reg CP0Cause_ref >>= fun w__9 : CauseReg => let ips := _get_CauseReg_IP w__9 in read_reg CP0Status_ref >>= fun w__10 : StatusReg => let ie := _get_StatusReg_IE w__10 in read_reg CP0Status_ref >>= fun w__11 : StatusReg => let exl := _get_StatusReg_EXL w__11 in read_reg CP0Status_ref >>= fun w__12 : StatusReg => let erl := _get_StatusReg_ERL w__12 in (if andb (negb (bits_to_bool exl)) (andb (negb (bits_to_bool erl)) (andb (bits_to_bool ie) (neq_vec (and_vec ips ims) (Ox"00" : mword 8)))) then (SignalException Interrupt) : M (unit) else returnm tt) : M (unit). Definition strReg (r : mword 5) : string := concat_str_dec "$" (projT1 (uint r)). Definition strRRRArgs (r2 : mword 5) (r1 : mword 5) (rd : mword 5) : string := String.append (strReg rd) (String.append ", " (String.append (strReg r1) (String.append ", " (strReg r2)))). Definition strRRIArgs {n : Z} (rs : mword 5) (rd : mword 5) (imm : mword n) `{ArithFact (n >? 0)} : string := String.append (strReg rd) (String.append ", " (String.append (strReg rs) (String.append ", " (dec_str (projT1 (sint imm)))))). Definition strRRIUArgs {n : Z} (rs : mword 5) (rd : mword 5) (imm : mword n) `{ArithFact (n >? 0)} : string := String.append (strReg rd) (String.append ", " (String.append (strReg rs) (String.append ", " (hex_str (projT1 (uint imm)))))). Definition strRIArgs {n : Z} (rd : mword 5) (imm : mword n) `{ArithFact (n >? 0)} : string := String.append (strReg rd) (String.append ", " (hex_str (projT1 (uint imm)))). Definition strMemArgs {n : Z} (base : mword 5) (rt : mword 5) (offset : mword n) `{ArithFact (n >? 0)} : string := String.append (strReg rt) (String.append ", " (String.append (dec_str (projT1 (sint offset))) (String.append "(" (String.append (strReg base) ")")))). Definition decode_failure_of_num (arg_ : Z) `{ArithFact ((0 <=? arg_) && (arg_ <=? 3))} : decode_failure := let l__131 := arg_ in if sumbool_of_bool (Z.eqb l__131 0) then no_matching_pattern else if sumbool_of_bool (Z.eqb l__131 1) then unsupported_instruction else if sumbool_of_bool (Z.eqb l__131 2) then illegal_instruction else internal_error. Definition num_of_decode_failure (arg_ : decode_failure) : {e : Z & ArithFact ((0 <=? e) && (e <=? 3))} := build_ex ( match arg_ with | no_matching_pattern => 0 | unsupported_instruction => 1 | illegal_instruction => 2 | internal_error => 3 end ). Definition undefined_decode_failure '(tt : unit) : M (decode_failure) := (internal_pick [no_matching_pattern; unsupported_instruction; illegal_instruction; internal_error]) : M (decode_failure). Definition Comparison_of_num (arg_ : Z) `{ArithFact ((0 <=? arg_) && (arg_ <=? 7))} : Comparison := let l__124 := arg_ in if sumbool_of_bool (Z.eqb l__124 0) then EQ' else if sumbool_of_bool (Z.eqb l__124 1) then NE else if sumbool_of_bool (Z.eqb l__124 2) then GE else if sumbool_of_bool (Z.eqb l__124 3) then GEU else if sumbool_of_bool (Z.eqb l__124 4) then GT' else if sumbool_of_bool (Z.eqb l__124 5) then LE else if sumbool_of_bool (Z.eqb l__124 6) then LT' else LTU. Definition num_of_Comparison (arg_ : Comparison) : {e : Z & ArithFact ((0 <=? e) && (e <=? 7))} := build_ex ( match arg_ with | EQ' => 0 | NE => 1 | GE => 2 | GEU => 3 | GT' => 4 | LE => 5 | LT' => 6 | LTU => 7 end ). Definition undefined_Comparison '(tt : unit) : M (Comparison) := (internal_pick [EQ'; NE; GE; GEU; GT'; LE; LT'; LTU]) : M (Comparison). Definition strCmp (cmp : Comparison) : string := match cmp with | EQ' => "eq" | NE => "ne" | GE => "ge" | GEU => "geu" | GT' => "gt" | LE => "le" | LT' => "lt" | LTU => "ltu" end. Definition compare (cmp : Comparison) (valA : mword 64) (valB : mword 64) : bool := match cmp with | EQ' => eq_vec valA valB | NE => neq_vec valA valB | GE => zopz0zKzJ_s valA valB | GEU => zopz0zKzJ_u valA valB | GT' => zopz0zI_s valB valA | LE => zopz0zKzJ_s valB valA | LT' => zopz0zI_s valA valB | LTU => zopz0zI_u valA valB end. Definition WordType_of_num (arg_ : Z) `{ArithFact ((0 <=? arg_) && (arg_ <=? 3))} : WordType := let l__121 := arg_ in if sumbool_of_bool (Z.eqb l__121 0) then B else if sumbool_of_bool (Z.eqb l__121 1) then H else if sumbool_of_bool (Z.eqb l__121 2) then W else D. Definition num_of_WordType (arg_ : WordType) : {e : Z & ArithFact ((0 <=? e) && (e <=? 3))} := build_ex (match arg_ with | B => 0 | H => 1 | W => 2 | D => 3 end). Definition undefined_WordType '(tt : unit) : M (WordType) := (internal_pick [B; H; W; D]) : M (WordType). Definition WordTypeUnaligned_of_num (arg_ : Z) `{ArithFact ((0 <=? arg_) && (arg_ <=? 3))} : WordTypeUnaligned := let l__118 := arg_ in if sumbool_of_bool (Z.eqb l__118 0) then WL else if sumbool_of_bool (Z.eqb l__118 1) then WR else if sumbool_of_bool (Z.eqb l__118 2) then DL else DR. Definition num_of_WordTypeUnaligned (arg_ : WordTypeUnaligned) : {e : Z & ArithFact ((0 <=? e) && (e <=? 3))} := build_ex (match arg_ with | WL => 0 | WR => 1 | DL => 2 | DR => 3 end). Definition undefined_WordTypeUnaligned '(tt : unit) : M (WordTypeUnaligned) := (internal_pick [WL; WR; DL; DR]) : M (WordTypeUnaligned). Definition strWordType (w : WordType) : string := match w with | B => "b" | H => "h" | W => "w" | D => "d" end. Definition unalignedBytesTouched (vAddr : Z) (width : WordTypeUnaligned) : (Z * Z) := let woffset := projT1 (emod_with_eq vAddr 4) in let doffset := projT1 (emod_with_eq vAddr 8) in match width with | WL => (vAddr, Z.sub 4 woffset) | WR => (Z.sub vAddr woffset, Z.add woffset 1) | DL => (vAddr, Z.sub 8 doffset) | DR => (Z.sub vAddr doffset, Z.add doffset 1) end. Definition wordWidthBytes (w : WordType) : {rangevar : Z & ArithFact ((1 <=? rangevar) && (rangevar <=? 8))} := build_ex (match w with | B => 1 | H => 2 | W => 4 | D => 8 end). Definition alignment_width := 16. Hint Unfold alignment_width : sail. Definition isAddressAligned (addr : mword 64) (wordType : WordType) : bool := let a := projT1 (uint addr) in Z.eqb (projT1 (ediv_with_eq a alignment_width)) (projT1 (ediv_with_eq (Z.sub (Z.add a (projT1 (wordWidthBytes wordType))) 1) alignment_width)). Definition extendLoad {sz : Z} (memResult : mword sz) (sign : bool) `{ArithFact (sz <=? 64)} : mword 64 := if sumbool_of_bool sign then mips_sign_extend 64 memResult else mips_zero_extend 64 memResult. Definition MEMr_wrapper (addr : mword 64) (size : Z) `{ArithFact ((1 <=? size) && (size <=? 8))} : M (mword (8 * size)) := (if eq_vec addr (Ox"000000007F000000" : mword 64) then ((read_reg UART_RVALID_ref) : M (mword 1)) >>= fun rvalid => write_reg UART_RVALID_ref ('b"0" : mword 1) >> ((read_reg UART_RDATA_ref) : M (mword 8)) >>= fun w__0 : mword 8 => returnm (mask (Z.mul 8 (projT1 (__id size))) (concat_vec (Ox"00000000" : mword 32) (concat_vec w__0 (concat_vec rvalid (concat_vec ('b"0000000" : mword 7) (Ox"0000" : mword 16)))))) else if eq_vec addr (Ox"000000007F000004" : mword 64) then returnm (mask (Z.mul 8 (projT1 (__id size))) (Ox"000000000004FFFF" : mword 64)) else (MEMr addr size) >>= fun w__1 : mword (8 * size) => returnm (reverse_endianness w__1)) : M (mword (8 * size)). Definition MEMr_reserve_wrapper (addr : mword 64) (size : Z) `{ArithFact ((1 <=? size) && (size <=? 8))} : M (mword (8 * size)) := (MEMr_reserve addr size) >>= fun w__0 : mword (8 * size) => returnm (reverse_endianness w__0). Definition init_cp0_state '(tt : unit) : M (unit) := (_set_StatusReg_BEV CP0Status_ref ((cast_unit_vec B1) : mword 1)) : M (unit). Definition tlbEntryMatch (r : mword 2) (vpn2 : mword 27) (asid : mword 8) (entry : TLBEntry) : bool := let entryValid := _get_TLBEntry_valid entry in let entryR := _get_TLBEntry_r entry in let entryMask := _get_TLBEntry_pagemask entry in let entryVPN := _get_TLBEntry_vpn2 entry in let entryASID := _get_TLBEntry_asid entry in let entryG := _get_TLBEntry_g entry in let vpnMask : bits 27 := not_vec (mips_zero_extend 27 entryMask) in andb (bits_to_bool entryValid) (andb (eq_vec r entryR) (andb (eq_vec (and_vec vpn2 vpnMask) (and_vec entryVPN vpnMask)) (orb (eq_vec asid entryASID) (bits_to_bool entryG)))). Definition tlbSearch (VAddr : mword 64) : M (option (mword 6)) := catch_early_return (let r := subrange_vec_dec VAddr 63 62 in let vpn2 := subrange_vec_dec VAddr 39 13 in liftR (read_reg TLBEntryHi_ref) >>= fun w__0 : TLBEntryHiReg => let asid := _get_TLBEntryHiReg_ASID w__0 in (let loop_idx_lower := 0 in let loop_idx_upper := 63 in (foreach_ZM_up loop_idx_lower loop_idx_upper 1 tt (fun idx _ _ => liftR ((reg_deref (vec_access_dec TLBEntries idx))) >>= fun w__1 : TLBEntry => (if tlbEntryMatch r vpn2 asid w__1 then (early_return ((Some (to_bits 6 idx)) : option (mword 6)) : MR unit (option (mword 6))) : MR (unit) _ else returnm tt) : MR (unit) _))) >> returnm None). Definition MIPSSegmentOf (vAddr : mword 64) : M ((AccessLevel * option (mword 64))) := let compat32 := eq_vec (subrange_vec_dec vAddr 61 31) ('b"1111111111111111111111111111111" : mword (61 - 31 + 1)) in let b__0 := subrange_vec_dec vAddr 63 62 in (if eq_vec b__0 ('b"11" : mword (63 - 62 + 1)) then returnm (match (compat32, subrange_vec_dec vAddr 30 29) with | (true, b__1) => if eq_vec b__1 ('b"11" : mword (30 - 29 + 1)) then (Kernel, None : option (bits 64)) else if eq_vec b__1 ('b"10" : mword (30 - 29 + 1)) then (Supervisor, None : option (bits 64)) else if eq_vec b__1 ('b"01" : mword (30 - 29 + 1)) then (Kernel, Some (concat_vec (Ox"00000000" : mword 32) (concat_vec ('b"000" : mword 3) (subrange_vec_dec vAddr 28 0)))) else if eq_vec b__1 ('b"00" : mword (30 - 29 + 1)) then (Kernel, Some (concat_vec (Ox"00000000" : mword 32) (concat_vec ('b"000" : mword 3) (subrange_vec_dec vAddr 28 0)))) else match (true, b__1) with | (_, _) => (Kernel, None : option (bits 64)) end | (_, _) => (Kernel, None : option (bits 64)) end) else if eq_vec b__0 ('b"10" : mword (63 - 62 + 1)) then returnm (Kernel, Some (concat_vec ('b"00000" : mword 5) (subrange_vec_dec vAddr 58 0))) else if eq_vec b__0 ('b"01" : mword (63 - 62 + 1)) then returnm (Supervisor, None : option (bits 64)) else if eq_vec b__0 ('b"00" : mword (63 - 62 + 1)) then returnm (User, None : option (bits 64)) else assert_exp' false "Pattern match failure at ../mips/mips_tlb.sail 64:1 - 75:2" >>= fun _ => exit tt) : M ((AccessLevel * option (mword 64))). Definition TLBTranslate2 (vAddr : mword 64) (accessType : MemAccessType) (accessLevel : AccessLevel) : M ((mword 64 * MemAccessCapRestriction)) := (tlbSearch vAddr) >>= fun idx => (match idx with | Some idx => let i := projT1 (uint idx) in (reg_deref (vec_access_dec TLBEntries i)) >>= fun entry => let entryMask := _get_TLBEntry_pagemask entry in let b__0 := entryMask in (if eq_vec b__0 (Ox"0000" : mword 16) then returnm (build_ex 12) else if eq_vec b__0 (Ox"0003" : mword 16) then returnm (build_ex 14) else if eq_vec b__0 (Ox"000F" : mword 16) then returnm (build_ex 16) else if eq_vec b__0 (Ox"003F" : mword 16) then returnm (build_ex 18) else if eq_vec b__0 (Ox"00FF" : mword 16) then returnm (build_ex 20) else if eq_vec b__0 (Ox"03FF" : mword 16) then returnm (build_ex 22) else if eq_vec b__0 (Ox"0FFF" : mword 16) then returnm (build_ex 24) else if eq_vec b__0 (Ox"3FFF" : mword 16) then returnm (build_ex 26) else if eq_vec b__0 (Ox"FFFF" : mword 16) then returnm (build_ex 28) else (undefined_range 12 28) : M ({rangevar : Z & ArithFact ((12 <=? rangevar) && (rangevar <=? 28))})) >>= fun '(existT _ evenOddBit _ : {rangevar : Z & ArithFact ((12 <=? rangevar) && (rangevar <=? 28))}) => let isOdd := access_vec_dec vAddr evenOddBit in let '(caps, caplg, capl, pfn, d, v) := if (bit_to_bool isOdd) : bool then (_get_TLBEntry_caps1 entry, _get_TLBEntry_caplg1 entry, _get_TLBEntry_capl1 entry, _get_TLBEntry_pfn1 entry, _get_TLBEntry_d1 entry, _get_TLBEntry_v1 entry) else (_get_TLBEntry_caps0 entry, _get_TLBEntry_caplg0 entry, _get_TLBEntry_capl0 entry, _get_TLBEntry_pfn0 entry, _get_TLBEntry_d0 entry, _get_TLBEntry_v0 entry) in (if negb (bits_to_bool v) then (SignalExceptionTLB (if generic_eq accessType StoreData then XTLBInvS else XTLBInvL) vAddr) : M ((mword 64 * MemAccessCapRestriction)) else if andb (generic_eq accessType StoreData) (negb (bits_to_bool d)) then (SignalExceptionTLB TLBMod vAddr) : M ((mword 64 * MemAccessCapRestriction)) else let res : bits 64 := mips_zero_extend 64 (concat_vec (subrange_vec_dec pfn 23 (Z.sub evenOddBit 12)) (subrange_vec_dec vAddr (Z.sub evenOddBit 1) 0)) in (if generic_eq accessType StoreData then returnm (if (bits_to_bool caps) : bool then Trap else Unrestricted) else if (bits_to_bool capl) : bool then returnm Clear else (match accessLevel with | User => read_reg TLBEntryHi_ref >>= fun w__11 : TLBEntryHiReg => returnm (_get_TLBEntryHiReg_CLGU w__11) | Supervisor => read_reg TLBEntryHi_ref >>= fun w__12 : TLBEntryHiReg => returnm (_get_TLBEntryHiReg_CLGS w__12) | Kernel => read_reg TLBEntryHi_ref >>= fun w__13 : TLBEntryHiReg => returnm (_get_TLBEntryHiReg_CLGK w__13) end) >>= fun gclg : bits 1 => returnm (if neq_bool (bits_to_bool gclg) (bits_to_bool caplg) then Trap else Unrestricted)) >>= fun macr => returnm (res, macr)) : M ((mword 64 * MemAccessCapRestriction)) | None => (SignalExceptionTLB (if generic_eq accessType StoreData then XTLBRefillS else XTLBRefillL) vAddr) : M ((mword 64 * MemAccessCapRestriction)) end) : M ((mword 64 * MemAccessCapRestriction)). Definition TLBTranslateC (vAddr : mword 64) (accessType : MemAccessType) : M ((mword 64 * MemAccessCapRestriction)) := (getAccessLevel tt) >>= fun currentAccessLevel => let compat32 := eq_vec (subrange_vec_dec vAddr 61 31) ('b"1111111111111111111111111111111" : mword (61 - 31 + 1)) in (MIPSSegmentOf vAddr) >>= fun '((requiredLevel, addr) : (AccessLevel * option (bits 64))) => (if negb (grantsAccess currentAccessLevel requiredLevel) then (SignalExceptionBadAddr (if generic_eq accessType StoreData then AdES else AdEL) vAddr) : M ((mword 64 * MemAccessCapRestriction)) else (match addr with | Some a => returnm (a, Unrestricted) | None => (if sumbool_of_bool (andb (negb compat32) ((Z.gtb (projT1 (uint (subrange_vec_dec vAddr 61 0))) MAX_VA) : bool)) then (SignalExceptionBadAddr (if generic_eq accessType StoreData then AdES else AdEL) vAddr) : M ((mword 64 * MemAccessCapRestriction)) else (TLBTranslate2 vAddr accessType requiredLevel) : M ((mword 64 * MemAccessCapRestriction))) : M ((mword 64 * MemAccessCapRestriction)) end) >>= fun '((pa, c) : (bits 64 * MemAccessCapRestriction)) => (if sumbool_of_bool (Z.gtb (projT1 (uint pa)) MAX_PA) then (SignalExceptionBadAddr (if generic_eq accessType StoreData then AdES else AdEL) vAddr) : M ((mword 64 * MemAccessCapRestriction)) else returnm (pa, c)) : M ((mword 64 * MemAccessCapRestriction))) : M ((mword 64 * MemAccessCapRestriction)). Definition TLBTranslate (vAddr : mword 64) (accessType : MemAccessType) : M (mword 64) := (TLBTranslateC vAddr accessType) >>= fun '(addr, c) => returnm addr. Definition CPtrCmpOp_of_num (arg_ : Z) `{ArithFact ((0 <=? arg_) && (arg_ <=? 7))} : CPtrCmpOp := let l__111 := arg_ in if sumbool_of_bool (Z.eqb l__111 0) then CEQ else if sumbool_of_bool (Z.eqb l__111 1) then CNE else if sumbool_of_bool (Z.eqb l__111 2) then CLT else if sumbool_of_bool (Z.eqb l__111 3) then CLE else if sumbool_of_bool (Z.eqb l__111 4) then CLTU else if sumbool_of_bool (Z.eqb l__111 5) then CLEU else if sumbool_of_bool (Z.eqb l__111 6) then CEXEQ else CNEXEQ. Definition num_of_CPtrCmpOp (arg_ : CPtrCmpOp) : {e : Z & ArithFact ((0 <=? e) && (e <=? 7))} := build_ex ( match arg_ with | CEQ => 0 | CNE => 1 | CLT => 2 | CLE => 3 | CLTU => 4 | CLEU => 5 | CEXEQ => 6 | CNEXEQ => 7 end ). Definition undefined_CPtrCmpOp '(tt : unit) : M (CPtrCmpOp) := (internal_pick [CEQ; CNE; CLT; CLE; CLTU; CLEU; CEXEQ; CNEXEQ]) : M (CPtrCmpOp). Definition ClearRegSet_of_num (arg_ : Z) `{ArithFact ((0 <=? arg_) && (arg_ <=? 3))} : ClearRegSet := let l__108 := arg_ in if sumbool_of_bool (Z.eqb l__108 0) then GPLo else if sumbool_of_bool (Z.eqb l__108 1) then GPHi else if sumbool_of_bool (Z.eqb l__108 2) then CLo else CHi. Definition num_of_ClearRegSet (arg_ : ClearRegSet) : {e : Z & ArithFact ((0 <=? e) && (e <=? 3))} := build_ex (match arg_ with | GPLo => 0 | GPHi => 1 | CLo => 2 | CHi => 3 end). Definition undefined_ClearRegSet '(tt : unit) : M (ClearRegSet) := (internal_pick [GPLo; GPHi; CLo; CHi]) : M (ClearRegSet). Definition num_flags := 1. Hint Unfold num_flags : sail. Definition reserved_otypes := 16. Hint Unfold reserved_otypes : sail. Definition otype_unsealed := (-1). Hint Unfold otype_unsealed : sail. Definition otype_sentry := (-2). Hint Unfold otype_sentry : sail. Definition otype_unsealed_bits := to_bits 64 otype_unsealed. Hint Unfold otype_unsealed_bits : sail. Definition otype_sentry_bits := to_bits 64 otype_sentry. Hint Unfold otype_sentry_bits : sail. Definition max_otype := Z.sub (projT1 (MAX 18)) reserved_otypes. Hint Unfold max_otype : sail. Definition resetE := to_bits 6 52. Hint Unfold resetE : sail. Definition resetT := concat_vec ('b"01" : mword 2) (Ox"000" : mword 12). Hint Unfold resetT : sail. Definition null_cap : Capability := {| Capability_tag := false; Capability_uperms := (zeros_implicit 4 tt); Capability_permit_set_CID := false; Capability_access_system_regs := false; Capability_permit_unseal := false; Capability_permit_ccall := false; Capability_permit_seal := false; Capability_permit_store_local_cap := false; Capability_permit_store_cap := false; Capability_permit_load_cap := false; Capability_permit_store := false; Capability_permit_load := false; Capability_permit_execute := false; Capability_global := false; Capability_reserved := (zeros_implicit 3 tt); Capability_internal_e := true; Capability_E := resetE; Capability_sealed := false; Capability_B := (zeros_implicit 14 tt); Capability_T := resetT; Capability_otype := (ones_implicit 18 tt); Capability_address := (zeros_implicit 64 tt) |}. Hint Unfold null_cap : sail. Definition default_cap : Capability := {| Capability_tag := true; Capability_uperms := (ones_implicit 4 tt); Capability_permit_set_CID := true; Capability_access_system_regs := true; Capability_permit_unseal := true; Capability_permit_ccall := true; Capability_permit_seal := true; Capability_permit_store_local_cap := true; Capability_permit_store_cap := true; Capability_permit_load_cap := true; Capability_permit_store := true; Capability_permit_load := true; Capability_permit_execute := true; Capability_global := true; Capability_reserved := (zeros_implicit 3 tt); Capability_internal_e := true; Capability_E := resetE; Capability_sealed := false; Capability_B := (zeros_implicit 14 tt); Capability_T := resetT; Capability_otype := (ones_implicit 18 tt); Capability_address := (zeros_implicit 64 tt) |}. Hint Unfold default_cap : sail. Definition cap_size := 16. Hint Unfold cap_size : sail. Definition caps_per_cacheline := 8. Hint Unfold caps_per_cacheline : sail. Definition capBitsToCapability (t : bool) (c : mword 128) : Capability := let internal_exponent : bool := (bit_to_bool (access_vec_dec c 90)) : bool in let otype : bits 18 := subrange_vec_dec c 108 91 in let sealed : bool := neq_vec otype (ones_implicit 18 tt) in let E : bits 6 := zeros_implicit 6 tt in let Bs : bits 14 := zeros_implicit 14 tt in let T : bits 12 := zeros_implicit 12 tt in let lenMSBs : bits 2 := zeros_implicit 2 tt in let '(Bs, E, T, lenMSBs) := (if sumbool_of_bool internal_exponent then let E : bits 6 := concat_vec (subrange_vec_dec c 80 78) (subrange_vec_dec c 66 64) in let lenMSBs : bits 2 := 'b"01" : mword 2 in let T : bits 12 := concat_vec (subrange_vec_dec c 89 81) ('b"000" : mword 3) in let Bs : bits 14 := concat_vec (subrange_vec_dec c 77 67) ('b"000" : mword 3) in (Bs, E, T, lenMSBs) else let lenMSBs : bits 2 := 'b"00" : mword 2 in let T : bits 12 := subrange_vec_dec c 89 78 in let Bs : bits 14 := subrange_vec_dec c 77 64 in (Bs, E, T, lenMSBs)) : (mword 14 * mword 6 * mword 12 * mword 2) in let carry_out := if zopz0zI_u T (subrange_vec_dec Bs 11 0) then 'b"01" : mword 2 else 'b"00" : mword 2 in let Ttop2 := add_vec (add_vec (subrange_vec_dec Bs 13 12) lenMSBs) carry_out in {| Capability_tag := t; Capability_uperms := (subrange_vec_dec c 127 124); Capability_permit_set_CID := ((bit_to_bool (access_vec_dec c 123)) : bool); Capability_access_system_regs := ((bit_to_bool (access_vec_dec c 122)) : bool); Capability_permit_unseal := ((bit_to_bool (access_vec_dec c 121)) : bool); Capability_permit_ccall := ((bit_to_bool (access_vec_dec c 120)) : bool); Capability_permit_seal := ((bit_to_bool (access_vec_dec c 119)) : bool); Capability_permit_store_local_cap := ((bit_to_bool (access_vec_dec c 118)) : bool); Capability_permit_store_cap := ((bit_to_bool (access_vec_dec c 117)) : bool); Capability_permit_load_cap := ((bit_to_bool (access_vec_dec c 116)) : bool); Capability_permit_store := ((bit_to_bool (access_vec_dec c 115)) : bool); Capability_permit_load := ((bit_to_bool (access_vec_dec c 114)) : bool); Capability_permit_execute := ((bit_to_bool (access_vec_dec c 113)) : bool); Capability_global := ((bit_to_bool (access_vec_dec c 112)) : bool); Capability_reserved := (subrange_vec_dec c 111 109); Capability_internal_e := internal_exponent; Capability_E := E; Capability_sealed := sealed; Capability_B := Bs; Capability_T := (concat_vec Ttop2 T); Capability_otype := otype; Capability_address := (subrange_vec_dec c 63 0) |}. Definition getCapHardPerms (cap : Capability) : mword 12 := concat_vec (bool_to_bits cap.(Capability_permit_set_CID)) (concat_vec (bool_to_bits cap.(Capability_access_system_regs)) (concat_vec (bool_to_bits cap.(Capability_permit_unseal)) (concat_vec (bool_to_bits cap.(Capability_permit_ccall)) (concat_vec (bool_to_bits cap.(Capability_permit_seal)) (concat_vec (bool_to_bits cap.(Capability_permit_store_local_cap)) (concat_vec (bool_to_bits cap.(Capability_permit_store_cap)) (concat_vec (bool_to_bits cap.(Capability_permit_load_cap)) (concat_vec (bool_to_bits cap.(Capability_permit_store)) (concat_vec (bool_to_bits cap.(Capability_permit_load)) (concat_vec (bool_to_bits cap.(Capability_permit_execute)) (bool_to_bits cap.(Capability_global)))))))))))). Definition capToBits (cap : Capability) : mword 128 := let t_hi : bits 9 := subrange_vec_dec cap.(Capability_T) 11 3 in let t_lo : bits 3 := subrange_vec_dec cap.(Capability_T) 2 0 in let b_hi : bits 11 := subrange_vec_dec cap.(Capability_B) 13 3 in let b_lo : bits 3 := subrange_vec_dec cap.(Capability_B) 2 0 in let '(b_lo, t_lo) := (if cap.(Capability_internal_e) then let t_lo : bits 3 := subrange_vec_dec cap.(Capability_E) 5 3 in let b_lo : bits 3 := subrange_vec_dec cap.(Capability_E) 2 0 in (b_lo, t_lo) else (b_lo, t_lo)) : (mword 3 * mword 3) in concat_vec cap.(Capability_uperms) (concat_vec (getCapHardPerms cap) (concat_vec cap.(Capability_reserved) (concat_vec cap.(Capability_otype) (concat_vec (bool_to_bits cap.(Capability_internal_e)) (concat_vec t_hi (concat_vec t_lo (concat_vec b_hi (concat_vec b_lo cap.(Capability_address))))))))). Definition null_cap_bits : bits 128 := capToBits null_cap. Hint Unfold null_cap_bits : sail. Definition capToMemBits (cap : Capability) : mword 128 := xor_vec (capToBits cap) null_cap_bits. Definition memBitsToCapability (tag : bool) (b : mword 128) : Capability := capBitsToCapability tag (xor_vec b null_cap_bits). Definition getCapPerms (cap : Capability) : mword 31 := let perms : bits 15 := mips_zero_extend 15 (getCapHardPerms cap) in concat_vec (Ox"000" : mword 12) (concat_vec cap.(Capability_uperms) perms). Definition setCapPerms (cap : Capability) (perms : mword 31) : Capability := {| Capability_tag := cap.(Capability_tag); Capability_uperms := (subrange_vec_dec perms 18 15); Capability_permit_set_CID := ((bit_to_bool (access_vec_dec perms 11)) : bool); Capability_access_system_regs := ((bit_to_bool (access_vec_dec perms 10)) : bool); Capability_permit_unseal := ((bit_to_bool (access_vec_dec perms 9)) : bool); Capability_permit_ccall := ((bit_to_bool (access_vec_dec perms 8)) : bool); Capability_permit_seal := ((bit_to_bool (access_vec_dec perms 7)) : bool); Capability_permit_store_local_cap := ((bit_to_bool (access_vec_dec perms 6)) : bool); Capability_permit_store_cap := ((bit_to_bool (access_vec_dec perms 5)) : bool); Capability_permit_load_cap := ((bit_to_bool (access_vec_dec perms 4)) : bool); Capability_permit_store := ((bit_to_bool (access_vec_dec perms 3)) : bool); Capability_permit_load := ((bit_to_bool (access_vec_dec perms 2)) : bool); Capability_permit_execute := ((bit_to_bool (access_vec_dec perms 1)) : bool); Capability_global := ((bit_to_bool (access_vec_dec perms 0)) : bool); Capability_reserved := cap.(Capability_reserved); Capability_internal_e := cap.(Capability_internal_e); Capability_E := cap.(Capability_E); Capability_sealed := cap.(Capability_sealed); Capability_B := cap.(Capability_B); Capability_T := cap.(Capability_T); Capability_otype := cap.(Capability_otype); Capability_address := cap.(Capability_address) |}. Definition sealCap (cap : Capability) (otyp : mword 24) : (bool * Capability) := (true, {| Capability_tag := cap.(Capability_tag); Capability_uperms := cap.(Capability_uperms); Capability_permit_set_CID := cap.(Capability_permit_set_CID); Capability_access_system_regs := cap.(Capability_access_system_regs); Capability_permit_unseal := cap.(Capability_permit_unseal); Capability_permit_ccall := cap.(Capability_permit_ccall); Capability_permit_seal := cap.(Capability_permit_seal); Capability_permit_store_local_cap := cap.(Capability_permit_store_local_cap); Capability_permit_store_cap := cap.(Capability_permit_store_cap); Capability_permit_load_cap := cap.(Capability_permit_load_cap); Capability_permit_store := cap.(Capability_permit_store); Capability_permit_load := cap.(Capability_permit_load); Capability_permit_execute := cap.(Capability_permit_execute); Capability_global := cap.(Capability_global); Capability_reserved := cap.(Capability_reserved); Capability_internal_e := cap.(Capability_internal_e); Capability_E := cap.(Capability_E); Capability_sealed := true; Capability_B := cap.(Capability_B); Capability_T := cap.(Capability_T); Capability_otype := (subrange_vec_dec otyp 17 0); Capability_address := cap.(Capability_address) |}). Definition unsealCap (cap : Capability) : Capability := {| Capability_tag := cap.(Capability_tag); Capability_uperms := cap.(Capability_uperms); Capability_permit_set_CID := cap.(Capability_permit_set_CID); Capability_access_system_regs := cap.(Capability_access_system_regs); Capability_permit_unseal := cap.(Capability_permit_unseal); Capability_permit_ccall := cap.(Capability_permit_ccall); Capability_permit_seal := cap.(Capability_permit_seal); Capability_permit_store_local_cap := cap.(Capability_permit_store_local_cap); Capability_permit_store_cap := cap.(Capability_permit_store_cap); Capability_permit_load_cap := cap.(Capability_permit_load_cap); Capability_permit_store := cap.(Capability_permit_store); Capability_permit_load := cap.(Capability_permit_load); Capability_permit_execute := cap.(Capability_permit_execute); Capability_global := cap.(Capability_global); Capability_reserved := cap.(Capability_reserved); Capability_internal_e := cap.(Capability_internal_e); Capability_E := cap.(Capability_E); Capability_sealed := false; Capability_B := cap.(Capability_B); Capability_T := cap.(Capability_T); Capability_otype := (ones_implicit 18 tt); Capability_address := cap.(Capability_address) |}. Definition getCapTop (c : Capability) : {rangevar : Z & ArithFact ((0 <=? rangevar) && (rangevar <=? (2 ^ 65)))} := build_ex ( let '(existT _ _ _, existT _ top _) := getCapBounds c in top ). Definition getCapOffset (c : Capability) : {rangevar : Z & ArithFact ((0 <=? rangevar) && (rangevar <=? (2 ^ 64 - 1)))} := build_ex ( let base := projT1 (getCapBase c) in projT1 (emod_with_eq (Z.sub (projT1 (uint c.(Capability_address))) base) (projT1 (pow2 64))) ). Definition getCapLength (c : Capability) : M ({rangevar : Z & ArithFact ((0 <=? rangevar) && (rangevar <=? (2 ^ 65)))}) := let '(existT _ base _, existT _ top _) := getCapBounds c in assert_exp (orb (negb c.(Capability_tag)) (Z.geb top base)) "cheri_prelude_128.sail 318:40 - 318:41" >> returnm (build_ex (projT1 (emod_with_eq (Z.sub top base) (projT1 (pow2 65))))). Definition getCapCursor (cap : Capability) : {rangevar : Z & ArithFact ((0 <=? rangevar) && (rangevar <=? (2 ^ 64 - 1)))} := build_ex (projT1 (uint cap.(Capability_address))). Definition setCapAddr (c : Capability) (addr : mword 64) : (bool * Capability) := let newCap := {[ c with Capability_address := addr ]} in let representable := capBoundsEqual c newCap in (representable, newCap). Definition incCapOffset (c : Capability) (delta : mword 64) : (bool * Capability) := let newAddress : bits 64 := add_vec c.(Capability_address) delta in let newCap := {[ c with Capability_address := newAddress ]} in let representable := capBoundsEqual c newCap in (representable, newCap). Definition setCapBounds (cap : Capability) (base : mword 64) (top : mword 65) : (bool * Capability) := let base65 := concat_vec ('b"0" : mword 1) base in let length := sub_vec top base65 in let e := Z.sub 52 (projT1 (count_leading_zeros (subrange_vec_dec length 64 13))) in let ie := orb (projT1 (neq_int e 0)) (bit_to_bool (access_vec_dec length 12)) in let Bbits := vector_truncate base 14 in let Tbits := vector_truncate top 14 in let lostSignificantTop : bool := false in let lostSignificantBase : bool := false in let incE : bool := false in let '(Bbits, Tbits, incE, lostSignificantBase, lostSignificantTop) := (if sumbool_of_bool ie then let B_ie := vector_truncate (shiftr base (Z.add e 3)) 11 in let T_ie := vector_truncate (shiftr top (Z.add e 3)) 11 in let maskLo : bits 65 := mips_zero_extend 65 (sail_ones (Z.add e 3)) in let z65 : bits 65 := zeros_implicit 65 tt in let lostSignificantBase : bool := neq_vec (and_vec base65 maskLo) z65 in let lostSignificantTop : bool := neq_vec (and_vec top maskLo) z65 in let T_ie : mword 11 := if sumbool_of_bool lostSignificantTop then add_vec_int T_ie 1 else T_ie in let len_ie := sub_vec T_ie B_ie in let '(B_ie, T_ie, incE, lostSignificantBase, lostSignificantTop) := (if (bit_to_bool (access_vec_dec len_ie 10)) : bool then let incE : bool := true in let lostSignificantBase : bool := orb lostSignificantBase (bit_to_bool (access_vec_dec B_ie 0)) in let lostSignificantTop : bool := orb lostSignificantTop (bit_to_bool (access_vec_dec T_ie 0)) in let B_ie : mword 11 := vector_truncate (shiftr base (Z.add e 4)) 11 in let incT := if sumbool_of_bool lostSignificantTop then 1 else 0 in let T_ie : mword 11 := add_vec_int (vector_truncate (shiftr top (Z.add e 4)) 11) incT in (B_ie, T_ie, incE, lostSignificantBase, lostSignificantTop) else (B_ie, T_ie, incE, lostSignificantBase, lostSignificantTop)) : (mword 11 * mword 11 * bool * bool * bool) in let Bbits : mword 14 := concat_vec B_ie ('b"000" : mword 3) in let Tbits : mword 14 := concat_vec T_ie ('b"000" : mword 3) in (Bbits, Tbits, incE, lostSignificantBase, lostSignificantTop) else (Bbits, Tbits, incE, lostSignificantBase, lostSignificantTop)) : (mword 14 * mword 14 * bool * bool * bool) in let newCap := {| Capability_tag := cap.(Capability_tag); Capability_uperms := cap.(Capability_uperms); Capability_permit_set_CID := cap.(Capability_permit_set_CID); Capability_access_system_regs := cap.(Capability_access_system_regs); Capability_permit_unseal := cap.(Capability_permit_unseal); Capability_permit_ccall := cap.(Capability_permit_ccall); Capability_permit_seal := cap.(Capability_permit_seal); Capability_permit_store_local_cap := cap.(Capability_permit_store_local_cap); Capability_permit_store_cap := cap.(Capability_permit_store_cap); Capability_permit_load_cap := cap.(Capability_permit_load_cap); Capability_permit_store := cap.(Capability_permit_store); Capability_permit_load := cap.(Capability_permit_load); Capability_permit_execute := cap.(Capability_permit_execute); Capability_global := cap.(Capability_global); Capability_reserved := cap.(Capability_reserved); Capability_internal_e := ie; Capability_E := (to_bits 6 (if sumbool_of_bool incE then Z.add e 1 else e)); Capability_sealed := cap.(Capability_sealed); Capability_B := Bbits; Capability_T := Tbits; Capability_otype := cap.(Capability_otype); Capability_address := base |} in let exact := negb (orb lostSignificantBase lostSignificantTop) in (exact, newCap). Definition getRepresentableAlignmentMask (len : mword 64) : mword 64 := let '(exact, c) := setCapBounds default_cap (sub_vec (ones_implicit 64 tt) len) (concat_vec ('b"0" : mword 1) (Ox"FFFFFFFFFFFFFFFF" : mword 64)) in let e := projT1 (min_atom (projT1 (uint c.(Capability_E))) 52) in let e' := if c.(Capability_internal_e) then Z.add e 3 else 0 in autocast (concat_vec (sail_ones (Z.sub 64 e')) (zeros e')). Definition getRepresentableLength (len : mword 64) : mword 64 := let m := getRepresentableAlignmentMask len in and_vec (add_vec len (not_vec m)) m. Definition CapRegs : vec (register_ref regstate register_value Capability) 32 := vec_of_list_len [C31_ref;C30_ref;C29_ref;C28_ref;C27_ref;C26_ref;C25_ref;C24_ref;C23_ref;C22_ref; C21_ref;C20_ref;C19_ref;C18_ref;C17_ref;C16_ref;C15_ref;C14_ref;C13_ref;C12_ref; C11_ref;C10_ref;C09_ref;C08_ref;C07_ref;C06_ref;C05_ref;C04_ref;C03_ref;C02_ref; C01_ref;DDC_ref]. Hint Unfold CapRegs : sail. Definition have_cp2 := true. Hint Unfold have_cp2 : sail. Definition readCapReg (n : mword 5) : M (Capability) := (if eq_vec n ('b"00000" : mword 5) then returnm null_cap else let i := projT1 (uint n) in (reg_deref (vec_access_dec CapRegs i)) : M (Capability)) : M (Capability). Definition readCapRegDDC (n : mword 5) : M (Capability) := let i := projT1 (uint n) in (reg_deref (vec_access_dec CapRegs i)) : M (Capability). Definition hasReservedOType (cap : Capability) : bool := Z.gtb (projT1 (uint cap.(Capability_otype))) max_otype. Definition capToString (cap : Capability) (fixlen : bool) : M (string) := (skip tt) >> (getCapLength cap) >>= fun '(existT _ len _) => let len_str := if sumbool_of_bool fixlen then string_of_bits (to_bits 64 (projT1 (min_atom len (projT1 (MAX 64))))) else string_of_bits (to_bits 68 len) in let otype64 : bits 64 := if hasReservedOType cap then mips_sign_extend 64 cap.(Capability_otype) else mips_zero_extend 64 cap.(Capability_otype) in returnm (String.append " t:" (String.append (if cap.(Capability_tag) then "1" else "0") (String.append " s:" (String.append (if cap.(Capability_sealed) then "1" else "0") (String.append " perms:" (String.append (string_of_bits (concat_vec ('b"0" : mword 1) (getCapPerms cap))) (String.append " type:" (String.append (string_of_bits otype64) (String.append " offset:" (String.append (string_of_bits (to_bits 64 (projT1 (getCapOffset cap)))) (String.append " base:" (String.append (string_of_bits (to_bits 64 (projT1 (getCapBase cap)))) (String.append " length:" len_str))))))))))))). Definition writeCapReg (n : mword 5) (cap : Capability) : M (unit) := (if eq_vec n ('b"00000" : mword 5) then returnm tt else let i := projT1 (uint n) in (if sumbool_of_bool trace then let '_ := (prerr (string_of_int i)) : unit in let '_ := (prerr " <- ") : unit in (capToString cap false) >>= fun w__0 : string => let '_ := (prerr_endline w__0) : unit in let cap2 := capBitsToCapability cap.(Capability_tag) (capToBits cap) in (if generic_neq cap cap2 then let '_ := (prerr_endline "Wrote non-normal cap:") : unit in (capToString cap false) >>= fun w__1 : string => let '_ := (prerr_endline w__1) : unit in (capToString cap2 false) >>= fun w__2 : string => let '_ := (prerr_endline w__2) : unit in assert_exp' false "wrote non-normal capability" >>= fun _ => exit tt else returnm tt) : M (unit) else (skip tt) : M (unit)) >> write_reg (vec_access_dec CapRegs i) cap : M (unit)) : M (unit). Definition CapEx_of_num (arg_ : Z) `{ArithFact ((0 <=? arg_) && (arg_ <=? 24))} : CapEx := let l__84 := arg_ in if sumbool_of_bool (Z.eqb l__84 0) then CapEx_None else if sumbool_of_bool (Z.eqb l__84 1) then CapEx_LengthViolation else if sumbool_of_bool (Z.eqb l__84 2) then CapEx_TagViolation else if sumbool_of_bool (Z.eqb l__84 3) then CapEx_SealViolation else if sumbool_of_bool (Z.eqb l__84 4) then CapEx_TypeViolation else if sumbool_of_bool (Z.eqb l__84 5) then CapEx_CallTrap else if sumbool_of_bool (Z.eqb l__84 6) then CapEx_ReturnTrap else if sumbool_of_bool (Z.eqb l__84 7) then CapEx_TSSUnderFlow else if sumbool_of_bool (Z.eqb l__84 8) then CapEx_UserDefViolation else if sumbool_of_bool (Z.eqb l__84 9) then CapEx_TLBNoStoreCap else if sumbool_of_bool (Z.eqb l__84 10) then CapEx_InexactBounds else if sumbool_of_bool (Z.eqb l__84 11) then CapEx_GlobalViolation else if sumbool_of_bool (Z.eqb l__84 12) then CapEx_PermitExecuteViolation else if sumbool_of_bool (Z.eqb l__84 13) then CapEx_PermitLoadViolation else if sumbool_of_bool (Z.eqb l__84 14) then CapEx_PermitStoreViolation else if sumbool_of_bool (Z.eqb l__84 15) then CapEx_PermitLoadCapViolation else if sumbool_of_bool (Z.eqb l__84 16) then CapEx_PermitStoreCapViolation else if sumbool_of_bool (Z.eqb l__84 17) then CapEx_PermitStoreLocalCapViolation else if sumbool_of_bool (Z.eqb l__84 18) then CapEx_PermitSealViolation else if sumbool_of_bool (Z.eqb l__84 19) then CapEx_AccessSystemRegsViolation else if sumbool_of_bool (Z.eqb l__84 20) then CapEx_PermitCCallViolation else if sumbool_of_bool (Z.eqb l__84 21) then CapEx_AccessCCallIDCViolation else if sumbool_of_bool (Z.eqb l__84 22) then CapEx_PermitUnsealViolation else if sumbool_of_bool (Z.eqb l__84 23) then CapEx_PermitSetCIDViolation else CapEx_TLBLoadCap. Definition num_of_CapEx (arg_ : CapEx) : {e : Z & ArithFact ((0 <=? e) && (e <=? 24))} := build_ex ( match arg_ with | CapEx_None => 0 | CapEx_LengthViolation => 1 | CapEx_TagViolation => 2 | CapEx_SealViolation => 3 | CapEx_TypeViolation => 4 | CapEx_CallTrap => 5 | CapEx_ReturnTrap => 6 | CapEx_TSSUnderFlow => 7 | CapEx_UserDefViolation => 8 | CapEx_TLBNoStoreCap => 9 | CapEx_InexactBounds => 10 | CapEx_GlobalViolation => 11 | CapEx_PermitExecuteViolation => 12 | CapEx_PermitLoadViolation => 13 | CapEx_PermitStoreViolation => 14 | CapEx_PermitLoadCapViolation => 15 | CapEx_PermitStoreCapViolation => 16 | CapEx_PermitStoreLocalCapViolation => 17 | CapEx_PermitSealViolation => 18 | CapEx_AccessSystemRegsViolation => 19 | CapEx_PermitCCallViolation => 20 | CapEx_AccessCCallIDCViolation => 21 | CapEx_PermitUnsealViolation => 22 | CapEx_PermitSetCIDViolation => 23 | CapEx_TLBLoadCap => 24 end ). Definition undefined_CapEx '(tt : unit) : M (CapEx) := (internal_pick [CapEx_None; CapEx_LengthViolation; CapEx_TagViolation; CapEx_SealViolation; CapEx_TypeViolation; CapEx_CallTrap; CapEx_ReturnTrap; CapEx_TSSUnderFlow; CapEx_UserDefViolation; CapEx_TLBNoStoreCap; CapEx_InexactBounds; CapEx_GlobalViolation; CapEx_PermitExecuteViolation; CapEx_PermitLoadViolation; CapEx_PermitStoreViolation; CapEx_PermitLoadCapViolation; CapEx_PermitStoreCapViolation; CapEx_PermitStoreLocalCapViolation; CapEx_PermitSealViolation; CapEx_AccessSystemRegsViolation; CapEx_PermitCCallViolation; CapEx_AccessCCallIDCViolation; CapEx_PermitUnsealViolation; CapEx_PermitSetCIDViolation; CapEx_TLBLoadCap]) : M (CapEx). Definition Mk_CapCauseReg (v : mword 16) : CapCauseReg := {| CapCauseReg_CapCauseReg_chunk_0 := (subrange_vec_dec v 15 0) |}. Definition _get_CapCauseReg_bits (v : CapCauseReg) : mword 16 := subrange_vec_dec v.(CapCauseReg_CapCauseReg_chunk_0) 15 0. Definition _set_CapCauseReg_bits (r_ref : register_ref regstate register_value CapCauseReg) (v : mword 16) : M (unit) := (reg_deref r_ref) >>= fun r => let r := {[ r with CapCauseReg_CapCauseReg_chunk_0 := (update_subrange_vec_dec r.(CapCauseReg_CapCauseReg_chunk_0) 15 0 (subrange_vec_dec v 15 0)) ]} : CapCauseReg in write_reg r_ref r : M (unit). Definition _update_CapCauseReg_bits (v : CapCauseReg) (x : mword 16) : CapCauseReg := {[ v with CapCauseReg_CapCauseReg_chunk_0 := (update_subrange_vec_dec v.(CapCauseReg_CapCauseReg_chunk_0) 15 0 (subrange_vec_dec x 15 0)) ]}. Definition _get_CapCauseReg_ExcCode (v : CapCauseReg) : mword 8 := subrange_vec_dec v.(CapCauseReg_CapCauseReg_chunk_0) 15 8. Definition _update_CapCauseReg_ExcCode (v : CapCauseReg) (x : mword 8) : CapCauseReg := {[ v with CapCauseReg_CapCauseReg_chunk_0 := (update_subrange_vec_dec v.(CapCauseReg_CapCauseReg_chunk_0) 15 8 (subrange_vec_dec x 7 0)) ]}. Definition _get_CapCauseReg_RegNum (v : CapCauseReg) : mword 8 := subrange_vec_dec v.(CapCauseReg_CapCauseReg_chunk_0) 7 0. Definition _update_CapCauseReg_RegNum (v : CapCauseReg) (x : mword 8) : CapCauseReg := {[ v with CapCauseReg_CapCauseReg_chunk_0 := (update_subrange_vec_dec v.(CapCauseReg_CapCauseReg_chunk_0) 7 0 (subrange_vec_dec x 7 0)) ]}. Definition execute_branch_pcc (newPCC : Capability) : M (unit) := write_reg DelayedPC_ref (to_bits 64 (projT1 (getCapOffset newPCC))) >> write_reg DelayedPCC_ref newPCC >> write_reg BranchPending_ref ('b"1" : mword 1) >> write_reg NextInBranchDelay_ref ('b"1" : mword 1) : M (unit). Definition raise_c2_exception {o : Type} (capEx : CapEx) (regnum : mword 5) : M (o) := let reg8 := concat_vec ('b"000" : mword 3) regnum in (raise_c2_exception8 capEx reg8) : M (o). Definition raise_c2_exception_badaddr {o : Type} (capEx : CapEx) (regnum : mword 5) (badAddr : mword 64) : M (o) := write_reg CP0BadVAddr_ref badAddr >> (raise_c2_exception capEx regnum) : M (o). Definition cap_addr_mask := to_bits 64 (Z.sub (projT1 (pow2 64)) cap_size). Hint Unfold cap_addr_mask : sail. Definition MEMw_wrapper (addr : mword 64) (size : Z) (data : mword (8 * size)) `{ArithFact (size >=? 1)} : M (unit) := (if eq_vec addr (Ox"000000007F000000" : mword 64) then let ledata := reverse_endianness data in write_reg UART_WDATA_ref (subrange_vec_dec ledata 7 0) >> write_reg UART_WRITTEN_ref ('b"1" : mword 1) : M (unit) else assert_exp (eq_vec (and_vec addr cap_addr_mask) (and_vec (add_vec addr (to_bits 64 (Z.sub size 1))) cap_addr_mask)) "cheri_prelude_common.sail 460:85 - 460:86" >> (MEMw_tagged addr size false (autocast (autocast data))) : M (unit)) : M (unit). Definition MEMw_conditional_wrapper (addr : mword 64) (size : Z) (data : mword (8 * size)) `{ArithFact (size >=? 1)} : M (bool) := assert_exp (eq_vec (and_vec addr cap_addr_mask) (and_vec (add_vec addr (to_bits 64 (Z.sub size 1))) cap_addr_mask)) "cheri_prelude_common.sail 472:85 - 472:86" >> (MEMw_tagged_conditional addr size false (autocast (autocast data))) : M (bool). Definition checkDDCPerms (ddc : Capability) (accessType : MemAccessType) : M (unit) := (if negb ddc.(Capability_tag) then (raise_c2_exception CapEx_TagViolation ('b"00000" : mword 5)) : M (unit) else if ddc.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation ('b"00000" : mword 5)) : M (unit) else returnm tt) >> (match accessType with | Instruction => assert_exp' false "cheri_prelude_common.sail 485:34 - 485:35" >>= fun _ => exit tt | LoadData => (if negb ddc.(Capability_permit_load) then (raise_c2_exception CapEx_PermitLoadViolation ('b"00000" : mword 5)) : M (unit) else returnm tt) : M (unit) | StoreData => (if negb ddc.(Capability_permit_store) then (raise_c2_exception CapEx_PermitStoreViolation ('b"00000" : mword 5)) : M (unit) else returnm tt) : M (unit) end) : M (unit). Definition addrWrapper (addr : mword 64) (accessType : MemAccessType) (width : WordType) : M (mword 64) := read_reg DDC_ref >>= fun ddc => (checkDDCPerms ddc accessType) >> let cursor := projT1 (getCapCursor ddc) in let vAddr := projT1 (emod_with_eq (Z.add cursor (projT1 (uint addr))) (projT1 (pow2 64))) in let size := projT1 (wordWidthBytes width) in let '(existT _ base _, existT _ top _) := getCapBounds ddc in (if sumbool_of_bool (Z.gtb (Z.add vAddr size) top) then (raise_c2_exception CapEx_LengthViolation ('b"00000" : mword 5)) : M (mword 64) else if sumbool_of_bool (Z.ltb vAddr base) then (raise_c2_exception CapEx_LengthViolation ('b"00000" : mword 5)) : M (mword 64) else returnm (to_bits 64 vAddr)) : M (mword 64). Definition addrWrapperUnaligned (addr : mword 64) (accessType : MemAccessType) (width : WordTypeUnaligned) : M ((mword 64 * Z)) := read_reg DDC_ref >>= fun ddc => (checkDDCPerms ddc accessType) >> let cursor := projT1 (getCapCursor ddc) in let vAddr := projT1 (emod_with_eq (Z.add cursor (projT1 (uint addr))) (projT1 (pow2 64))) in let '(waddr, size) := unalignedBytesTouched vAddr width in let '(existT _ base _, existT _ top _) := getCapBounds ddc in (if sumbool_of_bool (Z.gtb (Z.add waddr size) top) then (raise_c2_exception CapEx_LengthViolation ('b"00000" : mword 5)) : M ((mword 64 * Z)) else if sumbool_of_bool (Z.ltb waddr base) then (raise_c2_exception CapEx_LengthViolation ('b"00000" : mword 5)) : M ((mword 64 * Z)) else returnm (to_bits 64 waddr, size)) : M ((mword 64 * Z)). Definition execute_branch (pc : mword 64) : M (unit) := read_reg PCC_ref >>= fun w__0 : Capability => (getCapLength w__0) >>= fun '(existT _ len _) => (if sumbool_of_bool (Z.gtb (Z.add (projT1 (uint pc)) 4) len) then (raise_c2_exception_noreg CapEx_LengthViolation) : M (unit) else returnm tt) >> (execute_branch_mips pc) : M (unit). Definition TranslatePC (vAddr : mword 64) : M (mword 64) := (incrementCP0Count tt) >> read_reg PCC_ref >>= fun pcc => let '(existT _ base _, existT _ top _) := getCapBounds pcc in let absPC := Z.add base (projT1 (uint vAddr)) in (if sumbool_of_bool (projT1 (neq_int (projT1 (emod_with_eq absPC 4)) 0)) then (SignalExceptionBadAddr AdEL (to_bits 64 absPC)) : M (mword 64) else if negb pcc.(Capability_tag) then (raise_c2_exception_noreg CapEx_TagViolation) : M (mword 64) else if pcc.(Capability_sealed) then (raise_c2_exception_noreg CapEx_SealViolation) : M (mword 64) else if negb pcc.(Capability_permit_execute) then (raise_c2_exception_noreg CapEx_PermitExecuteViolation) : M (mword 64) else if sumbool_of_bool (Z.gtb (Z.add absPC 4) top) then (raise_c2_exception_noreg CapEx_LengthViolation) : M (mword 64) else (TLBTranslate (to_bits 64 absPC) Instruction) : M (mword 64)) : M (mword 64). Definition checkCP2usable '(tt : unit) : M (unit) := read_reg CP0Status_ref >>= fun w__0 : StatusReg => (if negb (bit_to_bool (access_vec_dec (_get_StatusReg_CU w__0) 2)) then (_set_CauseReg_CE CP0Cause_ref ('b"10" : mword 2)) >> (SignalException CpU) : M (unit) else returnm tt) : M (unit). Definition init_cp2_state '(tt : unit) : M (unit) := write_reg PCC_ref default_cap >> write_reg NextPCC_ref default_cap >> write_reg DelayedPCC_ref default_cap >> write_reg DDC_ref default_cap >> write_reg KCC_ref default_cap >> write_reg EPCC_ref default_cap >> write_reg ErrorEPCC_ref default_cap >> write_reg KDC_ref null_cap >> write_reg KR1C_ref null_cap >> write_reg KR2C_ref null_cap >> write_reg CPLR_ref null_cap >> write_reg CULR_ref null_cap >> let loop_i_lower := 1 in let loop_i_upper := 31 in (foreach_ZM_up loop_i_lower loop_i_upper 1 tt (fun i _ _ => let idx := to_bits 5 i in (writeCapReg idx null_cap) : M (unit))). Definition cp2_next_pc '(tt : unit) : M (unit) := read_reg NextPCC_ref >>= fun w__0 : Capability => write_reg PCC_ref w__0 >> ((read_reg InBranchDelay_ref) : M (mword 1)) >>= fun w__1 : mword 1 => (if (bits_to_bool w__1) : bool then read_reg DelayedPCC_ref >>= fun w__2 : Capability => write_reg NextPCC_ref w__2 : M (unit) else returnm tt) : M (unit). Definition get_CP0EPC '(tt : unit) : M (mword 64) := read_reg EPCC_ref >>= fun w__0 : Capability => returnm (to_bits 64 (projT1 (getCapOffset w__0))). Definition set_CP0EPC (newEPC : mword 64) : M (unit) := read_reg EPCC_ref >>= fun w__0 : Capability => let '(representable, newEPCC) := setCapOffset w__0 newEPC in write_reg EPCC_ref (if sumbool_of_bool representable then {[ newEPCC with Capability_tag := (andb newEPCC.(Capability_tag) (negb newEPCC.(Capability_sealed))) ]} else unrepCap newEPCC) : M (unit). Definition get_CP0ErrorEPC '(tt : unit) : M (mword 64) := read_reg ErrorEPCC_ref >>= fun w__0 : Capability => returnm (to_bits 64 (projT1 (getCapOffset w__0))). Definition set_CP0ErrorEPC (v : mword 64) : M (unit) := read_reg ErrorEPCC_ref >>= fun w__0 : Capability => let '(representable, newErrorEPCC) := setCapOffset w__0 v in write_reg ErrorEPCC_ref (if sumbool_of_bool representable then {[ newErrorEPCC with Capability_tag := (andb newErrorEPCC.(Capability_tag) (negb newErrorEPCC.(Capability_sealed))) ]} else unrepCap newErrorEPCC) : M (unit). Definition dump_cp2_state '(tt : unit) : M (unit) := read_reg PCC_ref >>= fun w__0 : Capability => (capToString w__0 true) >>= fun w__1 : string => let '_ := (print_endline (String.append "DEBUG CAP PCC" w__1)) : unit in (let loop_i_lower := 0 in let loop_i_upper := 31 in (foreach_ZM_up loop_i_lower loop_i_upper 1 tt (fun i _ _ => (readCapReg (to_bits 5 i)) >>= fun w__2 : Capability => (capToString w__2 true) >>= fun w__3 : string => returnm (let '_ := (print_endline (String.append "DEBUG CAP REG " (String.append (string_of_int i) w__3))) : unit in tt)))) >> read_reg DDC_ref >>= fun w__4 : Capability => (capToString w__4 true) >>= fun w__5 : string => let '_ := (print_endline (String.append "DEBUG CAP HWREG 00" w__5)) : unit in read_reg CULR_ref >>= fun w__6 : Capability => (capToString w__6 true) >>= fun w__7 : string => let '_ := (print_endline (String.append "DEBUG CAP HWREG 01" w__7)) : unit in read_reg CPLR_ref >>= fun w__8 : Capability => (capToString w__8 true) >>= fun w__9 : string => let '_ := (print_endline (String.append "DEBUG CAP HWREG 08" w__9)) : unit in read_reg KR1C_ref >>= fun w__10 : Capability => (capToString w__10 true) >>= fun w__11 : string => let '_ := (print_endline (String.append "DEBUG CAP HWREG 22" w__11)) : unit in read_reg KR2C_ref >>= fun w__12 : Capability => (capToString w__12 true) >>= fun w__13 : string => let '_ := (print_endline (String.append "DEBUG CAP HWREG 23" w__13)) : unit in read_reg ErrorEPCC_ref >>= fun w__14 : Capability => (capToString w__14 true) >>= fun w__15 : string => let '_ := (print_endline (String.append "DEBUG CAP HWREG 28" w__15)) : unit in read_reg KCC_ref >>= fun w__16 : Capability => (capToString w__16 true) >>= fun w__17 : string => let '_ := (print_endline (String.append "DEBUG CAP HWREG 29" w__17)) : unit in read_reg KDC_ref >>= fun w__18 : Capability => (capToString w__18 true) >>= fun w__19 : string => let '_ := (print_endline (String.append "DEBUG CAP HWREG 30" w__19)) : unit in read_reg EPCC_ref >>= fun w__20 : Capability => (capToString w__20 true) >>= fun w__21 : string => returnm (print_endline (String.append "DEBUG CAP HWREG 31" w__21)). Definition getCapFlags (cap : Capability) : mword 1 := 'b"0" : mword 1. Definition setCapFlags (cap : Capability) (flags : mword 1) : Capability := cap. Definition isSentryCap (cap : Capability) : bool := Z.eqb (projT1 (sint cap.(Capability_otype))) otype_sentry. Definition ERETHook '(tt : unit) : M (unit) := read_reg CP0Status_ref >>= fun w__0 : StatusReg => (if Bool.eqb (bits_to_bool (_get_StatusReg_ERL w__0)) (bit_to_bool B1) then read_reg ErrorEPCC_ref : M (Capability) else read_reg EPCC_ref : M (Capability)) >>= fun epcc_val => let new_pcc := if isSentryCap epcc_val then unsealCap epcc_val else epcc_val in (set_next_pcc new_pcc) : M (unit). Definition TLBWriteEntry (idx : mword 6) : M (unit) := ((read_reg TLBPageMask_ref) : M (mword 16)) >>= fun pagemask => let b__0 := pagemask in (if eq_vec b__0 (Ox"0000" : mword 16) then returnm tt else if eq_vec b__0 (Ox"0003" : mword 16) then returnm tt else if eq_vec b__0 (Ox"000F" : mword 16) then returnm tt else if eq_vec b__0 (Ox"003F" : mword 16) then returnm tt else if eq_vec b__0 (Ox"00FF" : mword 16) then returnm tt else if eq_vec b__0 (Ox"03FF" : mword 16) then returnm tt else if eq_vec b__0 (Ox"0FFF" : mword 16) then returnm tt else if eq_vec b__0 (Ox"3FFF" : mword 16) then returnm tt else if eq_vec b__0 (Ox"FFFF" : mword 16) then returnm tt else (SignalException MCheck) : M (unit)) >> let i := projT1 (uint idx) in let entry := vec_access_dec TLBEntries i in (_set_TLBEntry_pagemask entry pagemask) >> read_reg TLBEntryHi_ref >>= fun w__0 : TLBEntryHiReg => (_set_TLBEntry_r entry (_get_TLBEntryHiReg_R w__0)) >> read_reg TLBEntryHi_ref >>= fun w__1 : TLBEntryHiReg => (_set_TLBEntry_vpn2 entry (_get_TLBEntryHiReg_VPN2 w__1)) >> read_reg TLBEntryHi_ref >>= fun w__2 : TLBEntryHiReg => (_set_TLBEntry_asid entry (_get_TLBEntryHiReg_ASID w__2)) >> (and_boolM (read_reg TLBEntryLo0_ref >>= fun w__3 : TLBEntryLoReg => returnm ((bits_to_bool (_get_TLBEntryLoReg_G w__3)) : bool)) (read_reg TLBEntryLo1_ref >>= fun w__4 : TLBEntryLoReg => returnm ((bits_to_bool (_get_TLBEntryLoReg_G w__4)) : bool))) >>= fun w__5 : bool => (_set_TLBEntry_g entry ((bool_to_bits w__5) : mword 1)) >> (_set_TLBEntry_valid entry ((cast_unit_vec B1) : mword 1)) >> read_reg TLBEntryLo0_ref >>= fun w__6 : TLBEntryLoReg => (_set_TLBEntry_caps0 entry (_get_TLBEntryLoReg_CapS w__6)) >> read_reg TLBEntryLo0_ref >>= fun w__7 : TLBEntryLoReg => (_set_TLBEntry_capl0 entry (_get_TLBEntryLoReg_CapL w__7)) >> read_reg TLBEntryLo0_ref >>= fun w__8 : TLBEntryLoReg => (_set_TLBEntry_caplg0 entry (_get_TLBEntryLoReg_CapLG w__8)) >> read_reg TLBEntryLo0_ref >>= fun w__9 : TLBEntryLoReg => (_set_TLBEntry_pfn0 entry (_get_TLBEntryLoReg_PFN w__9)) >> read_reg TLBEntryLo0_ref >>= fun w__10 : TLBEntryLoReg => (_set_TLBEntry_c0 entry (_get_TLBEntryLoReg_C w__10)) >> read_reg TLBEntryLo0_ref >>= fun w__11 : TLBEntryLoReg => (_set_TLBEntry_d0 entry (_get_TLBEntryLoReg_D w__11)) >> read_reg TLBEntryLo0_ref >>= fun w__12 : TLBEntryLoReg => (_set_TLBEntry_v0 entry (_get_TLBEntryLoReg_V w__12)) >> read_reg TLBEntryLo1_ref >>= fun w__13 : TLBEntryLoReg => (_set_TLBEntry_caps1 entry (_get_TLBEntryLoReg_CapS w__13)) >> read_reg TLBEntryLo1_ref >>= fun w__14 : TLBEntryLoReg => (_set_TLBEntry_capl1 entry (_get_TLBEntryLoReg_CapL w__14)) >> read_reg TLBEntryLo1_ref >>= fun w__15 : TLBEntryLoReg => (_set_TLBEntry_caplg1 entry (_get_TLBEntryLoReg_CapLG w__15)) >> read_reg TLBEntryLo1_ref >>= fun w__16 : TLBEntryLoReg => (_set_TLBEntry_pfn1 entry (_get_TLBEntryLoReg_PFN w__16)) >> read_reg TLBEntryLo1_ref >>= fun w__17 : TLBEntryLoReg => (_set_TLBEntry_c1 entry (_get_TLBEntryLoReg_C w__17)) >> read_reg TLBEntryLo1_ref >>= fun w__18 : TLBEntryLoReg => (_set_TLBEntry_d1 entry (_get_TLBEntryLoReg_D w__18)) >> read_reg TLBEntryLo1_ref >>= fun w__19 : TLBEntryLoReg => (_set_TLBEntry_v1 entry (_get_TLBEntryLoReg_V w__19)) : M (unit). Definition strCReg (r : mword 5) : string := concat_str_dec "$c" (projT1 (uint r)). Definition strRRArgs (rd : mword 5) (r1 : mword 5) : string := String.append (strReg rd) (String.append ", " (strReg r1)). Definition strRCArgs (rd : mword 5) (c1 : mword 5) : string := String.append (strReg rd) (String.append ", " (strCReg c1)). Definition strCRArgs (cd : mword 5) (r1 : mword 5) : string := String.append (strCReg cd) (String.append ", " (strReg r1)). Definition strCCArgs (cd : mword 5) (c1 : mword 5) : string := String.append (strCReg cd) (String.append ", " (strCReg c1)). Definition strCCCArgs (cd : mword 5) (c1 : mword 5) (c2 : mword 5) : string := String.append (strCReg cd) (String.append ", " (String.append (strCReg c1) (String.append ", " (strCReg c2)))). Definition strCCRArgs (cd : mword 5) (c1 : mword 5) (r2 : mword 5) : string := String.append (strCReg cd) (String.append ", " (String.append (strCReg c1) (String.append ", " (strReg r2)))). Definition strRCCArgs (rd : mword 5) (c1 : mword 5) (c2 : mword 5) : string := String.append (strReg rd) (String.append ", " (String.append (strCReg c1) (String.append ", " (strCReg c2)))). Definition strRCRArgs (rd : mword 5) (c1 : mword 5) (r2 : mword 5) : string := String.append (strReg rd) (String.append ", " (String.append (strCReg c1) (String.append ", " (strReg r2)))). Definition strCCIArgs {n : Z} (cd : mword 5) (cs : mword 5) (imm : mword n) `{ArithFact (n >? 0)} : string := String.append (strCReg cd) (String.append ", " (String.append (strCReg cs) (String.append ", " (dec_str (projT1 (sint imm)))))). Definition strCCIUArgs {n : Z} (cd : mword 5) (cs : mword 5) (imm : mword n) `{ArithFact (n >? 0)} : string := String.append (strCReg cd) (String.append ", " (String.append (strCReg cs) (String.append ", " (hex_str (projT1 (uint imm)))))). Definition decode (v__0 : mword 32) : option ast := if eq_vec (subrange_vec_dec v__0 31 26) ('b"011001" : mword (31 - 26 + 1)) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in let imm : imm16 := subrange_vec_dec v__0 15 0 in Some (DADDIU (rs, rt, imm)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000000" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00000101101" : mword (10 - 0 + 1))) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in let rd : regno := subrange_vec_dec v__0 15 11 in Some (DADDU (rs, rt, rd)) else if eq_vec (subrange_vec_dec v__0 31 26) ('b"011000" : mword (31 - 26 + 1)) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in let imm : imm16 := subrange_vec_dec v__0 15 0 in Some (DADDI (rs, rt, imm)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000000" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00000101100" : mword (10 - 0 + 1))) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in let rd : regno := subrange_vec_dec v__0 15 11 in Some (DADD (rs, rt, rd)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000000" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00000100000" : mword (10 - 0 + 1))) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in let rd : regno := subrange_vec_dec v__0 15 11 in Some (ADD (rs, rt, rd)) else if eq_vec (subrange_vec_dec v__0 31 26) ('b"001000" : mword (31 - 26 + 1)) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in let imm : imm16 := subrange_vec_dec v__0 15 0 in Some (ADDI (rs, rt, imm)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000000" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00000100001" : mword (10 - 0 + 1))) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in let rd : regno := subrange_vec_dec v__0 15 11 in Some (ADDU (rs, rt, rd)) else if eq_vec (subrange_vec_dec v__0 31 26) ('b"001001" : mword (31 - 26 + 1)) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in let imm : imm16 := subrange_vec_dec v__0 15 0 in Some (ADDIU (rs, rt, imm)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000000" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00000101111" : mword (10 - 0 + 1))) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in let rd : regno := subrange_vec_dec v__0 15 11 in Some (DSUBU (rs, rt, rd)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000000" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00000101110" : mword (10 - 0 + 1))) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in let rd : regno := subrange_vec_dec v__0 15 11 in Some (DSUB (rs, rt, rd)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000000" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00000100010" : mword (10 - 0 + 1))) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in let rd : regno := subrange_vec_dec v__0 15 11 in Some (SUB (rs, rt, rd)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000000" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00000100011" : mword (10 - 0 + 1))) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in let rd : regno := subrange_vec_dec v__0 15 11 in Some (SUBU (rs, rt, rd)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000000" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00000100100" : mword (10 - 0 + 1))) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in let rd : regno := subrange_vec_dec v__0 15 11 in Some (AND (rs, rt, rd)) else if eq_vec (subrange_vec_dec v__0 31 26) ('b"001100" : mword (31 - 26 + 1)) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in let imm : imm16 := subrange_vec_dec v__0 15 0 in Some (ANDI (rs, rt, imm)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000000" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00000100101" : mword (10 - 0 + 1))) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in let rd : regno := subrange_vec_dec v__0 15 11 in Some (OR (rs, rt, rd)) else if eq_vec (subrange_vec_dec v__0 31 26) ('b"001101" : mword (31 - 26 + 1)) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in let imm : imm16 := subrange_vec_dec v__0 15 0 in Some (ORI (rs, rt, imm)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000000" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00000100111" : mword (10 - 0 + 1))) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in let rd : regno := subrange_vec_dec v__0 15 11 in Some (NOR (rs, rt, rd)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000000" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00000100110" : mword (10 - 0 + 1))) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in let rd : regno := subrange_vec_dec v__0 15 11 in Some (XOR (rs, rt, rd)) else if eq_vec (subrange_vec_dec v__0 31 26) ('b"001110" : mword (31 - 26 + 1)) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in let imm : imm16 := subrange_vec_dec v__0 15 0 in Some (XORI (rs, rt, imm)) else if eq_vec (subrange_vec_dec v__0 31 21) ('b"00111100000" : mword (31 - 21 + 1)) then let rt : regno := subrange_vec_dec v__0 20 16 in let imm : imm16 := subrange_vec_dec v__0 15 0 in Some (LUI (rt, imm)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"00000000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"111000" : mword (5 - 0 + 1))) then let sa : bits 5 := subrange_vec_dec v__0 10 6 in let rt : regno := subrange_vec_dec v__0 20 16 in let rd : regno := subrange_vec_dec v__0 15 11 in Some (DSLL (rt, rd, sa)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"00000000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"111100" : mword (5 - 0 + 1))) then let sa : bits 5 := subrange_vec_dec v__0 10 6 in let rt : regno := subrange_vec_dec v__0 20 16 in let rd : regno := subrange_vec_dec v__0 15 11 in Some (DSLL32 (rt, rd, sa)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000000" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00000010100" : mword (10 - 0 + 1))) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in let rd : regno := subrange_vec_dec v__0 15 11 in Some (DSLLV (rs, rt, rd)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"00000000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"111011" : mword (5 - 0 + 1))) then let sa : bits 5 := subrange_vec_dec v__0 10 6 in let rt : regno := subrange_vec_dec v__0 20 16 in let rd : regno := subrange_vec_dec v__0 15 11 in Some (DSRA (rt, rd, sa)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"00000000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"111111" : mword (5 - 0 + 1))) then let sa : bits 5 := subrange_vec_dec v__0 10 6 in let rt : regno := subrange_vec_dec v__0 20 16 in let rd : regno := subrange_vec_dec v__0 15 11 in Some (DSRA32 (rt, rd, sa)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000000" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00000010111" : mword (10 - 0 + 1))) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in let rd : regno := subrange_vec_dec v__0 15 11 in Some (DSRAV (rs, rt, rd)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"00000000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"111010" : mword (5 - 0 + 1))) then let sa : bits 5 := subrange_vec_dec v__0 10 6 in let rt : regno := subrange_vec_dec v__0 20 16 in let rd : regno := subrange_vec_dec v__0 15 11 in Some (DSRL (rt, rd, sa)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"00000000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"111110" : mword (5 - 0 + 1))) then let sa : bits 5 := subrange_vec_dec v__0 10 6 in let rt : regno := subrange_vec_dec v__0 20 16 in let rd : regno := subrange_vec_dec v__0 15 11 in Some (DSRL32 (rt, rd, sa)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000000" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00000010110" : mword (10 - 0 + 1))) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in let rd : regno := subrange_vec_dec v__0 15 11 in Some (DSRLV (rs, rt, rd)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"00000000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"000000" : mword (5 - 0 + 1))) then let sa : regno := subrange_vec_dec v__0 10 6 in let rt : regno := subrange_vec_dec v__0 20 16 in let rd : regno := subrange_vec_dec v__0 15 11 in Some (SLL (rt, rd, sa)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000000" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00000000100" : mword (10 - 0 + 1))) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in let rd : regno := subrange_vec_dec v__0 15 11 in Some (SLLV (rs, rt, rd)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"00000000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"000011" : mword (5 - 0 + 1))) then let sa : regno := subrange_vec_dec v__0 10 6 in let rt : regno := subrange_vec_dec v__0 20 16 in let rd : regno := subrange_vec_dec v__0 15 11 in Some (SRA (rt, rd, sa)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000000" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00000000111" : mword (10 - 0 + 1))) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in let rd : regno := subrange_vec_dec v__0 15 11 in Some (SRAV (rs, rt, rd)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"00000000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"000010" : mword (5 - 0 + 1))) then let sa : regno := subrange_vec_dec v__0 10 6 in let rt : regno := subrange_vec_dec v__0 20 16 in let rd : regno := subrange_vec_dec v__0 15 11 in Some (SRL (rt, rd, sa)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000000" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00000000110" : mword (10 - 0 + 1))) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in let rd : regno := subrange_vec_dec v__0 15 11 in Some (SRLV (rs, rt, rd)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000000" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00000101010" : mword (10 - 0 + 1))) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in let rd : regno := subrange_vec_dec v__0 15 11 in Some (SLT (rs, rt, rd)) else if eq_vec (subrange_vec_dec v__0 31 26) ('b"001010" : mword (31 - 26 + 1)) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in let imm : imm16 := subrange_vec_dec v__0 15 0 in Some (SLTI (rs, rt, imm)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000000" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00000101011" : mword (10 - 0 + 1))) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in let rd : regno := subrange_vec_dec v__0 15 11 in Some (SLTU (rs, rt, rd)) else if eq_vec (subrange_vec_dec v__0 31 26) ('b"001011" : mword (31 - 26 + 1)) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in let imm : imm16 := subrange_vec_dec v__0 15 0 in Some (SLTIU (rs, rt, imm)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000000" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00000001011" : mword (10 - 0 + 1))) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in let rd : regno := subrange_vec_dec v__0 15 11 in Some (MOVN (rs, rt, rd)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000000" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00000001010" : mword (10 - 0 + 1))) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in let rd : regno := subrange_vec_dec v__0 15 11 in Some (MOVZ (rs, rt, rd)) else if andb (eq_vec (subrange_vec_dec v__0 31 16) (Ox"0000" : mword (31 - 16 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00000010000" : mword (10 - 0 + 1))) then let rd : regno := subrange_vec_dec v__0 15 11 in Some (MFHI rd) else if andb (eq_vec (subrange_vec_dec v__0 31 16) (Ox"0000" : mword (31 - 16 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00000010010" : mword (10 - 0 + 1))) then let rd : regno := subrange_vec_dec v__0 15 11 in Some (MFLO rd) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000000" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 20 0) ('b"000000000000000010001" : mword (20 - 0 + 1))) then let rs : regno := subrange_vec_dec v__0 25 21 in Some (MTHI rs) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000000" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 20 0) ('b"000000000000000010011" : mword (20 - 0 + 1))) then let rs : regno := subrange_vec_dec v__0 25 21 in Some (MTLO rs) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"011100" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00000000010" : mword (10 - 0 + 1))) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in let rd : regno := subrange_vec_dec v__0 15 11 in Some (MUL (rs, rt, rd)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000000" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 15 0) (Ox"0018" : mword (15 - 0 + 1))) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in Some (MULT (rs, rt)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000000" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 15 0) (Ox"0019" : mword (15 - 0 + 1))) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in Some (MULTU (rs, rt)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000000" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 15 0) (Ox"001C" : mword (15 - 0 + 1))) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in Some (DMULT (rs, rt)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000000" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 15 0) (Ox"001D" : mword (15 - 0 + 1))) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in Some (DMULTU (rs, rt)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"011100" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 15 0) (Ox"0000" : mword (15 - 0 + 1))) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in Some (MADD (rs, rt)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"011100" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 15 0) (Ox"0001" : mword (15 - 0 + 1))) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in Some (MADDU (rs, rt)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"011100" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 15 0) (Ox"0004" : mword (15 - 0 + 1))) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in Some (MSUB (rs, rt)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"011100" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 15 0) (Ox"0005" : mword (15 - 0 + 1))) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in Some (MSUBU (rs, rt)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000000" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 15 0) (Ox"001A" : mword (15 - 0 + 1))) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in Some (DIV (rs, rt)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000000" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 15 0) (Ox"001B" : mword (15 - 0 + 1))) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in Some (DIVU (rs, rt)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000000" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 15 0) (Ox"001E" : mword (15 - 0 + 1))) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in Some (DDIV (rs, rt)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000000" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 15 0) (Ox"001F" : mword (15 - 0 + 1))) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in Some (DDIVU (rs, rt)) else if eq_vec (subrange_vec_dec v__0 31 26) ('b"000010" : mword (31 - 26 + 1)) then let offset : bits 26 := subrange_vec_dec v__0 25 0 in Some (J offset) else if eq_vec (subrange_vec_dec v__0 31 26) ('b"000011" : mword (31 - 26 + 1)) then let offset : bits 26 := subrange_vec_dec v__0 25 0 in Some (JAL offset) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000000" : mword (31 - 26 + 1))) (andb (eq_vec (subrange_vec_dec v__0 20 11) ('b"0000000000" : mword (20 - 11 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"001000" : mword (5 - 0 + 1)))) then let rs : regno := subrange_vec_dec v__0 25 21 in Some (JR rs) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000000" : mword (31 - 26 + 1))) (andb (eq_vec (subrange_vec_dec v__0 20 16) ('b"00000" : mword (20 - 16 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"001001" : mword (5 - 0 + 1)))) then let rs : regno := subrange_vec_dec v__0 25 21 in let rd : regno := subrange_vec_dec v__0 15 11 in Some (JALR (rs, rd)) else if eq_vec (subrange_vec_dec v__0 31 26) ('b"000100" : mword (31 - 26 + 1)) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in let imm : imm16 := subrange_vec_dec v__0 15 0 in Some (BEQ (rs, rt, imm, false, false)) else if eq_vec (subrange_vec_dec v__0 31 26) ('b"010100" : mword (31 - 26 + 1)) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in let imm : imm16 := subrange_vec_dec v__0 15 0 in Some (BEQ (rs, rt, imm, false, true)) else if eq_vec (subrange_vec_dec v__0 31 26) ('b"000101" : mword (31 - 26 + 1)) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in let imm : imm16 := subrange_vec_dec v__0 15 0 in Some (BEQ (rs, rt, imm, true, false)) else if eq_vec (subrange_vec_dec v__0 31 26) ('b"010101" : mword (31 - 26 + 1)) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in let imm : imm16 := subrange_vec_dec v__0 15 0 in Some (BEQ (rs, rt, imm, true, true)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000001" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 20 16) ('b"00000" : mword (20 - 16 + 1))) then let rs : regno := subrange_vec_dec v__0 25 21 in let imm : imm16 := subrange_vec_dec v__0 15 0 in Some (BCMPZ (rs, imm, LT', false, false)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000001" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 20 16) ('b"10000" : mword (20 - 16 + 1))) then let rs : regno := subrange_vec_dec v__0 25 21 in let imm : imm16 := subrange_vec_dec v__0 15 0 in Some (BCMPZ (rs, imm, LT', true, false)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000001" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 20 16) ('b"00010" : mword (20 - 16 + 1))) then let rs : regno := subrange_vec_dec v__0 25 21 in let imm : imm16 := subrange_vec_dec v__0 15 0 in Some (BCMPZ (rs, imm, LT', false, true)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000001" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 20 16) ('b"10010" : mword (20 - 16 + 1))) then let rs : regno := subrange_vec_dec v__0 25 21 in let imm : imm16 := subrange_vec_dec v__0 15 0 in Some (BCMPZ (rs, imm, LT', true, true)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000001" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 20 16) ('b"00001" : mword (20 - 16 + 1))) then let rs : regno := subrange_vec_dec v__0 25 21 in let imm : imm16 := subrange_vec_dec v__0 15 0 in Some (BCMPZ (rs, imm, GE, false, false)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000001" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 20 16) ('b"10001" : mword (20 - 16 + 1))) then let rs : regno := subrange_vec_dec v__0 25 21 in let imm : imm16 := subrange_vec_dec v__0 15 0 in Some (BCMPZ (rs, imm, GE, true, false)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000001" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 20 16) ('b"00011" : mword (20 - 16 + 1))) then let rs : regno := subrange_vec_dec v__0 25 21 in let imm : imm16 := subrange_vec_dec v__0 15 0 in Some (BCMPZ (rs, imm, GE, false, true)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000001" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 20 16) ('b"10011" : mword (20 - 16 + 1))) then let rs : regno := subrange_vec_dec v__0 25 21 in let imm : imm16 := subrange_vec_dec v__0 15 0 in Some (BCMPZ (rs, imm, GE, true, true)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000111" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 20 16) ('b"00000" : mword (20 - 16 + 1))) then let rs : regno := subrange_vec_dec v__0 25 21 in let imm : imm16 := subrange_vec_dec v__0 15 0 in Some (BCMPZ (rs, imm, GT', false, false)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"010111" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 20 16) ('b"00000" : mword (20 - 16 + 1))) then let rs : regno := subrange_vec_dec v__0 25 21 in let imm : imm16 := subrange_vec_dec v__0 15 0 in Some (BCMPZ (rs, imm, GT', false, true)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000110" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 20 16) ('b"00000" : mword (20 - 16 + 1))) then let rs : regno := subrange_vec_dec v__0 25 21 in let imm : imm16 := subrange_vec_dec v__0 15 0 in Some (BCMPZ (rs, imm, LE, false, false)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"010110" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 20 16) ('b"00000" : mword (20 - 16 + 1))) then let rs : regno := subrange_vec_dec v__0 25 21 in let imm : imm16 := subrange_vec_dec v__0 15 0 in Some (BCMPZ (rs, imm, LE, false, true)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000000" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"001100" : mword (5 - 0 + 1))) then Some (SYSCALL tt) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000000" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"001101" : mword (5 - 0 + 1))) then Some (BREAK tt) else if eq_vec v__0 (Ox"42000020" : mword 32) then Some (WAIT tt) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000000" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"110000" : mword (5 - 0 + 1))) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in Some (TRAPREG (rs, rt, GE)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000000" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"110001" : mword (5 - 0 + 1))) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in Some (TRAPREG (rs, rt, GEU)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000000" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"110010" : mword (5 - 0 + 1))) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in Some (TRAPREG (rs, rt, LT')) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000000" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"110011" : mword (5 - 0 + 1))) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in Some (TRAPREG (rs, rt, LTU)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000000" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"110100" : mword (5 - 0 + 1))) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in Some (TRAPREG (rs, rt, EQ')) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000000" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"110110" : mword (5 - 0 + 1))) then let rt : regno := subrange_vec_dec v__0 20 16 in let rs : regno := subrange_vec_dec v__0 25 21 in Some (TRAPREG (rs, rt, NE)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000001" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 20 16) ('b"01100" : mword (20 - 16 + 1))) then let rs : regno := subrange_vec_dec v__0 25 21 in let imm : imm16 := subrange_vec_dec v__0 15 0 in Some (TRAPIMM (rs, imm, EQ')) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000001" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 20 16) ('b"01110" : mword (20 - 16 + 1))) then let rs : regno := subrange_vec_dec v__0 25 21 in let imm : imm16 := subrange_vec_dec v__0 15 0 in Some (TRAPIMM (rs, imm, NE)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000001" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 20 16) ('b"01000" : mword (20 - 16 + 1))) then let rs : regno := subrange_vec_dec v__0 25 21 in let imm : imm16 := subrange_vec_dec v__0 15 0 in Some (TRAPIMM (rs, imm, GE)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000001" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 20 16) ('b"01001" : mword (20 - 16 + 1))) then let rs : regno := subrange_vec_dec v__0 25 21 in let imm : imm16 := subrange_vec_dec v__0 15 0 in Some (TRAPIMM (rs, imm, GEU)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000001" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 20 16) ('b"01010" : mword (20 - 16 + 1))) then let rs : regno := subrange_vec_dec v__0 25 21 in let imm : imm16 := subrange_vec_dec v__0 15 0 in Some (TRAPIMM (rs, imm, LT')) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"000001" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 20 16) ('b"01011" : mword (20 - 16 + 1))) then let rs : regno := subrange_vec_dec v__0 25 21 in let imm : imm16 := subrange_vec_dec v__0 15 0 in Some (TRAPIMM (rs, imm, LTU)) else if eq_vec (subrange_vec_dec v__0 31 26) ('b"100000" : mword (31 - 26 + 1)) then let rt : regno := subrange_vec_dec v__0 20 16 in let offset : imm16 := subrange_vec_dec v__0 15 0 in let base : regno := subrange_vec_dec v__0 25 21 in Some (Load (B, true, false, base, rt, offset)) else if eq_vec (subrange_vec_dec v__0 31 26) ('b"100100" : mword (31 - 26 + 1)) then let rt : regno := subrange_vec_dec v__0 20 16 in let offset : imm16 := subrange_vec_dec v__0 15 0 in let base : regno := subrange_vec_dec v__0 25 21 in Some (Load (B, false, false, base, rt, offset)) else if eq_vec (subrange_vec_dec v__0 31 26) ('b"100001" : mword (31 - 26 + 1)) then let rt : regno := subrange_vec_dec v__0 20 16 in let offset : imm16 := subrange_vec_dec v__0 15 0 in let base : regno := subrange_vec_dec v__0 25 21 in Some (Load (H, true, false, base, rt, offset)) else if eq_vec (subrange_vec_dec v__0 31 26) ('b"100101" : mword (31 - 26 + 1)) then let rt : regno := subrange_vec_dec v__0 20 16 in let offset : imm16 := subrange_vec_dec v__0 15 0 in let base : regno := subrange_vec_dec v__0 25 21 in Some (Load (H, false, false, base, rt, offset)) else if eq_vec (subrange_vec_dec v__0 31 26) ('b"100011" : mword (31 - 26 + 1)) then let rt : regno := subrange_vec_dec v__0 20 16 in let offset : imm16 := subrange_vec_dec v__0 15 0 in let base : regno := subrange_vec_dec v__0 25 21 in Some (Load (W, true, false, base, rt, offset)) else if eq_vec (subrange_vec_dec v__0 31 26) ('b"100111" : mword (31 - 26 + 1)) then let rt : regno := subrange_vec_dec v__0 20 16 in let offset : imm16 := subrange_vec_dec v__0 15 0 in let base : regno := subrange_vec_dec v__0 25 21 in Some (Load (W, false, false, base, rt, offset)) else if eq_vec (subrange_vec_dec v__0 31 26) ('b"110111" : mword (31 - 26 + 1)) then let rt : regno := subrange_vec_dec v__0 20 16 in let offset : imm16 := subrange_vec_dec v__0 15 0 in let base : regno := subrange_vec_dec v__0 25 21 in Some (Load (D, false, false, base, rt, offset)) else if eq_vec (subrange_vec_dec v__0 31 26) ('b"110000" : mword (31 - 26 + 1)) then let rt : regno := subrange_vec_dec v__0 20 16 in let offset : imm16 := subrange_vec_dec v__0 15 0 in let base : regno := subrange_vec_dec v__0 25 21 in Some (Load (W, true, true, base, rt, offset)) else if eq_vec (subrange_vec_dec v__0 31 26) ('b"110100" : mword (31 - 26 + 1)) then let rt : regno := subrange_vec_dec v__0 20 16 in let offset : imm16 := subrange_vec_dec v__0 15 0 in let base : regno := subrange_vec_dec v__0 25 21 in Some (Load (D, false, true, base, rt, offset)) else if eq_vec (subrange_vec_dec v__0 31 26) ('b"101000" : mword (31 - 26 + 1)) then let rt : regno := subrange_vec_dec v__0 20 16 in let offset : imm16 := subrange_vec_dec v__0 15 0 in let base : regno := subrange_vec_dec v__0 25 21 in Some (Store (B, false, base, rt, offset)) else if eq_vec (subrange_vec_dec v__0 31 26) ('b"101001" : mword (31 - 26 + 1)) then let rt : regno := subrange_vec_dec v__0 20 16 in let offset : imm16 := subrange_vec_dec v__0 15 0 in let base : regno := subrange_vec_dec v__0 25 21 in Some (Store (H, false, base, rt, offset)) else if eq_vec (subrange_vec_dec v__0 31 26) ('b"101011" : mword (31 - 26 + 1)) then let rt : regno := subrange_vec_dec v__0 20 16 in let offset : imm16 := subrange_vec_dec v__0 15 0 in let base : regno := subrange_vec_dec v__0 25 21 in Some (Store (W, false, base, rt, offset)) else if eq_vec (subrange_vec_dec v__0 31 26) ('b"111111" : mword (31 - 26 + 1)) then let rt : regno := subrange_vec_dec v__0 20 16 in let offset : imm16 := subrange_vec_dec v__0 15 0 in let base : regno := subrange_vec_dec v__0 25 21 in Some (Store (D, false, base, rt, offset)) else if eq_vec (subrange_vec_dec v__0 31 26) ('b"111000" : mword (31 - 26 + 1)) then let rt : regno := subrange_vec_dec v__0 20 16 in let offset : imm16 := subrange_vec_dec v__0 15 0 in let base : regno := subrange_vec_dec v__0 25 21 in Some (Store (W, true, base, rt, offset)) else if eq_vec (subrange_vec_dec v__0 31 26) ('b"111100" : mword (31 - 26 + 1)) then let rt : regno := subrange_vec_dec v__0 20 16 in let offset : imm16 := subrange_vec_dec v__0 15 0 in let base : regno := subrange_vec_dec v__0 25 21 in Some (Store (D, true, base, rt, offset)) else if eq_vec (subrange_vec_dec v__0 31 26) ('b"100010" : mword (31 - 26 + 1)) then let rt : regno := subrange_vec_dec v__0 20 16 in let offset : imm16 := subrange_vec_dec v__0 15 0 in let base : regno := subrange_vec_dec v__0 25 21 in Some (LWL (base, rt, offset)) else if eq_vec (subrange_vec_dec v__0 31 26) ('b"100110" : mword (31 - 26 + 1)) then let rt : regno := subrange_vec_dec v__0 20 16 in let offset : imm16 := subrange_vec_dec v__0 15 0 in let base : regno := subrange_vec_dec v__0 25 21 in Some (LWR (base, rt, offset)) else if eq_vec (subrange_vec_dec v__0 31 26) ('b"101010" : mword (31 - 26 + 1)) then let rt : regno := subrange_vec_dec v__0 20 16 in let offset : imm16 := subrange_vec_dec v__0 15 0 in let base : regno := subrange_vec_dec v__0 25 21 in Some (SWL (base, rt, offset)) else if eq_vec (subrange_vec_dec v__0 31 26) ('b"101110" : mword (31 - 26 + 1)) then let rt : regno := subrange_vec_dec v__0 20 16 in let offset : imm16 := subrange_vec_dec v__0 15 0 in let base : regno := subrange_vec_dec v__0 25 21 in Some (SWR (base, rt, offset)) else if eq_vec (subrange_vec_dec v__0 31 26) ('b"011010" : mword (31 - 26 + 1)) then let rt : regno := subrange_vec_dec v__0 20 16 in let offset : imm16 := subrange_vec_dec v__0 15 0 in let base : regno := subrange_vec_dec v__0 25 21 in Some (LDL (base, rt, offset)) else if eq_vec (subrange_vec_dec v__0 31 26) ('b"011011" : mword (31 - 26 + 1)) then let rt : regno := subrange_vec_dec v__0 20 16 in let offset : imm16 := subrange_vec_dec v__0 15 0 in let base : regno := subrange_vec_dec v__0 25 21 in Some (LDR (base, rt, offset)) else if eq_vec (subrange_vec_dec v__0 31 26) ('b"101100" : mword (31 - 26 + 1)) then let rt : regno := subrange_vec_dec v__0 20 16 in let offset : imm16 := subrange_vec_dec v__0 15 0 in let base : regno := subrange_vec_dec v__0 25 21 in Some (SDL (base, rt, offset)) else if eq_vec (subrange_vec_dec v__0 31 26) ('b"101101" : mword (31 - 26 + 1)) then let rt : regno := subrange_vec_dec v__0 20 16 in let offset : imm16 := subrange_vec_dec v__0 15 0 in let base : regno := subrange_vec_dec v__0 25 21 in Some (SDR (base, rt, offset)) else if eq_vec (subrange_vec_dec v__0 31 26) ('b"101111" : mword (31 - 26 + 1)) then let op : regno := subrange_vec_dec v__0 20 16 in let imm : imm16 := subrange_vec_dec v__0 15 0 in let base : regno := subrange_vec_dec v__0 25 21 in Some (CACHE (base, op, imm)) else if andb (eq_vec (subrange_vec_dec v__0 31 11) ('b"000000000000000000000" : mword (31 - 11 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"001111" : mword (5 - 0 + 1))) then Some (SYNC tt) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01000000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 10 3) (Ox"00" : mword (10 - 3 + 1))) then let sel : bits 3 := subrange_vec_dec v__0 2 0 in let rt : regno := subrange_vec_dec v__0 20 16 in let rd : regno := subrange_vec_dec v__0 15 11 in Some (MFC0 (rt, rd, sel, false)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01000000001" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 10 3) (Ox"00" : mword (10 - 3 + 1))) then let sel : bits 3 := subrange_vec_dec v__0 2 0 in let rt : regno := subrange_vec_dec v__0 20 16 in let rd : regno := subrange_vec_dec v__0 15 11 in Some (MFC0 (rt, rd, sel, true)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01000000100" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 15 0) (Ox"B800" : mword (15 - 0 + 1))) then Some (HCF tt) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01000000100" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 15 0) (Ox"D000" : mword (15 - 0 + 1))) then Some (HCF tt) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01000000100" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 10 3) (Ox"00" : mword (10 - 3 + 1))) then let sel : bits 3 := subrange_vec_dec v__0 2 0 in let rt : regno := subrange_vec_dec v__0 20 16 in let rd : regno := subrange_vec_dec v__0 15 11 in Some (MTC0 (rt, rd, sel, false)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01000000101" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 10 3) (Ox"00" : mword (10 - 3 + 1))) then let sel : bits 3 := subrange_vec_dec v__0 2 0 in let rt : regno := subrange_vec_dec v__0 20 16 in let rd : regno := subrange_vec_dec v__0 15 11 in Some (MTC0 (rt, rd, sel, true)) else if eq_vec v__0 (Ox"42000002" : mword 32) then Some ((TLBWI tt) : ast) else if eq_vec v__0 (Ox"42000006" : mword 32) then Some ((TLBWR tt) : ast) else if eq_vec v__0 (Ox"42000001" : mword 32) then Some ((TLBR tt) : ast) else if eq_vec v__0 (Ox"42000008" : mword 32) then Some ((TLBP tt) : ast) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01111100000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00000111011" : mword (10 - 0 + 1))) then let rt : regno := subrange_vec_dec v__0 20 16 in let rd : regno := subrange_vec_dec v__0 15 11 in Some (RDHWR (rt, rd)) else if eq_vec v__0 (Ox"42000018" : mword 32) then Some (ERET tt) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00000000000" : mword (10 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CGetPerm (rd, cb)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00000000001" : mword (10 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CGetType (rd, cb)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00000000010" : mword (10 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CGetBase (rd, cb)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00000000011" : mword (10 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CGetLen (rd, cb)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00000000101" : mword (10 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CGetTag (rd, cb)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00000000110" : mword (10 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CGetSealed (rd, cb)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 15 0) (Ox"0004" : mword (15 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in Some (CGetCause rd) else if eq_vec v__0 (Ox"48C00000" : mword 32) then Some (CReturn tt) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001001101" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00000000010" : mword (10 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CGetOffset (rd, cb)) else if andb (eq_vec (subrange_vec_dec v__0 31 11) ('b"010010001000000000000" : mword (31 - 11 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"000100" : mword (5 - 0 + 1))) then let rt : IntRegEnc := subrange_vec_dec v__0 10 6 in Some (CSetCause rt) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000100" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"000000" : mword (5 - 0 + 1))) then let rt : IntRegEnc := subrange_vec_dec v__0 10 6 in let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CAndPerm (cd, cb, rt)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001001100" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"000000" : mword (5 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in let ct : CapRegOrDDCEnc := subrange_vec_dec v__0 10 6 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CToPtr (rd, cb, ct)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001001110" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"000000" : mword (5 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in let ct : CapRegEnc := subrange_vec_dec v__0 10 6 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CPtrCmp (rd, cb, ct, CEQ)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001001110" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"000001" : mword (5 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in let ct : CapRegEnc := subrange_vec_dec v__0 10 6 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CPtrCmp (rd, cb, ct, CNE)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001001110" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"000010" : mword (5 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in let ct : CapRegEnc := subrange_vec_dec v__0 10 6 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CPtrCmp (rd, cb, ct, CLT)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001001110" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"000011" : mword (5 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in let ct : CapRegEnc := subrange_vec_dec v__0 10 6 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CPtrCmp (rd, cb, ct, CLE)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001001110" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"000100" : mword (5 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in let ct : CapRegEnc := subrange_vec_dec v__0 10 6 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CPtrCmp (rd, cb, ct, CLTU)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001001110" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"000101" : mword (5 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in let ct : CapRegEnc := subrange_vec_dec v__0 10 6 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CPtrCmp (rd, cb, ct, CLEU)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001001110" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"000110" : mword (5 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in let ct : CapRegEnc := subrange_vec_dec v__0 10 6 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CPtrCmp (rd, cb, ct, CEXEQ)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001001110" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"000111" : mword (5 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in let ct : CapRegEnc := subrange_vec_dec v__0 10 6 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CPtrCmp (rd, cb, ct, CNEXEQ)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001001101" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"000000" : mword (5 - 0 + 1))) then let rt : IntRegEnc := subrange_vec_dec v__0 10 6 in let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CIncOffset (cd, cb, rt)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001001101" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"000001" : mword (5 - 0 + 1))) then let rt : IntRegEnc := subrange_vec_dec v__0 10 6 in let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CSetOffset (cd, cb, rt)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000001" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"000000" : mword (5 - 0 + 1))) then let rt : IntRegEnc := subrange_vec_dec v__0 10 6 in let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CSetBounds (cd, cb, rt)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000100" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00000000101" : mword (10 - 0 + 1))) then let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CClearTag (cd, cb)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000100" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"000111" : mword (5 - 0 + 1))) then let rt : IntRegEnc := subrange_vec_dec v__0 10 6 in let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CFromPtr (cd, cb, rt)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001001011" : mword (31 - 21 + 1))) (andb (eq_vec (subrange_vec_dec v__0 15 11) ('b"00000" : mword (15 - 11 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"000000" : mword (5 - 0 + 1)))) then let rt : IntRegEnc := subrange_vec_dec v__0 10 6 in let cs : CapRegEnc := subrange_vec_dec v__0 20 16 in Some (CCheckPerm (cs, rt)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001001011" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00000000001" : mword (10 - 0 + 1))) then let cs : CapRegEnc := subrange_vec_dec v__0 20 16 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CCheckType (cs, cb)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000010" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"000000" : mword (5 - 0 + 1))) then let ct : CapRegEnc := subrange_vec_dec v__0 10 6 in let cs : CapRegEnc := subrange_vec_dec v__0 15 11 in let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in Some (CSeal (cd, cs, ct)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000011" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"000000" : mword (5 - 0 + 1))) then let ct : CapRegEnc := subrange_vec_dec v__0 10 6 in let cs : CapRegEnc := subrange_vec_dec v__0 15 11 in let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in Some (CUnseal (cd, cs, ct)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000111" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00000000000" : mword (10 - 0 + 1))) then let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CJALR (cd, cb, true)) else if andb (eq_vec (subrange_vec_dec v__0 31 16) (Ox"4900" : mword (31 - 16 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00000000000" : mword (10 - 0 + 1))) then let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CJALR ('b"00000" : mword 5, cb, false)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 15 0) (Ox"0FFF" : mword (15 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in Some (CGetCause rd) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 15 0) (Ox"17FF" : mword (15 - 0 + 1))) then let rs : IntRegEnc := subrange_vec_dec v__0 20 16 in Some (CSetCause rs) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 15 0) (Ox"07FF" : mword (15 - 0 + 1))) then let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in Some (CGetPCC cd) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 15 0) (Ox"1FFF" : mword (15 - 0 + 1))) then let cb : CapRegEnc := subrange_vec_dec v__0 20 16 in Some (CJALR ('b"00000" : mword 5, cb, false)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 15 0) (Ox"27FF" : mword (15 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in Some (CGetCID rd) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 15 0) (Ox"2FFF" : mword (15 - 0 + 1))) then let cb : CapRegEnc := subrange_vec_dec v__0 20 16 in Some (CSetCID cb) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 15 0) (Ox"C7FF" : mword (15 - 0 + 1))) then let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 20 16 in Some (CClearTags cb) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"01000111111" : mword (10 - 0 + 1))) then let rt : IntRegEnc := subrange_vec_dec v__0 15 11 in let cs : CapRegEnc := subrange_vec_dec v__0 20 16 in Some (CCheckPerm (cs, rt)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"01001111111" : mword (10 - 0 + 1))) then let cs : CapRegEnc := subrange_vec_dec v__0 20 16 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CCheckType (cs, cb)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"01011111111" : mword (10 - 0 + 1))) then let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CClearTag (cd, cb)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"01010111111" : mword (10 - 0 + 1))) then let cs : CapRegEnc := subrange_vec_dec v__0 15 11 in let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in Some (CMove (cd, cs)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"01100111111" : mword (10 - 0 + 1))) then let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CJALR (cd, cb, true)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"11101111111" : mword (10 - 0 + 1))) then let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CSealEntry (cd, cb)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"11110111111" : mword (10 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 15 11 in Some (CLoadTags (rd, cb)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00000111111" : mword (10 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CGetPerm (rd, cb)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00001111111" : mword (10 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CGetType (rd, cb)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00010111111" : mword (10 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CGetBase (rd, cb)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00011111111" : mword (10 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CGetLen (rd, cb)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00100111111" : mword (10 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CGetTag (rd, cb)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00101111111" : mword (10 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CGetSealed (rd, cb)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00110111111" : mword (10 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CGetOffset (rd, cb)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00111111111" : mword (10 - 0 + 1))) then let rs : IntRegEnc := subrange_vec_dec v__0 15 11 in let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in Some (CGetPCCSetOffset (cd, rs)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"01101111111" : mword (10 - 0 + 1))) then let sel : CapHwrEnc := subrange_vec_dec v__0 15 11 in let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in Some (CReadHwr (cd, sel)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"01110111111" : mword (10 - 0 + 1))) then let sel : CapHwrEnc := subrange_vec_dec v__0 15 11 in let cb : CapRegEnc := subrange_vec_dec v__0 20 16 in Some (CWriteHwr (cb, sel)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"01111111111" : mword (10 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CGetAddr (rd, cb)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"10010111111" : mword (10 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CGetFlags (rd, cb)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"10011111111" : mword (10 - 0 + 1))) then let rs : IntRegEnc := subrange_vec_dec v__0 15 11 in let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in Some (CGetPCCIncOffset (cd, rs)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"10100111111" : mword (10 - 0 + 1))) then let rs : IntRegEnc := subrange_vec_dec v__0 15 11 in let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in Some (CGetPCCSetAddr (cd, rs)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"10000111111" : mword (10 - 0 + 1))) then let rt : IntRegEnc := subrange_vec_dec v__0 20 16 in let rs : IntRegEnc := subrange_vec_dec v__0 15 11 in Some (CRAP (rt, rs)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"10001111111" : mword (10 - 0 + 1))) then let rt : IntRegEnc := subrange_vec_dec v__0 20 16 in let rs : IntRegEnc := subrange_vec_dec v__0 15 11 in Some (CRAM (rt, rs)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"001011" : mword (5 - 0 + 1))) then let ct : CapRegEnc := subrange_vec_dec v__0 10 6 in let cs : CapRegEnc := subrange_vec_dec v__0 15 11 in let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in Some (CSeal (cd, cs, ct)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"001100" : mword (5 - 0 + 1))) then let ct : CapRegEnc := subrange_vec_dec v__0 10 6 in let cs : CapRegEnc := subrange_vec_dec v__0 15 11 in let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in Some (CUnseal (cd, cs, ct)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"001101" : mword (5 - 0 + 1))) then let rt : IntRegEnc := subrange_vec_dec v__0 10 6 in let cs : CapRegEnc := subrange_vec_dec v__0 15 11 in let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in Some (CAndPerm (cd, cs, rt)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"001111" : mword (5 - 0 + 1))) then let rt : IntRegEnc := subrange_vec_dec v__0 10 6 in let cs : CapRegEnc := subrange_vec_dec v__0 15 11 in let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in Some (CSetOffset (cd, cs, rt)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"001000" : mword (5 - 0 + 1))) then let rt : IntRegEnc := subrange_vec_dec v__0 10 6 in let cs : CapRegEnc := subrange_vec_dec v__0 15 11 in let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in Some (CSetBounds (cd, cs, rt)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"001001" : mword (5 - 0 + 1))) then let rt : IntRegEnc := subrange_vec_dec v__0 10 6 in let cs : CapRegEnc := subrange_vec_dec v__0 15 11 in let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in Some (CSetBoundsExact (cd, cs, rt)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"001110" : mword (5 - 0 + 1))) then let rt : IntRegEnc := subrange_vec_dec v__0 10 6 in let cs : CapRegEnc := subrange_vec_dec v__0 15 11 in let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in Some (CSetFlags (cd, cs, rt)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"010001" : mword (5 - 0 + 1))) then let rt : IntRegEnc := subrange_vec_dec v__0 10 6 in let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CIncOffset (cd, cb, rt)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"011101" : mword (5 - 0 + 1))) then let ct : CapRegEnc := subrange_vec_dec v__0 10 6 in let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 15 11 in Some (CBuildCap (cd, cb, ct)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"011110" : mword (5 - 0 + 1))) then let ct : CapRegEnc := subrange_vec_dec v__0 10 6 in let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CCopyType (cd, cb, ct)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"011111" : mword (5 - 0 + 1))) then let ct : CapRegEnc := subrange_vec_dec v__0 10 6 in let cs : CapRegEnc := subrange_vec_dec v__0 15 11 in let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in Some (CCSeal (cd, cs, ct)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"010010" : mword (5 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in let ct : CapRegEnc := subrange_vec_dec v__0 10 6 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CToPtr (rd, cb, ct)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"010011" : mword (5 - 0 + 1))) then let rs : IntRegEnc := subrange_vec_dec v__0 10 6 in let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 15 11 in Some (CFromPtr (cd, cb, rs)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"001010" : mword (5 - 0 + 1))) then let rt : IntRegEnc := subrange_vec_dec v__0 20 16 in let cs : CapRegEnc := subrange_vec_dec v__0 10 6 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CSub (rt, cb, cs)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"011011" : mword (5 - 0 + 1))) then let rs : IntRegEnc := subrange_vec_dec v__0 10 6 in let cs : CapRegEnc := subrange_vec_dec v__0 15 11 in let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in Some (CMOVX (cd, cs, rs, false)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"011100" : mword (5 - 0 + 1))) then let rs : IntRegEnc := subrange_vec_dec v__0 10 6 in let cs : CapRegEnc := subrange_vec_dec v__0 15 11 in let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in Some (CMOVX (cd, cs, rs, true)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"100010" : mword (5 - 0 + 1))) then let rs : IntRegEnc := subrange_vec_dec v__0 10 6 in let cs : CapRegEnc := subrange_vec_dec v__0 15 11 in let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in Some (CSetAddr (cd, cs, rs)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"100011" : mword (5 - 0 + 1))) then let rs : IntRegEnc := subrange_vec_dec v__0 10 6 in let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in let cs : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CGetAndAddr (rd, cs, rs)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"100100" : mword (5 - 0 + 1))) then let rt : IntRegEnc := subrange_vec_dec v__0 10 6 in let cs : CapRegEnc := subrange_vec_dec v__0 15 11 in let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in Some (CAndAddr (cd, cs, rt)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"010100" : mword (5 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in let cs : CapRegEnc := subrange_vec_dec v__0 10 6 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CPtrCmp (rd, cb, cs, CEQ)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"010101" : mword (5 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in let cs : CapRegEnc := subrange_vec_dec v__0 10 6 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CPtrCmp (rd, cb, cs, CNE)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"010110" : mword (5 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in let cs : CapRegEnc := subrange_vec_dec v__0 10 6 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CPtrCmp (rd, cb, cs, CLT)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"010111" : mword (5 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in let cs : CapRegEnc := subrange_vec_dec v__0 10 6 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CPtrCmp (rd, cb, cs, CLE)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"011000" : mword (5 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in let cs : CapRegEnc := subrange_vec_dec v__0 10 6 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CPtrCmp (rd, cb, cs, CLTU)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"011001" : mword (5 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in let cs : CapRegEnc := subrange_vec_dec v__0 10 6 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CPtrCmp (rd, cb, cs, CLEU)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"011010" : mword (5 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in let cs : CapRegEnc := subrange_vec_dec v__0 10 6 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CPtrCmp (rd, cb, cs, CEXEQ)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"100001" : mword (5 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in let cs : CapRegEnc := subrange_vec_dec v__0 10 6 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CPtrCmp (rd, cb, cs, CNEXEQ)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"100000" : mword (5 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in let ct : CapRegEnc := subrange_vec_dec v__0 10 6 in let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 15 11 in Some (CTestSubset (rd, cb, ct)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"111000" : mword (5 - 0 + 1))) then let rs : IntRegEnc := subrange_vec_dec v__0 10 6 in let cs : CapRegOrDDCEnc := subrange_vec_dec v__0 15 11 in let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in Some (CLCNT (cd, cs, rs)) else if eq_vec (subrange_vec_dec v__0 31 21) ('b"01001001001" : mword (31 - 21 + 1)) then let imm : bits 16 := subrange_vec_dec v__0 15 0 in let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in Some (CBX (cd, imm, true)) else if eq_vec (subrange_vec_dec v__0 31 21) ('b"01001001010" : mword (31 - 21 + 1)) then let imm : bits 16 := subrange_vec_dec v__0 15 0 in let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in Some (CBX (cd, imm, false)) else if eq_vec (subrange_vec_dec v__0 31 21) ('b"01001010001" : mword (31 - 21 + 1)) then let imm : bits 16 := subrange_vec_dec v__0 15 0 in let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in Some (CBZ (cd, imm, false)) else if eq_vec (subrange_vec_dec v__0 31 21) ('b"01001010010" : mword (31 - 21 + 1)) then let imm : bits 16 := subrange_vec_dec v__0 15 0 in let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in Some (CBZ (cd, imm, true)) else if eq_vec v__0 (Ox"48A007FF" : mword 32) then Some (CReturn tt) else if eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000101" : mword (31 - 21 + 1)) then let selector : bits 11 := subrange_vec_dec v__0 10 0 in let cs : CapRegEnc := subrange_vec_dec v__0 20 16 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CCall (cs, cb, selector)) else if eq_vec (subrange_vec_dec v__0 31 16) (Ox"49E0" : mword (31 - 16 + 1)) then let imm : bits 16 := subrange_vec_dec v__0 15 0 in Some (ClearRegs (GPLo, imm)) else if eq_vec (subrange_vec_dec v__0 31 16) (Ox"49E1" : mword (31 - 16 + 1)) then let imm : bits 16 := subrange_vec_dec v__0 15 0 in Some (ClearRegs (GPHi, imm)) else if eq_vec (subrange_vec_dec v__0 31 16) (Ox"49E2" : mword (31 - 16 + 1)) then let imm : bits 16 := subrange_vec_dec v__0 15 0 in Some (ClearRegs (CLo, imm)) else if eq_vec (subrange_vec_dec v__0 31 16) (Ox"49E3" : mword (31 - 16 + 1)) then let imm : bits 16 := subrange_vec_dec v__0 15 0 in Some (ClearRegs (CHi, imm)) else if eq_vec (subrange_vec_dec v__0 31 21) ('b"01001010011" : mword (31 - 21 + 1)) then let imm : bits 11 := subrange_vec_dec v__0 10 0 in let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CIncOffsetImmediate (cd, cb, imm)) else if eq_vec (subrange_vec_dec v__0 31 21) ('b"01001010100" : mword (31 - 21 + 1)) then let imm : bits 11 := subrange_vec_dec v__0 10 0 in let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in Some (CSetBoundsImmediate (cd, cb, imm)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"110010" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 2 0) ('b"000" : mword (2 - 0 + 1))) then let rt : IntRegEnc := subrange_vec_dec v__0 15 11 in let rd : IntRegEnc := subrange_vec_dec v__0 25 21 in let offset : bits 8 := subrange_vec_dec v__0 10 3 in let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 20 16 in Some (CLoad (rd, cb, rt, offset, false, B)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"110010" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 2 0) ('b"100" : mword (2 - 0 + 1))) then let rt : IntRegEnc := subrange_vec_dec v__0 15 11 in let rd : IntRegEnc := subrange_vec_dec v__0 25 21 in let offset : bits 8 := subrange_vec_dec v__0 10 3 in let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 20 16 in Some (CLoad (rd, cb, rt, offset, true, B)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"110010" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 2 0) ('b"001" : mword (2 - 0 + 1))) then let rt : IntRegEnc := subrange_vec_dec v__0 15 11 in let rd : IntRegEnc := subrange_vec_dec v__0 25 21 in let offset : bits 8 := subrange_vec_dec v__0 10 3 in let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 20 16 in Some (CLoad (rd, cb, rt, offset, false, H)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"110010" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 2 0) ('b"101" : mword (2 - 0 + 1))) then let rt : IntRegEnc := subrange_vec_dec v__0 15 11 in let rd : IntRegEnc := subrange_vec_dec v__0 25 21 in let offset : bits 8 := subrange_vec_dec v__0 10 3 in let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 20 16 in Some (CLoad (rd, cb, rt, offset, true, H)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"110010" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 2 0) ('b"010" : mword (2 - 0 + 1))) then let rt : IntRegEnc := subrange_vec_dec v__0 15 11 in let rd : IntRegEnc := subrange_vec_dec v__0 25 21 in let offset : bits 8 := subrange_vec_dec v__0 10 3 in let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 20 16 in Some (CLoad (rd, cb, rt, offset, false, W)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"110010" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 2 0) ('b"110" : mword (2 - 0 + 1))) then let rt : IntRegEnc := subrange_vec_dec v__0 15 11 in let rd : IntRegEnc := subrange_vec_dec v__0 25 21 in let offset : bits 8 := subrange_vec_dec v__0 10 3 in let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 20 16 in Some (CLoad (rd, cb, rt, offset, true, W)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"110010" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 2 0) ('b"011" : mword (2 - 0 + 1))) then let rt : IntRegEnc := subrange_vec_dec v__0 15 11 in let rd : IntRegEnc := subrange_vec_dec v__0 25 21 in let offset : bits 8 := subrange_vec_dec v__0 10 3 in let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 20 16 in Some (CLoad (rd, cb, rt, offset, false, D)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001010000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00000001000" : mword (10 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 15 11 in Some (CLoadLinked (rd, cb, false, B)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001010000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00000001100" : mword (10 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 15 11 in Some (CLoadLinked (rd, cb, true, B)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001010000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00000001001" : mword (10 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 15 11 in Some (CLoadLinked (rd, cb, false, H)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001010000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00000001101" : mword (10 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 15 11 in Some (CLoadLinked (rd, cb, true, H)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001010000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00000001010" : mword (10 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 15 11 in Some (CLoadLinked (rd, cb, false, W)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001010000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00000001110" : mword (10 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 15 11 in Some (CLoadLinked (rd, cb, true, W)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001010000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00000001011" : mword (10 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 15 11 in Some (CLoadLinked (rd, cb, false, D)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"111010" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 2 0) ('b"000" : mword (2 - 0 + 1))) then let rt : IntRegEnc := subrange_vec_dec v__0 15 11 in let rs : IntRegEnc := subrange_vec_dec v__0 25 21 in let offset : bits 8 := subrange_vec_dec v__0 10 3 in let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 20 16 in Some (CStore (rs, cb, rt, offset, B)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"111010" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 2 0) ('b"001" : mword (2 - 0 + 1))) then let rt : IntRegEnc := subrange_vec_dec v__0 15 11 in let rs : IntRegEnc := subrange_vec_dec v__0 25 21 in let offset : bits 8 := subrange_vec_dec v__0 10 3 in let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 20 16 in Some (CStore (rs, cb, rt, offset, H)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"111010" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 2 0) ('b"010" : mword (2 - 0 + 1))) then let rt : IntRegEnc := subrange_vec_dec v__0 15 11 in let rs : IntRegEnc := subrange_vec_dec v__0 25 21 in let offset : bits 8 := subrange_vec_dec v__0 10 3 in let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 20 16 in Some (CStore (rs, cb, rt, offset, W)) else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b"111010" : mword (31 - 26 + 1))) (eq_vec (subrange_vec_dec v__0 2 0) ('b"011" : mword (2 - 0 + 1))) then let rt : IntRegEnc := subrange_vec_dec v__0 15 11 in let rs : IntRegEnc := subrange_vec_dec v__0 25 21 in let offset : bits 8 := subrange_vec_dec v__0 10 3 in let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 20 16 in Some (CStore (rs, cb, rt, offset, D)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001010000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"000000" : mword (5 - 0 + 1))) then let rs : IntRegEnc := subrange_vec_dec v__0 20 16 in let rd : IntRegEnc := subrange_vec_dec v__0 10 6 in let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 15 11 in Some (CStoreConditional (rs, cb, rd, B)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001010000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"000001" : mword (5 - 0 + 1))) then let rs : IntRegEnc := subrange_vec_dec v__0 20 16 in let rd : IntRegEnc := subrange_vec_dec v__0 10 6 in let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 15 11 in Some (CStoreConditional (rs, cb, rd, H)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001010000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"000010" : mword (5 - 0 + 1))) then let rs : IntRegEnc := subrange_vec_dec v__0 20 16 in let rd : IntRegEnc := subrange_vec_dec v__0 10 6 in let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 15 11 in Some (CStoreConditional (rs, cb, rd, W)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001010000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"000011" : mword (5 - 0 + 1))) then let rs : IntRegEnc := subrange_vec_dec v__0 20 16 in let rd : IntRegEnc := subrange_vec_dec v__0 10 6 in let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 15 11 in Some (CStoreConditional (rs, cb, rd, D)) else if eq_vec (subrange_vec_dec v__0 31 26) ('b"111110" : mword (31 - 26 + 1)) then let rt : IntRegEnc := subrange_vec_dec v__0 15 11 in let offset : bits 11 := subrange_vec_dec v__0 10 0 in let cs : CapRegEnc := subrange_vec_dec v__0 25 21 in let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 20 16 in Some (CSC (cs, cb, rt, offset)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001010000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 5 0) ('b"000111" : mword (5 - 0 + 1))) then let rd : IntRegEnc := subrange_vec_dec v__0 10 6 in let cs : CapRegEnc := subrange_vec_dec v__0 20 16 in let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 15 11 in Some (CSCC (cs, cb, rd)) else if eq_vec (subrange_vec_dec v__0 31 26) ('b"110110" : mword (31 - 26 + 1)) then let rt : IntRegEnc := subrange_vec_dec v__0 15 11 in let offset : bits 11 := subrange_vec_dec v__0 10 0 in let cd : CapRegEnc := subrange_vec_dec v__0 25 21 in let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 20 16 in Some (CLC (cd, cb, rt, offset)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001010000" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 10 0) ('b"00000001111" : mword (10 - 0 + 1))) then let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 15 11 in Some (CLLC (cd, cb)) else if eq_vec (subrange_vec_dec v__0 31 26) ('b"011101" : mword (31 - 26 + 1)) then let offset : bits 16 := subrange_vec_dec v__0 15 0 in let cd : CapRegEnc := subrange_vec_dec v__0 25 21 in let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 20 16 in Some (CLCBI (cd, cb, offset)) else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b"01001000100" : mword (31 - 21 + 1))) (eq_vec (subrange_vec_dec v__0 15 0) (Ox"0006" : mword (15 - 0 + 1))) then let rt : IntRegEnc := subrange_vec_dec v__0 20 16 in Some (C2Dump rt) else Some (RI tt). Definition execute_XORI (rs : mword 5) (rt : mword 5) (imm : mword 16) : M (unit) := (rGPR rs) >>= fun w__0 : mword 64 => (wGPR rt (xor_vec w__0 (mips_zero_extend 64 imm))) : M (unit). Definition execute_XOR (rs : mword 5) (rt : mword 5) (rd : mword 5) : M (unit) := (rGPR rs) >>= fun w__0 : mword 64 => (rGPR rt) >>= fun w__1 : mword 64 => (wGPR rd (xor_vec w__0 w__1)) : M (unit). Definition execute_WAIT '(tt : unit) : M (unit) := ((read_reg InBranchDelay_ref) : M (mword 1)) >>= fun w__0 : mword 1 => (if (bits_to_bool w__0) : bool then (SignalException ResI) : M (unit) else returnm tt) >> ((read_reg PC_ref) : M (mword 64)) >>= fun w__1 : mword 64 => write_reg NextPC_ref w__1 : M (unit). Definition execute_TRAPREG (rs : mword 5) (rt : mword 5) (cmp : Comparison) : M (unit) := (rGPR rs) >>= fun rs_val => (rGPR rt) >>= fun rt_val => let condition := compare cmp rs_val rt_val in (if sumbool_of_bool condition then (SignalException Tr) : M (unit) else returnm tt) : M (unit). Definition execute_TRAPIMM (rs : mword 5) (imm : mword 16) (cmp : Comparison) : M (unit) := (rGPR rs) >>= fun rs_val => let imm_val : bits 64 := mips_sign_extend 64 imm in let condition := compare cmp rs_val imm_val in (if sumbool_of_bool condition then (SignalException Tr) : M (unit) else returnm tt) : M (unit). Definition execute_TLBWR '(tt : unit) : M (unit) := (checkCP0Access tt) >> ((read_reg TLBRandom_ref) : M (mword 6)) >>= fun w__0 : mword 6 => (TLBWriteEntry w__0) : M (unit). Definition execute_TLBWI '(tt : unit) : M (unit) := (checkCP0Access tt) >> ((read_reg TLBIndex_ref) : M (mword 6)) >>= fun w__0 : mword 6 => (TLBWriteEntry w__0) : M (unit). Definition execute_TLBR '(tt : unit) : M (unit) := (checkCP0Access tt) >> ((read_reg TLBIndex_ref) : M (mword 6)) >>= fun w__0 : mword 6 => let i := projT1 (uint w__0) in (reg_deref (vec_access_dec TLBEntries i)) >>= fun entry => write_reg TLBPageMask_ref (_get_TLBEntry_pagemask entry) >> (_set_TLBEntryHiReg_R TLBEntryHi_ref (_get_TLBEntry_r entry)) >> (_set_TLBEntryHiReg_CLGK TLBEntryHi_ref ((cast_unit_vec B0) : mword 1)) >> (_set_TLBEntryHiReg_CLGS TLBEntryHi_ref ((cast_unit_vec B0) : mword 1)) >> (_set_TLBEntryHiReg_CLGU TLBEntryHi_ref ((cast_unit_vec B0) : mword 1)) >> (_set_TLBEntryHiReg_VPN2 TLBEntryHi_ref (_get_TLBEntry_vpn2 entry)) >> (_set_TLBEntryHiReg_ASID TLBEntryHi_ref (_get_TLBEntry_asid entry)) >> (_set_TLBEntryLoReg_CapS TLBEntryLo0_ref (_get_TLBEntry_caps0 entry)) >> (_set_TLBEntryLoReg_CapL TLBEntryLo0_ref (_get_TLBEntry_capl0 entry)) >> (_set_TLBEntryLoReg_CapLG TLBEntryLo0_ref (_get_TLBEntry_caplg0 entry)) >> (_set_TLBEntryLoReg_PFN TLBEntryLo0_ref (_get_TLBEntry_pfn0 entry)) >> (_set_TLBEntryLoReg_C TLBEntryLo0_ref (_get_TLBEntry_c0 entry)) >> (_set_TLBEntryLoReg_D TLBEntryLo0_ref (_get_TLBEntry_d0 entry)) >> (_set_TLBEntryLoReg_V TLBEntryLo0_ref (_get_TLBEntry_v0 entry)) >> (_set_TLBEntryLoReg_G TLBEntryLo0_ref (_get_TLBEntry_g entry)) >> (_set_TLBEntryLoReg_CapS TLBEntryLo1_ref (_get_TLBEntry_caps1 entry)) >> (_set_TLBEntryLoReg_CapL TLBEntryLo1_ref (_get_TLBEntry_capl1 entry)) >> (_set_TLBEntryLoReg_CapLG TLBEntryLo1_ref (_get_TLBEntry_caplg1 entry)) >> (_set_TLBEntryLoReg_PFN TLBEntryLo1_ref (_get_TLBEntry_pfn1 entry)) >> (_set_TLBEntryLoReg_C TLBEntryLo1_ref (_get_TLBEntry_c1 entry)) >> (_set_TLBEntryLoReg_D TLBEntryLo1_ref (_get_TLBEntry_d1 entry)) >> (_set_TLBEntryLoReg_V TLBEntryLo1_ref (_get_TLBEntry_v1 entry)) >> (_set_TLBEntryLoReg_G TLBEntryLo1_ref (_get_TLBEntry_g entry)) : M (unit). Definition execute_TLBP '(tt : unit) : M (unit) := (checkCP0Access tt) >> read_reg TLBEntryHi_ref >>= fun w__0 : TLBEntryHiReg => (tlbSearch (_get_TLBEntryHiReg_bits w__0)) >>= fun result => (match result with | Some idx => write_reg TLBProbe_ref ('b"0" : mword 1) >> write_reg TLBIndex_ref idx : M (unit) | None => write_reg TLBProbe_ref ('b"1" : mword 1) >> write_reg TLBIndex_ref ('b"000000" : mword 6) : M (unit) end) : M (unit). Definition execute_Store (width : WordType) (conditional : bool) (base : mword 5) (rt : mword 5) (offset : mword 16) : M (unit) := (rGPR base) >>= fun w__0 : mword 64 => (addrWrapper (add_vec (mips_sign_extend 64 offset) w__0) StoreData width) >>= fun vAddr : bits 64 => (rGPR rt) >>= fun rt_val => (if negb (isAddressAligned vAddr width) then (SignalExceptionBadAddr AdES vAddr) : M (unit) else (TLBTranslate vAddr StoreData) >>= fun pAddr => if sumbool_of_bool conditional then (and_boolM (((read_reg CP0LLBit_ref) : M (mword 1)) >>= fun w__1 : mword 1 => returnm ((bit_to_bool (access_vec_dec w__1 0)) : bool)) (((read_reg CP0LLAddr_ref) : M (mword 64)) >>= fun w__2 : mword 64 => returnm ((eq_vec w__2 pAddr) : bool))) >>= fun w__3 : bool => (if sumbool_of_bool w__3 then (match width with | W => (MEMw_conditional_wrapper pAddr 4 (subrange_vec_dec rt_val 31 0)) : M (bool) | D => (MEMw_conditional_wrapper pAddr 8 rt_val) : M (bool) | _ => throw (Error_internal_error tt) end) : M (bool) else returnm false) >>= fun success : bool => (wGPR rt (mips_zero_extend 64 (bool_to_bits success))) : M (unit) else (match width with | B => (MEMw_wrapper pAddr 1 (subrange_vec_dec rt_val 7 0)) : M (unit) | H => (MEMw_wrapper pAddr 2 (subrange_vec_dec rt_val 15 0)) : M (unit) | W => (MEMw_wrapper pAddr 4 (subrange_vec_dec rt_val 31 0)) : M (unit) | D => (MEMw_wrapper pAddr 8 rt_val) : M (unit) end) : M (unit)) : M (unit). Definition execute_SYSCALL '(tt : unit) : M (unit) := (SignalException Sys) : M (unit). Definition execute_SYNC '(tt : unit) : M (unit) := (MEM_sync tt) : M (unit). Definition execute_SWR (base : mword 5) (rt : mword 5) (offset : mword 16) : M (unit) := (rGPR base) >>= fun w__0 : mword 64 => (addrWrapperUnaligned (add_vec (mips_sign_extend 64 offset) w__0) StoreData WR) >>= fun '(vAddr, size) => (TLBTranslate vAddr StoreData) >>= fun pAddr => (rGPR rt) >>= fun reg_val => let l__12 := size in (if sumbool_of_bool (Z.eqb l__12 1) then (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 7 0)))) : M (unit) else if sumbool_of_bool (Z.eqb l__12 2) then (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 15 0)))) : M (unit) else if sumbool_of_bool (Z.eqb l__12 3) then (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 23 0)))) : M (unit) else if sumbool_of_bool (Z.eqb l__12 4) then (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 31 0)))) : M (unit) else assert_exp' false "../mips/mips_insts.sail 1404:26 - 1404:27" >>= fun _ => exit tt) : M (unit). Definition execute_SWL (base : mword 5) (rt : mword 5) (offset : mword 16) : M (unit) := (rGPR base) >>= fun w__0 : mword 64 => (addrWrapperUnaligned (add_vec (mips_sign_extend 64 offset) w__0) StoreData WL) >>= fun '(vAddr, size) => (TLBTranslate vAddr StoreData) >>= fun pAddr => (rGPR rt) >>= fun reg_val => let l__8 := size in (if sumbool_of_bool (Z.eqb l__8 4) then (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 31 0)))) : M (unit) else if sumbool_of_bool (Z.eqb l__8 3) then (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 31 8)))) : M (unit) else if sumbool_of_bool (Z.eqb l__8 2) then (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 31 16)))) : M (unit) else if sumbool_of_bool (Z.eqb l__8 1) then (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 31 24)))) : M (unit) else assert_exp' false "../mips/mips_insts.sail 1383:24 - 1383:25" >>= fun _ => exit tt) : M (unit). Definition execute_SUBU (rs : mword 5) (rt : mword 5) (rd : mword 5) : M (unit) := (rGPR rs) >>= fun opA => (rGPR rt) >>= fun opB => (if orb (NotWordVal opA) (NotWordVal opB) then (undefined_bitvector 64) >>= fun w__0 : mword 64 => (wGPR rd w__0) : M (unit) else (wGPR rd (mips_sign_extend 64 (sub_vec (subrange_vec_dec opA 31 0) (subrange_vec_dec opB 31 0)))) : M (unit)) : M (unit). Definition execute_SUB (rs : mword 5) (rt : mword 5) (rd : mword 5) : M (unit) := (rGPR rs) >>= fun opA => (rGPR rt) >>= fun opB => (if orb (NotWordVal opA) (NotWordVal opB) then (undefined_bitvector 64) >>= fun w__0 : mword 64 => (wGPR rd w__0) : M (unit) else let temp33 : bits 33 := sub_vec (mips_sign_extend 33 (subrange_vec_dec opA 31 0)) (mips_sign_extend 33 (subrange_vec_dec opB 31 0)) in (if neq_bool (bit_to_bool (access_vec_dec temp33 32)) (bit_to_bool (access_vec_dec temp33 31)) then (SignalException Ov) : M (unit) else (wGPR rd (mips_sign_extend 64 (subrange_vec_dec temp33 31 0))) : M (unit)) : M (unit)) : M (unit). Definition execute_SRLV (rs : mword 5) (rt : mword 5) (rd : mword 5) : M (unit) := (rGPR rt) >>= fun temp => (rGPR rs) >>= fun w__0 : mword 64 => let sa := subrange_vec_dec w__0 4 0 in (if NotWordVal temp then (undefined_bitvector 64) >>= fun w__1 : mword 64 => (wGPR rd w__1) : M (unit) else let rt32 := subrange_vec_dec temp 31 0 in (shift_bits_right rt32 sa) >>= fun w__2 : mword (31 - 0 + 1) => (wGPR rd (mips_sign_extend 64 w__2)) : M (unit)) : M (unit). Definition execute_SRL (rt : mword 5) (rd : mword 5) (sa : mword 5) : M (unit) := (rGPR rt) >>= fun temp => (if NotWordVal temp then (undefined_bitvector 64) >>= fun w__0 : mword 64 => (wGPR rd w__0) : M (unit) else let rt32 := subrange_vec_dec temp 31 0 in (shift_bits_right rt32 sa) >>= fun w__1 : mword (31 - 0 + 1) => (wGPR rd (mips_sign_extend 64 w__1)) : M (unit)) : M (unit). Definition execute_SRAV (rs : mword 5) (rt : mword 5) (rd : mword 5) : M (unit) := (rGPR rt) >>= fun temp => (rGPR rs) >>= fun w__0 : mword 64 => let sa := subrange_vec_dec w__0 4 0 in (if NotWordVal temp then (undefined_bitvector 64) >>= fun w__1 : mword 64 => (wGPR rd w__1) : M (unit) else let rt32 := subrange_vec_dec temp 31 0 in (shift_bits_right_arith rt32 sa) >>= fun w__2 : mword (31 - 0 + 1) => (wGPR rd (mips_sign_extend 64 w__2)) : M (unit)) : M (unit). Definition execute_SRA (rt : mword 5) (rd : mword 5) (sa : mword 5) : M (unit) := (rGPR rt) >>= fun temp => (if NotWordVal temp then (undefined_bitvector 64) >>= fun w__0 : mword 64 => (wGPR rd w__0) : M (unit) else let rt32 := subrange_vec_dec temp 31 0 in (shift_bits_right_arith rt32 sa) >>= fun w__1 : mword (31 - 0 + 1) => (wGPR rd (mips_sign_extend 64 w__1)) : M (unit)) : M (unit). Definition execute_SLTU (rs : mword 5) (rt : mword 5) (rd : mword 5) : M (unit) := (rGPR rs) >>= fun rs_val => (rGPR rt) >>= fun rt_val => (wGPR rd (mips_zero_extend 64 (if zopz0zI_u rs_val rt_val then 'b"1" : mword 1 else 'b"0" : mword 1))) : M (unit). Definition execute_SLTIU (rs : mword 5) (rt : mword 5) (imm : mword 16) : M (unit) := (rGPR rs) >>= fun rs_val => let immext : bits 64 := mips_sign_extend 64 imm in (wGPR rt (mips_zero_extend 64 (if zopz0zI_u rs_val immext then 'b"1" : mword 1 else 'b"0" : mword 1))) : M (unit). Definition execute_SLTI (rs : mword 5) (rt : mword 5) (imm : mword 16) : M (unit) := let imm_val := projT1 (sint imm) in (rGPR rs) >>= fun w__0 : mword 64 => let rs_val := projT1 (sint w__0) in (wGPR rt (mips_zero_extend 64 (if sumbool_of_bool (Z.ltb rs_val imm_val) then 'b"1" : mword 1 else 'b"0" : mword 1))) : M (unit). Definition execute_SLT (rs : mword 5) (rt : mword 5) (rd : mword 5) : M (unit) := (rGPR rs) >>= fun w__0 : mword 64 => (rGPR rt) >>= fun w__1 : mword 64 => (wGPR rd (mips_zero_extend 64 (if zopz0zI_s w__0 w__1 then 'b"1" : mword 1 else 'b"0" : mword 1))) : M (unit). Definition execute_SLLV (rs : mword 5) (rt : mword 5) (rd : mword 5) : M (unit) := (rGPR rs) >>= fun w__0 : mword 64 => let sa := subrange_vec_dec w__0 4 0 in (rGPR rt) >>= fun w__1 : mword 64 => let rt32 := subrange_vec_dec w__1 31 0 in (shift_bits_left rt32 sa) >>= fun w__2 : mword (31 - 0 + 1) => (wGPR rd (mips_sign_extend 64 w__2)) : M (unit). Definition execute_SLL (rt : mword 5) (rd : mword 5) (sa : mword 5) : M (unit) := (rGPR rt) >>= fun w__0 : mword 64 => let rt32 := subrange_vec_dec w__0 31 0 in (shift_bits_left rt32 sa) >>= fun w__1 : mword (31 - 0 + 1) => (wGPR rd (mips_sign_extend 64 w__1)) : M (unit). Definition execute_SDR (base : mword 5) (rt : mword 5) (offset : mword 16) : M (unit) := (rGPR base) >>= fun w__0 : mword 64 => (addrWrapperUnaligned (add_vec (mips_sign_extend 64 offset) w__0) StoreData DR) >>= fun '(vAddr, size) => (TLBTranslate vAddr StoreData) >>= fun pAddr => (rGPR rt) >>= fun reg_val => let l__40 := size in (if sumbool_of_bool (Z.eqb l__40 1) then (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 7 0)))) : M (unit) else if sumbool_of_bool (Z.eqb l__40 2) then (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 15 0)))) : M (unit) else if sumbool_of_bool (Z.eqb l__40 3) then (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 23 0)))) : M (unit) else if sumbool_of_bool (Z.eqb l__40 4) then (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 31 0)))) : M (unit) else if sumbool_of_bool (Z.eqb l__40 5) then (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 39 0)))) : M (unit) else if sumbool_of_bool (Z.eqb l__40 6) then (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 47 0)))) : M (unit) else if sumbool_of_bool (Z.eqb l__40 7) then (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 55 0)))) : M (unit) else if sumbool_of_bool (Z.eqb l__40 8) then (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 63 0)))) : M (unit) else assert_exp' false "../mips/mips_insts.sail 1509:24 - 1509:25" >>= fun _ => exit tt) : M (unit). Definition execute_SDL (base : mword 5) (rt : mword 5) (offset : mword 16) : M (unit) := (rGPR base) >>= fun w__0 : mword 64 => (addrWrapperUnaligned (add_vec (mips_sign_extend 64 offset) w__0) StoreData DL) >>= fun '(vAddr, size) => (TLBTranslate vAddr StoreData) >>= fun pAddr => (rGPR rt) >>= fun reg_val => let l__32 := size in (if sumbool_of_bool (Z.eqb l__32 8) then (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 63 0)))) : M (unit) else if sumbool_of_bool (Z.eqb l__32 7) then (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 63 8)))) : M (unit) else if sumbool_of_bool (Z.eqb l__32 6) then (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 63 16)))) : M (unit) else if sumbool_of_bool (Z.eqb l__32 5) then (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 63 24)))) : M (unit) else if sumbool_of_bool (Z.eqb l__32 4) then (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 63 32)))) : M (unit) else if sumbool_of_bool (Z.eqb l__32 3) then (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 63 40)))) : M (unit) else if sumbool_of_bool (Z.eqb l__32 2) then (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 63 48)))) : M (unit) else if sumbool_of_bool (Z.eqb l__32 1) then (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 63 56)))) : M (unit) else assert_exp' false "../mips/mips_insts.sail 1482:24 - 1482:25" >>= fun _ => exit tt) : M (unit). Definition execute_RI '(tt : unit) : M (unit) := (skip tt) >> (SignalException ResI) : M (unit). Definition execute_RDHWR (rt : mword 5) (rd : mword 5) : M (unit) := (getAccessLevel tt) >>= fun accessLevel => let haveAccessLevel : bool := generic_eq accessLevel Kernel in read_reg CP0Status_ref >>= fun w__0 : StatusReg => let haveCU0 : bool := eq_bit B1 (access_vec_dec (_get_StatusReg_CU w__0) 0) in let rdi := projT1 (uint rd) in ((read_reg CP0HWREna_ref) : M (mword 32)) >>= fun w__1 : mword 32 => let haveHWREna : bool := eq_bit B1 (access_vec_dec w__1 rdi) in (if sumbool_of_bool (negb (orb haveAccessLevel (orb haveCU0 haveHWREna))) then (SignalException ResI) : M (unit) else returnm tt) >> let b__102 := rd in (if eq_vec b__102 ('b"00000" : mword 5) then returnm (mips_zero_extend 64 ('b"0" : mword 1)) else if eq_vec b__102 ('b"00001" : mword 5) then returnm (mips_zero_extend 64 ('b"0" : mword 1)) else if eq_vec b__102 ('b"00010" : mword 5) then ((read_reg CP0Count_ref) : M (mword 32)) >>= fun w__2 : mword 32 => returnm (mips_zero_extend 64 w__2) else if eq_vec b__102 ('b"00011" : mword 5) then returnm (mips_zero_extend 64 ('b"1" : mword 1)) else if eq_vec b__102 ('b"11101" : mword 5) then ((read_reg CP0UserLocal_ref) : M (mword 64)) : M (mword 64) else (SignalException ResI) : M (mword 64)) >>= fun temp : bits 64 => (wGPR rt temp) : M (unit). Definition execute_ORI (rs : mword 5) (rt : mword 5) (imm : mword 16) : M (unit) := (rGPR rs) >>= fun w__0 : mword 64 => (wGPR rt (or_vec w__0 (mips_zero_extend 64 imm))) : M (unit). Definition execute_OR (rs : mword 5) (rt : mword 5) (rd : mword 5) : M (unit) := (rGPR rs) >>= fun w__0 : mword 64 => (rGPR rt) >>= fun w__1 : mword 64 => (wGPR rd (or_vec w__0 w__1)) : M (unit). Definition execute_NOR (rs : mword 5) (rt : mword 5) (rd : mword 5) : M (unit) := (rGPR rs) >>= fun w__0 : mword 64 => (rGPR rt) >>= fun w__1 : mword 64 => (wGPR rd (not_vec (or_vec w__0 w__1))) : M (unit). Definition execute_MULTU (rs : mword 5) (rt : mword 5) : M (unit) := (rGPR rs) >>= fun rsVal => (rGPR rt) >>= fun rtVal => (if orb (NotWordVal rsVal) (NotWordVal rtVal) then (undefined_bitvector 64) : M (mword 64) else returnm (mult_vec (subrange_vec_dec rsVal 31 0) (subrange_vec_dec rtVal 31 0))) >>= fun result : bits 64 => write_reg HI_ref (mips_sign_extend 64 (subrange_vec_dec result 63 32)) >> write_reg LO_ref (mips_sign_extend 64 (subrange_vec_dec result 31 0)) : M (unit). Definition execute_MULT (rs : mword 5) (rt : mword 5) : M (unit) := (rGPR rs) >>= fun rsVal => (rGPR rt) >>= fun rtVal => (if orb (NotWordVal rsVal) (NotWordVal rtVal) then (undefined_bitvector 64) : M (mword 64) else returnm (mults_vec (subrange_vec_dec rsVal 31 0) (subrange_vec_dec rtVal 31 0))) >>= fun result : bits 64 => write_reg HI_ref (mips_sign_extend 64 (subrange_vec_dec result 63 32)) >> write_reg LO_ref (mips_sign_extend 64 (subrange_vec_dec result 31 0)) : M (unit). Definition execute_MUL (rs : mword 5) (rt : mword 5) (rd : mword 5) : M (unit) := (rGPR rs) >>= fun rsVal => (rGPR rt) >>= fun rtVal => let result : bits 64 := mips_sign_extend 64 (mults_vec (subrange_vec_dec rsVal 31 0) (subrange_vec_dec rtVal 31 0)) in (if orb (NotWordVal rsVal) (NotWordVal rtVal) then (undefined_bitvector 64) : M (mword 64) else returnm (mips_sign_extend 64 (subrange_vec_dec result 31 0))) >>= fun w__1 : mword 64 => (wGPR rd w__1) : M (unit). Definition execute_MTLO (rs : mword 5) : M (unit) := (rGPR rs) >>= fun w__0 : mword 64 => write_reg LO_ref w__0 : M (unit). Definition execute_MTHI (rs : mword 5) : M (unit) := (rGPR rs) >>= fun w__0 : mword 64 => write_reg HI_ref w__0 : M (unit). Definition execute_MTC0 (rt : mword 5) (rd : mword 5) (sel : mword 3) (double : bool) : M (unit) := (checkCP0Access tt) >> (rGPR rt) >>= fun reg_val => (match (rd, sel) with | (b__64, b__65) => (if andb (eq_vec b__64 ('b"00000" : mword 5)) (eq_vec b__65 ('b"000" : mword 3)) then write_reg TLBIndex_ref (mask 6 reg_val) : M (unit) else if andb (eq_vec b__64 ('b"00001" : mword 5)) (eq_vec b__65 ('b"000" : mword 3)) then returnm tt else if andb (eq_vec b__64 ('b"00010" : mword 5)) (eq_vec b__65 ('b"000" : mword 3)) then (_set_TLBEntryLoReg_bits TLBEntryLo0_ref reg_val) : M (unit) else if andb (eq_vec b__64 ('b"00011" : mword 5)) (eq_vec b__65 ('b"000" : mword 3)) then (_set_TLBEntryLoReg_bits TLBEntryLo1_ref reg_val) : M (unit) else if andb (eq_vec b__64 ('b"00100" : mword 5)) (eq_vec b__65 ('b"000" : mword 3)) then (_set_ContextReg_PTEBase TLBContext_ref (subrange_vec_dec reg_val 63 23)) : M (unit) else if andb (eq_vec b__64 ('b"00100" : mword 5)) (eq_vec b__65 ('b"010" : mword 3)) then write_reg CP0UserLocal_ref reg_val : M (unit) else if andb (eq_vec b__64 ('b"00101" : mword 5)) (eq_vec b__65 ('b"000" : mword 3)) then write_reg TLBPageMask_ref (subrange_vec_dec reg_val 28 13) : M (unit) else if andb (eq_vec b__64 ('b"00110" : mword 5)) (eq_vec b__65 ('b"000" : mword 3)) then write_reg TLBWired_ref (mask 6 reg_val) >> write_reg TLBRandom_ref TLBIndexMax : M (unit) else if andb (eq_vec b__64 ('b"00111" : mword 5)) (eq_vec b__65 ('b"000" : mword 3)) then write_reg CP0HWREna_ref (concat_vec (subrange_vec_dec reg_val 31 29) (concat_vec ('b"0000000000000000000000000" : mword 25) (subrange_vec_dec reg_val 3 0))) : M (unit) else if andb (eq_vec b__64 ('b"01000" : mword 5)) (eq_vec b__65 ('b"000" : mword 3)) then returnm tt else if andb (eq_vec b__64 ('b"01001" : mword 5)) (eq_vec b__65 ('b"000" : mword 3)) then write_reg CP0Count_ref (subrange_vec_dec reg_val 31 0) : M (unit) else if andb (eq_vec b__64 ('b"01010" : mword 5)) (eq_vec b__65 ('b"000" : mword 3)) then (_set_TLBEntryHiReg_R TLBEntryHi_ref (subrange_vec_dec reg_val 63 62)) >> (_set_TLBEntryHiReg_CLGK TLBEntryHi_ref ((cast_unit_vec (access_vec_dec reg_val 61)) : mword 1)) >> (_set_TLBEntryHiReg_CLGS TLBEntryHi_ref ((cast_unit_vec (access_vec_dec reg_val 60)) : mword 1)) >> (_set_TLBEntryHiReg_CLGU TLBEntryHi_ref ((cast_unit_vec (access_vec_dec reg_val 59)) : mword 1)) >> (_set_TLBEntryHiReg_VPN2 TLBEntryHi_ref (subrange_vec_dec reg_val 39 13)) >> (_set_TLBEntryHiReg_ASID TLBEntryHi_ref (subrange_vec_dec reg_val 7 0)) : M (unit) else if andb (eq_vec b__64 ('b"01011" : mword 5)) (eq_vec b__65 ('b"000" : mword 3)) then write_reg CP0Compare_ref (subrange_vec_dec reg_val 31 0) >> read_reg CP0Cause_ref >>= fun w__0 : CauseReg => (_set_CauseReg_IP CP0Cause_ref (and_vec (_get_CauseReg_IP w__0) (Ox"7F" : mword 8))) : M (unit) else if andb (eq_vec b__64 ('b"01100" : mword 5)) (eq_vec b__65 ('b"000" : mword 3)) then (_set_StatusReg_CU CP0Status_ref (and_vec (subrange_vec_dec reg_val 31 28) (concat_vec ('b"0" : mword 1) (concat_vec (bool_to_bits have_cp2) ('b"01" : mword 2))))) >> (_set_StatusReg_BEV CP0Status_ref ((cast_unit_vec (access_vec_dec reg_val 22)) : mword 1)) >> (_set_StatusReg_IM CP0Status_ref (subrange_vec_dec reg_val 15 8)) >> (_set_StatusReg_KX CP0Status_ref ((cast_unit_vec (access_vec_dec reg_val 7)) : mword 1)) >> (_set_StatusReg_SX CP0Status_ref ((cast_unit_vec (access_vec_dec reg_val 6)) : mword 1)) >> (_set_StatusReg_UX CP0Status_ref ((cast_unit_vec (access_vec_dec reg_val 5)) : mword 1)) >> (_set_StatusReg_KSU CP0Status_ref (subrange_vec_dec reg_val 4 3)) >> (_set_StatusReg_ERL CP0Status_ref ((cast_unit_vec (access_vec_dec reg_val 2)) : mword 1)) >> (_set_StatusReg_EXL CP0Status_ref ((cast_unit_vec (access_vec_dec reg_val 1)) : mword 1)) >> (_set_StatusReg_IE CP0Status_ref ((cast_unit_vec (access_vec_dec reg_val 0)) : mword 1)) : M (unit) else if andb (eq_vec b__64 ('b"01101" : mword 5)) (eq_vec b__65 ('b"000" : mword 3)) then (_set_CauseReg_IV CP0Cause_ref ((cast_unit_vec (access_vec_dec reg_val 23)) : mword 1)) >> read_reg CP0Cause_ref >>= fun w__1 : CauseReg => let ip := _get_CauseReg_IP w__1 in (_set_CauseReg_IP CP0Cause_ref (concat_vec (subrange_vec_dec ip 7 2) (subrange_vec_dec reg_val 9 8))) : M (unit) else if andb (eq_vec b__64 ('b"01110" : mword 5)) (eq_vec b__65 ('b"000" : mword 3)) then (set_CP0EPC reg_val) : M (unit) else if andb (eq_vec b__64 ('b"10000" : mword 5)) (eq_vec b__65 ('b"000" : mword 3)) then write_reg CP0ConfigK0_ref (subrange_vec_dec reg_val 2 0) : M (unit) else if andb (eq_vec b__64 ('b"10100" : mword 5)) (eq_vec b__65 ('b"000" : mword 3)) then (_set_XContextReg_XPTEBase TLBXContext_ref (subrange_vec_dec reg_val 63 33)) : M (unit) else if andb (eq_vec b__64 ('b"11110" : mword 5)) (eq_vec b__65 ('b"000" : mword 3)) then (set_CP0ErrorEPC reg_val) : M (unit) else (SignalException ResI) : M (unit)) : M (unit) end) : M (unit). Definition execute_MSUBU (rs : mword 5) (rt : mword 5) : M (unit) := (rGPR rs) >>= fun rsVal => (rGPR rt) >>= fun rtVal => (if orb (NotWordVal rsVal) (NotWordVal rtVal) then (undefined_bitvector 64) : M (mword 64) else returnm (mult_vec (subrange_vec_dec rsVal 31 0) (subrange_vec_dec rtVal 31 0))) >>= fun mul_result : bits 64 => ((read_reg HI_ref) : M (mword 64)) >>= fun w__1 : mword 64 => ((read_reg LO_ref) : M (mword 64)) >>= fun w__2 : mword 64 => let result := sub_vec (concat_vec (subrange_vec_dec w__1 31 0) (subrange_vec_dec w__2 31 0)) mul_result in write_reg HI_ref (mips_sign_extend 64 (subrange_vec_dec result 63 32)) >> write_reg LO_ref (mips_sign_extend 64 (subrange_vec_dec result 31 0)) : M (unit). Definition execute_MSUB (rs : mword 5) (rt : mword 5) : M (unit) := (rGPR rs) >>= fun rsVal => (rGPR rt) >>= fun rtVal => (if orb (NotWordVal rsVal) (NotWordVal rtVal) then (undefined_bitvector 64) : M (mword 64) else returnm (mults_vec (subrange_vec_dec rsVal 31 0) (subrange_vec_dec rtVal 31 0))) >>= fun mul_result : bits 64 => ((read_reg HI_ref) : M (mword 64)) >>= fun w__1 : mword 64 => ((read_reg LO_ref) : M (mword 64)) >>= fun w__2 : mword 64 => let result := sub_vec (concat_vec (subrange_vec_dec w__1 31 0) (subrange_vec_dec w__2 31 0)) mul_result in write_reg HI_ref (mips_sign_extend 64 (subrange_vec_dec result 63 32)) >> write_reg LO_ref (mips_sign_extend 64 (subrange_vec_dec result 31 0)) : M (unit). Definition execute_MOVZ (rs : mword 5) (rt : mword 5) (rd : mword 5) : M (unit) := (rGPR rt) >>= fun w__0 : mword 64 => (if eq_vec w__0 (Ox"0000000000000000" : mword 64) then (rGPR rs) >>= fun w__1 : mword 64 => (wGPR rd w__1) : M (unit) else returnm tt) : M (unit). Definition execute_MOVN (rs : mword 5) (rt : mword 5) (rd : mword 5) : M (unit) := (rGPR rt) >>= fun w__0 : mword 64 => (if neq_vec w__0 (Ox"0000000000000000" : mword 64) then (rGPR rs) >>= fun w__1 : mword 64 => (wGPR rd w__1) : M (unit) else returnm tt) : M (unit). Definition execute_MFLO (rd : mword 5) : M (unit) := ((read_reg LO_ref) : M (mword 64)) >>= fun w__0 : mword 64 => (wGPR rd w__0) : M (unit). Definition execute_MFHI (rd : mword 5) : M (unit) := ((read_reg HI_ref) : M (mword 64)) >>= fun w__0 : mword 64 => (wGPR rd w__0) : M (unit). Definition execute_MFC0 (rt : mword 5) (rd : mword 5) (sel : mword 3) (double : bool) : M (unit) := (checkCP0Access tt) >> (match (rd, sel) with | (b__0, b__1) => (if andb (eq_vec b__0 ('b"00000" : mword 5)) (eq_vec b__1 ('b"000" : mword 3)) then ((read_reg TLBIndex_ref) : M (mword 6)) >>= fun w__0 : mword 6 => let idx : bits 31 := mips_zero_extend 31 w__0 in ((read_reg TLBProbe_ref) : M (mword 1)) >>= fun w__1 : mword 1 => returnm (concat_vec (Ox"00000000" : mword 32) (concat_vec w__1 idx)) else if andb (eq_vec b__0 ('b"00001" : mword 5)) (eq_vec b__1 ('b"000" : mword 3)) then ((read_reg TLBRandom_ref) : M (mword 6)) >>= fun w__2 : mword 6 => returnm (mips_zero_extend 64 w__2) else if andb (eq_vec b__0 ('b"00010" : mword 5)) (eq_vec b__1 ('b"000" : mword 3)) then read_reg TLBEntryLo0_ref >>= fun w__3 : TLBEntryLoReg => returnm (_get_TLBEntryLoReg_bits w__3) else if andb (eq_vec b__0 ('b"00011" : mword 5)) (eq_vec b__1 ('b"000" : mword 3)) then read_reg TLBEntryLo1_ref >>= fun w__4 : TLBEntryLoReg => returnm (_get_TLBEntryLoReg_bits w__4) else if andb (eq_vec b__0 ('b"00100" : mword 5)) (eq_vec b__1 ('b"000" : mword 3)) then read_reg TLBContext_ref >>= fun w__5 : ContextReg => returnm (_get_ContextReg_bits w__5) else if andb (eq_vec b__0 ('b"00100" : mword 5)) (eq_vec b__1 ('b"010" : mword 3)) then ((read_reg CP0UserLocal_ref) : M (mword 64)) : M (mword 64) else if andb (eq_vec b__0 ('b"00101" : mword 5)) (eq_vec b__1 ('b"000" : mword 3)) then ((read_reg TLBPageMask_ref) : M (mword 16)) >>= fun w__7 : mword 16 => returnm (mips_zero_extend 64 (concat_vec w__7 (Ox"000" : mword 12))) else if andb (eq_vec b__0 ('b"00110" : mword 5)) (eq_vec b__1 ('b"000" : mword 3)) then ((read_reg TLBWired_ref) : M (mword 6)) >>= fun w__8 : mword 6 => returnm (mips_zero_extend 64 w__8) else if andb (eq_vec b__0 ('b"00111" : mword 5)) (eq_vec b__1 ('b"000" : mword 3)) then ((read_reg CP0HWREna_ref) : M (mword 32)) >>= fun w__9 : mword 32 => returnm (mips_zero_extend 64 w__9) else if andb (eq_vec b__0 ('b"01000" : mword 5)) (eq_vec b__1 ('b"000" : mword 3)) then ((read_reg CP0BadVAddr_ref) : M (mword 64)) : M (mword 64) else if andb (eq_vec b__0 ('b"01000" : mword 5)) (eq_vec b__1 ('b"001" : mword 3)) then ((read_reg CP0BadInstr_ref) : M (mword 32)) >>= fun w__11 : mword 32 => returnm (mips_zero_extend 64 w__11) else if andb (eq_vec b__0 ('b"01000" : mword 5)) (eq_vec b__1 ('b"010" : mword 3)) then ((read_reg CP0BadInstrP_ref) : M (mword 32)) >>= fun w__12 : mword 32 => returnm (mips_zero_extend 64 w__12) else if andb (eq_vec b__0 ('b"01001" : mword 5)) (eq_vec b__1 ('b"000" : mword 3)) then ((read_reg CP0Count_ref) : M (mword 32)) >>= fun w__13 : mword 32 => returnm (mips_zero_extend 64 w__13) else if andb (eq_vec b__0 ('b"01010" : mword 5)) (eq_vec b__1 ('b"000" : mword 3)) then read_reg TLBEntryHi_ref >>= fun w__14 : TLBEntryHiReg => returnm (_get_TLBEntryHiReg_bits w__14) else if andb (eq_vec b__0 ('b"01011" : mword 5)) (eq_vec b__1 ('b"000" : mword 3)) then ((read_reg CP0Compare_ref) : M (mword 32)) >>= fun w__15 : mword 32 => returnm (mips_zero_extend 64 w__15) else if andb (eq_vec b__0 ('b"01100" : mword 5)) (eq_vec b__1 ('b"000" : mword 3)) then read_reg CP0Status_ref >>= fun w__16 : StatusReg => returnm (mips_zero_extend 64 (_get_StatusReg_bits w__16)) else if andb (eq_vec b__0 ('b"01101" : mword 5)) (eq_vec b__1 ('b"000" : mword 3)) then read_reg CP0Cause_ref >>= fun w__17 : CauseReg => returnm (mips_zero_extend 64 (_get_CauseReg_bits w__17)) else if andb (eq_vec b__0 ('b"01110" : mword 5)) (eq_vec b__1 ('b"000" : mword 3)) then (get_CP0EPC tt) : M (mword 64) else if andb (eq_vec b__0 ('b"01111" : mword 5)) (eq_vec b__1 ('b"000" : mword 3)) then returnm (mips_zero_extend 64 (Ox"00000405" : mword 32)) else if andb (eq_vec b__0 ('b"01111" : mword 5)) (eq_vec b__1 ('b"110" : mword 3)) then returnm (mips_zero_extend 64 ('b"0" : mword 1)) else if andb (eq_vec b__0 ('b"01111" : mword 5)) (eq_vec b__1 ('b"111" : mword 3)) then returnm (mips_zero_extend 64 ('b"0" : mword 1)) else if andb (eq_vec b__0 ('b"10000" : mword 5)) (eq_vec b__1 ('b"000" : mword 3)) then ((read_reg CP0ConfigK0_ref) : M (mword 3)) >>= fun w__19 : mword 3 => returnm (mips_zero_extend 64 (concat_vec ('b"1" : mword 1) (concat_vec ('b"000000000000000" : mword 15) (concat_vec ('b"1" : mword 1) (concat_vec ('b"10" : mword 2) (concat_vec ('b"000" : mword 3) (concat_vec ('b"001" : mword 3) (concat_vec (Ox"0" : mword 4) w__19)))))))) else if andb (eq_vec b__0 ('b"10000" : mword 5)) (eq_vec b__1 ('b"001" : mword 3)) then returnm (mips_zero_extend 64 (concat_vec ('b"1" : mword 1) (concat_vec TLBIndexMax (concat_vec ('b"000" : mword 3) (concat_vec ('b"000" : mword 3) (concat_vec ('b"000" : mword 3) (concat_vec ('b"000" : mword 3) (concat_vec ('b"000" : mword 3) (concat_vec ('b"000" : mword 3) (concat_vec (bool_to_bits have_cp2) (concat_vec ('b"0" : mword 1) (concat_vec ('b"0" : mword 1) (concat_vec ('b"0" : mword 1) (concat_vec ('b"0" : mword 1) (concat_vec ('b"0" : mword 1) ('b"0" : mword 1)))))))))))))))) else if andb (eq_vec b__0 ('b"10000" : mword 5)) (eq_vec b__1 ('b"010" : mword 3)) then returnm (mips_zero_extend 64 (concat_vec ('b"1" : mword 1) (concat_vec ('b"000" : mword 3) (concat_vec (Ox"0" : mword 4) (concat_vec (Ox"0" : mword 4) (concat_vec (Ox"0" : mword 4) (concat_vec (Ox"0" : mword 4) (concat_vec (Ox"0" : mword 4) (concat_vec (Ox"0" : mword 4) (Ox"0" : mword 4)))))))))) else if andb (eq_vec b__0 ('b"10000" : mword 5)) (eq_vec b__1 ('b"011" : mword 3)) then returnm (Ox"000000000C002000" : mword 64) else if andb (eq_vec b__0 ('b"10000" : mword 5)) (eq_vec b__1 ('b"101" : mword 3)) then returnm (Ox"0000000000000000" : mword 64) else if andb (eq_vec b__0 ('b"10000" : mword 5)) (eq_vec b__1 ('b"110" : mword 3)) then returnm (Ox"0000000000000000" : mword 64) else if andb (eq_vec b__0 ('b"10001" : mword 5)) (eq_vec b__1 ('b"000" : mword 3)) then ((read_reg CP0LLAddr_ref) : M (mword 64)) : M (mword 64) else if andb (eq_vec b__0 ('b"10010" : mword 5)) (eq_vec b__1 ('b"000" : mword 3)) then returnm (mips_zero_extend 64 ('b"0" : mword 1)) else if andb (eq_vec b__0 ('b"10011" : mword 5)) (eq_vec b__1 ('b"000" : mword 3)) then returnm (mips_zero_extend 64 ('b"0" : mword 1)) else if andb (eq_vec b__0 ('b"10100" : mword 5)) (eq_vec b__1 ('b"000" : mword 3)) then read_reg TLBXContext_ref >>= fun w__21 : XContextReg => returnm (_get_XContextReg_bits w__21) else if andb (eq_vec b__0 ('b"11110" : mword 5)) (eq_vec b__1 ('b"000" : mword 3)) then (get_CP0ErrorEPC tt) : M (mword 64) else (SignalException ResI) : M (mword 64)) : M (mword 64) end) >>= fun result : bits 64 => (wGPR rt (if sumbool_of_bool double then result else mips_sign_extend 64 (subrange_vec_dec result 31 0))) : M (unit). Definition execute_MADDU (rs : mword 5) (rt : mword 5) : M (unit) := (rGPR rs) >>= fun rsVal => (rGPR rt) >>= fun rtVal => (if orb (NotWordVal rsVal) (NotWordVal rtVal) then (undefined_bitvector 64) : M (mword 64) else returnm (mult_vec (subrange_vec_dec rsVal 31 0) (subrange_vec_dec rtVal 31 0))) >>= fun mul_result : bits 64 => ((read_reg HI_ref) : M (mword 64)) >>= fun w__1 : mword 64 => ((read_reg LO_ref) : M (mword 64)) >>= fun w__2 : mword 64 => let result := add_vec mul_result (concat_vec (subrange_vec_dec w__1 31 0) (subrange_vec_dec w__2 31 0)) in write_reg HI_ref (mips_sign_extend 64 (subrange_vec_dec result 63 32)) >> write_reg LO_ref (mips_sign_extend 64 (subrange_vec_dec result 31 0)) : M (unit). Definition execute_MADD (rs : mword 5) (rt : mword 5) : M (unit) := (rGPR rs) >>= fun rsVal => (rGPR rt) >>= fun rtVal => (if orb (NotWordVal rsVal) (NotWordVal rtVal) then (undefined_bitvector 64) : M (mword 64) else returnm (mults_vec (subrange_vec_dec rsVal 31 0) (subrange_vec_dec rtVal 31 0))) >>= fun mul_result : bits 64 => ((read_reg HI_ref) : M (mword 64)) >>= fun w__1 : mword 64 => ((read_reg LO_ref) : M (mword 64)) >>= fun w__2 : mword 64 => let result := add_vec mul_result (concat_vec (subrange_vec_dec w__1 31 0) (subrange_vec_dec w__2 31 0)) in write_reg HI_ref (mips_sign_extend 64 (subrange_vec_dec result 63 32)) >> write_reg LO_ref (mips_sign_extend 64 (subrange_vec_dec result 31 0)) : M (unit). Definition execute_Load (width : WordType) (sign : bool) (linked : bool) (base : mword 5) (rt : mword 5) (offset : mword 16) : M (unit) := (rGPR base) >>= fun w__0 : mword 64 => (addrWrapper (add_vec (mips_sign_extend 64 offset) w__0) LoadData width) >>= fun vAddr : bits 64 => (if negb (isAddressAligned vAddr width) then (SignalExceptionBadAddr AdEL vAddr) : M (unit) else (TLBTranslate vAddr LoadData) >>= fun pAddr => (if sumbool_of_bool linked then write_reg CP0LLBit_ref ('b"1" : mword 1) >> write_reg CP0LLAddr_ref pAddr >> (match width with | W => (MEMr_reserve_wrapper pAddr 4) >>= fun w__1 : mword (8 * 4) => returnm (extendLoad w__1 sign) | D => (MEMr_reserve_wrapper pAddr 8) >>= fun w__2 : mword (8 * 8) => returnm (extendLoad w__2 sign) | _ => throw (Error_internal_error tt) end) : M (mword 64) else (match width with | B => (MEMr_wrapper pAddr 1) >>= fun w__5 : mword (8 * 1) => returnm (extendLoad w__5 sign) | H => (MEMr_wrapper pAddr 2) >>= fun w__6 : mword (8 * 2) => returnm (extendLoad w__6 sign) | W => (MEMr_wrapper pAddr 4) >>= fun w__7 : mword (8 * 4) => returnm (extendLoad w__7 sign) | D => (MEMr_wrapper pAddr 8) >>= fun w__8 : mword (8 * 8) => returnm (extendLoad w__8 sign) end) : M (mword 64)) >>= fun memResult : bits 64 => (wGPR rt memResult) : M (unit)) : M (unit). Definition execute_LWR (base : mword 5) (rt : mword 5) (offset : mword 16) : M (unit) := (rGPR base) >>= fun w__0 : mword 64 => (addrWrapperUnaligned (add_vec (mips_sign_extend 64 offset) w__0) LoadData WR) >>= fun '(vAddr, size) => (TLBTranslate vAddr LoadData) >>= fun pAddr => (rGPR rt) >>= fun reg_val => let l__4 := size in (if sumbool_of_bool (Z.eqb l__4 1) then (MEMr_wrapper pAddr size) >>= fun w__1 : mword (8 * size) => returnm (autocast (autocast (concat_vec (subrange_vec_dec reg_val 31 8) w__1))) else if sumbool_of_bool (Z.eqb l__4 2) then (MEMr_wrapper pAddr size) >>= fun w__2 : mword (8 * size) => returnm (autocast (autocast (concat_vec (subrange_vec_dec reg_val 31 16) w__2))) else if sumbool_of_bool (Z.eqb l__4 3) then (MEMr_wrapper pAddr size) >>= fun w__3 : mword (8 * size) => returnm (autocast (autocast (concat_vec (subrange_vec_dec reg_val 31 24) w__3))) else if sumbool_of_bool (Z.eqb l__4 4) then (MEMr_wrapper pAddr _) : M (mword (8 * 4)) else assert_exp' false "../mips/mips_insts.sail 1360:21 - 1360:22" >>= fun _ => exit tt) >>= fun result : bits 32 => (wGPR rt (mips_sign_extend 64 result)) : M (unit). Definition execute_LWL (base : mword 5) (rt : mword 5) (offset : mword 16) : M (unit) := (rGPR base) >>= fun w__0 : mword 64 => (addrWrapperUnaligned (add_vec (mips_sign_extend 64 offset) w__0) LoadData WL) >>= fun '(vAddr, size) => (TLBTranslate vAddr LoadData) >>= fun pAddr => (rGPR rt) >>= fun reg_val => let l__0 := size in (if sumbool_of_bool (Z.eqb l__0 4) then (MEMr_wrapper pAddr _) : M (mword (8 * 4)) else if sumbool_of_bool (Z.eqb l__0 3) then (MEMr_wrapper pAddr size) >>= fun w__2 : mword (8 * size) => returnm (autocast (autocast (concat_vec w__2 (subrange_vec_dec reg_val 7 0)))) else if sumbool_of_bool (Z.eqb l__0 2) then (MEMr_wrapper pAddr size) >>= fun w__3 : mword (8 * size) => returnm (autocast (autocast (concat_vec w__3 (subrange_vec_dec reg_val 15 0)))) else if sumbool_of_bool (Z.eqb l__0 1) then (MEMr_wrapper pAddr size) >>= fun w__4 : mword (8 * size) => returnm (autocast (autocast (concat_vec w__4 (subrange_vec_dec reg_val 23 0)))) else assert_exp' false "../mips/mips_insts.sail 1339:21 - 1339:22" >>= fun _ => exit tt) >>= fun result : bits 32 => (wGPR rt (mips_sign_extend 64 result)) : M (unit). Definition execute_LUI (rt : mword 5) (imm : mword 16) : M (unit) := (wGPR rt (mips_sign_extend 64 (concat_vec imm (Ox"0000" : mword 16)))) : M (unit). Definition execute_LDR (base : mword 5) (rt : mword 5) (offset : mword 16) : M (unit) := (rGPR base) >>= fun w__0 : mword 64 => (addrWrapperUnaligned (add_vec (mips_sign_extend 64 offset) w__0) LoadData DR) >>= fun '(vAddr, size) => (TLBTranslate vAddr LoadData) >>= fun pAddr => (rGPR rt) >>= fun reg_val => let l__24 := size in (if sumbool_of_bool (Z.eqb l__24 1) then (MEMr_wrapper pAddr size) >>= fun w__1 : mword (8 * size) => returnm (autocast (autocast (concat_vec (subrange_vec_dec reg_val 63 8) w__1))) else if sumbool_of_bool (Z.eqb l__24 2) then (MEMr_wrapper pAddr size) >>= fun w__2 : mword (8 * size) => returnm (autocast (autocast (concat_vec (subrange_vec_dec reg_val 63 16) w__2))) else if sumbool_of_bool (Z.eqb l__24 3) then (MEMr_wrapper pAddr size) >>= fun w__3 : mword (8 * size) => returnm (autocast (autocast (concat_vec (subrange_vec_dec reg_val 63 24) w__3))) else if sumbool_of_bool (Z.eqb l__24 4) then (MEMr_wrapper pAddr size) >>= fun w__4 : mword (8 * size) => returnm (autocast (autocast (concat_vec (subrange_vec_dec reg_val 63 32) w__4))) else if sumbool_of_bool (Z.eqb l__24 5) then (MEMr_wrapper pAddr size) >>= fun w__5 : mword (8 * size) => returnm (autocast (autocast (concat_vec (subrange_vec_dec reg_val 63 40) w__5))) else if sumbool_of_bool (Z.eqb l__24 6) then (MEMr_wrapper pAddr size) >>= fun w__6 : mword (8 * size) => returnm (autocast (autocast (concat_vec (subrange_vec_dec reg_val 63 48) w__6))) else if sumbool_of_bool (Z.eqb l__24 7) then (MEMr_wrapper pAddr size) >>= fun w__7 : mword (8 * size) => returnm (autocast (autocast (concat_vec (subrange_vec_dec reg_val 63 56) w__7))) else if sumbool_of_bool (Z.eqb l__24 8) then (MEMr_wrapper pAddr _) : M (mword (8 * 8)) else assert_exp' false "../mips/mips_insts.sail 1456:21 - 1456:22" >>= fun _ => exit tt) >>= fun w__16 : mword 64 => (wGPR rt w__16) : M (unit). Definition execute_LDL (base : mword 5) (rt : mword 5) (offset : mword 16) : M (unit) := (rGPR base) >>= fun w__0 : mword 64 => (addrWrapperUnaligned (add_vec (mips_sign_extend 64 offset) w__0) LoadData DL) >>= fun '(vAddr, size) => (TLBTranslate vAddr LoadData) >>= fun pAddr => (rGPR rt) >>= fun reg_val => let l__16 := size in (if sumbool_of_bool (Z.eqb l__16 8) then (MEMr_wrapper pAddr _) : M (mword (8 * 8)) else if sumbool_of_bool (Z.eqb l__16 7) then (MEMr_wrapper pAddr size) >>= fun w__2 : mword (8 * size) => returnm (autocast (autocast (concat_vec w__2 (subrange_vec_dec reg_val 7 0)))) else if sumbool_of_bool (Z.eqb l__16 6) then (MEMr_wrapper pAddr size) >>= fun w__3 : mword (8 * size) => returnm (autocast (autocast (concat_vec w__3 (subrange_vec_dec reg_val 15 0)))) else if sumbool_of_bool (Z.eqb l__16 5) then (MEMr_wrapper pAddr size) >>= fun w__4 : mword (8 * size) => returnm (autocast (autocast (concat_vec w__4 (subrange_vec_dec reg_val 23 0)))) else if sumbool_of_bool (Z.eqb l__16 4) then (MEMr_wrapper pAddr size) >>= fun w__5 : mword (8 * size) => returnm (autocast (autocast (concat_vec w__5 (subrange_vec_dec reg_val 31 0)))) else if sumbool_of_bool (Z.eqb l__16 3) then (MEMr_wrapper pAddr size) >>= fun w__6 : mword (8 * size) => returnm (autocast (autocast (concat_vec w__6 (subrange_vec_dec reg_val 39 0)))) else if sumbool_of_bool (Z.eqb l__16 2) then (MEMr_wrapper pAddr size) >>= fun w__7 : mword (8 * size) => returnm (autocast (autocast (concat_vec w__7 (subrange_vec_dec reg_val 47 0)))) else if sumbool_of_bool (Z.eqb l__16 1) then (MEMr_wrapper pAddr size) >>= fun w__8 : mword (8 * size) => returnm (autocast (autocast (concat_vec w__8 (subrange_vec_dec reg_val 55 0)))) else assert_exp' false "../mips/mips_insts.sail 1430:21 - 1430:22" >>= fun _ => exit tt) >>= fun w__16 : mword 64 => (wGPR rt w__16) : M (unit). Definition execute_JR (rs : mword 5) : M (unit) := ((read_reg InBranchDelay_ref) : M (mword 1)) >>= fun w__0 : mword 1 => (if (bits_to_bool w__0) : bool then (SignalException ResI) : M (unit) else returnm tt) >> (rGPR rs) >>= fun w__1 : mword 64 => (execute_branch w__1) : M (unit). Definition execute_JALR (rs : mword 5) (rd : mword 5) : M (unit) := ((read_reg InBranchDelay_ref) : M (mword 1)) >>= fun w__0 : mword 1 => (if (bits_to_bool w__0) : bool then (SignalException ResI) : M (unit) else returnm tt) >> (rGPR rs) >>= fun w__1 : mword 64 => (execute_branch w__1) >> ((read_reg PC_ref) : M (mword 64)) >>= fun w__2 : mword 64 => (wGPR rd (add_vec_int w__2 8)) : M (unit). Definition execute_JAL (offset : mword 26) : M (unit) := ((read_reg InBranchDelay_ref) : M (mword 1)) >>= fun w__0 : mword 1 => (if (bits_to_bool w__0) : bool then (SignalException ResI) : M (unit) else returnm tt) >> ((read_reg PC_ref) : M (mword 64)) >>= fun w__1 : mword 64 => (execute_branch (concat_vec (subrange_vec_dec (add_vec_int w__1 4) 63 28) (concat_vec offset ('b"00" : mword 2)))) >> ((read_reg PC_ref) : M (mword 64)) >>= fun w__2 : mword 64 => (wGPR ('b"11111" : mword 5) (add_vec_int w__2 8)) : M (unit). Definition execute_J (offset : mword 26) : M (unit) := ((read_reg InBranchDelay_ref) : M (mword 1)) >>= fun w__0 : mword 1 => (if (bits_to_bool w__0) : bool then (SignalException ResI) : M (unit) else returnm tt) >> ((read_reg PC_ref) : M (mword 64)) >>= fun w__1 : mword 64 => (execute_branch (concat_vec (subrange_vec_dec (add_vec_int w__1 4) 63 28) (concat_vec offset ('b"00" : mword 2)))) : M (unit). Definition execute_HCF '(tt : unit) : unit := tt. Definition execute_ERET '(tt : unit) : M (unit) := (checkCP0Access tt) >> (ERETHook tt) >> write_reg CP0LLBit_ref ('b"0" : mword 1) >> read_reg CP0Status_ref >>= fun w__0 : StatusReg => (if Bool.eqb (bits_to_bool (_get_StatusReg_ERL w__0)) (bit_to_bool B1) then (get_CP0ErrorEPC tt) >>= fun w__1 : mword 64 => write_reg NextPC_ref w__1 >> (_set_StatusReg_ERL CP0Status_ref ('b"0" : mword 1)) : M (unit) else (get_CP0EPC tt) >>= fun w__2 : mword 64 => write_reg NextPC_ref w__2 >> (_set_StatusReg_EXL CP0Status_ref ('b"0" : mword 1)) : M (unit)) : M (unit). Definition execute_DSUBU (rs : mword 5) (rt : mword 5) (rd : mword 5) : M (unit) := (rGPR rs) >>= fun w__0 : mword 64 => (rGPR rt) >>= fun w__1 : mword 64 => (wGPR rd (sub_vec w__0 w__1)) : M (unit). Definition execute_DSUB (rs : mword 5) (rt : mword 5) (rd : mword 5) : M (unit) := (rGPR rs) >>= fun w__0 : mword 64 => (rGPR rt) >>= fun w__1 : mword 64 => let temp65 : bits 65 := sub_vec (mips_sign_extend 65 w__0) (mips_sign_extend 65 w__1) in (if neq_bool (bit_to_bool (access_vec_dec temp65 64)) (bit_to_bool (access_vec_dec temp65 63)) then (SignalException Ov) : M (unit) else (wGPR rd (subrange_vec_dec temp65 63 0)) : M (unit)) : M (unit). Definition execute_DSRLV (rs : mword 5) (rt : mword 5) (rd : mword 5) : M (unit) := (rGPR rt) >>= fun temp => (rGPR rs) >>= fun w__0 : mword 64 => let sa := subrange_vec_dec w__0 5 0 in (shift_bits_right temp sa) >>= fun w__1 : mword 64 => (wGPR rd w__1) : M (unit). Definition execute_DSRL32 (rt : mword 5) (rd : mword 5) (sa : mword 5) : M (unit) := (rGPR rt) >>= fun temp => let sa32 := concat_vec ('b"1" : mword 1) sa in (shift_bits_right temp sa32) >>= fun w__0 : mword 64 => (wGPR rd w__0) : M (unit). Definition execute_DSRL (rt : mword 5) (rd : mword 5) (sa : mword 5) : M (unit) := (rGPR rt) >>= fun temp => (shift_bits_right temp sa) >>= fun w__0 : mword 64 => (wGPR rd w__0) : M (unit). Definition execute_DSRAV (rs : mword 5) (rt : mword 5) (rd : mword 5) : M (unit) := (rGPR rt) >>= fun temp => (rGPR rs) >>= fun w__0 : mword 64 => let sa := subrange_vec_dec w__0 5 0 in (shift_bits_right_arith temp sa) >>= fun w__1 : mword 64 => (wGPR rd w__1) : M (unit). Definition execute_DSRA32 (rt : mword 5) (rd : mword 5) (sa : mword 5) : M (unit) := (rGPR rt) >>= fun temp => let sa32 := concat_vec ('b"1" : mword 1) sa in (shift_bits_right_arith temp sa32) >>= fun w__0 : mword 64 => (wGPR rd w__0) : M (unit). Definition execute_DSRA (rt : mword 5) (rd : mword 5) (sa : mword 5) : M (unit) := (rGPR rt) >>= fun temp => (shift_bits_right_arith temp sa) >>= fun w__0 : mword 64 => (wGPR rd w__0) : M (unit). Definition execute_DSLLV (rs : mword 5) (rt : mword 5) (rd : mword 5) : M (unit) := (rGPR rt) >>= fun w__0 : mword 64 => (rGPR rs) >>= fun w__1 : mword 64 => (shift_bits_left w__0 (subrange_vec_dec w__1 5 0)) >>= fun w__2 : mword 64 => (wGPR rd w__2) : M (unit). Definition execute_DSLL32 (rt : mword 5) (rd : mword 5) (sa : mword 5) : M (unit) := (rGPR rt) >>= fun w__0 : mword 64 => (shift_bits_left w__0 (concat_vec ('b"1" : mword 1) sa)) >>= fun w__1 : mword 64 => (wGPR rd w__1) : M (unit). Definition execute_DSLL (rt : mword 5) (rd : mword 5) (sa : mword 5) : M (unit) := (rGPR rt) >>= fun w__0 : mword 64 => (shift_bits_left w__0 sa) >>= fun w__1 : mword 64 => (wGPR rd w__1) : M (unit). Definition execute_DMULTU (rs : mword 5) (rt : mword 5) : M (unit) := (rGPR rs) >>= fun w__0 : mword 64 => (rGPR rt) >>= fun w__1 : mword 64 => let result := mult_vec w__0 w__1 in write_reg HI_ref (subrange_vec_dec result 127 64) >> write_reg LO_ref (subrange_vec_dec result 63 0) : M (unit). Definition execute_DMULT (rs : mword 5) (rt : mword 5) : M (unit) := (rGPR rs) >>= fun w__0 : mword 64 => (rGPR rt) >>= fun w__1 : mword 64 => let result := mults_vec w__0 w__1 in write_reg HI_ref (subrange_vec_dec result 127 64) >> write_reg LO_ref (subrange_vec_dec result 63 0) : M (unit). Definition execute_DIVU (rs : mword 5) (rt : mword 5) : M (unit) := (rGPR rs) >>= fun rsVal => (rGPR rt) >>= fun rtVal => (if orb (NotWordVal rsVal) (orb (NotWordVal rtVal) (eq_vec rtVal (Ox"0000000000000000" : mword 64))) then (undefined_bitvector 32) >>= fun w__0 : mword 32 => (undefined_bitvector 32) >>= fun w__1 : mword 32 => returnm (w__0 : bits 32, w__1 : bits 32) else let si := projT1 (uint (subrange_vec_dec rsVal 31 0)) in let ti := projT1 (uint (subrange_vec_dec rtVal 31 0)) in let qi := Z.quot si ti in let ri := Z.rem si ti in returnm (to_bits 32 qi, to_bits 32 ri)) >>= fun '(q, r) => write_reg HI_ref (mips_sign_extend 64 r) >> write_reg LO_ref (mips_sign_extend 64 q) : M (unit). Definition execute_DIV (rs : mword 5) (rt : mword 5) : M (unit) := (rGPR rs) >>= fun rsVal => (rGPR rt) >>= fun rtVal => (if orb (NotWordVal rsVal) (orb (NotWordVal rtVal) (eq_vec rtVal (Ox"0000000000000000" : mword 64))) then (undefined_bitvector 32) >>= fun w__0 : mword 32 => (undefined_bitvector 32) >>= fun w__1 : mword 32 => returnm (w__0 : bits 32, w__1 : bits 32) else let si := projT1 (sint (subrange_vec_dec rsVal 31 0)) in let ti := projT1 (sint (subrange_vec_dec rtVal 31 0)) in let qi := Z.quot si ti in let ri := Z.sub si (Z.mul ti qi) in returnm (to_bits 32 qi, to_bits 32 ri)) >>= fun '(q, r) => write_reg HI_ref (mips_sign_extend 64 r) >> write_reg LO_ref (mips_sign_extend 64 q) : M (unit). Definition execute_DDIVU (rs : mword 5) (rt : mword 5) : M (unit) := (rGPR rs) >>= fun w__0 : mword 64 => let rsVal := projT1 (uint w__0) in (rGPR rt) >>= fun w__1 : mword 64 => let rtVal := projT1 (uint w__1) in (if sumbool_of_bool (Z.eqb rtVal 0) then (undefined_bitvector 64) >>= fun w__2 : mword 64 => (undefined_bitvector 64) >>= fun w__3 : mword 64 => returnm (w__2 : bits 64, w__3 : bits 64) else let qi := Z.quot rsVal rtVal in let ri := Z.rem rsVal rtVal in returnm (to_bits 64 qi, to_bits 64 ri)) >>= fun '(q, r) => write_reg LO_ref q >> write_reg HI_ref r : M (unit). Definition execute_DDIV (rs : mword 5) (rt : mword 5) : M (unit) := (rGPR rs) >>= fun w__0 : mword 64 => let rsVal := projT1 (sint w__0) in (rGPR rt) >>= fun w__1 : mword 64 => let rtVal := projT1 (sint w__1) in (if sumbool_of_bool (Z.eqb rtVal 0) then (undefined_bitvector 64) >>= fun w__2 : mword 64 => (undefined_bitvector 64) >>= fun w__3 : mword 64 => returnm (w__2 : bits 64, w__3 : bits 64) else let qi := Z.quot rsVal rtVal in let ri := Z.sub rsVal (Z.mul qi rtVal) in returnm (to_bits 64 qi, to_bits 64 ri)) >>= fun '(q, r) => write_reg LO_ref q >> write_reg HI_ref r : M (unit). Definition execute_DADDU (rs : mword 5) (rt : mword 5) (rd : mword 5) : M (unit) := (rGPR rs) >>= fun w__0 : mword 64 => (rGPR rt) >>= fun w__1 : mword 64 => (wGPR rd (add_vec w__0 w__1)) : M (unit). Definition execute_DADDIU (rs : mword 5) (rt : mword 5) (imm : mword 16) : M (unit) := (rGPR rs) >>= fun w__0 : mword 64 => (wGPR rt (add_vec w__0 (mips_sign_extend 64 imm))) : M (unit). Definition execute_DADDI (rs : mword 5) (rt : mword 5) (imm : mword 16) : M (unit) := (rGPR rs) >>= fun w__0 : mword 64 => let sum65 : bits 65 := add_vec (mips_sign_extend 65 w__0) (mips_sign_extend 65 imm) in (if neq_bool (bit_to_bool (access_vec_dec sum65 64)) (bit_to_bool (access_vec_dec sum65 63)) then (SignalException Ov) : M (unit) else (wGPR rt (subrange_vec_dec sum65 63 0)) : M (unit)) : M (unit). Definition execute_DADD (rs : mword 5) (rt : mword 5) (rd : mword 5) : M (unit) := (rGPR rs) >>= fun w__0 : mword 64 => (rGPR rt) >>= fun w__1 : mword 64 => let sum65 : bits 65 := add_vec (mips_sign_extend 65 w__0) (mips_sign_extend 65 w__1) in (if neq_bool (bit_to_bool (access_vec_dec sum65 64)) (bit_to_bool (access_vec_dec sum65 63)) then (SignalException Ov) : M (unit) else (wGPR rd (subrange_vec_dec sum65 63 0)) : M (unit)) : M (unit). Definition execute_ClearRegs (regset : ClearRegSet) (m : mword 16) : M (unit) := (if orb (generic_eq regset CLo) (generic_eq regset CHi) then (checkCP2usable tt) : M (unit) else returnm tt) >> let loop_i_lower := 0 in let loop_i_upper := 15 in (foreach_ZM_up loop_i_lower loop_i_upper 1 tt (fun i _ _ => (if (bit_to_bool (access_vec_dec m i)) : bool then (match regset with | GPLo => (wGPR (to_bits 5 i) (zeros_implicit 64 tt)) : M (unit) | GPHi => (wGPR (to_bits 5 (Z.add i 16)) (zeros_implicit 64 tt)) : M (unit) | CLo => (if sumbool_of_bool (Z.eqb i 0) then write_reg DDC_ref null_cap : M (unit) else (writeCapReg (to_bits 5 i) null_cap) : M (unit)) : M (unit) | CHi => (writeCapReg (to_bits 5 (Z.add i 16)) null_cap) : M (unit) end) : M (unit) else returnm tt) : M (unit))). Definition execute_CWriteHwr (cb : mword 5) (sel : mword 5) : M (unit) := (checkCP2usable tt) >> let l__75 := projT1 (uint sel) in (if sumbool_of_bool (Z.eqb l__75 0) then returnm (false, false) else if sumbool_of_bool (Z.eqb l__75 1) then returnm (false, false) else if sumbool_of_bool (Z.eqb l__75 8) then returnm (false, true) else if sumbool_of_bool (Z.eqb l__75 22) then returnm (true, true) else if sumbool_of_bool (Z.eqb l__75 23) then returnm (true, true) else if sumbool_of_bool (Z.eqb l__75 28) then returnm (true, true) else if sumbool_of_bool (Z.eqb l__75 29) then returnm (true, true) else if sumbool_of_bool (Z.eqb l__75 30) then returnm (true, true) else if sumbool_of_bool (Z.eqb l__75 31) then returnm (true, true) else (SignalException ResI) : M ((bool * bool))) >>= fun '((needSup, needAccessSys) : (bool * bool)) => (and_boolMP ((returnm (build_ex needAccessSys)) : M ({_bool : bool & ArithFact (Bool.eqb needAccessSys _bool)})) (build_trivial_ex ((pcc_access_system_regs tt) >>= fun w__9 : bool => returnm ((negb w__9) : bool))) : M ({_bool : bool & ArithFactP (exists simp_1 , Bool.eqb (needAccessSys && simp_1) _bool = true)})) >>= fun '(existT _ w__10 _) => (if sumbool_of_bool w__10 then (raise_c2_exception CapEx_AccessSystemRegsViolation sel) : M (unit) else (and_boolMP ((returnm (build_ex needSup)) : M ({_bool : bool & ArithFact (Bool.eqb needSup _bool)})) (build_trivial_ex ((getAccessLevel tt) >>= fun w__11 : AccessLevel => returnm ((negb (grantsAccess w__11 Supervisor)) : bool))) : M ({_bool : bool & ArithFactP (exists simp_1 , Bool.eqb (needSup && simp_1) _bool = true)})) >>= fun '(existT _ w__12 _) => if sumbool_of_bool w__12 then (raise_c2_exception CapEx_AccessSystemRegsViolation sel) : M (unit) else (readCapReg cb) >>= fun capVal => let l__66 := projT1 (uint sel) in (if sumbool_of_bool (Z.eqb l__66 0) then write_reg DDC_ref capVal : M (unit) else if sumbool_of_bool (Z.eqb l__66 1) then write_reg CULR_ref capVal : M (unit) else if sumbool_of_bool (Z.eqb l__66 8) then write_reg CPLR_ref capVal : M (unit) else if sumbool_of_bool (Z.eqb l__66 22) then write_reg KR1C_ref capVal : M (unit) else if sumbool_of_bool (Z.eqb l__66 23) then write_reg KR2C_ref capVal : M (unit) else if sumbool_of_bool (Z.eqb l__66 28) then write_reg ErrorEPCC_ref capVal : M (unit) else if sumbool_of_bool (Z.eqb l__66 29) then write_reg KCC_ref capVal : M (unit) else if sumbool_of_bool (Z.eqb l__66 30) then write_reg KDC_ref capVal : M (unit) else if sumbool_of_bool (Z.eqb l__66 31) then write_reg EPCC_ref capVal : M (unit) else assert_exp' false "CWriteHwr: should be unreachable code" >>= fun _ => exit tt) : M (unit)) : M (unit). Definition execute_CUnseal (cd : mword 5) (cs : mword 5) (ct : mword 5) : M (unit) := (checkCP2usable tt) >> (readCapReg cs) >>= fun cs_val => let cs_otype := projT1 (uint cs_val.(Capability_otype)) in (readCapReg ct) >>= fun ct_val => let ct_cursor := projT1 (getCapCursor ct_val) in (if negb cs_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cs) : M (unit) else if negb ct_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation ct) : M (unit) else if negb cs_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cs) : M (unit) else if ct_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation ct) : M (unit) else if hasReservedOType cs_val then (raise_c2_exception CapEx_TypeViolation cs) : M (unit) else if sumbool_of_bool (projT1 (neq_int ct_cursor cs_otype)) then (raise_c2_exception CapEx_TypeViolation ct) : M (unit) else if negb ct_val.(Capability_permit_unseal) then (raise_c2_exception CapEx_PermitUnsealViolation ct) : M (unit) else if sumbool_of_bool (Z.ltb ct_cursor (projT1 (getCapBase ct_val))) then (raise_c2_exception CapEx_LengthViolation ct) : M (unit) else if sumbool_of_bool (Z.geb ct_cursor (projT1 (getCapTop ct_val))) then (raise_c2_exception CapEx_LengthViolation ct) : M (unit) else (writeCapReg cd {[ (unsealCap cs_val) with Capability_global := (andb cs_val.(Capability_global) ct_val.(Capability_global)) ]}) : M (unit)) : M (unit). Definition execute_CToPtr (rd : mword 5) (cb : mword 5) (ct : mword 5) : M (unit) := (checkCP2usable tt) >> (readCapRegDDC ct) >>= fun ct_val => (readCapReg cb) >>= fun cb_val => (if negb ct_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation ct) : M (unit) else if andb cb_val.(Capability_tag) cb_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cb) : M (unit) else let ctBase := projT1 (getCapBase ct_val) in (wGPR rd (if negb cb_val.(Capability_tag) then zeros_implicit 64 tt else to_bits 64 (Z.sub (projT1 (getCapCursor cb_val)) ctBase))) : M (unit)) : M (unit). Definition execute_CTestSubset (rd : mword 5) (cb : mword 5) (ct : mword 5) : M (unit) := (checkCP2usable tt) >> (readCapRegDDC cb) >>= fun cb_val => (readCapReg ct) >>= fun ct_val => let ct_top := projT1 (getCapTop ct_val) in let ct_base := projT1 (getCapBase ct_val) in let ct_perms := getCapPerms ct_val in let cb_top := projT1 (getCapTop cb_val) in let cb_base := projT1 (getCapBase cb_val) in let cb_perms := getCapPerms cb_val in let result := if neq_bool cb_val.(Capability_tag) ct_val.(Capability_tag) then 'b"0" : mword 1 else if sumbool_of_bool (Z.ltb ct_base cb_base) then 'b"0" : mword 1 else if sumbool_of_bool (Z.gtb ct_top cb_top) then 'b"0" : mword 1 else if neq_vec (and_vec ct_perms cb_perms) ct_perms then 'b"0" : mword 1 else 'b"1" : mword 1 in (wGPR rd (mips_zero_extend 64 result)) : M (unit). Definition execute_CSub (rd : mword 5) (cb : mword 5) (ct : mword 5) : M (unit) := (checkCP2usable tt) >> (readCapReg ct) >>= fun ct_val => (readCapReg cb) >>= fun cb_val => (wGPR rd (to_bits 64 (Z.sub (projT1 (getCapCursor cb_val)) (projT1 (getCapCursor ct_val))))) : M (unit). Definition execute_CStoreConditional (rs : mword 5) (cb : mword 5) (rd : mword 5) (width : WordType) : M (unit) := (checkCP2usable tt) >> (readCapRegDDC cb) >>= fun cb_val => (if negb cb_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cb) : M (unit) else if cb_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cb) : M (unit) else if negb cb_val.(Capability_permit_store) then (raise_c2_exception CapEx_PermitStoreViolation cb) : M (unit) else let size := projT1 (wordWidthBytes width) in let vAddr := projT1 (getCapCursor cb_val) in let vAddr64 := to_bits 64 vAddr in (if sumbool_of_bool (Z.gtb (Z.add vAddr size) (projT1 (getCapTop cb_val))) then (raise_c2_exception CapEx_LengthViolation cb) : M (unit) else if sumbool_of_bool (Z.ltb vAddr (projT1 (getCapBase cb_val))) then (raise_c2_exception CapEx_LengthViolation cb) : M (unit) else if negb (isAddressAligned vAddr64 width) then (SignalExceptionBadAddr AdES vAddr64) : M (unit) else (TLBTranslate vAddr64 StoreData) >>= fun pAddr => (rGPR rs) >>= fun rs_val => ((read_reg CP0LLBit_ref) : M (mword 1)) >>= fun w__0 : mword 1 => (if (bit_to_bool (access_vec_dec w__0 0)) : bool then (match width with | B => (MEMw_conditional_wrapper pAddr 1 (subrange_vec_dec rs_val 7 0)) : M (bool) | H => (MEMw_conditional_wrapper pAddr 2 (subrange_vec_dec rs_val 15 0)) : M (bool) | W => (MEMw_conditional_wrapper pAddr 4 (subrange_vec_dec rs_val 31 0)) : M (bool) | D => (MEMw_conditional_wrapper pAddr 8 rs_val) : M (bool) end) : M (bool) else returnm false) >>= fun success : bool => (wGPR rd (mips_zero_extend 64 (bool_to_bits success))) : M (unit)) : M (unit)) : M (unit). Definition execute_CStore (rs : mword 5) (cb : mword 5) (rt : mword 5) (offset : mword 8) (width : WordType) : M (unit) := (checkCP2usable tt) >> (readCapRegDDC cb) >>= fun cb_val => (if negb cb_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cb) : M (unit) else if cb_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cb) : M (unit) else if negb cb_val.(Capability_permit_store) then (raise_c2_exception CapEx_PermitStoreViolation cb) : M (unit) else let size := projT1 (wordWidthBytes width) in let cursor := projT1 (getCapCursor cb_val) in (rGPR rt) >>= fun w__0 : mword 64 => let vAddr := projT1 (emod_with_eq (Z.add (Z.add cursor (projT1 (uint w__0))) (Z.mul size (projT1 (sint offset)))) (projT1 (pow2 64))) in let vAddr64 := to_bits 64 vAddr in (if sumbool_of_bool (Z.gtb (Z.add vAddr size) (projT1 (getCapTop cb_val))) then (raise_c2_exception CapEx_LengthViolation cb) : M (unit) else if sumbool_of_bool (Z.ltb vAddr (projT1 (getCapBase cb_val))) then (raise_c2_exception CapEx_LengthViolation cb) : M (unit) else if negb (isAddressAligned vAddr64 width) then (SignalExceptionBadAddr AdES vAddr64) : M (unit) else (TLBTranslate vAddr64 StoreData) >>= fun pAddr => (rGPR rs) >>= fun rs_val => (match width with | B => (MEMw_wrapper pAddr 1 (subrange_vec_dec rs_val 7 0)) : M (unit) | H => (MEMw_wrapper pAddr 2 (subrange_vec_dec rs_val 15 0)) : M (unit) | W => (MEMw_wrapper pAddr 4 (subrange_vec_dec rs_val 31 0)) : M (unit) | D => (MEMw_wrapper pAddr 8 rs_val) : M (unit) end) : M (unit)) : M (unit)) : M (unit). Definition execute_CSetOffset (cd : mword 5) (cb : mword 5) (rt : mword 5) : M (unit) := (checkCP2usable tt) >> (readCapReg cb) >>= fun cb_val => (rGPR rt) >>= fun rt_val => (if andb cb_val.(Capability_tag) cb_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cb) : M (unit) else let '(success, newCap) := setCapOffset cb_val rt_val in (if sumbool_of_bool success then (writeCapReg cd newCap) : M (unit) else (writeCapReg cd (unrepCap newCap)) : M (unit)) : M (unit)) : M (unit). Definition execute_CSetFlags (cd : mword 5) (cb : mword 5) (rt : mword 5) : M (unit) := (checkCP2usable tt) >> (readCapReg cb) >>= fun cb_val => (rGPR rt) >>= fun rt_val => (if andb cb_val.(Capability_tag) cb_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cb) : M (unit) else let newCap := setCapFlags cb_val (vector_truncate rt_val num_flags) in (writeCapReg cd newCap) : M (unit)) : M (unit). Definition execute_CSetCause (rt : mword 5) : M (unit) := (checkCP2usable tt) >> (pcc_access_system_regs tt) >>= fun w__0 : bool => (if sumbool_of_bool (negb w__0) then (raise_c2_exception_noreg CapEx_AccessSystemRegsViolation) : M (unit) else (rGPR rt) >>= fun rt_val => (_set_CapCauseReg_ExcCode CapCause_ref (subrange_vec_dec rt_val 15 8)) >> (_set_CapCauseReg_RegNum CapCause_ref (subrange_vec_dec rt_val 7 0)) : M (unit)) : M (unit). Definition execute_CSetCID (cb : mword 5) : M (unit) := (checkCP2usable tt) >> (readCapReg cb) >>= fun cb_val => (if negb cb_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cb) : M (unit) else if cb_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cb) : M (unit) else if negb cb_val.(Capability_permit_set_CID) then (raise_c2_exception CapEx_PermitSetCIDViolation cb) : M (unit) else let addr := projT1 (getCapCursor cb_val) in (if sumbool_of_bool (Z.ltb addr (projT1 (getCapBase cb_val))) then (raise_c2_exception CapEx_LengthViolation cb) : M (unit) else if sumbool_of_bool (Z.geb addr (projT1 (getCapTop cb_val))) then (raise_c2_exception CapEx_LengthViolation cb) : M (unit) else write_reg CID_ref (to_bits 64 addr) : M (unit)) : M (unit)) : M (unit). Definition execute_CSetBoundsImmediate (cd : mword 5) (cb : mword 5) (imm : mword 11) : M (unit) := (checkCP2usable tt) >> (readCapReg cb) >>= fun cb_val => let immU := projT1 (uint imm) in let cursor := projT1 (getCapCursor cb_val) in let base := projT1 (getCapBase cb_val) in let top := projT1 (getCapTop cb_val) in let newTop := Z.add cursor immU in (if negb cb_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cb) : M (unit) else if cb_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cb) : M (unit) else if sumbool_of_bool (Z.ltb cursor base) then (raise_c2_exception CapEx_LengthViolation cb) : M (unit) else if sumbool_of_bool (Z.gtb newTop top) then (raise_c2_exception CapEx_LengthViolation cb) : M (unit) else let '(_, newCap) := setCapBounds cb_val (to_bits 64 cursor) (to_bits 65 newTop) in (writeCapReg cd newCap) : M (unit)) : M (unit). Definition execute_CSetBoundsExact (cd : mword 5) (cb : mword 5) (rt : mword 5) : M (unit) := (checkCP2usable tt) >> (readCapReg cb) >>= fun cb_val => (rGPR rt) >>= fun w__0 : mword 64 => let rt_val := projT1 (uint w__0) in let cursor := projT1 (getCapCursor cb_val) in let base := projT1 (getCapBase cb_val) in let top := projT1 (getCapTop cb_val) in let newTop := Z.add cursor rt_val in (if negb cb_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cb) : M (unit) else if cb_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cb) : M (unit) else if sumbool_of_bool (Z.ltb cursor base) then (raise_c2_exception CapEx_LengthViolation cb) : M (unit) else if sumbool_of_bool (Z.gtb newTop top) then (raise_c2_exception CapEx_LengthViolation cb) : M (unit) else let '(exact, newCap) := setCapBounds cb_val (to_bits 64 cursor) (to_bits 65 newTop) in (if sumbool_of_bool (negb exact) then (raise_c2_exception CapEx_InexactBounds cb) : M (unit) else (writeCapReg cd newCap) : M (unit)) : M (unit)) : M (unit). Definition execute_CSetBounds (cd : mword 5) (cb : mword 5) (rt : mword 5) : M (unit) := (checkCP2usable tt) >> (readCapReg cb) >>= fun cb_val => (rGPR rt) >>= fun w__0 : mword 64 => let rt_val := projT1 (uint w__0) in let cursor := projT1 (getCapCursor cb_val) in let base := projT1 (getCapBase cb_val) in let top := projT1 (getCapTop cb_val) in let newTop := Z.add cursor rt_val in (if negb cb_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cb) : M (unit) else if cb_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cb) : M (unit) else if sumbool_of_bool (Z.ltb cursor base) then (raise_c2_exception CapEx_LengthViolation cb) : M (unit) else if sumbool_of_bool (Z.gtb newTop top) then (raise_c2_exception CapEx_LengthViolation cb) : M (unit) else let '(_, newCap) := setCapBounds cb_val (to_bits 64 cursor) (to_bits 65 newTop) in (writeCapReg cd newCap) : M (unit)) : M (unit). Definition execute_CSetAddr (cd : mword 5) (cb : mword 5) (rt : mword 5) : M (unit) := (checkCP2usable tt) >> (readCapReg cb) >>= fun cb_val => (rGPR rt) >>= fun rt_val => (if andb cb_val.(Capability_tag) cb_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cb) : M (unit) else let '(representable, newCap) := setCapAddr cb_val rt_val in (if sumbool_of_bool representable then (writeCapReg cd newCap) : M (unit) else (writeCapReg cd (unrepCap newCap)) : M (unit)) : M (unit)) : M (unit). Definition execute_CSealEntry (cd : mword 5) (cs : mword 5) : M (unit) := (checkCP2usable tt) >> (readCapReg cs) >>= fun cs_val => let cs_cursor := projT1 (getCapCursor cs_val) in let cs_top := projT1 (getCapTop cs_val) in let cs_base := projT1 (getCapBase cs_val) in (if negb cs_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cs) : M (unit) else if cs_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cs) : M (unit) else if negb cs_val.(Capability_permit_execute) then (raise_c2_exception CapEx_PermitExecuteViolation cs) : M (unit) else let '(success, newCap) := sealCap cs_val (to_bits 24 otype_sentry) in (if sumbool_of_bool (negb success) then (raise_c2_exception CapEx_InexactBounds cs) : M (unit) else (writeCapReg cd newCap) : M (unit)) : M (unit)) : M (unit). Definition execute_CSeal (cd : mword 5) (cs : mword 5) (ct : mword 5) : M (unit) := (checkCP2usable tt) >> (readCapReg cs) >>= fun cs_val => (readCapReg ct) >>= fun ct_val => let ct_cursor := projT1 (getCapCursor ct_val) in let ct_top := projT1 (getCapTop ct_val) in let ct_base := projT1 (getCapBase ct_val) in (if negb cs_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cs) : M (unit) else if negb ct_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation ct) : M (unit) else if cs_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cs) : M (unit) else if ct_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation ct) : M (unit) else if negb ct_val.(Capability_permit_seal) then (raise_c2_exception CapEx_PermitSealViolation ct) : M (unit) else if sumbool_of_bool (Z.ltb ct_cursor ct_base) then (raise_c2_exception CapEx_LengthViolation ct) : M (unit) else if sumbool_of_bool (Z.geb ct_cursor ct_top) then (raise_c2_exception CapEx_LengthViolation ct) : M (unit) else if sumbool_of_bool (Z.gtb ct_cursor max_otype) then (raise_c2_exception CapEx_LengthViolation ct) : M (unit) else let '(success, newCap) := sealCap cs_val (to_bits 24 ct_cursor) in (if sumbool_of_bool (negb success) then (raise_c2_exception CapEx_InexactBounds cs) : M (unit) else (writeCapReg cd newCap) : M (unit)) : M (unit)) : M (unit). Definition execute_CSCC (cs : mword 5) (cb : mword 5) (rd : mword 5) : M (unit) := (checkCP2usable tt) >> (readCapReg cs) >>= fun cs_val => (readCapRegDDC cb) >>= fun cb_val => (if negb cb_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cb) : M (unit) else if cb_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cb) : M (unit) else if negb cb_val.(Capability_permit_store) then (raise_c2_exception CapEx_PermitStoreViolation cb) : M (unit) else if andb (negb cb_val.(Capability_permit_store_cap)) cs_val.(Capability_tag) then (raise_c2_exception CapEx_PermitStoreCapViolation cb) : M (unit) else if andb (negb cb_val.(Capability_permit_store_local_cap)) (andb cs_val.(Capability_tag) (negb cs_val.(Capability_global))) then (raise_c2_exception CapEx_PermitStoreLocalCapViolation cb) : M (unit) else let vAddr := projT1 (getCapCursor cb_val) in let vAddr64 := to_bits 64 vAddr in (if sumbool_of_bool (Z.gtb (Z.add vAddr cap_size) (projT1 (getCapTop cb_val))) then (raise_c2_exception CapEx_LengthViolation cb) : M (unit) else if sumbool_of_bool (Z.ltb vAddr (projT1 (getCapBase cb_val))) then (raise_c2_exception CapEx_LengthViolation cb) : M (unit) else if sumbool_of_bool (projT1 (neq_int (projT1 (emod_with_eq vAddr cap_size)) 0)) then (SignalExceptionBadAddr AdES vAddr64) : M (unit) else (TLBTranslateC vAddr64 StoreData) >>= fun '(pAddr, macr) => (match (if eq_bit ((bool_to_bit cs_val.(Capability_tag)) : bitU) ((bool_to_bit false) : bitU) then Unrestricted else macr) with | Trap => (raise_c2_exception_badaddr CapEx_TLBNoStoreCap cs vAddr64) : M (bool) | Clear => returnm false | Unrestricted => returnm cs_val.(Capability_tag) end) >>= fun mtag : bool => ((read_reg CP0LLBit_ref) : M (mword 1)) >>= fun w__1 : mword 1 => (if (bit_to_bool (access_vec_dec w__1 0)) : bool then (MEMw_tagged_conditional pAddr cap_size mtag (capToMemBits cs_val)) : M (bool) else returnm false) >>= fun success => (wGPR rd (mips_zero_extend 64 (bool_to_bits success))) : M (unit)) : M (unit)) : M (unit). Definition execute_CSC (cs : mword 5) (cb : mword 5) (rt : mword 5) (offset : mword 11) : M (unit) := (checkCP2usable tt) >> (readCapReg cs) >>= fun cs_val => (readCapRegDDC cb) >>= fun cb_val => (if negb cb_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cb) : M (unit) else if cb_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cb) : M (unit) else if negb cb_val.(Capability_permit_store) then (raise_c2_exception CapEx_PermitStoreViolation cb) : M (unit) else if andb (negb cb_val.(Capability_permit_store_cap)) cs_val.(Capability_tag) then (raise_c2_exception CapEx_PermitStoreCapViolation cb) : M (unit) else if andb (negb cb_val.(Capability_permit_store_local_cap)) (andb cs_val.(Capability_tag) (negb cs_val.(Capability_global))) then (raise_c2_exception CapEx_PermitStoreLocalCapViolation cb) : M (unit) else let cursor := projT1 (getCapCursor cb_val) in (rGPR rt) >>= fun w__0 : mword 64 => let vAddr := projT1 (emod_with_eq (Z.add (Z.add cursor (projT1 (uint w__0))) (Z.mul 16 (projT1 (sint offset)))) (projT1 (pow2 64))) in let vAddr64 := to_bits 64 vAddr in (if sumbool_of_bool (Z.gtb (Z.add vAddr cap_size) (projT1 (getCapTop cb_val))) then (raise_c2_exception CapEx_LengthViolation cb) : M (unit) else if sumbool_of_bool (Z.ltb vAddr (projT1 (getCapBase cb_val))) then (raise_c2_exception CapEx_LengthViolation cb) : M (unit) else if sumbool_of_bool (projT1 (neq_int (projT1 (emod_with_eq vAddr cap_size)) 0)) then (SignalExceptionBadAddr AdES vAddr64) : M (unit) else (TLBTranslateC vAddr64 StoreData) >>= fun '(pAddr, macr) => (match (if eq_bit ((bool_to_bit cs_val.(Capability_tag)) : bitU) ((bool_to_bit false) : bitU) then Unrestricted else macr) with | Unrestricted => returnm cs_val.(Capability_tag) | Clear => returnm false | Trap => (raise_c2_exception_badaddr CapEx_TLBNoStoreCap cs vAddr64) : M (bool) end) >>= fun mtag : bool => (MEMw_tagged pAddr cap_size mtag (capToMemBits cs_val)) : M (unit)) : M (unit)) : M (unit). Definition execute_CReturn '(tt : unit) : M (unit) := (checkCP2usable tt) >> (raise_c2_exception_noreg CapEx_ReturnTrap) : M (unit). Definition execute_CReadHwr (cd : mword 5) (sel : mword 5) : M (unit) := (checkCP2usable tt) >> let l__57 := projT1 (uint sel) in (if sumbool_of_bool (Z.eqb l__57 0) then returnm (false, false) else if sumbool_of_bool (Z.eqb l__57 1) then returnm (false, false) else if sumbool_of_bool (Z.eqb l__57 8) then returnm (false, true) else if sumbool_of_bool (Z.eqb l__57 22) then returnm (true, true) else if sumbool_of_bool (Z.eqb l__57 23) then returnm (true, true) else if sumbool_of_bool (Z.eqb l__57 28) then returnm (true, true) else if sumbool_of_bool (Z.eqb l__57 29) then returnm (true, true) else if sumbool_of_bool (Z.eqb l__57 30) then returnm (true, true) else if sumbool_of_bool (Z.eqb l__57 31) then returnm (true, true) else (SignalException ResI) : M ((bool * bool))) >>= fun '((needSup, needAccessSys) : (bool * bool)) => (and_boolMP ((returnm (build_ex needAccessSys)) : M ({_bool : bool & ArithFact (Bool.eqb needAccessSys _bool)})) (build_trivial_ex ((pcc_access_system_regs tt) >>= fun w__9 : bool => returnm ((negb w__9) : bool))) : M ({_bool : bool & ArithFactP (exists simp_1 , Bool.eqb (needAccessSys && simp_1) _bool = true)})) >>= fun '(existT _ w__10 _) => (if sumbool_of_bool w__10 then (raise_c2_exception CapEx_AccessSystemRegsViolation sel) : M (unit) else (and_boolMP ((returnm (build_ex needSup)) : M ({_bool : bool & ArithFact (Bool.eqb needSup _bool)})) (build_trivial_ex ((getAccessLevel tt) >>= fun w__11 : AccessLevel => returnm ((negb (grantsAccess w__11 Supervisor)) : bool))) : M ({_bool : bool & ArithFactP (exists simp_1 , Bool.eqb (needSup && simp_1) _bool = true)})) >>= fun '(existT _ w__12 _) => if sumbool_of_bool w__12 then (raise_c2_exception CapEx_AccessSystemRegsViolation sel) : M (unit) else let l__48 := projT1 (uint sel) in (if sumbool_of_bool (Z.eqb l__48 0) then read_reg DDC_ref : M (Capability) else if sumbool_of_bool (Z.eqb l__48 1) then read_reg CULR_ref : M (Capability) else if sumbool_of_bool (Z.eqb l__48 8) then read_reg CPLR_ref : M (Capability) else if sumbool_of_bool (Z.eqb l__48 22) then read_reg KR1C_ref : M (Capability) else if sumbool_of_bool (Z.eqb l__48 23) then read_reg KR2C_ref : M (Capability) else if sumbool_of_bool (Z.eqb l__48 28) then read_reg ErrorEPCC_ref : M (Capability) else if sumbool_of_bool (Z.eqb l__48 29) then read_reg KCC_ref : M (Capability) else if sumbool_of_bool (Z.eqb l__48 30) then read_reg KDC_ref : M (Capability) else if sumbool_of_bool (Z.eqb l__48 31) then read_reg EPCC_ref : M (Capability) else assert_exp' false "CReadHwr: should be unreachable code" >>= fun _ => exit tt) >>= fun capVal : Capability => (writeCapReg cd capVal) : M (unit)) : M (unit). Definition execute_CRAP (rt : mword 5) (rs : mword 5) : M (unit) := (checkCP2usable tt) >> (rGPR rs) >>= fun len => (wGPR rt (getRepresentableLength len)) : M (unit). Definition execute_CRAM (rt : mword 5) (rs : mword 5) : M (unit) := (checkCP2usable tt) >> (rGPR rs) >>= fun len => (wGPR rt (getRepresentableAlignmentMask len)) : M (unit). Definition execute_CPtrCmp (rd : mword 5) (cb : mword 5) (ct : mword 5) (op : CPtrCmpOp) : M (unit) := (checkCP2usable tt) >> (readCapReg cb) >>= fun cb_val => (readCapReg ct) >>= fun ct_val => let equal : bool := eq_vec cb_val.(Capability_address) ct_val.(Capability_address) in let ltu : bool := zopz0zI_u cb_val.(Capability_address) ct_val.(Capability_address) in let lts : bool := zopz0zI_s cb_val.(Capability_address) ct_val.(Capability_address) in let cmp : bool := match op with | CEQ => equal | CNE => negb equal | CLT => lts | CLE => orb lts equal | CLTU => ltu | CLEU => orb ltu equal | CEXEQ => generic_eq cb_val ct_val | CNEXEQ => generic_neq cb_val ct_val end in (wGPR rd (mips_zero_extend 64 (bool_to_bits cmp))) : M (unit). Definition execute_CMove (cd : mword 5) (cb : mword 5) : M (unit) := (checkCP2usable tt) >> (readCapReg cb) >>= fun w__0 : Capability => (writeCapReg cd w__0) : M (unit). Definition execute_CMOVX (cd : mword 5) (cb : mword 5) (rt : mword 5) (ismovn : bool) : M (unit) := (checkCP2usable tt) >> (rGPR rt) >>= fun w__0 : mword 64 => (if (bits_to_bool (xor_vec (bool_to_bits (eq_vec w__0 (zeros_implicit 64 tt))) ((bool_to_bits ismovn) : mword 1))) : bool then (readCapReg cb) >>= fun w__1 : Capability => (writeCapReg cd w__1) : M (unit) else returnm tt) : M (unit). Definition execute_CLoadTags (rd : mword 5) (cb : mword 5) : M (unit) := (checkCP2usable tt) >> (readCapRegDDC cb) >>= fun cb_val => (if negb cb_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cb) : M (unit) else if cb_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cb) : M (unit) else if negb cb_val.(Capability_permit_load) then (raise_c2_exception CapEx_PermitLoadViolation cb) : M (unit) else if negb cb_val.(Capability_permit_load_cap) then (raise_c2_exception CapEx_PermitLoadCapViolation cb) : M (unit) else let vAddr := projT1 (getCapCursor cb_val) in let vAddr64 := to_bits 64 (projT1 (getCapCursor cb_val)) in (if sumbool_of_bool (Z.gtb (Z.add vAddr (Z.mul caps_per_cacheline cap_size)) (projT1 (getCapTop cb_val))) then (raise_c2_exception CapEx_LengthViolation cb) : M (unit) else if sumbool_of_bool (Z.ltb vAddr (projT1 (getCapBase cb_val))) then (raise_c2_exception CapEx_LengthViolation cb) : M (unit) else if sumbool_of_bool (negb (Z.eqb (projT1 (emod_with_eq vAddr (Z.mul cap_size caps_per_cacheline))) 0)) then (SignalExceptionBadAddr AdEL vAddr64) : M (unit) else (TLBTranslateC vAddr64 LoadData) >>= fun '(pAddr, macr) => (match macr with | Clear => (raise_c2_exception_badaddr CapEx_TLBLoadCap cb vAddr64) : M (unit) | Trap => (raise_c2_exception_badaddr CapEx_TLBLoadCap cb vAddr64) : M (unit) | Unrestricted => let x : bits 64 := zeros_implicit 64 tt in (let loop_i_lower := 0 in let loop_i_upper := Z.sub caps_per_cacheline 1 in (foreach_ZM_up loop_i_lower loop_i_upper 1 x (fun i _ x => (MEMr_tagged (add_vec_int pAddr (Z.mul i cap_size)) cap_size true) >>= fun '(tag, _) => let x : bits 64 := update_vec_dec x i ((bool_to_bit tag) : bitU) in returnm x))) >>= fun x : mword 64 => (wGPR rd x) : M (unit) end) : M (unit)) : M (unit)) : M (unit). Definition execute_CLoadLinked (rd : mword 5) (cb : mword 5) (signext : bool) (width : WordType) : M (unit) := (checkCP2usable tt) >> (readCapRegDDC cb) >>= fun cb_val => (if negb cb_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cb) : M (unit) else if cb_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cb) : M (unit) else if negb cb_val.(Capability_permit_load) then (raise_c2_exception CapEx_PermitLoadViolation cb) : M (unit) else let size := projT1 (wordWidthBytes width) in let vAddr := projT1 (getCapCursor cb_val) in let vAddr64 := to_bits 64 vAddr in (if sumbool_of_bool (Z.gtb (Z.add vAddr size) (projT1 (getCapTop cb_val))) then (raise_c2_exception CapEx_LengthViolation cb) : M (unit) else if sumbool_of_bool (Z.ltb vAddr (projT1 (getCapBase cb_val))) then (raise_c2_exception CapEx_LengthViolation cb) : M (unit) else if negb (isAddressAligned vAddr64 width) then (SignalExceptionBadAddr AdEL vAddr64) : M (unit) else (TLBTranslate vAddr64 LoadData) >>= fun pAddr => (MEMr_reserve_wrapper pAddr size) >>= fun w__0 : mword (8 * size) => let memResult : bits 64 := extendLoad w__0 signext in write_reg CP0LLBit_ref ('b"1" : mword 1) >> write_reg CP0LLAddr_ref pAddr >> (wGPR rd memResult) : M (unit)) : M (unit)) : M (unit). Definition execute_CLoad (rd : mword 5) (cb : mword 5) (rt : mword 5) (offset : mword 8) (signext : bool) (width : WordType) : M (unit) := (checkCP2usable tt) >> (readCapRegDDC cb) >>= fun cb_val => (if negb cb_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cb) : M (unit) else if cb_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cb) : M (unit) else if negb cb_val.(Capability_permit_load) then (raise_c2_exception CapEx_PermitLoadViolation cb) : M (unit) else let size := projT1 (wordWidthBytes width) in let cursor := projT1 (getCapCursor cb_val) in (rGPR rt) >>= fun w__0 : mword 64 => let vAddr := projT1 (emod_with_eq (Z.add (Z.add cursor (projT1 (uint w__0))) (Z.mul size (projT1 (sint offset)))) (projT1 (pow2 64))) in let vAddr64 := to_bits 64 vAddr in (if sumbool_of_bool (Z.gtb (Z.add vAddr size) (projT1 (getCapTop cb_val))) then (raise_c2_exception CapEx_LengthViolation cb) : M (unit) else if sumbool_of_bool (Z.ltb vAddr (projT1 (getCapBase cb_val))) then (raise_c2_exception CapEx_LengthViolation cb) : M (unit) else if negb (isAddressAligned vAddr64 width) then (SignalExceptionBadAddr AdEL vAddr64) : M (unit) else (TLBTranslate vAddr64 LoadData) >>= fun pAddr => (MEMr_wrapper pAddr size) >>= fun w__1 : mword (8 * size) => let memResult : bits 64 := extendLoad w__1 signext in (wGPR rd memResult) : M (unit)) : M (unit)) : M (unit). Definition execute_CLLC (cd : mword 5) (cb : mword 5) : M (unit) := (checkCP2usable tt) >> (readCapRegDDC cb) >>= fun cb_val => (if negb cb_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cb) : M (unit) else if cb_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cb) : M (unit) else if negb cb_val.(Capability_permit_load) then (raise_c2_exception CapEx_PermitLoadViolation cb) : M (unit) else let vAddr := projT1 (getCapCursor cb_val) in let vAddr64 := to_bits 64 vAddr in (if sumbool_of_bool (Z.gtb (Z.add vAddr cap_size) (projT1 (getCapTop cb_val))) then (raise_c2_exception CapEx_LengthViolation cb) : M (unit) else if sumbool_of_bool (Z.ltb vAddr (projT1 (getCapBase cb_val))) then (raise_c2_exception CapEx_LengthViolation cb) : M (unit) else if sumbool_of_bool (projT1 (neq_int (projT1 (emod_with_eq vAddr cap_size)) 0)) then (SignalExceptionBadAddr AdEL vAddr64) : M (unit) else (TLBTranslateC vAddr64 LoadData) >>= fun '(pAddr, macr) => (MEMr_tagged_reserve pAddr cap_size (andb cb_val.(Capability_permit_load_cap) (negb (generic_eq macr Clear)))) >>= fun '(tag, mem) => (if sumbool_of_bool (andb tag (generic_eq macr Trap)) then (raise_c2_exception_badaddr CapEx_TLBLoadCap cb vAddr64) : M (unit) else let cap := memBitsToCapability tag mem in (writeCapReg cd cap) >> write_reg CP0LLBit_ref ('b"1" : mword 1) >> write_reg CP0LLAddr_ref pAddr : M (unit)) : M (unit)) : M (unit)) : M (unit). Definition execute_CLCBI (cd : mword 5) (cb : mword 5) (offset : mword 16) : M (unit) := (checkCP2usable tt) >> (readCapRegDDC cb) >>= fun cb_val => (if negb cb_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cb) : M (unit) else if cb_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cb) : M (unit) else if negb cb_val.(Capability_permit_load) then (raise_c2_exception CapEx_PermitLoadViolation cb) : M (unit) else let cursor := projT1 (getCapCursor cb_val) in let vAddr := projT1 (emod_with_eq (Z.add cursor (Z.mul 16 (projT1 (sint offset)))) (projT1 (pow2 64))) in let vAddr64 := to_bits 64 vAddr in (if sumbool_of_bool (Z.gtb (Z.add vAddr cap_size) (projT1 (getCapTop cb_val))) then (raise_c2_exception CapEx_LengthViolation cb) : M (unit) else if sumbool_of_bool (Z.ltb vAddr (projT1 (getCapBase cb_val))) then (raise_c2_exception CapEx_LengthViolation cb) : M (unit) else if sumbool_of_bool (projT1 (neq_int (projT1 (emod_with_eq vAddr cap_size)) 0)) then (SignalExceptionBadAddr AdEL vAddr64) : M (unit) else (TLBTranslateC vAddr64 LoadData) >>= fun '(pAddr, macr) => (MEMr_tagged pAddr cap_size (andb cb_val.(Capability_permit_load_cap) (negb (generic_eq macr Clear)))) >>= fun '(tag, mem) => (if sumbool_of_bool (andb tag (generic_eq macr Trap)) then (raise_c2_exception_badaddr CapEx_TLBLoadCap cb vAddr64) : M (unit) else let cap := memBitsToCapability tag mem in (writeCapReg cd cap) : M (unit)) : M (unit)) : M (unit)) : M (unit). Definition execute_CLC (cd : mword 5) (cb : mword 5) (rt : mword 5) (offset : mword 11) : M (unit) := (checkCP2usable tt) >> (readCapRegDDC cb) >>= fun cb_val => (if negb cb_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cb) : M (unit) else if cb_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cb) : M (unit) else if negb cb_val.(Capability_permit_load) then (raise_c2_exception CapEx_PermitLoadViolation cb) : M (unit) else let cursor := projT1 (getCapCursor cb_val) in (rGPR rt) >>= fun w__0 : mword 64 => let vAddr := projT1 (emod_with_eq (Z.add (Z.add cursor (projT1 (uint w__0))) (Z.mul 16 (projT1 (sint offset)))) (projT1 (pow2 64))) in let vAddr64 := to_bits 64 vAddr in (if sumbool_of_bool (Z.gtb (Z.add vAddr cap_size) (projT1 (getCapTop cb_val))) then (raise_c2_exception CapEx_LengthViolation cb) : M (unit) else if sumbool_of_bool (Z.ltb vAddr (projT1 (getCapBase cb_val))) then (raise_c2_exception CapEx_LengthViolation cb) : M (unit) else if sumbool_of_bool (projT1 (neq_int (projT1 (emod_with_eq vAddr cap_size)) 0)) then (SignalExceptionBadAddr AdEL vAddr64) : M (unit) else (TLBTranslateC vAddr64 LoadData) >>= fun '(pAddr, macr) => (MEMr_tagged pAddr cap_size (andb cb_val.(Capability_permit_load_cap) (negb (generic_eq macr Clear)))) >>= fun '(tag, mem) => (if sumbool_of_bool (andb tag (generic_eq macr Trap)) then (raise_c2_exception_badaddr CapEx_TLBLoadCap cb vAddr64) : M (unit) else let cap := memBitsToCapability tag mem in (writeCapReg cd cap) : M (unit)) : M (unit)) : M (unit)) : M (unit). Definition execute_CJALR (cd : mword 5) (cb : mword 5) (link : bool) : M (unit) := (checkCP2usable tt) >> ((read_reg InBranchDelay_ref) : M (mword 1)) >>= fun w__0 : mword 1 => (if (bits_to_bool w__0) : bool then (SignalException ResI) : M (unit) else returnm tt) >> (readCapReg cb) >>= fun cb_val => let cb_ptr := projT1 (getCapCursor cb_val) in let cb_top := projT1 (getCapTop cb_val) in let cb_base := projT1 (getCapBase cb_val) in let sentry := isSentryCap cb_val in (if negb cb_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cb) : M (unit) else if sumbool_of_bool (andb cb_val.(Capability_sealed) (negb sentry)) then (raise_c2_exception CapEx_SealViolation cb) : M (unit) else if negb cb_val.(Capability_permit_execute) then (raise_c2_exception CapEx_PermitExecuteViolation cb) : M (unit) else if sumbool_of_bool (Z.ltb cb_ptr cb_base) then (raise_c2_exception CapEx_LengthViolation cb) : M (unit) else if sumbool_of_bool (Z.gtb (Z.add cb_ptr 4) cb_top) then (raise_c2_exception CapEx_LengthViolation cb) : M (unit) else if sumbool_of_bool (projT1 (neq_int (projT1 (emod_with_eq cb_ptr 4)) 0)) then (SignalException AdEL) : M (unit) else let cb_val : Capability := if sumbool_of_bool sentry then unsealCap cb_val else cb_val in (if sumbool_of_bool link then read_reg PCC_ref >>= fun w__1 : Capability => ((read_reg PC_ref) : M (mword 64)) >>= fun w__2 : mword 64 => let '(success, linkCap) := setCapOffset w__1 (add_vec_int w__2 8) in assert_exp' success "Link cap should always be representable." >>= fun _ => let '(success2, sealedLink) := sealCap linkCap (to_bits 24 otype_sentry) in assert_exp' success2 "Sealing should always be possible with current format." >>= fun _ => (writeCapReg cd sealedLink) : M (unit) else returnm tt) >> (execute_branch_pcc cb_val) : M (unit)) >> write_reg NextInBranchDelay_ref ('b"1" : mword 1) : M (unit). Definition execute_CIncOffsetImmediate (cd : mword 5) (cb : mword 5) (imm : mword 11) : M (unit) := (checkCP2usable tt) >> (readCapReg cb) >>= fun cb_val => let imm64 : bits 64 := mips_sign_extend 64 imm in (if andb cb_val.(Capability_tag) cb_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cb) : M (unit) else let '(success, newCap) := incCapOffset cb_val imm64 in (if sumbool_of_bool success then (writeCapReg cd newCap) : M (unit) else (writeCapReg cd (unrepCap newCap)) : M (unit)) : M (unit)) : M (unit). Definition execute_CIncOffset (cd : mword 5) (cb : mword 5) (rt : mword 5) : M (unit) := (checkCP2usable tt) >> (readCapReg cb) >>= fun cb_val => (rGPR rt) >>= fun rt_val => (if andb cb_val.(Capability_tag) cb_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cb) : M (unit) else let '(success, newCap) := incCapOffset cb_val rt_val in (if sumbool_of_bool success then (writeCapReg cd newCap) : M (unit) else (writeCapReg cd (unrepCap newCap)) : M (unit)) : M (unit)) : M (unit). Definition execute_CGetType (rd : mword 5) (cb : mword 5) : M (unit) := (checkCP2usable tt) >> (readCapReg cb) >>= fun capVal => (wGPR rd (if hasReservedOType capVal then mips_sign_extend 64 capVal.(Capability_otype) else mips_zero_extend 64 capVal.(Capability_otype))) : M (unit). Definition execute_CGetTag (rd : mword 5) (cb : mword 5) : M (unit) := (checkCP2usable tt) >> (readCapReg cb) >>= fun capVal => (wGPR rd (mips_zero_extend 64 (bool_to_bits capVal.(Capability_tag)))) : M (unit). Definition execute_CGetSealed (rd : mword 5) (cb : mword 5) : M (unit) := (checkCP2usable tt) >> (readCapReg cb) >>= fun capVal => (wGPR rd (mips_zero_extend 64 (bool_to_bits capVal.(Capability_sealed)))) : M (unit). Definition execute_CGetPerm (rd : mword 5) (cb : mword 5) : M (unit) := (checkCP2usable tt) >> (readCapReg cb) >>= fun capVal => (wGPR rd (mips_zero_extend 64 (getCapPerms capVal))) : M (unit). Definition execute_CGetPCCSetOffset (cd : mword 5) (rs : mword 5) : M (unit) := (checkCP2usable tt) >> (rGPR rs) >>= fun rs_val => read_reg PCC_ref >>= fun w__0 : Capability => let '(success, newPCC) := setCapOffset w__0 rs_val in (if sumbool_of_bool success then (writeCapReg cd newPCC) : M (unit) else (writeCapReg cd (unrepCap newPCC)) : M (unit)) : M (unit). Definition execute_CGetPCCSetAddr (cd : mword 5) (rs : mword 5) : M (unit) := (checkCP2usable tt) >> (rGPR rs) >>= fun rs_val => read_reg PCC_ref >>= fun w__0 : Capability => let '(success, newCap) := setCapAddr w__0 rs_val in (if sumbool_of_bool success then (writeCapReg cd newCap) : M (unit) else (writeCapReg cd (unrepCap newCap)) : M (unit)) : M (unit). Definition execute_CGetPCCIncOffset (cd : mword 5) (rs : mword 5) : M (unit) := (checkCP2usable tt) >> (rGPR rs) >>= fun rs_val => read_reg PCC_ref >>= fun w__0 : Capability => ((read_reg PC_ref) : M (mword 64)) >>= fun w__1 : mword 64 => let '(success, newCap) := setCapOffset w__0 (add_vec w__1 rs_val) in (if sumbool_of_bool success then (writeCapReg cd newCap) : M (unit) else (writeCapReg cd (unrepCap newCap)) : M (unit)) : M (unit). Definition execute_CGetPCC (cd : mword 5) : M (unit) := (checkCP2usable tt) >> read_reg PCC_ref >>= fun w__0 : Capability => ((read_reg PC_ref) : M (mword 64)) >>= fun w__1 : mword 64 => let '(success, pcc) := setCapOffset w__0 w__1 in assert_exp' success "PCC with offset PC should always be representable" >>= fun _ => (writeCapReg cd pcc) : M (unit). Definition execute_CGetOffset (rd : mword 5) (cb : mword 5) : M (unit) := (checkCP2usable tt) >> (readCapReg cb) >>= fun capVal => (wGPR rd (to_bits 64 (projT1 (getCapOffset capVal)))) : M (unit). Definition execute_CGetLen (rd : mword 5) (cb : mword 5) : M (unit) := (checkCP2usable tt) >> (readCapReg cb) >>= fun capVal => (getCapLength capVal) >>= fun '(existT _ len65 _) => (wGPR rd (to_bits 64 (if sumbool_of_bool (Z.gtb len65 MAX_U64) then MAX_U64 else len65))) : M (unit). Definition execute_CGetFlags (rd : mword 5) (cb : mword 5) : M (unit) := (checkCP2usable tt) >> (readCapReg cb) >>= fun capVal => (wGPR rd (mips_zero_extend 64 (getCapFlags capVal))) : M (unit). Definition execute_CGetCause (rd : mword 5) : M (unit) := (checkCP2usable tt) >> (pcc_access_system_regs tt) >>= fun w__0 : bool => (if sumbool_of_bool (negb w__0) then (raise_c2_exception_noreg CapEx_AccessSystemRegsViolation) : M (unit) else read_reg CapCause_ref >>= fun w__1 : CapCauseReg => (wGPR rd (mips_zero_extend 64 (_get_CapCauseReg_bits w__1))) : M (unit)) : M (unit). Definition execute_CGetCID (rd : mword 5) : M (unit) := (checkCP2usable tt) >> ((read_reg CID_ref) : M (mword 64)) >>= fun w__0 : mword 64 => (wGPR rd w__0) : M (unit). Definition execute_CGetBase (rd : mword 5) (cb : mword 5) : M (unit) := (checkCP2usable tt) >> (readCapReg cb) >>= fun capVal => (wGPR rd (to_bits 64 (projT1 (getCapBase capVal)))) : M (unit). Definition execute_CGetAndAddr (rd : mword 5) (cb : mword 5) (rs : mword 5) : M (unit) := (checkCP2usable tt) >> (readCapReg cb) >>= fun capVal => (rGPR rs) >>= fun rs_val => (wGPR rd (and_vec capVal.(Capability_address) rs_val)) : M (unit). Definition execute_CGetAddr (rd : mword 5) (cb : mword 5) : M (unit) := (checkCP2usable tt) >> (readCapReg cb) >>= fun capVal => (wGPR rd capVal.(Capability_address)) : M (unit). Definition execute_CFromPtr (cd : mword 5) (cb : mword 5) (rt : mword 5) : M (unit) := (checkCP2usable tt) >> (readCapRegDDC cb) >>= fun cb_val => (rGPR rt) >>= fun rt_val => (if eq_vec rt_val (Ox"0000000000000000" : mword 64) then (writeCapReg cd null_cap) : M (unit) else if negb cb_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cb) : M (unit) else if cb_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cb) : M (unit) else let '(success, newCap) := setCapOffset cb_val rt_val in (if sumbool_of_bool success then (writeCapReg cd newCap) : M (unit) else (writeCapReg cd (unrepCap newCap)) : M (unit)) : M (unit)) : M (unit). Definition execute_CCopyType (cd : mword 5) (cb : mword 5) (ct : mword 5) : M (unit) := (checkCP2usable tt) >> (readCapReg cb) >>= fun cb_val => (readCapReg ct) >>= fun ct_val => let cb_base := projT1 (getCapBase cb_val) in let cb_top := projT1 (getCapTop cb_val) in let ct_otype := projT1 (uint ct_val.(Capability_otype)) in (if negb cb_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cb) : M (unit) else if cb_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cb) : M (unit) else if orb (negb ct_val.(Capability_sealed)) (hasReservedOType ct_val) then (writeCapReg cd {[ null_cap with Capability_address := (mips_sign_extend 64 ct_val.(Capability_otype)) ]}) : M (unit) else if sumbool_of_bool (Z.ltb ct_otype cb_base) then (raise_c2_exception CapEx_LengthViolation cb) : M (unit) else if sumbool_of_bool (Z.geb ct_otype cb_top) then (raise_c2_exception CapEx_LengthViolation cb) : M (unit) else let '(success, cap) := setCapOffset cb_val (to_bits 64 (Z.sub ct_otype cb_base)) in assert_exp' success "CopyType: offset is in bounds so should be representable" >>= fun _ => (writeCapReg cd cap) : M (unit)) : M (unit). Definition execute_CClearTags (cb : mword 5) : M (unit) := (checkCP2usable tt) >> (readCapRegDDC cb) >>= fun cb_val => (if negb cb_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cb) : M (unit) else if cb_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cb) : M (unit) else if negb cb_val.(Capability_permit_store) then (raise_c2_exception CapEx_PermitStoreViolation cb) : M (unit) else let vAddr := projT1 (getCapCursor cb_val) in let vAddr64 := to_bits 64 (projT1 (getCapCursor cb_val)) in (if sumbool_of_bool (Z.gtb (Z.add vAddr (Z.mul caps_per_cacheline cap_size)) (projT1 (getCapTop cb_val))) then (raise_c2_exception CapEx_LengthViolation cb) : M (unit) else if sumbool_of_bool (Z.ltb vAddr (projT1 (getCapBase cb_val))) then (raise_c2_exception CapEx_LengthViolation cb) : M (unit) else if sumbool_of_bool (negb (Z.eqb (projT1 (emod_with_eq vAddr (Z.mul cap_size caps_per_cacheline))) 0)) then (SignalExceptionBadAddr AdEL vAddr64) : M (unit) else (TLBTranslate vAddr64 StoreData) >>= fun pAddr => let loop_i_lower := 0 in let loop_i_upper := Z.sub caps_per_cacheline 1 in (foreach_ZM_up loop_i_lower loop_i_upper 1 tt (fun i _ _ => (MEMr_tagged (add_vec_int pAddr (Z.mul i cap_size)) cap_size false) >>= fun '(_, mem) => (MEMw_tagged (add_vec_int pAddr (Z.mul i cap_size)) cap_size false mem) : M (unit)))) : M (unit)) : M (unit). Definition execute_CClearTag (cd : mword 5) (cb : mword 5) : M (unit) := (checkCP2usable tt) >> (readCapReg cb) >>= fun cb_val => (writeCapReg cd {[ cb_val with Capability_tag := false ]}) : M (unit). Definition execute_CCheckType (cs : mword 5) (cb : mword 5) : M (unit) := (checkCP2usable tt) >> (readCapReg cs) >>= fun cs_val => (readCapReg cb) >>= fun cb_val => (if negb cs_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cs) : M (unit) else if negb cb_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cb) : M (unit) else if orb (negb cs_val.(Capability_sealed)) (hasReservedOType cs_val) then (raise_c2_exception CapEx_SealViolation cs) : M (unit) else if orb (negb cb_val.(Capability_sealed)) (hasReservedOType cb_val) then (raise_c2_exception CapEx_SealViolation cb) : M (unit) else if neq_vec cs_val.(Capability_otype) cb_val.(Capability_otype) then (raise_c2_exception CapEx_TypeViolation cs) : M (unit) else returnm tt) : M (unit). Definition execute_CCheckTag (cs : mword 5) : M (unit) := (checkCP2usable tt) >> (readCapReg cs) >>= fun cs_val => (if negb cs_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cs) : M (unit) else returnm tt) : M (unit). Definition execute_CCheckPerm (cs : mword 5) (rt : mword 5) : M (unit) := (checkCP2usable tt) >> (readCapReg cs) >>= fun cs_val => let cs_perms : bits 64 := mips_zero_extend 64 (getCapPerms cs_val) in (rGPR rt) >>= fun rt_perms => (if negb cs_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cs) : M (unit) else if neq_vec (and_vec cs_perms rt_perms) rt_perms then (raise_c2_exception CapEx_UserDefViolation cs) : M (unit) else returnm tt) : M (unit). Definition execute_CCall (cs : mword 5) (cb : mword 5) (b__107 : mword 11) : M (unit) := (if eq_vec b__107 ('b"00000000000" : mword 11) then (checkCP2usable tt) >> ((read_reg InBranchDelay_ref) : M (mword 1)) >>= fun w__0 : mword 1 => (if (bits_to_bool w__0) : bool then (SignalException ResI) : M (unit) else returnm tt) >> (readCapReg cs) >>= fun cs_val => (readCapReg cb) >>= fun cb_val => let cs_cursor := projT1 (getCapCursor cs_val) in (if negb cs_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cs) : M (unit) else if negb cb_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cb) : M (unit) else if orb (negb cs_val.(Capability_sealed)) (hasReservedOType cs_val) then (raise_c2_exception CapEx_SealViolation cs) : M (unit) else if orb (negb cb_val.(Capability_sealed)) (hasReservedOType cb_val) then (raise_c2_exception CapEx_SealViolation cb) : M (unit) else if neq_vec cs_val.(Capability_otype) cb_val.(Capability_otype) then (raise_c2_exception CapEx_TypeViolation cs) : M (unit) else if negb cs_val.(Capability_permit_execute) then (raise_c2_exception CapEx_PermitExecuteViolation cs) : M (unit) else if cb_val.(Capability_permit_execute) then (raise_c2_exception CapEx_PermitExecuteViolation cb) : M (unit) else if sumbool_of_bool (Z.ltb cs_cursor (projT1 (getCapBase cs_val))) then (raise_c2_exception CapEx_LengthViolation cs) : M (unit) else if sumbool_of_bool (Z.geb cs_cursor (projT1 (getCapTop cs_val))) then (raise_c2_exception CapEx_LengthViolation cs) : M (unit) else (raise_c2_exception CapEx_CallTrap cs) : M (unit)) : M (unit) else if eq_vec b__107 ('b"00000000001" : mword 11) then (checkCP2usable tt) >> ((read_reg InBranchDelay_ref) : M (mword 1)) >>= fun w__1 : mword 1 => (if (bits_to_bool w__1) : bool then (SignalException ResI) : M (unit) else returnm tt) >> (readCapReg cs) >>= fun cs_val => (readCapReg cb) >>= fun cb_val => let cs_cursor := projT1 (getCapCursor cs_val) in (if negb cs_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cs) : M (unit) else if negb cb_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cb) : M (unit) else if hasReservedOType cs_val then (raise_c2_exception CapEx_SealViolation cs) : M (unit) else if hasReservedOType cb_val then (raise_c2_exception CapEx_SealViolation cb) : M (unit) else if neq_vec cs_val.(Capability_otype) cb_val.(Capability_otype) then (raise_c2_exception CapEx_TypeViolation cs) : M (unit) else if negb cs_val.(Capability_permit_ccall) then (raise_c2_exception CapEx_PermitCCallViolation cs) : M (unit) else if negb cb_val.(Capability_permit_ccall) then (raise_c2_exception CapEx_PermitCCallViolation cb) : M (unit) else if negb cs_val.(Capability_permit_execute) then (raise_c2_exception CapEx_PermitExecuteViolation cs) : M (unit) else if cb_val.(Capability_permit_execute) then (raise_c2_exception CapEx_PermitExecuteViolation cb) : M (unit) else if sumbool_of_bool (Z.ltb cs_cursor (projT1 (getCapBase cs_val))) then (raise_c2_exception CapEx_LengthViolation cs) : M (unit) else if sumbool_of_bool (Z.geb cs_cursor (projT1 (getCapTop cs_val))) then (raise_c2_exception CapEx_LengthViolation cs) : M (unit) else (set_next_pcc (unsealCap cs_val)) >> write_reg C26_ref (unsealCap cb_val) >> write_reg NextPC_ref (to_bits 64 (projT1 (getCapOffset cs_val))) : M (unit)) : M (unit) else assert_exp' false "Pattern match failure at ../mips/mips_ri.sail 41:16 - 45:1" >>= fun _ => exit tt) : M (unit). Definition execute_CCSeal (cd : mword 5) (cs : mword 5) (ct : mword 5) : M (unit) := (checkCP2usable tt) >> (readCapReg cs) >>= fun cs_val => (readCapReg ct) >>= fun ct_val => let ct_cursor := projT1 (getCapCursor ct_val) in let ct_top := projT1 (getCapTop ct_val) in let ct_base := projT1 (getCapBase ct_val) in (if negb cs_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cs) : M (unit) else if eq_vec ct_val.(Capability_address) otype_sentry_bits then (if cs_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cs) : M (unit) else if negb cs_val.(Capability_permit_execute) then (raise_c2_exception CapEx_PermitExecuteViolation cs) : M (unit) else let '(success, newCap) := sealCap cs_val (to_bits 24 otype_sentry) in (if sumbool_of_bool (negb success) then (raise_c2_exception CapEx_InexactBounds cs) : M (unit) else (writeCapReg cd newCap) : M (unit)) : M (unit)) : M (unit) else if orb (negb ct_val.(Capability_tag)) (eq_vec ct_val.(Capability_address) otype_unsealed_bits) then (writeCapReg cd cs_val) : M (unit) else if cs_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cs) : M (unit) else if ct_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation ct) : M (unit) else if negb ct_val.(Capability_permit_seal) then (raise_c2_exception CapEx_PermitSealViolation ct) : M (unit) else if sumbool_of_bool (Z.ltb ct_cursor ct_base) then (raise_c2_exception CapEx_LengthViolation ct) : M (unit) else if sumbool_of_bool (Z.geb ct_cursor ct_top) then (raise_c2_exception CapEx_LengthViolation ct) : M (unit) else if sumbool_of_bool (Z.gtb ct_cursor max_otype) then (raise_c2_exception CapEx_TypeViolation ct) : M (unit) else let '(success, newCap) := sealCap cs_val (to_bits 24 ct_cursor) in (if sumbool_of_bool (negb success) then (raise_c2_exception CapEx_InexactBounds cs) : M (unit) else (writeCapReg cd newCap) : M (unit)) : M (unit)) : M (unit). Definition execute_CBuildCap (cd : mword 5) (cb : mword 5) (ct : mword 5) : M (unit) := (checkCP2usable tt) >> (readCapRegDDC cb) >>= fun cb_val => (readCapReg ct) >>= fun ct_val => let cb_base := projT1 (getCapBase cb_val) in let ct_base := projT1 (getCapBase ct_val) in let cb_top := projT1 (getCapTop cb_val) in let ct_top := projT1 (getCapTop ct_val) in let cb_perms := getCapPerms cb_val in let ct_perms := getCapPerms ct_val in let ct_offset := projT1 (getCapOffset ct_val) in (if negb cb_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cb) : M (unit) else if cb_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cb) : M (unit) else if sumbool_of_bool (Z.ltb ct_base cb_base) then (raise_c2_exception CapEx_LengthViolation cb) : M (unit) else if sumbool_of_bool (Z.gtb ct_top cb_top) then (raise_c2_exception CapEx_LengthViolation cb) : M (unit) else if sumbool_of_bool (Z.gtb ct_base ct_top) then (raise_c2_exception CapEx_LengthViolation ct) : M (unit) else if neq_vec (and_vec ct_perms cb_perms) ct_perms then (raise_c2_exception CapEx_UserDefViolation cb) : M (unit) else let '(exact, cd1) := setCapBounds cb_val (to_bits 64 ct_base) (to_bits 65 ct_top) in let '(representable, cd2) := setCapOffset cd1 (to_bits 64 ct_offset) in let cd3 := setCapPerms cd2 ct_perms in assert_exp' exact "CBuildCap: setCapBounds was not exact" >>= fun _ => assert_exp' representable "CBuildCap: offset was not representable" >>= fun _ => (writeCapReg cd cd3) : M (unit)) : M (unit). Definition execute_CBZ (cb : mword 5) (imm : mword 16) (notzero : bool) : M (unit) := (checkCP2usable tt) >> ((read_reg InBranchDelay_ref) : M (mword 1)) >>= fun w__0 : mword 1 => (if (bits_to_bool w__0) : bool then (SignalException ResI) : M (unit) else returnm tt) >> (readCapReg cb) >>= fun cb_val => (if (bits_to_bool (xor_vec (bool_to_bits (eq_vec cb_val.(Capability_address) (zeros_implicit 64 tt))) ((bool_to_bits notzero) : mword 1))) : bool then let offset : bits 64 := add_vec_int (mips_sign_extend 64 (concat_vec imm ('b"00" : mword 2))) 4 in ((read_reg PC_ref) : M (mword 64)) >>= fun w__1 : mword 64 => (execute_branch (add_vec w__1 offset)) : M (unit) else returnm tt) >> write_reg NextInBranchDelay_ref ('b"1" : mword 1) : M (unit). Definition execute_CBX (cb : mword 5) (imm : mword 16) (notset : bool) : M (unit) := (checkCP2usable tt) >> ((read_reg InBranchDelay_ref) : M (mword 1)) >>= fun w__0 : mword 1 => (if (bits_to_bool w__0) : bool then (SignalException ResI) : M (unit) else returnm tt) >> (readCapReg cb) >>= fun cb_val => (if (bits_to_bool (xor_vec (bool_to_bits cb_val.(Capability_tag)) ((bool_to_bits notset) : mword 1))) : bool then let offset : bits 64 := add_vec_int (mips_sign_extend 64 (concat_vec imm ('b"00" : mword 2))) 4 in ((read_reg PC_ref) : M (mword 64)) >>= fun w__1 : mword 64 => (execute_branch (add_vec w__1 offset)) : M (unit) else returnm tt) >> write_reg NextInBranchDelay_ref ('b"1" : mword 1) : M (unit). Definition execute_CAndPerm (cd : mword 5) (cb : mword 5) (rt : mword 5) : M (unit) := (checkCP2usable tt) >> (readCapReg cb) >>= fun cb_val => (rGPR rt) >>= fun rt_val => (if negb cb_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cb) : M (unit) else if cb_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cb) : M (unit) else let perms := getCapPerms cb_val in let newCap := setCapPerms cb_val (and_vec perms (subrange_vec_dec rt_val 30 0)) in (writeCapReg cd newCap) : M (unit)) : M (unit). Definition execute_CAndAddr (cd : mword 5) (cb : mword 5) (rt : mword 5) : M (unit) := (checkCP2usable tt) >> (readCapReg cb) >>= fun cb_val => (rGPR rt) >>= fun rt_val => (if andb cb_val.(Capability_tag) cb_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cb) : M (unit) else let newAddr := and_vec cb_val.(Capability_address) rt_val in let '(representable, newCap) := setCapAddr cb_val newAddr in (if sumbool_of_bool representable then (writeCapReg cd newCap) : M (unit) else (writeCapReg cd (unrepCap newCap)) : M (unit)) : M (unit)) : M (unit). Definition execute_CACHE (base : mword 5) (op : mword 5) (imm : mword 16) : M (unit) := (checkCP0Access tt) : M (unit). Definition execute_C2Dump (rt : mword 5) : unit := tt. Definition execute_BREAK '(tt : unit) : M (unit) := (SignalException Bp) : M (unit). Definition execute_BEQ (rs : mword 5) (rd : mword 5) (imm : mword 16) (ne : bool) (likely : bool) : M (unit) := ((read_reg InBranchDelay_ref) : M (mword 1)) >>= fun w__0 : mword 1 => (if (bits_to_bool w__0) : bool then (SignalException ResI) : M (unit) else returnm tt) >> (rGPR rs) >>= fun w__1 : mword 64 => (rGPR rd) >>= fun w__2 : mword 64 => (if (bits_to_bool (xor_vec (bool_to_bits (eq_vec w__1 w__2)) ((bool_to_bits ne) : mword 1))) : bool then let offset : bits 64 := add_vec_int (mips_sign_extend 64 (concat_vec imm ('b"00" : mword 2))) 4 in ((read_reg PC_ref) : M (mword 64)) >>= fun w__3 : mword 64 => (execute_branch (add_vec w__3 offset)) : M (unit) else if sumbool_of_bool likely then ((read_reg PC_ref) : M (mword 64)) >>= fun w__4 : mword 64 => write_reg NextPC_ref (add_vec_int w__4 8) : M (unit) else write_reg NextInBranchDelay_ref ('b"1" : mword 1) : M (unit)) : M (unit). Definition execute_BCMPZ (rs : mword 5) (imm : mword 16) (cmp : Comparison) (link : bool) (likely : bool) : M (unit) := ((read_reg InBranchDelay_ref) : M (mword 1)) >>= fun w__0 : mword 1 => (if (bits_to_bool w__0) : bool then (SignalException ResI) : M (unit) else returnm tt) >> ((read_reg PC_ref) : M (mword 64)) >>= fun w__1 : mword 64 => let linkVal := add_vec_int w__1 8 in (rGPR rs) >>= fun regVal => let condition := compare cmp regVal (mips_zero_extend 64 ('b"0" : mword 1)) in (if sumbool_of_bool condition then let offset : bits 64 := add_vec_int (mips_sign_extend 64 (concat_vec imm ('b"00" : mword 2))) 4 in ((read_reg PC_ref) : M (mword 64)) >>= fun w__2 : mword 64 => (execute_branch (add_vec w__2 offset)) : M (unit) else if sumbool_of_bool likely then ((read_reg PC_ref) : M (mword 64)) >>= fun w__3 : mword 64 => write_reg NextPC_ref (add_vec_int w__3 8) : M (unit) else write_reg NextInBranchDelay_ref ('b"1" : mword 1) : M (unit)) >> (if sumbool_of_bool link then (wGPR ('b"11111" : mword 5) linkVal) : M (unit) else returnm tt) : M (unit). Definition execute_ANDI (rs : mword 5) (rt : mword 5) (imm : mword 16) : M (unit) := (rGPR rs) >>= fun w__0 : mword 64 => (wGPR rt (and_vec w__0 (mips_zero_extend 64 imm))) : M (unit). Definition execute_AND (rs : mword 5) (rt : mword 5) (rd : mword 5) : M (unit) := (rGPR rs) >>= fun w__0 : mword 64 => (rGPR rt) >>= fun w__1 : mword 64 => (wGPR rd (and_vec w__0 w__1)) : M (unit). Definition execute_ADDU (rs : mword 5) (rt : mword 5) (rd : mword 5) : M (unit) := (rGPR rs) >>= fun opA => (rGPR rt) >>= fun opB => (if orb (NotWordVal opA) (NotWordVal opB) then (undefined_bitvector 64) >>= fun w__0 : mword 64 => (wGPR rd w__0) : M (unit) else (wGPR rd (mips_sign_extend 64 (add_vec (subrange_vec_dec opA 31 0) (subrange_vec_dec opB 31 0)))) : M (unit)) : M (unit). Definition execute_ADDIU (rs : mword 5) (rt : mword 5) (imm : mword 16) : M (unit) := (rGPR rs) >>= fun opA => (if NotWordVal opA then (undefined_bitvector 64) >>= fun w__0 : mword 64 => (wGPR rt w__0) : M (unit) else (wGPR rt (mips_sign_extend 64 (add_vec (subrange_vec_dec opA 31 0) (mips_sign_extend (Z.add (Z.sub 31 0) 1) imm)))) : M (unit)) : M (unit). Definition execute_ADDI (rs : mword 5) (rt : mword 5) (imm : mword 16) : M (unit) := (rGPR rs) >>= fun opA => (if NotWordVal opA then (undefined_bitvector 64) >>= fun w__0 : mword 64 => (wGPR rt w__0) : M (unit) else let sum33 : bits 33 := add_vec (mips_sign_extend 33 (subrange_vec_dec opA 31 0)) (mips_sign_extend 33 imm) in (if neq_bool (bit_to_bool (access_vec_dec sum33 32)) (bit_to_bool (access_vec_dec sum33 31)) then (SignalException Ov) : M (unit) else (wGPR rt (mips_sign_extend 64 (subrange_vec_dec sum33 31 0))) : M (unit)) : M (unit)) : M (unit). Definition execute_ADD (rs : mword 5) (rt : mword 5) (rd : mword 5) : M (unit) := (rGPR rs) >>= fun opA : bits 64 => (rGPR rt) >>= fun opB : bits 64 => (if orb (NotWordVal opA) (NotWordVal opB) then (undefined_bitvector 64) >>= fun w__0 : mword 64 => (wGPR rd w__0) : M (unit) else let sum33 : bits 33 := add_vec (mips_sign_extend 33 (subrange_vec_dec opA 31 0)) (mips_sign_extend 33 (subrange_vec_dec opB 31 0)) in (if neq_bool (bit_to_bool (access_vec_dec sum33 32)) (bit_to_bool (access_vec_dec sum33 31)) then (SignalException Ov) : M (unit) else (wGPR rd (mips_sign_extend 64 (subrange_vec_dec sum33 31 0))) : M (unit)) : M (unit)) : M (unit). Definition execute_measure (instr : ast) : Z := match instr with | CLCNT (cd, cb, rt) => 1 | _ => 0 end. Fixpoint _rec_execute (merge_var : ast) (_reclimit : Z) (_acc : Acc (Zwf 0) _reclimit) {struct _acc} : M (unit). exact ( assert_exp' (Z.geb _reclimit 0) "recursion limit reached" >>= fun _ => (match merge_var with | CLCNT (cd, cb, rt) => (_rec_execute (CLC (cd, cb, rt, to_bits 11 0)) (Z.sub _reclimit 1) (_limit_reduces _acc)) : M (unit) | DADDIU (rs, rt, imm) => (execute_DADDIU rs rt imm) : M (unit) | DADDU (rs, rt, rd) => (execute_DADDU rs rt rd) : M (unit) | DADDI (rs, rt, imm) => (execute_DADDI rs rt imm) : M (unit) | DADD (rs, rt, rd) => (execute_DADD rs rt rd) : M (unit) | ADD (rs, rt, rd) => (execute_ADD rs rt rd) : M (unit) | ADDI (rs, rt, imm) => (execute_ADDI rs rt imm) : M (unit) | ADDU (rs, rt, rd) => (execute_ADDU rs rt rd) : M (unit) | ADDIU (rs, rt, imm) => (execute_ADDIU rs rt imm) : M (unit) | DSUBU (rs, rt, rd) => (execute_DSUBU rs rt rd) : M (unit) | DSUB (rs, rt, rd) => (execute_DSUB rs rt rd) : M (unit) | SUB (rs, rt, rd) => (execute_SUB rs rt rd) : M (unit) | SUBU (rs, rt, rd) => (execute_SUBU rs rt rd) : M (unit) | AND (rs, rt, rd) => (execute_AND rs rt rd) : M (unit) | ANDI (rs, rt, imm) => (execute_ANDI rs rt imm) : M (unit) | OR (rs, rt, rd) => (execute_OR rs rt rd) : M (unit) | ORI (rs, rt, imm) => (execute_ORI rs rt imm) : M (unit) | NOR (rs, rt, rd) => (execute_NOR rs rt rd) : M (unit) | XOR (rs, rt, rd) => (execute_XOR rs rt rd) : M (unit) | XORI (rs, rt, imm) => (execute_XORI rs rt imm) : M (unit) | LUI (rt, imm) => (execute_LUI rt imm) : M (unit) | DSLL (rt, rd, sa) => (execute_DSLL rt rd sa) : M (unit) | DSLL32 (rt, rd, sa) => (execute_DSLL32 rt rd sa) : M (unit) | DSLLV (rs, rt, rd) => (execute_DSLLV rs rt rd) : M (unit) | DSRA (rt, rd, sa) => (execute_DSRA rt rd sa) : M (unit) | DSRA32 (rt, rd, sa) => (execute_DSRA32 rt rd sa) : M (unit) | DSRAV (rs, rt, rd) => (execute_DSRAV rs rt rd) : M (unit) | DSRL (rt, rd, sa) => (execute_DSRL rt rd sa) : M (unit) | DSRL32 (rt, rd, sa) => (execute_DSRL32 rt rd sa) : M (unit) | DSRLV (rs, rt, rd) => (execute_DSRLV rs rt rd) : M (unit) | SLL (rt, rd, sa) => (execute_SLL rt rd sa) : M (unit) | SLLV (rs, rt, rd) => (execute_SLLV rs rt rd) : M (unit) | SRA (rt, rd, sa) => (execute_SRA rt rd sa) : M (unit) | SRAV (rs, rt, rd) => (execute_SRAV rs rt rd) : M (unit) | SRL (rt, rd, sa) => (execute_SRL rt rd sa) : M (unit) | SRLV (rs, rt, rd) => (execute_SRLV rs rt rd) : M (unit) | SLT (rs, rt, rd) => (execute_SLT rs rt rd) : M (unit) | SLTI (rs, rt, imm) => (execute_SLTI rs rt imm) : M (unit) | SLTU (rs, rt, rd) => (execute_SLTU rs rt rd) : M (unit) | SLTIU (rs, rt, imm) => (execute_SLTIU rs rt imm) : M (unit) | MOVN (rs, rt, rd) => (execute_MOVN rs rt rd) : M (unit) | MOVZ (rs, rt, rd) => (execute_MOVZ rs rt rd) : M (unit) | MFHI rd => (execute_MFHI rd) : M (unit) | MFLO rd => (execute_MFLO rd) : M (unit) | MTHI rs => (execute_MTHI rs) : M (unit) | MTLO rs => (execute_MTLO rs) : M (unit) | MUL (rs, rt, rd) => (execute_MUL rs rt rd) : M (unit) | MULT (rs, rt) => (execute_MULT rs rt) : M (unit) | MULTU (rs, rt) => (execute_MULTU rs rt) : M (unit) | DMULT (rs, rt) => (execute_DMULT rs rt) : M (unit) | DMULTU (rs, rt) => (execute_DMULTU rs rt) : M (unit) | MADD (rs, rt) => (execute_MADD rs rt) : M (unit) | MADDU (rs, rt) => (execute_MADDU rs rt) : M (unit) | MSUB (rs, rt) => (execute_MSUB rs rt) : M (unit) | MSUBU (rs, rt) => (execute_MSUBU rs rt) : M (unit) | DIV (rs, rt) => (execute_DIV rs rt) : M (unit) | DIVU (rs, rt) => (execute_DIVU rs rt) : M (unit) | DDIV (rs, rt) => (execute_DDIV rs rt) : M (unit) | DDIVU (rs, rt) => (execute_DDIVU rs rt) : M (unit) | J offset => (execute_J offset) : M (unit) | JAL offset => (execute_JAL offset) : M (unit) | JR rs => (execute_JR rs) : M (unit) | JALR (rs, rd) => (execute_JALR rs rd) : M (unit) | BEQ (rs, rd, imm, ne, likely) => (execute_BEQ rs rd imm ne likely) : M (unit) | BCMPZ (rs, imm, cmp, link, likely) => (execute_BCMPZ rs imm cmp link likely) : M (unit) | SYSCALL arg0 => (execute_SYSCALL arg0) : M (unit) | BREAK arg0 => (execute_BREAK arg0) : M (unit) | WAIT arg0 => (execute_WAIT arg0) : M (unit) | TRAPREG (rs, rt, cmp) => (execute_TRAPREG rs rt cmp) : M (unit) | TRAPIMM (rs, imm, cmp) => (execute_TRAPIMM rs imm cmp) : M (unit) | Load (width, sign, linked, base, rt, offset) => (execute_Load width sign linked base rt offset) : M (unit) | Store (width, conditional, base, rt, offset) => (execute_Store width conditional base rt offset) : M (unit) | LWL (base, rt, offset) => (execute_LWL base rt offset) : M (unit) | LWR (base, rt, offset) => (execute_LWR base rt offset) : M (unit) | SWL (base, rt, offset) => (execute_SWL base rt offset) : M (unit) | SWR (base, rt, offset) => (execute_SWR base rt offset) : M (unit) | LDL (base, rt, offset) => (execute_LDL base rt offset) : M (unit) | LDR (base, rt, offset) => (execute_LDR base rt offset) : M (unit) | SDL (base, rt, offset) => (execute_SDL base rt offset) : M (unit) | SDR (base, rt, offset) => (execute_SDR base rt offset) : M (unit) | CACHE (base, op, imm) => (execute_CACHE base op imm) : M (unit) | SYNC arg0 => (execute_SYNC arg0) : M (unit) | MFC0 (rt, rd, sel, double) => (execute_MFC0 rt rd sel double) : M (unit) | HCF arg0 => returnm (execute_HCF arg0) | MTC0 (rt, rd, sel, double) => (execute_MTC0 rt rd sel double) : M (unit) | TLBWI arg0 => (execute_TLBWI arg0) : M (unit) | TLBWR arg0 => (execute_TLBWR arg0) : M (unit) | TLBR arg0 => (execute_TLBR arg0) : M (unit) | TLBP arg0 => (execute_TLBP arg0) : M (unit) | RDHWR (rt, rd) => (execute_RDHWR rt rd) : M (unit) | ERET arg0 => (execute_ERET arg0) : M (unit) | CGetPerm (rd, cb) => (execute_CGetPerm rd cb) : M (unit) | CGetFlags (rd, cb) => (execute_CGetFlags rd cb) : M (unit) | CGetType (rd, cb) => (execute_CGetType rd cb) : M (unit) | CGetBase (rd, cb) => (execute_CGetBase rd cb) : M (unit) | CGetOffset (rd, cb) => (execute_CGetOffset rd cb) : M (unit) | CGetLen (rd, cb) => (execute_CGetLen rd cb) : M (unit) | CGetTag (rd, cb) => (execute_CGetTag rd cb) : M (unit) | CGetSealed (rd, cb) => (execute_CGetSealed rd cb) : M (unit) | CGetAddr (rd, cb) => (execute_CGetAddr rd cb) : M (unit) | CGetAndAddr (rd, cb, rs) => (execute_CGetAndAddr rd cb rs) : M (unit) | CGetPCC cd => (execute_CGetPCC cd) : M (unit) | CGetPCCSetOffset (cd, rs) => (execute_CGetPCCSetOffset cd rs) : M (unit) | CGetPCCIncOffset (cd, rs) => (execute_CGetPCCIncOffset cd rs) : M (unit) | CGetPCCSetAddr (cd, rs) => (execute_CGetPCCSetAddr cd rs) : M (unit) | CGetCause rd => (execute_CGetCause rd) : M (unit) | CSetCause rt => (execute_CSetCause rt) : M (unit) | CGetCID rd => (execute_CGetCID rd) : M (unit) | CSetCID cb => (execute_CSetCID cb) : M (unit) | CRAP (rt, rs) => (execute_CRAP rt rs) : M (unit) | CRAM (rt, rs) => (execute_CRAM rt rs) : M (unit) | CReadHwr (cd, sel) => (execute_CReadHwr cd sel) : M (unit) | CWriteHwr (cb, sel) => (execute_CWriteHwr cb sel) : M (unit) | CAndPerm (cd, cb, rt) => (execute_CAndPerm cd cb rt) : M (unit) | CSetFlags (cd, cb, rt) => (execute_CSetFlags cd cb rt) : M (unit) | CToPtr (rd, cb, ct) => (execute_CToPtr rd cb ct) : M (unit) | CSub (rd, cb, ct) => (execute_CSub rd cb ct) : M (unit) | CPtrCmp (rd, cb, ct, op) => (execute_CPtrCmp rd cb ct op) : M (unit) | CIncOffset (cd, cb, rt) => (execute_CIncOffset cd cb rt) : M (unit) | CIncOffsetImmediate (cd, cb, imm) => (execute_CIncOffsetImmediate cd cb imm) : M (unit) | CSetOffset (cd, cb, rt) => (execute_CSetOffset cd cb rt) : M (unit) | CSetAddr (cd, cb, rt) => (execute_CSetAddr cd cb rt) : M (unit) | CAndAddr (cd, cb, rt) => (execute_CAndAddr cd cb rt) : M (unit) | CSetBounds (cd, cb, rt) => (execute_CSetBounds cd cb rt) : M (unit) | CSetBoundsImmediate (cd, cb, imm) => (execute_CSetBoundsImmediate cd cb imm) : M (unit) | CSetBoundsExact (cd, cb, rt) => (execute_CSetBoundsExact cd cb rt) : M (unit) | CClearTag (cd, cb) => (execute_CClearTag cd cb) : M (unit) | CMOVX (cd, cb, rt, ismovn) => (execute_CMOVX cd cb rt ismovn) : M (unit) | CMove (cd, cb) => (execute_CMove cd cb) : M (unit) | ClearRegs (regset, m) => (execute_ClearRegs regset m) : M (unit) | CFromPtr (cd, cb, rt) => (execute_CFromPtr cd cb rt) : M (unit) | CBuildCap (cd, cb, ct) => (execute_CBuildCap cd cb ct) : M (unit) | CCopyType (cd, cb, ct) => (execute_CCopyType cd cb ct) : M (unit) | CCheckPerm (cs, rt) => (execute_CCheckPerm cs rt) : M (unit) | CCheckType (cs, cb) => (execute_CCheckType cs cb) : M (unit) | CCheckTag cs => (execute_CCheckTag cs) : M (unit) | CTestSubset (rd, cb, ct) => (execute_CTestSubset rd cb ct) : M (unit) | CSeal (cd, cs, ct) => (execute_CSeal cd cs ct) : M (unit) | CCSeal (cd, cs, ct) => (execute_CCSeal cd cs ct) : M (unit) | CSealEntry (cd, cs) => (execute_CSealEntry cd cs) : M (unit) | CUnseal (cd, cs, ct) => (execute_CUnseal cd cs ct) : M (unit) | CCall (cs, cb, b__107) => (execute_CCall cs cb b__107) : M (unit) | CReturn arg0 => (execute_CReturn arg0) : M (unit) | CBX (cb, imm, notset) => (execute_CBX cb imm notset) : M (unit) | CBZ (cb, imm, notzero) => (execute_CBZ cb imm notzero) : M (unit) | CJALR (cd, cb, link) => (execute_CJALR cd cb link) : M (unit) | CLoad (rd, cb, rt, offset, signext, width) => (execute_CLoad rd cb rt offset signext width) : M (unit) | CLoadLinked (rd, cb, signext, width) => (execute_CLoadLinked rd cb signext width) : M (unit) | CLoadTags (rd, cb) => (execute_CLoadTags rd cb) : M (unit) | CStore (rs, cb, rt, offset, width) => (execute_CStore rs cb rt offset width) : M (unit) | CStoreConditional (rs, cb, rd, width) => (execute_CStoreConditional rs cb rd width) : M (unit) | CSC (cs, cb, rt, offset) => (execute_CSC cs cb rt offset) : M (unit) | CSCC (cs, cb, rd) => (execute_CSCC cs cb rd) : M (unit) | CLC (cd, cb, rt, offset) => (execute_CLC cd cb rt offset) : M (unit) | CLCBI (cd, cb, offset) => (execute_CLCBI cd cb offset) : M (unit) | CLLC (cd, cb) => (execute_CLLC cd cb) : M (unit) | CClearTags cb => (execute_CClearTags cb) : M (unit) | C2Dump rt => returnm (execute_C2Dump rt) | RI arg0 => (execute_RI arg0) : M (unit) end) : M (unit) ). Defined. Definition execute (i : ast) : M (unit) := (_rec_execute i ((execute_measure i) : Z) (Zwf_guarded _)) : M (unit). Definition assembly (merge_var : ast) : string := match merge_var with | DADDIU (rs, rt, imm) => String.append "daddiu " (strRRIArgs rs rt imm) | DADDU (rs, rt, rd) => String.append "daddu " (strRRRArgs rs rt rd) | DADDI (rs, rt, imm) => String.append "daddi " (strRRIArgs rs rt imm) | DADD (rs, rt, rd) => String.append "dadd " (strRRRArgs rs rt rd) | ADD (rs, rt, rd) => String.append "add " (strRRRArgs rs rt rd) | ADDI (rs, rt, imm) => String.append "addi " (strRRIArgs rs rt imm) | ADDU (rs, rt, rd) => String.append "addu " (strRRRArgs rs rt rd) | ADDIU (rs, rt, imm) => String.append "addiu " (strRRIArgs rs rt imm) | DSUBU (rs, rt, rd) => String.append "dsubu " (strRRRArgs rs rt rd) | DSUB (rs, rt, rd) => String.append "dsub " (strRRRArgs rs rt rd) | SUB (rs, rt, rd) => String.append "sub " (strRRRArgs rs rt rd) | SUBU (rs, rt, rd) => String.append "subu " (strRRRArgs rs rt rd) | AND (rs, rt, rd) => String.append "and " (strRRRArgs rs rt rd) | ANDI (rs, rt, imm) => String.append "andi " (strRRIUArgs rs rt imm) | OR (rs, rt, rd) => String.append "or " (strRRRArgs rs rt rd) | ORI (rs, rt, imm) => String.append "ori " (strRRIUArgs rs rt imm) | NOR (rs, rt, rd) => String.append "nor " (strRRRArgs rs rt rd) | XOR (rs, rt, rd) => String.append "xor " (strRRRArgs rs rt rd) | XORI (rs, rt, imm) => String.append "xori " (strRRIUArgs rs rt imm) | LUI (rt, imm) => String.append "lui " (strRIArgs rt imm) | DSLL (rs, rd, sa) => String.append "dsll " (strRRIUArgs rs rd sa) | DSLL32 (rs, rd, sa) => String.append "dsll32 " (strRRIUArgs rs rd sa) | DSLLV (rs, rt, rd) => String.append "dsllv " (strRRRArgs rs rt rd) | DSRA (rt, rd, sa) => String.append "dsra " (strRRIUArgs rt rd sa) | DSRA32 (rt, rd, sa) => String.append "dsra32 " (strRRIUArgs rt rd sa) | DSRAV (rs, rt, rd) => String.append "dsrav " (strRRRArgs rs rt rd) | DSRL (rt, rd, sa) => String.append "dsrl " (strRRIUArgs rt rd sa) | DSRL32 (rt, rd, sa) => String.append "dsrl32 " (strRRIUArgs rt rd sa) | DSRLV (rs, rt, rd) => String.append "dsrlv " (strRRRArgs rs rt rd) | SLL (rt, rd, sa) => String.append "sll " (strRRIUArgs rt rd sa) | SLLV (rs, rt, rd) => String.append "sllv " (strRRRArgs rs rt rd) | SRA (rt, rd, sa) => String.append "sra " (strRRIUArgs rt rd sa) | SRAV (rs, rt, rd) => String.append "srav " (strRRRArgs rs rt rd) | SRL (rt, rd, sa) => String.append "srl " (strRRIUArgs rt rd sa) | SRLV (rs, rt, rd) => String.append "srlv " (strRRRArgs rs rt rd) | SLT (rs, rt, rd) => String.append "slt " (strRRRArgs rs rt rd) | SLTI (rs, rd, imm) => String.append "slti " (strRRIArgs rs rd imm) | SLTU (rs, rt, rd) => String.append "sltu " (strRRRArgs rs rt rd) | SLTIU (rs, rd, imm) => String.append "sltiu " (strRRIUArgs rs rd imm) | MOVN (rs, rt, rd) => String.append "movn " (strRRRArgs rs rt rd) | MOVZ (rs, rt, rd) => String.append "movz " (strRRRArgs rs rt rd) | MFHI rd => String.append "mfhi " (strReg rd) | MFLO rd => String.append "mflo " (strReg rd) | MTHI rs => String.append "mthi " (strReg rs) | MTLO rs => String.append "mtlo " (strReg rs) | MUL (rs, rt, rd) => String.append "mul " (strRRRArgs rs rt rd) | MULT (rs, rt) => String.append "mult " (String.append (strReg rs) (String.append ", " (strReg rt))) | MULTU (rs, rt) => String.append "multu " (String.append (strReg rs) (String.append ", " (strReg rt))) | DMULT (rs, rt) => String.append "dmult " (String.append (strReg rs) (String.append ", " (strReg rt))) | DMULTU (rs, rt) => String.append "dmultu " (String.append (strReg rs) (String.append ", " (strReg rt))) | MADD (rs, rt) => String.append "madd " (String.append (strReg rs) (String.append ", " (strReg rt))) | MADDU (rs, rt) => String.append "maddu " (String.append (strReg rs) (String.append ", " (strReg rt))) | MSUB (rs, rt) => String.append "msub " (String.append (strReg rs) (String.append ", " (strReg rt))) | MSUBU (rs, rt) => String.append "msubu " (String.append (strReg rs) (String.append ", " (strReg rt))) | DIV (rs, rt) => String.append "div " (String.append (strReg rs) (String.append ", " (strReg rt))) | DIVU (rs, rt) => String.append "divu " (String.append (strReg rs) (String.append ", " (strReg rt))) | DDIV (rs, rt) => String.append "ddiv " (String.append (strReg rs) (String.append ", " (strReg rt))) | DDIVU (rs, rt) => String.append "ddivu " (String.append (strReg rs) (String.append ", " (strReg rt))) | J offset => String.append "j " (hex_str (projT1 (uint offset))) | JAL offset => String.append "jal " (hex_str (projT1 (uint offset))) | JR rs => String.append "jr " (strReg rs) | JALR (rs, rd) => String.append "jalr " (String.append (strReg rd) (String.append ", " (strReg rs))) | BEQ (rs, rt, imm, ne, likely) => let op := if sumbool_of_bool ne then "bne" else "beq" in let l := if sumbool_of_bool likely then "l " else " " in String.append op (String.append l (String.append (strReg rs) (String.append ", " (String.append (strReg rt) (String.append ", " (hex_str (projT1 (sint imm)))))))) | BCMPZ (rs, imm, cmp, link, likely) => let op := String.append "b" (String.append (strCmp cmp) "z") in let al := if sumbool_of_bool link then "al" else "" in let l := if sumbool_of_bool likely then "l " else " " in String.append op (String.append al (String.append l (String.append (strReg rs) (String.append ", " (hex_str (projT1 (sint imm))))))) | SYSCALL tt => "syscall" | BREAK tt => "break" | WAIT tt => "wait" | TRAPREG (rs, rt, cmp) => let op := String.append "t" (String.append (strCmp cmp) " ") in String.append op (String.append (strReg rs) (String.append ", " (strReg rt))) | TRAPIMM (rs, imm, cmp) => let op := String.append "t" (String.append (strCmp cmp) "i ") in String.append op (String.append (strReg rs) (String.append ", " (hex_str (projT1 (uint imm))))) | Load (width, sign, linked, base, rt, offset) => let op : string := match (width, sign, linked) with | (B, true, false) => "lb " | (B, false, false) => "lbu " | (H, true, false) => "lh " | (H, false, false) => "lhu " | (W, true, false) => "lw " | (W, false, false) => "lwu " | (D, false, false) => "ld " | (W, true, true) => "ll " | (D, false, true) => "lld " | _ => "invalid load" end in String.append op (strMemArgs base rt offset) | Store (width, conditional, base, rt, offset) => let op : string := if sumbool_of_bool conditional then match width with | W => "sc" | D => "scd" | _ => "invalid sc" end else String.append "s" (strWordType width) in String.append op (String.append " " (strMemArgs base rt offset)) | LWL (base, rt, offset) => String.append "lwl " (strMemArgs base rt offset) | LWR (base, rt, offset) => String.append "lwr " (strMemArgs base rt offset) | SWL (base, rt, offset) => String.append "swl " (strMemArgs base rt offset) | SWR (base, rt, offset) => String.append "swr " (strMemArgs base rt offset) | LDL (base, rt, offset) => String.append "ldl " (strMemArgs base rt offset) | LDR (base, rt, offset) => String.append "ldr " (strMemArgs base rt offset) | SDL (base, rt, offset) => String.append "sdl " (strMemArgs base rt offset) | SDR (base, rt, offset) => String.append "sdr " (strMemArgs base rt offset) | CACHE (base, op, imm) => String.append "cache " (strMemArgs base op imm) | SYNC tt => "sync" | MFC0 (rt, rd, sel, double) => let op := if sumbool_of_bool double then "dmfc0 " else "mfc0 " in String.append op (String.append (strReg rt) (String.append ", " (String.append (strReg rd) (String.append ", $" (dec_str (projT1 (uint sel))))))) | MTC0 (rt, rd, sel, double) => let op := if sumbool_of_bool double then "dmtc0 " else "mtc0 " in String.append op (String.append (strReg rt) (String.append ", " (String.append (strReg rd) (String.append ", $" (dec_str (projT1 (uint sel))))))) | TLBWI tt => "tlbwi" | TLBWR tt => "tlbwr" | TLBR tt => "tlbr" | TLBP tt => "tlbp" | RDHWR (rt, rd) => String.append "rdhwr" (String.append (strReg rt) (String.append ", " (strReg rd))) | ERET tt => "eret" | CGetCause rd => String.append "cgetcause " (strReg rd) | CSetCause rs => String.append "csetcause " (strReg rs) | CGetPCC cd => String.append "cgetpcc " (strCReg cd) | CJALR (b__0, cb, false) => if eq_vec b__0 ('b"00000" : mword 5) then String.append "cjr " (strCReg cb) else "assembly unimplemented" | CGetCID rd => String.append "cgetcid " (strReg rd) | CSetCID cb => String.append "csetcid " (strCReg cb) | CClearTags cb => String.append "ccleartags " (strCReg cb) | CCheckPerm (cs, rt) => String.append "ccheckperm " (strCRArgs cs rt) | CCheckType (cs, cb) => String.append "cchecktype " (strCCArgs cs cb) | CClearTag (cd, cb) => String.append "ccleartag " (strCCArgs cd cb) | CMove (cd, cs) => String.append "cmove " (strCCArgs cd cs) | CJALR (cd, cb, true) => String.append "cjalr " (strCCArgs cd cb) | CSealEntry (cd, cb) => String.append "csealentry " (strCCArgs cd cb) | CLoadTags (rd, cb) => String.append "cloadtags " (strRCArgs rd cb) | CGetPerm (rd, cb) => String.append "cgetperm " (strRCArgs rd cb) | CGetType (rd, cb) => String.append "cgettype " (strRCArgs rd cb) | CGetBase (rd, cb) => String.append "cgetbase " (strRCArgs rd cb) | CGetLen (rd, cb) => String.append "cgetlen " (strRCArgs rd cb) | CGetTag (rd, cb) => String.append "cgettag " (strRCArgs rd cb) | CGetSealed (rd, cb) => String.append "cgetsealed " (strRCArgs rd cb) | CGetOffset (rd, cb) => String.append "cgetoffset " (strRCArgs rd cb) | CGetPCCSetOffset (cd, rs) => String.append "cgetpccsetoffset " (strCRArgs cd rs) | CReadHwr (cd, sel) => String.append "creadhwr " (strCRArgs cd sel) | CWriteHwr (cb, sel) => String.append "cwritehwr " (strCRArgs cb sel) | CGetAddr (rd, cb) => String.append "cgetaddr " (strRCArgs rd cb) | CGetFlags (rd, cb) => String.append "cgetflags " (strRCArgs rd cb) | CGetPCCIncOffset (cd, rs) => String.append "cgetpccincoffset " (strCRArgs cd rs) | CGetPCCSetAddr (cd, rs) => String.append "cgetpccsetaddr " (strCRArgs cd rs) | CRAP (rt, rs) => String.append "crrl " (strRRArgs rt rs) | CRAM (rt, rs) => String.append "cram " (strRRArgs rt rs) | CSeal (cd, cs, ct) => String.append "cseal " (strCCCArgs cd cs ct) | CUnseal (cd, cs, ct) => String.append "cunseal " (strCCCArgs cd cs ct) | CAndPerm (cd, cs, rt) => String.append "candperm " (strCCRArgs cd cs rt) | CSetOffset (cd, cs, rt) => String.append "csetoffset " (strCCRArgs cd cs rt) | CSetBounds (cd, cs, rt) => String.append "csetbounds " (strCCRArgs cd cs rt) | CSetBoundsExact (cd, cs, rt) => String.append "csetboundsexact " (strCCRArgs cd cs rt) | CSetFlags (cd, cs, rt) => String.append "csetflags " (strCCRArgs cd cs rt) | CIncOffset (cd, cs, rt) => String.append "cincoffset " (strCCRArgs cd cs rt) | CBuildCap (cd, cs, ct) => String.append "cbuildcap " (strCCCArgs cd cs ct) | CCopyType (cd, cs, ct) => String.append "ccopytype " (strCCCArgs cd cs ct) | CCSeal (cd, cs, ct) => String.append "ccseal " (strCCCArgs cd cs ct) | CToPtr (rd, cb, ct) => String.append "ctoptr " (strRCRArgs rd cb ct) | CFromPtr (cd, cb, rs) => String.append "cfromptr " (strCCRArgs cd cb rs) | CSub (rt, cb, cs) => String.append "csub " (strRCCArgs rt cb cs) | CMOVX (cd, cs, rs, false) => String.append "cmovz " (strCCRArgs cd cs rs) | CMOVX (cd, cs, rs, true) => String.append "cmovn " (strCCRArgs cd cs rs) | CSetAddr (cd, cs, rt) => String.append "csetaddr " (strCCRArgs cd cs rt) | CGetAndAddr (rd, cs, rs) => String.append "cgetandaddr " (strRCRArgs rd cs rs) | CAndAddr (cd, cs, rt) => String.append "candaddr " (strCCRArgs cd cs rt) | CReturn tt => "creturn" | CCall (cs, cb, selector) => String.append "ccall " (strCCIUArgs cs cb selector) | CIncOffsetImmediate (cd, cb, imm) => String.append "cincoffsetimm " (strCCIArgs cd cb imm) | CSetBoundsImmediate (cd, cb, imm) => String.append "csetboundsimm " (strCCIUArgs cd cb imm) | RI tt => "reserved instruction" | _ => "assembly unimplemented" end. Definition supported_instructions (instr : ast) : option ast := Some instr. Definition initialize_registers '(tt : unit) : M (unit) := (undefined_bitvector 64) >>= fun w__0 : mword 64 => write_reg PC_ref w__0 >> (undefined_bitvector 64) >>= fun w__1 : mword 64 => write_reg NextPC_ref w__1 >> (undefined_bitvector 1) >>= fun w__2 : mword 1 => write_reg TLBProbe_ref w__2 >> (undefined_bitvector 6) >>= fun w__3 : mword 6 => write_reg TLBIndex_ref w__3 >> (undefined_bitvector 6) >>= fun w__4 : mword 6 => write_reg TLBRandom_ref w__4 >> (undefined_TLBEntryLoReg tt) >>= fun w__5 : TLBEntryLoReg => write_reg TLBEntryLo0_ref w__5 >> (undefined_TLBEntryLoReg tt) >>= fun w__6 : TLBEntryLoReg => write_reg TLBEntryLo1_ref w__6 >> (undefined_ContextReg tt) >>= fun w__7 : ContextReg => write_reg TLBContext_ref w__7 >> (undefined_bitvector 16) >>= fun w__8 : mword 16 => write_reg TLBPageMask_ref w__8 >> (undefined_bitvector 6) >>= fun w__9 : mword 6 => write_reg TLBWired_ref w__9 >> (undefined_TLBEntryHiReg tt) >>= fun w__10 : TLBEntryHiReg => write_reg TLBEntryHi_ref w__10 >> (undefined_XContextReg tt) >>= fun w__11 : XContextReg => write_reg TLBXContext_ref w__11 >> (undefined_TLBEntry tt) >>= fun w__12 : TLBEntry => write_reg TLBEntry00_ref w__12 >> (undefined_TLBEntry tt) >>= fun w__13 : TLBEntry => write_reg TLBEntry01_ref w__13 >> (undefined_TLBEntry tt) >>= fun w__14 : TLBEntry => write_reg TLBEntry02_ref w__14 >> (undefined_TLBEntry tt) >>= fun w__15 : TLBEntry => write_reg TLBEntry03_ref w__15 >> (undefined_TLBEntry tt) >>= fun w__16 : TLBEntry => write_reg TLBEntry04_ref w__16 >> (undefined_TLBEntry tt) >>= fun w__17 : TLBEntry => write_reg TLBEntry05_ref w__17 >> (undefined_TLBEntry tt) >>= fun w__18 : TLBEntry => write_reg TLBEntry06_ref w__18 >> (undefined_TLBEntry tt) >>= fun w__19 : TLBEntry => write_reg TLBEntry07_ref w__19 >> (undefined_TLBEntry tt) >>= fun w__20 : TLBEntry => write_reg TLBEntry08_ref w__20 >> (undefined_TLBEntry tt) >>= fun w__21 : TLBEntry => write_reg TLBEntry09_ref w__21 >> (undefined_TLBEntry tt) >>= fun w__22 : TLBEntry => write_reg TLBEntry10_ref w__22 >> (undefined_TLBEntry tt) >>= fun w__23 : TLBEntry => write_reg TLBEntry11_ref w__23 >> (undefined_TLBEntry tt) >>= fun w__24 : TLBEntry => write_reg TLBEntry12_ref w__24 >> (undefined_TLBEntry tt) >>= fun w__25 : TLBEntry => write_reg TLBEntry13_ref w__25 >> (undefined_TLBEntry tt) >>= fun w__26 : TLBEntry => write_reg TLBEntry14_ref w__26 >> (undefined_TLBEntry tt) >>= fun w__27 : TLBEntry => write_reg TLBEntry15_ref w__27 >> (undefined_TLBEntry tt) >>= fun w__28 : TLBEntry => write_reg TLBEntry16_ref w__28 >> (undefined_TLBEntry tt) >>= fun w__29 : TLBEntry => write_reg TLBEntry17_ref w__29 >> (undefined_TLBEntry tt) >>= fun w__30 : TLBEntry => write_reg TLBEntry18_ref w__30 >> (undefined_TLBEntry tt) >>= fun w__31 : TLBEntry => write_reg TLBEntry19_ref w__31 >> (undefined_TLBEntry tt) >>= fun w__32 : TLBEntry => write_reg TLBEntry20_ref w__32 >> (undefined_TLBEntry tt) >>= fun w__33 : TLBEntry => write_reg TLBEntry21_ref w__33 >> (undefined_TLBEntry tt) >>= fun w__34 : TLBEntry => write_reg TLBEntry22_ref w__34 >> (undefined_TLBEntry tt) >>= fun w__35 : TLBEntry => write_reg TLBEntry23_ref w__35 >> (undefined_TLBEntry tt) >>= fun w__36 : TLBEntry => write_reg TLBEntry24_ref w__36 >> (undefined_TLBEntry tt) >>= fun w__37 : TLBEntry => write_reg TLBEntry25_ref w__37 >> (undefined_TLBEntry tt) >>= fun w__38 : TLBEntry => write_reg TLBEntry26_ref w__38 >> (undefined_TLBEntry tt) >>= fun w__39 : TLBEntry => write_reg TLBEntry27_ref w__39 >> (undefined_TLBEntry tt) >>= fun w__40 : TLBEntry => write_reg TLBEntry28_ref w__40 >> (undefined_TLBEntry tt) >>= fun w__41 : TLBEntry => write_reg TLBEntry29_ref w__41 >> (undefined_TLBEntry tt) >>= fun w__42 : TLBEntry => write_reg TLBEntry30_ref w__42 >> (undefined_TLBEntry tt) >>= fun w__43 : TLBEntry => write_reg TLBEntry31_ref w__43 >> (undefined_TLBEntry tt) >>= fun w__44 : TLBEntry => write_reg TLBEntry32_ref w__44 >> (undefined_TLBEntry tt) >>= fun w__45 : TLBEntry => write_reg TLBEntry33_ref w__45 >> (undefined_TLBEntry tt) >>= fun w__46 : TLBEntry => write_reg TLBEntry34_ref w__46 >> (undefined_TLBEntry tt) >>= fun w__47 : TLBEntry => write_reg TLBEntry35_ref w__47 >> (undefined_TLBEntry tt) >>= fun w__48 : TLBEntry => write_reg TLBEntry36_ref w__48 >> (undefined_TLBEntry tt) >>= fun w__49 : TLBEntry => write_reg TLBEntry37_ref w__49 >> (undefined_TLBEntry tt) >>= fun w__50 : TLBEntry => write_reg TLBEntry38_ref w__50 >> (undefined_TLBEntry tt) >>= fun w__51 : TLBEntry => write_reg TLBEntry39_ref w__51 >> (undefined_TLBEntry tt) >>= fun w__52 : TLBEntry => write_reg TLBEntry40_ref w__52 >> (undefined_TLBEntry tt) >>= fun w__53 : TLBEntry => write_reg TLBEntry41_ref w__53 >> (undefined_TLBEntry tt) >>= fun w__54 : TLBEntry => write_reg TLBEntry42_ref w__54 >> (undefined_TLBEntry tt) >>= fun w__55 : TLBEntry => write_reg TLBEntry43_ref w__55 >> (undefined_TLBEntry tt) >>= fun w__56 : TLBEntry => write_reg TLBEntry44_ref w__56 >> (undefined_TLBEntry tt) >>= fun w__57 : TLBEntry => write_reg TLBEntry45_ref w__57 >> (undefined_TLBEntry tt) >>= fun w__58 : TLBEntry => write_reg TLBEntry46_ref w__58 >> (undefined_TLBEntry tt) >>= fun w__59 : TLBEntry => write_reg TLBEntry47_ref w__59 >> (undefined_TLBEntry tt) >>= fun w__60 : TLBEntry => write_reg TLBEntry48_ref w__60 >> (undefined_TLBEntry tt) >>= fun w__61 : TLBEntry => write_reg TLBEntry49_ref w__61 >> (undefined_TLBEntry tt) >>= fun w__62 : TLBEntry => write_reg TLBEntry50_ref w__62 >> (undefined_TLBEntry tt) >>= fun w__63 : TLBEntry => write_reg TLBEntry51_ref w__63 >> (undefined_TLBEntry tt) >>= fun w__64 : TLBEntry => write_reg TLBEntry52_ref w__64 >> (undefined_TLBEntry tt) >>= fun w__65 : TLBEntry => write_reg TLBEntry53_ref w__65 >> (undefined_TLBEntry tt) >>= fun w__66 : TLBEntry => write_reg TLBEntry54_ref w__66 >> (undefined_TLBEntry tt) >>= fun w__67 : TLBEntry => write_reg TLBEntry55_ref w__67 >> (undefined_TLBEntry tt) >>= fun w__68 : TLBEntry => write_reg TLBEntry56_ref w__68 >> (undefined_TLBEntry tt) >>= fun w__69 : TLBEntry => write_reg TLBEntry57_ref w__69 >> (undefined_TLBEntry tt) >>= fun w__70 : TLBEntry => write_reg TLBEntry58_ref w__70 >> (undefined_TLBEntry tt) >>= fun w__71 : TLBEntry => write_reg TLBEntry59_ref w__71 >> (undefined_TLBEntry tt) >>= fun w__72 : TLBEntry => write_reg TLBEntry60_ref w__72 >> (undefined_TLBEntry tt) >>= fun w__73 : TLBEntry => write_reg TLBEntry61_ref w__73 >> (undefined_TLBEntry tt) >>= fun w__74 : TLBEntry => write_reg TLBEntry62_ref w__74 >> (undefined_TLBEntry tt) >>= fun w__75 : TLBEntry => write_reg TLBEntry63_ref w__75 >> (undefined_bitvector 32) >>= fun w__76 : mword 32 => write_reg CP0Compare_ref w__76 >> (undefined_CauseReg tt) >>= fun w__77 : CauseReg => write_reg CP0Cause_ref w__77 >> (undefined_bitvector 1) >>= fun w__78 : mword 1 => write_reg CP0LLBit_ref w__78 >> (undefined_bitvector 64) >>= fun w__79 : mword 64 => write_reg CP0LLAddr_ref w__79 >> (undefined_bitvector 64) >>= fun w__80 : mword 64 => write_reg CP0BadVAddr_ref w__80 >> (undefined_bitvector 32) >>= fun w__81 : mword 32 => write_reg CurrentInstrBits_ref w__81 >> (undefined_bitvector 32) >>= fun w__82 : mword 32 => write_reg LastInstrBits_ref w__82 >> (undefined_bitvector 32) >>= fun w__83 : mword 32 => write_reg CP0BadInstr_ref w__83 >> (undefined_bitvector 32) >>= fun w__84 : mword 32 => write_reg CP0BadInstrP_ref w__84 >> (undefined_bitvector 32) >>= fun w__85 : mword 32 => write_reg CP0Count_ref w__85 >> (undefined_bitvector 32) >>= fun w__86 : mword 32 => write_reg CP0HWREna_ref w__86 >> (undefined_bitvector 64) >>= fun w__87 : mword 64 => write_reg CP0UserLocal_ref w__87 >> (undefined_bitvector 3) >>= fun w__88 : mword 3 => write_reg CP0ConfigK0_ref w__88 >> (undefined_StatusReg tt) >>= fun w__89 : StatusReg => write_reg CP0Status_ref w__89 >> (undefined_bitvector 1) >>= fun w__90 : mword 1 => write_reg NextInBranchDelay_ref w__90 >> (undefined_bitvector 1) >>= fun w__91 : mword 1 => write_reg InBranchDelay_ref w__91 >> (undefined_bitvector 1) >>= fun w__92 : mword 1 => write_reg BranchPending_ref w__92 >> (undefined_bitvector 64) >>= fun w__93 : mword 64 => write_reg DelayedPC_ref w__93 >> (undefined_bitvector 64) >>= fun w__94 : mword 64 => write_reg HI_ref w__94 >> (undefined_bitvector 64) >>= fun w__95 : mword 64 => write_reg LO_ref w__95 >> (undefined_bitvector 64) >>= fun w__96 : mword 64 => (undefined_vector 32 w__96) >>= fun w__97 : vec (mword 64) 32 => write_reg GPR_ref w__97 >> (undefined_bitvector 8) >>= fun w__98 : mword 8 => write_reg UART_WDATA_ref w__98 >> (undefined_bitvector 1) >>= fun w__99 : mword 1 => write_reg UART_WRITTEN_ref w__99 >> (undefined_bitvector 8) >>= fun w__100 : mword 8 => write_reg UART_RDATA_ref w__100 >> (undefined_bitvector 1) >>= fun w__101 : mword 1 => write_reg UART_RVALID_ref w__101 >> (undefined_Capability tt) >>= fun w__102 : Capability => write_reg PCC_ref w__102 >> (undefined_Capability tt) >>= fun w__103 : Capability => write_reg NextPCC_ref w__103 >> (undefined_Capability tt) >>= fun w__104 : Capability => write_reg DelayedPCC_ref w__104 >> (undefined_Capability tt) >>= fun w__105 : Capability => write_reg DDC_ref w__105 >> (undefined_Capability tt) >>= fun w__106 : Capability => write_reg C01_ref w__106 >> (undefined_Capability tt) >>= fun w__107 : Capability => write_reg C02_ref w__107 >> (undefined_Capability tt) >>= fun w__108 : Capability => write_reg C03_ref w__108 >> (undefined_Capability tt) >>= fun w__109 : Capability => write_reg C04_ref w__109 >> (undefined_Capability tt) >>= fun w__110 : Capability => write_reg C05_ref w__110 >> (undefined_Capability tt) >>= fun w__111 : Capability => write_reg C06_ref w__111 >> (undefined_Capability tt) >>= fun w__112 : Capability => write_reg C07_ref w__112 >> (undefined_Capability tt) >>= fun w__113 : Capability => write_reg C08_ref w__113 >> (undefined_Capability tt) >>= fun w__114 : Capability => write_reg C09_ref w__114 >> (undefined_Capability tt) >>= fun w__115 : Capability => write_reg C10_ref w__115 >> (undefined_Capability tt) >>= fun w__116 : Capability => write_reg C11_ref w__116 >> (undefined_Capability tt) >>= fun w__117 : Capability => write_reg C12_ref w__117 >> (undefined_Capability tt) >>= fun w__118 : Capability => write_reg C13_ref w__118 >> (undefined_Capability tt) >>= fun w__119 : Capability => write_reg C14_ref w__119 >> (undefined_Capability tt) >>= fun w__120 : Capability => write_reg C15_ref w__120 >> (undefined_Capability tt) >>= fun w__121 : Capability => write_reg C16_ref w__121 >> (undefined_Capability tt) >>= fun w__122 : Capability => write_reg C17_ref w__122 >> (undefined_Capability tt) >>= fun w__123 : Capability => write_reg C18_ref w__123 >> (undefined_Capability tt) >>= fun w__124 : Capability => write_reg C19_ref w__124 >> (undefined_Capability tt) >>= fun w__125 : Capability => write_reg C20_ref w__125 >> (undefined_Capability tt) >>= fun w__126 : Capability => write_reg C21_ref w__126 >> (undefined_Capability tt) >>= fun w__127 : Capability => write_reg C22_ref w__127 >> (undefined_Capability tt) >>= fun w__128 : Capability => write_reg C23_ref w__128 >> (undefined_Capability tt) >>= fun w__129 : Capability => write_reg C24_ref w__129 >> (undefined_Capability tt) >>= fun w__130 : Capability => write_reg C25_ref w__130 >> (undefined_Capability tt) >>= fun w__131 : Capability => write_reg C26_ref w__131 >> (undefined_Capability tt) >>= fun w__132 : Capability => write_reg C27_ref w__132 >> (undefined_Capability tt) >>= fun w__133 : Capability => write_reg C28_ref w__133 >> (undefined_Capability tt) >>= fun w__134 : Capability => write_reg C29_ref w__134 >> (undefined_Capability tt) >>= fun w__135 : Capability => write_reg C30_ref w__135 >> (undefined_Capability tt) >>= fun w__136 : Capability => write_reg C31_ref w__136 >> (undefined_Capability tt) >>= fun w__137 : Capability => write_reg CULR_ref w__137 >> (undefined_Capability tt) >>= fun w__138 : Capability => write_reg CPLR_ref w__138 >> (undefined_Capability tt) >>= fun w__139 : Capability => write_reg KR1C_ref w__139 >> (undefined_Capability tt) >>= fun w__140 : Capability => write_reg KR2C_ref w__140 >> (undefined_Capability tt) >>= fun w__141 : Capability => write_reg KCC_ref w__141 >> (undefined_Capability tt) >>= fun w__142 : Capability => write_reg KDC_ref w__142 >> (undefined_Capability tt) >>= fun w__143 : Capability => write_reg EPCC_ref w__143 >> (undefined_Capability tt) >>= fun w__144 : Capability => write_reg ErrorEPCC_ref w__144 >> (undefined_CapCauseReg tt) >>= fun w__145 : CapCauseReg => write_reg CapCause_ref w__145 >> (undefined_bitvector 64) >>= fun w__146 : mword 64 => write_reg CID_ref w__146 : M (unit). Definition initial_CauseReg : CauseReg := {| CauseReg_CauseReg_chunk_0 := (Ox"00000000" : mword 32) |}. Hint Unfold initial_CauseReg : sail. Definition initial_TLBEntryLoReg : TLBEntryLoReg := {| TLBEntryLoReg_TLBEntryLoReg_chunk_0 := (Ox"0000000000000000" : mword 64) |}. Hint Unfold initial_TLBEntryLoReg : sail. Definition initial_TLBEntryHiReg : TLBEntryHiReg := {| TLBEntryHiReg_TLBEntryHiReg_chunk_0 := (Ox"0000000000000000" : mword 64) |}. Hint Unfold initial_TLBEntryHiReg : sail. Definition initial_ContextReg : ContextReg := {| ContextReg_ContextReg_chunk_0 := (Ox"0000000000000000" : mword 64) |}. Hint Unfold initial_ContextReg : sail. Definition initial_XContextReg : XContextReg := {| XContextReg_XContextReg_chunk_0 := (Ox"0000000000000000" : mword 64) |}. Hint Unfold initial_XContextReg : sail. Definition initial_TLBEntry : TLBEntry := {| TLBEntry_TLBEntry_chunk_1 := ('b"0000000000000000000000000000000000000000000000000000000" : mword 55); TLBEntry_TLBEntry_chunk_0 := (Ox"0000000000000000" : mword 64) |}. Hint Unfold initial_TLBEntry : sail. Definition initial_StatusReg : StatusReg := {| StatusReg_StatusReg_chunk_0 := (Ox"00000000" : mword 32) |}. Hint Unfold initial_StatusReg : sail. Definition initial_Capability : Capability := {| Capability_tag := false; Capability_uperms := (Ox"0" : mword 4); Capability_permit_set_CID := false; Capability_access_system_regs := false; Capability_permit_unseal := false; Capability_permit_ccall := false; Capability_permit_seal := false; Capability_permit_store_local_cap := false; Capability_permit_store_cap := false; Capability_permit_load_cap := false; Capability_permit_store := false; Capability_permit_load := false; Capability_permit_execute := false; Capability_global := false; Capability_reserved := ('b"000" : mword 3); Capability_internal_e := false; Capability_E := ('b"000000" : mword 6); Capability_sealed := false; Capability_B := ('b"00000000000000" : mword 14); Capability_T := ('b"00000000000000" : mword 14); Capability_otype := ('b"000000000000000000" : mword 18); Capability_address := (Ox"0000000000000000" : mword 64) |}. Hint Unfold initial_Capability : sail. Definition initial_CapCauseReg : CapCauseReg := {| CapCauseReg_CapCauseReg_chunk_0 := (Ox"0000" : mword 16) |}. Hint Unfold initial_CapCauseReg : sail. Definition initial_regstate : regstate := {| CID := (Ox"0000000000000000" : mword 64); CapCause := initial_CapCauseReg; ErrorEPCC := initial_Capability; EPCC := initial_Capability; KDC := initial_Capability; KCC := initial_Capability; KR2C := initial_Capability; KR1C := initial_Capability; CPLR := initial_Capability; CULR := initial_Capability; C31 := initial_Capability; C30 := initial_Capability; C29 := initial_Capability; C28 := initial_Capability; C27 := initial_Capability; C26 := initial_Capability; C25 := initial_Capability; C24 := initial_Capability; C23 := initial_Capability; C22 := initial_Capability; C21 := initial_Capability; C20 := initial_Capability; C19 := initial_Capability; C18 := initial_Capability; C17 := initial_Capability; C16 := initial_Capability; C15 := initial_Capability; C14 := initial_Capability; C13 := initial_Capability; C12 := initial_Capability; C11 := initial_Capability; C10 := initial_Capability; C09 := initial_Capability; C08 := initial_Capability; C07 := initial_Capability; C06 := initial_Capability; C05 := initial_Capability; C04 := initial_Capability; C03 := initial_Capability; C02 := initial_Capability; C01 := initial_Capability; DDC := initial_Capability; DelayedPCC := initial_Capability; NextPCC := initial_Capability; PCC := initial_Capability; UART_RVALID := ('b"0" : mword 1); UART_RDATA := (Ox"00" : mword 8); UART_WRITTEN := ('b"0" : mword 1); UART_WDATA := (Ox"00" : mword 8); GPR := (vec_of_list_len [Ox"0000000000000000" : mword 64;Ox"0000000000000000" : mword 64;Ox"0000000000000000" : mword 64; Ox"0000000000000000" : mword 64;Ox"0000000000000000" : mword 64;Ox"0000000000000000" : mword 64; Ox"0000000000000000" : mword 64;Ox"0000000000000000" : mword 64;Ox"0000000000000000" : mword 64; Ox"0000000000000000" : mword 64;Ox"0000000000000000" : mword 64;Ox"0000000000000000" : mword 64; Ox"0000000000000000" : mword 64;Ox"0000000000000000" : mword 64;Ox"0000000000000000" : mword 64; Ox"0000000000000000" : mword 64;Ox"0000000000000000" : mword 64;Ox"0000000000000000" : mword 64; Ox"0000000000000000" : mword 64;Ox"0000000000000000" : mword 64;Ox"0000000000000000" : mword 64; Ox"0000000000000000" : mword 64;Ox"0000000000000000" : mword 64;Ox"0000000000000000" : mword 64; Ox"0000000000000000" : mword 64;Ox"0000000000000000" : mword 64;Ox"0000000000000000" : mword 64; Ox"0000000000000000" : mword 64;Ox"0000000000000000" : mword 64;Ox"0000000000000000" : mword 64; Ox"0000000000000000" : mword 64;Ox"0000000000000000" : mword 64]); LO := (Ox"0000000000000000" : mword 64); HI := (Ox"0000000000000000" : mword 64); DelayedPC := (Ox"0000000000000000" : mword 64); BranchPending := ('b"0" : mword 1); InBranchDelay := ('b"0" : mword 1); NextInBranchDelay := ('b"0" : mword 1); CP0Status := initial_StatusReg; CP0ConfigK0 := ('b"000" : mword 3); CP0UserLocal := (Ox"0000000000000000" : mword 64); CP0HWREna := (Ox"00000000" : mword 32); CP0Count := (Ox"00000000" : mword 32); CP0BadInstrP := (Ox"00000000" : mword 32); CP0BadInstr := (Ox"00000000" : mword 32); LastInstrBits := (Ox"00000000" : mword 32); CurrentInstrBits := (Ox"00000000" : mword 32); CP0BadVAddr := (Ox"0000000000000000" : mword 64); CP0LLAddr := (Ox"0000000000000000" : mword 64); CP0LLBit := ('b"0" : mword 1); CP0Cause := initial_CauseReg; CP0Compare := (Ox"00000000" : mword 32); TLBEntry63 := initial_TLBEntry; TLBEntry62 := initial_TLBEntry; TLBEntry61 := initial_TLBEntry; TLBEntry60 := initial_TLBEntry; TLBEntry59 := initial_TLBEntry; TLBEntry58 := initial_TLBEntry; TLBEntry57 := initial_TLBEntry; TLBEntry56 := initial_TLBEntry; TLBEntry55 := initial_TLBEntry; TLBEntry54 := initial_TLBEntry; TLBEntry53 := initial_TLBEntry; TLBEntry52 := initial_TLBEntry; TLBEntry51 := initial_TLBEntry; TLBEntry50 := initial_TLBEntry; TLBEntry49 := initial_TLBEntry; TLBEntry48 := initial_TLBEntry; TLBEntry47 := initial_TLBEntry; TLBEntry46 := initial_TLBEntry; TLBEntry45 := initial_TLBEntry; TLBEntry44 := initial_TLBEntry; TLBEntry43 := initial_TLBEntry; TLBEntry42 := initial_TLBEntry; TLBEntry41 := initial_TLBEntry; TLBEntry40 := initial_TLBEntry; TLBEntry39 := initial_TLBEntry; TLBEntry38 := initial_TLBEntry; TLBEntry37 := initial_TLBEntry; TLBEntry36 := initial_TLBEntry; TLBEntry35 := initial_TLBEntry; TLBEntry34 := initial_TLBEntry; TLBEntry33 := initial_TLBEntry; TLBEntry32 := initial_TLBEntry; TLBEntry31 := initial_TLBEntry; TLBEntry30 := initial_TLBEntry; TLBEntry29 := initial_TLBEntry; TLBEntry28 := initial_TLBEntry; TLBEntry27 := initial_TLBEntry; TLBEntry26 := initial_TLBEntry; TLBEntry25 := initial_TLBEntry; TLBEntry24 := initial_TLBEntry; TLBEntry23 := initial_TLBEntry; TLBEntry22 := initial_TLBEntry; TLBEntry21 := initial_TLBEntry; TLBEntry20 := initial_TLBEntry; TLBEntry19 := initial_TLBEntry; TLBEntry18 := initial_TLBEntry; TLBEntry17 := initial_TLBEntry; TLBEntry16 := initial_TLBEntry; TLBEntry15 := initial_TLBEntry; TLBEntry14 := initial_TLBEntry; TLBEntry13 := initial_TLBEntry; TLBEntry12 := initial_TLBEntry; TLBEntry11 := initial_TLBEntry; TLBEntry10 := initial_TLBEntry; TLBEntry09 := initial_TLBEntry; TLBEntry08 := initial_TLBEntry; TLBEntry07 := initial_TLBEntry; TLBEntry06 := initial_TLBEntry; TLBEntry05 := initial_TLBEntry; TLBEntry04 := initial_TLBEntry; TLBEntry03 := initial_TLBEntry; TLBEntry02 := initial_TLBEntry; TLBEntry01 := initial_TLBEntry; TLBEntry00 := initial_TLBEntry; TLBXContext := initial_XContextReg; TLBEntryHi := initial_TLBEntryHiReg; TLBWired := ('b"000000" : mword 6); TLBPageMask := (Ox"0000" : mword 16); TLBContext := initial_ContextReg; TLBEntryLo1 := initial_TLBEntryLoReg; TLBEntryLo0 := initial_TLBEntryLoReg; TLBRandom := ('b"000000" : mword 6); TLBIndex := ('b"000000" : mword 6); TLBProbe := ('b"0" : mword 1); NextPC := (Ox"0000000000000000" : mword 64); PC := (Ox"0000000000000000" : mword 64) |}. Hint Unfold initial_regstate : sail.
# Bandstructures for 1D, 2D, and 3D nanowires For more information see: B. Nijholt, A. R. Akhmerov, *Orbital effect of magnetic field on the Majorana phase diagram*, [arXiv:1509.02675](https://arxiv.org/abs/1509.02675) [[pdf](https://arxiv.org/pdf/1509.02675.pdf)], [Phys. Rev. B 93, 235434 (2016)](http://journals.aps.org/prb/abstract/10.1103/PhysRevB.93.235434). ```python from copy import copy from functools import partial from operator import itemgetter from time import time import adaptive import holoviews as hv import kwant import numpy as np import pandas as pd import sympy import wires adaptive.notebook_extension() sympy.init_printing() # hv.notebook_extension('bokeh') hv.notebook_extension("matplotlib") ``` # Hamiltonian ```python wires.get_sympy_hamiltonian({}, 2) ``` # System example ```python %matplotlib inline import matplotlib.pyplot syst_pars = dict(a=10, L=100, dim=1) syst = wires.make_wire(**syst_pars) kwant.plot(syst) ``` ```python syst_pars = dict(a=10, L=100, dim=2, r=30) syst = wires.make_wire(**syst_pars) kwant.plot(syst) ``` ```python syst_pars = dict(a=10, L=100, dim=3, r=30) syst = wires.make_wire(**syst_pars) kwant.plot(syst) ``` ```python R = 30 triangle = wires.get_triangle(R) syst_pars = dict(a=10, L=100, dim=3, r=None, shape=triangle) syst = wires.make_wire(**syst_pars) kwant.plot(syst) ``` # Band structures ```python def bands(ylim, alpha, mu, Delta, B_x, B_y, B_z, params, lead_SC, lead_N): params = dict(params, alpha=alpha, mu=mu, Delta=Delta, B_x=B_x, B_y=B_y, B_z=B_z) ks = np.linspace(-0.9, 0.9, 201) Es = wires.bands(lead_N.finalized(), params, ks) kdims = [hv.Dimension(r"$k$", unit=r"nm$^{-1}$"), hv.Dimension(r"$E$", unit=r"meV")] normal = hv.Path((ks, Es), kdims=kdims, label="normal") Es = wires.bands(lead_SC.finalized(), params, ks) SC = hv.Path((ks, Es), kdims=kdims, label="SC") fermi_level = hv.HLine(0).opts(style=dict(linestyle="--")) return (normal * fermi_level).select(E=(-ylim, ylim)) + SC.select(E=(-ylim, ylim)) kdims = [ hv.Dimension(("ylim"), range=(0.01, 50), default=5), hv.Dimension(("alpha", r"$\alpha$"), range=(0, 50), unit="meV·nm", default=20), hv.Dimension(("mu", r"$\mu$"), range=(0.0, 30), unit="meV", default=5), hv.Dimension(("Delta", r"$\Delta$"), range=(0, 1.0), unit="meV", default=0.25), hv.Dimension(("B_x", r"$B_x$"), range=(0, 10), unit="T", default=1), hv.Dimension(("B_y", r"$B_y$"), range=(0, 10), unit="T", default=0), hv.Dimension(("B_z", r"$B_z$"), range=(0, 0.5), unit="T", default=0), ] ``` ## 1D band structure $$H(x) = \left[ \frac{p_x^2}{2m} - \mu \right]\sigma_0\otimes\tau_z + \alpha p_x \sigma_y \otimes \tau_z + \frac{1}{2}B_x\sigma_x \otimes \tau_0 + \Delta\sigma_0\otimes\tau_x$$ ```python lead_SC = wires.make_lead_SC(10, dim=1) lead_N = wires.make_lead_normal(10, with_holes=False, dim=1) params = dict(V=0, g=50, **wires.constants) bands_1D = partial(bands, params=params, lead_SC=lead_SC, lead_N=lead_N) hv.DynamicMap(bands_1D, kdims=kdims) ``` ## 2D band structure $$H=\left(\frac{\mathbf{p}^{2}}{2m}-\mu\right)\sigma_{0}\otimes\tau_{z}+\alpha\left(p_{y}\sigma_{x}\otimes\tau_{z}-p_{x}\sigma_{y}\otimes\tau_{z}\right)+\frac{1}{2}B_{x}\sigma_{x}\otimes\tau_{0}+\frac{1}{2}B_{y}\sigma_{y}\otimes\tau_{0}+\frac{1}{2}B_{z}\sigma_{z}\otimes\tau_{0}+\Delta \sigma_{0}\otimes\tau_{x}$$ ```python syst_pars = dict(a=10, r=30, dim=2) lead_SC = wires.make_lead_SC(**syst_pars) lead_N = wires.make_lead_normal(**syst_pars, with_holes=False) params = dict(a=syst_pars["a"], V=0, g=50, **wires.constants) bands_2D = partial(bands, params=params, lead_SC=lead_SC, lead_N=lead_N) hv.DynamicMap(bands_2D, kdims=kdims) ``` ## 3D band structure $$H=\left(\frac{\mathbf{p}^{2}}{2m}-\mu\right)\sigma_{0}\otimes\tau_{z}+\alpha\left(p_{y}\sigma_{x}\otimes\tau_{z}-p_{x}\sigma_{y}\otimes\tau_{z}\right)+\frac{1}{2}B_{x}\sigma_{x}\otimes\tau_{0}+\frac{1}{2}B_{y}\sigma_{y}\otimes\tau_{0}+\frac{1}{2}B_{z}\sigma_{z}\otimes\tau_{0}+\Delta \sigma_{0}\otimes\tau_{x}$$ ```python syst_pars = dict(a=10, r=30, dim=3) lead_SC = wires.make_lead_SC(**syst_pars) lead_N = wires.make_lead_normal(**syst_pars, with_holes=False) params = dict(a=syst_pars["a"], V=0, g=50, **wires.constants) bands_3D = partial(bands, params=params, lead_SC=lead_SC, lead_N=lead_N) hv.DynamicMap(bands_3D, kdims=kdims) ``` # Wave functions ## Wavefunction in the cross section of a 3D infinite lead. ```python def wavefunctions(lead, momentum, p): h, t = lead.cell_hamiltonian(args=[p]), lead.inter_cell_hopping(args=[p]) h_k = lambda k: h + t * np.exp(1j * k) + t.T.conj() * np.exp(-1j * k) vals, vecs = np.linalg.eigh(h_k(momentum)) indxs = np.argsort(abs(vals)) vecs = vecs[:, indxs] vals = vals[indxs] return vals, vecs syst_pars = dict(a=10, r=30, dim=3) lead_SC = wires.make_lead_SC(**syst_pars).finalized() params = dict( a=syst_pars["a"], Delta=1, B_x=1, # in units of meV mu=1, V=0, alpha=20, g=1, B_y=0, B_z=0, **wires.constants ) params["mu_B"] = 2 wires.plot_wfs_in_cross_section(lead_SC, params, 0) ``` ## Wavefunction of finite system ```python syst_pars = dict(a=10, r=30, dim=1, L=4000) syst = wires.make_wire(**syst_pars) ``` ```python params = dict( # should be topological alpha=20, g=1, B_y=0, B_z=0, V=0, B_x=0.86, mu=0.42, Delta=0.384, **wires.constants ) params["mu_B"] = 2 ``` ```python H = syst.hamiltonian_submatrix(params=params) Es, ψs = np.linalg.eigh(H) indices = np.abs(Es).argsort() rho = kwant.operator.Density(syst) wf = rho(ψs[:, indices[0]]) hv.Curve(wf) ```
(* Title: The pi-calculus Author/Maintainer: Jesper Bengtson (jebe.dk), 2012 *) theory Weak_Late_Cong_Subst_SC imports Weak_Late_Cong_Subst Strong_Late_Bisim_Subst_SC begin (******** Structural Congruence **********) (******** The \<nu>-operator *****************) lemma resComm: fixes P :: pi shows "<\<nu>a><\<nu>b>P \<simeq>\<^sup>s <\<nu>b><\<nu>a>P" proof - have "<\<nu>a><\<nu>b>P \<sim>\<^sup>s <\<nu>b><\<nu>a>P" by(rule Strong_Late_Bisim_Subst_SC.resComm) thus ?thesis by(rule strongEqWeakCong) qed (******** Match *********) lemma matchId: fixes a :: name and P :: pi shows "[a\<frown>a]P \<simeq>\<^sup>s P" proof - have "[a\<frown>a]P \<sim>\<^sup>s P" by(rule Strong_Late_Bisim_Subst_SC.matchId) thus ?thesis by(rule strongEqWeakCong) qed (******** Mismatch *********) lemma matchNil: fixes a :: name and P :: pi shows "[a\<noteq>a]P \<simeq>\<^sup>s \<zero>" proof - have "[a\<noteq>a]P \<sim>\<^sup>s \<zero>" by(rule Strong_Late_Bisim_Subst_SC.mismatchNil) thus ?thesis by(rule strongEqWeakCong) qed (******** The +-operator *********) lemma sumSym: fixes P :: pi and Q :: pi shows "P \<oplus> Q \<simeq>\<^sup>s Q \<oplus> P" proof - have "P \<oplus> Q \<sim>\<^sup>s Q \<oplus> P" by(rule Strong_Late_Bisim_Subst_SC.sumSym) thus ?thesis by(rule strongEqWeakCong) qed (******** The |-operator *********) lemma parZero: fixes P :: pi shows "P \<parallel> \<zero> \<simeq>\<^sup>s P" proof - have "P \<parallel> \<zero> \<sim>\<^sup>s P" by(rule Strong_Late_Bisim_Subst_SC.parZero) thus ?thesis by(rule strongEqWeakCong) qed lemma parSym: fixes P :: pi and Q :: pi shows "P \<parallel> Q \<simeq>\<^sup>s Q \<parallel> P" proof - have "P \<parallel> Q \<sim>\<^sup>s Q \<parallel> P" by(rule Strong_Late_Bisim_Subst_SC.parSym) thus ?thesis by(rule strongEqWeakCong) qed assumes "x \<sharp> P" shows "<\<nu>x>(P \<parallel> Q) \<simeq>\<^sup>s P \<parallel> <\<nu>x>Q" proof - from assms have "<\<nu>x>(P \<parallel> Q) \<sim>\<^sup>s P \<parallel> <\<nu>x>Q" by(rule Strong_Late_Bisim_Subst_SC.scopeExtPar) thus ?thesis by(rule strongEqWeakCong) qed lemma scopeExtPar': fixes P :: pi and Q :: pi and x :: name assumes xFreshQ: "x \<sharp> Q" shows "<\<nu>x>(P \<parallel> Q) \<simeq>\<^sup>s (<\<nu>x>P) \<parallel> Q" proof - from assms have "<\<nu>x>(P \<parallel> Q) \<sim>\<^sup>s (<\<nu>x>P) \<parallel> Q" by(rule Strong_Late_Bisim_Subst_SC.scopeExtPar') thus ?thesis by(rule strongEqWeakCong) qed shows "(P \<parallel> Q) \<parallel> R \<simeq>\<^sup>s P \<parallel> (Q \<parallel> R)" proof - have "(P \<parallel> Q) \<parallel> R \<sim>\<^sup>s P \<parallel> (Q \<parallel> R)" by(rule Strong_Late_Bisim_Subst_SC.parAssoc) thus ?thesis by(rule strongEqWeakCong) qed assumes aFreshP: "a \<sharp> P" shows "<\<nu>a>P \<simeq>\<^sup>s P" proof - from assms have "<\<nu>a>P \<sim>\<^sup>s P" by(rule Strong_Late_Bisim_Subst_SC.scopeFresh) thus ?thesis by(rule strongEqWeakCong) qed lemma scopeExtSum: fixes P :: pi and Q :: pi and x :: name assumes "x \<sharp> P" shows "<\<nu>x>(P \<oplus> Q) \<simeq>\<^sup>s P \<oplus> <\<nu>x>Q" proof - from assms have "<\<nu>x>(P \<oplus> Q) \<sim>\<^sup>s P \<oplus> <\<nu>x>Q" by(rule Strong_Late_Bisim_Subst_SC.scopeExtSum) thus ?thesis by(rule strongEqWeakCong) qed lemma bangSC: fixes P shows "!P \<simeq>\<^sup>s P \<parallel> !P" proof - have "!P \<sim>\<^sup>s P \<parallel> !P" by(rule Strong_Late_Bisim_Subst_SC.bangSC) thus ?thesis by(rule strongEqWeakCong) qed end
make_complex_projective_space := proc(n::nonnegint) local T,x,i; T := table([]): T["name"] := sprintf("CP^%d",n); T["dimension"] := 2*n; T["cohomology_gens"] := tdeg(x); T["cohomology_degrees"] := table([x = 2]); T["cohomology_rels"] := [x^(n+1)]; T["cohomology_basis"] := [seq(x^i,i=0..n)]; T["cohomology_graded_basis"] := table([]): for i from 0 to 2*n do T["cohomology_graded_basis"][i] := `if`(modp(i,2)=0,[x^(i/2)],[]); od: return eval(T); end:
/* $Id$ */ /*--------------------------------------------------------------------*/ /*; Copyright (C) 2013-2020 */ /*; Associated Universities, Inc. Washington DC, USA. */ /*; */ /*; This program is free software; you can redistribute it and/or */ /*; modify it under the terms of the GNU General Public License as */ /*; published by the Free Software Foundation; either version 2 of */ /*; the License, or (at your option) any later version. */ /*; */ /*; This program is distributed in the hope that it will be useful, */ /*; but WITHOUT ANY WARRANTY; without even the implied warranty of */ /*; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */ /*; GNU General Public License for more details. */ /*; */ /*; You should have received a copy of the GNU General Public */ /*; License along with this program; if not, write to the Free */ /*; Software Foundation, Inc., 675 Massachusetts Ave, Cambridge, */ /*; MA 02139, USA. */ /*; */ /*;Correspondence about this software should be addressed as follows: */ /*; Internet email: [email protected]. */ /*; Postal address: William Cotton */ /*; National Radio Astronomy Observatory */ /*; 520 Edgemont Road */ /*; Charlottesville, VA 22903-2475 USA */ /*--------------------------------------------------------------------*/ #include "ObitRMFit.h" #include "ObitThread.h" #include "ObitSinCos.h" #ifdef HAVE_GSL #include <gsl/gsl_blas.h> #endif /* HAVE_GSL */ #ifndef VELIGHT #define VELIGHT 2.997924562e8 #endif /* VELIGHT */ /*----------------Obit: Merx mollis mortibus nuper ------------------*/ /** * \file ObitRMFit.c * ObitRMFit class function definitions. * This class is derived from the Obit base class. */ /** name of the class defined in this file */ static gchar *myClassName = "ObitRMFit"; /** Function to obtain parent ClassInfo */ static ObitGetClassFP ObitParentGetClass = ObitGetClass; /** * ClassInfo structure ObitRMFitClassInfo. * This structure is used by class objects to access class functions. */ static ObitRMFitClassInfo myClassInfo = {FALSE}; /*--------------- File Global Variables ----------------*/ /*---------------Private function prototypes----------------*/ /** Private: Initialize newly instantiated object. */ void ObitRMFitInit (gpointer in); /** Private: Deallocate members. */ void ObitRMFitClear (gpointer in); /** Private: Set Class function pointers. */ static void ObitRMFitClassInfoDefFn (gpointer inClass); /** Private: Do actual fitting */ static void Fitter (ObitRMFit* in, ObitErr *err); /** Private: Write output image */ static void WriteOutput (ObitRMFit* in, ObitImage *outImage, ObitErr *err); #ifdef HAVE_GSL /** Private: Solver function evaluation */ static int RMFitFunc (const gsl_vector *x, void *params, gsl_vector *f); /** Private: Solver Jacobian evaluation */ static int RMFitJac (const gsl_vector *x, void *params, gsl_matrix *J); /** Private: Solver function + Jacobian evaluation */ static int RMFitFuncJac (const gsl_vector *x, void *params, gsl_vector *f, gsl_matrix *J); #endif /* HAVE_GSL */ /** Private: Threaded fitting */ static gpointer ThreadNLRMFit (gpointer arg); /** Private: Threaded RM synthesis fitting */ static gpointer ThreadRMSynFit (gpointer arg); /*---------------Private structures----------------*/ /* FT threaded function argument */ typedef struct { /** ObitRMFit object */ ObitRMFit *in; /* Obit error stack object */ ObitErr *err; /** First (1-rel) value in y to process this thread */ olong first; /** Highest (1-rel) value in y to process this thread */ olong last; /** thread number, >0 -> no threading */ olong ithread; /** max number of terms to fit */ olong nterm; /** number of frequencies */ olong nlamb2; /** number of valid data points in x, q, u, w */ olong nvalid; /** maximum iteration */ olong maxIter; /** acceptable iteration delta, rel and abs. */ odouble minDelta; /** Array of Lambda^2 (nlamb2) */ ofloat *lamb2; /** Array of Q, U weights (1/RMS) per inFArrays (nlamb2) */ ofloat *Qweight, *Uweight; /** Array of Q, U variance per inFArrays (nlamb2) */ ofloat *Qvar, *Uvar; /** Array of Q, U pixel values being fitted (nlamb2) */ ofloat *Qobs, *Uobs; /** Array of polarized intensity pixel values being fitted (nlamb2) */ ofloat *Pobs; /** min Q/U SNR */ ofloat minQUSNR; /** min fraction of valid samples */ ofloat minFrac; /** Reference lambda^2 */ ofloat refLamb2; /** Vector of guess/fitted coefficients, optional errors */ ofloat *coef; /** Chi squared of fit */ ofloat ChiSq; /** Do error analysis? */ gboolean doError; /** work arrays */ double *x, *q, *u, *w; ofloat *wrk1, *wrk2, *wrk3; #ifdef HAVE_GSL /** Fitting solver */ gsl_multifit_fdfsolver *solver; /** Fitting solver function structure */ gsl_multifit_function_fdf *funcStruc; /** Fitting work vector */ gsl_vector *work; /** Covariance matrix */ gsl_matrix *covar; #endif /* HAVE_GSL */ } NLRMFitArg; /** Private: Actual fitting */ static void NLRMFit (NLRMFitArg *arg); /** Private: coarse search */ static olong RMcoarse (NLRMFitArg *arg); /*----------------------Public functions---------------------------*/ /** * Constructor. * Initializes class if needed on first call. * \param name An optional name for the object. * \return the new object. */ ObitRMFit* newObitRMFit (gchar* name) { ObitRMFit* out; ofloat s, c; /* Class initialization if needed */ if (!myClassInfo.initialized) ObitRMFitClassInit(); /* allocate/init structure */ out = g_malloc0(sizeof(ObitRMFit)); /* initialize values */ if (name!=NULL) out->name = g_strdup(name); else out->name = g_strdup("Noname"); /* set ClassInfo */ out->ClassInfo = (gpointer)&myClassInfo; /* initialize other stuff */ ObitRMFitInit((gpointer)out); ObitSinCosCalc(0.0, &s, &c); /* Sine/cosine functions */ return out; } /* end newObitRMFit */ /** * Returns ClassInfo pointer for the class. * \return pointer to the class structure. */ gconstpointer ObitRMFitGetClass (void) { /* Class initialization if needed */ if (!myClassInfo.initialized) ObitRMFitClassInit(); return (gconstpointer)&myClassInfo; } /* end ObitRMFitGetClass */ /** * Make a deep copy of an ObitRMFit. * \param in The object to copy * \param out An existing object pointer for output or NULL if none exists. * \param err Obit error stack object. * \return pointer to the new object. */ ObitRMFit* ObitRMFitCopy (ObitRMFit *in, ObitRMFit *out, ObitErr *err) { const ObitClassInfo *ParentClass; gboolean oldExist; gchar *outName; olong i, nOut; /* error checks */ if (err->error) return out; g_assert (ObitIsA(in, &myClassInfo)); if (out) g_assert (ObitIsA(out, &myClassInfo)); /* Create if it doesn't exist */ oldExist = out!=NULL; if (!oldExist) { /* derive object name */ outName = g_strconcat ("Copy: ",in->name,NULL); out = newObitRMFit(outName); g_free(outName); } /* deep copy any base class members */ ParentClass = myClassInfo.ParentClass; g_assert ((ParentClass!=NULL) && (ParentClass->ObitCopy!=NULL)); ParentClass->ObitCopy (in, out, err); /* copy this class */ out->nlamb2 = in->nlamb2; out->nterm = in->nterm; /* Arrays */ if (out->QRMS) g_free(out->QRMS); out->QRMS = g_malloc0(out->nlamb2*sizeof(ofloat)); if (in->QRMS) for (i=0; i<out->nlamb2; i++) out->QRMS[i] = in->QRMS[i]; if (out->URMS) g_free(out->URMS); out->URMS = g_malloc0(out->nlamb2*sizeof(ofloat)); if (in->URMS) for (i=0; i<out->nlamb2; i++) out->URMS[i] = in->URMS[i]; /* reference this class members */ if (out->outDesc) out->outDesc = ObitImageDescUnref(out->outDesc); if (in->outDesc) out->outDesc = ObitImageDescRef(in->outDesc); if (out->inQFArrays) { for (i=0; i<in->nlamb2; i++) out->inQFArrays[i] = ObitFArrayUnref(out->inQFArrays[i]); } if (in->inQFArrays) { for (i=0; i<in->nlamb2; i++) out->inQFArrays[i] = ObitFArrayRef(in->inQFArrays[i]); } if (out->inUFArrays) { for (i=0; i<in->nlamb2; i++) out->inUFArrays[i] = ObitFArrayUnref(out->inUFArrays[i]); } if (in->inUFArrays) { for (i=0; i<in->nlamb2; i++) out->inUFArrays[i] = ObitFArrayRef(in->inUFArrays[i]); } /* How many output planes */ if (in->doError) nOut = 1+in->nterm*2; else nOut = in->nterm; if (out->outFArrays) { for (i=0; i<nOut; i++) out->outFArrays[i] = ObitFArrayUnref(out->outFArrays[i]); } if (in->outFArrays) { for (i=0; i<nOut; i++) out->outFArrays[i] = ObitFArrayRef(in->outFArrays[i]); } return out; } /* end ObitRMFitCopy */ /** * Make a copy of a object but do not copy the actual data * This is useful to create an RMFit similar to the input one. * \param in The object to copy * \param out An existing object pointer for output, must be defined. * \param err Obit error stack object. */ void ObitRMFitClone (ObitRMFit *in, ObitRMFit *out, ObitErr *err) { const ObitClassInfo *ParentClass; olong i, nOut; /* error checks */ g_assert (ObitErrIsA(err)); if (err->error) return; g_assert (ObitIsA(in, &myClassInfo)); g_assert (ObitIsA(out, &myClassInfo)); /* deep copy any base class members */ ParentClass = myClassInfo.ParentClass; g_assert ((ParentClass!=NULL) && (ParentClass->ObitCopy!=NULL)); ParentClass->ObitCopy (in, out, err); /* copy this class */ out->nlamb2 = in->nlamb2; out->nterm = in->nterm; /* Arrays */ if (out->QRMS) g_free(out->QRMS); out->QRMS = g_malloc0(out->nlamb2*sizeof(ofloat)); if (in->QRMS) for (i=0; i<out->nlamb2; i++) out->QRMS[i] = in->QRMS[i]; if (out->URMS) g_free(out->URMS); out->URMS = g_malloc0(out->nlamb2*sizeof(ofloat)); if (in->URMS) for (i=0; i<out->nlamb2; i++) out->URMS[i] = in->URMS[i]; /* reference this class members */ if (out->outDesc) out->outDesc = ObitImageDescUnref(out->outDesc); if (in->outDesc) out->outDesc = ObitImageDescRef(in->outDesc); if (out->inQFArrays) { for (i=0; i<in->nlamb2; i++) out->inQFArrays[i] = ObitFArrayUnref(out->inQFArrays[i]); } if (in->inQFArrays) { for (i=0; i<in->nlamb2; i++) out->inQFArrays[i] = ObitFArrayRef(in->inQFArrays[i]); } if (out->inUFArrays) { for (i=0; i<in->nlamb2; i++) out->inUFArrays[i] = ObitFArrayUnref(out->inUFArrays[i]); } if (in->inUFArrays) { for (i=0; i<in->nlamb2; i++) out->inUFArrays[i] = ObitFArrayRef(in->inUFArrays[i]); } /* How many output planes */ if (in->doError) nOut = 1+in->nterm*2; else nOut = in->nterm; if (out->outFArrays) { for (i=0; i<nOut; i++) out->outFArrays[i] = ObitFArrayUnref(out->outFArrays[i]); } if (in->outFArrays) { for (i=0; i<nOut; i++) out->outFArrays[i] = ObitFArrayRef(in->outFArrays[i]); } } /* end ObitRMFitClone */ /** * Creates an ObitRMFit * \param name An optional name for the object. * \param nterm Number of coefficients of powers of log(nu) * \return the new object. */ ObitRMFit* ObitRMFitCreate (gchar* name, olong nterm) { ObitRMFit* out; /* Create basic structure */ out = newObitRMFit (name); out->nterm = nterm; return out; } /* end ObitRMFitCreate */ /** * Fit RM to an image cube pixels. * The third axis of the output image will be "SPECRM " to indicate that the * planes are RM fit parameters. The "CRVAL" on this axis will be the reference * Frequency for the fitting. * Item "NTERM" is added to the output image descriptor * \param in Spectral fitting object * Potential parameters on in->info: * \li "refLamb2" OBIT_double scalar Reference frequency for fit [def ref for inQImage] * \li "minQUSNR" OBIT_float scalar min. SNR for Q and U pixels [def 3.0] * \li "minFrac" OBIT_float scalar min. fraction of planes included [def 0.5] * \li "doError" OBIT_boolean scalar If true do error analysis [def False] * \li "doRMSyn" OBIT_boolean scalar If true do max RM synthesis [def False] * \li "maxRMSyn" OBIT_float scalar max RM to search (rad/m^2) [def ambiguity] * \li "minRMSyn" OBIT_float scalar min RM to search (rad/m^2)[def -ambiguity] * \li "delRMSyn" OBIT_float scalar RM increment for search (rad/m^2)[def 1.0] * \li "maxChi2" OBIT_float scalar max Chi^2 for search [def 10.0] * * \param inQImage Q Image cube to be fitted * \param inUImage U Image cube to be fitted * \param outImage Image cube with fitted spectra. * Should be defined but not created. * Planes 1->nterm are coefficients per pixel * if doError: * Planes nterm+1->2*nterm are uncertainties in coefficients * Plane 2*nterm+1 = Chi squared of fit * if do RMsyn, planes are 1=RM, 2=EVPA@0 lambda, 3=amp@0 lambda, 4=sum wt. * \param err Obit error stack object. */ void ObitRMFitCube (ObitRMFit* in, ObitImage *inQImage, ObitImage *inUImage, ObitImage *outImage, ObitErr *err) { olong i, iplane, nOut, plane[5]={1,1,1,1,1}, noffset=0; olong naxis[2]; ObitIOSize IOBy; ObitInfoType type; ObitIOCode retCode; union ObitInfoListEquiv InfoReal; gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1}; odouble freq; gchar *today=NULL, *SPECRM = "SPECRM ", *MaxRMSyn = "MaxRMSyn", keyword[9]; ObitHistory *inHist=NULL, *outHist=NULL; gchar hiCard[73], *TF[2]={"False","True"}; gchar *routine = "ObitRMFitCube"; /* error checks */ if (err->error) return; g_assert (ObitIsA(in, &myClassInfo)); g_assert(ObitImageIsA(inQImage)); g_assert(ObitImageIsA(inUImage)); g_assert(ObitImageIsA(outImage)); /* Warn if no GSL implementation */ #ifndef HAVE_GSL Obit_log_error(err, OBIT_InfoWarn, "NO GSL available - results will be approximate"); #endif /* Control parameters */ /* Min Q/U pixel SNR for fit */ InfoReal.flt = 3.0; type = OBIT_float; in->minQUSNR = 3.0; ObitInfoListGetTest(in->info, "minQUSNR", &type, dim, &InfoReal); if (type==OBIT_float) in->minQUSNR = InfoReal.flt; else if (type==OBIT_double) in->minQUSNR = (ofloat)InfoReal.dbl; /* Min fraction of planes in the fit */ InfoReal.flt = 0.5; type = OBIT_float; in->minFrac = 0.5; ObitInfoListGetTest(in->info, "minFrac", &type, dim, &InfoReal); if (type==OBIT_float) in->minFrac = InfoReal.flt; else if (type==OBIT_double) in->minFrac = (ofloat)InfoReal.dbl; /* Want Error analysis? */ InfoReal.itg = (olong)FALSE; type = OBIT_bool; ObitInfoListGetTest(in->info, "doError", &type, dim, &InfoReal); in->doError = InfoReal.itg; /* Want max RM Synthesis? */ InfoReal.itg = (olong)FALSE; type = OBIT_bool; ObitInfoListGetTest(in->info, "doRMSyn", &type, dim, &InfoReal); in->doRMSyn = InfoReal.itg; if (in->doRMSyn) Obit_log_error(err, OBIT_InfoErr, "Using Max RM Synthesis"); /* Max RM for RM syn search */ InfoReal.flt = 0.0; type = OBIT_float; in->maxRMSyn = 0.0; ObitInfoListGetTest(in->info, "maxRMSyn", &type, dim, &InfoReal); if (type==OBIT_float) in->maxRMSyn = InfoReal.flt; else if (type==OBIT_double) in->maxRMSyn = (ofloat)InfoReal.dbl; /* Min RM for RM syn search */ InfoReal.flt = 1.0; type = OBIT_float; in->minRMSyn = 1.0; ObitInfoListGetTest(in->info, "minRMSyn", &type, dim, &InfoReal); if (type==OBIT_float) in->minRMSyn = InfoReal.flt; else if (type==OBIT_double) in->minRMSyn = (ofloat)InfoReal.dbl; /* Delta RM for RM syn search */ InfoReal.flt = 1.0; type = OBIT_float; in->delRMSyn = 1.0; ObitInfoListGetTest(in->info, "delRMSyn", &type, dim, &InfoReal); if (type==OBIT_float) in->delRMSyn = InfoReal.flt; else if (type==OBIT_double) in->delRMSyn = (ofloat)InfoReal.dbl; /* maxChi2 for RM syn search */ InfoReal.flt = 10.0; type = OBIT_float; in->maxChi2 = 10.0; ObitInfoListGetTest(in->info, "maxChi2", &type, dim, &InfoReal); if (type==OBIT_float) in->maxChi2 = InfoReal.flt; else if (type==OBIT_double) in->maxChi2 = (ofloat)InfoReal.dbl; /* Open input images to get info */ IOBy = OBIT_IO_byPlane; dim[0] = 1; ObitInfoListAlwaysPut (inQImage->info, "IOBy", OBIT_long, dim, &IOBy); inQImage->extBuffer = TRUE; /* Using inFArrays as I/O buffer */ retCode = ObitImageOpen (inQImage, OBIT_IO_ReadOnly, err); if ((retCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine, inQImage->name); ObitInfoListAlwaysPut (inUImage->info, "IOBy", OBIT_long, dim, &IOBy); inUImage->extBuffer = TRUE; /* Using inFArrays as I/O buffer */ retCode = ObitImageOpen (inUImage, OBIT_IO_ReadOnly, err); if ((retCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine, inUImage->name); /* Check compatability */ Obit_return_if_fail(((inQImage->myDesc->inaxes[0]==inUImage->myDesc->inaxes[0]) && (inQImage->myDesc->inaxes[1]==inUImage->myDesc->inaxes[1]) && (inQImage->myDesc->inaxes[2]==inUImage->myDesc->inaxes[2])), err, "%s: Input images incompatable", routine); /* Get Reference frequency/lambda^2 , default from input Q ref. freq. */ InfoReal.dbl = VELIGHT/inQImage->myDesc->crval[inQImage->myDesc->jlocf]; InfoReal.dbl *= InfoReal.dbl; type = OBIT_double; in->refLamb2 = InfoReal.dbl; ObitInfoListGetTest(in->info, "refLamb2", &type, dim, &InfoReal); if (type==OBIT_float) in->refLamb2 = InfoReal.flt; else if (type==OBIT_double) in->refLamb2 = (ofloat)InfoReal.dbl; in->refLamb2 = MAX (1.0e-10, in->refLamb2); /* Avoid zero divide */ /* What plane does spectral data start on */ if (!strncmp(inQImage->myDesc->ctype[inQImage->myDesc->jlocf], "SPECLNMF", 8)) { noffset = 2; /* What plane does spectral data start on */ ObitInfoListGetTest (inQImage->myDesc->info, "NTERM", &type, dim, &noffset); } else { /* Normal spectral cube */ noffset = 0; } /* Determine number of frequency planes and initialize in */ in->nlamb2 = inQImage->myDesc->inaxes[inQImage->myDesc->jlocf]-noffset; in->QRMS = g_malloc0(in->nlamb2*sizeof(ofloat)); in->URMS = g_malloc0(in->nlamb2*sizeof(ofloat)); in->inQFArrays = g_malloc0(in->nlamb2*sizeof(ObitFArray*)); in->inUFArrays = g_malloc0(in->nlamb2*sizeof(ObitFArray*)); in->lamb2 = g_malloc0(in->nlamb2*sizeof(odouble)); /* How many output planes? */ if (in->doError) nOut = 1+in->nterm*2; else nOut = in->nterm; /* always 4 for doRMSyn */ if (in->doRMSyn) nOut = 4; /* Define term arrays */ in->outFArrays = g_malloc0((nOut)*sizeof(ObitFArray*)); for (i=0; i<nOut; i++) in->outFArrays[i] = NULL; /* Image size */ in->nx = inQImage->myDesc->inaxes[0]; in->ny = inQImage->myDesc->inaxes[1]; naxis[0] = (olong)in->nx; naxis[1] = (olong)in->ny; for (i=0; i<in->nlamb2; i++) in->inQFArrays[i] = ObitFArrayCreate (NULL, 2, naxis); for (i=0; i<in->nlamb2; i++) in->inUFArrays[i] = ObitFArrayCreate (NULL, 2, naxis); for (i=0; i<nOut; i++) in->outFArrays[i] = ObitFArrayCreate (NULL, 2, naxis); /* Output Image descriptor */ outImage->myDesc = ObitImageDescCopy (inQImage->myDesc, in->outDesc, err); if (err->error) Obit_traceback_msg (err, routine, inQImage->name); /* Change third axis to type "SPECRM " and leave the reference frequency as the "CRVAL" */ outImage->myDesc->inaxes[outImage->myDesc->jlocf] = nOut; outImage->myDesc->crval[outImage->myDesc->jlocf] = VELIGHT/sqrt(in->refLamb2); outImage->myDesc->crpix[outImage->myDesc->jlocf] = 1.0; outImage->myDesc->cdelt[outImage->myDesc->jlocf] = 1.0; if (in->doRMSyn) strncpy (outImage->myDesc->ctype[outImage->myDesc->jlocf], MaxRMSyn, IMLEN_KEYWORD); else strncpy (outImage->myDesc->ctype[outImage->myDesc->jlocf], SPECRM , IMLEN_KEYWORD); outImage->myDesc->bitpix = -32; /* Float it */ /* Creation date today */ today = ObitToday(); strncpy (outImage->myDesc->date, today, IMLEN_VALUE); if (today) g_free(today); /* Copy of output descriptor to in */ in->outDesc = ObitImageDescCopy (outImage->myDesc, in->outDesc, err); /* Loop reading planes */ for (iplane=0; iplane<in->nlamb2; iplane++) { /* Lambda^2 Check for MFImage outputs */ if (!strncmp(inQImage->myDesc->ctype[inQImage->myDesc->jlocf], "SPECLNMF", 8)) { sprintf (keyword, "FREQ%4.4d",iplane+1); freq = inQImage->myDesc->crval[inQImage->myDesc->jlocf] + inQImage->myDesc->cdelt[inQImage->myDesc->jlocf] * (inQImage->myDesc->plane - inQImage->myDesc->crpix[inQImage->myDesc->jlocf]); ObitInfoListGetTest (inQImage->myDesc->info, keyword, &type, dim, &freq); } else { /* Normal spectral cube */ freq = inQImage->myDesc->crval[inQImage->myDesc->jlocf] + inQImage->myDesc->cdelt[inQImage->myDesc->jlocf] * (inQImage->myDesc->plane - inQImage->myDesc->crpix[inQImage->myDesc->jlocf]); } in->lamb2[iplane] = (VELIGHT/freq)*(VELIGHT/freq); plane[0] = iplane+noffset+1; /* Select correct plane */ retCode = ObitImageGetPlane (inQImage, in->inQFArrays[iplane]->array, plane, err); retCode = ObitImageGetPlane (inUImage, in->inUFArrays[iplane]->array, plane, err); /* if it didn't work bail out */ if ((retCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine, inQImage->name); /* Plane RMSes */ in->QRMS[iplane] = ObitFArrayRMS(in->inQFArrays[iplane]); in->URMS[iplane] = ObitFArrayRMS(in->inUFArrays[iplane]); } /* end loop reading planes */ /* Close inputs */ retCode = ObitImageClose (inQImage, err); inQImage->extBuffer = FALSE; /* May need I/O buffer later */ retCode = ObitImageClose (inUImage, err); inUImage->extBuffer = FALSE; /* May need I/O buffer later */ /* if it didn't work bail out */ if ((retCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine, inQImage->name); /* Do actual fitting */ Fitter (in, err); if (err->error) Obit_traceback_msg (err, routine, inQImage->name); /* Update output header to reference Frequency */ outImage->myDesc->crval[outImage->myDesc->jlocf] = VELIGHT/sqrt(in->refLamb2); in->outDesc->crval[in->outDesc->jlocf] = VELIGHT/sqrt(in->refLamb2); /* Write output */ WriteOutput(in, outImage, err); if (err->error) Obit_traceback_msg (err, routine, inQImage->name); /* History */ /* Copy any history */ inHist = newObitDataHistory((ObitData*)inQImage, OBIT_IO_ReadOnly, err); outHist = newObitDataHistory((ObitData*)outImage, OBIT_IO_WriteOnly, err); outHist = ObitHistoryCopy (inHist, outHist, err); /* Add parameters */ ObitHistoryOpen (outHist, OBIT_IO_ReadWrite, err); ObitHistoryTimeStamp (outHist, "ObitRMFitCube", err); g_snprintf ( hiCard, 72, "RMCube nterm = %d",in->nterm); ObitHistoryWriteRec (outHist, -1, hiCard, err); g_snprintf ( hiCard, 72, "RMCube refLamb2 = %lf",in->refLamb2); ObitHistoryWriteRec (outHist, -1, hiCard, err); g_snprintf ( hiCard, 72, "RMCube minQUSNR = %f",in->minQUSNR); ObitHistoryWriteRec (outHist, -1, hiCard, err); g_snprintf ( hiCard, 72, "RMCube minFrac = %f",in->minFrac); ObitHistoryWriteRec (outHist, -1, hiCard, err); g_snprintf ( hiCard, 72, "RMCube doRMSyn = %s",TF[in->doRMSyn]); ObitHistoryWriteRec (outHist, -1, hiCard, err); if (in->doRMSyn) { ObitHistoryWriteRec (outHist, -1, hiCard, err); g_snprintf ( hiCard, 72, "RMCube maxRMSyn = %f",in->maxRMSyn); ObitHistoryWriteRec (outHist, -1, hiCard, err); g_snprintf ( hiCard, 72, "RMCube minRMSyn = %f",in->minRMSyn); ObitHistoryWriteRec (outHist, -1, hiCard, err); g_snprintf ( hiCard, 72, "RMCube delRMSyn = %f",in->delRMSyn); ObitHistoryWriteRec (outHist, -1, hiCard, err); g_snprintf ( hiCard, 72, "RMCube maxChi2 = %f", in->maxChi2); ObitHistoryWriteRec (outHist, -1, hiCard, err); } /* end doRMSyn */ ObitHistoryClose (outHist, err); if (err->error) Obit_traceback_msg (err, routine, in->name); inHist = ObitHistoryUnref(inHist); outHist = ObitHistoryUnref(outHist); } /* end ObitRMFitCube */ /** * Fit RM to an array of images * The third axis of the output image will be "SPECRM " to indicate that then * planes are spectral fit parameters. The "CRVAL" on this axis will be the reference * Frequency for the fitting. * Item "NTERM" is added to the output image descriptor to give the maximum number * of terms fitted * \param in Spectral fitting object * \li "refLamb2" OBIT_double scalar Reference frequency for fit [def average of inputs] * \li "minQUSNR" OBIT_float scalar Max. min. SNR for Q and U pixels [def 3.0] * \li "doError" OBIT_boolean scalar If true do error analysis [def False] * \param nimage Number of entries in imQArr * \param imQArr Array of Q images to be fitted * \param imUArr Array of U images to be fitted, same geometry as imQArr * \param outImage Image cube with fitted parameters. * Should be defined but not created. * Planes 1->nterm are coefficients per pixel * if doError: * Planes nterm+1->2*nterm are uncertainties in coefficients * Plane 2*nterm+1 = Chi squared of fit * \param err Obit error stack object. */ void ObitRMFitImArr (ObitRMFit* in, olong nimage, ObitImage **imQArr, ObitImage **imUArr, ObitImage *outImage, ObitErr *err) { olong i, iplane, nOut; olong naxis[2]; ObitIOSize IOBy; ObitInfoType type; ObitIOCode retCode; union ObitInfoListEquiv InfoReal; gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1}; ofloat ipixel[2], opixel[2]; gboolean bad; odouble avgLamb2, freq; gchar *today=NULL, *SPECRM = "SPECRM "; gchar *routine = "ObitRMFitCube"; /* error checks */ if (err->error) return; g_assert (ObitIsA(in, &myClassInfo)); g_assert(ObitImageIsA(outImage)); /* Warn if no GSL implementation */ #ifndef HAVE_GSL Obit_log_error(err, OBIT_InfoWarn, "NO GSL available - results will be approximate"); #endif /* Control parameters */ /* Min Q/U pixel SNR for fit */ InfoReal.flt = 3.0; type = OBIT_float; in->minQUSNR = 3.0; ObitInfoListGetTest(in->info, "minQUSNR", &type, dim, &InfoReal); if (type==OBIT_float) in->minQUSNR = InfoReal.flt; else if (type==OBIT_double) in->minQUSNR = (ofloat)InfoReal.dbl; /* Min fraction of planes in the fit */ InfoReal.flt = 0.5; type = OBIT_float; in->minFrac = 0.5; ObitInfoListGetTest(in->info, "minFrac", &type, dim, &InfoReal); if (type==OBIT_float) in->minFrac = InfoReal.flt; else if (type==OBIT_double) in->minFrac = (ofloat)InfoReal.dbl; /* Want Error analysis? */ InfoReal.itg = (olong)FALSE; type = OBIT_bool; ObitInfoListGetTest(in->info, "doError", &type, dim, &InfoReal); in->doError = InfoReal.itg; /* Determine number of lambda^2 planes and initialize in */ in->nlamb2 = nimage; in->QRMS = g_malloc0(in->nlamb2*sizeof(ofloat)); in->URMS = g_malloc0(in->nlamb2*sizeof(ofloat)); in->inQFArrays = g_malloc0(in->nlamb2*sizeof(ObitFArray*)); in->inUFArrays = g_malloc0(in->nlamb2*sizeof(ObitFArray*)); in->lamb2 = g_malloc0(in->nlamb2*sizeof(odouble)); /* How many output planes? */ if (in->doError) nOut = 1+in->nterm*2; else nOut = in->nterm; /* Define term arrays */ in->outFArrays = g_malloc0((nOut)*sizeof(ObitFArray*)); for (i=0; i<nOut; i++) in->outFArrays[i] = NULL; /* Loop over images */ for (iplane = 0; iplane<nimage; iplane++) { /* Open input image to get info */ IOBy = OBIT_IO_byPlane; dim[0] = 1; ObitInfoListAlwaysPut (imQArr[iplane]->info, "IOBy", OBIT_long, dim, &IOBy); imQArr[iplane]->extBuffer = TRUE; /* Using inFArrays as I/O buffer */ retCode = ObitImageOpen (imQArr[iplane], OBIT_IO_ReadOnly, err); ObitInfoListAlwaysPut (imUArr[iplane]->info, "IOBy", OBIT_long, dim, &IOBy); imUArr[iplane]->extBuffer = TRUE; /* Using inFArrays as I/O buffer */ retCode = ObitImageOpen (imUArr[iplane], OBIT_IO_ReadOnly, err); /* if it didn't work bail out */ if ((retCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine, imQArr[iplane]->name); /* On first image initialize */ if (iplane==0) { /* Image size */ in->nx = imQArr[iplane]->myDesc->inaxes[0]; in->ny = imQArr[iplane]->myDesc->inaxes[1]; naxis[0] = (olong)in->nx; naxis[1] = (olong)in->ny; for (i=0; i<in->nlamb2; i++) in->inQFArrays[i] = ObitFArrayCreate (NULL, 2, naxis); for (i=0; i<in->nlamb2; i++) in->inUFArrays[i] = ObitFArrayCreate (NULL, 2, naxis); for (i=0; i<nOut; i++) in->outFArrays[i] = ObitFArrayCreate (NULL, 2, naxis); /* Output Image descriptor */ outImage->myDesc = ObitImageDescCopy (imQArr[iplane]->myDesc, in->outDesc, err); if (err->error) Obit_traceback_msg (err, routine, imQArr[iplane]->name); /* Change third axis to type "SPECRM " and leave the reference frequency as the "CRVAL" */ outImage->myDesc->inaxes[outImage->myDesc->jlocf] = nOut; outImage->myDesc->crpix[outImage->myDesc->jlocf] = 1.0; outImage->myDesc->cdelt[outImage->myDesc->jlocf] = 1.0; strncpy (outImage->myDesc->ctype[outImage->myDesc->jlocf], SPECRM , IMLEN_KEYWORD); outImage->myDesc->bitpix = -32; /* Float it */ /* Creation date today */ today = ObitToday(); strncpy (outImage->myDesc->date, today, IMLEN_VALUE); if (today) g_free(today); /* Copy of output descriptor to in */ in->outDesc = ObitImageDescCopy (outImage->myDesc, in->outDesc, err); } else { /* On subsequent images check for consistency */ /* Check size of planes */ Obit_return_if_fail(((imQArr[iplane]->myDesc->inaxes[0]==in->outDesc->inaxes[0]) && (imQArr[iplane]->myDesc->inaxes[1]==in->outDesc->inaxes[1])), err, "%s: Image planes incompatible %d!= %d or %d!= %d", routine, imQArr[iplane]->myDesc->inaxes[0], in->outDesc->inaxes[0], imQArr[iplane]->myDesc->inaxes[1], in->outDesc->inaxes[1]) ; Obit_return_if_fail(((imUArr[iplane]->myDesc->inaxes[0]==in->outDesc->inaxes[0]) && (imUArr[iplane]->myDesc->inaxes[1]==in->outDesc->inaxes[1])), err, "%s: Image planes incompatible %d!= %d or %d!= %d", routine, imUArr[iplane]->myDesc->inaxes[0], in->outDesc->inaxes[0], imUArr[iplane]->myDesc->inaxes[1], in->outDesc->inaxes[1]) ; /* Check alignment of pixels */ ipixel[0] = 1.0; ipixel[1] = 1.0; bad = !ObitImageDescCvtPixel (imQArr[iplane]->myDesc, in->outDesc, ipixel, opixel, err); if (err->error) Obit_traceback_msg (err, routine, imQArr[iplane]->name); Obit_return_if_fail(!bad, err, "%s: Image planes incompatible", routine); Obit_return_if_fail(((fabs(ipixel[0]-opixel[0])<0.01) && (fabs(ipixel[1]-opixel[1])<0.01)), err, "%s: Image pixels not aligned %f!=%f or %f!=%f", routine, ipixel[0], opixel[0], ipixel[1], opixel[1]) ; } /* end consistency check */ /* Read planes */ retCode = ObitImageRead (imQArr[iplane], in->inQFArrays[iplane]->array, err); retCode = ObitImageRead (imUArr[iplane], in->inUFArrays[iplane]->array, err); /* if it didn't work bail out */ if ((retCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine, imQArr[iplane]->name); /* Plane RMSes */ in->QRMS[iplane] = ObitFArrayRMS(in->inQFArrays[iplane]); in->URMS[iplane] = ObitFArrayRMS(in->inUFArrays[iplane]); /* Lambda^2 */ freq = imQArr[iplane]->myDesc->crval[imQArr[iplane]->myDesc->jlocf] + imQArr[iplane]->myDesc->cdelt[imQArr[iplane]->myDesc->jlocf] * (imQArr[iplane]->myDesc->plane - imQArr[iplane]->myDesc->crpix[imQArr[iplane]->myDesc->jlocf]); in->lamb2[iplane] = (VELIGHT/freq)*(VELIGHT/freq); /* Close inputs */ retCode = ObitImageClose (imQArr[iplane], err); imQArr[iplane]->extBuffer = FALSE; /* May need I/O buffer later */ retCode = ObitImageClose (imUArr[iplane], err); imUArr[iplane]->extBuffer = FALSE; /* May need I/O buffer later */ /* if it didn't work bail out */ if ((retCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine, imQArr[iplane]->name); } /* end loop over input images */ /* Average Lambda^2 */ avgLamb2 = 0.0; for (i=0; i<in->nlamb2; i++) avgLamb2 += in->lamb2[i]; avgLamb2 /= in->nlamb2; /* Get Reference lambda^2 , default avg. input ref. freq. */ InfoReal.dbl = avgLamb2; type = OBIT_double; in->refLamb2 = InfoReal.dbl; ObitInfoListGetTest(in->info, "refLamb2", &type, dim, &InfoReal); if (type==OBIT_float) in->refLamb2 = InfoReal.flt; else if (type==OBIT_double) in->refLamb2 = (ofloat)InfoReal.dbl; in->refLamb2 = MAX (1.0e-10, in->refLamb2); /* Avoid zero divide */ /* Update output header to reference Frequency */ outImage->myDesc->crval[outImage->myDesc->jlocf] =VELIGHT/sqrt(in->refLamb2); in->outDesc->crval[in->outDesc->jlocf] = VELIGHT/sqrt(in->refLamb2); /* Do actual fitting */ Fitter (in, err); if (err->error) Obit_traceback_msg (err, routine, imQArr[0]->name); /* Write output */ WriteOutput(in, outImage, err); if (err->error) Obit_traceback_msg (err, routine, outImage->name); } /* end ObitRMFitImArr */ /** * Fit single RM to Q, Uflux measurements * \param nlamb2 Number of entries in freq, flux, sigma * \param nterm Number of coefficients of powers of log(nu) to fit * \param refLamb2 Reference lambda^2 (m^2) * \param lamb2 Array of lambda^2 (m^2) * \param qflux Array of Q fluxes (Jy) same dim as lamb2 * \param qsigma Array of Q errors (Jy) same dim as lamb2 * \param uflux Array of U fluxes (Jy) same dim as lamb2 * \param usigma Array of U errors (Jy) same dim as lamb2 * \param err Obit error stack object. * \return Array of fitter parameters, errors for each and Chi Squares of fit * Initial terms are in Jy, other in log. */ ofloat* ObitRMFitSingle (olong nlamb2, olong nterm, odouble refLamb2, odouble *lamb2, ofloat *qflux, ofloat *qsigma, ofloat *uflux, ofloat *usigma, ObitErr *err) { ofloat *out = NULL; ofloat fblank = ObitMagicF(); olong i, j; NLRMFitArg *arg=NULL; gchar *routine = "ObitRMFitSingle"; /* GSL implementation */ #ifdef HAVE_GSL const gsl_multifit_fdfsolver_type *T=NULL; #endif /* HAVE_GSL */ /* Warn if no GSL implementation */ #ifndef HAVE_GSL Obit_log_error(err, OBIT_InfoWarn, "NO GSL available - results will be approximate"); #endif if (err->error) return out; /* Warn if ref. lambda^2 <= 0, set to 1.0 */ if (refLamb2<=0.0) { refLamb2 = 1.0; Obit_log_error(err, OBIT_InfoWarn, "%s: Setting reference lambda^2 to 1", routine); } /* Create function argument */ arg = g_malloc(sizeof(NLRMFitArg)); arg->in = NULL; /* Not needed here */ arg->nlamb2 = nlamb2; arg->maxIter = 100; /* max. number of iterations */ arg->minDelta = 1.0e-5; /* Min step size */ arg->nterm = nterm; arg->doError = TRUE; arg->minQUSNR = 3.0; /* min pixel SNR */ arg->minFrac = 0.5; /* min fraction of samples */ arg->refLamb2 = refLamb2; /* Reference Frequency */ arg->Qweight = g_malloc0(arg->nlamb2*sizeof(ofloat)); arg->Uweight = g_malloc0(arg->nlamb2*sizeof(ofloat)); arg->Qvar = g_malloc0(arg->nlamb2*sizeof(ofloat)); arg->Uvar = g_malloc0(arg->nlamb2*sizeof(ofloat)); arg->Qobs = g_malloc0(arg->nlamb2*sizeof(ofloat)); arg->Uobs = g_malloc0(arg->nlamb2*sizeof(ofloat)); arg->Pobs = g_malloc0(arg->nlamb2*sizeof(ofloat)); arg->lamb2 = g_malloc0(arg->nlamb2*sizeof(ofloat)); arg->x = g_malloc0(arg->nlamb2*sizeof(double)); arg->w = g_malloc0(arg->nlamb2*sizeof(double)); arg->q = g_malloc0(arg->nlamb2*sizeof(double)); arg->u = g_malloc0(arg->nlamb2*sizeof(double)); arg->wrk1 = g_malloc0(arg->nlamb2*sizeof(ofloat)); arg->wrk2 = g_malloc0(arg->nlamb2*sizeof(ofloat)); arg->wrk3 = g_malloc0(arg->nlamb2*sizeof(ofloat)); arg->coef = g_malloc0(3*arg->nterm*sizeof(ofloat)); for (i=0; i<nlamb2; i++) { arg->lamb2[i] = lamb2[i]; arg->Qvar[i] = qsigma[i]*qsigma[i]; arg->Uvar[i] = usigma[i]*usigma[i]; arg->Qobs[i] = qflux[i]; arg->Uobs[i] = uflux[i]; if ((arg->Qobs[i]!=fblank) && (arg->Uobs[i]!=fblank)) { arg->Pobs[i] = sqrt (qflux[i]*qflux[i] + uflux[i]*uflux[i]); arg->Qweight[i] = 1.0 / qsigma[i]; arg->Uweight[i] = 1.0 / usigma[i]; } else{ arg->Pobs[i] = 0.0; arg->Qweight[i] = 0.0; arg->Uweight[i] = 0.0; } } /* GSL implementation */ #ifdef HAVE_GSL arg->solver = NULL; arg->covar = NULL; arg->work = NULL; /* Setup solver */ T = gsl_multifit_fdfsolver_lmder; arg->solver = gsl_multifit_fdfsolver_alloc(T, 2*arg->nlamb2, 2); /* Fitting function info */ arg->funcStruc = g_malloc0(sizeof(gsl_multifit_function_fdf)); arg->funcStruc->f = &RMFitFunc; arg->funcStruc->df = &RMFitJac; arg->funcStruc->fdf = &RMFitFuncJac; arg->funcStruc->n = 2*arg->nlamb2; arg->funcStruc->p = 2; arg->funcStruc->params = arg; /* Set up work arrays */ arg->covar = gsl_matrix_alloc(2, 2); arg->work = gsl_vector_alloc(2); #endif /* HAVE_GSL */ /* Do fit */ NLRMFit(arg); /* get results parameters + errors */ out = g_malloc0((2*arg->nterm+1)*sizeof(ofloat)); for (j=0; j<nterm*2+1; j++) out[j] = arg->coef[j]; /* Cleanup */ if (arg->Qweight) g_free(arg->Qweight); if (arg->Uweight) g_free(arg->Uweight); if (arg->Qvar) g_free(arg->Qvar); if (arg->Uvar) g_free(arg->Uvar); if (arg->Qobs) g_free(arg->Qobs); if (arg->Uobs) g_free(arg->Uobs); if (arg->Pobs) g_free(arg->Pobs); if (arg->lamb2) g_free(arg->lamb2); if (arg->x) g_free(arg->x); if (arg->w) g_free(arg->w); if (arg->q) g_free(arg->q); if (arg->u) g_free(arg->u); if (arg->wrk1) g_free(arg->wrk1); if (arg->wrk2) g_free(arg->wrk2); if (arg->wrk3) g_free(arg->wrk3); if (arg->coef) g_free(arg->coef); #ifdef HAVE_GSL if (arg->solver) gsl_multifit_fdfsolver_free (arg->solver); if (arg->work) gsl_vector_free(arg->work); if (arg->covar) gsl_matrix_free(arg->covar); if (arg->funcStruc) g_free(arg->funcStruc); #endif /* HAVE_GSL */ g_free(arg); return out; } /* end ObitRMFitSingle */ /** * Make single spectrum fitting argument array * \param nlamb2 Number of entries in freq, flux, sigma * \param nterm Number of coefficients of powers of log(nu) to fit * \param refLamb2 Reference lambda^2 (m^2) * \param lamb2 Array of lambda^2 (m^2) * \param out Array for output results, should be g_freed when done * \param err Obit error stack object. * \return argument for single spectrum fitting, use ObitRMFitKillArg to dispose. */ gpointer ObitRMFitMakeArg (olong nlamb2, olong nterm, odouble refLamb2, odouble *lamb2, ofloat **out, ObitErr *err) { olong i; NLRMFitArg *arg=NULL; gchar *routine = "ObitRMFitMakeArg"; #ifdef HAVE_GSL const gsl_multifit_fdfsolver_type *T=NULL; #endif /* HAVE_GSL */ if (err->error) return out; /* Warn if too many terms asked for */ if (nterm>2) { Obit_log_error(err, OBIT_InfoWarn, "%s: Asked for %d terms, will limit to 2", routine, nterm); } /* Warn if ref. lambda^2 <= 0, set to 1.0 */ if (refLamb2<=0.0) { refLamb2 = 1.0; Obit_log_error(err, OBIT_InfoWarn, "%s: Setting reference Lambda^2 to 1", routine); } /* Create function argument */ arg = g_malloc(sizeof(NLRMFitArg)); arg->in = NULL; /* Not needed here */ arg->nlamb2 = nlamb2; arg->maxIter = 100; /* max. number of iterations */ arg->minDelta = 1.0e-5; /* Min step size */ arg->nterm = nterm; arg->doError = TRUE; arg->minQUSNR = 3.0; /* min pixel SNR */ arg->minFrac = 0.5; /* min fraction of samples */ arg->refLamb2 = refLamb2; /* Reference Frequency */ arg->Qweight = g_malloc0(arg->nlamb2*sizeof(ofloat)); arg->Uweight = g_malloc0(arg->nlamb2*sizeof(ofloat)); arg->Qvar = g_malloc0(arg->nlamb2*sizeof(ofloat)); arg->Uvar = g_malloc0(arg->nlamb2*sizeof(ofloat)); arg->Qobs = g_malloc0(arg->nlamb2*sizeof(ofloat)); arg->Uobs = g_malloc0(arg->nlamb2*sizeof(ofloat)); arg->Pobs = g_malloc0(arg->nlamb2*sizeof(ofloat)); arg->lamb2 = g_malloc0(arg->nlamb2*sizeof(ofloat)); arg->x = g_malloc0(arg->nlamb2*sizeof(double)); arg->w = g_malloc0(arg->nlamb2*sizeof(double)); arg->q = g_malloc0(arg->nlamb2*sizeof(double)); arg->u = g_malloc0(arg->nlamb2*sizeof(double)); arg->wrk1 = g_malloc0(arg->nlamb2*sizeof(ofloat)); arg->wrk2 = g_malloc0(arg->nlamb2*sizeof(ofloat)); arg->wrk3 = g_malloc0(arg->nlamb2*sizeof(ofloat)); arg->coef = g_malloc0(3*arg->nterm*sizeof(ofloat)); for (i=0; i<nlamb2; i++) { arg->lamb2[i] = lamb2[i]; } /* GSL implementation */ #ifdef HAVE_GSL arg->solver = NULL; arg->covar = NULL; arg->work = NULL; /* Setup solver */ T = gsl_multifit_fdfsolver_lmder; arg->solver = gsl_multifit_fdfsolver_alloc(T, 2*arg->nlamb2, 2); /* Fitting function info */ arg->funcStruc = g_malloc0(sizeof(gsl_multifit_function_fdf)); arg->funcStruc->f = &RMFitFunc; arg->funcStruc->df = &RMFitJac; arg->funcStruc->fdf = &RMFitFuncJac; arg->funcStruc->n = 2*arg->nlamb2; arg->funcStruc->p = 2; arg->funcStruc->params = arg; /* Set up work arrays */ arg->covar = gsl_matrix_alloc(2, 2); arg->work = gsl_vector_alloc(2); #endif /* HAVE_GSL */ /* output array */ *out = (ofloat*)g_malloc0((2*arg->nterm+1)*sizeof(ofloat)); return (gpointer)arg; } /* end ObitRMFitMakeArg */ /** * Fit single RM to measurements using precomputed argument * \param aarg pointer to argument for fitting * \param Qflux Array of Q values to be fitted * \param Qsigma Array of uncertainties of Qflux * \param Uflux Array of U values to be fitted * \param Usigma Array of uncertainties of Qflux * \param out Result array at least 2*nterms+1 in size. * in order, fitted parameters, error estimates, chi sq of fit. */ void ObitRMFitSingleArg (gpointer aarg, ofloat *qflux, ofloat *qsigma, ofloat *uflux, ofloat *usigma, ofloat *out) { olong i, j; NLRMFitArg *arg=(NLRMFitArg*)aarg; ofloat fblank = ObitMagicF(); gboolean allBad; /* Save flux array, sigma, Check if all data blanked */ allBad = TRUE; for (i=0; i<arg->nlamb2; i++) { if ((arg->Qobs[i]!=fblank) && (arg->Uobs[i]!=fblank) && ((fabs(qflux[i])>arg->minQUSNR*qsigma[i]) || (fabs(uflux[i])>arg->minQUSNR*usigma[i]))) allBad = FALSE; arg->Qobs[i] = qflux[i]; arg->Uobs[i] = uflux[i]; arg->Qvar[i] = qsigma[i]; arg->Uvar[i] = usigma[i]; if ((arg->Qobs[i]!=fblank) && (arg->Uobs[i]!=fblank)) { arg->Pobs[i] = sqrt (qflux[i]*qflux[i] + uflux[i]*uflux[i]); /* arg->Qweight[i] = arg->Pobs[i] / arg->Qvar[i]; arg->Uweight[i] = arg->Pobs[i] / arg->Uvar[i]; */ arg->Qweight[i] = 1.0 / qsigma[i]; arg->Uweight[i] = 1.0 / usigma[i]; } else { arg->Pobs[i] = 0.0; arg->Qweight[i] = 0.0; arg->Uweight[i] = 0.0; } } /* Return fblanks/zeroes for no data */ if (allBad) { out[0] = fblank; for (j=1; j<=arg->nterm*2; j++) out[j] = 0.0; return; } /* Fit */ NLRMFit(arg); /* get results parameters + errors */ for (j=0; j<arg->nterm*2; j++) out[j] = arg->coef[j]; /* Chi squared */ out[arg->nterm*2] = arg->ChiSq; return; } /* end ObitRMFitSingleArg */ /** * Delete single fitting argument * \param aarg pointer to argument to kill */ void ObitRMFitKillArg (gpointer aarg) { NLRMFitArg *arg= (NLRMFitArg*)aarg; if (arg==NULL) return; if (arg->Qweight) g_free(arg->Qweight); if (arg->Uweight) g_free(arg->Uweight); if (arg->Qvar) g_free(arg->Qvar); if (arg->Uvar) g_free(arg->Uvar); if (arg->Qobs) g_free(arg->Qobs); if (arg->Uobs) g_free(arg->Uobs); if (arg->Pobs) g_free(arg->Pobs); if (arg->lamb2) g_free(arg->lamb2); if (arg->x) g_free(arg->x); if (arg->w) g_free(arg->w); if (arg->q) g_free(arg->q); if (arg->u) g_free(arg->u); if (arg->wrk1) g_free(arg->wrk1); if (arg->wrk2) g_free(arg->wrk2); if (arg->wrk3) g_free(arg->wrk3); if (arg->coef) g_free(arg->coef); #ifdef HAVE_GSL if (arg->solver) gsl_multifit_fdfsolver_free (arg->solver); if (arg->work) gsl_vector_free(arg->work); if (arg->covar) gsl_matrix_free(arg->covar); if (arg->funcStruc) g_free(arg->funcStruc); #endif /* HAVE_GSL */ g_free(arg); } /* end ObitRMFitKillArg */ /** * Initialize global ClassInfo Structure. */ void ObitRMFitClassInit (void) { if (myClassInfo.initialized) return; /* only once */ /* Set name and parent for this class */ myClassInfo.ClassName = g_strdup(myClassName); myClassInfo.ParentClass = ObitParentGetClass(); /* Set function pointers */ ObitRMFitClassInfoDefFn ((gpointer)&myClassInfo); myClassInfo.initialized = TRUE; /* Now initialized */ } /* end ObitRMFitClassInit */ /** * Initialize global ClassInfo Function pointers. */ static void ObitRMFitClassInfoDefFn (gpointer inClass) { ObitRMFitClassInfo *theClass = (ObitRMFitClassInfo*)inClass; ObitClassInfo *ParentClass = (ObitClassInfo*)myClassInfo.ParentClass; if (theClass->initialized) return; /* only once */ /* Check type of inClass */ g_assert (ObitInfoIsA(inClass, (ObitClassInfo*)&myClassInfo)); /* Initialize (recursively) parent class first */ if ((ParentClass!=NULL) && (ParentClass->ObitClassInfoDefFn!=NULL)) ParentClass->ObitClassInfoDefFn(theClass); /* function pointers defined or overloaded this class */ theClass->ObitClassInit = (ObitClassInitFP)ObitRMFitClassInit; theClass->newObit = (newObitFP)newObitRMFit; theClass->ObitClassInfoDefFn = (ObitClassInfoDefFnFP)ObitRMFitClassInfoDefFn; theClass->ObitGetClass = (ObitGetClassFP)ObitRMFitGetClass; theClass->ObitCopy = (ObitCopyFP)ObitRMFitCopy; theClass->ObitClone = NULL; theClass->ObitClear = (ObitClearFP)ObitRMFitClear; theClass->ObitInit = (ObitInitFP)ObitRMFitInit; theClass->ObitRMFitCreate = (ObitRMFitCreateFP)ObitRMFitCreate; theClass->ObitRMFitCube = (ObitRMFitCubeFP)ObitRMFitCube; theClass->ObitRMFitImArr = (ObitRMFitImArrFP)ObitRMFitImArr; theClass->ObitRMFitSingle = (ObitRMFitSingleFP)ObitRMFitSingle; } /* end ObitRMFitClassDefFn */ /*---------------Private functions--------------------------*/ /** * Creates empty member objects, initialize reference count. * Parent classes portions are (recursively) initialized first * \param inn Pointer to the object to initialize. */ void ObitRMFitInit (gpointer inn) { ObitClassInfo *ParentClass; ObitRMFit *in = inn; /* error checks */ g_assert (in != NULL); /* recursively initialize parent class members */ ParentClass = (ObitClassInfo*)(myClassInfo.ParentClass); if ((ParentClass!=NULL) && ( ParentClass->ObitInit!=NULL)) ParentClass->ObitInit (inn); /* set members in this class */ in->thread = newObitThread(); in->info = newObitInfoList(); in->nterm = 2; in->nlamb2 = 0; in->minQUSNR = 3.0; in->minFrac = 0.5; in->QRMS = NULL; in->URMS = NULL; in->outDesc = NULL; in->inQFArrays = NULL; in->inUFArrays = NULL; in->outFArrays = NULL; in->lamb2 = NULL; } /* end ObitRMFitInit */ /** * Deallocates member objects. * Does (recursive) deallocation of parent class members. * \param inn Pointer to the object to deallocate. * Actually it should be an ObitRMFit* cast to an Obit*. */ void ObitRMFitClear (gpointer inn) { ObitClassInfo *ParentClass; ObitRMFit *in = inn; olong i, nOut; /* error checks */ g_assert (ObitIsA(in, &myClassInfo)); /* delete this class members */ if (in->QRMS) g_free(in->QRMS); if (in->URMS) g_free(in->URMS); in->thread = ObitThreadUnref(in->thread); in->info = ObitInfoListUnref(in->info); if (in->outDesc) in->outDesc = ObitImageDescUnref(in->outDesc); if (in->inQFArrays) { for (i=0; i<in->nlamb2; i++) in->inQFArrays[i] = ObitFArrayUnref(in->inQFArrays[i]); g_free(in->inQFArrays); } if (in->inUFArrays) { for (i=0; i<in->nlamb2; i++) in->inUFArrays[i] = ObitFArrayUnref(in->inUFArrays[i]); g_free(in->inUFArrays); } /* How many output planes */ if (in->doError) nOut = 1+in->nterm*2; else nOut = in->nterm; if (in->outFArrays) { for (i=0; i<nOut; i++) in->outFArrays[i] = ObitFArrayUnref(in->outFArrays[i]); g_free(in->outFArrays); } if (in->lamb2) g_free(in->lamb2); /* unlink parent class members */ ParentClass = (ObitClassInfo*)(myClassInfo.ParentClass); /* delete parent class members */ if ((ParentClass!=NULL) && ( ParentClass->ObitClear!=NULL)) ParentClass->ObitClear (inn); } /* end ObitRMFitClear */ /** * Does RM fitting, input and output on input object * Work divided up amoung 1 or more threads * In each pixel an RM is fitted if the number of valid data points * exceeds in->nterm, otherwise the pixel is blanked. * If in->doRMSyn then the max value of an RM synthesis is used * The results are stored in outFArrays: * \li first entry is the RM at the reference lambda^2 * \li second is the EVLA (rad) at 0 lambda^2 * \li third is the polarized amplitude at 0 lambda^2 * \li fouurth is the sum of the statistical weights * Otherwise, the results are stored in outFArrays: * \li first entry is the RM at the reference lambda^2 * \li second is the EVLA (rad) at the reference lambda^2 * \li entries nterm+1->nterm*2 RMS uncertainties on coefficients * \li entry 1+nterm*2 = the Chi squared of the fit * * \param in RMFit to fit * \param err Obit error stack object. */ static void Fitter (ObitRMFit* in, ObitErr *err) { olong i, loy, hiy, nyPerThread, nThreads; gboolean OK; NLRMFitArg **threadArgs; NLRMFitArg *args=NULL; ObitThreadFunc func=(ObitThreadFunc)ThreadNLRMFit; gchar *routine = "Fitter"; /* GSL implementation */ #ifdef HAVE_GSL const gsl_multifit_fdfsolver_type *T=NULL; #endif /* HAVE_GSL */ /* error checks */ if (err->error) return; /* Warn if too many terms asked for */ if (in->nterm>2) { Obit_log_error(err, OBIT_InfoWarn, "%s: Asked for %d terms, will limit to 2", routine, in->nterm); } /* How many threads to use? */ nThreads = MAX (1, ObitThreadNumProc(in->thread)); /* Initialize threadArg array */ threadArgs = g_malloc0(nThreads*sizeof(NLRMFitArg*)); for (i=0; i<nThreads; i++) threadArgs[i] = g_malloc0(sizeof(NLRMFitArg)); /* Set up thread arguments */ for (i=0; i<nThreads; i++) { args = (NLRMFitArg*)threadArgs[i]; args->in = in; args->err = err; args->nlamb2 = in->nlamb2; args->maxIter = 100; /* max. number of iterations */ args->minDelta = 1.0e-5; /* Min step size */ args->nterm = in->nterm; args->doError = in->doError; args->minQUSNR = in->minQUSNR; /* min pixel SNR */ args->minFrac = in->minFrac; /* min fraction of samples */ args->Qweight = g_malloc0(args->nlamb2*sizeof(ofloat)); args->Uweight = g_malloc0(args->nlamb2*sizeof(ofloat)); args->Qvar = g_malloc0(args->nlamb2*sizeof(ofloat)); args->Uvar = g_malloc0(args->nlamb2*sizeof(ofloat)); args->Qobs = g_malloc0(args->nlamb2*sizeof(ofloat)); args->Uobs = g_malloc0(args->nlamb2*sizeof(ofloat)); args->Pobs = g_malloc0(args->nlamb2*sizeof(ofloat)); args->lamb2 = g_malloc0(args->nlamb2*sizeof(ofloat)); args->x = g_malloc0(args->nlamb2*sizeof(double)); args->w = g_malloc0(args->nlamb2*sizeof(double)); args->q = g_malloc0(args->nlamb2*sizeof(double)); args->u = g_malloc0(args->nlamb2*sizeof(double)); args->wrk1 = g_malloc0(args->nlamb2*sizeof(ofloat)); args->wrk2 = g_malloc0(args->nlamb2*sizeof(ofloat)); args->wrk3 = g_malloc0(args->nlamb2*sizeof(ofloat)); if (args->doError) args->coef = g_malloc0(3*args->nterm*sizeof(ofloat)); else args->coef = g_malloc0(args->nterm*sizeof(ofloat)); /* GSL implementation */ #ifdef HAVE_GSL args->solver = NULL; args->covar = NULL; args->work = NULL; /* Setup solver */ T = gsl_multifit_fdfsolver_lmder; args->solver = gsl_multifit_fdfsolver_alloc(T, 2*args->nlamb2, 2); /* Fitting function info */ args->funcStruc = g_malloc0(sizeof(gsl_multifit_function_fdf)); args->funcStruc->f = &RMFitFunc; args->funcStruc->df = &RMFitJac; args->funcStruc->fdf = &RMFitFuncJac; args->funcStruc->n = 2*args->nlamb2; args->funcStruc->p = 2; args->funcStruc->params = args; /* Set up work arrays */ args->covar = gsl_matrix_alloc(2, 2); args->work = gsl_vector_alloc(2); #endif /* HAVE_GSL */ } /* end initialize */ /* Divide up work */ nyPerThread = in->ny/nThreads; loy = 1; hiy = nyPerThread; hiy = MIN (hiy, in->ny); /* Set up thread arguments */ for (i=0; i<nThreads; i++) { if (i==(nThreads-1)) hiy = in->ny; /* Make sure do all */ args = (NLRMFitArg*)threadArgs[i]; args->first = loy; args->last = hiy; if (nThreads>1) args->ithread = i; else args->ithread = -1; /* Update which y */ loy += nyPerThread; hiy += nyPerThread; hiy = MIN (hiy, in->ny); } /* Do operation possibly with threads */ if (in->doRMSyn) func = (ObitThreadFunc)ThreadRMSynFit; else func = (ObitThreadFunc)ThreadNLRMFit; OK = ObitThreadIterator (in->thread, nThreads, func, (gpointer)threadArgs); /* Check for problems */ if (!OK) { Obit_log_error(err, OBIT_Error,"%s: Problem in threading", routine); } /* Shut down any threading */ ObitThreadPoolFree (in->thread); if (threadArgs) { for (i=0; i<nThreads; i++) { args = (NLRMFitArg*)threadArgs[i]; if (args->Qweight) g_free(args->Qweight); if (args->Uweight) g_free(args->Uweight); if (args->Qvar) g_free(args->Qvar); if (args->Uvar) g_free(args->Uvar); if (args->Qobs) g_free(args->Qobs); if (args->Uobs) g_free(args->Uobs); if (args->Pobs) g_free(args->Pobs); if (args->lamb2) g_free(args->lamb2); if (args->x) g_free(args->x); if (args->w) g_free(args->w); if (args->q) g_free(args->q); if (args->u) g_free(args->u); if (args->wrk1) g_free(args->wrk1); if (args->wrk2) g_free(args->wrk2); if (args->wrk3) g_free(args->wrk3); if (args->coef) g_free(args->coef); #ifdef HAVE_GSL if (args->solver) gsl_multifit_fdfsolver_free (args->solver); if (args->work) gsl_vector_free(args->work); if (args->covar) gsl_matrix_free(args->covar); if (args->funcStruc) g_free(args->funcStruc); #endif /* HAVE_GSL */ g_free(threadArgs[i]); } g_free(threadArgs); } } /* end Fitter */ /** * Write contents on in to outImage * \param in RM fitting object * \param outImage Image cube with fitted spectra. * Should be defined but not created. * Planes 1->nterm are coefficients per pixel * Planes nterm+1->2*nterm are uncertainties in coefficients * \param err Obit error stack object. */ static void WriteOutput (ObitRMFit* in, ObitImage *outImage, ObitErr *err) { olong iplane, nOut; ObitIOSize IOBy; olong i, blc[IM_MAXDIM], trc[IM_MAXDIM]; ObitIOCode retCode; gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1}; gchar *routine = "WriteOutput"; /* error checks */ if (err->error) return; g_assert (ObitIsA(in, &myClassInfo)); g_assert(ObitImageIsA(outImage)); /* Open output- all, by plane */ dim[0] = IM_MAXDIM; for (i=0; i<IM_MAXDIM; i++) blc[i] = 1; for (i=0; i<IM_MAXDIM; i++) trc[i] = 0; ObitInfoListPut (outImage->info, "BLC", OBIT_long, dim, blc, err); ObitInfoListPut (outImage->info, "TRC", OBIT_long, dim, trc, err); IOBy = OBIT_IO_byPlane; dim[0] = 1; ObitInfoListAlwaysPut (outImage->info, "IOBy", OBIT_long, dim, &IOBy); outImage->extBuffer = TRUE; /* Using outFArrays as I/O buffer */ retCode = ObitImageOpen (outImage, OBIT_IO_ReadWrite, err); /* if it didn't work bail out */ if ((retCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine, outImage->name); /* save descriptive material */ ObitImageDescCopyDesc (in->outDesc, outImage->myDesc, err); if (err->error) Obit_traceback_msg (err, routine, outImage->name); /* How many output planes? */ if (in->doError) nOut = 1+in->nterm*2; else nOut = in->nterm; /* always 4 for doRMSyn */ if (in->doRMSyn) nOut = 4; /* Loop writing planes */ for (iplane=0; iplane<nOut; iplane++) { retCode = ObitImageWrite (outImage, in->outFArrays[iplane]->array, err); /* if it didn't work bail out */ if ((retCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine, outImage->name); } /* end loop writing planes */ /* Save nterms on output descriptor */ dim[0] = dim[1] = dim[2] = 1; ObitInfoListAlwaysPut (outImage->myDesc->info, "NTERM", OBIT_long, dim, &in->nterm); ObitInfoListAlwaysPut (((ObitImageDesc*)outImage->myIO->myDesc)->info, "NTERM", OBIT_long, dim, &in->nterm); /* Close output */ retCode = ObitImageClose (outImage, err); outImage->extBuffer = FALSE; /* May need I/O buffer later */ /* if it didn't work bail out */ if ((retCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine, outImage->name); } /* end WriteOutput */ /** * Thread function to fit a portion of the image set * \param arg NLRMFitArg structure */ static gpointer ThreadNLRMFit (gpointer arg) { NLRMFitArg *larg = (NLRMFitArg*)arg; ObitRMFit* in = (ObitRMFit*)larg->in; olong lo = larg->first-1; /* First in y range */ olong hi = larg->last; /* Highest in y range */ gboolean doError = larg->doError; /* Error analysis? */ ObitErr *err = larg->err; olong ix, iy, indx, i, nOut; ofloat fblank = ObitMagicF(); /*gchar *routine = "ThreadNLRMFit";*/ /* error checks */ if (err->error) return NULL; g_assert (ObitIsA(in, &myClassInfo)); /* Set up frequency info */ larg->refLamb2 = in->refLamb2; for (i=0; i<in->nlamb2; i++) { larg->lamb2[i] = in->lamb2[i]; } /* How many output planes */ if (in->doError) nOut = 1+in->nterm*2; else nOut = in->nterm; /* Loop over pixels in Y */ indx = lo*in->nx -1; /* Offset in pixel arrays */ for (iy=lo; iy<hi; iy++) { /* Loop over pixels in X */ for (ix=0; ix<in->nx; ix++) { indx ++; /* Collect values; */ for (i=0; i<in->nlamb2; i++) { larg->Qobs[i] = in->inQFArrays[i]->array[indx]; larg->Uobs[i] = in->inUFArrays[i]->array[indx]; /* Data valid? */ if ((larg->Qobs[i]!=fblank) && (larg->Uobs[i]!=fblank) && ((fabs(larg->Qobs[i])>in->minQUSNR*in->QRMS[i]) || (fabs(larg->Uobs[i])>in->minQUSNR*in->URMS[i]))) { /* Statistical weight */ larg->Qvar[i] = (in->QRMS[i]*in->QRMS[i]); larg->Uvar[i] = (in->URMS[i]*in->URMS[i]); larg->Pobs[i] = sqrt (larg->Qobs[i]*larg->Qobs[i] + larg->Uobs[i]*larg->Uobs[i]); /* larg->Qweight[i] = larg->Pobs[i] / larg->Qvar[i]; larg->Uweight[i] = larg->Pobs[i] / larg->Uvar[i];*/ larg->Qweight[i] = 1.0 / in->QRMS[i]; larg->Uweight[i] = 1.0 / in->URMS[i]; /* End if datum valid */ } else { /* invalid pixel */ larg->Qweight[i] = 0.0; larg->Qvar[i] = 0.0; larg->Uweight[i] = 0.0; larg->Uvar[i] = 0.0; larg->Pobs[i] = 0.0; } /* DEBUG if ((ix==669) && (iy==449)) { fprintf (stderr,"%3d q=%g u=%g qs=%g us=%g wt=%f\n", i, larg->Qobs[i], larg->Uobs[i], in->QRMS[i], in->URMS[i], larg->Qweight[i]); } */ } /* end loop over frequencies */ /* Fit */ NLRMFit(larg); /* DEBUG if ((ix==669) && (iy==449)) { fprintf (stderr,"ix=%4d iy=%4d\n",ix+1,iy+1); fprintf (stderr,"RM=%f EVPA=%f chi2=%f\n", larg->coef[0], larg->coef[1],larg->coef[4]); } */ /* Save to output */ if (doError) { for (i=0; i<nOut; i++) in->outFArrays[i]->array[indx] = larg->coef[i]; } else { /* only values */ for (i=0; i<in->nterm; i++) in->outFArrays[i]->array[indx] = larg->coef[i]; } } /* end x loop */ } /* end y loop */ /* Indicate completion */ if (larg->ithread>=0) ObitThreadPoolDone (in->thread, (gpointer)&larg->ithread); return NULL; } /* end ThreadNLRMFit */ /** * Fit RM and EVPA at the reference lambda^2 * Only fits for up to 5 terms * \param arg NLRMFitArg structure * fitted parameters returned in arg->in->coef * RM, EVPA, sig RM, sig EVPA, chi2 */ static void NLRMFit (NLRMFitArg *arg) { olong iter=0, i, nterm=2, nvalid; ofloat sumwt, fblank = ObitMagicF(); double chi2; int status; /* Initialize output */ if (arg->doError) for (i=0; i<2*nterm+1; i++) arg->coef[i] = 0.0; else for (i=0; i<nterm; i++) arg->coef[i] = 0.0; /* Blank */ arg->coef[0] = arg->coef[1] = fblank; /* try to unwrap EVPA, get data to be fitted, returns number of valid data and crude fits */ nvalid = RMcoarse (arg); if (nvalid<=MAX(2,nterm)) return; /* enough good data for fit? */ /* High enough fraction of valid pixels? */ if ((((ofloat)nvalid)/((ofloat)arg->nlamb2)) < arg->minFrac) return; /* Do fit */ #ifdef HAVE_GSL /* order EVPA, RM */ gsl_vector_set(arg->work, 0, (double)arg->coef[1]); gsl_vector_set(arg->work, 1, (double)arg->coef[0]); arg->funcStruc->n = arg->nlamb2*2; arg->funcStruc->p = nterm; arg->funcStruc->params = arg; gsl_multifit_fdfsolver_set (arg->solver, arg->funcStruc, arg->work); iter = 0; /* iteration loop */ do { iter++; status = gsl_multifit_fdfsolver_iterate(arg->solver); /*if (status) break;???*/ status = gsl_multifit_test_delta (arg->solver->dx, arg->solver->x, (double)arg->minDelta, (double)arg->minDelta); /* DEBUG if (nvalid>nterm) { sumwt = (ofloat)gsl_blas_dnrm2(arg->solver->f); chi2 = (sumwt*sumwt)/(nvalid-nterm); } else chi2 = -1.0; for (i=0; i<nterm; i++) arg->coef[i] = (ofloat)gsl_vector_get(arg->solver->x, i); fprintf (stderr," iter=%d RM %f EVPA %f chi2 %g status %d\n", iter, arg->coef[1], arg->coef[0], chi2, status); */ /* end DEBUG */ } while ((status==GSL_CONTINUE) && (iter<arg->maxIter)); /* If it didn't work - bail */ if ((status!=GSL_SUCCESS) && (status!=GSL_CONTINUE)) { fprintf (stderr, "Failed, status = %s\n", gsl_strerror(status)); return; } /* normalized Chi squares */ if (nvalid>nterm) { sumwt = (ofloat)gsl_blas_dnrm2(arg->solver->f); chi2 = (sumwt*sumwt)/(nvalid-nterm); } else chi2 = -1.0; /* Get fitted values - switch order to RM, EVPA*/ arg->coef[0] = (ofloat)gsl_vector_get(arg->solver->x, 1); arg->coef[1] = (ofloat)gsl_vector_get(arg->solver->x, 0); /* Errors wanted? */ if (arg->doError) { gsl_matrix *J; /* second argument removes degenerate col/row from Jacobean */ J = gsl_matrix_alloc(2*arg->nlamb2, 2); #ifdef HAVE_GSL_MULTIFIT_FDFSOLVER_JAC gsl_multifit_fdfsolver_jac(arg->solver, J); #else gsl_matrix_memcpy(J, arg->solver->J); #endif gsl_multifit_covar (J, 1.0e-8, arg->covar); gsl_matrix_free(J); arg->coef[nterm+0] = sqrt(gsl_matrix_get(arg->covar, 1, 1)); arg->coef[nterm+1] = sqrt(gsl_matrix_get(arg->covar, 0, 0)); arg->coef[4] = chi2; } /* end of get errors */ #endif /* HAVE_GSL */ } /* end NLRMFit */ /** * Make crude estimate of RM, EVPA and populate argument arrays * \param arg NLRMFitArg structure * Data to be fitted in x,q,u,w * RM, EVPA in coef * \return number of valid data */ static olong RMcoarse (NLRMFitArg *arg) { olong i, j, ntest, nvalid, numb; ofloat minDL, maxDL, dRM, tRM, bestRM=0.0, fblank = ObitMagicF(); ofloat bestQ, bestU, sumrQ, sumrU, penFact; double aarg, varaarg; odouble amb, res, best, test; /* get EVLA values count valid data*/ nvalid = 0; numb = 0; for (i=0; i<arg->nlamb2; i++) { if ((arg->Qobs[i]!=fblank) && (arg->Qweight[i]>0.0) && (arg->Uobs[i]!=fblank) && (arg->Uweight[i]>0.0)) { arg->x[numb] = arg->lamb2[i] - arg->refLamb2; /* Weight */ aarg = fabs(arg->Uobs[i]/arg->Qobs[i]); varaarg = aarg*aarg*(arg->Qvar[i]/(arg->Qobs[i]*arg->Qobs[i]) + arg->Uvar[i]/(arg->Uobs[i]*arg->Uobs[i])); arg->w[numb] = (1.0+aarg*aarg)/varaarg; /* arg->q[numb] = arg->Qobs[i] * arg->w[numb]; arg->u[numb] = arg->Uobs[i] * arg->w[numb];*/ arg->q[numb] = arg->Qobs[i]; arg->u[numb] = arg->Uobs[i]; /* DEBUG fprintf (stderr, "%3d x=%8.5f q=%8.5f u=%8.5f w=%8.5g \n ", numb,arg->x[numb], arg->q[numb],arg->u[numb],arg->w[numb]); arg->Qweight[i] = arg->Uweight[i] = 1.0/20.0e-6; fprintf (stderr,"%3d l2=%g q=%g u=%g p=%f qwt=%g uwt=%g\n", i,arg->lamb2[i]-arg->refLamb2, arg->Qobs[i], arg->Uobs[i],arg->Pobs[i], arg->Qweight[i], arg->Uweight[i]);*/ numb++; } } nvalid = numb; if (nvalid<=MAX(2,arg->nterm)) return nvalid; /* enough good data for fit? */ /* High enough fraction of valid pixels? */ if ((((ofloat)nvalid)/((ofloat)arg->nlamb2)) < arg->minFrac) return nvalid; arg->nvalid = nvalid; /* max and min delta lamb2 - assume lamb2 ordered */ maxDL = fabs(arg->x[0]-arg->x[numb-1]); /* range of actual delta lamb2 */ minDL = 1.0e20; for (i=1; i<numb; i++) minDL = MIN (minDL, fabs(arg->x[i]-arg->x[i-1])); /* ambiguity = pi/min_dlamb2 resolution = pi/max_dlamb2 = RM which gives 1 turn over lamb2 range */ amb = G_PI / fabs(minDL); res = G_PI / maxDL; dRM = 0.05 * res; /* test RM interval */ /* DEBUG fprintf (stderr,"amb = %f res= %f dRM=%f\n", amb, res, dRM); */ /* end DEBUG */ /* Test +/- half ambiguity every dRM */ ntest = 1 + 0.5*amb/dRM; ntest = MIN (ntest, 1001); /* Some bounds */ /* Penalty to downweight solutions away from zero, weight 0.25 at edge of search */ penFact = 0.25 / (0.5*ntest); best = -1.0e20; for (i=0; i<ntest; i++) { tRM = (i-ntest/2) * dRM; /* Loop over data samples - first phases to convert to ref Lamb2 */ for (j=0; j<numb; j++) arg->wrk1[j]= -2*tRM * arg->x[j]; /* sines/cosine */ ObitSinCosVec (numb, arg->wrk1, arg->wrk3, arg->wrk2); /* DEBUG if ((fabs(tRM-133.0)<0.95*dRM) || (fabs(tRM-133.)<0.95*dRM)) { for (j=0; j<numb; j++) { test = (arg->q[j]*arg->wrk2[j])*(arg->q[j]*arg->wrk2[j]) + (arg->u[j]*arg->wrk3[j])*(arg->u[j]*arg->wrk3[j]); fprintf (stderr," i=%d j=%d t phase=%f obs phase %lf q=%f u=%lf test=%f\n", i, j, arg->wrk1[j], 0.5*atan2(arg->u[j],arg->q[j]), (arg->q[j]*arg->wrk2[j] - arg->u[j]*arg->wrk3[j])*1000, (arg->q[j]*arg->wrk3[j] + arg->u[j]*arg->wrk2[j])*1000, test); } } */ /* end DEBUG*/ /* Find best sum of weighted amplitudes^2 converted to ref lambda^2 */ test = 0.0; sumrQ = sumrU = 0.0; for (j=0; j<numb; j++) { sumrQ += arg->w[j]*(arg->q[j]*arg->wrk2[j] - arg->u[j]*arg->wrk3[j]); sumrU += arg->w[j]*(arg->q[j]*arg->wrk3[j] + arg->u[j]*arg->wrk2[j]); } test = sumrQ*sumrQ + sumrU*sumrU; /* Add penalty */ test *= (1.0 - penFact*abs(i-ntest/2)); /* DEBUG fprintf (stderr," i=%d test=%g tRM %f sum Q=%f sum U=%f pen %f\n", i, test, tRM, sumrQ, sumrU, penFact*abs(i-ntest/2));*/ /* end DEBUG */ if (test>best) { best = test; bestRM = tRM; bestQ = sumrQ; bestU = sumrU; } } /* Save */ arg->coef[0] = bestRM; arg->coef[1] = 0.5 * atan2(bestU, bestQ); /* DEBUG fprintf (stderr,"RM = %f EVPA= %f best=%f dRM=%f\n", arg->coef[1],arg->coef[0], best, dRM); */ /* end DEBUG */ return nvalid; } /* end RMcoarse */ #ifdef HAVE_GSL /** * Function evaluator for spectral fitting solver * Evaluates (model-observed) / sigma * \param x Vector of parameters to be fitted * Flux,array_of spectral_terms * \param param Function parameter structure (NLRMFitArg) * \param f Vector of (model-obs)/sigma for data points * in order q, u each datum * \return completion code GSL_SUCCESS=OK */ static int RMFitFunc (const gsl_vector *x, void *params, gsl_vector *f) { NLRMFitArg *args = (NLRMFitArg*)params; ofloat fblank = ObitMagicF(); olong nlamb2 = args->nlamb2; double func; odouble RM, EVPA; size_t i, j; /* DEBUG odouble sum=0.0; */ /* get model parameters */ EVPA = gsl_vector_get(x, 0); RM = gsl_vector_get(x, 1); /* DEBUG fprintf (stderr,"FitFunc RM=%f EVPA=%f\n", RM,EVPA); */ /* First compute model phases */ for (j=0; j<nlamb2; j++) args->wrk1[j] = 2*(EVPA + RM * (args->lamb2[j]-args->refLamb2)); /* then sine/cosine */ ObitSinCosVec (nlamb2, args->wrk1, args->wrk3, args->wrk2); /* Loop over data - Residuals */ for (i=0; i<nlamb2; i++) { /* Q model = args->Pobs[i] * args->wrk2[i] */ if ((args->Qobs[i]!=fblank) && (args->Qweight[i]>0.0)) { func = (args->Pobs[i] * args->wrk2[i] - args->Qobs[i]) * args->Qweight[i]; /* sum += func*func; DEBUG fprintf (stderr,"FitFunc q i=%3ld func=%lg obs=%g mod=%g wt=%g p=%f\n", 2*i, func, args->Uobs[i], args->Pobs[i]*args->wrk3[i], args->Uweight[i], args->Pobs[i]); */ gsl_vector_set(f, 2*i, func); /* Save function residual */ } else { /* Invalid data */ func = 0.0; gsl_vector_set(f, 2*i, func); /* Save function residual */ } /* U model = args->Pobs[i] * args->wrk3[i] */ if ((args->Uobs[i]!=fblank) && (args->Uweight[i]>0.0)) { func = (args->Pobs[i] * args->wrk3[i] - args->Uobs[i]) * args->Uweight[i]; /* sum += func*func; DEBUG fprintf (stderr,"FitFunc u i=%3ld func=%lg obs=%g mod=%g wt=%g phs=%f\n", 2*i+1, func, args->Uobs[i], args->Pobs[i]*args->wrk3[i], args->Uweight[i], args->wrk1[i]*28.648); */ gsl_vector_set(f, 2*i+1, func); /* Save function residual */ } else { /* Invalid data */ func = 0.0; gsl_vector_set(f, 2*i+1, func); /* Save function residual */ } } /* End loop over data */ /* DEBUG fprintf (stderr,"FitFunc RMS=%g\n", sqrt(sum)); */ return GSL_SUCCESS; } /* end RMFitFunc */ /** * Jacobian evaluator for spectral fitting solver * Evaluates partial derivatives of model wrt each parameter * \param x Vector of parameters to be fitted * Flux,array_of spectral_terms * \param param Function parameter structure (NLRMFitArg) * \param J Jacobian matrix J[data_point, parameter] * in order q, u each datum * \return completion code GSL_SUCCESS=OK */ static int RMFitJac (const gsl_vector *x, void *params, gsl_matrix *J) { NLRMFitArg *args = (NLRMFitArg*)params; ofloat fblank = ObitMagicF(); olong nlamb2 = args->nlamb2; odouble RM, EVPA; double jac; size_t i, j; /* get model parameters */ EVPA = gsl_vector_get(x, 0); RM = gsl_vector_get(x, 1); /* DEBUG fprintf (stderr,"FitJac RM=%f EVPA=%f\n", RM,EVPA);*/ /* First compute model phases */ for (j=0; j<nlamb2; j++) args->wrk1[j] = 2*(EVPA + RM * (args->lamb2[j]-args->refLamb2)); /* then sine/cosine */ ObitSinCosVec (nlamb2, args->wrk1, args->wrk3, args->wrk2); /* Loop over data - gradients */ for (i=0; i<nlamb2; i++) { j = 0; /* EVPA */ /* d Q model/d EVPA = -args->Pobs[i] * args->wrk3[i] */ if ((args->Qobs[i]!=fblank) && (args->Qweight[i]>0.0)) { jac = -(args->Pobs[i] * args->wrk3[i]) * args->Qweight[i]; gsl_matrix_set(J, 2*i, j, jac); /* Save function gradient */ } else { /* Invalid data */ jac = 0.0; gsl_matrix_set(J, 2*i, j, jac); /* Save function gradient */ } /* d U model/d EVPA = args->Pobs[i] * args->wrk2[i] */ if ((args->Uobs[i]!=fblank) && (args->Uweight[i]>0.0)) { jac = (args->Pobs[i] * args->wrk2[i]) * args->Uweight[i]; gsl_matrix_set(J, 2*i+1, j, jac); /* Save function gradient */ } else { /* Invalid data */ jac = 0.0; gsl_matrix_set(J, 2*i+1, j, jac); /* Save function gradient */ } j = 1; /* RM */ /* d Q model/d RM = -2 args->Pobs[i] * args->wrk3[i] * (args->lamb2[i]-args->refLamb2) */ if ((args->Qobs[i]!=fblank) && (args->Qweight[i]>0.0)) { jac = -2*(args->Pobs[i] * args->wrk3[i]) * (args->lamb2[i]-args->refLamb2) * args->Qweight[i]; gsl_matrix_set(J, 2*i, j, jac); /* Save function gradient */ } else { /* Invalid data */ jac = 0.0; gsl_matrix_set(J, 2*i, j, jac); /* Save function gradient */ } /* d U model/d RM = 2 args->Pobs[i] * args->wrk2[i] * (args->lamb2[i]-args->refLamb2) */ if ((args->Uobs[i]!=fblank) && (args->Uweight[i]>0.0)) { jac = 2*(args->Pobs[i] * args->wrk2[i]) * (args->lamb2[i]-args->refLamb2) * args->Uweight[i]; gsl_matrix_set(J, 2*i+1, j, jac); /* Save function gradient */ } else { /* Invalid data */ jac = 0.0; gsl_matrix_set(J, 2*i+1, j, jac); /* Save function gradient */ } } /* End loop over data */ return GSL_SUCCESS; } /* end RMFitJac */ /** * Function and Jacobian evaluator for spectral fitting solver * Function = (model-observed) / sigma * Jacobian = partial derivatives of model wrt each parameter * \param x Vector of parameters to be fitted * Flux,array_of spectral_terms * \param param Function parameter structure (NLRMFitArg) * \param f Vector of (model-obs)/sigma for data points * in order q, u each datum * \param J Jacobian matrix J[data_point, parameter] * in order q, u each datum * \return completion code GSL_SUCCESS=OK */ static int RMFitFuncJac (const gsl_vector *x, void *params, gsl_vector *f, gsl_matrix *J) { NLRMFitArg *args = (NLRMFitArg*)params; ofloat fblank = ObitMagicF(); double func, jac; olong nlamb2 = args->nlamb2; odouble RM, EVPA; size_t i, j; /* DEBUG odouble sum=0.0; */ /* get model parameters */ EVPA = gsl_vector_get(x, 0); RM = gsl_vector_get(x, 1); /* DEBUG fprintf (stderr,"FuncJac RM=%f EVPA=%f\n", RM,EVPA); */ /* First compute model phases */ for (j=0; j<nlamb2; j++) args->wrk1[j] = 2*(EVPA + RM * (args->lamb2[j]-args->refLamb2)); /* then sine/cosine */ ObitSinCosVec (nlamb2, args->wrk1, args->wrk3, args->wrk2); /* Loop over data - gradients */ for (i=0; i<nlamb2; i++) { if ((args->Qobs[i]!=fblank) && (args->Qweight[i]>0.0)) { /* Q model = args->Pobs[i] * args->wrk2[i] */ func = (args->Pobs[i] * args->wrk2[i] - args->Qobs[i]) * args->Qweight[i]; /* sum += func*func; DEBUG */ /* DEBUG fprintf (stderr,"FuncJac q i=%3ld func=%lg obs=%g mod=%g wt=%g p=%f\n", 2*i, func, args->Qobs[i], args->Pobs[i] * args->wrk2[i], args->Qweight[i], args->Pobs[i]); */ gsl_vector_set(f, 2*i, func); /* Save function residual */ j = 0; /* EVPA */ /* d Q model/d EVPA = -args->Pobs[i] * args->wrk3[i] */ jac = -(args->Pobs[i] * args->wrk3[i]) * args->Qweight[i]; /* DEBUG fprintf (stderr,"FuncJac q i=%3ld j=%3ld jac=%lf\n", 2*i, j, jac); */ gsl_matrix_set(J, 2*i, j, jac); /* Save function residual */ j = 1; /* RM */ /* d Q model/d RM = -2 args->Pobs[i] * args->wrk3[i] * (args->lamb2[i]-args->refLamb2) */ jac = -2*(args->Pobs[i] * args->wrk3[i]) * (args->lamb2[i]-args->refLamb2) * args->Qweight[i]; /* DEBUG fprintf (stderr,"FuncJac q i=%3ld j=%3ld jac=%lf\n", 2*i+1, j, jac);*/ gsl_matrix_set(J, 2*i, j, jac); /* Save function gradient */ } else { /* Invalid data */ func = 0.0; gsl_vector_set(f, 2*i, func); j = 0; /* EVPA */ jac = 0.0; gsl_matrix_set(J, 2*i, j, jac); j = 1; /* RM */ gsl_matrix_set(J, 2*i, j, jac); } if ((args->Uobs[i]!=fblank) && (args->Uweight[i]>0.0)) { /* U model = 2 args->Pobs[i] * args->wrk3[i] */ func = (args->Pobs[i] * args->wrk3[i] - args->Uobs[i]) * args->Uweight[i]; /* sum += func*func; DEBUG */ /* DEBUG fprintf (stderr,"FuncJac u i=%3ld func=%lg obs=%g mod=%g wt=%g phs=%f\n", 2*i+1, func, args->Uobs[i], args->Pobs[i]*args->wrk3[i], args->Uweight[i], args->wrk1[i]*28.648); */ gsl_vector_set(f, 2*i+1, func); /* Save function residual */ j = 0; /* EVPA */ /* d U model/d EVPA = args->Pobs[i] * args->wrk2[i] */ jac = (args->Pobs[i] * args->wrk2[i]) * args->Uweight[i]; /* DEBUG fprintf (stderr,"FuncJac u i=%3ld j=%3ld jac=%lf\n", 2*i, j, jac); */ gsl_matrix_set(J, 2*i+1, j, jac); /* Save function gradient */ j = 1; /* RM */ /* d U model/d RM = args->Pobs[i] * args->wrk2[i] * (args->lamb2[i]-args->refLamb2) */ jac = 2*(args->Pobs[i] * args->wrk2[i]) * (args->lamb2[i]-args->refLamb2) * args->Uweight[i]; /* DEBUG fprintf (stderr,"FuncJac u i=%3ld j=%3ld jac=%lf\n", 2*i+1, j, jac); */ gsl_matrix_set(J, 2*i+1, j, jac); /* Save function gradient */ } else { /* Invalid data */ func = 0.0; gsl_vector_set(f, 2*i+1, func); j = 0; /* EVPA */ jac = 0.0; gsl_matrix_set(J, 2*i+1, j, jac); j = 1; /* RM */ gsl_matrix_set(J, 2*i+1, j, jac); } } /* End loop over data */ /* DEBUG fprintf (stderr,"FuncJac RMS=%g\n", sqrt(sum)); */ return GSL_SUCCESS; } /* end RMFitFuncJac */ #endif /* HAVE_GSL */ /* RM Synthesis max routines */ /** * Thread function to RM Synthesis Max fit a portion of the image set * \param arg NLRMFitArg structure * \li coef[0]=RM, coef[1]=amp, coef[2]=phase, coef[3]=RMS Q,U */ static gpointer ThreadRMSynFit (gpointer arg) { NLRMFitArg *larg = (NLRMFitArg*)arg; ObitRMFit* in = (ObitRMFit*)larg->in; olong lo = larg->first-1; /* First in y range */ olong hi = larg->last; /* Highest in y range */ ObitErr *err = larg->err; olong ix, iy, indx, i, besti; ofloat fblank = ObitMagicF(); olong j, ntest, nvalid, numb; ofloat minDL, maxDL, dRM, tRM, bestRM=0.0; ofloat bestQ, bestU, sumrQ, sumrU, sumW=0.0, EVPA, amp; double aarg, varaarg; odouble amb, res, best, test; /*gchar *routine = "ThreadRMSynFit";*/ /* error checks */ if (err->error) return NULL; g_assert (ObitIsA(in, &myClassInfo)); /* Set up frequency info if in given */ if (in) { larg->refLamb2 = in->refLamb2; for (i=0; i<in->nlamb2; i++) { larg->lamb2[i] = in->lamb2[i]; } } /* Loop over pixels in Y */ indx = lo*in->nx -1; /* Offset in pixel arrays */ for (iy=lo; iy<hi; iy++) { /* Loop over pixels in X */ for (ix=0; ix<in->nx; ix++) { indx ++; /* Collect values; */ for (i=0; i<in->nlamb2; i++) { larg->Qobs[i] = in->inQFArrays[i]->array[indx]; larg->Uobs[i] = in->inUFArrays[i]->array[indx]; /* Data valid? */ if ((larg->Qobs[i]!=fblank) && (larg->Uobs[i]!=fblank) && ((fabs(larg->Qobs[i])>in->minQUSNR*in->QRMS[i]) || (fabs(larg->Uobs[i])>in->minQUSNR*in->URMS[i]))) { /* Statistical weight */ larg->Qvar[i] = (in->QRMS[i]*in->QRMS[i]); larg->Uvar[i] = (in->URMS[i]*in->URMS[i]); larg->Qweight[i] = 1.0 / in->QRMS[i]; larg->Uweight[i] = 1.0 / in->URMS[i]; /* End if datum valid */ } else { /* invalid pixel */ larg->Qweight[i] = 0.0; larg->Uweight[i] = 0.0; } /* DEBUG if ((ix==669) && (iy==449)) { fprintf (stderr,"%3d q=%g u=%g qs=%g us=%g wt=%f\n", i, larg->Qobs[i], larg->Uobs[i], in->QRMS[i], in->URMS[i], larg->Qweight[i]); } */ } /* end loop over frequencies */ /* Fit coef[0]=RM, coef[1]=amp, coef[2]=phase, coef[3]=RMS Q,U */ /* get values count valid data*/ numb = 0; sumW = 0.0; for (i=0; i<larg->nlamb2; i++) { if ((larg->Qweight[i]>0.0) && (larg->Uweight[i]>0.0)) { larg->x[numb] = larg->lamb2[i] - larg->refLamb2; /* Weight of polarized amplitude */ aarg = fabs(larg->Uobs[i]/larg->Qobs[i]); varaarg = aarg*aarg*(larg->Qvar[i]/(larg->Qobs[i]*larg->Qobs[i]) + larg->Uvar[i]/(larg->Uobs[i]*larg->Uobs[i])); larg->w[numb] = (1.0+aarg*aarg)/varaarg; larg->q[numb] = larg->Qobs[i]; larg->u[numb] = larg->Uobs[i]; sumW += larg->w[numb]; /* DEBUG fprintf (stderr, "%3d x=%8.5f q=%8.5f u=%8.5f w=%8.5g \n ", numb,larg->x[numb], larg->q[numb],larg->u[numb],larg->w[numb]); larg->Qweight[i] = larg->Uweight[i] = 1.0/20.0e-6; fprintf (stderr,"%3d l2=%g q=%g u=%g p=%f qwt=%g uwt=%g\n", i,larg->lamb2[i]-larg->refLamb2, larg->Qobs[i], larg->Uobs[i],larg->Pobs[i], larg->Qweight[i], larg->Uweight[i]);*/ numb++; } } nvalid = numb; /* enough data? */ if ((nvalid<=2) || ((((ofloat)nvalid)/((ofloat)larg->nlamb2)) < larg->minFrac)) { bestRM = EVPA = fblank; amp = 0.0; sumrQ = sumrU = 1000.0; goto doneFit; } /* max and min delta lamb2 - assume lamb2 ordered */ maxDL = fabs(larg->x[0]-larg->x[numb-1]); /* range of actual delta lamb2 */ minDL = 1.0e20; for (i=1; i<numb; i++) minDL = MIN (minDL, fabs(larg->x[i]-larg->x[i-1])); /* ambiguity = pi/min_dlamb2 resolution = pi/max_dlamb2 = RM which gives 1 turn over lamb2 range */ if (in->maxRMSyn>in->minRMSyn) { dRM = MAX (0.01,in->delRMSyn); ntest = 1+(in->maxRMSyn - in->minRMSyn)/dRM; } else { amb = G_PI / fabs(minDL); res = G_PI / maxDL; dRM = 0.05 * res; /* test RM interval */ /* Test +/- 0.05 ambiguity every dRM */ ntest = 1 + amb/(0.05*dRM); dRM *= 0.05; in->minRMSyn = -(ntest/2) * dRM; } ntest = MIN (ntest, 10001); /* Some bounds */ /* DEBUG fprintf (stderr,"amb = %f res= %f dRM=%f\n", amb, res, dRM); */ /* end DEBUG */ best = -1.0e20; besti = 0; for (i=0; i<ntest; i++) { tRM = in->minRMSyn + i * dRM; /* Loop over data samples - first phases to convert to ref Lamb2 */ for (j=0; j<numb; j++) larg->wrk1[j]= -2*tRM * larg->x[j]; /* sines/cosine */ ObitSinCosVec (numb, larg->wrk1, larg->wrk3, larg->wrk2); /* Find best sum of weighted amplitudes^2 converted to ref lambda^2 */ test = 0.0; sumrQ = sumrU = 0.0; for (j=0; j<numb; j++) { sumrQ += larg->w[j]*(larg->q[j]*larg->wrk2[j] - larg->u[j]*larg->wrk3[j]); sumrU += larg->w[j]*(larg->q[j]*larg->wrk3[j] + larg->u[j]*larg->wrk2[j]); } test = sumrQ*sumrQ + sumrU*sumrU; /* DEBUG fprintf (stderr," i=%d test=%g tRM %f sum Q=%f sum U=%f pen %f\n", i, test, tRM, sumrQ, sumrU, penFact*abs(i-ntest/2));*/ /* end DEBUG */ if (test>best) { besti = i; best = test; bestRM = tRM; bestQ = sumrQ; bestU = sumrU; } } /* Get chi sq for fit */ EVPA = 0.5 * atan2(bestU, bestQ); amp = sqrtf(bestU*bestU + bestQ*bestQ)/sumW; tRM = bestRM; /* Loop over data samples - first phases to convert to ref Lamb2 */ for (j=0; j<larg->nlamb2; j++) larg->wrk1[j]= 2*tRM * (larg->lamb2[j]-larg->refLamb2) + 2.0*EVPA; /* sines/cosine */ ObitSinCosVec (larg->nlamb2, larg->wrk1, larg->wrk3, larg->wrk2); sumrQ = sumrU = 0.0; numb = 0; for (j=0; j<larg->nlamb2; j++) { if ((larg->Qweight[j]>0.0) && (larg->Uweight[j]>0.0)) { numb += 2; sumrQ += (larg->Qobs[j]-amp*larg->wrk2[j])*(larg->Qobs[j]-amp*larg->wrk2[j])/larg->Qvar[j]; sumrU += (larg->Uobs[j]-amp*larg->wrk3[j])*(larg->Uobs[j]-amp*larg->wrk3[j])/larg->Uvar[j]; } } sumrQ /= numb; sumrU /= numb; /* Save */ doneFit: larg->coef[0] = bestRM; larg->coef[1] = EVPA; larg->coef[2] = amp; larg->coef[3] = (sumrQ+sumrU); /* Edit */ if ((larg->coef[3]>in->maxChi2) || (besti<=0) || (besti>=(ntest-1))) { larg->coef[0] = larg->coef[1] = fblank; } /* DEBUG if ((ix==669) && (iy==449)) { fprintf (stderr,"ix=%4d iy=%4d\n",ix+1,iy+1); fprintf (stderr,"RM=%f EVPA=%f chi2=%f\n", larg->coef[0], larg->coef[1],larg->coef[4]); } */ /* Save to output */ for (i=0; i<4; i++) in->outFArrays[i]->array[indx] = larg->coef[i]; } /* end x loop */ } /* end y loop */ /* Indicate completion */ if (larg->ithread>=0) ObitThreadPoolDone (in->thread, (gpointer)&larg->ithread); return NULL; } /* end ThreadRMSynFit */
In the 2000s , property values rose after expensive projects were completed and demand for second homes by the wealthy increased . It has made it difficult for middle @-@ class workers to find affordable housing on the island .
[STATEMENT] lemma parts_in_effect: assumes \<open>p \<in> set z\<close> and \<open>(B, z') |\<in>| effect r (A, z)\<close> shows \<open>\<exists>C xs. set A \<subseteq> set C \<and> xs \<in> set (parts C r p) \<and> set xs \<subseteq> set z'\<close> [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<exists>C xs. set A \<subseteq> set C \<and> xs \<in> set (parts C r p) \<and> set xs \<subseteq> set z' [PROOF STEP] using assms parts_in_children ne_effect_not_branchDone [PROOF STATE] proof (prove) using this: p \<in> set z (B, z') |\<in>| effect r (A, z) \<lbrakk>?p \<in> set ?z; ?z' \<in> set (children ?A ?r ?z)\<rbrakk> \<Longrightarrow> \<exists>B xs. set ?A \<subseteq> set B \<and> xs \<in> set (parts B ?r ?p) \<and> set xs \<subseteq> set ?z' (?B, ?z') |\<in>| effect ?r (?A, ?z) \<Longrightarrow> \<not> branchDone ?z goal (1 subgoal): 1. \<exists>C xs. set A \<subseteq> set C \<and> xs \<in> set (parts C r p) \<and> set xs \<subseteq> set z' [PROOF STEP] by (smt (verit, ccfv_threshold) Pair_inject effect.simps fimageE fset_of_list_elem le_sup_iff set_append set_remdups)
Here are the top free stock photography websites where you will find royalty free, attribute free and copyright free images and photos. This simply means that you can copy, modify, or distribute the images that you have downloaded. Pexels – aggregator of hand picked high resolution images. Stock Up – Search 26 high-quality, free stock photo websites in one place. Gratisography – huge resource for offbeat photos. picjumbo – another resource where you can down completely free high resolution photos. splitshire – stunning photos all for free! All the Free Stock – offers not just free photos but also free stock images, videos, music and icons as well. Foodie’s Feed – Perfect if you need high resolution food photos.
theory TS_Proof_Rules imports TS_Model begin lemmas [simp] = push_inv_def lemma CAS_Top_written_addr_post: "cls ccs CAS\<^sup>R[libTop, True, a , b]\<^sub>t cls' ccs' \<Longrightarrow> c \<in> written_addr cls' \<Longrightarrow> c \<notin> written_addr cls \<Longrightarrow> c = b " apply(simp add: written_addr_def) apply(subgoal_tac "lib_value cls' ` lib_writes_on cls' Top = lib_value cls ` lib_writes_on cls Top \<union> {b}") apply simp apply(simp add: lib_CAS_Rel_step_def,elim exE conjE) apply(case_tac "lib_value cls (aa, ba) = a", simp_all) apply(simp add: lib_update_r_def all_updates_l lib_writes_on_def var_def tst_def lib_value_def) apply safe apply simp_all apply auto[3] apply (smt Lib.lib_write_record.select_convs(1) fst_conv image_iff mem_Collect_eq) apply safe apply clarsimp apply (smt fresh_ts_not_in_writes fst_conv imageI less_numeral_extra(3) lib_value_def mem_Collect_eq var_def) apply clarsimp apply (smt fresh_ts_not_in_writes fst_conv imageI less_numeral_extra(3) lib_value_def mem_Collect_eq var_def) done lemma CAS_Top_written_addr_post2: "cls ccs CAS\<^sup>R[libTop, True, a , b]\<^sub>t cls' ccs' \<Longrightarrow> c \<in> lib_value cls' `(lib_writes_on cls' Top) - {Null} \<Longrightarrow> c \<notin> lib_value cls `(lib_writes_on cls Top) - {Null} \<Longrightarrow> c = b " using CAS_Top_written_addr_post written_addr_def by blast lemma failed_CAS_Top_written_addr_post: "cls ccs CAS\<^sup>R[libTop, False, a , b]\<^sub>t cls' ccs' \<Longrightarrow> lib_value cls' `lib_writes_on cls' Top = lib_value cls `lib_writes_on cls Top" apply(simp add: lib_CAS_Rel_step_def,elim exE conjE) apply(case_tac "lib_value cls (aa, ba) = a", simp_all) apply(simp add: lib_read_def all_updates_l lib_writes_on_def var_def tst_def lib_value_def) done lemma failed_CAS_Top_written_addr_post2: "cls ccs CAS\<^sup>R[libTop, False, a , b]\<^sub>t cls' ccs' \<Longrightarrow> written_addr cls' = written_addr cls" apply(simp add: written_addr_def) using failed_CAS_Top_written_addr_post apply metis done lemma diff_var_write_written_addr: "lib_wfs cls ccs \<Longrightarrow> cls ccs [lib(x) := b]\<^sub>t cls' ccs' \<Longrightarrow> x \<noteq>Top \<Longrightarrow> written_addr cls' = written_addr cls" apply(simp add: written_addr_def lib_write_step_def, elim exE conjE) apply(simp add: lib_write_def all_updates_l lib_writes_on_def var_def tst_def lib_visible_writes_def lib_valid_fresh_ts_def) apply safe apply simp apply(simp add: lib_value_def) apply linarith apply linarith apply(simp add: lib_value_def) apply(simp add: lib_wfs_def) apply(simp add: lib_write_def all_updates_l lib_writes_on_def var_def tst_def lib_visible_writes_def lib_valid_fresh_ts_def) apply safe apply (smt image_iff mem_Collect_eq) by linarith lemma success_CAS_Top_written_addr_post: "cls ccs CAS\<^sup>R[libTop, True, a , b]\<^sub>t cls' ccs' \<Longrightarrow> lib_value cls' `lib_writes_on cls' Top = lib_value cls `lib_writes_on cls Top \<union> {b}" apply(simp add: lib_CAS_Rel_step_def,elim exE conjE) apply(case_tac "lib_value cls (aa, ba) = a", simp_all) apply(simp add: lib_update_r_def all_updates_l lib_writes_on_def var_def tst_def lib_value_def) apply safe apply auto[1] apply auto[1] apply (smt Lib.lib_write_record.select_convs(1) a_is_x fst_conv image_iff mem_Collect_eq) by (smt fresh_ts_not_in_writes image_iff mem_Collect_eq) lemma success_CAS_Top_written_addr_post2: "cls ccs CAS\<^sup>R[libTop, True, a , b]\<^sub>t cls' ccs' \<Longrightarrow> b \<noteq> Null \<Longrightarrow> written_addr cls' = written_addr cls \<union> {b}" using success_CAS_Top_written_addr_post written_addr_def by (simp add: written_addr_def insert_Diff_if) lemma read_value_in_written: "cls ccs [r \<leftarrow>\<^sup>A lib x]\<^sub>t cls' ccs' \<Longrightarrow> r \<in> lib_value cls ` lib_writes_on cls x" apply(simp add: lib_writes_on_def lib_value_def lib_read_step_def lib_read_def all_updates_l, elim exE conjE) by (smt image_iff lib_visible_writes_def lib_writes_on_def mem_Collect_eq) lemma c_obs_Top_read: assumes "wfs cs" and "lib_wfs ls cs" and "c_obs_Top t ps cls ccs" and "lib_read_step t' x b cls ccs cls' ccs' v " shows "c_obs_Top t ps' cls' ccs'" using assms apply(simp add: c_obs_Top_def) apply(intro conjI allI impI) apply(erule_tac x=ad in allE) apply(subgoal_tac "written_addr cls' = written_addr cls") defer apply(simp add: written_addr_def , elim exE conjE) apply(subgoal_tac "lib_writes_on cls' Top = lib_writes_on cls Top", simp) apply(simp add: lib_value_def) apply(subgoal_tac "\<forall> w . w\<in>lib_writes_on cls Top \<longrightarrow> lib_mods cls w = lib_mods cls' w") apply (metis (no_types, lifting) image_cong) apply(intro allI impI) apply(simp add: lib_read_step_def lib_read_def all_updates_l) apply auto[1] apply(simp add: lib_read_step_def lib_read_def all_updates_l lib_writes_on_def var_def tst_def) apply auto[1] apply (simp, elim conjE exE) apply(rule_tac x=xa in exI) apply(simp add: lib_c_obs_lib_only_def) apply(simp add: lib_visible_writes_def lib_d_obs_def, intro allI impI conjI) apply(simp add: lib_read_step_def lib_visible_writes_def lib_read_def all_updates_l, elim conjE exE) apply(case_tac "lib_syncing cls (aa, baa) b", simp_all) apply(simp add: lib_writes_on_def lib_lastWr_def var_def tst_def) apply(unfold lib_wfs_def lib_writes_on_def var_def tst_def lib_value_def lib_lastWr_def, simp)[1] apply (smt dual_order.trans fun_upd_other fun_upd_same snd_conv ts_oride_def tst_def) apply(unfold lib_wfs_def lib_writes_on_def var_def tst_def lib_value_def lib_lastWr_def, simp)[1] apply (smt dual_order.trans fun_upd_apply snd_conv) apply(simp add: lib_read_step_def lib_visible_writes_def lib_read_def all_updates_l, elim conjE exE) apply(unfold lib_wfs_def lib_writes_on_def var_def tst_def lib_value_def lib_lastWr_def, simp)[1] apply(case_tac "lib_syncing cls (x, baa) b", simp_all, elim conjE exE) apply (smt dual_order.trans fst_conv fun_upd_other fun_upd_same snd_conv ts_oride_def tst_def) apply (smt dual_order.trans fst_conv fun_upd_other fun_upd_same snd_conv ts_oride_def tst_def) apply(simp add: lib_read_step_def lib_visible_writes_def lib_read_def all_updates_l, elim conjE exE) apply(unfold lib_wfs_def lib_writes_on_def var_def tst_def lib_value_def lib_lastWr_def, simp)[1] apply(case_tac "lib_syncing cls (x, baa) b", simp_all, elim conjE exE) apply(simp_all add: lib_releasing_def) apply (smt dual_order.trans fst_conv fun_upd_other fun_upd_same snd_conv ts_oride_def tst_def) by (smt dual_order.trans fst_conv fun_upd_apply snd_conv) lemma c_obs_TopNxt_read: assumes "wfs cs" and "lib_wfs ls cs" and "c_obs_TopNxt t ps cls ccs" and "lib_read_step t' x b cls ccs cls' ccs' v " shows "c_obs_TopNxt t ps' cls' ccs'" using assms apply(simp add: c_obs_TopNxt_def) apply(intro conjI allI impI) apply(erule_tac x=ad in allE) apply(subgoal_tac "written_addr cls' = written_addr cls") defer apply(simp add: written_addr_def , elim exE conjE) apply(subgoal_tac "lib_writes_on cls' Top = lib_writes_on cls Top", simp) apply(simp add: lib_value_def) apply(subgoal_tac "\<forall> w . w\<in>lib_writes_on cls Top \<longrightarrow> lib_mods cls w = lib_mods cls' w") apply (metis (no_types, lifting) image_cong) apply(intro allI impI) apply(simp add: lib_read_step_def lib_read_def all_updates_l) apply auto[1] apply(simp add: lib_read_step_def lib_read_def all_updates_l lib_writes_on_def var_def tst_def) apply auto[1] apply (simp, elim conjE exE) apply(rule_tac x=xa in exI) apply(simp add: lib_c_obs_lib_only_def) apply(simp add: lib_visible_writes_def lib_d_obs_def, intro allI impI conjI) apply(simp add: lib_read_step_def lib_visible_writes_def lib_read_def all_updates_l, elim conjE exE) apply(case_tac "lib_syncing cls (aa, baa) b", simp_all) apply(simp add: lib_writes_on_def lib_lastWr_def var_def tst_def) apply(unfold lib_wfs_def lib_writes_on_def var_def tst_def lib_value_def lib_lastWr_def, simp)[1] apply (smt dual_order.trans fun_upd_other fun_upd_same snd_conv ts_oride_def tst_def) apply(unfold lib_wfs_def lib_writes_on_def var_def tst_def lib_value_def lib_lastWr_def, simp)[1] apply (smt dual_order.trans fun_upd_apply snd_conv) apply(simp add: lib_read_step_def lib_visible_writes_def lib_read_def all_updates_l, elim conjE exE) apply(unfold lib_wfs_def lib_writes_on_def var_def tst_def lib_value_def lib_lastWr_def, simp)[1] apply(case_tac "lib_syncing cls (x, baa) b", simp_all, elim conjE exE) apply (smt dual_order.trans fst_conv fun_upd_other fun_upd_same snd_conv ts_oride_def tst_def) apply (smt dual_order.trans fst_conv fun_upd_other fun_upd_same snd_conv ts_oride_def tst_def) apply(unfold lib_wfs_def lib_writes_on_def var_def tst_def lib_value_def lib_lastWr_def, simp)[1] apply(simp add: lib_read_step_def lib_visible_writes_def lib_read_def all_updates_l, elim conjE exE) apply(simp_all add: lib_releasing_def) by (smt fun_upd_other fun_upd_same lib_writes_on_def mem_Collect_eq order.trans snd_conv ts_oride_def tst_def) lemma c_obs_Top_CASR_unsuccessful: assumes "wfs cs" and "lib_wfs ls cs" and "c_obs_Top t ps cls ccs" and "cls ccs CAS\<^sup>R[lib(x), False, u , u']\<^sub>t' cls' ccs' " shows "c_obs_Top t ps' cls' ccs'" using assms apply(simp add: lib_CAS_Rel_step_def, elim exE conjE) apply(case_tac "lib_value cls (a, b) = u", simp_all) by (meson c_obs_Top_read lib_read_step_def) lemma c_obs_TopNxt_CASR_unsuccessful: assumes "wfs cs" and "lib_wfs ls cs" and "c_obs_TopNxt t ps cls ccs" and "cls ccs CAS\<^sup>R[lib(x), False, u , u']\<^sub>t' cls' ccs' " shows "c_obs_TopNxt t ps' cls' ccs'" using assms apply(simp add: lib_CAS_Rel_step_def, elim exE conjE) apply(case_tac "lib_value cls (a, b) = u", simp_all) by (meson c_obs_TopNxt_read lib_read_step_def) lemma last_the_same1: "lib_wfs cls als \<Longrightarrow> w \<in> lib_visible_writes cls t Top \<Longrightarrow> w \<notin> lib_covered cls \<Longrightarrow> lib_valid_fresh_ts cls w ts' \<Longrightarrow> cls' = fst (lib_update_r t w u cls ccs ts') \<Longrightarrow> ts' < tst (lib_lastWr cls Top) \<Longrightarrow> lib_lastWr cls' Top = lib_lastWr cls Top" apply(simp add: lib_visible_writes_def lib_valid_fresh_ts_def lib_lastWr_def lib_writes_on_def all_updates_l lib_update_r_def) apply(simp add: var_def tst_def) apply safe apply(subgoal_tac "ts' < Max (snd ` {w. fst w = Top \<and> w \<in> lib_writes cls})") defer apply blast apply(subgoal_tac "{w. fst w = Top \<and> (w = (Top, ts') \<or> w \<in> lib_writes cls)} = {w. fst w = Top \<and> (w \<in> lib_writes cls)} \<union> {(Top, ts')}") defer apply safe apply simp apply simp apply(subgoal_tac " Max (insert ts' (snd ` {w. fst w = Top \<and> w \<in> lib_writes cls})) \<in> {ts', Max (snd ` {w. fst w = Top \<and> w \<in> lib_writes cls})}") defer apply(subgoal_tac "finite(snd ` {w. fst w = Top \<and> w \<in> lib_writes cls})") apply (metis (no_types, lifting) Max_in finite.insertI infinite_growing insertCI insertE insert_not_empty member_less_max) apply(simp add: lib_wfs_def lib_writes_on_def var_def tst_def) apply(subgoal_tac "Max ((snd ` {w. fst w = Top \<and> w \<in> lib_writes cls})) \<noteq> ts'") defer apply linarith apply simp apply(simp add: lib_wfs_def lib_writes_on_def var_def tst_def) apply(subgoal_tac "ts'\<notin> snd ` {w. fst w = Top \<and> w \<in> lib_writes cls}") defer apply(elim disjE) apply safe apply auto[1] apply auto[1] apply(subgoal_tac "snd ` {w. fst w = Top \<and> w \<in> lib_writes cls} \<noteq> {}") defer apply blast by auto lemma last_the_same2: "lib_wfs cls als \<Longrightarrow> w \<in> lib_visible_writes cls t Top \<Longrightarrow> w \<notin> lib_covered cls \<Longrightarrow> lib_valid_fresh_ts cls w ts' \<Longrightarrow> cls' = fst (lib_update_r t w u cls ccs ts') \<Longrightarrow> ts' > tst (lib_lastWr cls Top) \<Longrightarrow> lib_lastWr cls' Top = (Top, ts')" apply(simp add: lib_visible_writes_def lib_valid_fresh_ts_def lib_lastWr_def lib_writes_on_def all_updates_l lib_update_r_def) apply(simp add: var_def tst_def) apply safe apply(subgoal_tac "ts' > Max (snd ` {w. fst w = Top \<and> w \<in> lib_writes cls})") defer apply blast apply(subgoal_tac "{w. fst w = Top \<and> w \<in> lib_writes cls} \<noteq> {}") apply(subgoal_tac "finite({w. fst w = Top \<and> w \<in> lib_writes cls})") apply(subgoal_tac "{w. fst w = Top \<and> (w = (Top, ts') \<or> w \<in> lib_writes cls)} = {w. fst w = Top \<and> (w \<in> lib_writes cls)} \<union> {(Top, ts')}") using max_of_union apply auto[1] apply(simp add: lib_wfs_def lib_writes_on_def var_def) apply (simp add: writes_ts_rewrite) apply(simp add: lib_wfs_def lib_writes_on_def var_def) by blast lemma nxt_rel_subset: "a \<notin> pushed_addr ps \<Longrightarrow> b\<in>pushed_addr ps \<Longrightarrow> pushed_addr ps' = pushed_addr ps \<union> {a} \<Longrightarrow> nxt_rel ps cls \<subseteq> nxt_rel ps' cls" apply(simp add: nxt_rel_def) by auto lemma nxt_rel_subset1: "a\<notin>pushed_addr ps \<Longrightarrow> pushed_addr ps' = pushed_addr ps \<Longrightarrow> nxt_rel ps cls\<subseteq> nxt_rel ps' cls" by(simp add: nxt_rel_def) lemma agt_add_n: "a \<in> pushed_addr ps \<Longrightarrow> b\<in>pushed_addr ps \<Longrightarrow> agt a b ps cls \<Longrightarrow> pushed_addr ps' = pushed_addr ps \<union> {c} \<Longrightarrow> c\<notin>pushed_addr ps \<Longrightarrow> agt a b ps' cls" apply(simp add: agt_def clss_def) apply(subgoal_tac "nxt_rel ps cls\<subseteq> nxt_rel ps' cls") using trancl_mono apply blast using nxt_rel_subset by (simp add: nxt_rel_subset) lemma agt_pushed_same: "a\<notin>pushed_addr ps \<Longrightarrow> agt a b ps cls \<Longrightarrow> pushed_addr ps' = pushed_addr ps \<Longrightarrow> agt a b ps' cls" apply(simp add: agt_def clss_def) apply(subgoal_tac "nxt_rel ps cls \<subseteq> nxt_rel ps' cls") using trancl_mono apply blast using nxt_rel_subset by (simp add: nxt_rel_subset1) (*nxt ps' = (nxt ps) (a := b) \<Longrightarrow>*) lemma agt_pushed_same2: "agt c d ps cls \<Longrightarrow> pushed_addr ps' = pushed_addr ps \<Longrightarrow> agt c d ps' cls" apply(simp add: agt_def clss_def) apply(subgoal_tac "nxt_rel ps cls\<subseteq> nxt_rel ps' cls") using trancl_mono apply blast using nxt_rel_subset by (simp add: nxt_rel_def) lemma agt_pushed_failed_cas: " glb_inv ps cls \<Longrightarrow> cls ccs CAS\<^sup>R[lib a, False, u, u']\<^sub>t cls' ccs'\<Longrightarrow> agt c d ps cls \<Longrightarrow> same_except_for_pc_and_top ps ps' \<Longrightarrow> agt c d ps' cls'" apply(simp add: agt_def clss_def) apply(subgoal_tac "nxt_rel ps cls \<subseteq> nxt_rel ps' cls'") apply (simp add: nxt_rel_def) apply (simp add: trancl_mono) apply (simp add: nxt_rel_def) apply safe apply(rule_tac x= aaa in exI) apply safe apply(simp add: globals) using failed_CAS_preserves_last by auto lemma agt_pushed_successful_cas: " glb_inv ps cls \<Longrightarrow> cls ccs CAS\<^sup>R[lib Top, True, u, u']\<^sub>t cls' ccs'\<Longrightarrow> u' \<noteq> c \<Longrightarrow> u' \<noteq> d \<Longrightarrow> agt c d ps cls \<Longrightarrow> pushed_addr ps' = pushed_addr ps \<union> {u'} \<Longrightarrow> agt c d ps' cls'" apply(simp add: agt_def clss_def) apply(subgoal_tac "nxt_rel ps cls \<subseteq> nxt_rel ps' cls'") apply (simp add: nxt_rel_def) apply (simp add: trancl_mono) apply (simp add: nxt_rel_def) apply(simp add: globals) by (smt Collect_mono_iff succ_CAS_preserves_last) lemma cls_after_new_before: assumes "(a,b)\<in>f'\<^sup>+" and "(a,c)\<notin>f'\<^sup>+" and "c \<noteq> a" and "f' = f \<union> {(c,d)}" shows "(a,b)\<in>f\<^sup>+" using assms apply(induction a b rule: trancl.induct) apply auto[1] by (metis Un_insert_right insert_iff old.prod.inject sup_bot.right_neutral trancl.trancl_into_trancl) lemma no_nxt_no_agt: "\<forall> e . e\<in>pushed_addr ps \<longrightarrow> lib_value cls (lib_lastWr cls (Suc e)) \<noteq> b \<Longrightarrow> \<not> agt a b ps cls" apply(simp add: agt_def clss_def nxt_rel_def) apply(case_tac "a \<in> pushed_addr ps") apply(simp add: trancl_def ) apply (smt tranclp.cases) apply(simp add: trancl_def ) using converse_tranclpE by fastforce lemma agt_pushed_successful_cas_before: " glb_inv ps cls \<Longrightarrow> to ps cls \<Longrightarrow> glb ps cls \<Longrightarrow> cls ccs CAS\<^sup>R[lib Top, True, u, u']\<^sub>t cls' ccs'\<Longrightarrow> u' \<notin> pushed_addr ps \<Longrightarrow> u' \<noteq> c \<Longrightarrow> u' \<noteq> d \<Longrightarrow> c\<in>pushed_addr ps \<Longrightarrow> d\<in>pushed_addr ps \<Longrightarrow> agt c d ps' cls' \<Longrightarrow> \<not>agt c u' ps' cls' \<Longrightarrow> u' \<noteq> Top \<Longrightarrow> Suc u' \<noteq> Top \<Longrightarrow> pushed_addr ps' = pushed_addr ps \<union> {u'} \<Longrightarrow> agt c d ps cls" apply(simp add: agt_def clss_def) apply(subgoal_tac " nxt_rel ps' cls' = nxt_rel ps cls \<union> {(u', lib_value cls (lib_lastWr cls (Suc (u'))))}", simp) apply (metis Un_empty_right Un_insert_right cls_after_new_before) apply(simp add: nxt_rel_def) apply(subgoal_tac "\<forall> p . p\<in>pushed_addr ps \<longrightarrow> lib_value cls' (lib_lastWr cls' (Suc p)) = lib_value cls (lib_lastWr cls (Suc p))") defer apply(simp add: globals) apply (metis succ_CAS_preserves_last) apply safe using succ_CAS_preserves_last apply auto[1] defer apply blast using succ_CAS_preserves_last apply auto[1] apply simp by blast lemma aa: "finite (A::((nat \<times> nat) set)) \<Longrightarrow> A \<noteq> {} \<Longrightarrow> Max (snd `A) \<in> snd `A" using Max_in by blast lemma aa1: "finite (A::((nat \<times> nat) set)) \<Longrightarrow> A \<noteq> {} \<Longrightarrow> Max (snd `A) \<in> snd `A" using Max_in by blast lemma lib_lastWr_in_lib_writes_on: "finite(lib_writes_on cls Top) \<Longrightarrow> lib_writes_on cls Top \<noteq> {} \<Longrightarrow> lib_lastWr cls Top \<in> lib_writes_on cls Top" apply(simp add: lib_lastWr_def ) apply safe apply(subgoal_tac "a = Top", simp) defer apply(simp add: lib_writes_on_def) apply(subgoal_tac "b \<in> (tst ` lib_writes_on cls Top)") defer apply(simp add: lib_writes_on_def var_def tst_def) apply (simp add: image_iff) apply(subgoal_tac "Max (tst ` lib_writes_on cls Top) \<notin> tst ` lib_writes_on cls Top") defer apply(simp add: lib_writes_on_def var_def tst_def) apply (simp add: image_iff) apply(simp add: lib_writes_on_def var_def tst_def) by (metis (no_types, lifting) Max_eq_iff empty_iff finite_imageI) lemma agt_pop_successful_cas_before3: "lib_wfs cls ccs \<Longrightarrow> glb_inv ps cls \<Longrightarrow> glb ps cls \<Longrightarrow> to ps cls \<Longrightarrow> cvd[lib(Top), u] cls \<Longrightarrow> cls ccs CAS\<^sup>R[lib Top, True, u, u']\<^sub>t cls' ccs'\<Longrightarrow> u \<noteq> u' \<Longrightarrow> c\<in>pushed_addr ps \<Longrightarrow> d\<in>pushed_addr ps \<Longrightarrow> u \<noteq> c \<Longrightarrow> u\<noteq>d \<Longrightarrow> agt c d ps' cls' \<Longrightarrow> pushed_addr ps' = pushed_addr ps - {u} \<Longrightarrow> agt c d ps cls" apply(subgoal_tac "lastTop cls = u") defer apply(simp add: lastTop_def lib_covered_v_def) apply safe apply(subgoal_tac "\<exists> w . w\<in>lib_writes_on cls Top \<and> w = lib_lastWr cls Top") apply(elim exE conjE) apply(subgoal_tac "w \<notin> lib_covered cls") apply fastforce apply(simp add: lib_wfs_def) apply auto[1] apply(subgoal_tac "lib_lastWr cls Top\<in>lib_writes_on cls Top") apply blast apply(simp add: lib_wfs_def ) using lib_lastWr_in_lib_writes_on apply fastforce apply(simp add: agt_def) apply(subgoal_tac " agt u c ps cls \<and> agt u d ps cls") defer apply (simp add: globals to_p2_def) apply(simp add: agt_def clss_def) apply(subgoal_tac "nxt_rel ps' cls' = nxt_rel ps cls - {(u, lib_value cls (lib_lastWr cls (Suc u)))}") apply (simp add: trancl_mono) apply(simp add: nxt_rel_def) apply(subgoal_tac "\<forall> p . p\<in>pushed_addr ps \<longrightarrow> lib_value cls' (lib_lastWr cls' (Suc p)) = lib_value cls (lib_lastWr cls (Suc p))") apply(subgoal_tac "{(a, lib_value cls' (lib_lastWr cls' (Suc a))) |a. a \<in> pushed_addr ps \<and> a \<noteq> lastTop cls} = {(a, lib_value cls' (lib_lastWr cls' (Suc a))) |a. a \<in> pushed_addr ps} - {(lastTop cls, lib_value cls' (lib_lastWr cls' (Suc (lastTop cls))))} ") apply(simp add: lastTop_def) apply safe apply blast apply blast apply simp apply simp apply blast apply blast apply blast apply(simp add: globals) by (metis succ_CAS_preserves_last) lemma agt_pushed_failed_cas_before_state: " glb_inv ps cls \<Longrightarrow> cls ccs CAS\<^sup>R[lib a, False, u, u']\<^sub>t cls' ccs'\<Longrightarrow> agt c d ps' cls' \<Longrightarrow> same_except_for_pc_and_top ps ps' \<Longrightarrow> agt c d ps cls" apply(simp add: agt_def clss_def) apply(subgoal_tac "nxt_rel ps cls = nxt_rel ps' cls'") apply (simp add: nxt_rel_def) apply (simp add: nxt_rel_def) apply safe apply(rule_tac x= aaa in exI) apply safe apply(simp add: globals) using failed_CAS_preserves_last by auto lemma agt_pushed_same2wr: " glb_inv ps cls \<Longrightarrow> a \<notin> pushed_addr ps \<Longrightarrow> a\<in>addr_val ps \<Longrightarrow> cls ccs [lib a := v]\<^sub>t cls' ccs'\<Longrightarrow> agt c d ps cls \<Longrightarrow> same_except_for_pc_and_top ps ps' \<Longrightarrow> agt c d ps' cls'" apply(simp add: agt_def clss_def) apply(subgoal_tac "nxt_rel ps cls \<subseteq> nxt_rel ps' cls'") apply (simp add: nxt_rel_def) apply (simp add: trancl_mono) apply (simp add: nxt_rel_def) apply safe apply(rule_tac x= aaa in exI) apply safe apply(simp add: globals) by (metis wr_preserves_last) lemma agt_pushed_same2wr_before_state: " glb_inv ps cls \<Longrightarrow> a \<notin> pushed_addr ps \<Longrightarrow> a\<in>addr_val ps \<Longrightarrow> cls ccs [lib a := v]\<^sub>t cls' ccs'\<Longrightarrow> agt c d ps' cls' \<Longrightarrow> same_except_for_pc_and_top ps ps' \<Longrightarrow> agt c d ps cls" apply(simp add: agt_def clss_def) apply(subgoal_tac "nxt_rel ps cls = nxt_rel ps' cls'") apply simp apply (simp add: nxt_rel_def written_addr_def globals) apply safe apply (metis wr_preserves_last) apply (metis wr_preserves_last) apply (metis wr_preserves_last) by (metis wr_preserves_last) lemma agt_pushed_same2wr_nxt: " glb_inv ps cls \<Longrightarrow> a \<notin> pushed_addr ps \<Longrightarrow> a\<in>addr_val ps \<Longrightarrow> cls ccs [lib (a+1) := v]\<^sub>t cls' ccs'\<Longrightarrow> agt c d ps cls \<Longrightarrow> same_except_for_pc_and_top ps ps' \<Longrightarrow> agt c d ps' cls'" apply(simp add: agt_def clss_def) apply(subgoal_tac "nxt_rel ps cls \<subseteq> nxt_rel ps' cls'") apply (simp add: nxt_rel_def) apply (simp add: trancl_mono) apply (simp add: nxt_rel_def) apply safe apply(rule_tac x= aaa in exI) apply safe apply(simp add: globals) by (metis Suc_inject wr_preserves_last) lemma agt_pushed_same2wr_nxt_before_state: " glb_inv ps cls \<Longrightarrow> a \<notin> pushed_addr ps \<Longrightarrow> a\<in>addr_val ps \<Longrightarrow> cls ccs [lib (a+1) := v]\<^sub>t cls' ccs'\<Longrightarrow> agt c d ps' cls' \<Longrightarrow> same_except_for_pc_and_top ps ps' \<Longrightarrow> agt c d ps cls" apply(simp add: agt_def clss_def) apply(subgoal_tac "nxt_rel ps cls \<subseteq> nxt_rel ps' cls'") apply (simp add: nxt_rel_def) apply (smt Collect_cong nat.inject wr_preserves_last) apply (simp add: nxt_rel_def) apply safe apply(rule_tac x= aaa in exI) apply safe apply(simp add: globals) by (metis Suc_inject wr_preserves_last) lemma agt_pushed_same2rd: "cls ccs [a \<leftarrow>\<^sup>A lib b]\<^sub>t cls' ccs' \<Longrightarrow> agt c d ps cls \<Longrightarrow> pushed_addr ps' = pushed_addr ps \<Longrightarrow> agt c d ps' cls'" apply(simp add: agt_def clss_def) apply(subgoal_tac "nxt_rel ps cls \<subseteq> nxt_rel ps' cls'") using trancl_mono apply blast apply (simp add: nxt_rel_def) by (simp add: rd_A_preserves_last) lemma agt_pushed_same2rd_relax: "cls ccs [a \<leftarrow> lib b]\<^sub>t cls' ccs' \<Longrightarrow> agt c d ps cls \<Longrightarrow> pushed_addr ps' = pushed_addr ps \<Longrightarrow> agt c d ps' cls'" apply(simp add: agt_def clss_def) apply(subgoal_tac "nxt_rel ps cls \<subseteq> nxt_rel ps' cls'") using trancl_mono apply blast apply (simp add: nxt_rel_def) by (simp add: rd_preserves_last) lemma agt_pushed_same2rd_before_state: "cls ccs [a \<leftarrow>\<^sup>A lib b]\<^sub>t cls' ccs' \<Longrightarrow> agt c d ps' cls' \<Longrightarrow> pushed_addr ps' = pushed_addr ps \<Longrightarrow> agt c d ps cls" apply(simp add: agt_def clss_def) apply(subgoal_tac "nxt_rel ps cls = nxt_rel ps' cls'") using trancl_mono apply blast apply (simp add: nxt_rel_def) by (simp add: rd_A_preserves_last) lemma agt_pushed_same2rd_relax_before_state: "cls ccs [a \<leftarrow> lib b]\<^sub>t cls' ccs' \<Longrightarrow> agt c d ps' cls' \<Longrightarrow> pushed_addr ps' = pushed_addr ps \<Longrightarrow> agt c d ps cls" apply(simp add: agt_def clss_def) apply(subgoal_tac "nxt_rel ps cls = nxt_rel ps' cls'") using trancl_mono apply blast apply (simp add: nxt_rel_def) by (simp add: rd_preserves_last) lemma agt_pushed_same3: "a\<notin>pushed_addr ps \<Longrightarrow> b\<in>pushed_addr ps \<Longrightarrow> agt b c ps cls \<Longrightarrow> pushed_addr ps' = pushed_addr ps \<union> {a} \<Longrightarrow> agt b c ps' cls" apply(simp add: agt_def clss_def) apply(subgoal_tac "nxt_rel ps cls\<subseteq> nxt_rel ps' cls") using trancl_mono apply blast apply(simp add: nxt_rel_def) by auto lemma clss_same: "a\<notin>pushed_addr ps \<Longrightarrow> pushed_addr ps' = pushed_addr ps \<Longrightarrow> clss ps' cls = clss ps cls" apply(simp add: clss_def) by (metis (full_types) nxt_rel_subset1 subset_antisym) lemma a_not_in_pushed_nxt_rel: "a \<notin> pushed_addr ps \<Longrightarrow> (a,b)\<notin>nxt_rel ps cls" apply(simp add: clss_def nxt_rel_def) done lemma a_not_in_pushed_clss: "a \<notin> pushed_addr ps \<Longrightarrow> (a,b)\<notin>clss ps cls" apply(simp add: clss_def) by (meson a_not_in_pushed_nxt_rel tranclD) lemma not_dom: "glb_inv ps cls \<Longrightarrow> a\<notin>pushed_addr ps \<Longrightarrow> a \<noteq> Null \<Longrightarrow> a \<notin> Domain (nxt_rel ps cls)" apply (simp add: agt_def clss_def nxt_rel_def) by auto lemma not_range: "glb_inv ps cls \<Longrightarrow> a\<notin>pushed_addr ps \<Longrightarrow> a \<noteq> Null \<Longrightarrow> a \<notin> Range (nxt_rel ps cls)" apply (simp add: agt_def globals clss_def nxt_rel_def) by auto lemma a_not_in_range: "glb_inv ps cls \<Longrightarrow> a \<noteq> Null \<Longrightarrow> a\<notin>pushed_addr ps \<Longrightarrow> pushed_addr ps' = pushed_addr ps \<union> {a} \<Longrightarrow> lastNxtVal cls a \<noteq> a \<Longrightarrow> a\<notin>Range (clss ps' cls)" apply (simp add: clss_def) apply (simp add: clss_def nxt_rel_def) using not_range by (smt Null_def RangeE Suc_eq_plus1 glb_inv8_def globals(1) lastVal_def mem_Collect_eq neq0_conv prod.sel(2)) lemma a_not_in_clss_prime: "glb_inv ps cls \<Longrightarrow> a \<noteq> Null \<Longrightarrow> a\<notin>pushed_addr ps \<Longrightarrow> pushed_addr ps' = pushed_addr ps \<union> {a} \<Longrightarrow> lastNxtVal cls a \<noteq> a \<Longrightarrow> (a,a)\<notin>clss ps' cls" by (meson Range_iff a_not_in_range) lemma failed_cas_preserves_clss: "cls ccs CAS\<^sup>R[lib(x), False, v, u]\<^sub>t cls' ccs' \<Longrightarrow> pushed_addr ps' = pushed_addr ps \<Longrightarrow> clss ps' cls' = clss ps cls" apply(simp add: clss_def nxt_rel_def) by (simp add: failed_CAS_preserves_last) lemma or_union_eq: "finite P \<Longrightarrow> {(x, f x) | x . x\<in>P \<or> x = a} = insert (a, f a) {(x, f x) | x . x\<in>P}" apply safe apply simp apply simp apply simp by simp lemma or_union_eq': "finite (pushed_addr ps) \<Longrightarrow> {(a, lib_value cls' (lib_lastWr cls' (Suc a))) |a. a = n_val ps t \<or> a \<in> pushed_addr ps} = insert (n_val ps t, lib_value cls' (lib_lastWr cls' (Suc (n_val ps t)))) {(a, lib_value cls' (lib_lastWr cls' (Suc a))) | a. a \<in> pushed_addr ps}" using or_union_eq[where a = "n_val ps t" and P = "pushed_addr ps"] by blast lemma tc1: "a\<in>f \<Longrightarrow> f' = f - {a} \<Longrightarrow> f'\<^sup>+\<subseteq>f\<^sup>+" by (simp add: subrelI trancl_mono) lemma to1: "to ps cls \<Longrightarrow> glb ps cls \<Longrightarrow> glb_inv ps cls \<Longrightarrow> Null \<notin> Domain (nxt_rel ps cls)" by (meson Domain.simps a_not_in_pushed_nxt_rel agt_def to_def to_p3_def to_p4_def) lemma to2: "to ps cls \<Longrightarrow> glb ps cls \<Longrightarrow> glb_inv ps cls \<Longrightarrow> Null \<notin> Domain (clss ps cls)" by (metis clss_def to1 trancl_domain) lemma a_nxt_null_smallest: "to ps cls \<Longrightarrow> glb ps cls \<Longrightarrow> glb_inv ps cls \<Longrightarrow> a\<in>pushed_addr ps \<Longrightarrow> b\<in>pushed_addr ps \<Longrightarrow> a\<noteq>b \<Longrightarrow> lastNxtVal cls a = Null \<Longrightarrow> agt b a ps cls" apply(simp add: agt_def) apply(subgoal_tac "(a,Null)\<in>clss ps cls") defer apply (simp add: agt_def to_def to_p3_def) apply(subgoal_tac "(a, Null)\<in>nxt_rel ps cls") defer apply(simp add: nxt_rel_def) apply(subgoal_tac "\<forall> add. add\<in>pushed_addr ps \<and> add \<noteq> a \<longrightarrow> (add, Null)\<notin>nxt_rel ps cls") defer apply (intro allI impI) apply(simp add: nxt_rel_def globals) apply (metis bot.not_eq_extremum bot_nat_def) apply(simp add: globals to_p2_def to_p3_def to_p4_def agt_def clss_def) by (metis (no_types, hide_lams) a_not_in_pushed_nxt_rel trancl.cases) lemma nothing_between_a_nxt: "to ps cls \<Longrightarrow> glb ps cls \<Longrightarrow> glb_inv ps cls \<Longrightarrow> a\<in>pushed_addr ps \<Longrightarrow> x\<in>pushed_addr ps \<Longrightarrow> agt a x ps cls \<Longrightarrow> x\<noteq> lastNxtVal cls a \<Longrightarrow> x\<noteq>a \<Longrightarrow> agt (lastNxtVal cls a) x ps cls" apply(simp add: globals to_p2_def to_p3_def to_p4_def) apply safe apply (metis a_not_in_pushed_clss agt_def ) by (smt Suc_eq_plus1 agt_def clss_def converse_tranclE fst_conv lastVal_def mem_Collect_eq nxt_rel_def prod.sel(2)) lemmas to_simps = to_def to_p1_def to_p2_def to_p4_def to_p3_def definition "rel_img r e \<equiv> {a . (e, a)\<in>r}" definition "rel_dr r e \<equiv> {(e,a) | a . (e, a)\<in>r}" lemma domain_clss: "to ps cls \<Longrightarrow> glb ps cls \<Longrightarrow> glb_inv ps cls \<Longrightarrow> Domain (clss ps cls) = pushed_addr ps" apply(simp add: clss_def nxt_rel_def globals ) apply safe apply auto[1] by blast lemma range_clss: "to ps cls \<Longrightarrow> glb ps cls \<Longrightarrow> glb_inv ps cls \<Longrightarrow> Range (clss ps cls) = (pushed_addr ps \<union> {Null}) - {lastTop cls}" apply(simp add: clss_def nxt_rel_def globals to_p2_def to_p3_def to_p4_def) apply safe apply auto[2] apply(simp_all) apply fastforce apply(simp add: agt_def clss_def nxt_rel_def) apply (meson Range.intros trancl.cases) apply (meson a_not_in_pushed_clss agt_def subset_iff) apply(simp add: agt_def clss_def nxt_rel_def) by (metis (mono_tags, lifting) Range.intros trancl_range) lemma ntop_other_stable: "t \<noteq> ta \<Longrightarrow> lib_pop t v ps cls ccs ps' cls' ccs' \<Longrightarrow> pc ps t = L2 \<Longrightarrow> ntop ps' ta = ntop ps ta" apply (subgoal_tac "ta \<noteq> t \<longrightarrow> ntop ps' ta = ntop ps ta") apply simp by (simp add: lib_pop_def) lemma read_lib_d_obs: "lib_wfs cls ccs \<Longrightarrow> cls ccs [ r \<leftarrow> lib x]\<^sub>t cls' ccs' \<Longrightarrow> [lib x =\<^sub>t n] cls \<Longrightarrow> r = n" apply(simp add: lib_read_step_def lib_d_obs_def lib_d_obs_t_def, elim exE conjE) apply(simp add: lib_read_def all_updates_l) apply(case_tac "lib_syncing cls (a, b) False", simp_all) apply (simp add: lib_syncing_def) apply(simp add: lib_wfs_def lib_syncing_def lib_visible_writes_def lib_writes_on_def lib_value_def tst_def var_def lib_lastWr_def) apply clarsimp by (metis (mono_tags, lifting) Max.coboundedI antisym finite_imageI image_eqI mem_Collect_eq snd_conv) lemma l5: "glb ps cls \<Longrightarrow> glb_inv12 ps cls \<Longrightarrow> glb_inv10 ps cls \<Longrightarrow> glb_inv6 ps cls \<Longrightarrow> glb_inv3 ps cls \<Longrightarrow> glb_inv4 ps cls \<Longrightarrow> glb_inv5 ps cls \<Longrightarrow> to ps cls \<Longrightarrow> lastTop cls \<noteq> Null \<Longrightarrow> lastVal cls ((lastTop cls) + 1) = Null \<Longrightarrow> pushed_addr ps \<subseteq> {lastTop cls}" apply (simp add: globals agt_def clss_def nxt_rel_def to_p3_def) apply safe apply simp apply(subgoal_tac "Null\<notin>pushed_addr ps") defer apply auto[1] apply simp by (smt mem_Collect_eq old.prod.inject tranclE) lemma Top_next_not_null: "glb ps cls \<Longrightarrow> to ps cls \<Longrightarrow> glb_inv ps cls \<Longrightarrow> e\<in>pushed_addr ps \<Longrightarrow> e \<noteq> lastTop cls \<Longrightarrow> lastTop cls \<noteq> Null \<Longrightarrow> lastNxtVal cls (lastTop cls) \<noteq> Null" apply(simp add: glb_inv_def) using TS_Proof_Rules.l5 by auto lemma TopLV_Null_pushed_empty: "to ps cls \<Longrightarrow> glb_inv ps cls \<Longrightarrow> glb ps cls \<Longrightarrow> lastTop cls = Null \<Longrightarrow> pushed_addr ps = {}" apply (simp add: globals to_p3_def agt_def clss_def nxt_rel_def) apply safe by (smt Collect_empty_eq Collect_empty_eq_bot bot_set_def empty_Collect_eq ex_in_conv exists_least_iff less_numeral_extra(3) mem_Collect_eq neq0_conv neqE not_less_zero of_nat_0_less_iff of_nat_eq_iff of_nat_less_0_iff of_nat_less_iff old.prod.exhaust old.prod.inject singleton_conv singleton_conv2 surj_pair tranclE trancl_trans zero_less_imp_eq_int) lemma agt_order: "agt a b ps cls \<Longrightarrow> agt b c ps cls \<Longrightarrow> agt a c ps cls " apply(simp add: agt_def clss_def nxt_rel_def) done lemma TopLV_agt_others: "to ps cls \<Longrightarrow> glb_inv ps cls \<Longrightarrow> glb ps cls \<Longrightarrow> b \<noteq> lastTop cls \<Longrightarrow> lastTop cls \<noteq> Null \<Longrightarrow> b\<in>pushed_addr ps \<Longrightarrow> agt (lastTop cls) b ps cls" apply (simp add: globals to_p3_def agt_def clss_def nxt_rel_def) apply safe by (smt Collect_empty_eq Collect_empty_eq_bot bot_set_def empty_Collect_eq ex_in_conv exists_least_iff less_numeral_extra(3) mem_Collect_eq neq0_conv neqE not_less_zero of_nat_0_less_iff of_nat_eq_iff of_nat_less_0_iff of_nat_less_iff old.prod.exhaust old.prod.inject singleton_conv singleton_conv2 surj_pair tranclE trancl_trans zero_less_imp_eq_int) lemma failed_CAS_R_preserves_dobs: assumes "[lib(x) =\<^sub>t u] cls" and "cls ccs CAS\<^sup>R[lib(y), False, u, u']\<^sub>t' cls' ccs'" and "lib_wfs cls ccs" and "wfs ccs" shows "[lib(x) =\<^sub>t u] cls'" using assms apply(simp add: lib_CAS_Rel_step_def, elim exE conjE) apply(case_tac "lib_value cls (a, b) = u", simp_all) using failed_CASR_pres_d_obs_lib by blast lemma failed_cas_dobs_to: "lib_wfs cls ccs \<Longrightarrow> wfs ccs \<Longrightarrow> dobs_to t ps cls ccs \<Longrightarrow> pushed_addr ps' = pushed_addr ps \<Longrightarrow> top ps' = top ps \<Longrightarrow> cls ccs CAS\<^sup>R[lib Top, False, u, u']\<^sub>t' cls' ccs'\<Longrightarrow> dobs_to t ps' cls' ccs'" apply(simp add: dobs_to_def same_except_for_pc_and_top_def) apply(intro conjI allI impI) apply(subgoal_tac "\<exists>vl. [libad =\<^sub>t vl] cls") apply(elim exE, rule_tac x=vl in exI) using failed_CAS_R_preserves_dobs apply (meson failed_CASR_pres_d_obs_lib) apply(subgoal_tac "agt (prog_state.top ps t) ad ps' cls' = agt (prog_state.top ps t) ad ps cls") apply blast apply(simp add: agt_def clss_def) apply (metis clss_def failed_cas_preserves_clss) apply(simp add: agt_def clss_def) by (smt clss_def failed_CASR_pres_d_obs_lib failed_cas_preserves_clss) lemma read_pres_last_val: assumes "wfs ccs" and "lib_wfs cls ccs" and "lib_read_step t' x b cls ccs cls' ccs' v " shows "lib_value cls' (lib_lastWr cls' y) = lib_value cls (lib_lastWr cls y)" using assms apply(simp add: lib_read_step_def lib_value_def lib_lastWr_def, elim exE) apply(simp add: lib_read_def all_updates_l) by (simp add: read_pres_writes_on_diff_var) lemma cobs_to_read_pres: assumes "wfs ccs" and "lib_wfs cls ccs" and "cobs_to t ps cls ccs" and "lib_read_step t' x b cls ccs cls' ccs' v " and "pushed_addr ps' = pushed_addr ps" shows "cobs_to t ps' cls' ccs'" using assms apply(simp add: cobs_to_def) apply safe apply(subgoal_tac "\<exists>vl. [libTop = ad1]\<lparr>libad2 =\<^sub>t vl \<rparr> cls") apply(elim exE conjE) apply(rule_tac x=vl in exI) using lib_c_obs_lib_only_pres_read_var apply blast apply(subgoal_tac "agt ad1 ad2 ps' cls' = agt ad1 ad2 ps cls") apply simp apply(simp add: agt_def clss_def nxt_rel_def) apply(subgoal_tac "{(a, lib_value cls' (lib_lastWr cls' (Suc a))) |a. a \<in> pushed_addr ps} = {(a, lib_value cls (lib_lastWr cls (Suc a))) |a. a \<in> pushed_addr ps}") apply simp apply(subgoal_tac "\<forall> a . a\<in>pushed_addr ps \<longrightarrow> lib_value cls' (lib_lastWr cls' (Suc a)) = lib_value cls (lib_lastWr cls (Suc a))") apply auto[1] apply safe apply (simp add: read_pres_last_val) apply(subgoal_tac "\<exists>vl. [libTop = ad1]\<lparr>libSuc(ad2) =\<^sub>t vl \<rparr> cls") apply(elim exE conjE) apply(rule_tac x=vl in exI) using lib_c_obs_lib_only_pres_read_var apply blast apply(subgoal_tac "agt ad1 ad2 ps' cls' = agt ad1 ad2 ps cls") apply simp apply(simp add: agt_def clss_def nxt_rel_def) apply(subgoal_tac "{(a, lib_value cls' (lib_lastWr cls' (Suc a))) |a. a \<in> pushed_addr ps} = {(a, lib_value cls (lib_lastWr cls (Suc a))) |a. a \<in> pushed_addr ps}") apply simp apply(subgoal_tac "\<forall> a . a\<in>pushed_addr ps \<longrightarrow> lib_value cls' (lib_lastWr cls' (Suc a)) = lib_value cls (lib_lastWr cls (Suc a))") apply auto[1] apply safe apply (simp add: read_pres_last_val) using lib_c_obs_lib_only_pres_read_var apply blast using lib_c_obs_lib_only_pres_read_var by blast lemma cobs_to_CAS_pres: assumes "wfs ccs" and "lib_wfs cls ccs" and "cobs_to t ps cls ccs" and "cls ccs CAS\<^sup>R[lib Top, False, u, u']\<^sub>t' cls' ccs'" and "pushed_addr ps' = pushed_addr ps" shows "cobs_to t ps' cls' ccs'" using assms apply(simp add: cobs_to_def) apply safe apply(subgoal_tac "\<exists>vl. [libTop = ad1]\<lparr>libad2 =\<^sub>t vl \<rparr> cls") apply(elim exE conjE) apply(rule_tac x=vl in exI) using failed_CASR_pres_c_obs_lib_only apply blast apply(subgoal_tac "agt ad1 ad2 ps' cls' = agt ad1 ad2 ps cls") apply simp apply(simp add: agt_def clss_def nxt_rel_def) apply(subgoal_tac "{(a, lib_value cls' (lib_lastWr cls' (Suc a))) |a. a \<in> pushed_addr ps} = {(a, lib_value cls (lib_lastWr cls (Suc a))) |a. a \<in> pushed_addr ps}") apply simp apply(subgoal_tac "\<forall> a . a\<in>pushed_addr ps \<longrightarrow> lib_value cls' (lib_lastWr cls' (Suc a)) = lib_value cls (lib_lastWr cls (Suc a))") apply auto[1] apply (simp add: failed_CAS_preserves_last) apply(subgoal_tac "\<exists>vl. [libTop = ad1]\<lparr>libSuc(ad2) =\<^sub>t vl \<rparr> cls") apply(elim exE conjE) apply(rule_tac x=vl in exI) using failed_CASR_pres_c_obs_lib_only apply auto[1] apply(subgoal_tac "agt ad1 ad2 ps' cls' = agt ad1 ad2 ps cls") apply simp apply(simp add: agt_def clss_def nxt_rel_def) apply(subgoal_tac "{(a, lib_value cls' (lib_lastWr cls' (Suc a))) |a. a \<in> pushed_addr ps} = {(a, lib_value cls (lib_lastWr cls (Suc a))) |a. a \<in> pushed_addr ps}") apply simp apply(subgoal_tac "\<forall> a . a\<in>pushed_addr ps \<longrightarrow> lib_value cls' (lib_lastWr cls' (Suc a)) = lib_value cls (lib_lastWr cls (Suc a))") apply auto[1] using failed_CAS_preserves_last apply auto[1] using failed_CASR_pres_c_obs_lib_only apply blast using failed_CASR_pres_c_obs_lib_only apply blast done lemma no_Top_n_written_addr: "no_Top_n t ps cls \<longrightarrow> n_val ps t \<notin> written_addr cls \<and> n_nxt ps t \<notin> written_addr cls" apply(simp add: no_Top_n_def written_addr_def) by fastforce lemma pobs_cobs_same_val: "lib_wfs cls ccs \<Longrightarrow> wfs ccs \<Longrightarrow> [lib(a)\<approx>\<^sub>t u]cls \<Longrightarrow> [lib(a)\<approx>\<^sub>t' u]cls \<Longrightarrow> [lib(a) = u]\<lparr>lib(b) =\<^sub>t u'\<rparr> cls \<Longrightarrow> [lib(a) = u]\<lparr>lib(b) =\<^sub>t' v'\<rparr> cls \<Longrightarrow> t\<noteq>t' \<Longrightarrow> u' = v'" by (smt lib_c_obs_lib_only_def lib_d_obs_def lib_p_obs_def) lemma dobs_pobs_cobs_same_val: "lib_wfs cls ccs \<Longrightarrow> wfs ccs \<Longrightarrow> [lib(b) =\<^sub>t v']cls \<Longrightarrow> [lib(a)\<approx>\<^sub>t u]cls \<Longrightarrow> [lib(a) = u]\<lparr>lib(b) =\<^sub>t u'\<rparr> cls \<Longrightarrow> u' = v'" by (smt lib_c_obs_lib_only_def lib_d_obs_def lib_d_obs_t_def lib_p_obs_def) lemma pobs_cobs_dobs_same_val: "lib_wfs cls ccs \<Longrightarrow> wfs ccs \<Longrightarrow> [lib(a)\<approx>\<^sub>t u]cls \<Longrightarrow> [lib(a) = u]\<lparr>lib(b) =\<^sub>t u'\<rparr> cls \<Longrightarrow> [lib(b) =\<^sub>t' v'] cls \<Longrightarrow> t\<noteq>t' \<Longrightarrow> u' = v'" by (smt lib_c_obs_lib_only_def lib_d_obs_def lib_d_obs_t_def lib_p_obs_def) lemma successful_CAS_lib_c_obs_lib_pre_same_value_pres2: assumes "wfs cs" and "lib_wfs ls cs" and "[lib(x) = u]\<lparr>lib(y) =\<^sub>t v \<rparr> cls" and "[lib(y) =\<^sub>t' v] cls" and "[lib(x) \<approx>\<^sub>t u] cls" and "\<not>[lib(x) \<approx>\<^sub>t' u] cls" and "cls ccs CAS\<^sup>R[lib(x), True, m, u]\<^sub>t' cls' ccs'" and "t \<noteq> t'" and "x \<noteq> y" shows "[lib(x) = u]\<lparr>lib(y) =\<^sub>t v \<rparr> cls'" using assms apply(simp add: lib_c_obs_lib_only_def lib_visible_writes_def) apply(intro allI impI conjI, elim conjE) apply(simp add: lib_d_obs_def lib_d_obs_t_def) apply(intro conjI, elim conjE) apply(simp add: lib_CAS_Rel_step_def, elim conjE exE) apply(case_tac "lib_value cls (aa, ba) = m", simp_all) apply(simp add: lib_update_r_def all_updates_l) apply safe using a_is_x apply blast using a_is_x apply blast using a_is_x apply blast apply(simp add: lib_lastWr_def) using CAS_Rel_preserves_writes_on_diff_var assms(7) apply auto[1] apply(simp add: lib_lastWr_def lib_writes_on_def) using a_is_x apply blast apply(simp add: lib_visible_writes_def lib_lastWr_def lib_writes_on_def lib_valid_fresh_ts_def tst_def var_def lib_value_def) apply safe apply (smt Collect_cong fst_conv) using succ_CAS_preserves_last apply blast apply(simp add: lib_CAS_Rel_step_def, elim conjE exE) apply(case_tac "lib_value cls (aa, ba) = m", simp_all) apply(simp add: lib_update_r_def all_updates_l lib_releasing_def) apply safe by (smt CAS_Rel_preserves_releasing_new CAS_Rel_preserves_value_old a_is_x assms(7) fun_upd_other lib_releasing_def lib_state.ext_inject lib_state.surjective lib_state.update_convs(1) lib_state.update_convs(2) lib_state.update_convs(3) lib_state.update_convs(4) lib_state.update_convs(5) lib_visible_writes_def mem_Collect_eq ts_not_in_writes_on) lemma nxt_a_b_not_agt_b_a: "glb_inv ps cls \<Longrightarrow> to ps cls \<Longrightarrow> a\<in>pushed_addr ps \<Longrightarrow> b\<in>pushed_addr ps \<Longrightarrow> lastNxtVal cls a = b \<Longrightarrow> \<not>agt b a ps cls" apply simp apply(simp add: globals to_p2_def to_p3_def to_p4_def agt_def clss_def nxt_rel_def ) apply safe apply (metis (no_types, lifting) trancl_trans) by (metis (mono_tags, lifting) mem_Collect_eq trancl_into_trancl2) lemma nxt_rel_after_successful_CAS: "glb ps cls \<Longrightarrow> glb_inv ps cls \<Longrightarrow> to ps cls \<Longrightarrow> cls ccs CAS\<^sup>R[lib(Top), True, b, a]\<^sub>t cls' ccs' \<Longrightarrow> lib_value cls (lib_lastWr cls (Suc (a))) = b \<Longrightarrow>a\<in>addr_val ps \<Longrightarrow> a\<notin>pushed_addr ps \<Longrightarrow> pushed_addr ps' = pushed_addr ps \<union> {a} \<Longrightarrow> nxt_rel ps' cls' = nxt_rel ps cls \<union> {(a, b)}" apply(simp add: nxt_rel_def globals to_simps) apply safe apply (metis (full_types) succ_CAS_preserves_last) apply (metis (full_types) succ_CAS_preserves_last) apply (metis (full_types) succ_CAS_preserves_last) apply (metis (full_types) succ_CAS_preserves_last) apply (metis (full_types) succ_CAS_preserves_last) apply (metis (full_types) succ_CAS_preserves_last) apply (metis (full_types) succ_CAS_preserves_last) apply (metis (full_types) succ_CAS_preserves_last) apply (metis (full_types) succ_CAS_preserves_last) apply (metis (full_types) succ_CAS_preserves_last) done lemma written_vals_write: "cls ccs [lib(x) := v]\<^sub>t cls' ccs' \<Longrightarrow> written_vals cls' x = written_vals cls x \<union> {v}" apply(simp add: lib_write_step_def written_vals_def, elim exE conjE) apply(simp add: lib_write_def all_updates_l lib_writes_on_def var_def tst_def lib_value_def) apply safe apply simp apply auto[1] apply (smt Lib.lib_write_record.select_convs(1) a_is_x fst_conv image_iff mem_Collect_eq) by (smt fresh_ts_not_in_writes image_iff mem_Collect_eq) lemma written_vals_write_diff_var: "cls ccs [lib(y) := v]\<^sub>t cls' ccs' \<Longrightarrow> x\<noteq>y \<Longrightarrow> written_vals cls' x = written_vals cls x" apply(simp add: lib_write_step_def written_vals_def, elim exE conjE) apply(simp add: lib_write_def all_updates_l lib_writes_on_def var_def tst_def lib_value_def) apply safe apply simp apply auto[1] apply (smt Lib.lib_write_record.select_convs(1) a_is_x fst_conv image_iff mem_Collect_eq) apply (smt fresh_ts_not_in_writes image_iff mem_Collect_eq) by (smt fresh_ts_not_in_writes image_iff mem_Collect_eq) lemma written_vals_CAS_Rel_diff_var: "cls ccs CAS\<^sup>R[lib(y), b, v, v']\<^sub>t cls' ccs' \<Longrightarrow> x\<noteq>y \<Longrightarrow> written_vals cls' x = written_vals cls x" apply(simp add: lib_CAS_Rel_step_def written_vals_def, elim exE conjE) apply(case_tac "lib_value cls (a, ba) = v", simp_all) apply(simp add: lib_update_r_def all_updates_l lib_writes_on_def var_def tst_def lib_value_def) apply safe apply simp apply auto[1] apply (smt Lib.lib_write_record.select_convs(1) a_is_x fst_conv image_iff mem_Collect_eq) apply (smt fresh_ts_not_in_writes image_iff mem_Collect_eq) apply (smt fresh_ts_not_in_writes image_iff mem_Collect_eq) apply(simp add: lib_read_def all_updates_l lib_writes_on_def var_def tst_def lib_value_def) apply auto[1] apply(simp add: lib_read_def all_updates_l lib_writes_on_def var_def tst_def lib_value_def) apply auto[1] done lemma "no_Top_n t' ps cls \<Longrightarrow> \<not>[lib(Top) \<approx>\<^sub>t (n_val ps t')] cls" apply(simp add: no_Top_n_def) by (simp add: no_Top_n_def no_Top_n_implies_no_p_obs) lemma agt_pres_diff_write: "cls ccs [lib(a) := b]\<^sub>t cls' ccs' \<Longrightarrow> a \<notin> pushed_addr ps \<Longrightarrow> pushed_addr ps' = pushed_addr ps \<Longrightarrow> (\<forall> e . e\<in>pushed_addr ps \<longrightarrow> Suc e \<noteq> a) \<Longrightarrow> agt c d ps cls = agt c d ps' cls'" apply(simp add : agt_def clss_def) apply(subgoal_tac "nxt_rel ps' cls' = nxt_rel ps cls") apply auto[1] apply(simp add: nxt_rel_def) using wr_preserves_last by auto lemma agt_ad2_pushed_or_null: "glb_inv ps cls \<Longrightarrow> to ps cls \<Longrightarrow> agt ad1 ad2 ps cls \<Longrightarrow> ad2\<in>pushed_addr ps \<union> {Null}" apply(simp add: agt_def clss_def) by (metis Null_def Range.intros not_range trancl_range) lemma agt_n_val_False: "(\<forall> p . p\<in>pushed_addr ps \<longrightarrow> lastVal cls (Suc p) \<noteq> ad2) \<Longrightarrow> agt ad1 ad2 ps cls \<Longrightarrow> False" apply(simp add: agt_def clss_def ) apply(subgoal_tac "ad2\<notin>Range (nxt_rel ps cls)") apply (metis Range.intros trancl_range) apply(simp add: nxt_rel_def) by blast lemma agt_ad1_not_in_pushed_False: "ad1\<notin>pushed_addr ps \<Longrightarrow> agt ad1 ad2 ps cls \<Longrightarrow> False" apply(simp add: agt_def clss_def nxt_rel_def) by (smt Pair_inject converse_tranclE mem_Collect_eq) end
import .lib /- * Parameterization by the word size, in bits. -/ namespace word section variable (n : ℕ) def wordsize : ℕ := n def modulus : ℕ := 2^wordsize n def half_modulus : ℕ := 2^(wordsize n - 1) def max_unsigned : ℕ := modulus n - 1 def max_signed : ℕ := half_modulus n - 1 def min_signed : ℤ := - half_modulus n theorem modulus_pos : modulus n > 0 := nat.pos_pow_of_pos _ dec_trivial theorem succ_max_unsigned : nat.succ (max_unsigned n) = modulus n := nat.succ_pred_eq_of_pos (modulus_pos _) end end word /- * Representation of machine integers -/ /- A machine integer (type [word]) is represented as an arbitrary-precision natural number (type [nat]) plus a proof that it is less than [modulus]. -/ def word (n) := fin (word.modulus n) namespace word def repr {w} (x : ℤ) : word w := ⟨x.nat_mod (modulus w), sorry'⟩ instance coe_int_word {w} : has_coe ℤ (word w) := ⟨repr⟩ /- The [unsigned] and [signed] functions return the Coq integer corresponding to the given machine integer, interpreted as unsigned or signed respectively. -/ def unsigned {w} (n : word w) : ℕ := n.1 section parameter {wordsize : ℕ} local notation `modulus` := modulus wordsize local notation `half_modulus` := half_modulus wordsize local notation `max_unsigned` := max_unsigned wordsize local notation `max_signed` := max_signed wordsize local notation `min_signed` := min_signed wordsize local notation `word` := word wordsize local notation `repr` := @repr wordsize local notation `unsigned` := @unsigned wordsize def signed (n : word) : ℤ := let x := unsigned n in if x < half_modulus then x else x - modulus instance coe_word_int : has_coe word ℤ := ⟨signed⟩ /- Conversely, [repr] takes a Coq integer and returns the corresponding machine integer. The argument is treated modulo [modulus]. -/ def in_srange (x : ℤ) : bool := min_signed ≤ x ∧ x < half_modulus def in_urange (x : ℕ) : bool := x < modulus def iwordsize := repr wordsize instance : has_zero word := ⟨repr 0⟩ instance : has_one word := ⟨repr 1⟩ instance eq_dec : decidable_eq word := by tactic.mk_dec_eq_instance /- * Arithmetic and logical operations over machine integers -/ def ltu (x y : word) : Prop := unsigned x < unsigned y def leu (x y : word) : Prop := unsigned x ≤ unsigned y instance : has_lt word := ⟨λx y, signed x < signed y⟩ instance : has_le word := ⟨λx y, signed x ≤ signed y⟩ protected def neg (x : word) : word := repr (-unsigned x) instance : has_neg word := ⟨word.neg⟩ protected def add (x y : word) : word := repr (unsigned x + unsigned y) protected def mul (x y : word) : word := repr (unsigned x * unsigned y) instance : has_add word := ⟨word.add⟩ instance : has_mul word := ⟨word.mul⟩ def divs (x y : word) : word := repr (int.quot (signed x) (signed y)) def mods (x y : word) : word := repr (int.rem (signed x) (signed y)) instance : has_div word := ⟨divs⟩ instance : has_mod word := ⟨mods⟩ def divu (x y : word) : word := repr (unsigned x / unsigned y : ℕ) def modu (x y : word) : word := repr (unsigned x % unsigned y : ℕ) /- Bitwise boolean operations. -/ protected def and (x y : word) : word := repr (int.land (unsigned x) (unsigned y)) protected def or (x y : word) : word := repr (int.lor (unsigned x) (unsigned y)) protected def xor (x y : word) : word := repr (int.lxor (unsigned x) (unsigned y)) protected def not (x : word) : word := repr (int.lnot (unsigned x)) /- Shifts and rotates. -/ def shl (x y : word) : word := repr (int.shiftl (unsigned x) (unsigned y)) def shru (x y : word) : word := repr (int.shiftr (unsigned x) (unsigned y)) def shr (x y : word) : word := repr (int.shiftr (signed x) (unsigned y)) def rol (x y : word) : word := let n := unsigned y % wordsize in repr (int.lor (int.shiftl (unsigned x) n) (int.shiftr (unsigned x) (wordsize - n))) def ror (x y : word) : word := let n := unsigned y % wordsize in repr (int.lor (int.shiftr (unsigned x) n) (int.shiftl (unsigned x) (wordsize - n))) def rolm (x a m : word) : word := word.and (rol x a) m /- Viewed as signed divisions by powers of two, [shrx] rounds towards zero, while [shr] rounds towards minus infinity. -/ def shrx (x y : word) : word := x / shl 1 y /- High half of full multiply. -/ def mulhu (x y : word) : word := repr ((unsigned x * unsigned y) / modulus) def mulhs (x y : word) : word := repr ((signed x * signed y) / modulus) instance coe_bool_word : has_coe bool word := ⟨λb, cond b 1 0⟩ /- Condition flags -/ def negative (x : word) : word := to_bool (x < 0) def add_carry (x y cin : word) : word := to_bool (unsigned x + unsigned y + unsigned cin ≥ modulus) def add_overflow (x y cin : word) : word := bnot $ in_srange (signed x + signed y + signed cin) def sub_borrow (x y bin : word) : word := to_bool (unsigned x - unsigned y - unsigned bin < 0) def sub_overflow (x y bin : word) : word := bnot $ in_srange (signed x - signed y - signed bin) /- [shr_carry x y] is 1 if [x] is negative and at least one 1 bit is shifted away. -/ def shr_carry (x y : word) : word := to_bool (x < 0 ∧ and x (shl 1 y + -1) ≠ 0) /- Zero and sign extensions -/ def zero_ext (n : ℕ) (x : word) : word := repr (unsigned x % 2^n) def sign_ext (n : ℕ+) (x : word) : word := let modulus' := 2^n.1, y := unsigned x % modulus' in repr (if y < modulus'/2 then y else y - modulus') /- Decomposition of a number as a sum of powers of two. -/ def one_bits (x : word) : list word := (num.one_bits (unsigned x)).map (λx:ℕ, repr x) /- Recognition of powers of two. -/ def is_power2 (x : word) : option word := match num.one_bits (unsigned x) with | (i :: []) := some (repr i) | _ := none end /- Comparisons. -/ instance decidable_lt : @decidable_rel word (<) := by apply_instance instance decidable_le : @decidable_rel word (≤) := by apply_instance instance decidable_ltu : decidable_rel ltu := by delta ltu; apply_instance instance decidable_leu : decidable_rel leu := by delta leu; apply_instance def cmp : comparison → word → word → bool | Ceq x y := x = y | Cne x y := x ≠ y | Clt x y := x < y | Cle x y := x ≤ y | Cgt x y := y < x | Cge x y := y ≤ x def cmpu : comparison → word → word → bool | Ceq x y := x = y | Cne x y := x ≠ y | Clt x y := ltu x y | Cle x y := bnot (ltu y x) | Cgt x y := ltu y x | Cge x y := bnot (ltu x y) def is_false (x : word) : Prop := x = 0 def is_true (x : word) : Prop := x ≠ 0 def notbool (x : word) : word := to_bool (x = 0) /- x86-style extended division and modulus -/ def divmodu2 (nhi nlo : word) (d : word) : option (word × word) := if d = 0 then none else let q := unsigned nhi * modulus + unsigned nlo / unsigned d in if q < modulus then some (repr q, repr (unsigned nhi * modulus + unsigned nlo % unsigned d)) else none def divmods2 (nhi nlo : word) (d : word) : option (word × word) := if d = 0 then none else let q := int.quot (signed nhi * modulus + unsigned nlo) (signed d) in if in_srange q then some (repr q, repr (int.rem (signed nhi * modulus + unsigned nlo) (signed d))) else none /- Encode and decode from an integer -/ def words_of_int : ℕ → ℤ → list word | 0 x := [] | (m + 1) x := repr x :: words_of_int m (x / modulus) def nat_of_words : list word → ℕ | [] := 0 | (b :: l') := unsigned b + nat_of_words l' * modulus /- * Properties of integers and integer arithmetic -/ /- Relative positions, from greatest to smallest: << max_unsigned max_signed 2*wordsize-1 wordsize 0 min_signed >> -/ theorem half_modulus_pos : half_modulus > 0 := nat.pos_pow_of_pos _ dec_trivial theorem min_signed_neg : min_signed < 0 := sorry' theorem max_signed_pos : max_signed ≥ 0 := sorry' theorem two_wordsize_max_unsigned : 2 * wordsize - 1 ≤ max_unsigned := sorry' theorem max_signed_unsigned : max_signed < max_unsigned := sorry' @[simp] lemma unsigned_repr_eq (x) : unsigned (repr x) = x.nat_mod modulus := sorry' lemma signed_repr_eq (x) : signed (repr x) = if x.nat_mod modulus < half_modulus then x.nat_mod modulus else x.nat_mod modulus - modulus := sorry' lemma mod_eq_of_repr_eq {x y} (h : repr x = repr y) : x.nat_mod modulus = y.nat_mod modulus := let t := congr_arg unsigned h in by simp at t; simp [t] theorem unsigned_range (i) : unsigned i < modulus := sorry' theorem unsigned_range_2 (i) : unsigned i ≤ max_unsigned := sorry' theorem min_signed_range (i) : min_signed ≤ signed i := sorry' theorem max_signed_range (i) : signed i ≤ max_signed := sorry' @[simp] theorem repr_unsigned (i) : repr (unsigned i) = i := sorry' @[simp] theorem repr_signed (i) : repr (signed i) = i := sorry' theorem unsigned_repr {z} (h : z ≤ max_unsigned) : unsigned (repr z) = z := sorry' theorem signed_repr {z} : min_signed ≤ z → z ≤ max_signed → signed (repr z) = z := sorry' theorem signed_eq_unsigned (x) : unsigned x ≤ max_signed → signed x = unsigned x := sorry' theorem signed_positive (x) : 0 ≤ signed x ↔ unsigned x ≤ max_signed := sorry' /- ** Properties of zero, one, minus one -/ theorem unsigned_zero : unsigned 0 = 0 := sorry' theorem unsigned_mone : unsigned (-1) = modulus - 1 := sorry' theorem signed_zero : signed 0 = 0 := sorry' theorem signed_mone : signed (-1) = -1 := sorry' theorem unsigned_repr_wordsize : unsigned iwordsize = wordsize := sorry' /- ** Properties of equality -/ theorem eq_signed (x y) : x = y ↔ signed x = signed y := sorry' theorem eq_unsigned (x y) : x = y ↔ unsigned x = unsigned y := sorry' /- ** Properties of addition -/ theorem add_unsigned (x y) : x + y = repr (unsigned x + unsigned y) := sorry' theorem add_signed (x y) : x + y = repr (signed x + signed y) := sorry' theorem add_comm (x y : word) : x + y = y + x := sorry' theorem add_zero (x : word) : x + 0 = x := sorry' theorem add_assoc (x y z : word) : (x + y) + z = x + (y + z) := sorry' theorem add_left_neg (x : word) : -x + x = 0 := sorry' theorem unsigned_add_carry (x y) : unsigned (x + y) = unsigned x + unsigned y - unsigned (add_carry x y 0) * modulus := sorry' theorem unsigned_add_either (x y) : unsigned (x + y) = unsigned x + unsigned y ∨ (unsigned (x + y) : ℤ) = unsigned x + unsigned y - modulus := sorry' /- ** Properties of negation -/ theorem neg_repr (z) : -(repr z) = repr (-z) := sorry' /- ** Properties of multiplication -/ theorem mul_comm (x y : word) : x * y = y * x := sorry' theorem mul_one (x : word) : x * 1 = x := sorry' theorem mul_assoc (x y z : word) : (x * y) * z = x * (y * z) := sorry' theorem right_distrib (x y z : word) : (x + y) * z = x * z + y * z := sorry' theorem mul_signed (x y) : x * y = repr (signed x * signed y) := sorry' instance comm_ring : comm_ring word := { add := (+), add_assoc := add_assoc, zero := 0, zero_add := λx, by rw [add_comm, add_zero], add_zero := add_zero, neg := has_neg.neg, add_left_neg := add_left_neg, add_comm := add_comm, mul := (*), mul_assoc := mul_assoc, one := 1, one_mul := λx, by rw [mul_comm, mul_one], mul_one := mul_one, left_distrib := λx y z, by rw [mul_comm, right_distrib, mul_comm y x, mul_comm z x]; refl, right_distrib := right_distrib, mul_comm := mul_comm } /- ** Properties of subtraction -/ theorem sub_unsigned (x y) : x - y = repr (unsigned x - unsigned y) := sorry' theorem sub_signed (x y) : x - y = repr (signed x - signed y) := sorry' theorem unsigned_sub_borrow (x y) : unsigned (x - y) = unsigned x - unsigned y + unsigned (sub_borrow x y 0) * modulus := sorry' /- ** Properties of division and modulus -/ lemma divu_add_modu (x y) : y ≠ 0 → divu x y * y + modu x y = x := sorry' theorem modu_divu (x y) : y ≠ 0 → modu x y = x - divu x y * y := sorry' lemma mods_divs_Euclid (x y : word) : x / y * y + x % y = x := sorry' theorem mods_divs (x y : word) : x % y = x - x / y * y := sorry' theorem divu_one (x) : divu x 1 = x := sorry' theorem modu_one (x) : modu x 1 = 0 := sorry' theorem divs_mone (x : word) : x / (-1) = -x := sorry' theorem mods_mone (x : word) : x % (-1) = 0 := sorry' theorem divmodu2_divu_modu (n d) : d ≠ 0 → divmodu2 0 n d = some (divu n d, modu n d) := sorry' lemma unsigned_signed (n) : (unsigned n : ℤ) = if n < 0 then signed n + modulus else signed n := sorry' theorem divmods2_divs_mods (n d) : d ≠ 0 → n ≠ repr min_signed ∨ d ≠ -1 → divmods2 (if n < 0 then -1 else 0) n d = some (divs n d, mods n d) := sorry' /- ** Bit-level properties -/ /- ** Bit-level reasoning over type [int] -/ def test_bit (x : word) (i : ℕ) : bool := int.test_bit (unsigned x) i lemma test_bit_repr (x i) : i < wordsize → test_bit (repr x) i = int.test_bit x i := sorry' lemma same_bits_eq (x y) : (∀ i < wordsize, test_bit x i = test_bit y i) → x = y := sorry' lemma bits_above (x i) : i ≥ wordsize → test_bit x i = ff := sorry' lemma bits_zero (i) : test_bit 0 i = ff := sorry' theorem bits_one (n) : test_bit 1 n = to_bool (n = 0) := sorry' lemma bits_mone (i) : i < wordsize → test_bit (-1) i := sorry' lemma sign_bit_of_unsigned (x) : test_bit x (wordsize - 1) = to_bool (unsigned x ≥ half_modulus) := sorry' lemma bits_signed (x i) : int.test_bit (signed x) i = test_bit x (if i < wordsize then i else wordsize - 1) := sorry' lemma bits_le (x y) : (∀ i < wordsize, test_bit x i → test_bit y i) → unsigned x ≤ unsigned y := sorry' /- ** Properties of bitwise and, or, xor -/ @[simp] lemma bits_and (x y i) : i < wordsize → test_bit (word.and x y) i = test_bit x i && test_bit y i := sorry' @[simp] lemma bits_or (x y i) : i < wordsize → test_bit (word.or x y) i = test_bit x i || test_bit y i := sorry' @[simp] lemma bits_xor (x y i) : i < wordsize → test_bit (word.xor x y) i = bxor (test_bit x i) (test_bit y i) := sorry' @[simp] lemma bits_not (x i) : i < wordsize → test_bit (word.not x) i = bnot (test_bit x i) := sorry' theorem and_comm (x y) : word.and x y = word.and y x := sorry' theorem and_assoc (x y z) : word.and (word.and x y) z = word.and x (word.and y z) := sorry' @[simp] theorem and_zero (x) : word.and x 0 = 0 := sorry' @[simp] theorem zero_and (x) : word.and 0 x = 0 := sorry' @[simp] theorem and_mone (x) : word.and x (-1) = x := sorry' @[simp] theorem mone_and (x) : word.and (-1) x = x := sorry' @[simp] theorem and_self (x) : and x x = x := sorry' theorem or_comm (x y) : word.or x y = word.or y x := sorry' theorem or_assoc (x y z) : word.or (word.or x y) z = word.or x (word.or y z) := sorry' @[simp] theorem or_zero (x) : word.or x 0 = x := sorry' @[simp] theorem zero_or (x) : word.or 0 x = x := sorry' @[simp] theorem or_mone (x) : word.or x (-1) = -1 := sorry' @[simp] theorem or_self (x) : word.or x x = x := sorry' theorem and_or_left_distrib (x y z) : word.and x (word.or y z) = word.or (word.and x y) (word.and x z) := sorry' theorem and_or_right_distrib (x y z) : word.and (word.or x y) z = word.or (word.and x z) (word.and y z) := sorry' theorem or_and_left_distrib (x y z) : word.or x (word.and y z) = word.and (word.or x y) (word.or x z) := sorry' theorem or_and_right_distrib (x y z) : word.or (word.and x y) z = word.and (word.or x z) (word.or y z) := sorry' @[simp] theorem and_or_absorb (x y) : word.and x (word.or x y) = x := sorry' @[simp] theorem or_and_absorb (x y) : word.or x (word.and x y) = x := sorry' theorem xor_comm (x y) : word.xor x y = word.xor y x := sorry' theorem xor_assoc (x y z) : word.xor (word.xor x y) z = word.xor x (word.xor y z) := sorry' @[simp] theorem xor_zero (x) : word.xor x 0 = x := sorry' @[simp] theorem zero_xor (x) : word.xor 0 x = x := sorry' @[simp] theorem xor_self (x) : word.xor x x = 0 := sorry' @[simp] theorem xor_zero_one : word.xor 0 1 = 1 := zero_xor _ @[simp] theorem xor_one_one : word.xor 1 1 = 0 := xor_self _ theorem eq_of_xor_zero (x y) : word.xor x y = 0 → x = y := sorry' theorem and_xor_distrib (x y z) : word.and x (word.xor y z) = word.xor (word.and x y) (word.and x z) := sorry' theorem and_le (x y) : unsigned (word.and x y) ≤ unsigned x := sorry' theorem or_le (x y) : unsigned x ≤ unsigned (word.or x y) := sorry' /- Properties of bitwise complement.-/ theorem not_not (x) : word.not (word.not x) = x := sorry' theorem not_zero : word.not 0 = -1 := sorry' theorem not_mone : word.not (-1) = 0 := sorry' theorem not_or_and_not (x y) : word.not (word.or x y) = word.and (word.not x) (word.not y) := sorry' theorem not_and_or_not (x y) : word.not (word.and x y) = word.or (word.not x) (word.not y) := sorry' theorem and_not_self (x) : word.and x (word.not x) = 0 := sorry' theorem or_not_self (x) : word.or x (word.not x) = -1 := sorry' theorem xor_not_self (x) : word.xor x (word.not x) = -1 := sorry' lemma unsigned_not (x) : unsigned (word.not x) = max_unsigned - unsigned x := sorry' theorem not_neg (x) : word.not x = -x - 1 := sorry' theorem neg_not (x) : -x = word.not x + 1 := sorry' theorem sub_add_not (x y) : x - y = x + word.not y + 1 := sorry' theorem sub_add_not_3 (x y b) : b = 0 ∨ b = 1 → x - y - b = x + word.not y + word.xor b 1 := sorry' theorem sub_borrow_add_carry (x y b) : b = 0 ∨ b = 1 → sub_borrow x y b = word.xor (add_carry x (word.not y) (word.xor b 1)) 1 := sorry' /- Connections between [add] and bitwise logical operations. -/ lemma Z_add_is_or (i x y) : (∀ j ≤ i, int.test_bit x j && int.test_bit y j = ff) → int.test_bit (x + y) i = int.test_bit x i || int.test_bit y i := sorry' theorem add_is_or (x y) : word.and x y = 0 → x + y = word.or x y := sorry' theorem xor_is_or (x y) : word.and x y = 0 → word.xor x y = word.or x y := sorry' theorem add_is_xor (x y) : word.and x y = 0 → x + y = word.xor x y := sorry' theorem add_and (x y z) : word.and y z = 0 → word.and x y + word.and x z = word.and x (word.or y z) := sorry' /- ** Properties of shifts -/ @[simp] lemma bits_shl (x y i) : i < wordsize → test_bit (shl x y) i = if i < unsigned y then ff else test_bit x (i - unsigned y) := sorry' @[simp] lemma bits_shru (x y i) : i < wordsize → test_bit (shru x y) i = if i + unsigned y < wordsize then test_bit x (i + unsigned y) else ff := sorry' @[simp] lemma bits_shr (x y i) : i < wordsize → test_bit (shr x y) i = test_bit x (if i + unsigned y < wordsize then i + unsigned y else wordsize - 1) := sorry' @[simp] theorem shl_zero (x) : shl x 0 = x := sorry' lemma bitwise_binop_shl {f : word → word → word} {f' : bool → bool → bool} : (∀ x y i, i < wordsize → test_bit (f x y) i = f' (test_bit x i) (test_bit y i)) → f' ff ff = ff → ∀ x y n, f (shl x n) (shl y n) = shl (f x y) n := sorry' theorem and_shl : ∀ x y n, word.and (shl x n) (shl y n) = shl (word.and x y) n := bitwise_binop_shl bits_and rfl theorem or_shl : ∀ x y n, word.or (shl x n) (shl y n) = shl (word.or x y) n := bitwise_binop_shl bits_or rfl theorem xor_shl : ∀ x y n, word.xor (shl x n) (shl y n) = shl (word.xor x y) n := bitwise_binop_shl bits_xor rfl lemma ltu_inv (x y) : ltu x y → unsigned x < unsigned y := id lemma ltu_iwordsize_inv (x) : ltu x iwordsize → unsigned x < wordsize := sorry' theorem shl_shl (x y z) : ltu y iwordsize → ltu z iwordsize → ltu (y + z) iwordsize → shl (shl x y) z = shl x (y + z) := sorry' theorem shru_zero (x) : shru x 0 = x := sorry' lemma bitwise_binop_shru {f : word → word → word} {f' : bool → bool → bool} : (∀ x y i, i < wordsize → test_bit (f x y) i = f' (test_bit x i) (test_bit y i)) → f' ff ff = ff → ∀ x y n, f (shru x n) (shru y n) = shru (f x y) n := sorry' theorem and_shru : ∀ x y n, word.and (shru x n) (shru y n) = shru (word.and x y) n := bitwise_binop_shru bits_and rfl theorem or_shru : ∀ x y n, word.or (shru x n) (shru y n) = shru (word.or x y) n := bitwise_binop_shru bits_or rfl theorem xor_shru : ∀ x y n, word.xor (shru x n) (shru y n) = shru (word.xor x y) n := bitwise_binop_shru bits_xor rfl theorem shru_shru (x y z) : ltu y iwordsize → ltu z iwordsize → ltu (y + z) iwordsize → shru (shru x y) z = shru x (y + z) := sorry' theorem shr_zero (x) : shr x 0 = x := sorry' lemma bitwise_binop_shr {f : word → word → word} {f' : bool → bool → bool} : (∀ x y i, i < wordsize → test_bit (f x y) i = f' (test_bit x i) (test_bit y i)) → ∀ x y n, f (shr x n) (shr y n) = shr (f x y) n := sorry' theorem and_shr : ∀ x y n, word.and (shr x n) (shr y n) = shr (word.and x y) n := bitwise_binop_shr bits_and theorem or_shr : ∀ x y n, word.or (shr x n) (shr y n) = shr (word.or x y) n := bitwise_binop_shr bits_or theorem xor_shr : ∀ x y n, word.xor (shr x n) (shr y n) = shr (word.xor x y) n := bitwise_binop_shr bits_xor theorem shr_shr (x y z) : ltu y iwordsize → ltu z iwordsize → ltu (y + z) iwordsize → shr (shr x y) z = shr x (y + z) := sorry' theorem and_shr_shru (x y z) : word.and (shr x z) (shru y z) = shru (word.and x y) z := sorry' theorem shr_and_shru_and (x y z) : shru (shl z y) y = z → word.and (shr x y) z = word.and (shru x y) z := sorry' theorem shru_lt_zero (x) : shru x (repr (wordsize - 1)) = to_bool (x < 0) := sorry' theorem shr_lt_zero (x) : shr x (repr (wordsize - 1)) = -to_bool (x < 0) := sorry' /- ** Properties of rotations -/ @[simp] lemma bits_rol (x y i) : i < wordsize → test_bit (rol x y) i = test_bit x ((i - unsigned y) % wordsize) := sorry' @[simp] lemma bits_ror (x y i) : i < wordsize → test_bit (ror x y) i = test_bit x ((i + unsigned y) % wordsize) := sorry' theorem shl_rolm (x n) : ltu n iwordsize → shl x n = rolm x n (shl (-1) n) := sorry' theorem shru_rolm (x n) : ltu n iwordsize → shru x n = rolm x (iwordsize - n) (shru (-1) n) := sorry' theorem rol_zero (x) : rol x 0 = x := sorry' lemma bitwise_binop_rol {f : word → word → word} {f' : bool → bool → bool} : (∀ x y i, i < wordsize → test_bit (f x y) i = f' (test_bit x i) (test_bit y i)) → ∀ x y n, rol (f x y) n = f (rol x n) (rol y n) := sorry' theorem rol_and : ∀ x y n, rol (word.and x y) n = word.and (rol x n) (rol y n) := bitwise_binop_rol bits_and theorem rol_or : ∀ x y n, rol (word.or x y) n = word.or (rol x n) (rol y n) := bitwise_binop_rol bits_or theorem rol_xor : ∀ x y n, rol (word.xor x y) n = word.xor (rol x n) (rol y n) := bitwise_binop_rol bits_xor theorem rol_rol (x n m) : wordsize ∣ modulus → rol (rol x n) m = rol x (modu (n + m) iwordsize) := sorry' theorem rolm_zero (x m) : rolm x 0 m = word.and x m := sorry' theorem rolm_rolm (x n₁ m₁ n₂ m₂) : wordsize ∣ modulus → rolm (rolm x n₁ m₁) n₂ m₂ = rolm x (modu (n₁ + n₂) iwordsize) (word.and (rol m₁ n₂) m₂) := sorry' theorem or_rolm (x n m₁ m₂) : word.or (rolm x n m₁) (rolm x n m₂) = rolm x n (word.or m₁ m₂) := sorry' theorem ror_rol (x y) : ltu y iwordsize → ror x y = rol x (iwordsize - y) := sorry' theorem ror_rol_neg (x y) : wordsize ∣ modulus → ror x y = rol x (-y) := sorry' theorem or_ror (x y z) : ltu y iwordsize → ltu z iwordsize → y + z = iwordsize → ror x z = word.or (shl x y) (shru x z) := sorry' /- ** Properties of [Z_one_bits] and [is_power2]. -/ lemma is_power2_rng (n logn) : is_power2 n = some logn → unsigned logn < wordsize := sorry' theorem is_power2_range (n logn) : is_power2 n = some logn → ltu logn iwordsize := sorry' lemma is_power2_correct (n logn) : is_power2 n = some logn → unsigned n = 2^unsigned logn := sorry' theorem two_p_range (n) : n < wordsize → 2^n ≤ max_unsigned := sorry' lemma is_power2_two_p (n) : n < wordsize → is_power2 (repr (2^n)) = some (repr n) := sorry' /- ** Relation between bitwise operations and multiplications / divisions by powers of 2 -/ /- Left shifts and multiplications by powers of 2. -/ lemma Zshiftl_mul_two_p (x) (n : ℕ) : int.shiftl x n = x * 2^n := sorry' lemma shl_mul_two_p (x y) : shl x y = x * repr (2 ^ unsigned y) := sorry' theorem shl_mul (x y) : shl x y = x * shl 1 y := sorry' theorem mul_pow2 (x n logn) : is_power2 n = some logn → x * n = shl x logn := sorry' theorem shifted_or_is_add (x y n) : n < wordsize → unsigned y < 2^n → word.or (shl x (repr n)) y = repr (unsigned x * 2^n + unsigned y) := sorry' /- Unsigned right shifts and unsigned divisions by powers of 2. -/ lemma shru_div_two_p (x y) : shru x y = repr (unsigned x / 2^unsigned y) := sorry' theorem divu_pow2 (x n logn) : is_power2 n = some logn → divu x n = shru x logn := sorry' /- Signed right shifts and signed divisions by powers of 2. -/ lemma shr_div_two_p (x y) : shr x y = repr (signed x / 2^unsigned y) := sorry' theorem divs_pow2 (x n logn) : is_power2 n = some logn → x / n = shrx x logn := sorry' /- Unsigned modulus over [2^n] is masking with [2^n-1]. -/ theorem modu_and (x n logn) : is_power2 n = some logn → modu x n = word.and x (n - 1) := sorry' /- ** Properties of [shrx] (signed division by a power of 2) -/ lemma int.quot_div (x y) : y > 0 → int.quot x y = if x < 0 then (x + y - 1) / y else x / y := sorry' theorem shrx_shr (x y) : ltu y (repr (wordsize - 1)) → shrx x y = shr (if x < 0 then x + (shl 1 y - 1) else x) y := sorry' theorem shrx_shr_2 (x y) : ltu y (repr (wordsize - 1)) → shrx x y = shr (x + shru (shr x (repr (wordsize - 1))) (iwordsize - y)) y := sorry' lemma Zdiv_shift (x y) : y > 0 → (x + (y - 1)) / y = x / y + if x % y = 0 then 0 else 1 := sorry' theorem shrx_carry (x y) : ltu y (repr (wordsize - 1)) → shrx x y = shr x y + shr_carry x y := sorry' /- Connections between [shr] and [shru]. -/ lemma shr_shru_positive (x y) : signed x ≥ 0 → shr x y = shru x y := sorry' lemma and_positive (x y) : signed y ≥ 0 → signed (word.and x y) ≥ 0 := sorry' theorem shr_and_is_shru_and (x y z) : y ≥ 0 → shr (word.and x y) z = shru (word.and x y) z := sorry' @[simp] lemma bits_zero_ext (n x i) : test_bit (zero_ext n x) i = to_bool (i < n) && test_bit x i := sorry' @[simp] lemma bits_sign_ext (n x i) : i < wordsize → test_bit (sign_ext n x) i = test_bit x (if i < n then i else n - 1) := sorry' theorem zero_ext_above (n x) : n ≥ wordsize → zero_ext n x = x := sorry' theorem sign_ext_above (n : ℕ+) (x) : n.1 ≥ wordsize → sign_ext n x = x := sorry' theorem zero_ext_and (n x) : zero_ext n x = word.and x (repr (2^n - 1)) := sorry' theorem zero_ext_mod (n x) : n < wordsize → unsigned (zero_ext n x) = unsigned x % 2^n := sorry' theorem zero_ext_widen (x n n') : n ≤ n' → zero_ext n' (zero_ext n x) = zero_ext n x := sorry' theorem sign_ext_widen (x) (n n' : ℕ+) : n.1 ≤ n'.1 → sign_ext n' (sign_ext n x) = sign_ext n x := sorry' theorem sign_zero_ext_widen (x n) (n' : ℕ+) : n < n'.1 → sign_ext n' (zero_ext n x) = zero_ext n x := sorry' theorem zero_ext_narrow (x n n') : n ≤ n' → zero_ext n (zero_ext n' x) = zero_ext n x := sorry' theorem sign_ext_narrow (x) (n n' : ℕ+) : n.1 ≤ n'.1 → sign_ext n (sign_ext n' x) = sign_ext n x := sorry' theorem zero_sign_ext_narrow (x n) (n' : ℕ+) : n ≤ n'.1 → zero_ext n (sign_ext n' x) = zero_ext n x := sorry' theorem zero_ext_self (n x) : zero_ext n (zero_ext n x) = zero_ext n x := sorry' theorem sign_ext_self (n x) : sign_ext n (sign_ext n x) = sign_ext n x := sorry' theorem sign_ext_zero_ext (x n) : sign_ext n (zero_ext n x) = sign_ext n x := sorry' theorem zero_ext_sign_ext (x) (n : ℕ+) : zero_ext n (sign_ext n x) = zero_ext n x := sorry' theorem sign_ext_equal_if_zero_equal (n : ℕ+) (x y) : zero_ext n x = zero_ext n y → sign_ext n x = sign_ext n y := sorry' theorem zero_ext_shru_shl (n x) : 0 < n → n < wordsize → let y := repr (wordsize - n) in zero_ext n x = shru (shl x y) y := sorry' theorem sign_ext_shr_shl (n : ℕ+) (x) : n.1 < wordsize → let y := repr (wordsize - n) in sign_ext n x = shr (shl x y) y := sorry' /- [zero_ext n x] is the unique integer congruent to [x] modulo [2^n] in the range [0...2^n-1]. -/ lemma zero_ext_range (n x) : n < wordsize → unsigned (zero_ext n x) < 2^n := sorry' lemma eqmod_zero_ext (n x) : n < wordsize → unsigned (zero_ext n x) = unsigned x % 2^n := sorry' /- [sign_ext n x] is the unique integer congruent to [x] modulo [2^n] in the range [-2^(n-1)...2^(n-1) - 1]. -/ lemma sign_ext_range (x) (n : ℕ+) : n.1 < wordsize → -(2^(n-1) : ℤ) ≤ signed (sign_ext n x) ∧ signed (sign_ext n x) < 2^(n-1) := sorry' lemma eqmod_sign_ext' (x) (n : ℕ+) : n.1 < wordsize → unsigned (sign_ext n x) % 2^n = unsigned x % 2^n := sorry' lemma eqmod_sign_ext (x) (n : ℕ+) : n.1 < wordsize → signed (sign_ext n x) % 2^n = unsigned x % 2^n := sorry' /- ** Properties of [one_bits] (decomposition in sum of powers of two) -/ theorem one_bits_range (x i) : i ∈ one_bits x → ltu i iwordsize := sorry' def int_of_one_bits : list word → word | [] := 0 | (a :: l) := shl 1 a + int_of_one_bits l theorem one_bits_decomp (x) : int_of_one_bits (one_bits x) = x := sorry' /- ** Properties of comparisons -/ theorem negate_cmp (c x y) : cmp (negate_comparison c) x y = bnot (cmp c x y) := sorry' theorem negate_cmpu (c x y) : cmpu (negate_comparison c) x y = bnot (cmpu c x y) := sorry' theorem swap_cmp (c x y) : cmp (swap_comparison c) x y = cmp c y x := sorry' theorem swap_cmpu (c x y) : cmpu (swap_comparison c) x y = cmpu c y x := sorry' lemma translate_ltu (x y d) : unsigned x + unsigned d ≤ max_unsigned → unsigned y + unsigned d ≤ max_unsigned → ltu (x + d) (y + d) ↔ ltu x y := sorry' theorem translate_cmpu (c x y d) : unsigned x + unsigned d ≤ max_unsigned → unsigned y + unsigned d ≤ max_unsigned → cmpu c (x + d) (y + d) = cmpu c x y := sorry' lemma translate_lt (x y d) : in_srange (signed x + signed d) → in_srange (signed y + signed d) → x + d < y + d ↔ x < y := sorry' theorem translate_cmp (c x y d) : in_srange (signed x + signed d) → in_srange (signed y + signed d) → cmp c (x + d) (y + d) = cmp c x y := sorry' theorem notbool_isfalse_istrue (x) : is_false x → is_true (notbool x) := sorry' theorem notbool_istrue_isfalse (x) : is_true x → is_false (notbool x) := sorry' theorem ltu_range_test (x y) : ltu x y → unsigned y ≤ max_signed → 0 ≤ signed x ∧ signed x < unsigned y := sorry' theorem lt_sub_overflow (x y) : word.xor (sub_overflow x y 0) (negative (x - y)) = to_bool (x < y) := sorry' lemma signed_eq {x y} : x = y ↔ signed x = signed y := sorry' lemma unsigned_eq {x y} : x = y ↔ unsigned x = unsigned y := sorry' lemma leu_iff_ltu_or_eq (x y : word) : leu x y ↔ ltu x y ∨ x = y := iff.trans (@le_iff_lt_or_eq ℕ _ _ _) (or_congr iff.rfl unsigned_eq.symm) lemma le_iff_lt_or_eq (x y : word) : x ≤ y ↔ x < y ∨ x = y := iff.trans (@le_iff_lt_or_eq ℤ _ _ _) (or_congr iff.rfl signed_eq.symm) instance decidable_linear_order : decidable_linear_order word := { le := (≤), le_refl := λx, @le_refl ℤ _ _, le_trans := λx y z, @le_trans ℤ _ _ _ _, le_antisymm := λx y h1 h2, signed_eq.2 $ le_antisymm h1 h2, lt := (<), le_iff_lt_or_eq := le_iff_lt_or_eq, lt_irrefl := λx, @lt_irrefl ℤ _ _, le_total := λx y, @le_total ℤ _ _ _, decidable_lt := by apply_instance, decidable_le := by apply_instance, decidable_eq := by apply_instance } lemma ltu_not (x y) : ltu y x ↔ ¬ltu x y ∧ x ≠ y := sorry' /- Non-overlapping test -/ def no_overlap (ofs1 : word) (sz1 : ℕ) (ofs2 : word) (sz2 : ℕ) : bool := let x1 := unsigned ofs1, x2 := unsigned ofs2 in x1 + sz1 < modulus ∧ x2 + sz2 < modulus ∧ (x1 + sz1 ≤ x2 ∨ x2 + sz2 ≤ x1) instance (ofs1 sz1 ofs2 sz2) : decidable (no_overlap ofs1 sz1 ofs2 sz2) := by apply_instance lemma no_overlap_sound (ofs1 sz1 ofs2 sz2 base) : sz1 > 0 → sz2 > 0 → no_overlap ofs1 sz1 ofs2 sz2 → unsigned (base + ofs1) + sz1 ≤ unsigned (base + ofs2) ∨ unsigned (base + ofs2) + sz2 ≤ unsigned (base + ofs1) := sorry' /- Size of integers, in bits. -/ def size (x : word) : ℕ := nat.size (unsigned x) set_option type_context.unfold_lemmas true theorem size_zero : size 0 = 0 := congr_arg nat.size unsigned_zero theorem test_bit_size (x) : x > 0 → test_bit x (size x - 1) := sorry' theorem test_bit_size_lt (x i) : test_bit x i → i < size x := sorry' theorem size_le_wordsize (x) : size x ≤ wordsize := sorry' theorem bits_size_le (x n) (h : ∀ i < wordsize, test_bit x i → i < n) : size x ≤ n := sorry' theorem bits_size_eq (x n) : test_bit x (n - 1) → (∀ i < wordsize, test_bit x i → i < n) → size x = n := sorry' theorem lt_pow_size (x) : unsigned x < 2^size x := nat.lt_pow_size _ theorem size_le_of_lt_pow (x n) : unsigned x < 2^n → size x ≤ n := nat.size_le_of_lt_pow theorem size_and (a b) : size (word.and a b) ≤ min (size a) (size b) := sorry' theorem and_interval (a b) : unsigned (word.and a b) < 2^ min (size a) (size b) := sorry' theorem size_or (a b) : size (word.or a b) = max (size a) (size b) := sorry' theorem or_interval (a b) : unsigned (word.or a b) < 2^ max (size a) (size b) := sorry' theorem size_xor (a b) : size (word.xor a b) ≤ max (size a) (size b) := sorry' theorem xor_interval (a b) : unsigned (word.xor a b) < 2^ max (size a) (size b) := sorry' theorem wordsize_dvd_modulus (n) : wordsize = 2^n → wordsize ∣ modulus := sorry' @[simp] lemma length_words_of_int (n x) : (words_of_int n x).length = n := by revert x; induction n; simph [words_of_int] @[simp] lemma nat_of_words_of_int (n x) : nat_of_words (words_of_int n x) = x.nat_mod (2^(wordsize * n)) := sorry' lemma words_of_int_mod (n) {x y : ℤ} : x.nat_mod (2^(wordsize * n)) = y.nat_mod (2^(wordsize * n)) → words_of_int n x = words_of_int n y := sorry' lemma nat_of_words_append (l2 l1) : nat_of_words (l1 ++ l2) = nat_of_words l1 + nat_of_words l2 * 2^(wordsize * l1.length) := sorry' lemma nat_of_words_range (l) : nat_of_words l < 2^(wordsize * l.length) := sorry' lemma words_of_int_append {n2 x2 n1 x1} : x1 < 2^(wordsize * n1) → words_of_int (n1 + n2) (x1 + x2 * 2^(wordsize * n1)) = words_of_int n1 x1 ++ words_of_int n2 x2 := sorry' /- Theorems that depend on positive word size -/ parameter {wordsize_pos : wordsize > 0} theorem unsigned_one : unsigned 1 = 1 := sorry' theorem one_ne_zero : (1:word) ≠ 0 := sorry' theorem succ_leu_of_ltu {x y} (h : ltu x y) : leu (x + 1) y := begin change unsigned (repr (unsigned x + unsigned 1)) ≤ unsigned y, rw [unsigned_one, -int.coe_nat_add, word.unsigned_repr], exact h, exact nat.lt_of_lt_of_le h (unsigned_range_2 _), end theorem leu_pred_of_ltu {x y} (h : ltu x y) : leu x (y - 1) := begin change unsigned x ≤ unsigned (y - 1), rw [sub_unsigned, unsigned_one, -int.coe_nat_sub, unsigned_repr], exact nat.pred_le_pred h, exact le_trans (nat.sub_le _ _) (unsigned_range_2 _), exact lt_of_le_of_lt (nat.zero_le _) h end /- ** Properties of [modulus], [max_unsigned], etc. -/ theorem half_modulus_modulus : modulus = 2 * half_modulus := sorry' end def scoe {w w' : ℕ} (x : word w) : word w' := repr (signed x) def ucoe {w w' : ℕ} (x : word w) : word w' := repr (unsigned x) end word def uword (n) := word n namespace uword open word section parameter {w : ℕ+} local notation `uword` := uword w instance coe_uword_nat : has_coe uword ℕ := ⟨unsigned⟩ instance : has_zero uword := ⟨repr 0⟩ instance : has_one uword := ⟨repr 1⟩ instance eq_dec : decidable_eq uword := word.eq_dec instance : has_lt uword := ⟨ltu⟩ instance : has_le uword := ⟨leu⟩ instance : has_neg uword := ⟨word.neg⟩ instance : has_add uword := ⟨word.add⟩ instance : has_mul uword := ⟨word.mul⟩ instance : has_div uword := ⟨divu⟩ instance : has_mod uword := ⟨modu⟩ instance decidable_lt : @decidable_rel uword (<) := by apply_instance instance decidable_le : @decidable_rel uword (≤) := by apply_instance instance comm_ring : comm_ring uword := word.comm_ring instance decidable_linear_order : decidable_linear_order uword := { le := (≤), le_refl := λx, @le_refl ℕ _ _, le_trans := λx y z, @le_trans ℕ _ _ _ _, le_antisymm := λx y h1 h2, unsigned_eq.2 $ le_antisymm h1 h2, lt := (<), le_iff_lt_or_eq := leu_iff_ltu_or_eq, lt_irrefl := λx, @lt_irrefl ℕ _ _, le_total := λx y, @le_total ℕ _ _ _, decidable_lt := by apply_instance, decidable_le := by apply_instance, decidable_eq := by apply_instance } theorem succ_le_of_lt {x y : uword} : x < y → x + 1 ≤ y := word.succ_leu_of_ltu theorem le_pred_of_lt {x y : uword} : x < y → x ≤ y - 1 := word.leu_pred_of_ltu theorem zero_le (x : uword) : 0 ≤ x := show unsigned 0 ≤ _, by rw unsigned_zero; apply nat.zero_le end end uword
State Before: K : Type u L : Type v M : Type w inst✝² : Field K inst✝¹ : Field L inst✝ : Field M g : L →+* M f : K →+* L ⊢ Subfield.map g (fieldRange f) = fieldRange (comp g f) State After: no goals Tactic: simpa only [fieldRange_eq_map] using (⊤ : Subfield K).map_map g f
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov, Patrick Massot -/ import data.set.intervals.basic import data.equiv.mul_add import algebra.pointwise /-! # (Pre)images of intervals In this file we prove a bunch of trivial lemmas like “if we add `a` to all points of `[b, c]`, then we get `[a + b, a + c]`”. For the functions `x ↦ x ± a`, `x ↦ a ± x`, and `x ↦ -x` we prove lemmas about preimages and images of all intervals. We also prove a few lemmas about images under `x ↦ a * x`, `x ↦ x * a` and `x ↦ x⁻¹`. -/ universe u open_locale pointwise namespace set section has_exists_add_of_le /-! The lemmas in this section state that addition maps intervals bijectively. The typeclass `has_exists_add_of_le` is defined specifically to make them work when combined with `ordered_cancel_add_comm_monoid`; the lemmas below therefore apply to all `ordered_add_comm_group`, but also to `ℕ` and `ℝ≥0`, which are not groups. TODO : move as much as possible in this file to the setting of this weaker typeclass. -/ variables {α : Type u} [ordered_cancel_add_comm_monoid α] [has_exists_add_of_le α] (a b d : α) lemma Icc_add_bij : bij_on (+d) (Icc a b) (Icc (a + d) (b + d)) := begin refine ⟨λ _ h, ⟨add_le_add_right h.1 _, add_le_add_right h.2 _⟩, λ _ _ _ _ h, add_right_cancel h, λ _ h, _⟩, obtain ⟨c, rfl⟩ := exists_add_of_le h.1, rw [mem_Icc, add_right_comm, add_le_add_iff_right, add_le_add_iff_right] at h, exact ⟨a + c, h, by rw add_right_comm⟩, end lemma Ioo_add_bij : bij_on (+d) (Ioo a b) (Ioo (a + d) (b + d)) := begin refine ⟨λ _ h, ⟨add_lt_add_right h.1 _, add_lt_add_right h.2 _⟩, λ _ _ _ _ h, add_right_cancel h, λ _ h, _⟩, obtain ⟨c, rfl⟩ := exists_add_of_le h.1.le, rw [mem_Ioo, add_right_comm, add_lt_add_iff_right, add_lt_add_iff_right] at h, exact ⟨a + c, h, by rw add_right_comm⟩, end lemma Ioc_add_bij : bij_on (+d) (Ioc a b) (Ioc (a + d) (b + d)) := begin refine ⟨λ _ h, ⟨add_lt_add_right h.1 _, add_le_add_right h.2 _⟩, λ _ _ _ _ h, add_right_cancel h, λ _ h, _⟩, obtain ⟨c, rfl⟩ := exists_add_of_le h.1.le, rw [mem_Ioc, add_right_comm, add_lt_add_iff_right, add_le_add_iff_right] at h, exact ⟨a + c, h, by rw add_right_comm⟩, end lemma Ico_add_bij : bij_on (+d) (Ico a b) (Ico (a + d) (b + d)) := begin refine ⟨λ _ h, ⟨add_le_add_right h.1 _, add_lt_add_right h.2 _⟩, λ _ _ _ _ h, add_right_cancel h, λ _ h, _⟩, obtain ⟨c, rfl⟩ := exists_add_of_le h.1, rw [mem_Ico, add_right_comm, add_le_add_iff_right, add_lt_add_iff_right] at h, exact ⟨a + c, h, by rw add_right_comm⟩, end lemma Ici_add_bij : bij_on (+d) (Ici a) (Ici (a + d)) := begin refine ⟨λ x h, add_le_add_right (mem_Ici.mp h) _, λ _ _ _ _ h, add_right_cancel h, λ _ h, _⟩, obtain ⟨c, rfl⟩ := exists_add_of_le (mem_Ici.mp h), rw [mem_Ici, add_right_comm, add_le_add_iff_right] at h, exact ⟨a + c, h, by rw add_right_comm⟩, end lemma Ioi_add_bij : bij_on (+d) (Ioi a) (Ioi (a + d)) := begin refine ⟨λ x h, add_lt_add_right (mem_Ioi.mp h) _, λ _ _ _ _ h, add_right_cancel h, λ _ h, _⟩, obtain ⟨c, rfl⟩ := exists_add_of_le (mem_Ioi.mp h).le, rw [mem_Ioi, add_right_comm, add_lt_add_iff_right] at h, exact ⟨a + c, h, by rw add_right_comm⟩, end end has_exists_add_of_le section ordered_add_comm_group variables {G : Type u} [ordered_add_comm_group G] (a b c : G) /-! ### Preimages under `x ↦ a + x` -/ @[simp] lemma preimage_const_add_Ici : (λ x, a + x) ⁻¹' (Ici b) = Ici (b - a) := ext $ λ x, sub_le_iff_le_add'.symm @[simp] lemma preimage_const_add_Ioi : (λ x, a + x) ⁻¹' (Ioi b) = Ioi (b - a) := ext $ λ x, sub_lt_iff_lt_add'.symm @[simp] lemma preimage_const_add_Iic : (λ x, a + x) ⁻¹' (Iic b) = Iic (b - a) := ext $ λ x, le_sub_iff_add_le'.symm @[simp] lemma preimage_const_add_Iio : (λ x, a + x) ⁻¹' (Iio b) = Iio (b - a) := ext $ λ x, lt_sub_iff_add_lt'.symm @[simp] lemma preimage_const_add_Icc : (λ x, a + x) ⁻¹' (Icc b c) = Icc (b - a) (c - a) := by simp [← Ici_inter_Iic] @[simp] lemma preimage_const_add_Ico : (λ x, a + x) ⁻¹' (Ico b c) = Ico (b - a) (c - a) := by simp [← Ici_inter_Iio] @[simp] lemma preimage_const_add_Ioc : (λ x, a + x) ⁻¹' (Ioc b c) = Ioc (b - a) (c - a) := by simp [← Ioi_inter_Iic] @[simp] lemma preimage_const_add_Ioo : (λ x, a + x) ⁻¹' (Ioo b c) = Ioo (b - a) (c - a) := by simp [← Ioi_inter_Iio] /-! ### Preimages under `x ↦ x + a` -/ @[simp] lemma preimage_add_const_Ici : (λ x, x + a) ⁻¹' (Ici b) = Ici (b - a) := ext $ λ x, sub_le_iff_le_add.symm @[simp] lemma preimage_add_const_Ioi : (λ x, x + a) ⁻¹' (Ioi b) = Ioi (b - a) := ext $ λ x, sub_lt_iff_lt_add.symm @[simp] lemma preimage_add_const_Iic : (λ x, x + a) ⁻¹' (Iic b) = Iic (b - a) := ext $ λ x, le_sub_iff_add_le.symm @[simp] lemma preimage_add_const_Iio : (λ x, x + a) ⁻¹' (Iio b) = Iio (b - a) := ext $ λ x, lt_sub_iff_add_lt.symm @[simp] lemma preimage_add_const_Icc : (λ x, x + a) ⁻¹' (Icc b c) = Icc (b - a) (c - a) := by simp [← Ici_inter_Iic] @[simp] lemma preimage_add_const_Ico : (λ x, x + a) ⁻¹' (Ico b c) = Ico (b - a) (c - a) := by simp [← Ici_inter_Iio] @[simp] lemma preimage_add_const_Ioc : (λ x, x + a) ⁻¹' (Ioc b c) = Ioc (b - a) (c - a) := by simp [← Ioi_inter_Iic] @[simp] lemma preimage_add_const_Ioo : (λ x, x + a) ⁻¹' (Ioo b c) = Ioo (b - a) (c - a) := by simp [← Ioi_inter_Iio] /-! ### Preimages under `x ↦ -x` -/ @[simp] lemma preimage_neg_Ici : - Ici a = Iic (-a) := ext $ λ x, le_neg @[simp] lemma preimage_neg_Iic : - Iic a = Ici (-a) := ext $ λ x, neg_le @[simp] lemma preimage_neg_Ioi : - Ioi a = Iio (-a) := ext $ λ x, lt_neg @[simp] lemma preimage_neg_Iio : - Iio a = Ioi (-a) := ext $ λ x, neg_lt @[simp] lemma preimage_neg_Icc : - Icc a b = Icc (-b) (-a) := by simp [← Ici_inter_Iic, inter_comm] @[simp] lemma preimage_neg_Ico : - Ico a b = Ioc (-b) (-a) := by simp [← Ici_inter_Iio, ← Ioi_inter_Iic, inter_comm] @[simp] lemma preimage_neg_Ioc : - Ioc a b = Ico (-b) (-a) := by simp [← Ioi_inter_Iic, ← Ici_inter_Iio, inter_comm] @[simp] lemma preimage_neg_Ioo : - Ioo a b = Ioo (-b) (-a) := by simp [← Ioi_inter_Iio, inter_comm] /-! ### Preimages under `x ↦ x - a` -/ @[simp] lemma preimage_sub_const_Ici : (λ x, x - a) ⁻¹' (Ici b) = Ici (b + a) := by simp [sub_eq_add_neg] @[simp] lemma preimage_sub_const_Ioi : (λ x, x - a) ⁻¹' (Ioi b) = Ioi (b + a) := by simp [sub_eq_add_neg] @[simp] lemma preimage_sub_const_Iic : (λ x, x - a) ⁻¹' (Iic b) = Iic (b + a) := by simp [sub_eq_add_neg] @[simp] lemma preimage_sub_const_Iio : (λ x, x - a) ⁻¹' (Iio b) = Iio (b + a) := by simp [sub_eq_add_neg] @[simp] lemma preimage_sub_const_Icc : (λ x, x - a) ⁻¹' (Icc b c) = Icc (b + a) (c + a) := by simp [sub_eq_add_neg] @[simp] lemma preimage_sub_const_Ico : (λ x, x - a) ⁻¹' (Ico b c) = Ico (b + a) (c + a) := by simp [sub_eq_add_neg] @[simp] lemma preimage_sub_const_Ioc : (λ x, x - a) ⁻¹' (Ioc b c) = Ioc (b + a) (c + a) := by simp [sub_eq_add_neg] @[simp] lemma preimage_sub_const_Ioo : (λ x, x - a) ⁻¹' (Ioo b c) = Ioo (b + a) (c + a) := by simp [sub_eq_add_neg] /-! ### Preimages under `x ↦ a - x` -/ @[simp] lemma preimage_const_sub_Ici : (λ x, a - x) ⁻¹' (Ici b) = Iic (a - b) := ext $ λ x, le_sub @[simp] lemma preimage_const_sub_Iic : (λ x, a - x) ⁻¹' (Iic b) = Ici (a - b) := ext $ λ x, sub_le @[simp] lemma preimage_const_sub_Ioi : (λ x, a - x) ⁻¹' (Ioi b) = Iio (a - b) := ext $ λ x, lt_sub @[simp] lemma preimage_const_sub_Iio : (λ x, a - x) ⁻¹' (Iio b) = Ioi (a - b) := ext $ λ x, sub_lt @[simp] lemma preimage_const_sub_Icc : (λ x, a - x) ⁻¹' (Icc b c) = Icc (a - c) (a - b) := by simp [← Ici_inter_Iic, inter_comm] @[simp] lemma preimage_const_sub_Ico : (λ x, a - x) ⁻¹' (Ico b c) = Ioc (a - c) (a - b) := by simp [← Ioi_inter_Iic, ← Ici_inter_Iio, inter_comm] @[simp] lemma preimage_const_sub_Ioc : (λ x, a - x) ⁻¹' (Ioc b c) = Ico (a - c) (a - b) := by simp [← Ioi_inter_Iic, ← Ici_inter_Iio, inter_comm] @[simp] lemma preimage_const_sub_Ioo : (λ x, a - x) ⁻¹' (Ioo b c) = Ioo (a - c) (a - b) := by simp [← Ioi_inter_Iio, inter_comm] /-! ### Images under `x ↦ a + x` -/ @[simp] lemma image_const_add_Ici : (λ x, a + x) '' Ici b = Ici (a + b) := by simp [add_comm] @[simp] lemma image_const_add_Iic : (λ x, a + x) '' Iic b = Iic (a + b) := by simp [add_comm] @[simp] lemma image_const_add_Iio : (λ x, a + x) '' Iio b = Iio (a + b) := by simp [add_comm] @[simp] lemma image_const_add_Ioi : (λ x, a + x) '' Ioi b = Ioi (a + b) := by simp [add_comm] @[simp] lemma image_const_add_Icc : (λ x, a + x) '' Icc b c = Icc (a + b) (a + c) := by simp [add_comm] @[simp] lemma image_const_add_Ico : (λ x, a + x) '' Ico b c = Ico (a + b) (a + c) := by simp [add_comm] @[simp] lemma image_const_add_Ioc : (λ x, a + x) '' Ioc b c = Ioc (a + b) (a + c) := by simp [add_comm] @[simp] lemma image_const_add_Ioo : (λ x, a + x) '' Ioo b c = Ioo (a + b) (a + c) := by simp [add_comm] /-! ### Images under `x ↦ x + a` -/ @[simp] lemma image_add_const_Ici : (λ x, x + a) '' Ici b = Ici (b + a) := by simp @[simp] lemma image_add_const_Iic : (λ x, x + a) '' Iic b = Iic (b + a) := by simp @[simp] lemma image_add_const_Iio : (λ x, x + a) '' Iio b = Iio (b + a) := by simp @[simp] lemma image_add_const_Ioi : (λ x, x + a) '' Ioi b = Ioi (b + a) := by simp @[simp] lemma image_add_const_Icc : (λ x, x + a) '' Icc b c = Icc (b + a) (c + a) := by simp @[simp] lemma image_add_const_Ico : (λ x, x + a) '' Ico b c = Ico (b + a) (c + a) := by simp @[simp] lemma image_add_const_Ioc : (λ x, x + a) '' Ioc b c = Ioc (b + a) (c + a) := by simp @[simp] lemma image_add_const_Ioo : (λ x, x + a) '' Ioo b c = Ioo (b + a) (c + a) := by simp /-! ### Images under `x ↦ -x` -/ lemma image_neg_Ici : has_neg.neg '' (Ici a) = Iic (-a) := by simp lemma image_neg_Iic : has_neg.neg '' (Iic a) = Ici (-a) := by simp lemma image_neg_Ioi : has_neg.neg '' (Ioi a) = Iio (-a) := by simp lemma image_neg_Iio : has_neg.neg '' (Iio a) = Ioi (-a) := by simp lemma image_neg_Icc : has_neg.neg '' (Icc a b) = Icc (-b) (-a) := by simp lemma image_neg_Ico : has_neg.neg '' (Ico a b) = Ioc (-b) (-a) := by simp lemma image_neg_Ioc : has_neg.neg '' (Ioc a b) = Ico (-b) (-a) := by simp lemma image_neg_Ioo : has_neg.neg '' (Ioo a b) = Ioo (-b) (-a) := by simp /-! ### Images under `x ↦ a - x` -/ @[simp] lemma image_const_sub_Ici : (λ x, a - x) '' Ici b = Iic (a - b) := by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)] @[simp] lemma image_const_sub_Iic : (λ x, a - x) '' Iic b = Ici (a - b) := by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)] @[simp] lemma image_const_sub_Ioi : (λ x, a - x) '' Ioi b = Iio (a - b) := by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)] @[simp] lemma image_const_sub_Iio : (λ x, a - x) '' Iio b = Ioi (a - b) := by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)] @[simp] lemma image_const_sub_Icc : (λ x, a - x) '' Icc b c = Icc (a - c) (a - b) := by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)] @[simp] lemma image_const_sub_Ico : (λ x, a - x) '' Ico b c = Ioc (a - c) (a - b) := by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)] @[simp] lemma image_const_sub_Ioc : (λ x, a - x) '' Ioc b c = Ico (a - c) (a - b) := by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)] @[simp] lemma image_const_sub_Ioo : (λ x, a - x) '' Ioo b c = Ioo (a - c) (a - b) := by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)] /-! ### Images under `x ↦ x - a` -/ @[simp] lemma image_sub_const_Ici : (λ x, x - a) '' Ici b = Ici (b - a) := by simp [sub_eq_neg_add] @[simp] lemma image_sub_const_Iic : (λ x, x - a) '' Iic b = Iic (b - a) := by simp [sub_eq_neg_add] @[simp] lemma image_sub_const_Ioi : (λ x, x - a) '' Ioi b = Ioi (b - a) := by simp [sub_eq_neg_add] @[simp] lemma image_sub_const_Iio : (λ x, x - a) '' Iio b = Iio (b - a) := by simp [sub_eq_neg_add] @[simp] lemma image_sub_const_Icc : (λ x, x - a) '' Icc b c = Icc (b - a) (c - a) := by simp [sub_eq_neg_add] @[simp] lemma image_sub_const_Ico : (λ x, x - a) '' Ico b c = Ico (b - a) (c - a) := by simp [sub_eq_neg_add] @[simp] lemma image_sub_const_Ioc : (λ x, x - a) '' Ioc b c = Ioc (b - a) (c - a) := by simp [sub_eq_neg_add] @[simp] lemma image_sub_const_Ioo : (λ x, x - a) '' Ioo b c = Ioo (b - a) (c - a) := by simp [sub_eq_neg_add] /-! ### Bijections -/ lemma Iic_add_bij : bij_on (+a) (Iic b) (Iic (b + a)) := begin refine ⟨λ x h, add_le_add_right (mem_Iic.mp h) _, λ _ _ _ _ h, add_right_cancel h, λ _ h, _⟩, simpa [add_comm a] using h, end lemma Iio_add_bij : bij_on (+a) (Iio b) (Iio (b + a)) := begin refine ⟨λ x h, add_lt_add_right (mem_Iio.mp h) _, λ _ _ _ _ h, add_right_cancel h, λ _ h, _⟩, simpa [add_comm a] using h, end end ordered_add_comm_group /-! ### Multiplication and inverse in a field -/ section linear_ordered_field variables {k : Type u} [linear_ordered_field k] @[simp] lemma preimage_mul_const_Iio (a : k) {c : k} (h : 0 < c) : (λ x, x * c) ⁻¹' (Iio a) = Iio (a / c) := ext $ λ x, (lt_div_iff h).symm @[simp] lemma preimage_mul_const_Ioi (a : k) {c : k} (h : 0 < c) : (λ x, x * c) ⁻¹' (Ioi a) = Ioi (a / c) := ext $ λ x, (div_lt_iff h).symm @[simp] lemma preimage_mul_const_Iic (a : k) {c : k} (h : 0 < c) : (λ x, x * c) ⁻¹' (Iic a) = Iic (a / c) := ext $ λ x, (le_div_iff h).symm @[simp] lemma preimage_mul_const_Ici (a : k) {c : k} (h : 0 < c) : (λ x, x * c) ⁻¹' (Ici a) = Ici (a / c) := ext $ λ x, (div_le_iff h).symm @[simp] lemma preimage_mul_const_Ioo (a b : k) {c : k} (h : 0 < c) : (λ x, x * c) ⁻¹' (Ioo a b) = Ioo (a / c) (b / c) := by simp [← Ioi_inter_Iio, h] @[simp] lemma preimage_mul_const_Ioc (a b : k) {c : k} (h : 0 < c) : (λ x, x * c) ⁻¹' (Ioc a b) = Ioc (a / c) (b / c) := by simp [← Ioi_inter_Iic, h] @[simp] lemma preimage_mul_const_Ico (a b : k) {c : k} (h : 0 < c) : (λ x, x * c) ⁻¹' (Ico a b) = Ico (a / c) (b / c) := by simp [← Ici_inter_Iio, h] @[simp] lemma preimage_mul_const_Icc (a b : k) {c : k} (h : 0 < c) : (λ x, x * c) ⁻¹' (Icc a b) = Icc (a / c) (b / c) := by simp [← Ici_inter_Iic, h] @[simp] lemma preimage_mul_const_Iio_of_neg (a : k) {c : k} (h : c < 0) : (λ x, x * c) ⁻¹' (Iio a) = Ioi (a / c) := ext $ λ x, (div_lt_iff_of_neg h).symm @[simp] lemma preimage_mul_const_Ioi_of_neg (a : k) {c : k} (h : c < 0) : (λ x, x * c) ⁻¹' (Ioi a) = Iio (a / c) := ext $ λ x, (lt_div_iff_of_neg h).symm @[simp] lemma preimage_mul_const_Iic_of_neg (a : k) {c : k} (h : c < 0) : (λ x, x * c) ⁻¹' (Iic a) = Ici (a / c) := ext $ λ x, (div_le_iff_of_neg h).symm @[simp] lemma preimage_mul_const_Ici_of_neg (a : k) {c : k} (h : c < 0) : (λ x, x * c) ⁻¹' (Ici a) = Iic (a / c) := ext $ λ x, (le_div_iff_of_neg h).symm @[simp] lemma preimage_mul_const_Ioo_of_neg (a b : k) {c : k} (h : c < 0) : (λ x, x * c) ⁻¹' (Ioo a b) = Ioo (b / c) (a / c) := by simp [← Ioi_inter_Iio, h, inter_comm] @[simp] lemma preimage_mul_const_Ioc_of_neg (a b : k) {c : k} (h : c < 0) : (λ x, x * c) ⁻¹' (Ioc a b) = Ico (b / c) (a / c) := by simp [← Ioi_inter_Iic, ← Ici_inter_Iio, h, inter_comm] @[simp] lemma preimage_mul_const_Ico_of_neg (a b : k) {c : k} (h : c < 0) : (λ x, x * c) ⁻¹' (Ico a b) = Ioc (b / c) (a / c) := by simp [← Ici_inter_Iio, ← Ioi_inter_Iic, h, inter_comm] @[simp] lemma preimage_mul_const_Icc_of_neg (a b : k) {c : k} (h : c < 0) : (λ x, x * c) ⁻¹' (Icc a b) = Icc (b / c) (a / c) := by simp [← Ici_inter_Iic, h, inter_comm] @[simp] lemma preimage_const_mul_Iio (a : k) {c : k} (h : 0 < c) : ((*) c) ⁻¹' (Iio a) = Iio (a / c) := ext $ λ x, (lt_div_iff' h).symm @[simp] lemma preimage_const_mul_Ioi (a : k) {c : k} (h : 0 < c) : ((*) c) ⁻¹' (Ioi a) = Ioi (a / c) := ext $ λ x, (div_lt_iff' h).symm @[simp] lemma preimage_const_mul_Iic (a : k) {c : k} (h : 0 < c) : ((*) c) ⁻¹' (Iic a) = Iic (a / c) := ext $ λ x, (le_div_iff' h).symm @[simp] lemma preimage_const_mul_Ici (a : k) {c : k} (h : 0 < c) : ((*) c) ⁻¹' (Ici a) = Ici (a / c) := ext $ λ x, (div_le_iff' h).symm @[simp] lemma preimage_const_mul_Ioo (a b : k) {c : k} (h : 0 < c) : ((*) c) ⁻¹' (Ioo a b) = Ioo (a / c) (b / c) := by simp [← Ioi_inter_Iio, h] @[simp] lemma preimage_const_mul_Ioc (a b : k) {c : k} (h : 0 < c) : ((*) c) ⁻¹' (Ioc a b) = Ioc (a / c) (b / c) := by simp [← Ioi_inter_Iic, h] @[simp] lemma preimage_const_mul_Ico (a b : k) {c : k} (h : 0 < c) : ((*) c) ⁻¹' (Ico a b) = Ico (a / c) (b / c) := by simp [← Ici_inter_Iio, h] @[simp] lemma preimage_const_mul_Icc (a b : k) {c : k} (h : 0 < c) : ((*) c) ⁻¹' (Icc a b) = Icc (a / c) (b / c) := by simp [← Ici_inter_Iic, h] @[simp] lemma preimage_const_mul_Iio_of_neg (a : k) {c : k} (h : c < 0) : ((*) c) ⁻¹' (Iio a) = Ioi (a / c) := by simpa only [mul_comm] using preimage_mul_const_Iio_of_neg a h @[simp] lemma preimage_const_mul_Ioi_of_neg (a : k) {c : k} (h : c < 0) : ((*) c) ⁻¹' (Ioi a) = Iio (a / c) := by simpa only [mul_comm] using preimage_mul_const_Ioi_of_neg a h @[simp] lemma preimage_const_mul_Iic_of_neg (a : k) {c : k} (h : c < 0) : ((*) c) ⁻¹' (Iic a) = Ici (a / c) := by simpa only [mul_comm] using preimage_mul_const_Iic_of_neg a h @[simp] lemma preimage_const_mul_Ici_of_neg (a : k) {c : k} (h : c < 0) : ((*) c) ⁻¹' (Ici a) = Iic (a / c) := by simpa only [mul_comm] using preimage_mul_const_Ici_of_neg a h @[simp] lemma preimage_const_mul_Ioo_of_neg (a b : k) {c : k} (h : c < 0) : ((*) c) ⁻¹' (Ioo a b) = Ioo (b / c) (a / c) := by simpa only [mul_comm] using preimage_mul_const_Ioo_of_neg a b h @[simp] lemma preimage_const_mul_Ioc_of_neg (a b : k) {c : k} (h : c < 0) : ((*) c) ⁻¹' (Ioc a b) = Ico (b / c) (a / c) := by simpa only [mul_comm] using preimage_mul_const_Ioc_of_neg a b h @[simp] lemma preimage_const_mul_Ico_of_neg (a b : k) {c : k} (h : c < 0) : ((*) c) ⁻¹' (Ico a b) = Ioc (b / c) (a / c) := by simpa only [mul_comm] using preimage_mul_const_Ico_of_neg a b h @[simp] lemma preimage_const_mul_Icc_of_neg (a b : k) {c : k} (h : c < 0) : ((*) c) ⁻¹' (Icc a b) = Icc (b / c) (a / c) := by simpa only [mul_comm] using preimage_mul_const_Icc_of_neg a b h lemma image_mul_right_Icc' (a b : k) {c : k} (h : 0 < c) : (λ x, x * c) '' Icc a b = Icc (a * c) (b * c) := ((units.mk0 c h.ne').mul_right.image_eq_preimage _).trans (by simp [h, division_def]) lemma image_mul_right_Icc {a b c : k} (hab : a ≤ b) (hc : 0 ≤ c) : (λ x, x * c) '' Icc a b = Icc (a * c) (b * c) := begin cases eq_or_lt_of_le hc, { subst c, simp [(nonempty_Icc.2 hab).image_const] }, exact image_mul_right_Icc' a b ‹0 < c› end lemma image_mul_left_Icc' {a : k} (h : 0 < a) (b c : k) : ((*) a) '' Icc b c = Icc (a * b) (a * c) := by { convert image_mul_right_Icc' b c h using 1; simp only [mul_comm _ a] } lemma image_mul_left_Icc {a b c : k} (ha : 0 ≤ a) (hbc : b ≤ c) : ((*) a) '' Icc b c = Icc (a * b) (a * c) := by { convert image_mul_right_Icc hbc ha using 1; simp only [mul_comm _ a] } lemma image_mul_right_Ioo (a b : k) {c : k} (h : 0 < c) : (λ x, x * c) '' Ioo a b = Ioo (a * c) (b * c) := ((units.mk0 c h.ne').mul_right.image_eq_preimage _).trans (by simp [h, division_def]) lemma image_mul_left_Ioo {a : k} (h : 0 < a) (b c : k) : ((*) a) '' Ioo b c = Ioo (a * b) (a * c) := by { convert image_mul_right_Ioo b c h using 1; simp only [mul_comm _ a] } /-- The image under `inv` of `Ioo 0 a` is `Ioi a⁻¹`. -/ lemma image_inv_Ioo_0_left {a : k} (ha : 0 < a) : has_inv.inv '' Ioo 0 a = Ioi a⁻¹ := begin ext x, exact ⟨λ ⟨y, ⟨hy0, hya⟩, hyx⟩, hyx ▸ (inv_lt_inv ha hy0).2 hya, λ h, ⟨x⁻¹, ⟨inv_pos.2 (lt_trans (inv_pos.2 ha) h), (inv_lt ha (lt_trans (inv_pos.2 ha) h)).1 h⟩, inv_inv₀ x⟩⟩, end /-! ### Images under `x ↦ a * x + b` -/ @[simp] lemma image_affine_Icc' {a : k} (h : 0 < a) (b c d : k) : (λ x, a * x + b) '' Icc c d = Icc (a * c + b) (a * d + b) := begin suffices : (λ x, x + b) '' ((λ x, a * x) '' Icc c d) = Icc (a * c + b) (a * d + b), { rwa set.image_image at this, }, rw [image_mul_left_Icc' h, image_add_const_Icc], end end linear_ordered_field end set
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Seul Baek -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.omega.coeffs import Mathlib.PostPort namespace Mathlib /- Normalized linear integer arithmetic terms. -/ namespace omega /-- Shadow syntax of normalized terms. The first element represents the constant term and the list represents the coefficients. -/ def term := ℤ × List ℤ namespace term /-- Evaluate a term using the valuation v. -/ @[simp] def val (v : ℕ → ℤ) : term → ℤ := sorry @[simp] def neg : term → term := sorry @[simp] def add : term → term → term := sorry @[simp] def sub : term → term → term := sorry @[simp] def mul (i : ℤ) : term → term := sorry @[simp] def div (i : ℤ) : term → term := sorry theorem val_neg {v : ℕ → ℤ} {t : term} : val v (neg t) = -val v t := sorry @[simp] theorem val_sub {v : ℕ → ℤ} {t1 : term} {t2 : term} : val v (sub t1 t2) = val v t1 - val v t2 := sorry @[simp] theorem val_add {v : ℕ → ℤ} {t1 : term} {t2 : term} : val v (add t1 t2) = val v t1 + val v t2 := sorry @[simp] theorem val_mul {v : ℕ → ℤ} {i : ℤ} {t : term} : val v (mul i t) = i * val v t := sorry theorem val_div {v : ℕ → ℤ} {i : ℤ} {b : ℤ} {as : List ℤ} : i ∣ b → (∀ (x : ℤ), x ∈ as → i ∣ x) → val v (div i (b, as)) = val v (b, as) / i := sorry /-- Fresh de Brujin index not used by any variable ocurring in the term -/ def fresh_index (t : term) : ℕ := list.length (prod.snd t) def to_string (t : term) : string := list.foldr (fun (_x : ℕ × ℤ) => sorry) (to_string (prod.fst t)) (list.enum (prod.snd t)) protected instance has_to_string : has_to_string term := has_to_string.mk to_string end term /-- Fresh de Brujin index not used by any variable ocurring in the list of terms -/ def terms.fresh_index : List term → ℕ := sorry end Mathlib
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.linear_algebra.smodeq import Mathlib.ring_theory.ideal.operations import Mathlib.PostPort universes u_1 u_2 u_3 namespace Mathlib /-! # Completion of a module with respect to an ideal. In this file we define the notions of Hausdorff, precomplete, and complete for an `R`-module `M` with respect to an ideal `I`: ## Main definitions - `is_Hausdorff I M`: this says that the intersection of `I^n M` is `0`. - `is_precomplete I M`: this says that every Cauchy sequence converges. - `is_adic_complete I M`: this says that `M` is Hausdorff and precomplete. - `Hausdorffification I M`: this is the universal Hausdorff module with a map from `M`. - `completion I M`: if `I` is finitely generated, then this is the universal complete module (TODO) with a map from `M`. This map is injective iff `M` is Hausdorff and surjective iff `M` is precomplete. -/ /-- A module `M` is Hausdorff with respect to an ideal `I` if `⋂ I^n M = 0`. -/ def is_Hausdorff {R : Type u_1} [comm_ring R] (I : ideal R) (M : Type u_2) [add_comm_group M] [module R M] := ∀ (x : M), (∀ (n : ℕ), smodeq (I ^ n • ⊤) x 0) → x = 0 /-- A module `M` is precomplete with respect to an ideal `I` if every Cauchy sequence converges. -/ def is_precomplete {R : Type u_1} [comm_ring R] (I : ideal R) (M : Type u_2) [add_comm_group M] [module R M] := ∀ (f : ℕ → M), (∀ {m n : ℕ}, m ≤ n → smodeq (I ^ m • ⊤) (f m) (f n)) → ∃ (L : M), ∀ (n : ℕ), smodeq (I ^ n • ⊤) (f n) L /-- A module `M` is `I`-adically complete if it is Hausdorff and precomplete. -/ def is_adic_complete {R : Type u_1} [comm_ring R] (I : ideal R) (M : Type u_2) [add_comm_group M] [module R M] := is_Hausdorff I M ∧ is_precomplete I M /-- The Hausdorffification of a module with respect to an ideal. -/ def Hausdorffification {R : Type u_1} [comm_ring R] (I : ideal R) (M : Type u_2) [add_comm_group M] [module R M] := submodule.quotient (infi fun (n : ℕ) => I ^ n • ⊤) /-- The completion of a module with respect to an ideal. This is not necessarily Hausdorff. In fact, this is only complete if the ideal is finitely generated. -/ def adic_completion {R : Type u_1} [comm_ring R] (I : ideal R) (M : Type u_2) [add_comm_group M] [module R M] : submodule R ((n : ℕ) → submodule.quotient (I ^ n • ⊤)) := submodule.mk (set_of fun (f : (n : ℕ) → submodule.quotient (I ^ n • ⊤)) => ∀ {m n : ℕ}, m ≤ n → coe_fn (submodule.liftq (I ^ n • ⊤) (submodule.mkq (I ^ m • ⊤)) sorry) (f n) = f m) sorry sorry sorry namespace is_Hausdorff protected instance bot {R : Type u_1} [comm_ring R] (M : Type u_2) [add_comm_group M] [module R M] : is_Hausdorff ⊥ M := fun (x : M) (hx : ∀ (n : ℕ), smodeq (⊥ ^ n • ⊤) x 0) => eq.mpr (id (Eq.refl (x = 0))) (eq.mp (Eq.trans ((fun (U U_1 : submodule R M) (e_1 : U = U_1) (x x_1 : M) (e_2 : x = x_1) (y y_1 : M) (e_3 : y = y_1) => congr (congr (congr_arg smodeq e_1) e_2) e_3) (⊥ ^ 1 • ⊤) ⊥ (Eq.trans ((fun (ᾰ ᾰ_1 : ideal R) (e_2 : ᾰ = ᾰ_1) (ᾰ_2 ᾰ_3 : submodule R M) (e_3 : ᾰ_2 = ᾰ_3) => congr (congr_arg has_scalar.smul e_2) e_3) (⊥ ^ 1) ⊥ (pow_one ⊥) ⊤ ⊤ (Eq.refl ⊤)) (submodule.bot_smul ⊤)) x x (Eq.refl x) 0 0 (Eq.refl 0)) (propext smodeq.bot)) (hx 1)) protected theorem subsingleton {R : Type u_1} [comm_ring R] {M : Type u_2} [add_comm_group M] [module R M] (h : is_Hausdorff ⊤ M) : subsingleton M := sorry protected instance of_subsingleton {R : Type u_1} [comm_ring R] (I : ideal R) (M : Type u_2) [add_comm_group M] [module R M] [subsingleton M] : is_Hausdorff I M := fun (x : M) (_x : ∀ (n : ℕ), smodeq (I ^ n • ⊤) x 0) => subsingleton.elim x 0 theorem infi_pow_smul {R : Type u_1} [comm_ring R] {I : ideal R} {M : Type u_2} [add_comm_group M] [module R M] (h : is_Hausdorff I M) : (infi fun (n : ℕ) => I ^ n • ⊤) = ⊥ := sorry end is_Hausdorff namespace Hausdorffification /-- The canonical linear map to the Hausdorffification. -/ def of {R : Type u_1} [comm_ring R] (I : ideal R) (M : Type u_2) [add_comm_group M] [module R M] : linear_map R M (Hausdorffification I M) := submodule.mkq (infi fun (n : ℕ) => I ^ n • ⊤) theorem induction_on {R : Type u_1} [comm_ring R] {I : ideal R} {M : Type u_2} [add_comm_group M] [module R M] {C : Hausdorffification I M → Prop} (x : Hausdorffification I M) (ih : ∀ (x : M), C (coe_fn (of I M) x)) : C x := quotient.induction_on' x ih protected instance is_Hausdorff {R : Type u_1} [comm_ring R] (I : ideal R) (M : Type u_2) [add_comm_group M] [module R M] : is_Hausdorff I (Hausdorffification I M) := sorry /-- universal property of Hausdorffification: any linear map to a Hausdorff module extends to a unique map from the Hausdorffification. -/ def lift {R : Type u_1} [comm_ring R] (I : ideal R) {M : Type u_2} [add_comm_group M] [module R M] {N : Type u_3} [add_comm_group N] [module R N] [h : is_Hausdorff I N] (f : linear_map R M N) : linear_map R (Hausdorffification I M) N := submodule.liftq (infi fun (n : ℕ) => I ^ n • ⊤) f sorry theorem lift_of {R : Type u_1} [comm_ring R] (I : ideal R) {M : Type u_2} [add_comm_group M] [module R M] {N : Type u_3} [add_comm_group N] [module R N] [h : is_Hausdorff I N] (f : linear_map R M N) (x : M) : coe_fn (lift I f) (coe_fn (of I M) x) = coe_fn f x := rfl theorem lift_comp_of {R : Type u_1} [comm_ring R] (I : ideal R) {M : Type u_2} [add_comm_group M] [module R M] {N : Type u_3} [add_comm_group N] [module R N] [h : is_Hausdorff I N] (f : linear_map R M N) : linear_map.comp (lift I f) (of I M) = f := linear_map.ext fun (_x : M) => rfl /-- Uniqueness of lift. -/ theorem lift_eq {R : Type u_1} [comm_ring R] (I : ideal R) {M : Type u_2} [add_comm_group M] [module R M] {N : Type u_3} [add_comm_group N] [module R N] [h : is_Hausdorff I N] (f : linear_map R M N) (g : linear_map R (Hausdorffification I M) N) (hg : linear_map.comp g (of I M) = f) : g = lift I f := sorry end Hausdorffification namespace is_precomplete protected instance bot {R : Type u_1} [comm_ring R] (M : Type u_2) [add_comm_group M] [module R M] : is_precomplete ⊥ M := fun (f : ℕ → M) (hf : ∀ {m n : ℕ}, m ≤ n → smodeq (⊥ ^ m • ⊤) (f m) (f n)) => Exists.intro (f 1) fun (n : ℕ) => nat.cases_on n (eq.mpr (id (Eq._oldrec (Eq.refl (smodeq (⊥ ^ 0 • ⊤) (f 0) (f 1))) (pow_zero ⊥))) (eq.mpr (id (Eq._oldrec (Eq.refl (smodeq (1 • ⊤) (f 0) (f 1))) ideal.one_eq_top)) (eq.mpr (id (Eq._oldrec (Eq.refl (smodeq (⊤ • ⊤) (f 0) (f 1))) (submodule.top_smul ⊤))) smodeq.top))) fun (n : ℕ) => eq.mpr (id (Eq._oldrec (Eq.refl (smodeq (⊥ ^ Nat.succ n • ⊤) (f (Nat.succ n)) (f 1))) (eq.mp (Eq._oldrec (Eq.refl (smodeq ⊥ (f 1) (f (n + 1)))) (propext smodeq.bot)) (eq.mp (Eq._oldrec (Eq.refl (smodeq (⊥ • ⊤) (f 1) (f (n + 1)))) (submodule.bot_smul ⊤)) (eq.mp (Eq._oldrec (Eq.refl (smodeq (⊥ ^ 1 • ⊤) (f 1) (f (n + 1)))) (pow_one ⊥)) (hf (nat.le_add_left 1 n))))))) smodeq.refl protected instance top {R : Type u_1} [comm_ring R] (M : Type u_2) [add_comm_group M] [module R M] : is_precomplete ⊤ M := fun (f : ℕ → M) (hf : ∀ {m n : ℕ}, m ≤ n → smodeq (⊤ ^ m • ⊤) (f m) (f n)) => Exists.intro 0 fun (n : ℕ) => eq.mpr (id (Eq._oldrec (Eq.refl (smodeq (⊤ ^ n • ⊤) (f n) 0)) (ideal.top_pow R n))) (eq.mpr (id (Eq._oldrec (Eq.refl (smodeq (⊤ • ⊤) (f n) 0)) (submodule.top_smul ⊤))) smodeq.top) protected instance of_subsingleton {R : Type u_1} [comm_ring R] (I : ideal R) (M : Type u_2) [add_comm_group M] [module R M] [subsingleton M] : is_precomplete I M := fun (f : ℕ → M) (hf : ∀ {m n : ℕ}, m ≤ n → smodeq (I ^ m • ⊤) (f m) (f n)) => Exists.intro 0 fun (n : ℕ) => eq.mpr (id (Eq._oldrec (Eq.refl (smodeq (I ^ n • ⊤) (f n) 0)) (subsingleton.elim (f n) 0))) smodeq.refl end is_precomplete namespace adic_completion /-- The canonical linear map to the completion. -/ def of {R : Type u_1} [comm_ring R] (I : ideal R) (M : Type u_2) [add_comm_group M] [module R M] : linear_map R M ↥(adic_completion I M) := linear_map.mk (fun (x : M) => { val := fun (n : ℕ) => coe_fn (submodule.mkq (I ^ n • ⊤)) x, property := sorry }) sorry sorry @[simp] theorem of_apply {R : Type u_1} [comm_ring R] (I : ideal R) (M : Type u_2) [add_comm_group M] [module R M] (x : M) (n : ℕ) : subtype.val (coe_fn (of I M) x) n = coe_fn (submodule.mkq (I ^ n • ⊤)) x := rfl /-- Linearly evaluating a sequence in the completion at a given input. -/ def eval {R : Type u_1} [comm_ring R] (I : ideal R) (M : Type u_2) [add_comm_group M] [module R M] (n : ℕ) : linear_map R (↥(adic_completion I M)) (submodule.quotient (I ^ n • ⊤)) := linear_map.mk (fun (f : ↥(adic_completion I M)) => subtype.val f n) sorry sorry @[simp] theorem coe_eval {R : Type u_1} [comm_ring R] (I : ideal R) (M : Type u_2) [add_comm_group M] [module R M] (n : ℕ) : ⇑(eval I M n) = fun (f : ↥(adic_completion I M)) => subtype.val f n := rfl theorem eval_apply {R : Type u_1} [comm_ring R] (I : ideal R) (M : Type u_2) [add_comm_group M] [module R M] (n : ℕ) (f : ↥(adic_completion I M)) : coe_fn (eval I M n) f = subtype.val f n := rfl theorem eval_of {R : Type u_1} [comm_ring R] (I : ideal R) (M : Type u_2) [add_comm_group M] [module R M] (n : ℕ) (x : M) : coe_fn (eval I M n) (coe_fn (of I M) x) = coe_fn (submodule.mkq (I ^ n • ⊤)) x := rfl @[simp] theorem eval_comp_of {R : Type u_1} [comm_ring R] (I : ideal R) (M : Type u_2) [add_comm_group M] [module R M] (n : ℕ) : linear_map.comp (eval I M n) (of I M) = submodule.mkq (I ^ n • ⊤) := rfl @[simp] theorem range_eval {R : Type u_1} [comm_ring R] (I : ideal R) (M : Type u_2) [add_comm_group M] [module R M] (n : ℕ) : linear_map.range (eval I M n) = ⊤ := iff.mpr linear_map.range_eq_top fun (x : submodule.quotient (I ^ n • ⊤)) => quotient.induction_on' x fun (x : M) => Exists.intro (coe_fn (of I M) x) rfl theorem ext {R : Type u_1} [comm_ring R] {I : ideal R} {M : Type u_2} [add_comm_group M] [module R M] {x : ↥(adic_completion I M)} {y : ↥(adic_completion I M)} (h : ∀ (n : ℕ), coe_fn (eval I M n) x = coe_fn (eval I M n) y) : x = y := subtype.eq (funext h) protected instance is_Hausdorff {R : Type u_1} [comm_ring R] (I : ideal R) (M : Type u_2) [add_comm_group M] [module R M] : is_Hausdorff I ↥(adic_completion I M) := sorry end adic_completion namespace is_adic_complete protected instance bot {R : Type u_1} [comm_ring R] (M : Type u_2) [add_comm_group M] [module R M] : is_adic_complete ⊥ M := { left := is_Hausdorff.bot M, right := is_precomplete.bot M } protected theorem subsingleton {R : Type u_1} [comm_ring R] (M : Type u_2) [add_comm_group M] [module R M] (h : is_adic_complete ⊤ M) : subsingleton M := is_Hausdorff.subsingleton (and.left h) protected instance of_subsingleton {R : Type u_1} [comm_ring R] (I : ideal R) (M : Type u_2) [add_comm_group M] [module R M] [subsingleton M] : is_adic_complete I M := { left := is_Hausdorff.of_subsingleton I M, right := is_precomplete.of_subsingleton I M } end Mathlib
-- --------------------------------------------------------------- [ Error.idr ] -- Module : Error.idr -- Copyright : (c) Jan de Muijnck-Hughes -- License : see LICENSE -- --------------------------------------------------------------------- [ EOH ] ||| Common code for all DSML DSLs module GRL.Lang.Common.Error %access public export -- ------------------------------------------------------------------ [ Errors ] data GError : Type where NoFileError : GError NoSuchFileError : String -> GError ParserError : String -> String -> GError NoSuchIdentError : String -> GError BadModelError : GError Show GError where show (NoFileError) = "File Must Be specified" show (NoSuchFileError fn) = unwords ["No such file:", show fn] show (ParserError fn err) = unlines [unwords ["Unable to parse", show fn, "because:"], err] show (NoSuchIdentError ident) = unwords ["No such identifier:", show ident] show (BadModelError) = "Bad Model" -- --------------------------------------------------------------------- [ EOF ]
## Linear Regression $$ \bar{y} = wx + b $$ ```python %matplotlib inline from matplotlib import pyplot as plt import numpy as np import theano from theano import tensor as T ``` ```python train_X = np.linspace(-1, 1, 101) train_Y = 2 * train_X + 1 + np.random.randn(train_X.size) * 0.33 plt.scatter(train_X, train_Y) ``` ```python X, Y = T.scalar(), T.scalar() X.name, Y.name = 'x', 'y' def linear_model(X, w, b): return X * w + b ``` 损失函数: $ C = \left|\bar{y} - y \right|^2 $ 我们可以使用梯度下降法来迭代参数 w,b 的值,为此,我们将 w 和 b 设成共享变量: ```python w = theano.shared(np.asarray(0., dtype=theano.config.floatX)) w.name = 'w' b = theano.shared(np.asarray(0., dtype=theano.config.floatX)) b.name = 'b' Y_bar = linear_model(X, w, b) theano.pp(Y_bar) ``` '((x * w) + b)' ```python cost = T.mean(T.sqr(Y_bar - Y)) grads = T.grad(cost=cost, wrt=[w, b]) ``` ```python lr = 0.01 updates = [[w, w - grads[0] * lr], [b, b - grads[1] * lr]] train_model = theano.function(inputs=[X,Y], outputs=cost, updates=updates, allow_input_downcast=True) for i in range(100): for x, y in zip(train_X, train_Y): train_model(x, y) ``` ```python print(w.get_value()) print(b.get_value()) plt.scatter(train_X, train_Y) plt.plot(train_X, w.get_value() * train_X + b.get_value(), 'r') ``` ## Logistic Regression $$ s(x) = \frac{1}{1 + e^{-x}} = \frac{1 + tanh\left(\frac{x}{2}\right)}{2} $$ ```python rng = np.random # 数据大小和规模 N = 400 feats = 784 # D = (X, Y) D = (rng.randn(N, feats), rng.randint(size=N, low=0, high=2)) ``` ```python x = T.matrix('x') y = T.vector('y') # 要更新的变量: w = theano.shared(rng.randn(feats), name='w') b = theano.shared(0., name='b') ``` ```python h = 1 / (1 + T.exp(-T.dot(x, w) - b)) prediction = h > 0.5 ``` ```python cost = - T.mean(y * T.log(h) + (1 - y) * T.log(1 - h)) + 0.01 * T.sum(w ** 2) # 正则项,防止过拟合 gw, gb = T.grad(cost, [w, b]) ``` ```python train = theano.function(inputs=[x, y], outputs=cost, updates=[[w, w - 0.1 * gw], [b, b - 0.1 * gb]], allow_input_downcast=True) predict = theano.function(inputs=[x], outputs=prediction, allow_input_downcast=True) for i in range(10001): err = train(D[0], D[1]) if i % 1000 == 0: print('iter {0:5d}, error {1}'.format(i, err)) ``` iter 0, error nan iter 1000, error 0.20916386518319272 iter 2000, error 0.12385585775631414 iter 3000, error 0.12256679622266706 iter 4000, error 0.12254240274449477 iter 5000, error 0.12254162133721462 iter 6000, error 0.12254152989301592 iter 7000, error 0.12254151063149532 iter 8000, error 0.12254150627087208 iter 9000, error 0.12254150527768518 iter 10000, error 0.12254150505136419 ```python D[1] ``` array([0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0]) ```python predict(D[0]) ``` array([False, True, True, False, True, True, True, False, False, True, False, True, True, True, True, False, False, False, False, False, True, False, True, False, False, False, True, False, True, False, True, True, True, False, False, True, True, False, False, True, False, False, False, False, False, False, False, False, True, False, False, True, True, True, False, False, False, True, False, False, False, True, False, True, False, True, False, False, True, False, True, True, True, False, True, False, True, True, False, False, True, True, False, True, False, False, True, False, False, True, False, False, True, True, False, False, True, False, True, False, False, True, False, False, True, False, True, False, True, True, True, True, True, True, False, True, False, True, False, False, True, True, False, True, True, False, True, False, False, False, False, True, False, False, True, False, True, True, False, True, True, False, False, False, False, True, False, True, True, False, False, True, True, True, False, True, True, False, True, False, False, True, False, True, True, False, True, False, False, True, False, True, True, True, True, False, True, True, True, False, False, False, False, True, False, True, False, True, False, True, True, False, False, True, False, False, True, False, True, True, False, True, True, True, False, True, True, False, True, False, False, True, False, False, False, False, True, True, False, True, True, True, True, True, False, True, True, False, True, False, False, True, True, False, True, False, True, False, False, True, True, True, False, False, True, True, False, False, False, False, True, False, False, False, True, True, False, False, True, False, False, True, False, False, False, False, True, False, True, False, False, True, True, True, True, True, False, True, True, False, False, False, True, True, True, False, True, True, True, False, False, True, True, False, False, False, False, False, True, False, True, True, False, False, True, True, True, False, False, False, False, False, True, True, True, False, False, True, True, False, False, True, True, True, False, True, True, True, True, False, True, True, True, False, True, True, False, False, False, True, False, False, False, True, False, False, True, False, False, True, False, False, False, True, True, True, False, False, False, True, False, True, True, True, True, True, True, False, True, False, True, False, True, False, True, False, True, False, False, True, False, True, False, False, False, False, True, True, True, True, False, True, False, True, False, True, False, False, False, False], dtype=bool) ## Softmax Regression [MNIST 数据集](http://yann.lecun.com/exdb/mnist/) 是一个手写数字组成的数据集,现在被当作一个机器学习算法评测的基准数据集。 这是一个下载并解压数据的脚本: ```python %%file download_mnist.py import os import os.path import urllib import gzip import shutil if not os.path.exists('mnist'): os.mkdir('mnist') def download_and_gzip(name): if not os.path.exists(name + '.gz'): urllib.request.urlretrieve('http://yann.lecun.com/exdb/' + name + '.gz', name + '.gz') if not os.path.exists(name): with gzip.open(name + '.gz', 'rb') as f_in, open(name, 'wb') as f_out: shutil.copyfileobj(f_in, f_out) download_and_gzip('mnist/train-images-idx3-ubyte') download_and_gzip('mnist/train-labels-idx1-ubyte') download_and_gzip('mnist/t10k-images-idx3-ubyte') download_and_gzip('mnist/t10k-labels-idx1-ubyte') ``` Writing download_mnist.py ```python %run download_mnist.py ``` ```python %%file load.py import numpy as np import os datasets_dir = './' def one_hot(x,n): if type(x) == list: x = np.array(x) x = x.flatten() o_h = np.zeros((len(x),n)) o_h[np.arange(len(x)),x] = 1 return o_h def mnist(ntrain=60000,ntest=10000,onehot=True): data_dir = os.path.join(datasets_dir,'mnist/') fd = open(os.path.join(data_dir,'train-images-idx3-ubyte')) loaded = np.fromfile(file=fd,dtype=np.uint8) trX = loaded[16:].reshape((60000,28*28)).astype(float) fd = open(os.path.join(data_dir,'train-labels-idx1-ubyte')) loaded = np.fromfile(file=fd,dtype=np.uint8) trY = loaded[8:].reshape((60000)) fd = open(os.path.join(data_dir,'t10k-images-idx3-ubyte')) loaded = np.fromfile(file=fd,dtype=np.uint8) teX = loaded[16:].reshape((10000,28*28)).astype(float) fd = open(os.path.join(data_dir,'t10k-labels-idx1-ubyte')) loaded = np.fromfile(file=fd,dtype=np.uint8) teY = loaded[8:].reshape((10000)) trX = trX/255. teX = teX/255. trX = trX[:ntrain] trY = trY[:ntrain] teX = teX[:ntest] teY = teY[:ntest] if onehot: trY = one_hot(trY, 10) teY = one_hot(teY, 10) else: trY = np.asarray(trY) teY = np.asarray(teY) return trX,teX,trY,teY ``` Writing load.py ```python from load import mnist def floatX(X): return np.asarray(X, dtype=theano.config.floatX) def init_weights(shape): return theano.shared(floatX(np.random.randn(*shape) * 0.01)) A = T.matrix() B = T.nnet.softmax(A) test_softmax = theano.function([A], B) a = floatX(np.random.rand(3, 4)) b = test_softmax(a) print(b.shape) # 行和 print(b.sum(1)) ``` (3, 4) [ 1. 1. 1.] ```python def model(X, w): return T.nnet.softmax(T.dot(X, w)) trX, teX, trY, teY = mnist(onehot=True) X = T.fmatrix() Y = T.fmatrix() w = init_weights((784, 10)) py_x = model(X, w) y_pred = T.argmax(py_x, axis=1) # 损失函数为多类的交叉熵,这个在 theano 中也被定义好了: cost = T.mean(T.nnet.categorical_crossentropy(py_x, Y)) gradient = T.grad(cost=cost, wrt=w) update = [[w, w - gradient * 0.05]] train = theano.function(inputs=[X, Y], outputs=cost, updates=update, allow_input_downcast=True) predict = theano.function(inputs=[X], outputs=y_pred, allow_input_downcast=True) ``` ```python for i in range(100): for start, end in zip(range(0, len(trX), 128), range(128, len(trX), 128)): cost = train(trX[start:end], trY[start:end]) print("{0:03d}".format(i), np.mean(np.argmax(teY, axis=1) == predict(teX))) ``` 000 0.8857 001 0.8977 002 0.9045 003 0.9074 004 0.9099 005 0.9111 006 0.9135 007 0.9143 008 0.9151 009 0.9159 010 0.9164 011 0.9167 012 0.9169 013 0.9172 014 0.9177 015 0.9177 016 0.9182 017 0.9188 018 0.919 019 0.919 020 0.9197 021 0.9199 022 0.9199 023 0.9204 024 0.9205 025 0.9205 026 0.9209 027 0.9211 028 0.9211 029 0.9214 030 0.9213 031 0.9216 032 0.9215 033 0.9218 034 0.9219 035 0.9218 036 0.9217 037 0.9218 038 0.9221 039 0.9222 040 0.9223 041 0.9225 042 0.9225 043 0.9225 044 0.9224 045 0.9225 046 0.9225 047 0.9224 048 0.923 049 0.9231 050 0.9233 051 0.9235 052 0.9236 053 0.9236 054 0.9236 055 0.9235 056 0.9236 057 0.9239 058 0.9241 059 0.9241 060 0.9242 061 0.9242 062 0.9242 063 0.9242 064 0.9245 065 0.9245 066 0.9245 067 0.9243 068 0.9244 069 0.9243 070 0.9245 071 0.9244 072 0.9245 073 0.9244 074 0.9245 075 0.9244 076 0.9243 077 0.9244 078 0.9244 079 0.9243 080 0.9243 081 0.9247 082 0.9248 083 0.9248 084 0.9248 085 0.9248 086 0.9246 087 0.9246 088 0.9246 089 0.9246 090 0.9247 091 0.9248 092 0.9248 093 0.9251 094 0.925 095 0.925 096 0.925 097 0.925 098 0.9249 099 0.9248 ## ANN(人工神经网络) 我们在这里使用一个简单的三层神经网络:输入 - 隐层 - 输出。 对于网络的激活函数,隐层用sigmoid函数,输出层用softmax函数,其模型如下: $$ \begin{aligned} h &= \sigma (W_h X) \\ o &= \text{softmax} (W_o h) \end{aligned} $$ ```python def model(X, w_h, w_o): """ input: X: input data w_h: hidden unit weights w_o: output unit weights output: Y: probability of y given x """ # 隐层 h = T.nnet.sigmoid(T.dot(X, w_h)) # 输出层 pyx = T.nnet.softmax(T.dot(h, w_o)) return pyx def sgd(cost, params, lr=0.05): """ input: cost: cost function params: parameters lr: learning rate output: update rules """ grads = T.grad(cost=cost, wrt=params) updates = [] for p, g in zip(params, grads): updates.append([p, p - g * lr]) return updates def floatX(X): return np.asarray(X, dtype=theano.config.floatX) def init_weights(shape): return theano.shared(floatX(np.random.randn(*shape) * 0.01)) X = T.matrix() Y = T.matrix() w_h = init_weights((784, 625)) w_o = init_weights((625, 10)) py_x = model(X, w_h, w_o) y_x = T.argmax(py_x, axis=1) cost = T.mean(T.nnet.categorical_crossentropy(py_x, Y)) updates = sgd(cost, [w_h, w_o]) train = theano.function(inputs=[X, Y], outputs=cost, updates=updates, allow_input_downcast=True) predict = theano.function(inputs=[X], outputs=y_x, allow_input_downcast=True) trX, teX, trY, teY = mnist(onehot=True) ``` ```python for i in range(100): for start, end in zip(range(0, len(trX), 128), range(128, len(trX), 128)): cost = train(trX[start:end], trY[start:end]) print("{0:03d}".format(i), np.mean(np.argmax(teY, axis=1) == predict(teX))) ``` 000 0.7079 001 0.829 002 0.8671 003 0.8831 004 0.8894 005 0.8954 006 0.8981 007 0.9016 008 0.9043 009 0.9068 010 0.9093 011 0.9114 012 0.9129 013 0.9141 014 0.9153 015 0.9159 016 0.9163 017 0.917 018 0.9176 019 0.9184 020 0.9188 021 0.919 022 0.9195 023 0.9197 024 0.9204 025 0.9208 026 0.921 027 0.9217 028 0.922 029 0.9228 030 0.9238 031 0.9236 032 0.9241 033 0.9251 034 0.9258 035 0.9262 036 0.9265 037 0.9271 038 0.9278 039 0.9286 040 0.9294 041 0.9295 042 0.9299 043 0.93 044 0.9304 045 0.9307 046 0.9317 047 0.9322 048 0.9331 049 0.9334 050 0.9338 051 0.9352 052 0.9359 053 0.9366 054 0.9374 055 0.9379 056 0.9385 057 0.939 058 0.9395 059 0.9399 060 0.9408 061 0.9414 062 0.9418 063 0.9423 064 0.9429 065 0.9434 066 0.944 067 0.9447 068 0.9451 069 0.9457 070 0.9464 071 0.9464 072 0.947 073 0.9474 074 0.9478 075 0.9485 076 0.9488 077 0.9491 078 0.95 079 0.9507 080 0.951 081 0.9513 082 0.9517 083 0.952 084 0.9527 085 0.9535 086 0.9536 087 0.9543 088 0.9545 089 0.9548 090 0.955 091 0.9554 092 0.9558 093 0.9563 094 0.9569 095 0.9572 096 0.9575 097 0.9576 098 0.9582 099 0.9584 ## 更复杂的神经网络 之前我们采用的的激活函数是 sigmoid,现在我们使用 rectify 激活函数。 这可以使用 `T.nnet.relu(x, alpha=0)` 来实现,它本质上相当于:`T.switch(x > 0, x, alpha * x)`,而 rectify 函数的定义为: $$ \text{rectify}(x) = \left\{ \begin{aligned} x, & \ x > 0 \\ 0, & \ x < 0 \end{aligned}\right. $$ 之前我们构造的是一个单隐层的神经网络结构,现在我们构造一个双隐层的结构即“输入-隐层1-隐层2-输出”的全连接结构。 $$ \begin{aligned} & h_1 = \text{rectify}(W_{h_1} \ x) \\ & h_2 = \text{rectify}(W_{h_2} \ h_1) \\ & o = \text{softmax}(W_o h_2) \end{aligned} $$ Theano 自带的 `T.nnet.softmax()` 的 GPU 实现目前似乎有 bug 会导致梯度溢出的问题,因此自定义了 softmax 函数: ```python def dropout(X, prob=0.): if prob > 0: X *= srng.binomial(X.shape, p=1-prob, dtype = theano.config.floatX) X /= 1 - prob return X def softmax(X): e_x = T.exp(X - X.max(axis=1).dimshuffle(0, 'x')) return e_x / e_x.sum(axis=1).dimshuffle(0, 'x') def model(X, w_h1, w_h2, w_o, p_drop_input, p_drop_hidden): """ input: X: input data w_h1: weights input layer to hidden layer 1 w_h2: weights hidden layer 1 to hidden layer 2 w_o: weights hidden layer 2 to output layer p_drop_input: dropout rate for input layer p_drop_hidden: dropout rate for hidden layer output: h1: hidden layer 1 h2: hidden layer 2 py_x: output layer """ X = dropout(X, p_drop_input) h1 = T.nnet.relu(T.dot(X, w_h1)) h1 = dropout(h1, p_drop_hidden) h2 = T.nnet.relu(T.dot(h1, w_h2)) h2 = dropout(h2, p_drop_hidden) py_x = softmax(T.dot(h2, w_o)) return h1, h2, py_x def init_weights(shape): return theano.shared(floatX(np.random.randn(*shape) * 0.01)) w_h1 = init_weights((784, 625)) w_h2 = init_weights((625, 625)) w_o = init_weights((625, 10)) X = T.matrix() Y = T.matrix() ``` 定义更新的规则,之前我们使用的是简单的 SGD,这次我们使用 RMSprop 来更新,其规则为: $$ \begin{align} MS(w, t) &= \rho MS(w, t-1) + (1-\rho) \left(\left.\frac{\partial E}{\partial w}\right|_{w(t-1)}\right)^2 \\ w(t) &= w(t-1) - \alpha \left.\frac{\partial E}{\partial w}\right|_{w(t-1)} / \sqrt{MS(w, t)} \end{align} $$ ```python from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams srng = RandomStreams() def RMSprop(cost, params, accs, lr=0.001, rho=0.9, epsilon=1e-6): grads = T.grad(cost=cost, wrt=params) updates = [] for p, g, acc in zip(params, grads, accs): acc_new = rho * acc + (1 - rho) * g ** 2 gradient_scaling = T.sqrt(acc_new + epsilon) g = g / gradient_scaling updates.append((acc, acc_new)) updates.append((p, p - lr * g)) return updates # 有 dropout,用来训练 noise_h1, noise_h2, noise_py_x = model(X, w_h1, w_h2, w_o, 0.2, 0.5) cost = T.mean(T.nnet.categorical_crossentropy(noise_py_x, Y)) params = [w_h1, w_h2, w_o] accs = [theano.shared(p.get_value() * 0.) for p in params] updates = RMSprop(cost, params, accs, lr=0.001) # 训练函数 train = theano.function(inputs=[X, Y], outputs=cost, updates=updates, allow_input_downcast=True) # 没有 dropout,用来预测 h1, h2, py_x = model(X, w_h1, w_h2, w_o, 0., 0.) # 预测的结果 y_x = T.argmax(py_x, axis=1) predict = theano.function(inputs=[X], outputs=y_x, allow_input_downcast=True) ``` ```python trX, teX, trY, teY = mnist(onehot=True) for i in range(50): for start, end in zip(range(0, len(trX), 128), range(128, len(trX), 128)): cost = train(trX[start:end], trY[start:end]) print("iter {:03d} accuracy:".format(i + 1), np.mean(np.argmax(teY, axis=1) == predict(teX))) ``` iter 001 accuracy: 0.9412 iter 002 accuracy: 0.9633 iter 003 accuracy: 0.9721 iter 004 accuracy: 0.9745 iter 005 accuracy: 0.9741 iter 006 accuracy: 0.9775 iter 007 accuracy: 0.9762 iter 008 accuracy: 0.981 iter 009 accuracy: 0.9808 iter 010 accuracy: 0.9808 iter 011 accuracy: 0.9818 iter 012 accuracy: 0.9828 iter 013 accuracy: 0.9832 iter 014 accuracy: 0.9844 iter 015 accuracy: 0.984 iter 016 accuracy: 0.9826 iter 017 accuracy: 0.984 iter 018 accuracy: 0.9852 iter 019 accuracy: 0.9842 iter 020 accuracy: 0.9853 iter 021 accuracy: 0.9844 iter 022 accuracy: 0.9843 iter 023 accuracy: 0.9846 iter 024 accuracy: 0.9862 iter 025 accuracy: 0.9846 iter 026 accuracy: 0.9854 iter 027 accuracy: 0.9855 iter 028 accuracy: 0.9858 iter 029 accuracy: 0.9869 iter 030 accuracy: 0.9872 iter 031 accuracy: 0.9854 iter 032 accuracy: 0.9852 iter 033 accuracy: 0.9851 iter 034 accuracy: 0.9874 iter 035 accuracy: 0.9857 iter 036 accuracy: 0.9857 iter 037 accuracy: 0.9851 iter 038 accuracy: 0.986 iter 039 accuracy: 0.986 iter 040 accuracy: 0.9855 iter 041 accuracy: 0.9865 iter 042 accuracy: 0.9857 iter 043 accuracy: 0.9862 iter 044 accuracy: 0.9859 iter 045 accuracy: 0.9873 iter 046 accuracy: 0.9856 iter 047 accuracy: 0.988 iter 048 accuracy: 0.9878 iter 049 accuracy: 0.987 iter 050 accuracy: 0.988 清理文件 ```python import os import shutil os.remove("download_mnist.py") os.remove("load.py") shutil.rmtree("mnist") ``` ```python from theano.tensor.nnet import conv2d from theano.tensor.signal import pool trX, teX, trY, teY = mnist(onehot=True) trX = trX.reshape(-1, 1, 28, 28) teX = teX.reshape(-1, 1, 28, 28) def model(X, w, w2, w3, w4, p_drop_conv, p_drop_hidden): # X: 128 * 1 * 28 * 28 # w: 32 * 1 * 3 * 3 # full mode # l1a: 128 * 32 * (28 + 3 - 1) * (28 + 3 - 1) l1a = rectify(conv2d(X, w, border_mode='full')) # l1a: 128 * 32 * 30 * 30 # ignore_border False # l1: 128 * 32 * (30 / 2) * (30 / 2) l1 = pool.pool_2d(l1a, (2, 2), ignore_border=False) l1 = dropout(l1, p_drop_conv) # l1: 128 * 32 * 15 * 15 # w2: 64 * 32 * 3 * 3 # valid mode # l2a: 128 * 64 * (15 - 3 + 1) * (15 - 3 + 1) l2a = rectify(conv2d(l1, w2)) # l2a: 128 * 64 * 13 * 13 # l2: 128 * 64 * (13 / 2 + 1) * (13 / 2 + 1) l2 = pool.pool_2d(l2a, (2, 2), ignore_border=False) l2 = dropout(l2, p_drop_conv) # l2: 128 * 64 * 7 * 7 # w3: 128 * 64 * 3 * 3 # l3a: 128 * 128 * (7 - 3 + 1) * (7 - 3 + 1) l3a = rectify(conv2d(l2, w3)) # l3a: 128 * 128 * 5 * 5 # l3b: 128 * 128 * (5 / 2 + 1) * (5 / 2 + 1) l3b = pool.pool_2d(l3a, (2, 2), ignore_border=False) # l3b: 128 * 128 * 3 * 3 # l3: 128 * (128 * 3 * 3) l3 = T.flatten(l3b, outdim=2) l3 = dropout(l3, p_drop_conv) # l3: 128 * (128 * 3 * 3) # w4: (128 * 3 * 3) * 625 # l4: 128 * 625 l4 = rectify(T.dot(l3, w4)) l4 = dropout(l4, p_drop_hidden) # l5: 128 * 625 # w5: 625 * 10 # pyx: 128 * 10 pyx = softmax(T.dot(l4, w_o)) return l1, l2, l3, l4, pyx ``` ```python X = T.ftensor4() Y = T.fmatrix() w = init_weights((32, 1, 3, 3)) w2 = init_weights((64, 32, 3, 3)) w3 = init_weights((128, 64, 3, 3)) w4 = init_weights((128 * 3 * 3, 625)) w_o = init_weights((625, 10)) ``` ```python print("Theano Examples") ``` Theano Examples ```python ```
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import tactic.core import tactic.lint /-! # mk_iff_of_inductive_prop This file defines a tactic `tactic.mk_iff_of_inductive_prop` that generates `iff` rules for inductive `Prop`s. For example, when applied to `list.chain`, it creates a declaration with the following type: ```lean ∀{α : Type*} (R : α → α → Prop) (a : α) (l : list α), chain R a l ↔ l = [] ∨ ∃{b : α} {l' : list α}, R a b ∧ chain R b l ∧ l = b :: l' ``` This tactic can be called using either the `mk_iff_of_inductive_prop` user command or the `mk_iff` attribute. -/ open tactic expr namespace mk_iff /-- `select m n` runs `tactic.right` `m` times, and then `tactic.left` `(n-m)` times. Fails if `n < m`. -/ meta def select : ℕ → ℕ → tactic unit | 0 0 := skip | 0 (n + 1) := left >> skip | (m + 1) (n + 1) := right >> select m n | (n + 1) 0 := failure /-- `compact_relation bs as_ps`: Produce a relation of the form: ```lean R as := ∃ bs, Λ_i a_i = p_i[bs] ``` This relation is user-visible, so we compact it by removing each `b_j` where a `p_i = b_j`, and hence `a_i = b_j`. We need to take care when there are `p_i` and `p_j` with `p_i = p_j = b_k`. TODO: this is a variant of `compact_relation` in `coinductive_predicates.lean`, export it there. -/ meta def compact_relation : list expr → list (expr × expr) → list (option expr) × list (expr × expr) | [] ps := ([], ps) | (b :: bs) ps := match ps.span (λap:expr × expr, ¬ ap.2 =ₐ b) with | (_, []) := let (bs, ps) := compact_relation bs ps in (b::bs, ps) | (ps₁, (a, _) :: ps₂) := let i := a.instantiate_local b.local_uniq_name, (bs, ps) := compact_relation (bs.map i) ((ps₁ ++ ps₂).map (λ⟨a, p⟩, (a, i p))) in (none :: bs, ps) end @[nolint doc_blame] -- TODO: document meta def constr_to_prop (univs : list level) (g : list expr) (idxs : list expr) (c : name) : tactic ((list (option expr) × (expr ⊕ ℕ)) × expr) := do e ← get_env, decl ← get_decl c, some type' ← return $ decl.instantiate_type_univ_params univs, type ← drop_pis g type', (args, res) ← open_pis type, let idxs_inst := res.get_app_args.drop g.length, let (bs, eqs) := compact_relation args (idxs.zip idxs_inst), let bs' := bs.filter_map id, eqs ← eqs.mmap (λ⟨idx, inst⟩, do let ty := idx.local_type, inst_ty ← infer_type inst, sort u ← infer_type ty, (is_def_eq ty inst_ty >> return ((const `eq [u] : expr) ty idx inst)) <|> return ((const `heq [u] : expr) ty idx inst_ty inst)), (n, r) ← match bs', eqs with | [], [] := return (sum.inr 0, mk_true) | _, [] := do let t : expr := bs'.ilast.local_type, sort l ← infer_type t, if l = level.zero then do r ← mk_exists_lst bs'.init t, return (sum.inl bs'.ilast, r) else do r ← mk_exists_lst bs' mk_true, return (sum.inr 0, r) | _, _ := do r ← mk_exists_lst bs' (mk_and_lst eqs), return (sum.inr eqs.length, r) end, return ((bs, n), r) @[nolint doc_blame] -- TODO: document meta def to_cases (s : list $ list (option expr) × (expr ⊕ ℕ)) : tactic unit := do h ← intro1, i ← induction h, focus ((s.zip i).enum.map $ λ⟨p, (shape, t), _, vars, _⟩, do let si := (shape.zip vars).filter_map (λ⟨c, v⟩, c >>= λ _, some v), select p (s.length - 1), match t with | sum.inl e := do si.init.mmap' existsi, some v ← return $ vars.nth (shape.length - 1), exact v | sum.inr n := do si.mmap' existsi, iterate_exactly (n - 1) (split >> constructor >> skip) >> constructor >> skip end, done), done /-- Iterate over two lists, if the first element of the first list is `none`, insert `none` into the result and continue with the tail of first list. Otherwise, wrap the first element of the second list with `some` and continue with the tails of both lists. Return when either list is empty. Example: ``` list_option_merge [none, some (), none, some ()] [0, 1, 2, 3, 4] = [none, (some 0), none, (some 1)] ``` -/ def list_option_merge {α : Type*} {β : Type*} : list (option α) → list β → list (option β) | [] _ := [] | (none :: xs) ys := none :: list_option_merge xs ys | (some _ :: xs) (y :: ys) := some y :: list_option_merge xs ys | (some _ :: xs) [] := [] @[nolint doc_blame] -- TODO: document meta def to_inductive (cs : list name) (gs : list expr) (s : list (list (option expr) × (expr ⊕ ℕ))) (h : expr) : tactic unit := match s.length with | 0 := induction h >> skip | (n + 1) := do r ← elim_gen_sum n h, focus ((cs.zip (r.zip s)).map $ λ⟨constr_name, h, bs, e⟩, do let n := (bs.filter_map id).length, match e with | sum.inl e := elim_gen_prod (n - 1) h [] [] >> skip | sum.inr 0 := do (hs, h, _) ← elim_gen_prod n h [] [], clear h | sum.inr (e + 1) := do (hs, h, _) ← elim_gen_prod n h [] [], (es, eq, _) ← elim_gen_prod e h [] [], let es := es ++ [eq], /- `es.mmap' subst`: fails when we have dependent equalities (`heq`). `subst` will change the dependent hypotheses, so that the `uniq` local names in `es` are wrong afterwards. Instead we revert them and pull them out one-by-one. -/ revert_lst es, es.mmap' (λ_, intro1 >>= subst) end, ctxt ← local_context, let gs := ctxt.take gs.length, let hs := (ctxt.reverse.take n).reverse, let m := gs.map some ++ list_option_merge bs hs, args ← m.mmap (λa, match a with some v := return v | none := mk_mvar end), c ← mk_const constr_name, exact (c.mk_app args), done), done end end mk_iff namespace tactic open mk_iff /-- `mk_iff_of_inductive_prop i r` makes an `iff` rule for the inductively-defined proposition `i`. The new rule `r` has the shape `∀ps is, i as ↔ ⋁_j, ∃cs, is = cs`, where `ps` are the type parameters, `is` are the indices, `j` ranges over all possible constructors, the `cs` are the parameters for each of the constructors, and the equalities `is = cs` are the instantiations for each constructor for each of the indices to the inductive type `i`. In each case, we remove constructor parameters (i.e. `cs`) when the corresponding equality would be just `c = i` for some index `i`. For example, `mk_iff_of_inductive_prop` on `list.chain` produces: ```lean ∀ {α : Type*} (R : α → α → Prop) (a : α) (l : list α), chain R a l ↔ l = [] ∨ ∃{b : α} {l' : list α}, R a b ∧ chain R b l ∧ l = b :: l' ``` -/ meta def mk_iff_of_inductive_prop (i : name) (r : name) : tactic unit := do e ← get_env, guard (e.is_inductive i), let constrs := e.constructors_of i, let params := e.inductive_num_params i, let indices := e.inductive_num_indices i, let rec := match e.recursor_of i with | some rec := rec | none := i.append `rec end, decl ← get_decl i, let type := decl.type, let univ_names := decl.univ_params, let univs := univ_names.map level.param, /- we use these names for our universe parameters, maybe we should construct a copy of them using `uniq_name` -/ (g, `(Prop)) ← open_pis type | fail "Inductive type is not a proposition", let lhs := (const i univs).mk_app g, shape_rhss ← constrs.mmap (constr_to_prop univs (g.take params) (g.drop params)), let shape := shape_rhss.map prod.fst, let rhss := shape_rhss.map prod.snd, add_theorem_by r univ_names ((mk_iff lhs (mk_or_lst rhss)).pis g) (do gs ← intro_lst (g.map local_pp_name), split, focus' [to_cases shape, intro1 >>= to_inductive constrs (gs.take params) shape]), skip end tactic section setup_tactic_parser /-- `mk_iff_of_inductive_prop i r` makes an `iff` rule for the inductively-defined proposition `i`. The new rule `r` has the shape `∀ps is, i as ↔ ⋁_j, ∃cs, is = cs`, where `ps` are the type parameters, `is` are the indices, `j` ranges over all possible constructors, the `cs` are the parameters for each of the constructors, and the equalities `is = cs` are the instantiations for each constructor for each of the indices to the inductive type `i`. In each case, we remove constructor parameters (i.e. `cs`) when the corresponding equality would be just `c = i` for some index `i`. For example, `mk_iff_of_inductive_prop` on `list.chain` produces: ```lean ∀ {α : Type*} (R : α → α → Prop) (a : α) (l : list α), chain R a l ↔ l = [] ∨ ∃{b : α} {l' : list α}, R a b ∧ chain R b l ∧ l = b :: l' ``` See also the `mk_iff` user attribute. -/ @[user_command] meta def mk_iff_of_inductive_prop_cmd (_ : parse (tk "mk_iff_of_inductive_prop")) : parser unit := do i ← ident, r ← ident, tactic.mk_iff_of_inductive_prop i r add_tactic_doc { name := "mk_iff_of_inductive_prop", category := doc_category.cmd, decl_names := [``mk_iff_of_inductive_prop_cmd], tags := ["logic", "environment"] } /-- Applying the `mk_iff` attribute to an inductively-defined proposition `mk_iff` makes an `iff` rule `r` with the shape `∀ps is, i as ↔ ⋁_j, ∃cs, is = cs`, where `ps` are the type parameters, `is` are the indices, `j` ranges over all possible constructors, the `cs` are the parameters for each of the constructors, and the equalities `is = cs` are the instantiations for each constructor for each of the indices to the inductive type `i`. In each case, we remove constructor parameters (i.e. `cs`) when the corresponding equality would be just `c = i` for some index `i`. For example, if we try the following: ```lean @[mk_iff] structure foo (m n : ℕ) : Prop := (equal : m = n) (sum_eq_two : m + n = 2) ``` Then `#check foo_iff` returns: ```lean foo_iff : ∀ (m n : ℕ), foo m n ↔ m = n ∧ m + n = 2 ``` You can add an optional string after `mk_iff` to change the name of the generated lemma. For example, if we try the following: ```lean @[mk_iff bar] structure foo (m n : ℕ) : Prop := (equal : m = n) (sum_eq_two : m + n = 2) ``` Then `#check bar` returns: ```lean bar : ∀ (m n : ℕ), foo m n ↔ m = n ∧ m + n = 2 ``` See also the user command `mk_iff_of_inductive_prop`. -/ @[user_attribute] meta def mk_iff_attr : user_attribute unit (option name) := { name := `mk_iff, descr := "Generate an `iff` lemma for an inductive `Prop`.", parser := ident?, after_set := some $ λ n _ _, do tgt ← mk_iff_attr.get_param n, tactic.mk_iff_of_inductive_prop n (tgt.get_or_else (n.append_suffix "_iff")) } add_tactic_doc { name := "mk_iff", category := doc_category.attr, decl_names := [`mk_iff_attr], tags := ["logic", "environment"] } end
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.limits.shapes.terminal import category_theory.limits.shapes.binary_products import category_theory.subobject.basic /-! # Subterminal objects Subterminal objects are the objects which can be thought of as subobjects of the terminal object. In fact, the definition can be constructed to not require a terminal object, by defining `A` to be subterminal iff for any `Z`, there is at most one morphism `Z ⟶ A`. An alternate definition is that the diagonal morphism `A ⟶ A ⨯ A` is an isomorphism. In this file we define subterminal objects and show the equivalence of these three definitions. We also construct the subcategory of subterminal objects. ## TODO * Define exponential ideals, and show this subcategory is an exponential ideal. * Use the above to show that in a locally cartesian closed category, every subobject lattice is cartesian closed (equivalently, a Heyting algebra). -/ universes v₁ v₂ u₁ u₂ noncomputable theory namespace category_theory open limits category variables {C : Type u₁} [category.{v₁} C] {A : C} /-- An object `A` is subterminal iff for any `Z`, there is at most one morphism `Z ⟶ A`. -/ def is_subterminal (A : C) : Prop := ∀ ⦃Z : C⦄ (f g : Z ⟶ A), f = g lemma is_subterminal.def : is_subterminal A ↔ ∀ ⦃Z : C⦄ (f g : Z ⟶ A), f = g := iff.rfl /-- If `A` is subterminal, the unique morphism from it to a terminal object is a monomorphism. The converse of `is_subterminal_of_mono_is_terminal_from`. -/ lemma is_subterminal.mono_is_terminal_from (hA : is_subterminal A) {T : C} (hT : is_terminal T) : mono (hT.from A) := { right_cancellation := λ Z g h _, hA _ _ } /-- If `A` is subterminal, the unique morphism from it to the terminal object is a monomorphism. The converse of `is_subterminal_of_mono_terminal_from`. -/ lemma is_subterminal.mono_terminal_from [has_terminal C] (hA : is_subterminal A) : mono (terminal.from A) := hA.mono_is_terminal_from terminal_is_terminal /-- If the unique morphism from `A` to a terminal object is a monomorphism, `A` is subterminal. The converse of `is_subterminal.mono_is_terminal_from`. -/ lemma is_subterminal_of_mono_is_terminal_from {T : C} (hT : is_terminal T) [mono (hT.from A)] : is_subterminal A := λ Z f g, by { rw ← cancel_mono (hT.from A), apply hT.hom_ext } /-- If the unique morphism from `A` to the terminal object is a monomorphism, `A` is subterminal. The converse of `is_subterminal.mono_terminal_from`. -/ lemma is_subterminal_of_mono_terminal_from [has_terminal C] [mono (terminal.from A)] : is_subterminal A := λ Z f g, by { rw ← cancel_mono (terminal.from A), apply subsingleton.elim } lemma is_subterminal_of_is_terminal {T : C} (hT : is_terminal T) : is_subterminal T := λ Z f g, hT.hom_ext _ _ lemma is_subterminal_of_terminal [has_terminal C] : is_subterminal (⊤_ C) := λ Z f g, subsingleton.elim _ _ /-- If `A` is subterminal, its diagonal morphism is an isomorphism. The converse of `is_subterminal_of_is_iso_diag`. -/ lemma is_subterminal.is_iso_diag (hA : is_subterminal A) [has_binary_product A A] : is_iso (diag A) := ⟨⟨limits.prod.fst, ⟨by simp, by { rw is_subterminal.def at hA, tidy }⟩⟩⟩ /-- If the diagonal morphism of `A` is an isomorphism, then it is subterminal. The converse of `is_subterminal.is_iso_diag`. -/ lemma is_subterminal_of_is_iso_diag [has_binary_product A A] [is_iso (diag A)] : is_subterminal A := λ Z f g, begin have : (limits.prod.fst : A ⨯ A ⟶ _) = limits.prod.snd, { simp [←cancel_epi (diag A)] }, rw [←prod.lift_fst f g, this, prod.lift_snd], end /-- If `A` is subterminal, it is isomorphic to `A ⨯ A`. -/ @[simps] def is_subterminal.iso_diag (hA : is_subterminal A) [has_binary_product A A] : A ⨯ A ≅ A := begin letI := is_subterminal.is_iso_diag hA, apply (as_iso (diag A)).symm, end variables (C) /-- The (full sub)category of subterminal objects. TODO: If `C` is the category of sheaves on a topological space `X`, this category is equivalent to the lattice of open subsets of `X`. More generally, if `C` is a topos, this is the lattice of "external truth values". -/ @[derive category] def subterminals (C : Type u₁) [category.{v₁} C] := {A : C // is_subterminal A} instance [has_terminal C] : inhabited (subterminals C) := ⟨⟨⊤_ C, is_subterminal_of_terminal⟩⟩ /-- The inclusion of the subterminal objects into the original category. -/ @[derive [full, faithful], simps] def subterminal_inclusion : subterminals C ⥤ C := full_subcategory_inclusion _ instance subterminals_thin (X Y : subterminals C) : subsingleton (X ⟶ Y) := ⟨λ f g, Y.2 f g⟩ /-- The category of subterminal objects is equivalent to the category of monomorphisms to the terminal object (which is in turn equivalent to the subobjects of the terminal object). -/ @[simps] def subterminals_equiv_mono_over_terminal [has_terminal C] : subterminals C ≌ mono_over (⊤_ C) := { functor := { obj := λ X, ⟨over.mk (terminal.from X.1), X.2.mono_terminal_from⟩, map := λ X Y f, mono_over.hom_mk f (by ext1 ⟨⟩) }, inverse := { obj := λ X, ⟨X.val.left, λ Z f g, by { rw ← cancel_mono X.arrow, apply subsingleton.elim }⟩, map := λ X Y f, f.1 }, unit_iso := { hom := { app := λ X, 𝟙 _ }, inv := { app := λ X, 𝟙 _ } }, counit_iso := { hom := { app := λ X, over.hom_mk (𝟙 _) }, inv := { app := λ X, over.hom_mk (𝟙 _) } } } @[simp] lemma subterminals_to_mono_over_terminal_comp_forget [has_terminal C] : (subterminals_equiv_mono_over_terminal C).functor ⋙ mono_over.forget _ ⋙ over.forget _ = subterminal_inclusion C := rfl @[simp] lemma mono_over_terminal_to_subterminals_comp [has_terminal C] : (subterminals_equiv_mono_over_terminal C).inverse ⋙ subterminal_inclusion C = mono_over.forget _ ⋙ over.forget _ := rfl end category_theory
push!(LOAD_PATH,"../src/") using DickeModel using Documenter,Bibliography using Distributed using Plots ENV["GKSwstype"]="nul" addprocs(2,exeflags=`--project=docs/`) @everywhere push!(LOAD_PATH,"../src/") @everywhere using DickeModel #bib = CitationBibliography(Base.Filesystem.joinpath(@__DIR__,"refs.bib")) include("citations.jl") bib= CitationBibliography(import_bibtex(Base.Filesystem.joinpath(@__DIR__,"refs.bib"))) #Documenter.Selectors.runner(::Type{Documenter.Expanders.ExampleBlocks}, x, page, doc)= (page.mapping[x] = Documents.RawNode(:hey, x.code)) #Documenter.Selectors.runner(::Type{Documenter.Expanders.SetupBlocks}, x, page, doc)= (page.mapping[x] = Documents.RawNode(:hey, x.code)) makedocs(bib, format = Documenter.HTML( prettyurls = get(ENV, "CI", nothing) == "true", assets = ["assets/customcss.css"] ), sitename = "DickeModel.jl", modules = [DickeModel.ClassicalDicke, DickeModel.ClassicalSystems, DickeModel.DickeBCE, DickeModel.UPOs, DickeModel.ClassicalLMG, DickeModel.PhaseSpaces, DickeModel.TWA.Weyl, DickeModel.TWA, DickeModel.EnergyShellProjections], pages=[ "DickeModel.jl" => "index.md", "Examples" => [ "ClassicalDicke" => "ClassicalDickeExamples.md", "DickeBCE (Quantum Dicke)" => "DickeBCEExamples.md", "EnergyShellProjections" => "EnergyShellProjectionsExamples.md", "TWA" => "TWAExamples.md", "UPOs" => "UPOsExamples.md", "ClassicalLMG" => "ClassicalLMGExamples.md", ], "Documentation" => [ "ClassicalDicke" => "ClassicalDicke.md", "DickeBCE" => "DickeBCE.md", "EnergyShellProjections" => "EnergyShellProjections.md", "TWA" => "TWA.md", "UPOs" => "UPOs.md", "ClassicalLMG" => "ClassicalLMG.md", "ClassicalSystems" => "ClassicalSystems.md", "PhaseSpaces" => "PhaseSpaces.md" ], "References" => "references.md" ]) deploydocs(; repo="github.com/saulpila/DickeModel.jl", )
State Before: ι : Sort ?u.12274 α✝ : Type ?u.12277 inst✝¹ : CompleteLattice α✝ f : ι → α✝ α : Type u_1 inst✝ : CompleteLattice α k : α hk : IsCompactElement k s : Set α hemp : Set.Nonempty s hdir : DirectedOn (fun x x_1 => x ≤ x_1) s hbelow : ∀ (x : α), x ∈ s → x < k ⊢ sSup s < k State After: ι : Sort ?u.12274 α✝ : Type ?u.12277 inst✝¹ : CompleteLattice α✝ f : ι → α✝ α : Type u_1 inst✝ : CompleteLattice α k : α hk : ∀ (s : Set α), Set.Nonempty s → DirectedOn (fun x x_1 => x ≤ x_1) s → k ≤ sSup s → ∃ x, x ∈ s ∧ k ≤ x s : Set α hemp : Set.Nonempty s hdir : DirectedOn (fun x x_1 => x ≤ x_1) s hbelow : ∀ (x : α), x ∈ s → x < k ⊢ sSup s < k Tactic: rw [isCompactElement_iff_le_of_directed_sSup_le] at hk State Before: ι : Sort ?u.12274 α✝ : Type ?u.12277 inst✝¹ : CompleteLattice α✝ f : ι → α✝ α : Type u_1 inst✝ : CompleteLattice α k : α hk : ∀ (s : Set α), Set.Nonempty s → DirectedOn (fun x x_1 => x ≤ x_1) s → k ≤ sSup s → ∃ x, x ∈ s ∧ k ≤ x s : Set α hemp : Set.Nonempty s hdir : DirectedOn (fun x x_1 => x ≤ x_1) s hbelow : ∀ (x : α), x ∈ s → x < k ⊢ sSup s < k State After: ι : Sort ?u.12274 α✝ : Type ?u.12277 inst✝¹ : CompleteLattice α✝ f : ι → α✝ α : Type u_1 inst✝ : CompleteLattice α k : α hk : ∀ (s : Set α), Set.Nonempty s → DirectedOn (fun x x_1 => x ≤ x_1) s → k ≤ sSup s → ∃ x, x ∈ s ∧ k ≤ x s : Set α hemp : Set.Nonempty s hdir : DirectedOn (fun x x_1 => x ≤ x_1) s hbelow : ∀ (x : α), x ∈ s → x < k h : ¬sSup s < k ⊢ False Tactic: by_contra h State Before: ι : Sort ?u.12274 α✝ : Type ?u.12277 inst✝¹ : CompleteLattice α✝ f : ι → α✝ α : Type u_1 inst✝ : CompleteLattice α k : α hk : ∀ (s : Set α), Set.Nonempty s → DirectedOn (fun x x_1 => x ≤ x_1) s → k ≤ sSup s → ∃ x, x ∈ s ∧ k ≤ x s : Set α hemp : Set.Nonempty s hdir : DirectedOn (fun x x_1 => x ≤ x_1) s hbelow : ∀ (x : α), x ∈ s → x < k h : ¬sSup s < k ⊢ False State After: ι : Sort ?u.12274 α✝ : Type ?u.12277 inst✝¹ : CompleteLattice α✝ f : ι → α✝ α : Type u_1 inst✝ : CompleteLattice α k : α hk : ∀ (s : Set α), Set.Nonempty s → DirectedOn (fun x x_1 => x ≤ x_1) s → k ≤ sSup s → ∃ x, x ∈ s ∧ k ≤ x s : Set α hemp : Set.Nonempty s hdir : DirectedOn (fun x x_1 => x ≤ x_1) s hbelow : ∀ (x : α), x ∈ s → x < k h : ¬sSup s < k sSup' : sSup s ≤ k ⊢ False Tactic: have sSup' : sSup s ≤ k := sSup_le s k fun s hs => (hbelow s hs).le State Before: ι : Sort ?u.12274 α✝ : Type ?u.12277 inst✝¹ : CompleteLattice α✝ f : ι → α✝ α : Type u_1 inst✝ : CompleteLattice α k : α hk : ∀ (s : Set α), Set.Nonempty s → DirectedOn (fun x x_1 => x ≤ x_1) s → k ≤ sSup s → ∃ x, x ∈ s ∧ k ≤ x s : Set α hemp : Set.Nonempty s hdir : DirectedOn (fun x x_1 => x ≤ x_1) s hbelow : ∀ (x : α), x ∈ s → x < k h : ¬sSup s < k sSup' : sSup s ≤ k ⊢ False State After: ι : Sort ?u.12274 α✝ : Type ?u.12277 inst✝¹ : CompleteLattice α✝ f : ι → α✝ α : Type u_1 inst✝ : CompleteLattice α k : α hk : ∀ (s : Set α), Set.Nonempty s → DirectedOn (fun x x_1 => x ≤ x_1) s → k ≤ SupSet.sSup s → ∃ x, x ∈ s ∧ k ≤ x s : Set α hemp : Set.Nonempty s hdir : DirectedOn (fun x x_1 => x ≤ x_1) s hbelow : ∀ (x : α), x ∈ s → x < k h : ¬SupSet.sSup s < k sSup' : SupSet.sSup s ≤ k sSup : SupSet.sSup s = k ⊢ False Tactic: replace sSup : sSup s = k := eq_iff_le_not_lt.mpr ⟨sSup', h⟩ State Before: ι : Sort ?u.12274 α✝ : Type ?u.12277 inst✝¹ : CompleteLattice α✝ f : ι → α✝ α : Type u_1 inst✝ : CompleteLattice α k : α hk : ∀ (s : Set α), Set.Nonempty s → DirectedOn (fun x x_1 => x ≤ x_1) s → k ≤ SupSet.sSup s → ∃ x, x ∈ s ∧ k ≤ x s : Set α hemp : Set.Nonempty s hdir : DirectedOn (fun x x_1 => x ≤ x_1) s hbelow : ∀ (x : α), x ∈ s → x < k h : ¬SupSet.sSup s < k sSup' : SupSet.sSup s ≤ k sSup : SupSet.sSup s = k ⊢ False State After: case intro.intro ι : Sort ?u.12274 α✝ : Type ?u.12277 inst✝¹ : CompleteLattice α✝ f : ι → α✝ α : Type u_1 inst✝ : CompleteLattice α k : α hk : ∀ (s : Set α), Set.Nonempty s → DirectedOn (fun x x_1 => x ≤ x_1) s → k ≤ SupSet.sSup s → ∃ x, x ∈ s ∧ k ≤ x s : Set α hemp : Set.Nonempty s hdir : DirectedOn (fun x x_1 => x ≤ x_1) s hbelow : ∀ (x : α), x ∈ s → x < k h : ¬SupSet.sSup s < k sSup' : SupSet.sSup s ≤ k sSup : SupSet.sSup s = k x : α hxs : x ∈ s hkx : k ≤ x ⊢ False Tactic: obtain ⟨x, hxs, hkx⟩ := hk s hemp hdir sSup.symm.le State Before: case intro.intro ι : Sort ?u.12274 α✝ : Type ?u.12277 inst✝¹ : CompleteLattice α✝ f : ι → α✝ α : Type u_1 inst✝ : CompleteLattice α k : α hk : ∀ (s : Set α), Set.Nonempty s → DirectedOn (fun x x_1 => x ≤ x_1) s → k ≤ SupSet.sSup s → ∃ x, x ∈ s ∧ k ≤ x s : Set α hemp : Set.Nonempty s hdir : DirectedOn (fun x x_1 => x ≤ x_1) s hbelow : ∀ (x : α), x ∈ s → x < k h : ¬SupSet.sSup s < k sSup' : SupSet.sSup s ≤ k sSup : SupSet.sSup s = k x : α hxs : x ∈ s hkx : k ≤ x ⊢ False State After: case intro.intro ι : Sort ?u.12274 α✝ : Type ?u.12277 inst✝¹ : CompleteLattice α✝ f : ι → α✝ α : Type u_1 inst✝ : CompleteLattice α k : α hk : ∀ (s : Set α), Set.Nonempty s → DirectedOn (fun x x_1 => x ≤ x_1) s → k ≤ SupSet.sSup s → ∃ x, x ∈ s ∧ k ≤ x s : Set α hemp : Set.Nonempty s hdir : DirectedOn (fun x x_1 => x ≤ x_1) s hbelow : ∀ (x : α), x ∈ s → x < k h : ¬SupSet.sSup s < k sSup' : SupSet.sSup s ≤ k sSup : SupSet.sSup s = k x : α hxs : x ∈ s hkx : k ≤ x hxk : x < k ⊢ False Tactic: obtain hxk := hbelow x hxs State Before: case intro.intro ι : Sort ?u.12274 α✝ : Type ?u.12277 inst✝¹ : CompleteLattice α✝ f : ι → α✝ α : Type u_1 inst✝ : CompleteLattice α k : α hk : ∀ (s : Set α), Set.Nonempty s → DirectedOn (fun x x_1 => x ≤ x_1) s → k ≤ SupSet.sSup s → ∃ x, x ∈ s ∧ k ≤ x s : Set α hemp : Set.Nonempty s hdir : DirectedOn (fun x x_1 => x ≤ x_1) s hbelow : ∀ (x : α), x ∈ s → x < k h : ¬SupSet.sSup s < k sSup' : SupSet.sSup s ≤ k sSup : SupSet.sSup s = k x : α hxs : x ∈ s hkx : k ≤ x hxk : x < k ⊢ False State After: no goals Tactic: exact hxk.ne (hxk.le.antisymm hkx)
import numpy as np import pandas as pd import os # !pip install deepswarm import deepswarm import tensorflow.compat.v1 as tf from deepswarm.backends import Dataset, TFKerasBackend from deepswarm.deepswarm import DeepSwarm import cv2 from tqdm import tqdm tf.disable_v2_behavior() def format_images(arr,name): train_images = [] for i in tqdm(arr): img =cv2.imread(i) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img = cv2.resize(img,(512,512)) train_images.append(img) x_train = np.asarray(train_images) np.save(f"{name}.npy",x_train) return x_train def load_images(path): images = np.load(path) return images def preprocess_df(): df = pd.read_csv("../dataset_folds/trainFolds15.csv") df['path'] = df['image'].apply( lambda x: "../resized_train_15/" + x + ".jpg") df['path'] = df['image'].apply(lambda x: "../resized_train_15/" + x + ".jpg") fold_num = 4 level = ['level_0','level_1','level_2','level_3','level_4'] train = df[df['fold'] != fold_num] test = df[df['fold'] == fold_num] """ For Debug train = train.iloc[:100,:] test = test.iloc[200:300,:] """ # x_train = load_images("train.npy") # x_test = load_images("test.npy") x_train = format_images(train['path'].values,"train_512") y_train = train[level].values x_train = x_train.reshape(x_train.shape[0],512,512,3) x_test = format_images(test['path'].values,"test_512") y_test = test[level].values x_test = x_test.reshape(x_test.shape[0],512,512,3) return x_train,y_train,x_test,y_test if __name__ == '__main__': x_train, y_train,x_test, y_test = preprocess_df() dataset = Dataset( training_examples=x_train, training_labels=y_train, testing_examples=x_test, testing_labels=y_test, validation_split=0.3, ) # Create backend responsible for training & validating backend = TFKerasBackend(dataset=dataset) # Create DeepSwarm object responsible for optimization deepswarm = DeepSwarm(backend=backend) # Find the topology for a given dataset topology = deepswarm.find_topology() # Evaluate discovered topology deepswarm.evaluate_topology(topology) # Train topology on augmented data for additional 50 epochs trained_topology = deepswarm.train_topology(topology, 5) # Evaluate the final topology deepswarm.evaluate_topology(trained_topology)
module Issue1232.Fin where data Fin : Set where zero : Fin
Require Import Morphisms Setoid. Require Import Utf8. Add LoadPath "../theories" as CatQ. From CatQ.Structures Require Import Structures. Require Import CatQ.Categories.FunCat. Require Import CatQ.Functors.Bifunctor. Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Set Universe Polymorphism. Program Definition yoneda {C : Category} : Functor C (PSh[C]) := [fmap: fun _ _ f => homFunctor[-,f]n with fun a => (homFunctor[-,a] : PSh[C]) ]. Next Obligation. unfold Proper, respectful. intros. unfold Bifunctor_apply_R. simpl. rewrite H. reflexivity. Defined. Next Obligation. rewrite right_id_of. rewrite left_id_of. reflexivity. Defined. Next Obligation. rewrite right_id_of. rewrite right_id_of. rewrite right_id_of. apply assoc_of. Defined. Program Definition YonedaLemma_right {C : Category} {a : C} {F : PSh[C]} : @morphism PSh[C] (yoneda a) F -⇒ F a := [mapoid: fun yaF => yaF a identity]. Next Obligation. solve_proper. Defined. Program Definition YonedaLemma_left {C : Category} {a : C} {F : PSh[C]} : F a -⇒ @morphism (PSh[C]) (yoneda a) F := [mapoid: fun Fa => [Nat: fun (b : opposite C) => [mapoid: fun (ba : opposite_obj b ⟶ a) => fmap F ba Fa] ] ]. Next Obligation. unfold Proper, respectful. intros. apply mapoid_apply. rewrite H. reflexivity. Defined. Next Obligation. constructor. simpl. intros. refine (`begin (fmap F f) (fmap F x Fa) ↑⟨ Setoids_comp Fa ⟩ (fmap F f ∘ fmap F x) Fa =⟨ _ ⟩ fmap F (f ∘{opposite C} (x ∘{opposite C} identity)) Fa =⟨ _ ⟩ fmap F ((identity ∘ x) ∘ f) Fa `end). - reflexivity. - apply mapoid_apply. rewrite <- fmap_compose. rewrite right_id_of. reflexivity. Defined. Next Obligation. unfold Proper, respectful. simpl. intros. rewrite H. reflexivity. Defined. Lemma Yoneda {C : Category} {a : C} {F : PSh[C]} : @morphism (PSh[C]) (yoneda a) F ≃ F a in Setoids. Proof. refine [iso: (YonedaLemma_right : @hom Setoids _ _) with (YonedaLemma_left : @hom Setoids _ _) ]. constructor. - unfold YonedaLemma_right, YonedaLemma_left. simpl. intros. refine (`begin fmap F x0 ((x a) identity) =⟨ ltac: (apply Setoids_comp; reflexivity) ⟩ (fmap F x0 ∘ x a) identity =⟨ mapoid_apply identity (naturality_of x) ⟩ (x A ∘ fmap (homFunctor[-,a]) x0) identity =⟨ ltac: (apply Setoids_comp; reflexivity) ⟩ (x A) (fmap (homFunctor[-,a]) x0 identity) =⟨ mapoid_cong (x A) hom_refl ⟩ (x A) ((identity ∘ identity) ∘ x0) =⟨ ltac: (rewrite right_id_of; reflexivity) ⟩ (x A) (identity ∘ x0) =⟨ ltac: (rewrite left_id_of; reflexivity) ⟩ (x A) x0 `end). - unfold YonedaLemma_right, YonedaLemma_left. simpl. intros. refine (`begin (fmap F identity) x =⟨ mapoid_apply x (fmap_identity F) ⟩ @identity Setoids _ x =⟨ _ ⟩ x `end). reflexivity. Qed. Program Definition yF {C : Category} {F : PSh[C]} : Functor (opposite C) Setoids := [fmap: fun a b f => [mapoid: fun yaF => yaF ∘ fmap yoneda (opposite_hom f) by _] with fun a => (morphism (yoneda (opposite_obj a)) F : object Setoids)]. Next Obligation. unfold opposite_obj, opposite_hom. solve_proper. Defined. Next Obligation. unfold opposite_obj, opposite_hom. unfold Proper, respectful. simpl. intros. rewrite H. reflexivity. Defined. Next Obligation. unfold opposite_hom. rewrite left_id_of. rewrite right_id_of. reflexivity. Defined. Next Obligation. apply mapoid_cong. rewrite right_id_of. rewrite right_id_of. rewrite right_id_of. simpl. rewrite <- assoc_of. reflexivity. Defined. Program Definition yoneda_lemma_nat {C : Category} {F : PSh[C]} : Nat yF F := [Nat: fun a => @YonedaLemma_right C a F]. Next Obligation. constructor. unfold YonedaLemma_right. simpl. intros. refine (`begin fmap F f (x a identity) =⟨ ltac: (apply Setoids_comp) ⟩ (fmap F f ∘ x a) identity =⟨ ltac: (apply mapoid_apply; apply naturality_of) ⟩ (x b ∘ fmap (homFunctor[-,opposite_obj a]) f) identity =⟨ ltac: (apply Setoids_comp) ⟩ (x b) (fmap (homFunctor[-,opposite_obj a]) f identity) =⟨ mapoid_cong (x b) hom_refl ⟩ x b ((identity ∘{C} identity) ∘{C} opposite_hom f) =⟨ ltac: (rewrite left_id_of; rewrite left_id_of; reflexivity) ⟩ x b (opposite_hom f) ↑⟨ ltac: (rewrite right_id_of; rewrite right_id_of; reflexivity) ⟩ x b ((opposite_hom f ∘{C} identity) ∘{C} identity) `end). Defined. Theorem yoneda_ff {C : Category} : ff (@yoneda C). Proof. unfold ff. intros. generalize (@Yoneda C a (yoneda b)). intro. destruct X as [X1 X2 Xprop]. refine [iso: X2 with X1]. destruct Xprop. constructor. - apply iso_on_right. - apply iso_on_left. Qed. (* Corollary yoneda_ff_on_hom {C : Category} {a b : C} : (natiso : yoneda a x -≃→ yoneda b x) → isomorphic a b *)
from __future__ import print_function from numpy import ndarray, asarray, ufunc, prod from bolt.base import BoltArray from bolt.utils import inshape, tupleize from functools import reduce class BoltArrayLocal(ndarray, BoltArray): def __new__(cls, array): obj = asarray(array).view(cls) obj._mode = 'local' return obj def __array_finalize__(self, obj): if obj is None: return self._mode = getattr(obj, 'mode', None) def __array_wrap__(self, obj): if obj.shape == (): return obj[()] else: return ndarray.__array_wrap__(self, obj) @property def _constructor(self): return BoltArrayLocal def _align(self, axes, key_shape=None): """ Align local bolt array so that axes for iteration are in the keys. This operation is applied before most functional operators. It ensures that the specified axes are valid, and might transpose/reshape the underlying array so that the functional operators can be applied over the correct records. Parameters ---------- axes: tuple[int] One or more axes that will be iterated over by a functional operator Returns ------- BoltArrayLocal """ # ensure that the key axes are valid for an ndarray of this shape inshape(self.shape, axes) # compute the set of dimensions/axes that will be used to reshape remaining = [dim for dim in range(len(self.shape)) if dim not in axes] key_shape = key_shape if key_shape else [self.shape[axis] for axis in axes] remaining_shape = [self.shape[axis] for axis in remaining] linearized_shape = [prod(key_shape)] + remaining_shape # compute the transpose permutation transpose_order = axes + remaining # transpose the array so that the keys being mapped over come first, then linearize keys reshaped = self.transpose(*transpose_order).reshape(*linearized_shape) return reshaped def filter(self, func, axis=(0,)): """ Filter array along an axis. Applies a function which should evaluate to boolean, along a single axis or multiple axes. Array will be aligned so that the desired set of axes are in the keys, which may require a transpose/reshape. Parameters ---------- func : function Function to apply, should return boolean axis : tuple or int, optional, default=(0,) Axis or multiple axes to filter along. Returns ------- BoltArrayLocal """ axes = sorted(tupleize(axis)) reshaped = self._align(axes) filtered = asarray(list(filter(func, reshaped))) return self._constructor(filtered) def map(self, func, axis=(0,)): """ Apply a function across an axis. Array will be aligned so that the desired set of axes are in the keys, which may require a transpose/reshape. Parameters ---------- func : function Function of a single array to apply axis : tuple or int, optional, default=(0,) Axis or multiple axes to apply function along. Returns ------- BoltArrayLocal """ axes = sorted(tupleize(axis)) key_shape = [self.shape[axis] for axis in axes] reshaped = self._align(axes, key_shape=key_shape) mapped = asarray(list(map(func, reshaped))) elem_shape = mapped[0].shape # invert the previous reshape operation, using the shape of the map result linearized_shape_inv = key_shape + list(elem_shape) reordered = mapped.reshape(*linearized_shape_inv) return self._constructor(reordered) def reduce(self, func, axis=0): """ Reduce an array along an axis. Applies an associative/commutative function of two arguments cumulatively to all arrays along an axis. Array will be aligned so that the desired set of axes are in the keys, which may require a transpose/reshape. Parameters ---------- func : function Function of two arrays that returns a single array axis : tuple or int, optional, default=(0,) Axis or multiple axes to reduce along. Returns ------- BoltArrayLocal """ axes = sorted(tupleize(axis)) # if the function is a ufunc, it can automatically handle reducing over multiple axes if isinstance(func, ufunc): inshape(self.shape, axes) reduced = func.reduce(self, axis=tuple(axes)) else: reshaped = self._align(axes) reduced = reduce(func, reshaped) new_array = self._constructor(reduced) # ensure that the shape of the reduced array is valid expected_shape = [self.shape[i] for i in range(len(self.shape)) if i not in axes] if new_array.shape != tuple(expected_shape): raise ValueError("reduce did not yield a BoltArray with valid dimensions") return new_array def first(self): """ Return first element of the array """ return self[0] def concatenate(self, arry, axis=0): """ Join this array with another array. Paramters --------- arry : ndarray or BoltArrayLocal Another array to concatenate with axis : int, optional, default=0 The axis along which arrays will be joined. Returns ------- BoltArrayLocal """ if isinstance(arry, ndarray): from bolt import concatenate return concatenate((self, arry), axis) else: raise ValueError("other must be local array, got %s" % type(arry)) def toscalar(self): """ Returns the single scalar element contained in an array of shape (), if the array has that shape. Returns self otherwise. """ if self.shape == (): return self.toarray().reshape(1)[0] else: return self def tospark(self, sc, axis=0): """ Converts a BoltArrayLocal into a BoltArraySpark Parameters ---------- sc : SparkContext The SparkContext which will be used to create the BoltArraySpark axis : tuple or int, optional, default=0 The axis (or axes) across which this array will be parallelized Returns ------- BoltArraySpark """ from bolt import array return array(self.toarray(), sc, axis=axis) def tordd(self, sc, axis=0): """ Converts a BoltArrayLocal into an RDD Parameters ---------- sc : SparkContext The SparkContext which will be used to create the BoltArraySpark axis : tuple or int, optional, default=0 The axis (or axes) across which this array will be parallelized Returns ------- RDD[(tuple, ndarray)] """ from bolt import array return array(self.toarray(), sc, axis=axis).tordd() def toarray(self): """ Returns the underlying ndarray wrapped by this BoltArrayLocal """ return asarray(self) def display(self): """ Show a pretty-printed representation of this BoltArrayLocal """ print(str(self)) def __repr__(self): return BoltArray.__repr__(self)
Require Export low_mods. Fixpoint REL (alpha : SecOrder) : bool := match alpha with | relatSO _ _ => true | conjSO alpha1 alpha2 => if REL alpha1 then REL alpha2 else false | _ => false end. Lemma REL_conjSO_l : forall rel1 rel2, REL (conjSO rel1 rel2) = true -> REL rel1 = true. Proof. intros rel1 rel2 H. simpl in H. if_then_else_dest_blind; auto. Qed. Lemma REL_conjSO_r : forall rel1 rel2, REL (conjSO rel1 rel2) = true -> REL rel2 = true. Proof. intros rel1 rel2 H. simpl in H. if_then_else_dest_blind; auto. discriminate. Qed. Lemma preds_in_rel : forall rel, REL rel = true -> preds_in rel = nil. Proof. induction rel; intros H; try (simpl in *; discriminate). destruct f; destruct f0; reflexivity. simpl in *. rewrite IHrel1. rewrite IHrel2. reflexivity. apply REL_conjSO_r in H. assumption. apply REL_conjSO_l in H. assumption. Qed. Lemma P_occurs_in_rel : forall rel P, REL rel = true -> ~ Pred_in_SO rel P . Proof. induction rel; intros P Hrel; try discriminate. firstorder. pose proof (REL_conjSO_l _ _ Hrel). pose proof (REL_conjSO_r _ _ Hrel). apply Pred_in_SO_conjSO_f. firstorder. Qed.
(* Title: The pi-calculus Author/Maintainer: Jesper Bengtson (jebe.dk), 2012 *) theory Weak_Early_Cong_Subst_Pres imports Weak_Early_Cong_Subst Weak_Early_Cong_Pres begin lemma weakCongStructCong: fixes P :: pi and Q :: pi assumes "P \<equiv>\<^sub>s Q" shows "P \<simeq>\<^sup>s Q" using assms by(metis earlyCongStructCong strongEqWeakCong) lemma tauPres: fixes P :: pi and Q :: pi assumes "P \<simeq>\<^sup>s Q" shows "\<tau>.(P) \<simeq>\<^sup>s \<tau>.(Q)" using assms by(auto simp add: weakCongruenceSubst_def intro: Weak_Early_Cong_Pres.tauPres) lemma inputPres: fixes P :: pi and Q :: pi and a :: name and x :: name assumes PeqQ: "P \<simeq>\<^sup>s Q" shows "a<x>.P \<simeq>\<^sup>s a<x>.Q" proof(auto simp add: weakCongruenceSubst_def) fix s::"(name \<times> name) list" from congruenceWeakBisim have Input: "\<And>P Q a x s. \<lbrakk>P[<s>] \<simeq>\<^sup>s Q[<s>]; x \<sharp> s\<rbrakk> \<Longrightarrow> (a<x>.P)[<s>] \<simeq> (a<x>.Q)[<s>]" apply(auto simp add: weakCongruenceSubst_def weakCongruence_def) apply(rule Weak_Early_Step_Sim_Pres.inputPres, auto) apply(erule_tac x="[(x, y)]" in allE, auto) apply(rule Weak_Early_Step_Sim_Pres.inputPres, auto) by(erule_tac x="[(x, y)]" in allE, auto) then obtain c::name where cFreshP: "c \<sharp> P" and cFreshQ: "c \<sharp> Q" and cFreshs: "c \<sharp> s" by(force intro: name_exists_fresh[of "(P, Q, s)"]) from PeqQ have "P[<([(x, c)] \<bullet> s)>] \<simeq>\<^sup>s Q[<([(x, c)] \<bullet> s)>]" by(rule partUnfold) hence "([(x, c)] \<bullet> P[<([(x, c)] \<bullet> s)>]) \<simeq>\<^sup>s ([(x, c)] \<bullet> Q[<([(x, c)] \<bullet> s)>])" by(rule Weak_Early_Cong_Subst.eqvtI) hence "([(x, c)] \<bullet> P)[<s>] \<simeq>\<^sup>s ([(x, c)] \<bullet> Q)[<s>]" by simp hence "(a<c>.([(x, c)] \<bullet> P))[<s>] \<simeq> (a<c>.([(x, c)] \<bullet> Q))[<s>]" using cFreshs by(rule Input) moreover from cFreshP cFreshQ have "a<x>.P = a<c>.([(x, c)] \<bullet> P)" and "a<x>.Q = a<c>.([(x, c)] \<bullet> Q)" by(simp add: Agent.alphaInput)+ ultimately show "(a<x>.P)[<s>] \<simeq> (a<x>.Q)[<s>]" by simp qed lemma outputPres: fixes P :: pi and Q :: pi assumes "P \<simeq>\<^sup>s Q" shows "a{b}.P \<simeq>\<^sup>s a{b}.Q" using assms by(auto simp add: weakCongruenceSubst_def intro: Weak_Early_Cong_Pres.outputPres) assumes "P \<simeq>\<^sup>s Q" shows "[a\<frown>b]P \<simeq>\<^sup>s [a\<frown>b]Q" using assms by(auto simp add: weakCongruenceSubst_def intro: Weak_Early_Cong_Pres.matchPres) lemma mismatchPres: fixes P :: pi and Q :: pi and a :: name and b :: name assumes "P \<simeq>\<^sup>s Q" shows "[a\<noteq>b]P \<simeq>\<^sup>s [a\<noteq>b]Q" using assms by(auto simp add: weakCongruenceSubst_def intro: Weak_Early_Cong_Pres.mismatchPres) lemma sumPres: fixes P :: pi and Q :: pi and R :: pi assumes "P \<simeq>\<^sup>s Q" shows "P \<oplus> R \<simeq>\<^sup>s Q \<oplus> R" using assms by(auto simp add: weakCongruenceSubst_def intro: Weak_Early_Cong_Pres.sumPres) lemma parPres: fixes P :: pi and Q :: pi and R :: pi assumes "P \<simeq>\<^sup>s Q" shows "P \<parallel> R \<simeq>\<^sup>s Q \<parallel> R" using assms by(auto simp add: weakCongruenceSubst_def intro: Weak_Early_Cong_Pres.parPres) assumes PeqQ: "P \<simeq>\<^sup>s Q" shows "<\<nu>x>P \<simeq>\<^sup>s <\<nu>x>Q" proof(auto simp add: weakCongruenceSubst_def) fix s::"(name \<times> name) list" have Goal: "\<And>P Q x s. \<lbrakk>P[<s>] \<leadsto>\<guillemotleft>weakBisim\<guillemotright> Q[<s>]; x \<sharp> s\<rbrakk> \<Longrightarrow> (<\<nu>x>P)[<s>] \<leadsto>\<guillemotleft>weakBisim\<guillemotright> (<\<nu>x>Q)[<s>]" by(force intro: Weak_Early_Step_Sim_Pres.resPres Weak_Early_Bisim_Pres.resPres Weak_Early_Bisim.eqvt) then obtain c::name where cFreshP: "c \<sharp> P" and cFreshQ: "c \<sharp> Q" and cFreshs: "c \<sharp> s" by(force intro: name_exists_fresh[of "(P, Q, s)"]) from PeqQ have "P[<([(x, c)] \<bullet> s)>] \<leadsto>\<guillemotleft>weakBisim\<guillemotright> Q[<([(x, c)] \<bullet> s)>]" and "Q[<([(x, c)] \<bullet> s)>] \<leadsto>\<guillemotleft>weakBisim\<guillemotright> P[<([(x, c)] \<bullet> s)>]" by(force simp add: weakCongruenceSubst_def weakCongruence_def)+ hence "([(x, c)] \<bullet> (P[<([(x, c)] \<bullet> s)>])) \<leadsto>\<guillemotleft>weakBisim\<guillemotright> ([(x, c)] \<bullet> (Q[<([(x, c)] \<bullet> s)>]))" and "([(x, c)] \<bullet> (Q[<([(x, c)] \<bullet> s)>])) \<leadsto>\<guillemotleft>weakBisim\<guillemotright> ([(x, c)] \<bullet> (P[<([(x, c)] \<bullet> s)>]))" by(blast intro: Weak_Early_Step_Sim.eqvtI Weak_Early_Bisim.eqvt)+ hence "([(x, c)] \<bullet> P)[<s>] \<leadsto>\<guillemotleft>weakBisim\<guillemotright> ([(x, c)] \<bullet> Q)[<s>]" and "([(x, c)] \<bullet> Q)[<s>] \<leadsto>\<guillemotleft>weakBisim\<guillemotright> ([(x, c)] \<bullet> P)[<s>]" by simp+ with cFreshs have "(<\<nu>c>([(x, c)] \<bullet> P))[<s>] \<leadsto>\<guillemotleft>weakBisim\<guillemotright> (<\<nu>c>([(x, c)] \<bullet> Q))[<s>]" and "(<\<nu>c>([(x, c)] \<bullet> Q))[<s>] \<leadsto>\<guillemotleft>weakBisim\<guillemotright> (<\<nu>c>([(x, c)] \<bullet> P))[<s>]" by(blast intro: Goal)+ moreover from cFreshP cFreshQ have "<\<nu>x>P = <\<nu>c>([(x, c)] \<bullet> P)" and "<\<nu>x>Q = <\<nu>c>([(x, c)] \<bullet> Q)" by(simp add: alphaRes)+ ultimately show "(<\<nu>x>P)[<s>] \<simeq> (<\<nu>x>Q)[<s>]" by(simp add: weakCongruence_def) qed shows "!P \<simeq>\<^sup>s !Q" using assms by(auto simp add: weakCongruenceSubst_def intro: Weak_Early_Cong_Pres.bangPres) end
module Crypto.AES.Common import Utils.ConstantTable import Data.Bits import Data.DPair import Data.Fin import Data.List import Data.Nat import Data.Stream import Data.Vect import Utils.Misc import Utils.Bytes export matmul : Num a => {p : _} -> (op : Vect m a -> Vect m b -> c) -> Vect n (Vect m a) -> Vect m (Vect p b) -> Vect n (Vect p c) matmul op [] ys = [] matmul op (x :: xs) ys = map (op x) (transpose ys) :: matmul op xs ys export vecxor : Bits a => Vect n a -> Vect n a -> Vect n a vecxor = zipWith xor export matxor : Bits a => Vect n (Vect m a) -> Vect n (Vect m a) -> Vect n (Vect m a) matxor x y = zipWith vecxor x y export sbox : ConstantTable 256 Bits8 sbox = from_vect [ 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76 , 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0 , 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15 , 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75 , 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84 , 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf , 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8 , 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2 , 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73 , 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb , 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79 , 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08 , 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a , 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e , 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf , 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 ] export inv_sbox : ConstantTable 256 Bits8 inv_sbox = from_vect [ 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb , 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb , 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e , 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25 , 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92 , 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84 , 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06 , 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b , 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73 , 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e , 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b , 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4 , 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f , 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef , 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61 , 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d ] export sub_byte : Bits8 -> Bits8 sub_byte x = index_bits8 x sbox export inv_sub_byte : Bits8 -> Bits8 inv_sub_byte x = index_bits8 x inv_sbox export sub_word : Vect m Bits8 -> Vect m Bits8 sub_word = map sub_byte export inv_sub_word : Vect m Bits8 -> Vect m Bits8 inv_sub_word = map inv_sub_byte export sub_bytes : Vect n (Vect m Bits8) -> Vect n (Vect m Bits8) sub_bytes = map sub_word export inv_sub_bytes : Vect n (Vect m Bits8) -> Vect n (Vect m Bits8) inv_sub_bytes = map inv_sub_word export rot_word : {n : Nat} -> Nat -> Vect (S n) a -> Vect (S n) a rot_word k = take (S n) . drop k . cycle export inv_rot_word : {n : Nat} -> Nat -> Vect (S n) a -> Vect (S n) a inv_rot_word k = take (S n) . drop (n * k) . cycle export rcons : Stream Bits8 rcons = go 1 where go : Bits8 -> Stream Bits8 go x = x :: go ((if x < 0x80 then id else xor (0x1B)) $ 2 * x) export expand_key' : {n_k, n_b : _} -> {auto 0 ok : NonZero n_b} -> Fin n_k -> (rcs : Stream Bits8) -> (prev_block : Vect n_k (Vect n_b Bits8)) -> Stream (Vect n_b Bits8) expand_key' {n_b = S n_b'} counter (rc :: rcs) (x :: xs) = let y = last (x :: xs) in case counter of FZ => let z = (vecxor (rc :: replicate _ 0) $ vecxor x $ sub_word $ rot_word 1 $ y) in z :: expand_key' Data.Fin.last rcs (snoc xs z) (FS counter') => let z = vecxor x $ case isLT 6 n_k of Yes wit => if finToNat (FS counter') == 4 then sub_word y else y No contra => y in z :: expand_key' (weaken counter') (rc :: rcs) (snoc xs z) export expand_key : {n_k, n_b : _} -> {auto 0 ok : NonZero n_b} -> {auto 0 ok2 : NonZero n_k} -> Vect n_k (Vect n_b Bits8) -> Stream (Vect n_b Bits8) expand_key {n_k = S n_k'} k = expand_key' FZ rcons k public export data Mode : Type where AES128 : Mode AES192 : Mode AES256 : Mode public export get_n_k : Mode -> Nat get_n_k AES128 = 4 get_n_k AES192 = 6 get_n_k AES256 = 8 public export n_k_never_Z : (mode : _) -> NonZero (get_n_k mode) n_k_never_Z AES128 = SIsNonZero n_k_never_Z AES192 = SIsNonZero n_k_never_Z AES256 = SIsNonZero public export get_main_rounds : Mode -> Nat get_main_rounds AES128 = 9 get_main_rounds AES192 = 11 get_main_rounds AES256 = 13
# Quantum State Fidelity Date : December 15, 2021 This notebook contains material supporting a paper, currently titled *Five Starter Pieces: Quantum Information Science via Semi-definite Programs*, by Vikesh Siddhu ([email protected]) and Sridhar Tayur ([email protected]). The paper is available on this **[arXiv](http://arxiv.org/abs/2112.08276)** link. The arXiv paper is released there is under the **[arXiv.org perpetual, non-exclusive license](https://arxiv.org/licenses/nonexclusive-distrib/1.0/license.html)**, and this code is released under the **[MIT license](https://opensource.org/licenses/MIT)**. This notebook depends upon various packages including [numpy](https://numpy.org/) >= 1.19.5, [picos](https://picos-api.gitlab.io/picos/index.html) >= 2.2.55, and [cvxopt](http://cvxopt.org/) >= 1.2.5. [](https://colab.research.google.com/github/vsiddhu/SDP-Quantum-OR/blob/master/Notebook%202%20-%20Quantum%20State%20Fidelity.ipynb) ### Introduction Fidelity between two density operators $\rho$ and $\sigma$, $$ F(\rho,\sigma) = || \sqrt{\rho} \sqrt{\sigma}||_1,$$ is the optimum value of the semi-definite program (SDP) \begin{align} \begin{aligned} \text{maximize} \; & \frac{1}{2} \; \rm Tr(\Lambda + \Lambda^{\dagger}), \\ \text{subject to} \; & \begin{pmatrix} \rho & \Lambda \\ \Lambda^{\dagger} & \sigma \end{pmatrix} \succeq 0, & \end{aligned} \end{align} where $\Lambda$ is a linear operator. The SDP above has a dual formulation, \begin{align} \begin{aligned} \text{minimize} \; & \frac{1}{2} \; \big( \rm Tr(\rho Y) + \rm Tr( \sigma Z) \big), \\ \text{subject to} \; & \begin{pmatrix} Y & -I\\ -I & Z \end{pmatrix} \succeq 0, & \end{aligned} \end{align} where $I$ is the Identity matrix. ```python %pylab inline ``` Populating the interactive namespace from numpy and matplotlib ```python # For Google Colab use commands installing packages try: import google.colab IN_COLAB = True except: IN_COLAB = False # Install PICOS and CVXOPT in Google Colab if IN_COLAB: !pip install -q picos !pip install -q cvxopt ``` ```python import picos as pic import cvxopt as cvx ``` ```python print('Solvers supported on this installation of picos:', pic.solvers.all_solvers().keys()) ``` Solvers supported on this installation of picos: dict_keys(['cplex', 'cvxopt', 'ecos', 'glpk', 'gurobi', 'mosek', 'mskfsn', 'scip', 'smcp']) ```python print('Solvers available to picos on this machine :', pic.solvers.available_solvers()) ``` Solvers available to picos on this machine : ['cvxopt', 'mosek', 'mskfsn'] ### Example 1 Fidelity $F(\rho_2,\sigma_2)$ between $d$-dimensional random pure state density operators $\rho_2 = | \psi \rangle \langle \psi |$ and $\sigma_2 = | \phi \rangle \langle \phi |$ can be computed using both the Primal and Dual SDP formulations stated at the for of this notebook. ```python #Example 1 d= 4 mt1 = np.random.rand(d,1) + 1j*np.random.randn(d,1) mt1 = np.dot(mt1,mt1.conj().T) rho1 = mt1/np.trace(mt1) mt2 = np.random.rand(d,1) + 1j*np.random.randn(d,1) mt2 = np.dot(mt2,mt2.conj().T) sig1 = mt2/np.trace(mt2) ``` ```python #Primal SDP #Constants #---------- rhoPic1 = pic.Constant("rho", rho1) sigmaPic1 = pic.Constant("sigma", sig1) #Variables #---------- shp1 = np.shape(rho1) lmPic1 = pic.ComplexVariable("Lm", shp1) prob1 = pic.Problem() #Constraint #---------- prob1.add_constraint(((rhoPic1 & lmPic1) // (lmPic1.H & sigmaPic1)) >> 0) #Objective #---------- obj1 = pic.trace(lmPic1 + lmPic1.H)*0.5 prob1.set_objective('max',obj1) ``` ```python #User readable view of the problem being composed in PICOS print(prob1) ``` ----------------------------- Complex Semidefinite Program maximize tr(Lm + Lmᴴ)·0.5 over 4×4 complex variable Lm subject to [rho, Lm; Lmᴴ, sigma] ≽ 0 ----------------------------- ```python #Solve the problem using cvxopt as a solver prob1.solve(verbosity=False,solver='cvxopt') ``` <primal feasible solution pair (claimed optimal) from cvxopt> ```python #Solver claims to have found optimal solution fid1 = prob1.value ``` ```python #Dual SDP #Constants #---------- rhoD1 = pic.Constant("rho", rho1) sigmaD1 = pic.Constant("sigma", sig1) shp1 = np.shape(rho1) iMat = pic.Constant('I', np.eye(shp1[0])) #Variables #---------- AD = pic.HermitianVariable("A", shp1) BD = pic.HermitianVariable("B", shp1) prob1D = pic.Problem() #Constraint #---------- prob1D.add_constraint(((AD & -iMat) // (-iMat & BD)) >> 0) #Objective #---------- obj1D = .5*(rhoD1 | AD).real + .5*(sigmaD1 | BD).real prob1D.set_objective('min',obj1D) ``` ```python #User readable view of the problem being composed in PICOS print(prob1D) ``` ------------------------------------------------ Complex Semidefinite Program minimize 0.5·Re(⟨rho, A⟩) + 0.5·Re(⟨sigma, B⟩) over 4×4 hermitian variable A, B subject to [A, -I; -I, B] ≽ 0 ------------------------------------------------ ```python #Solve the problem using mosek as a cvxopt prob1D.solve(verbosity=False,solver='cvxopt') ``` <primal feasible solution pair (claimed optimal) from cvxopt> ```python #Solver claims to have found optimal solution fid1D = prob1D.value ``` $F(\rho_2,\sigma_2)$ between pure state density operators $\rho_2 = | \psi \rangle \langle \psi |$ and $\sigma_2 = | \phi \rangle \langle \phi |$ is simply given by \begin{equation} F(\rho_2,\sigma_2) = \sqrt{ \rm Tr (\rho_2 \sigma_2) } = |\langle \psi | \phi \rangle|. \end{equation} ```python #Compute fidelity using the formula above fid1Alg = np.sqrt(np.trace(np.dot(rho1,sig1)).real) ``` ```python print('Fidelity between two random pure states') print('Using Primal SDP = ', fid1) print('Using DualSDP = ', fid1D) print('Using Numpy', fid1Alg) diffMx1 = max(abs(fid1 - fid1D),abs(fid1 - fid1Alg),abs(fid1D - fid1Alg)) print('Maximum difference between any pair of values above =', diffMx1) ``` Fidelity between two random pure states Using Primal SDP = 0.18015900161366682 Using DualSDP = 0.18015900229617843 Using Numpy 0.1801590015472587 Maximum difference between any pair of values above = 7.489197317855911e-10 ### Example 2 Fidelity $F(\rho_2,\sigma_2)$ between a $d$-dimensional random pure state density operators $\rho_2 = | \psi \rangle \langle \psi |$ and a random mixed state $\sigma_2$. ```python #Example 2 d = 3 mtE2 = np.random.rand(d,1) + 1j*np.random.randn(d,1) mtE2 = np.dot(mtE2,mtE2.conj().T) rho2 = mtE2/np.trace(mtE2) mt2E2 = np.random.rand(d,d) + 1j*np.random.randn(d,d) mt2E2 = np.dot(mt2E2,mt2E2.conj().T) sig2 = mt2E2/np.trace(mt2E2) ``` ```python #Primal SDP #Constants #---------- rho2Pic = pic.Constant("rho2", rho2) sigma2Pic = pic.Constant("sigma2", sig2) #Variables #---------- shp2 = np.shape(rho2) lm2Pic = pic.ComplexVariable("Lm2", shp2) prob2 = pic.Problem() #Constraint #---------- prob2.add_constraint(((rho2Pic & lm2Pic) // (lm2Pic.H & sigma2Pic)) >> 0) #Objective #---------- obj2 = pic.trace(lm2Pic + lm2Pic.H)*0.5 prob2.set_objective('max',obj2) ``` ```python #User readable view of the problem being composed in PICOS print(prob2) ``` --------------------------------- Complex Semidefinite Program maximize tr(Lm2 + Lm2ᴴ)·0.5 over 3×3 complex variable Lm2 subject to [rho2, Lm2; Lm2ᴴ, sigma2] ≽ 0 --------------------------------- ```python #Solve the problem using mosek as a solver prob2.solve(verbosity=False,solver='mosek') ``` <primal feasible solution pair (claimed optimal) from mosek> ```python #Solver claims to have found optimal solution fid2 = prob2.value ``` ```python #Constants #---------- rhoD2 = pic.Constant("rho2", rho2) sigmaD2 = pic.Constant("sigma2", sig2) shp2 = np.shape(rho2) iMat = pic.Constant('I', np.eye(shp2[0])) #Variables #---------- A2D = pic.HermitianVariable("A2", shp2) B2D = pic.HermitianVariable("B2", shp2) prob2D = pic.Problem() #Constraint #---------- prob2D.add_constraint(((A2D & -iMat) // (-iMat & B2D)) >> 0) #Objective #---------- obj2D = .5*(rhoD2 | A2D).real + .5*(sigmaD2 | B2D).real prob2D.set_objective('min',obj2D) ``` ```python #User readable view of the problem being composed in PICOS' print(prob2D) ``` ---------------------------------------------------- Complex Semidefinite Program minimize 0.5·Re(⟨rho2, A2⟩) + 0.5·Re(⟨sigma2, B2⟩) over 3×3 hermitian variable A2, B2 subject to [A2, -I; -I, B2] ≽ 0 ---------------------------------------------------- ```python #Solve the problem using mosek as a solver prob2D.solve(verbosity=False,solver='mosek') ``` <primal feasible solution pair (claimed optimal) from mosek> ```python #Solver claims to have found optimal solution fid2D = prob2D.value ``` $F(\rho_3,\sigma_3)$ between the pure state density operator $\rho_3 = | \psi \rangle \langle \psi |$ and mixed state $\sigma_3$ is simply given by \begin{equation} F(\rho_3,\sigma_3) = \sqrt{ \langle \psi|\sigma_3|\psi \rangle} = \sqrt{ \rm Tr (\rho_3 \sigma_3) } \end{equation} ```python #Compute fidelity using the formula above fid2Alg = np.sqrt(np.trace(np.dot(rho2,sig2)).real) ``` ```python print('Fidelity between two random states, one pure and another mixed') print('Using Primal SDP = ', fid2) print('Using DualSDP = ', fid2D) print('Using Numpy', fid2Alg) diffMx1 = max(abs(fid2 - fid2D),abs(fid2 - fid2Alg),abs(fid2D - fid2Alg)) print('Maximum difference between any pair of values above =', diffMx1) ``` Fidelity between two random states, one pure and another mixed Using Primal SDP = 0.40275233796048393 Using DualSDP = 0.4028013483991454 Using Numpy 0.40272188430512085 Maximum difference between any pair of values above = 7.946409402453947e-05 ### Example 3 Fidelity $F(\rho_3,\sigma_3)$ between two $d$-dimensional random density operators $\rho_3$ and $\sigma_3$ is calculated using both primal and dual SDP formulations stated at the top of this notebook. ```python #Example 3 using the primal formulation d = 10 mtE3 = np.random.rand(d,d) + 1j*np.random.randn(d,d) mtE3 = np.dot(mtE3,mtE3.conj().T) rho3 = mtE3/np.trace(mtE3) mt2E3 = np.random.rand(d,d) + 1j*np.random.randn(d,d) mt2E3 = np.dot(mt2E3,mt2E3.conj().T) sig3 = mt2E3/np.trace(mt2E3) ``` ```python #Constants #---------- rho3Pic = pic.Constant("rho3", rho3) sigma3Pic = pic.Constant("sigma3", sig3) #Variables #---------- shp3 = np.shape(rho3) lm3Pic = pic.ComplexVariable("Lm3", shp3) prob3 = pic.Problem() #Constraint #---------- prob3.add_constraint(((rho3Pic & lm3Pic) // (lm3Pic.H & sigma3Pic)) >> 0) #Objective #---------- obj3 = pic.trace(lm3Pic + lm3Pic.H)*0.5 prob3.set_objective('max',obj3) ``` ```python #User readable view of the problem being composed in PICOS' print(prob3) ``` --------------------------------- Complex Semidefinite Program maximize tr(Lm3 + Lm3ᴴ)·0.5 over 10×10 complex variable Lm3 subject to [rho3, Lm3; Lm3ᴴ, sigma3] ≽ 0 --------------------------------- ```python #Solve the problem using mosek as a solver prob3.solve(verbosity=False,solver='mosek') ``` <primal feasible solution pair (claimed optimal) from mosek> ```python #Solver claims to have found optimal solution fid3 = prob3.value ``` ```python #Solve the same problem using the Dual Formulation ``` ```python #Constants #---------- iMat = pic.Constant('I', np.eye(shp3[0])) #Variables #---------- A3D = pic.HermitianVariable("A3", shp3) B3D = pic.HermitianVariable("B3", shp3) prob3D = pic.Problem() #Constraint #---------- prob3D.add_constraint(((A3D & -iMat) // (-iMat & B3D)) >> 0) #Objective #---------- obj3D = .5*(rho3Pic | A3D).real + .5*(sigma3Pic | B3D).real prob3D.set_objective('min',obj3D) ``` ```python #User readable view of the problem being composed in PICOS' print(prob3D) ``` ---------------------------------------------------- Complex Semidefinite Program minimize 0.5·Re(⟨rho3, A3⟩) + 0.5·Re(⟨sigma3, B3⟩) over 10×10 hermitian variable A3, B3 subject to [A3, -I; -I, B3] ≽ 0 ---------------------------------------------------- ```python #Solve the problem using mosek as a solver prob3D.solve(verbosity=False,solver='mosek') ``` <primal feasible solution pair (claimed optimal) from mosek> ```python #Solver claims to have found optimal solution fid3D = prob3D.value ``` The Fidelity between two mixed states $\rho_3$ and $\sigma_3$ is given by $$ F(\rho_3,\sigma_4) = || \sqrt{\rho_3} \sqrt{\sigma_3}||_1,$$ ```python #Calculate the Fidelity using the usual route via NumPy Libraries diag1,U = np.linalg.eigh(rho3) sqRho3 = np.dot(np.dot(U, np.diag(np.sqrt(diag1))), U.conj().T) # Square root of rho3. diag2,V = np.linalg.eigh(sig3) sqSig3 = np.dot(np.dot(V, np.diag(np.sqrt(diag2))), V.conj().T) # Square root of sig3. fid3Alg = sum(np.linalg.svd( np.dot(sqRho3, sqSig3) )[1] ) # Trace-norm of sqrt(P)·sqrt(Q). ``` ```python print('Fidelity between two random mixed states') print('Using Primal SDP = ', fid3) print('Using DualSDP = ', fid3D) print('Using Numpy', fid3Alg) diffMx1 = max(abs(fid3 - fid3D),abs(fid3 - fid3Alg),abs(fid3D - fid3Alg)) print('Maximum difference between any pair of values above =', diffMx1) ``` Fidelity between two random mixed states Using Primal SDP = 0.7599657404167818 Using DualSDP = 0.7599659619497257 Using Numpy 0.7599656910322277 Maximum difference between any pair of values above = 2.709174979909079e-07 ```python ```
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import tactic.monotonicity import tactic.norm_num import algebra.order.ring import measure_theory.measure.lebesgue import data.list.defs open list tactic tactic.interactive set example (h : 3 + 6 ≤ 4 + 5) : 1 + 3 + 2 + 6 ≤ 4 + 2 + 1 + 5 := begin ac_mono, end example (h : 3 ≤ (4 : ℤ)) (h' : 5 ≤ (6 : ℤ)) : (1 + 3 + 2) - 6 ≤ (4 + 2 + 1 : ℤ) - 5 := begin ac_mono, mono, end example (h : 3 ≤ (4 : ℤ)) (h' : 5 ≤ (6 : ℤ)) : (1 + 3 + 2) - 6 ≤ (4 + 2 + 1 : ℤ) - 5 := begin transitivity (1 + 3 + 2 - 5 : ℤ), { ac_mono }, { ac_mono }, end example (x y z k : ℤ) (h : 3 ≤ (4 : ℤ)) (h' : z ≤ y) : (k + 3 + x) - y ≤ (k + 4 + x) - z := begin mono, norm_num end example (x y z a b : ℤ) (h : a ≤ (b : ℤ)) (h' : z ≤ y) : (1 + a + x) - y ≤ (1 + b + x) - z := begin transitivity (1 + a + x - z), { mono, }, { mono, mono, mono }, end example (x y z : ℤ) (h' : z ≤ y) : (1 + 3 + x) - y ≤ (1 + 4 + x) - z := begin transitivity (1 + 3 + x - z), { mono }, { mono, mono, norm_num }, end example (x y z : ℤ) (h : 3 ≤ (4 : ℤ)) (h' : z ≤ y) : (1 + 3 + x) - y ≤ (1 + 4 + x) - z := begin ac_mono, mono* end @[simp] def list.le' {α : Type*} [has_le α] : list α → list α → Prop | (x::xs) (y::ys) := x ≤ y ∧ list.le' xs ys | [] [] := true | _ _ := false @[simp] instance list_has_le {α : Type*} [has_le α] : has_le (list α) := ⟨ list.le' ⟩ lemma list.le_refl {α : Type*} [preorder α] {xs : list α} : xs ≤ xs := begin induction xs with x xs, { trivial }, { simp [has_le.le,list.le], split, exact le_rfl, apply xs_ih } end -- @[trans] lemma list.le_trans {α : Type*} [preorder α] {xs zs : list α} (ys : list α) (h : xs ≤ ys) (h' : ys ≤ zs) : xs ≤ zs := begin revert ys zs, induction xs with x xs ; intros ys zs h h' ; cases ys with y ys ; cases zs with z zs ; try { cases h ; cases h' ; done }, { apply list.le_refl }, { simp [has_le.le,list.le], split, apply le_trans h.left h'.left, apply xs_ih _ h.right h'.right, } end @[mono] lemma list_le_mono_left {α : Type*} [preorder α] {xs ys zs : list α} (h : xs ≤ ys) : xs ++ zs ≤ ys ++ zs := begin revert ys, induction xs with x xs ; intros ys h, { cases ys, apply list.le_refl, cases h }, { cases ys with y ys, cases h, simp [has_le.le,list.le] at *, revert h, apply and.imp_right, apply xs_ih } end @[mono] lemma list_le_mono_right {α : Type*} [preorder α] {xs ys zs : list α} (h : xs ≤ ys) : zs ++ xs ≤ zs ++ ys := begin revert ys zs, induction xs with x xs ; intros ys zs h, { cases ys, { simp, apply list.le_refl }, cases h }, { cases ys with y ys, cases h, simp [has_le.le,list.le] at *, suffices : list.le' ((zs ++ [x]) ++ xs) ((zs ++ [y]) ++ ys), { refine cast _ this, simp, }, apply list.le_trans (zs ++ [y] ++ xs), { apply list_le_mono_left, induction zs with z zs, { simp [has_le.le,list.le], apply h.left }, { simp [has_le.le,list.le], split, exact le_rfl, apply zs_ih, } }, { apply xs_ih h.right, } } end lemma bar_bar' (h : [] ++ [3] ++ [2] ≤ [1] ++ [5] ++ [4]) : [] ++ [3] ++ [2] ++ [2] ≤ [1] ++ [5] ++ ([4] ++ [2]) := begin ac_mono, end lemma bar_bar'' (h : [3] ++ [2] ++ [2] ≤ [5] ++ [4] ++ []) : [1] ++ ([3] ++ [2]) ++ [2] ≤ [1] ++ [5] ++ ([4] ++ []) := begin ac_mono, end lemma bar_bar (h : [3] ++ [2] ≤ [5] ++ [4]) : [1] ++ [3] ++ [2] ++ [2] ≤ [1] ++ [5] ++ ([4] ++ [2]) := begin ac_mono, end def P (x : ℕ) := 7 ≤ x def Q (x : ℕ) := x ≤ 7 @[mono] lemma P_mono {x y : ℕ} (h : x ≤ y) : P x → P y := by { intro h', apply le_trans h' h } @[mono] lemma Q_mono {x y : ℕ} (h : y ≤ x) : Q x → Q y := by apply le_trans h example (x y z : ℕ) (h : x ≤ y) : P (x + z) → P (z + y) := begin ac_mono, ac_mono, end example (x y z : ℕ) (h : y ≤ x) : Q (x + z) → Q (z + y) := begin ac_mono, ac_mono, end example (x y z k m n : ℤ) (h₀ : z ≤ 0) (h₁ : y ≤ x) : (m + x + n) * z + k ≤ z * (y + n + m) + k := begin ac_mono, ac_mono, ac_mono, end example (x y z k m n : ℕ) (h₀ : z ≥ 0) (h₁ : x ≤ y) : (m + x + n) * z + k ≤ z * (y + n + m) + k := begin ac_mono, ac_mono, ac_mono, end example (x y z k m n : ℕ) (h₀ : z ≥ 0) (h₁ : x ≤ y) : (m + x + n) * z + k ≤ z * (y + n + m) + k := begin ac_mono, -- ⊢ (m + x + n) * z ≤ z * (y + n + m) ac_mono, -- ⊢ m + x + n ≤ y + n + m ac_mono, end example (x y z k m n : ℕ) (h₀ : z ≥ 0) (h₁ : x ≤ y) : (m + x + n) * z + k ≤ z * (y + n + m) + k := by { ac_mono* := h₁ } example (x y z k m n : ℕ) (h₀ : z ≥ 0) (h₁ : m + x + n ≤ y + n + m) : (m + x + n) * z + k ≤ z * (y + n + m) + k := by { ac_mono* := h₁ } example (x y z k m n : ℕ) (h₀ : z ≥ 0) (h₁ : n + x + m ≤ y + n + m) : (m + x + n) * z + k ≤ z * (y + n + m) + k := begin ac_mono* : m + x + n ≤ y + n + m, transitivity ; [ skip , apply h₁ ], apply le_of_eq, ac_refl, end example (x y z k m n : ℤ) (h₁ : x ≤ y) : true := begin have : (m + x + n) * z + k ≤ z * (y + n + m) + k, { ac_mono, success_if_fail { ac_mono }, admit }, trivial end example (x y z k m n : ℕ) (h₁ : x ≤ y) : true := begin have : (m + x + n) * z + k ≤ z * (y + n + m) + k, { ac_mono*, change 0 ≤ z, apply nat.zero_le, }, trivial end example (x y z k m n : ℕ) (h₁ : x ≤ y) : true := begin have : (m + x + n) * z + k ≤ z * (y + n + m) + k, { ac_mono, change (m + x + n) * z ≤ z * (y + n + m), admit }, trivial, end example (x y z k m n i j : ℕ) (h₁ : x + i = y + j) : (m + x + n + i) * z + k = z * (j + n + m + y) + k := begin ac_mono^3, cc end example (x y z k m n i j : ℕ) (h₁ : x + i = y + j) : z * (x + i + n + m) + k = z * (y + j + n + m) + k := begin congr, simp [h₁], end example (x y z k m n i j : ℕ) (h₁ : x + i = y + j) : (m + x + n + i) * z + k = z * (j + n + m + y) + k := begin ac_mono*, cc, end example (x y : ℕ) (h : x ≤ y) : true := begin (do v ← mk_mvar, p ← to_expr ```(%%v + x ≤ y + %%v), assert `h' p), ac_mono := h, trivial, exact 1, end example {x y z : ℕ} : true := begin have : y + x ≤ y + z, { mono, guard_target' x ≤ z, admit }, trivial end example {x y z : ℕ} : true := begin suffices : x + y ≤ z + y, trivial, mono, guard_target' x ≤ z, admit, end example {x y z w : ℕ} : true := begin have : x + y ≤ z + w, { mono, guard_target' x ≤ z, admit, guard_target' y ≤ w, admit }, trivial end example {x y z w : ℕ} : true := begin have : x * y ≤ z * w, { mono with [0 ≤ z,0 ≤ y], { guard_target 0 ≤ z, admit }, { guard_target 0 ≤ y, admit }, guard_target' x ≤ z, admit, guard_target' y ≤ w, admit }, trivial end example {x y z w : Prop} : true := begin have : x ∧ y → z ∧ w, { mono, guard_target' x → z, admit, guard_target' y → w, admit }, trivial end example {x y z w : Prop} : true := begin have : x ∨ y → z ∨ w, { mono, guard_target' x → z, admit, guard_target' y → w, admit }, trivial end example {x y z w : ℤ} : true := begin suffices : x + y < w + z, trivial, have : x < w, admit, have : y ≤ z, admit, mono right, end example {x y z w : ℤ} : true := begin suffices : x * y < w * z, trivial, have : x < w, admit, have : y ≤ z, admit, mono right, { guard_target' 0 < y, admit }, { guard_target' 0 ≤ w, admit }, end open tactic example (x y : ℕ) (h : x ≤ y) : true := begin (do v ← mk_mvar, p ← to_expr ```(%%v + x ≤ y + %%v), assert `h' p), ac_mono := h, trivial, exact 3 end example {α} [linear_order α] (a b c d e : α) : max a b ≤ e → b ≤ e := by { mono, apply le_max_right } example (a b c d e : Prop) (h : d → a) (h' : c → e) : (a ∧ b → c) ∨ d → (d ∧ b → e) ∨ a := begin mono, mono, mono, end example : ∫ x in Icc 0 1, real.exp x ≤ ∫ x in Icc 0 1, real.exp (x+1) := begin mono, { exact real.continuous_exp.integrable_on_compact is_compact_Icc }, { exact (real.continuous_exp.comp $ continuous_add_right 1).integrable_on_compact is_compact_Icc }, intro x, dsimp only, mono, linarith end
#' @title US farmers markets #' @description Dataset of all farmers markets in the US #' @format A data frame with 8788 rows and 9 variables: #' \describe{ #' \item{\code{FMID}}{integer Unique Farmers Market ID} #' \item{\code{MarketName}}{character Name of Farmers Market} #' \item{\code{street}}{character Street} #' \item{\code{city}}{character City} #' \item{\code{County}}{character County} #' \item{\code{State}}{integer State} #' \item{\code{zip}}{character zip code} #' \item{\code{x}}{double longitude} #' \item{\code{y}}{double latitude} #'} #' @details Dataset which includes the location and ID for every Farmers Market in the US #' @docType data #' @keywords datasets #' @name farmers_markets #' @usage farmers_markets #' @source \href{https://apps.ams.usda.gov/FarmersMarketsExport/ExcelExport.aspx}{https://apps.ams.usda.gov/FarmersMarketsExport/ExcelExport.aspx} #' @examples #' summary(farmers_markets) NULL
module DecEqTest import Language.Elab.Deriving.DecEq import Decidable.Equality %language ElabReflection data Flippy = Dolphin | Shark %runElab deriveDecEq Export `{{Flippy}} export data Foo1 : Type -> Type where Bor1 : Foo1 a export data Foo2 : Type -> Type where Bor2 : a -> Foo2 a data Foo4 : Type -> Type -> Type where Bor4 : b -> Foo4 a b data Foo5 : Type -> Type -> Type -> Type where Bor5 : a -> b -> c -> Foo5 a b c -- NB c is never used, so Eq shouldn't be required for it data Foo7 : Type -> Type -> Type -> Type where Zor7 : a -> Foo7 a b c Gor7 : b -> Foo7 a b c Nor7A : a -> b -> Foo7 a b c Nor7B : a -> b -> c -> Foo7 a b c Bor7 : Foo7 a b c -- NB a is never used, so Eq shouldn't be required for it data Foo7' : Type -> Type -> Type -> Type where Zor7' : c -> Foo7' a b c Gor7' : b -> Foo7' a b c Nor7' : b -> c -> Foo7' a b c Bor7' : Foo7' a b c -- we'll use our own nat for index experimentation export data MyNat : Type where MZ : MyNat MS : MyNat -> MyNat data Foo6 : Type -> Type -> Type -> Nat -> Type where Zor6 : a -> b -> Foo6 a b c Z Gor6 : b -> Foo6 a b c (S k) Nor6A : a -> b -> c -> Foo6 a b c n -- Nor6B : a -> (0 _ : b) -> c -> Foo6 a b c n -- NB: 0 Use arg Bor6A : Foo6 a b c n Bor6B : Foo6 a b c n -> Foo6 a b c n Wah6 : a -> (n : Nat) -> Foo6 a b c n export data Foo6' : Type -> Type -> Type -> MyNat -> Type where Zor6' : a -> b -> Foo6' a b c MZ Gor6A' : b -> Foo6' a b c (MS k) Gor6B' : (k : MyNat) -> b -> Foo6' a b c (MS k) Nor6A' : a -> b -> c -> Foo6' a b c n -- Nor6B' : a -> (0 _ : b) -> c -> Foo6' a b c n Bor6' : Foo6' a b c n Wah6' : a -> (n : MyNat) -> Foo6' a b c n -- Kah6' : a -> (n : MyNat) -> (0 _ : c) -> Foo6' a b c n -- Pah6' : a -> (n : MyNat) -> MyNat -> (0 _ : c) -> Foo6' a b c n -- Rah6' : a -> (n : MyNat) -> Foo6' a b c n -> MyNat -> (0 _ : c) -> Foo6' a b c n -> Foo6' a b c n -- Gah6' : {1 _ : a} -> (n : MyNat) -> MyNat -> (0 _ : c) -> Foo6' a b c n -- ^ another case to consider, what if I'm implicit but M1? -- Seems like an error would be appropriate there rather than showing -- implicits. Though showing implicits could be a flag in instance generation -- I guess. -- eqImplFoo6'Fun (Wah6' 'c' MZ) (Wah6' 'c' MZ) -- eqImplFoo6'Fun (Nor6A' {n=MZ} 'c' 'd' 'e') -- eqImplFoo6Fun (Wah6 {b=Int} {c=String} 'c' (S Z)) (Wah6 'c' (S Z)) data FooN : MyNat -> Type -> Type where BorZ : b -> FooN MZ b BorS : b -> FooN (MS MZ) b BorNA : (k : MyNat) -> b -> FooN n b BorNB : (n : MyNat) -> b -> FooN n b data XXX : Type where MkXXX : {a : Int} -> (b : Int) -> XXX %runElab deriveDecEq Export `{{MyNat}} %runElab deriveDecEq Export `{{Foo1}} %runElab deriveDecEq Export `{{Foo2}} %runElab deriveDecEq Private `{{Foo4}} %runElab deriveDecEq Private `{{Foo5}} %runElab deriveDecEq Private `{{Foo7}} %runElab deriveDecEq Private `{{Foo7'}} -- %runElab deriveDecEq Private `{{FooN}} -- %runElab deriveDecEq Private `{{Foo6}} -- %runElab deriveDecEq Export `{{Foo6'}} %runElab deriveDecEq Export `{{XXX}} -- can check what's generated via -- :printdef eqImplFoo7'Fun
@system StomataBase(Weather, Diffusion) begin gs: stomatal_conductance ~ hold gb: boundary_layer_conductance ~ hold A_net: net_photosynthesis ~ hold T: leaf_temperature ~ hold drb(Dw, Dc): diffusivity_ratio_boundary_layer => (Dw / Dc)^(2/3) ~ preserve(#= u"H2O/CO2", =# parameter) dra(Dw, Dc): diffusivity_ratio_air => (Dw / Dc) ~ preserve(#= u"H2O/CO2", =# parameter) Ca(CO2, P_air): co2_air => (CO2 * P_air) ~ track(u"μbar") Cs(Ca, A_net, gbc): co2_at_leaf_surface => begin Ca - A_net / gbc end ~ track(u"μbar") gv(gs, gb): total_conductance_h2o => (gs * gb / (gs + gb)) ~ track(u"mol/m^2/s/bar" #= H2O =#) rbc(gb, drb): boundary_layer_resistance_co2 => (drb / gb) ~ track(u"m^2*s/mol*bar") rsc(gs, dra): stomatal_resistance_co2 => (dra / gs) ~ track(u"m^2*s/mol*bar") rvc(rbc, rsc): total_resistance_co2 => (rbc + rsc) ~ track(u"m^2*s/mol*bar") gbc(rbc): boundary_layer_conductance_co2 => (1 / rbc) ~ track(u"mol/m^2/s/bar") gsc(rsc): stomatal_conductance_co2 => (1 / rsc) ~ track(u"mol/m^2/s/bar") gvc(rvc): total_conductance_co2 => (1 / rvc) ~ track(u"mol/m^2/s/bar") end @system StomataTuzet begin WP_leaf: leaf_water_potential => 0 ~ preserve(u"MPa", parameter) Ψv(WP_leaf): bulk_leaf_water_potential ~ track(u"MPa") Ψf: reference_leaf_water_potential => -2.0 ~ preserve(u"MPa", parameter) sf: stomata_sensitivity_param => 2.3 ~ preserve(u"MPa^-1", parameter) fΨv(Ψv, Ψf, sf): stomata_sensitivty => begin (1 + exp(sf*Ψf)) / (1 + exp(sf*(Ψf-Ψv))) end ~ track end @system StomataBallBerry(StomataBase, StomataTuzet) begin # Ball-Berry model parameters from Miner and Bauerle 2017, used to be 0.04 and 4.0, respectively (2018-09-04: KDY) g0 => 0.017 ~ preserve(u"mol/m^2/s/bar" #= H2O =#, parameter) g1 => 4.53 ~ preserve(parameter) #HACK: avoid scaling issue with dimensionless unit hs(g0, g1, gb, A_net, Cs, fΨv, RH): relative_humidity_at_leaf_surface => begin gs = g0 + g1*(A_net*hs/Cs) * fΨv (hs - RH)*gb ⩵ (1 - hs)*gs end ~ solve(lower=0, upper=1) #, u"percent") Ds(D=vp.D, T, hs): vapor_pressure_deficit_at_leaf_surface => begin D(T, hs) end ~ track(u"kPa") gs(g0, g1, A_net, hs, Cs, fΨv): stomatal_conductance => begin g0 + g1*(A_net*hs/Cs) * fΨv end ~ track(u"mol/m^2/s/bar" #= H2O =#, min=g0) end @system StomataMedlyn(StomataBase, StomataTuzet) begin g0 => 0.02 ~ preserve(u"mol/m^2/s/bar" #= H2O =#, parameter) g1 => 4.0 ~ preserve(u"√kPa", parameter) wa(ea=vp.ea, T_air, RH): vapor_pressure_at_air => ea(T_air, RH) ~ track(u"kPa") wi(es=vp.es, T): vapor_pressure_at_intercellular_space => es(T) ~ track(u"kPa") ws(Ds, wi): vapor_pressure_at_leaf_surface => (wi - Ds) ~ track(u"kPa") Ds¹ᐟ²(g0, g1, gb, A_net, Cs, fΨv, wi, wa) => begin #HACK: SymPy couldn't extract polynomial coeffs for ps inside √ gs = g0 + (1 + g1 / Ds¹ᐟ²) * (A_net / Cs) * fΨv ws = wi - Ds¹ᐟ²^2 (ws - wa)*gb ⩵ (wi - ws)*gs end ~ solve(lower=0, upper=√wi', u"√kPa") Ds(Ds¹ᐟ²): vapor_pressure_deficit_at_leaf_surface => Ds¹ᐟ²^2 ~ track(u"kPa", min=1u"Pa") hs(RH=vp.RH, T, Ds): relative_humidity_at_leaf_surface => RH(T, Ds) ~ track gs(g0, g1, A_net, Ds, Cs, fΨv): stomatal_conductance => begin g0 + (1 + g1/√Ds)*(A_net/Cs) * fΨv end ~ track(u"mol/m^2/s/bar" #= H2O =#, min=g0) end
/* ----------------------------------------------------------------------------- * Copyright 2021 Jonathan Haigh * SPDX-License-Identifier: MIT * ---------------------------------------------------------------------------*/ #ifndef SQ_INCLUDE_GUARD_core_test_Primitive_test_util_h_ #define SQ_INCLUDE_GUARD_core_test_Primitive_test_util_h_ #include "core/Primitive.h" #include "core/typeutil.h" #include <gsl/gsl> #include <string_view> namespace sq::test { SQ_ND Primitive to_primitive(PrimitiveString &&v); SQ_ND Primitive to_primitive(const PrimitiveString &v); SQ_ND Primitive to_primitive(std::string_view v); SQ_ND Primitive to_primitive(gsl::czstring<> v); SQ_ND Primitive to_primitive(PrimitiveInt v); SQ_ND Primitive to_primitive(int v); SQ_ND Primitive to_primitive(PrimitiveFloat v); SQ_ND Primitive to_primitive(PrimitiveBool v); SQ_ND Primitive to_primitive(PrimitiveNull v); } // namespace sq::test #endif // SQ_INCLUDE_GUARD_core_test_Primitive_test_util_h_
import os import unittest import warnings from io import BytesIO from pathlib import Path import h5py import numpy as np from h5py import SoftLink, HardLink, ExternalLink, File from h5py import filters as h5py_filters from hdmf.backends.hdf5 import H5DataIO from hdmf.backends.hdf5.h5tools import HDF5IO, ROOT_NAME, SPEC_LOC_ATTR from hdmf.backends.io import HDMFIO, UnsupportedOperation from hdmf.backends.warnings import BrokenLinkWarning from hdmf.build import (GroupBuilder, DatasetBuilder, BuildManager, TypeMap, ObjectMapper, OrphanContainerBuildError, LinkBuilder) from hdmf.container import Container, Data from hdmf.data_utils import DataChunkIterator, InvalidDataIOError from hdmf.spec.catalog import SpecCatalog from hdmf.spec.namespace import NamespaceCatalog from hdmf.spec.namespace import SpecNamespace from hdmf.spec.spec import (AttributeSpec, DatasetSpec, GroupSpec, LinkSpec, ZERO_OR_MANY, ONE_OR_MANY, ZERO_OR_ONE, RefSpec, DtypeSpec) from hdmf.testing import TestCase from hdmf.utils import docval, getargs from tests.unit.utils import (Foo, FooBucket, CORE_NAMESPACE, get_temp_filepath, CustomGroupSpec, CustomDatasetSpec, CustomSpecNamespace) class FooFile(Container): @docval({'name': 'buckets', 'type': list, 'doc': 'the FooBuckets in this file', 'default': list()}, {'name': 'foo_link', 'type': Foo, 'doc': 'an optional linked Foo', 'default': None}, {'name': 'foofile_data', 'type': 'array_data', 'doc': 'an optional dataset', 'default': None}, {'name': 'foo_ref_attr', 'type': Foo, 'doc': 'a reference Foo', 'default': None}, ) def __init__(self, **kwargs): buckets, foo_link, foofile_data, foo_ref_attr = getargs('buckets', 'foo_link', 'foofile_data', 'foo_ref_attr', kwargs) super().__init__(name=ROOT_NAME) # name is not used - FooFile should be the root container self.__buckets = {b.name: b for b in buckets} # note: collections of groups are unordered in HDF5 for f in buckets: f.parent = self self.__foo_link = foo_link self.__foofile_data = foofile_data self.__foo_ref_attr = foo_ref_attr def __eq__(self, other): return (self.buckets == other.buckets and self.foo_link == other.foo_link and self.foofile_data == other.foofile_data) def __str__(self): return ('buckets=%s, foo_link=%s, foofile_data=%s' % (self.buckets, self.foo_link, self.foofile_data)) @property def buckets(self): return self.__buckets def add_bucket(self, bucket): self.__buckets[bucket.name] = bucket bucket.parent = self def remove_bucket(self, bucket_name): bucket = self.__buckets.pop(bucket_name) if bucket.parent is self: self._remove_child(bucket) return bucket @property def foo_link(self): return self.__foo_link @foo_link.setter def foo_link(self, value): if self.__foo_link is None: self.__foo_link = value else: raise ValueError("can't reset foo_link attribute") @property def foofile_data(self): return self.__foofile_data @foofile_data.setter def foofile_data(self, value): if self.__foofile_data is None: self.__foofile_data = value else: raise ValueError("can't reset foofile_data attribute") @property def foo_ref_attr(self): return self.__foo_ref_attr @foo_ref_attr.setter def foo_ref_attr(self, value): if self.__foo_ref_attr is None: self.__foo_ref_attr = value else: raise ValueError("can't reset foo_ref_attr attribute") class H5IOTest(TestCase): """Tests for h5tools IO tools""" def setUp(self): self.path = get_temp_filepath() self.io = HDF5IO(self.path, mode='a') self.f = self.io._file def tearDown(self): self.io.close() os.remove(self.path) ########################################## # __chunked_iter_fill__(...) tests ########################################## def test__chunked_iter_fill(self): """Matrix test of HDF5IO.__chunked_iter_fill__ using a DataChunkIterator with different parameters""" data_opts = {'iterator': range(10), 'numpy': np.arange(30).reshape(5, 2, 3), 'list': np.arange(30).reshape(5, 2, 3).tolist(), 'sparselist1': [1, 2, 3, None, None, None, None, 8, 9, 10], 'sparselist2': [None, None, 3], 'sparselist3': [1, 2, 3, None, None], # note: cannot process None in ndarray 'nanlist': [[[1, 2, 3, np.nan, np.nan, 6], [np.nan, np.nan, 3, 4, np.nan, np.nan]], [[10, 20, 30, 40, np.nan, np.nan], [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan]]]} buffer_size_opts = [1, 2, 3, 4] # data is divisible by some of these, some not for data_type, data in data_opts.items(): iter_axis_opts = [0, 1, 2] if data_type == 'iterator' or data_type.startswith('sparselist'): iter_axis_opts = [0] # only one dimension for iter_axis in iter_axis_opts: for buffer_size in buffer_size_opts: with self.subTest(data_type=data_type, iter_axis=iter_axis, buffer_size=buffer_size): with warnings.catch_warnings(record=True) as w: dci = DataChunkIterator(data=data, buffer_size=buffer_size, iter_axis=iter_axis) if len(w) <= 1: # init may throw UserWarning for iterating over not-first dim of a list. ignore here pass dset_name = '%s, %d, %d' % (data_type, iter_axis, buffer_size) my_dset = HDF5IO.__chunked_iter_fill__(self.f, dset_name, dci) if data_type == 'iterator': self.assertListEqual(my_dset[:].tolist(), list(data)) elif data_type == 'numpy': self.assertTrue(np.all(my_dset[:] == data)) self.assertTupleEqual(my_dset.shape, data.shape) elif data_type == 'list' or data_type == 'nanlist': data_np = np.array(data) np.testing.assert_array_equal(my_dset[:], data_np) self.assertTupleEqual(my_dset.shape, data_np.shape) elif data_type.startswith('sparselist'): # replace None in original data with default hdf5 fillvalue 0 data_zeros = np.where(np.equal(np.array(data), None), 0, data) np.testing.assert_array_equal(my_dset[:], data_zeros) self.assertTupleEqual(my_dset.shape, data_zeros.shape) ########################################## # write_dataset tests: scalars ########################################## def test_write_dataset_scalar(self): a = 10 self.io.write_dataset(self.f, DatasetBuilder('test_dataset', a, attributes={})) dset = self.f['test_dataset'] self.assertTupleEqual(dset.shape, ()) self.assertEqual(dset[()], a) def test_write_dataset_string(self): a = 'test string' self.io.write_dataset(self.f, DatasetBuilder('test_dataset', a, attributes={})) dset = self.f['test_dataset'] self.assertTupleEqual(dset.shape, ()) # self.assertEqual(dset[()].decode('utf-8'), a) read_a = dset[()] if isinstance(read_a, bytes): read_a = read_a.decode('utf-8') self.assertEqual(read_a, a) ########################################## # write_dataset tests: lists ########################################## def test_write_dataset_list(self): a = np.arange(30).reshape(5, 2, 3) self.io.write_dataset(self.f, DatasetBuilder('test_dataset', a.tolist(), attributes={})) dset = self.f['test_dataset'] self.assertTrue(np.all(dset[:] == a)) def test_write_dataset_list_compress_gzip(self): a = H5DataIO(np.arange(30).reshape(5, 2, 3), compression='gzip', compression_opts=5, shuffle=True, fletcher32=True) self.io.write_dataset(self.f, DatasetBuilder('test_dataset', a, attributes={})) dset = self.f['test_dataset'] self.assertTrue(np.all(dset[:] == a.data)) self.assertEqual(dset.compression, 'gzip') self.assertEqual(dset.compression_opts, 5) self.assertEqual(dset.shuffle, True) self.assertEqual(dset.fletcher32, True) @unittest.skipIf("lzf" not in h5py_filters.encode, "LZF compression not supported in this h5py library install") def test_write_dataset_list_compress_lzf(self): warn_msg = ("lzf compression may not be available on all installations of HDF5. Use of gzip is " "recommended to ensure portability of the generated HDF5 files.") with self.assertWarnsWith(UserWarning, warn_msg): a = H5DataIO(np.arange(30).reshape(5, 2, 3), compression='lzf', shuffle=True, fletcher32=True) self.io.write_dataset(self.f, DatasetBuilder('test_dataset', a, attributes={})) dset = self.f['test_dataset'] self.assertTrue(np.all(dset[:] == a.data)) self.assertEqual(dset.compression, 'lzf') self.assertEqual(dset.shuffle, True) self.assertEqual(dset.fletcher32, True) @unittest.skipIf("szip" not in h5py_filters.encode, "SZIP compression not supported in this h5py library install") def test_write_dataset_list_compress_szip(self): warn_msg = ("szip compression may not be available on all installations of HDF5. Use of gzip is " "recommended to ensure portability of the generated HDF5 files.") with self.assertWarnsWith(UserWarning, warn_msg): a = H5DataIO(np.arange(30).reshape(5, 2, 3), compression='szip', compression_opts=('ec', 16), shuffle=True, fletcher32=True) self.io.write_dataset(self.f, DatasetBuilder('test_dataset', a, attributes={})) dset = self.f['test_dataset'] self.assertTrue(np.all(dset[:] == a.data)) self.assertEqual(dset.compression, 'szip') self.assertEqual(dset.shuffle, True) self.assertEqual(dset.fletcher32, True) def test_write_dataset_list_compress_available_int_filters(self): a = H5DataIO(np.arange(30).reshape(5, 2, 3), compression=1, shuffle=True, fletcher32=True, allow_plugin_filters=True) self.io.write_dataset(self.f, DatasetBuilder('test_dataset', a, attributes={})) dset = self.f['test_dataset'] self.assertTrue(np.all(dset[:] == a.data)) self.assertEqual(dset.compression, 'gzip') self.assertEqual(dset.shuffle, True) self.assertEqual(dset.fletcher32, True) def test_write_dataset_list_enable_default_compress(self): a = H5DataIO(np.arange(30).reshape(5, 2, 3), compression=True) self.assertEqual(a.io_settings['compression'], 'gzip') self.io.write_dataset(self.f, DatasetBuilder('test_dataset', a, attributes={})) dset = self.f['test_dataset'] self.assertTrue(np.all(dset[:] == a.data)) self.assertEqual(dset.compression, 'gzip') def test_write_dataset_list_disable_default_compress(self): with warnings.catch_warnings(record=True) as w: a = H5DataIO(np.arange(30).reshape(5, 2, 3), compression=False, compression_opts=5) self.assertEqual(len(w), 1) # We expect a warning that compression options are being ignored self.assertFalse('compression_ops' in a.io_settings) self.assertFalse('compression' in a.io_settings) self.io.write_dataset(self.f, DatasetBuilder('test_dataset', a, attributes={})) dset = self.f['test_dataset'] self.assertTrue(np.all(dset[:] == a.data)) self.assertEqual(dset.compression, None) def test_write_dataset_list_chunked(self): a = H5DataIO(np.arange(30).reshape(5, 2, 3), chunks=(1, 1, 3)) self.io.write_dataset(self.f, DatasetBuilder('test_dataset', a, attributes={})) dset = self.f['test_dataset'] self.assertTrue(np.all(dset[:] == a.data)) self.assertEqual(dset.chunks, (1, 1, 3)) def test_write_dataset_list_fillvalue(self): a = H5DataIO(np.arange(20).reshape(5, 4), fillvalue=-1) self.io.write_dataset(self.f, DatasetBuilder('test_dataset', a, attributes={})) dset = self.f['test_dataset'] self.assertTrue(np.all(dset[:] == a.data)) self.assertEqual(dset.fillvalue, -1) ########################################## # write_dataset tests: tables ########################################## def test_write_table(self): cmpd_dt = np.dtype([('a', np.int32), ('b', np.float64)]) data = np.zeros(10, dtype=cmpd_dt) data['a'][1] = 101 data['b'][1] = 0.1 dt = [{'name': 'a', 'dtype': 'int32', 'doc': 'a column'}, {'name': 'b', 'dtype': 'float64', 'doc': 'b column'}] self.io.write_dataset(self.f, DatasetBuilder('test_dataset', data, attributes={}, dtype=dt)) dset = self.f['test_dataset'] self.assertEqual(dset['a'].tolist(), data['a'].tolist()) self.assertEqual(dset['b'].tolist(), data['b'].tolist()) def test_write_table_nested(self): b_cmpd_dt = np.dtype([('c', np.int32), ('d', np.float64)]) cmpd_dt = np.dtype([('a', np.int32), ('b', b_cmpd_dt)]) data = np.zeros(10, dtype=cmpd_dt) data['a'][1] = 101 data['b']['c'] = 202 data['b']['d'] = 10.1 b_dt = [{'name': 'c', 'dtype': 'int32', 'doc': 'c column'}, {'name': 'd', 'dtype': 'float64', 'doc': 'd column'}] dt = [{'name': 'a', 'dtype': 'int32', 'doc': 'a column'}, {'name': 'b', 'dtype': b_dt, 'doc': 'b column'}] self.io.write_dataset(self.f, DatasetBuilder('test_dataset', data, attributes={}, dtype=dt)) dset = self.f['test_dataset'] self.assertEqual(dset['a'].tolist(), data['a'].tolist()) self.assertEqual(dset['b'].tolist(), data['b'].tolist()) ########################################## # write_dataset tests: Iterable ########################################## def test_write_dataset_iterable(self): self.io.write_dataset(self.f, DatasetBuilder('test_dataset', range(10), attributes={})) dset = self.f['test_dataset'] self.assertListEqual(dset[:].tolist(), list(range(10))) def test_write_dataset_iterable_multidimensional_array(self): a = np.arange(30).reshape(5, 2, 3) aiter = iter(a) daiter = DataChunkIterator.from_iterable(aiter, buffer_size=2) self.io.write_dataset(self.f, DatasetBuilder('test_dataset', daiter, attributes={})) dset = self.f['test_dataset'] self.assertListEqual(dset[:].tolist(), a.tolist()) def test_write_multi_dci_oaat(self): """ Test writing multiple DataChunkIterators, one at a time """ a = np.arange(30).reshape(5, 2, 3) b = np.arange(30, 60).reshape(5, 2, 3) aiter = iter(a) biter = iter(b) daiter1 = DataChunkIterator.from_iterable(aiter, buffer_size=2) daiter2 = DataChunkIterator.from_iterable(biter, buffer_size=2) builder = GroupBuilder("root") dataset1 = DatasetBuilder('test_dataset1', daiter1) dataset2 = DatasetBuilder('test_dataset2', daiter2) builder.set_dataset(dataset1) builder.set_dataset(dataset2) self.io.write_builder(builder) dset1 = self.f['test_dataset1'] self.assertListEqual(dset1[:].tolist(), a.tolist()) dset2 = self.f['test_dataset2'] self.assertListEqual(dset2[:].tolist(), b.tolist()) def test_write_multi_dci_conc(self): """ Test writing multiple DataChunkIterators, concurrently """ a = np.arange(30).reshape(5, 2, 3) b = np.arange(30, 60).reshape(5, 2, 3) aiter = iter(a) biter = iter(b) daiter1 = DataChunkIterator.from_iterable(aiter, buffer_size=2) daiter2 = DataChunkIterator.from_iterable(biter, buffer_size=2) builder = GroupBuilder("root") dataset1 = DatasetBuilder('test_dataset1', daiter1) dataset2 = DatasetBuilder('test_dataset2', daiter2) builder.set_dataset(dataset1) builder.set_dataset(dataset2) self.io.write_builder(builder) dset1 = self.f['test_dataset1'] self.assertListEqual(dset1[:].tolist(), a.tolist()) dset2 = self.f['test_dataset2'] self.assertListEqual(dset2[:].tolist(), b.tolist()) def test_write_dataset_iterable_multidimensional_array_compression(self): a = np.arange(30).reshape(5, 2, 3) aiter = iter(a) daiter = DataChunkIterator.from_iterable(aiter, buffer_size=2) wrapped_daiter = H5DataIO(data=daiter, compression='gzip', compression_opts=5, shuffle=True, fletcher32=True) self.io.write_dataset(self.f, DatasetBuilder('test_dataset', wrapped_daiter, attributes={})) dset = self.f['test_dataset'] self.assertEqual(dset.shape, a.shape) self.assertListEqual(dset[:].tolist(), a.tolist()) self.assertEqual(dset.compression, 'gzip') self.assertEqual(dset.compression_opts, 5) self.assertEqual(dset.shuffle, True) self.assertEqual(dset.fletcher32, True) ############################################# # write_dataset tests: data chunk iterator ############################################# def test_write_dataset_data_chunk_iterator(self): dci = DataChunkIterator(data=np.arange(10), buffer_size=2) self.io.write_dataset(self.f, DatasetBuilder('test_dataset', dci, attributes={}, dtype=dci.dtype)) dset = self.f['test_dataset'] self.assertListEqual(dset[:].tolist(), list(range(10))) self.assertEqual(dset[:].dtype, dci.dtype) def test_write_dataset_data_chunk_iterator_with_compression(self): dci = DataChunkIterator(data=np.arange(10), buffer_size=2) wrapped_dci = H5DataIO(data=dci, compression='gzip', compression_opts=5, shuffle=True, fletcher32=True, chunks=(2,)) self.io.write_dataset(self.f, DatasetBuilder('test_dataset', wrapped_dci, attributes={})) dset = self.f['test_dataset'] self.assertListEqual(dset[:].tolist(), list(range(10))) self.assertEqual(dset.compression, 'gzip') self.assertEqual(dset.compression_opts, 5) self.assertEqual(dset.shuffle, True) self.assertEqual(dset.fletcher32, True) self.assertEqual(dset.chunks, (2,)) def test_pass_through_of_recommended_chunks(self): class DC(DataChunkIterator): def recommended_chunk_shape(self): return (5, 1, 1) dci = DC(data=np.arange(30).reshape(5, 2, 3)) wrapped_dci = H5DataIO(data=dci, compression='gzip', compression_opts=5, shuffle=True, fletcher32=True) self.io.write_dataset(self.f, DatasetBuilder('test_dataset', wrapped_dci, attributes={})) dset = self.f['test_dataset'] self.assertEqual(dset.chunks, (5, 1, 1)) self.assertEqual(dset.compression, 'gzip') self.assertEqual(dset.compression_opts, 5) self.assertEqual(dset.shuffle, True) self.assertEqual(dset.fletcher32, True) def test_dci_h5dataset(self): data = np.arange(30).reshape(5, 2, 3) dci1 = DataChunkIterator(data=data, buffer_size=1, iter_axis=0) HDF5IO.__chunked_iter_fill__(self.f, 'test_dataset', dci1) dset = self.f['test_dataset'] dci2 = DataChunkIterator(data=dset, buffer_size=2, iter_axis=2) chunk = dci2.next() self.assertTupleEqual(chunk.shape, (5, 2, 2)) chunk = dci2.next() self.assertTupleEqual(chunk.shape, (5, 2, 1)) # TODO test chunk data, shape, selection self.assertTupleEqual(dci2.recommended_data_shape(), data.shape) self.assertIsNone(dci2.recommended_chunk_shape()) def test_dci_h5dataset_sparse_matched(self): data = [1, 2, 3, None, None, None, None, 8, 9, 10] dci1 = DataChunkIterator(data=data, buffer_size=3) HDF5IO.__chunked_iter_fill__(self.f, 'test_dataset', dci1) dset = self.f['test_dataset'] dci2 = DataChunkIterator(data=dset, buffer_size=2) # dataset is read such that Nones in original data were not written, but are read as 0s self.assertTupleEqual(dci2.maxshape, (10,)) self.assertEqual(dci2.dtype, np.dtype(int)) count = 0 for chunk in dci2: self.assertEqual(len(chunk.selection), 1) if count == 0: self.assertListEqual(chunk.data.tolist(), [1, 2]) self.assertEqual(chunk.selection[0], slice(0, 2)) elif count == 1: self.assertListEqual(chunk.data.tolist(), [3, 0]) self.assertEqual(chunk.selection[0], slice(2, 4)) elif count == 2: self.assertListEqual(chunk.data.tolist(), [0, 0]) self.assertEqual(chunk.selection[0], slice(4, 6)) elif count == 3: self.assertListEqual(chunk.data.tolist(), [0, 8]) self.assertEqual(chunk.selection[0], slice(6, 8)) elif count == 4: self.assertListEqual(chunk.data.tolist(), [9, 10]) self.assertEqual(chunk.selection[0], slice(8, 10)) count += 1 self.assertEqual(count, 5) self.assertTupleEqual(dci2.recommended_data_shape(), (10,)) self.assertIsNone(dci2.recommended_chunk_shape()) def test_dci_h5dataset_sparse_unmatched(self): data = [1, 2, 3, None, None, None, None, 8, 9, 10] dci1 = DataChunkIterator(data=data, buffer_size=3) HDF5IO.__chunked_iter_fill__(self.f, 'test_dataset', dci1) dset = self.f['test_dataset'] dci2 = DataChunkIterator(data=dset, buffer_size=4) # dataset is read such that Nones in original data were not written, but are read as 0s self.assertTupleEqual(dci2.maxshape, (10,)) self.assertEqual(dci2.dtype, np.dtype(int)) count = 0 for chunk in dci2: self.assertEqual(len(chunk.selection), 1) if count == 0: self.assertListEqual(chunk.data.tolist(), [1, 2, 3, 0]) self.assertEqual(chunk.selection[0], slice(0, 4)) elif count == 1: self.assertListEqual(chunk.data.tolist(), [0, 0, 0, 8]) self.assertEqual(chunk.selection[0], slice(4, 8)) elif count == 2: self.assertListEqual(chunk.data.tolist(), [9, 10]) self.assertEqual(chunk.selection[0], slice(8, 10)) count += 1 self.assertEqual(count, 3) self.assertTupleEqual(dci2.recommended_data_shape(), (10,)) self.assertIsNone(dci2.recommended_chunk_shape()) def test_dci_h5dataset_scalar(self): data = [1] dci1 = DataChunkIterator(data=data, buffer_size=3) HDF5IO.__chunked_iter_fill__(self.f, 'test_dataset', dci1) dset = self.f['test_dataset'] dci2 = DataChunkIterator(data=dset, buffer_size=4) # dataset is read such that Nones in original data were not written, but are read as 0s self.assertTupleEqual(dci2.maxshape, (1,)) self.assertEqual(dci2.dtype, np.dtype(int)) count = 0 for chunk in dci2: self.assertEqual(len(chunk.selection), 1) if count == 0: self.assertListEqual(chunk.data.tolist(), [1]) self.assertEqual(chunk.selection[0], slice(0, 1)) count += 1 self.assertEqual(count, 1) self.assertTupleEqual(dci2.recommended_data_shape(), (1,)) self.assertIsNone(dci2.recommended_chunk_shape()) ############################################# # H5DataIO general ############################################# def test_warning_on_non_gzip_compression(self): # Make sure no warning is issued when using gzip with warnings.catch_warnings(record=True) as w: dset = H5DataIO(np.arange(30), compression='gzip') self.assertEqual(len(w), 0) self.assertEqual(dset.io_settings['compression'], 'gzip') # Make sure a warning is issued when using szip (even if installed) if "szip" in h5py_filters.encode: with warnings.catch_warnings(record=True) as w: dset = H5DataIO(np.arange(30), compression='szip', compression_opts=('ec', 16)) self.assertEqual(len(w), 1) self.assertEqual(dset.io_settings['compression'], 'szip') else: with self.assertRaises(ValueError): H5DataIO(np.arange(30), compression='szip', compression_opts=('ec', 16)) # Make sure a warning is issued when using lzf compression with warnings.catch_warnings(record=True) as w: dset = H5DataIO(np.arange(30), compression='lzf') self.assertEqual(len(w), 1) self.assertEqual(dset.io_settings['compression'], 'lzf') def test_error_on_unsupported_compression_filter(self): # Make sure gzip does not raise an error try: H5DataIO(np.arange(30), compression='gzip', compression_opts=5) except ValueError: self.fail("Using gzip compression raised a ValueError when it should not") # Make sure szip raises an error if not installed (or does not raise an error if installed) warn_msg = ("szip compression may not be available on all installations of HDF5. Use of gzip is " "recommended to ensure portability of the generated HDF5 files.") if "szip" not in h5py_filters.encode: with self.assertRaises(ValueError): H5DataIO(np.arange(30), compression='szip', compression_opts=('ec', 16)) else: try: with self.assertWarnsWith(UserWarning, warn_msg): H5DataIO(np.arange(30), compression='szip', compression_opts=('ec', 16)) except ValueError: self.fail("SZIP is installed but H5DataIO still raises an error") # Test error on illegal (i.e., a made-up compressor) with self.assertRaises(ValueError): warn_msg = ("unknown compression may not be available on all installations of HDF5. Use of gzip is " "recommended to ensure portability of the generated HDF5 files.") with self.assertWarnsWith(UserWarning, warn_msg): H5DataIO(np.arange(30), compression="unknown") # Make sure passing int compression filter raise an error if not installed if not h5py_filters.h5z.filter_avail(h5py_filters.h5z.FILTER_MAX): with self.assertRaises(ValueError): warn_msg = ("%i compression may not be available on all installations of HDF5. Use of gzip is " "recommended to ensure portability of the generated HDF5 files." % h5py_filters.h5z.FILTER_MAX) with self.assertWarnsWith(UserWarning, warn_msg): H5DataIO(np.arange(30), compression=h5py_filters.h5z.FILTER_MAX, allow_plugin_filters=True) # Make sure available int compression filters raise an error without passing allow_plugin_filters=True with self.assertRaises(ValueError): H5DataIO(np.arange(30), compression=h5py_filters.h5z.FILTER_DEFLATE) def test_value_error_on_incompatible_compression_opts(self): # Make sure we warn when gzip with szip compression options is used with self.assertRaises(ValueError): H5DataIO(np.arange(30), compression='gzip', compression_opts=('ec', 16)) # Make sure we warn if gzip with a too high agression is used with self.assertRaises(ValueError): H5DataIO(np.arange(30), compression='gzip', compression_opts=100) # Make sure we warn if lzf with gzip compression option is used with self.assertRaises(ValueError): H5DataIO(np.arange(30), compression='lzf', compression_opts=5) # Make sure we warn if lzf with szip compression option is used with self.assertRaises(ValueError): H5DataIO(np.arange(30), compression='lzf', compression_opts=('ec', 16)) # Make sure we warn if szip with gzip compression option is used with self.assertRaises(ValueError): H5DataIO(np.arange(30), compression='szip', compression_opts=4) # Make sure szip raises a ValueError if bad options are used (odd compression option) with self.assertRaises(ValueError): H5DataIO(np.arange(30), compression='szip', compression_opts=('ec', 3)) # Make sure szip raises a ValueError if bad options are used (bad methos) with self.assertRaises(ValueError): H5DataIO(np.arange(30), compression='szip', compression_opts=('bad_method', 16)) def test_warning_on_linking_of_regular_array(self): with warnings.catch_warnings(record=True) as w: dset = H5DataIO(np.arange(30), link_data=True) self.assertEqual(len(w), 1) self.assertEqual(dset.link_data, False) def test_warning_on_setting_io_options_on_h5dataset_input(self): self.io.write_dataset(self.f, DatasetBuilder('test_dataset', np.arange(10), attributes={})) with warnings.catch_warnings(record=True) as w: H5DataIO(self.f['test_dataset'], compression='gzip', compression_opts=4, fletcher32=True, shuffle=True, maxshape=(10, 20), chunks=(10,), fillvalue=100) self.assertEqual(len(w), 7) def test_h5dataio_array_conversion_numpy(self): # Test that H5DataIO.__array__ is working when wrapping an ndarray test_speed = np.array([10., 20.]) data = H5DataIO((test_speed)) self.assertTrue(np.all(np.isfinite(data))) # Force call of H5DataIO.__array__ def test_h5dataio_array_conversion_list(self): # Test that H5DataIO.__array__ is working when wrapping a python list test_speed = [10., 20.] data = H5DataIO(test_speed) self.assertTrue(np.all(np.isfinite(data))) # Force call of H5DataIO.__array__ def test_h5dataio_array_conversion_datachunkiterator(self): # Test that H5DataIO.__array__ is working when wrapping a python list test_speed = DataChunkIterator(data=[10., 20.]) data = H5DataIO(test_speed) with self.assertRaises(NotImplementedError): np.isfinite(data) # Force call of H5DataIO.__array__ ############################################# # Copy/Link h5py.Dataset object ############################################# def test_link_h5py_dataset_input(self): self.io.write_dataset(self.f, DatasetBuilder('test_dataset', np.arange(10), attributes={})) self.io.write_dataset(self.f, DatasetBuilder('test_softlink', self.f['test_dataset'], attributes={})) self.assertTrue(isinstance(self.f.get('test_softlink', getlink=True), SoftLink)) def test_copy_h5py_dataset_input(self): self.io.write_dataset(self.f, DatasetBuilder('test_dataset', np.arange(10), attributes={})) self.io.write_dataset(self.f, DatasetBuilder('test_copy', self.f['test_dataset'], attributes={}), link_data=False) self.assertTrue(isinstance(self.f.get('test_copy', getlink=True), HardLink)) self.assertListEqual(self.f['test_dataset'][:].tolist(), self.f['test_copy'][:].tolist()) def test_link_h5py_dataset_h5dataio_input(self): self.io.write_dataset(self.f, DatasetBuilder('test_dataset', np.arange(10), attributes={})) self.io.write_dataset(self.f, DatasetBuilder('test_softlink', H5DataIO(data=self.f['test_dataset'], link_data=True), attributes={})) self.assertTrue(isinstance(self.f.get('test_softlink', getlink=True), SoftLink)) def test_copy_h5py_dataset_h5dataio_input(self): self.io.write_dataset(self.f, DatasetBuilder('test_dataset', np.arange(10), attributes={})) self.io.write_dataset(self.f, DatasetBuilder('test_copy', H5DataIO(data=self.f['test_dataset'], link_data=False), # Force dataset copy attributes={})) # Make sure the default behavior is set to link the data self.assertTrue(isinstance(self.f.get('test_copy', getlink=True), HardLink)) self.assertListEqual(self.f['test_dataset'][:].tolist(), self.f['test_copy'][:].tolist()) def test_list_fill_empty(self): dset = self.io.__list_fill__(self.f, 'empty_dataset', [], options={'dtype': int, 'io_settings': {}}) self.assertTupleEqual(dset.shape, (0,)) def test_list_fill_empty_no_dtype(self): with self.assertRaisesRegex(Exception, r"cannot add \S+ to [/\S]+ - could not determine type"): self.io.__list_fill__(self.f, 'empty_dataset', []) def _get_manager(): foo_spec = GroupSpec('A test group specification with a data type', data_type_def='Foo', datasets=[DatasetSpec('an example dataset', 'int', name='my_data', attributes=[AttributeSpec('attr2', 'an example integer attribute', 'int')])], attributes=[AttributeSpec('attr1', 'an example string attribute', 'text'), AttributeSpec('attr3', 'an example float attribute', 'float')]) tmp_spec = GroupSpec('A subgroup for Foos', name='foo_holder', groups=[GroupSpec('the Foos in this bucket', data_type_inc='Foo', quantity=ZERO_OR_MANY)]) bucket_spec = GroupSpec('A test group specification for a data type containing data type', data_type_def='FooBucket', groups=[tmp_spec]) class FooMapper(ObjectMapper): def __init__(self, spec): super().__init__(spec) my_data_spec = spec.get_dataset('my_data') self.map_spec('attr2', my_data_spec.get_attribute('attr2')) class BucketMapper(ObjectMapper): def __init__(self, spec): super().__init__(spec) foo_holder_spec = spec.get_group('foo_holder') self.unmap(foo_holder_spec) foo_spec = foo_holder_spec.get_data_type('Foo') self.map_spec('foos', foo_spec) file_links_spec = GroupSpec('Foo link group', name='links', links=[LinkSpec('Foo link', name='foo_link', target_type='Foo', quantity=ZERO_OR_ONE)] ) file_spec = GroupSpec("A file of Foos contained in FooBuckets", data_type_def='FooFile', groups=[GroupSpec('Holds the FooBuckets', name='buckets', groups=[GroupSpec("One or more FooBuckets", data_type_inc='FooBucket', quantity=ZERO_OR_MANY)]), file_links_spec], datasets=[DatasetSpec('Foo data', name='foofile_data', dtype='int', quantity=ZERO_OR_ONE)], attributes=[AttributeSpec(doc='Foo ref attr', name='foo_ref_attr', dtype=RefSpec('Foo', 'object'), required=False)], ) class FileMapper(ObjectMapper): def __init__(self, spec): super().__init__(spec) bucket_spec = spec.get_group('buckets').get_data_type('FooBucket') self.map_spec('buckets', bucket_spec) self.unmap(spec.get_group('links')) foo_link_spec = spec.get_group('links').get_link('foo_link') self.map_spec('foo_link', foo_link_spec) spec_catalog = SpecCatalog() spec_catalog.register_spec(foo_spec, 'test.yaml') spec_catalog.register_spec(bucket_spec, 'test.yaml') spec_catalog.register_spec(file_spec, 'test.yaml') namespace = SpecNamespace( 'a test namespace', CORE_NAMESPACE, [{'source': 'test.yaml'}], version='0.1.0', catalog=spec_catalog) namespace_catalog = NamespaceCatalog() namespace_catalog.add_namespace(CORE_NAMESPACE, namespace) type_map = TypeMap(namespace_catalog) type_map.register_container_type(CORE_NAMESPACE, 'Foo', Foo) type_map.register_container_type(CORE_NAMESPACE, 'FooBucket', FooBucket) type_map.register_container_type(CORE_NAMESPACE, 'FooFile', FooFile) type_map.register_map(Foo, FooMapper) type_map.register_map(FooBucket, BucketMapper) type_map.register_map(FooFile, FileMapper) manager = BuildManager(type_map) return manager class TestRoundTrip(TestCase): def setUp(self): self.manager = _get_manager() self.path = get_temp_filepath() def tearDown(self): if os.path.exists(self.path): os.remove(self.path) def test_roundtrip_basic(self): # Setup all the data we need foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) foobucket = FooBucket('bucket1', [foo1]) foofile = FooFile([foobucket]) with HDF5IO(self.path, manager=self.manager, mode='w') as io: io.write(foofile) with HDF5IO(self.path, manager=self.manager, mode='r') as io: read_foofile = io.read() self.assertListEqual(foofile.buckets['bucket1'].foos['foo1'].my_data, read_foofile.buckets['bucket1'].foos['foo1'].my_data[:].tolist()) def test_roundtrip_empty_dataset(self): foo1 = Foo('foo1', [], "I am foo1", 17, 3.14) foobucket = FooBucket('bucket1', [foo1]) foofile = FooFile([foobucket]) with HDF5IO(self.path, manager=self.manager, mode='w') as io: io.write(foofile) with HDF5IO(self.path, manager=self.manager, mode='r') as io: read_foofile = io.read() self.assertListEqual([], read_foofile.buckets['bucket1'].foos['foo1'].my_data[:].tolist()) def test_roundtrip_empty_group(self): foobucket = FooBucket('bucket1', []) foofile = FooFile([foobucket]) with HDF5IO(self.path, manager=self.manager, mode='w') as io: io.write(foofile) with HDF5IO(self.path, manager=self.manager, mode='r') as io: read_foofile = io.read() self.assertDictEqual({}, read_foofile.buckets['bucket1'].foos) def test_roundtrip_pathlib_path(self): pathlib_path = Path(self.path) foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) foobucket = FooBucket('bucket1', [foo1]) foofile = FooFile([foobucket]) with HDF5IO(pathlib_path, manager=self.manager, mode='w') as io: io.write(foofile) with HDF5IO(pathlib_path, manager=self.manager, mode='r') as io: read_foofile = io.read() self.assertListEqual(foofile.buckets['bucket1'].foos['foo1'].my_data, read_foofile.buckets['bucket1'].foos['foo1'].my_data[:].tolist()) class TestHDF5IO(TestCase): def setUp(self): self.manager = _get_manager() self.path = get_temp_filepath() foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) foobucket = FooBucket('bucket1', [foo1]) self.foofile = FooFile([foobucket]) self.file_obj = None def tearDown(self): if os.path.exists(self.path): os.remove(self.path) if self.file_obj is not None: fn = self.file_obj.filename self.file_obj.close() if os.path.exists(fn): os.remove(fn) def test_constructor(self): with HDF5IO(self.path, manager=self.manager, mode='w') as io: self.assertEqual(io.manager, self.manager) self.assertEqual(io.source, self.path) def test_set_file_mismatch(self): self.file_obj = File(get_temp_filepath(), 'w') err_msg = ("You argued %s as this object's path, but supplied a file with filename: %s" % (self.path, self.file_obj.filename)) with self.assertRaisesWith(ValueError, err_msg): HDF5IO(self.path, manager=self.manager, mode='w', file=self.file_obj) def test_pathlib_path(self): pathlib_path = Path(self.path) with HDF5IO(pathlib_path, mode='w') as io: self.assertEqual(io.source, self.path) class TestCacheSpec(TestCase): def setUp(self): self.manager = _get_manager() self.path = get_temp_filepath() def tearDown(self): if os.path.exists(self.path): os.remove(self.path) def test_cache_spec(self): foo1 = Foo('foo1', [0, 1, 2, 3, 4], "I am foo1", 17, 3.14) foo2 = Foo('foo2', [5, 6, 7, 8, 9], "I am foo2", 34, 6.28) foobucket = FooBucket('bucket1', [foo1, foo2]) foofile = FooFile([foobucket]) with HDF5IO(self.path, manager=self.manager, mode='w') as io: io.write(foofile) ns_catalog = NamespaceCatalog() HDF5IO.load_namespaces(ns_catalog, self.path) self.assertEqual(ns_catalog.namespaces, (CORE_NAMESPACE,)) source_types = self.__get_types(io.manager.namespace_catalog) read_types = self.__get_types(ns_catalog) self.assertSetEqual(source_types, read_types) def __get_types(self, catalog): types = set() for ns_name in catalog.namespaces: ns = catalog.get_namespace(ns_name) for source in ns['schema']: types.update(catalog.get_types(source['source'])) return types class TestNoCacheSpec(TestCase): def setUp(self): self.manager = _get_manager() self.path = get_temp_filepath() def tearDown(self): if os.path.exists(self.path): os.remove(self.path) def test_no_cache_spec(self): # Setup all the data we need foo1 = Foo('foo1', [0, 1, 2, 3, 4], "I am foo1", 17, 3.14) foo2 = Foo('foo2', [5, 6, 7, 8, 9], "I am foo2", 34, 6.28) foobucket = FooBucket('bucket1', [foo1, foo2]) foofile = FooFile([foobucket]) with HDF5IO(self.path, manager=self.manager, mode='w') as io: io.write(foofile, cache_spec=False) with File(self.path, 'r') as f: self.assertNotIn('specifications', f) class TestMultiWrite(TestCase): def setUp(self): self.path = get_temp_filepath() foo1 = Foo('foo1', [0, 1, 2, 3, 4], "I am foo1", 17, 3.14) foo2 = Foo('foo2', [5, 6, 7, 8, 9], "I am foo2", 34, 6.28) foobucket = FooBucket('bucket1', [foo1, foo2]) self.foofile = FooFile([foobucket]) def tearDown(self): if os.path.exists(self.path): os.remove(self.path) def test_double_write_new_manager(self): """Test writing to a container in write mode twice using a new manager without changing the container.""" with HDF5IO(self.path, manager=_get_manager(), mode='w') as io: io.write(self.foofile) with HDF5IO(self.path, manager=_get_manager(), mode='w') as io: io.write(self.foofile) # check that new bucket was written with HDF5IO(self.path, manager=_get_manager(), mode='r') as io: read_foofile = io.read() self.assertContainerEqual(read_foofile, self.foofile) def test_double_write_same_manager(self): """Test writing to a container in write mode twice using the same manager without changing the container.""" manager = _get_manager() with HDF5IO(self.path, manager=manager, mode='w') as io: io.write(self.foofile) with HDF5IO(self.path, manager=manager, mode='w') as io: io.write(self.foofile) # check that new bucket was written with HDF5IO(self.path, manager=_get_manager(), mode='r') as io: read_foofile = io.read() self.assertContainerEqual(read_foofile, self.foofile) @unittest.skip('Functionality not yet supported') def test_double_append_new_manager(self): """Test writing to a container in append mode twice using a new manager without changing the container.""" with HDF5IO(self.path, manager=_get_manager(), mode='a') as io: io.write(self.foofile) with HDF5IO(self.path, manager=_get_manager(), mode='a') as io: io.write(self.foofile) # check that new bucket was written with HDF5IO(self.path, manager=_get_manager(), mode='r') as io: read_foofile = io.read() self.assertContainerEqual(read_foofile, self.foofile) @unittest.skip('Functionality not yet supported') def test_double_append_same_manager(self): """Test writing to a container in append mode twice using the same manager without changing the container.""" manager = _get_manager() with HDF5IO(self.path, manager=manager, mode='a') as io: io.write(self.foofile) with HDF5IO(self.path, manager=manager, mode='a') as io: io.write(self.foofile) # check that new bucket was written with HDF5IO(self.path, manager=_get_manager(), mode='r') as io: read_foofile = io.read() self.assertContainerEqual(read_foofile, self.foofile) def test_write_add_write(self): """Test writing a container, adding to the in-memory container, then overwriting the same file.""" manager = _get_manager() with HDF5IO(self.path, manager=manager, mode='w') as io: io.write(self.foofile) # append new container to in-memory container foo3 = Foo('foo3', [10, 20], "I am foo3", 2, 0.1) new_bucket1 = FooBucket('new_bucket1', [foo3]) self.foofile.add_bucket(new_bucket1) # write to same file with same manager, overwriting existing file with HDF5IO(self.path, manager=manager, mode='w') as io: io.write(self.foofile) # check that new bucket was written with HDF5IO(self.path, manager=_get_manager(), mode='r') as io: read_foofile = io.read() self.assertEqual(len(read_foofile.buckets), 2) self.assertContainerEqual(read_foofile.buckets['new_bucket1'], new_bucket1) def test_write_add_append_bucket(self): """Test appending a container to a file.""" manager = _get_manager() with HDF5IO(self.path, manager=manager, mode='w') as io: io.write(self.foofile) foo3 = Foo('foo3', [10, 20], "I am foo3", 2, 0.1) new_bucket1 = FooBucket('new_bucket1', [foo3]) # append to same file with same manager, overwriting existing file with HDF5IO(self.path, manager=manager, mode='a') as io: read_foofile = io.read() # append to read container and call write read_foofile.add_bucket(new_bucket1) io.write(read_foofile) # check that new bucket was written with HDF5IO(self.path, manager=_get_manager(), mode='r') as io: read_foofile = io.read() self.assertEqual(len(read_foofile.buckets), 2) self.assertContainerEqual(read_foofile.buckets['new_bucket1'], new_bucket1) def test_write_add_append_double_write(self): """Test using the same IO object to append a container to a file twice.""" manager = _get_manager() with HDF5IO(self.path, manager=manager, mode='w') as io: io.write(self.foofile) foo3 = Foo('foo3', [10, 20], "I am foo3", 2, 0.1) new_bucket1 = FooBucket('new_bucket1', [foo3]) foo4 = Foo('foo4', [10, 20], "I am foo4", 2, 0.1) new_bucket2 = FooBucket('new_bucket2', [foo4]) # append to same file with same manager, overwriting existing file with HDF5IO(self.path, manager=manager, mode='a') as io: read_foofile = io.read() # append to read container and call write read_foofile.add_bucket(new_bucket1) io.write(read_foofile) # append to read container again and call write again read_foofile.add_bucket(new_bucket2) io.write(read_foofile) # check that both new buckets were written with HDF5IO(self.path, manager=_get_manager(), mode='r') as io: read_foofile = io.read() self.assertEqual(len(read_foofile.buckets), 3) self.assertContainerEqual(read_foofile.buckets['new_bucket1'], new_bucket1) self.assertContainerEqual(read_foofile.buckets['new_bucket2'], new_bucket2) class HDF5IOMultiFileTest(TestCase): """Tests for h5tools IO tools""" def setUp(self): numfiles = 3 self.paths = [get_temp_filepath() for i in range(numfiles)] # On Windows h5py cannot truncate an open file in write mode. # The temp file will be closed before h5py truncates it # and will be removed during the tearDown step. self.io = [HDF5IO(i, mode='a', manager=_get_manager()) for i in self.paths] self.f = [i._file for i in self.io] def tearDown(self): # Close all the files for i in self.io: i.close() del(i) self.io = None self.f = None # Make sure the files have been deleted for tf in self.paths: try: os.remove(tf) except OSError: pass def test_copy_file_with_external_links(self): # Create the first file foo1 = Foo('foo1', [0, 1, 2, 3, 4], "I am foo1", 17, 3.14) bucket1 = FooBucket('bucket1', [foo1]) foofile1 = FooFile(buckets=[bucket1]) # Write the first file self.io[0].write(foofile1) # Create the second file read_foofile1 = self.io[0].read() foo2 = Foo('foo2', read_foofile1.buckets['bucket1'].foos['foo1'].my_data, "I am foo2", 34, 6.28) bucket2 = FooBucket('bucket2', [foo2]) foofile2 = FooFile(buckets=[bucket2]) # Write the second file self.io[1].write(foofile2) self.io[1].close() self.io[0].close() # Don't forget to close the first file too # Copy the file self.io[2].close() with self.assertWarns(DeprecationWarning): HDF5IO.copy_file(source_filename=self.paths[1], dest_filename=self.paths[2], expand_external=True, expand_soft=False, expand_refs=False) # Test that everything is working as expected # Confirm that our original data file is correct f1 = File(self.paths[0], 'r') self.assertIsInstance(f1.get('/buckets/bucket1/foo_holder/foo1/my_data', getlink=True), HardLink) # Confirm that we successfully created and External Link in our second file f2 = File(self.paths[1], 'r') self.assertIsInstance(f2.get('/buckets/bucket2/foo_holder/foo2/my_data', getlink=True), ExternalLink) # Confirm that we successfully resolved the External Link when we copied our second file f3 = File(self.paths[2], 'r') self.assertIsInstance(f3.get('/buckets/bucket2/foo_holder/foo2/my_data', getlink=True), HardLink) class TestCloseLinks(TestCase): def setUp(self): self.path1 = get_temp_filepath() self.path2 = get_temp_filepath() def tearDown(self): if self.path1 is not None: os.remove(self.path1) # linked file may not be closed if self.path2 is not None: os.remove(self.path2) def test_close_file_with_links(self): # Create the first file foo1 = Foo('foo1', [0, 1, 2, 3, 4], "I am foo1", 17, 3.14) bucket1 = FooBucket('bucket1', [foo1]) foofile1 = FooFile(buckets=[bucket1]) # Write the first file with HDF5IO(self.path1, mode='w', manager=_get_manager()) as io: io.write(foofile1) # Create the second file manager = _get_manager() # use the same manager for read and write so that links work with HDF5IO(self.path1, mode='r', manager=manager) as read_io: read_foofile1 = read_io.read() foofile2 = FooFile(foo_link=read_foofile1.buckets['bucket1'].foos['foo1']) # cross-file link # Write the second file with HDF5IO(self.path2, mode='w', manager=manager) as write_io: write_io.write(foofile2) with HDF5IO(self.path2, mode='a', manager=_get_manager()) as new_io1: read_foofile2 = new_io1.read() # keep reference to container in memory self.assertTrue(read_foofile2.foo_link.my_data) new_io1.close_linked_files() self.assertFalse(read_foofile2.foo_link.my_data) # should be able to reopen both files with HDF5IO(self.path1, mode='a', manager=_get_manager()) as new_io3: new_io3.read() def test_double_close_file_with_links(self): # Create the first file foo1 = Foo('foo1', [0, 1, 2, 3, 4], "I am foo1", 17, 3.14) bucket1 = FooBucket('bucket1', [foo1]) foofile1 = FooFile(buckets=[bucket1]) # Write the first file with HDF5IO(self.path1, mode='w', manager=_get_manager()) as io: io.write(foofile1) # Create the second file manager = _get_manager() # use the same manager for read and write so that links work with HDF5IO(self.path1, mode='r', manager=manager) as read_io: read_foofile1 = read_io.read() foofile2 = FooFile(foo_link=read_foofile1.buckets['bucket1'].foos['foo1']) # cross-file link # Write the second file with HDF5IO(self.path2, mode='w', manager=manager) as write_io: write_io.write(foofile2) with HDF5IO(self.path2, mode='a', manager=_get_manager()) as new_io1: read_foofile2 = new_io1.read() # keep reference to container in memory read_foofile2.foo_link.my_data.file.close() # explicitly close the file from the h5dataset self.assertFalse(read_foofile2.foo_link.my_data) new_io1.close_linked_files() # make sure this does not fail because the linked-to file is already closed class HDF5IOInitNoFileTest(TestCase): """ Test if file does not exist, init with mode (r, r+) throws error, all others succeed """ def test_init_no_file_r(self): self.path = "test_init_nofile_r.h5" with self.assertRaisesWith(UnsupportedOperation, "Unable to open file %s in 'r' mode. File does not exist." % self.path): HDF5IO(self.path, mode='r') def test_init_no_file_rplus(self): self.path = "test_init_nofile_rplus.h5" with self.assertRaisesWith(UnsupportedOperation, "Unable to open file %s in 'r+' mode. File does not exist." % self.path): HDF5IO(self.path, mode='r+') def test_init_no_file_ok(self): # test that no errors are thrown modes = ('w', 'w-', 'x', 'a') for m in modes: self.path = "test_init_nofile.h5" with HDF5IO(self.path, mode=m): pass if os.path.exists(self.path): os.remove(self.path) class HDF5IOInitFileExistsTest(TestCase): """ Test if file exists, init with mode w-/x throws error, all others succeed """ def setUp(self): self.path = get_temp_filepath() temp_io = HDF5IO(self.path, mode='w') temp_io.close() self.io = None def tearDown(self): if self.io is not None: self.io.close() del(self.io) if os.path.exists(self.path): os.remove(self.path) def test_init_wminus_file_exists(self): with self.assertRaisesWith(UnsupportedOperation, "Unable to open file %s in 'w-' mode. File already exists." % self.path): self.io = HDF5IO(self.path, mode='w-') def test_init_x_file_exists(self): with self.assertRaisesWith(UnsupportedOperation, "Unable to open file %s in 'x' mode. File already exists." % self.path): self.io = HDF5IO(self.path, mode='x') def test_init_file_exists_ok(self): # test that no errors are thrown modes = ('r', 'r+', 'w', 'a') for m in modes: with HDF5IO(self.path, mode=m): pass class HDF5IOReadNoDataTest(TestCase): """ Test if file exists and there is no data, read with mode (r, r+, a) throws error """ def setUp(self): self.path = get_temp_filepath() temp_io = HDF5IO(self.path, mode='w') temp_io.close() self.io = None def tearDown(self): if self.io is not None: self.io.close() del(self.io) if os.path.exists(self.path): os.remove(self.path) def test_read_no_data_r(self): self.io = HDF5IO(self.path, mode='r') with self.assertRaisesWith(UnsupportedOperation, "Cannot read data from file %s in mode 'r'. There are no values." % self.path): self.io.read() def test_read_no_data_rplus(self): self.io = HDF5IO(self.path, mode='r+') with self.assertRaisesWith(UnsupportedOperation, "Cannot read data from file %s in mode 'r+'. There are no values." % self.path): self.io.read() def test_read_no_data_a(self): self.io = HDF5IO(self.path, mode='a') with self.assertRaisesWith(UnsupportedOperation, "Cannot read data from file %s in mode 'a'. There are no values." % self.path): self.io.read() class HDF5IOReadData(TestCase): """ Test if file exists and there is no data, read in mode (r, r+, a) is ok and read in mode w throws error """ def setUp(self): self.path = get_temp_filepath() foo1 = Foo('foo1', [0, 1, 2, 3, 4], "I am foo1", 17, 3.14) bucket1 = FooBucket('bucket1', [foo1]) self.foofile1 = FooFile(buckets=[bucket1]) with HDF5IO(self.path, manager=_get_manager(), mode='w') as temp_io: temp_io.write(self.foofile1) self.io = None def tearDown(self): if self.io is not None: self.io.close() del(self.io) if os.path.exists(self.path): os.remove(self.path) def test_read_file_ok(self): modes = ('r', 'r+', 'a') for m in modes: with HDF5IO(self.path, manager=_get_manager(), mode=m) as io: io.read() def test_read_file_w(self): with HDF5IO(self.path, manager=_get_manager(), mode='w') as io: with self.assertRaisesWith(UnsupportedOperation, "Cannot read from file %s in mode 'w'. Please use mode 'r', 'r+', or 'a'." % self.path): read_foofile1 = io.read() self.assertListEqual(self.foofile1.buckets['bucket1'].foos['foo1'].my_data, read_foofile1.buckets['bucket1'].foos['foo1'].my_data[:].tolist()) class HDF5IOReadBuilderClosed(TestCase): """Test if file exists but is closed, then read_builder raises an error. """ def setUp(self): self.path = get_temp_filepath() temp_io = HDF5IO(self.path, mode='w') temp_io.close() self.io = None def tearDown(self): if self.io is not None: self.io.close() del(self.io) if os.path.exists(self.path): os.remove(self.path) def test_read_closed(self): self.io = HDF5IO(self.path, mode='r') self.io.close() msg = "Cannot read data from closed HDF5 file '%s'" % self.path with self.assertRaisesWith(UnsupportedOperation, msg): self.io.read_builder() class HDF5IOWriteNoFile(TestCase): """ Test if file does not exist, write in mode (w, w-, x, a) is ok """ def setUp(self): foo1 = Foo('foo1', [0, 1, 2, 3, 4], "I am foo1", 17, 3.14) bucket1 = FooBucket('bucket1', [foo1]) self.foofile1 = FooFile(buckets=[bucket1]) self.path = 'test_write_nofile.h5' def tearDown(self): if os.path.exists(self.path): os.remove(self.path) def test_write_no_file_w_ok(self): self.__write_file('w') def test_write_no_file_wminus_ok(self): self.__write_file('w-') def test_write_no_file_x_ok(self): self.__write_file('x') def test_write_no_file_a_ok(self): self.__write_file('a') def __write_file(self, mode): with HDF5IO(self.path, manager=_get_manager(), mode=mode) as io: io.write(self.foofile1) with HDF5IO(self.path, manager=_get_manager(), mode='r') as io: read_foofile = io.read() self.assertListEqual(self.foofile1.buckets['bucket1'].foos['foo1'].my_data, read_foofile.buckets['bucket1'].foos['foo1'].my_data[:].tolist()) class HDF5IOWriteFileExists(TestCase): """ Test if file exists, write in mode (r+, w, a) is ok and write in mode r throws error """ def setUp(self): self.path = get_temp_filepath() foo1 = Foo('foo1', [0, 1, 2, 3, 4], "I am foo1", 17, 3.14) bucket1 = FooBucket('bucket1', [foo1]) self.foofile1 = FooFile(buckets=[bucket1]) foo2 = Foo('foo2', [0, 1, 2, 3, 4], "I am foo2", 17, 3.14) bucket2 = FooBucket('bucket2', [foo2]) self.foofile2 = FooFile(buckets=[bucket2]) with HDF5IO(self.path, manager=_get_manager(), mode='w') as io: io.write(self.foofile1) self.io = None def tearDown(self): if self.io is not None: self.io.close() del(self.io) if os.path.exists(self.path): os.remove(self.path) def test_write_rplus(self): with HDF5IO(self.path, manager=_get_manager(), mode='r+') as io: # even though foofile1 and foofile2 have different names, writing a # root object into a file that already has a root object, in r+ mode # should throw an error with self.assertRaisesWith(ValueError, "Unable to create group (name already exists)"): io.write(self.foofile2) def test_write_a(self): with HDF5IO(self.path, manager=_get_manager(), mode='a') as io: # even though foofile1 and foofile2 have different names, writing a # root object into a file that already has a root object, in a mode # should throw an error with self.assertRaisesWith(ValueError, "Unable to create group (name already exists)"): io.write(self.foofile2) def test_write_w(self): # mode 'w' should overwrite contents of file with HDF5IO(self.path, manager=_get_manager(), mode='w') as io: io.write(self.foofile2) with HDF5IO(self.path, manager=_get_manager(), mode='r') as io: read_foofile = io.read() self.assertListEqual(self.foofile2.buckets['bucket2'].foos['foo2'].my_data, read_foofile.buckets['bucket2'].foos['foo2'].my_data[:].tolist()) def test_write_r(self): with HDF5IO(self.path, manager=_get_manager(), mode='r') as io: with self.assertRaisesWith(UnsupportedOperation, ("Cannot write to file %s in mode 'r'. " "Please use mode 'r+', 'w', 'w-', 'x', or 'a'") % self.path): io.write(self.foofile2) class TestWritten(TestCase): def setUp(self): self.manager = _get_manager() self.path = get_temp_filepath() foo1 = Foo('foo1', [0, 1, 2, 3, 4], "I am foo1", 17, 3.14) foo2 = Foo('foo2', [5, 6, 7, 8, 9], "I am foo2", 34, 6.28) foobucket = FooBucket('bucket1', [foo1, foo2]) self.foofile = FooFile([foobucket]) def tearDown(self): if os.path.exists(self.path): os.remove(self.path) def test_set_written_on_write(self): """Test that write_builder changes the written flag of the builder and its children from False to True.""" with HDF5IO(self.path, manager=self.manager, mode='w') as io: builder = self.manager.build(container=self.foofile, source=self.path) self.assertFalse(io.get_written(builder)) self._check_written_children(io, builder, False) io.write_builder(builder) self.assertTrue(io.get_written(builder)) self._check_written_children(io, builder, True) def _check_written_children(self, io, builder, val): """Test whether the io object has the written flag of the child builders set to val.""" for group_bldr in builder.groups.values(): self.assertEqual(io.get_written(group_bldr), val) self._check_written_children(io, group_bldr, val) for dset_bldr in builder.datasets.values(): self.assertEqual(io.get_written(dset_bldr), val) for link_bldr in builder.links.values(): self.assertEqual(io.get_written(link_bldr), val) class H5DataIOValid(TestCase): def setUp(self): self.paths = [get_temp_filepath(), ] self.foo1 = Foo('foo1', H5DataIO([1, 2, 3, 4, 5]), "I am foo1", 17, 3.14) bucket1 = FooBucket('bucket1', [self.foo1]) foofile1 = FooFile(buckets=[bucket1]) with HDF5IO(self.paths[0], manager=_get_manager(), mode='w') as io: io.write(foofile1) def tearDown(self): for path in self.paths: if os.path.exists(path): os.remove(path) def test_valid(self): self.assertTrue(self.foo1.my_data.valid) def test_read_valid(self): """Test that h5py.H5Dataset.id.valid works as expected""" with HDF5IO(self.paths[0], manager=_get_manager(), mode='r') as io: read_foofile1 = io.read() self.assertTrue(read_foofile1.buckets['bucket1'].foos['foo1'].my_data.id.valid) self.assertFalse(read_foofile1.buckets['bucket1'].foos['foo1'].my_data.id.valid) def test_link(self): """Test that wrapping of linked data within H5DataIO """ with HDF5IO(self.paths[0], manager=_get_manager(), mode='r') as io: read_foofile1 = io.read() self.foo2 = Foo('foo2', H5DataIO(data=read_foofile1.buckets['bucket1'].foos['foo1'].my_data), "I am foo2", 17, 3.14) bucket2 = FooBucket('bucket2', [self.foo2]) foofile2 = FooFile(buckets=[bucket2]) self.paths.append(get_temp_filepath()) with HDF5IO(self.paths[1], manager=_get_manager(), mode='w') as io: io.write(foofile2) self.assertTrue(self.foo2.my_data.valid) # test valid self.assertEqual(len(self.foo2.my_data), 5) # test len self.assertEqual(self.foo2.my_data.shape, (5,)) # test getattr with shape self.assertTrue(np.array_equal(np.array(self.foo2.my_data), [1, 2, 3, 4, 5])) # test array conversion # test loop through iterable match = [1, 2, 3, 4, 5] for (i, j) in zip(self.foo2.my_data, match): self.assertEqual(i, j) # test iterator my_iter = iter(self.foo2.my_data) self.assertEqual(next(my_iter), 1) # foo2.my_data dataset is now closed self.assertFalse(self.foo2.my_data.valid) with self.assertRaisesWith(InvalidDataIOError, "Cannot get length of data. Data is not valid."): len(self.foo2.my_data) with self.assertRaisesWith(InvalidDataIOError, "Cannot get attribute 'shape' of data. Data is not valid."): self.foo2.my_data.shape with self.assertRaisesWith(InvalidDataIOError, "Cannot convert data to array. Data is not valid."): np.array(self.foo2.my_data) with self.assertRaisesWith(InvalidDataIOError, "Cannot iterate on data. Data is not valid."): for i in self.foo2.my_data: pass with self.assertRaisesWith(InvalidDataIOError, "Cannot iterate on data. Data is not valid."): iter(self.foo2.my_data) # re-open the file with the data linking to other file (still closed) with HDF5IO(self.paths[1], manager=_get_manager(), mode='r') as io: read_foofile2 = io.read() read_foo2 = read_foofile2.buckets['bucket2'].foos['foo2'] # note that read_foo2 dataset does not have an attribute 'valid' self.assertEqual(len(read_foo2.my_data), 5) # test len self.assertEqual(read_foo2.my_data.shape, (5,)) # test getattr with shape self.assertTrue(np.array_equal(np.array(read_foo2.my_data), [1, 2, 3, 4, 5])) # test array conversion # test loop through iterable match = [1, 2, 3, 4, 5] for (i, j) in zip(read_foo2.my_data, match): self.assertEqual(i, j) # test iterator my_iter = iter(read_foo2.my_data) self.assertEqual(next(my_iter), 1) class TestReadLink(TestCase): def setUp(self): self.target_path = get_temp_filepath() self.link_path = get_temp_filepath() root1 = GroupBuilder(name='root') subgroup = GroupBuilder(name='test_group') root1.set_group(subgroup) dataset = DatasetBuilder('test_dataset', data=[1, 2, 3, 4]) subgroup.set_dataset(dataset) root2 = GroupBuilder(name='root') link_group = LinkBuilder(subgroup, 'link_to_test_group') root2.set_link(link_group) link_dataset = LinkBuilder(dataset, 'link_to_test_dataset') root2.set_link(link_dataset) with HDF5IO(self.target_path, manager=_get_manager(), mode='w') as io: io.write_builder(root1) root1.source = self.target_path with HDF5IO(self.link_path, manager=_get_manager(), mode='w') as io: io.write_builder(root2) root2.source = self.link_path self.ios = [] def tearDown(self): for io in self.ios: io.close_linked_files() if os.path.exists(self.target_path): os.remove(self.target_path) if os.path.exists(self.link_path): os.remove(self.link_path) def test_set_link_loc(self): """ Test that Builder location is set when it is read as a link """ read_io = HDF5IO(self.link_path, manager=_get_manager(), mode='r') self.ios.append(read_io) # store IO object for closing in tearDown bldr = read_io.read_builder() self.assertEqual(bldr['link_to_test_group'].builder.location, '/') self.assertEqual(bldr['link_to_test_dataset'].builder.location, '/test_group') read_io.close() def test_link_to_link(self): """ Test that link to link gets written and read properly """ link_to_link_path = get_temp_filepath() read_io1 = HDF5IO(self.link_path, manager=_get_manager(), mode='r') self.ios.append(read_io1) # store IO object for closing in tearDown bldr1 = read_io1.read_builder() root3 = GroupBuilder(name='root') link = LinkBuilder(bldr1['link_to_test_group'].builder, 'link_to_link') root3.set_link(link) with HDF5IO(link_to_link_path, manager=_get_manager(), mode='w') as io: io.write_builder(root3) read_io1.close() read_io2 = HDF5IO(link_to_link_path, manager=_get_manager(), mode='r') self.ios.append(read_io2) bldr2 = read_io2.read_builder() self.assertEqual(bldr2['link_to_link'].builder.source, self.target_path) read_io2.close() def test_broken_link(self): """Test that opening a file with a broken link raises a warning but is still readable.""" os.remove(self.target_path) # with self.assertWarnsWith(BrokenLinkWarning, '/link_to_test_dataset'): # can't check both warnings with self.assertWarnsWith(BrokenLinkWarning, '/link_to_test_group'): with HDF5IO(self.link_path, manager=_get_manager(), mode='r') as read_io: bldr = read_io.read_builder() self.assertDictEqual(bldr.links, {}) def test_broken_linked_data(self): """Test that opening a file with a broken link raises a warning but is still readable.""" manager = _get_manager() with HDF5IO(self.target_path, manager=manager, mode='r') as read_io: read_root = read_io.read_builder() read_dataset_data = read_root.groups['test_group'].datasets['test_dataset'].data with HDF5IO(self.link_path, manager=manager, mode='w') as write_io: root2 = GroupBuilder(name='root') dataset = DatasetBuilder(name='link_to_test_dataset', data=read_dataset_data) root2.set_dataset(dataset) write_io.write_builder(root2, link_data=True) os.remove(self.target_path) with self.assertWarnsWith(BrokenLinkWarning, '/link_to_test_dataset'): with HDF5IO(self.link_path, manager=_get_manager(), mode='r') as read_io: bldr = read_io.read_builder() self.assertDictEqual(bldr.links, {}) class TestBuildWriteLinkToLink(TestCase): def setUp(self): self.paths = [ get_temp_filepath(), get_temp_filepath(), get_temp_filepath() ] self.ios = [] def tearDown(self): for io in self.ios: io.close_linked_files() for p in self.paths: if os.path.exists(p): os.remove(p) def test_external_link_to_external_link(self): """Test writing a file with external links to external links.""" foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) foobucket = FooBucket('bucket1', [foo1]) foofile = FooFile([foobucket]) with HDF5IO(self.paths[0], manager=_get_manager(), mode='w') as write_io: write_io.write(foofile) manager = _get_manager() with HDF5IO(self.paths[0], manager=manager, mode='r') as read_io: read_foofile = read_io.read() # make external link to existing group foofile2 = FooFile(foo_link=read_foofile.buckets['bucket1'].foos['foo1']) with HDF5IO(self.paths[1], manager=manager, mode='w') as write_io: write_io.write(foofile2) manager = _get_manager() with HDF5IO(self.paths[1], manager=manager, mode='r') as read_io: self.ios.append(read_io) # track IO objects for tearDown read_foofile2 = read_io.read() foofile3 = FooFile(foo_link=read_foofile2.foo_link) # make external link to external link with HDF5IO(self.paths[2], manager=manager, mode='w') as write_io: write_io.write(foofile3) with HDF5IO(self.paths[2], manager=_get_manager(), mode='r') as read_io: self.ios.append(read_io) # track IO objects for tearDown read_foofile3 = read_io.read() self.assertEqual(read_foofile3.foo_link.container_source, self.paths[0]) def test_external_link_to_soft_link(self): """Test writing a file with external links to external links.""" foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) foobucket = FooBucket('bucket1', [foo1]) foofile = FooFile([foobucket], foo_link=foo1) # create soft link with HDF5IO(self.paths[0], manager=_get_manager(), mode='w') as write_io: write_io.write(foofile) manager = _get_manager() with HDF5IO(self.paths[0], manager=manager, mode='r') as read_io: read_foofile = read_io.read() foofile2 = FooFile(foo_link=read_foofile.foo_link) # make external link to existing soft link with HDF5IO(self.paths[1], manager=manager, mode='w') as write_io: write_io.write(foofile2) manager = _get_manager() with HDF5IO(self.paths[1], manager=manager, mode='r') as read_io: self.ios.append(read_io) # track IO objects for tearDown read_foofile2 = read_io.read() foofile3 = FooFile(foo_link=read_foofile2.foo_link) # make external link to external link with HDF5IO(self.paths[2], manager=manager, mode='w') as write_io: write_io.write(foofile3) with HDF5IO(self.paths[2], manager=_get_manager(), mode='r') as read_io: self.ios.append(read_io) # track IO objects for tearDown read_foofile3 = read_io.read() self.assertEqual(read_foofile3.foo_link.container_source, self.paths[0]) class TestLinkData(TestCase): def setUp(self): self.target_path = get_temp_filepath() self.link_path = get_temp_filepath() root1 = GroupBuilder(name='root') subgroup = GroupBuilder(name='test_group') root1.set_group(subgroup) dataset = DatasetBuilder('test_dataset', data=[1, 2, 3, 4]) subgroup.set_dataset(dataset) with HDF5IO(self.target_path, manager=_get_manager(), mode='w') as io: io.write_builder(root1) def tearDown(self): if os.path.exists(self.target_path): os.remove(self.target_path) if os.path.exists(self.link_path): os.remove(self.link_path) def test_link_data_true(self): """Test that the argument link_data=True for write_builder creates an external link.""" manager = _get_manager() with HDF5IO(self.target_path, manager=manager, mode='r') as read_io: read_root = read_io.read_builder() read_dataset_data = read_root.groups['test_group'].datasets['test_dataset'].data with HDF5IO(self.link_path, manager=manager, mode='w') as write_io: root2 = GroupBuilder(name='root') dataset = DatasetBuilder(name='link_to_test_dataset', data=read_dataset_data) root2.set_dataset(dataset) write_io.write_builder(root2, link_data=True) with File(self.link_path, mode='r') as f: self.assertIsInstance(f.get('link_to_test_dataset', getlink=True), ExternalLink) def test_link_data_false(self): """Test that the argument link_data=False for write_builder copies the data.""" manager = _get_manager() with HDF5IO(self.target_path, manager=manager, mode='r') as read_io: read_root = read_io.read_builder() read_dataset_data = read_root.groups['test_group'].datasets['test_dataset'].data with HDF5IO(self.link_path, manager=manager, mode='w') as write_io: root2 = GroupBuilder(name='root') dataset = DatasetBuilder(name='link_to_test_dataset', data=read_dataset_data) root2.set_dataset(dataset) write_io.write_builder(root2, link_data=False) with File(self.link_path, mode='r') as f: self.assertFalse(isinstance(f.get('link_to_test_dataset', getlink=True), ExternalLink)) self.assertListEqual(f.get('link_to_test_dataset')[:].tolist(), [1, 2, 3, 4]) class TestLoadNamespaces(TestCase): def setUp(self): self.manager = _get_manager() self.path = get_temp_filepath() container = FooFile() with HDF5IO(self.path, manager=self.manager, mode='w') as io: io.write(container) def tearDown(self): if os.path.exists(self.path): os.remove(self.path) def test_load_namespaces_none_version(self): """Test that reading a file with a cached namespace and None version works but raises a warning.""" # make the file have group name "None" instead of "0.1.0" (namespace version is used as group name) # and set the version key to "None" with h5py.File(self.path, mode='r+') as f: # rename the group f.move('/specifications/test_core/0.1.0', '/specifications/test_core/None') # replace the namespace dataset with a serialized dict with the version key set to 'None' new_ns = ('{"namespaces":[{"doc":"a test namespace","schema":[{"source":"test"}],"name":"test_core",' '"version":"None"}]}') f['/specifications/test_core/None/namespace'][()] = new_ns # load the namespace from file ns_catalog = NamespaceCatalog() msg = "Loaded namespace '%s' is unversioned. Please notify the extension author." % CORE_NAMESPACE with self.assertWarnsWith(UserWarning, msg): HDF5IO.load_namespaces(ns_catalog, self.path) def test_load_namespaces_unversioned(self): """Test that reading a file with a cached, unversioned version works but raises a warning.""" # make the file have group name "unversioned" instead of "0.1.0" (namespace version is used as group name) # and remove the version key with h5py.File(self.path, mode='r+') as f: # rename the group f.move('/specifications/test_core/0.1.0', '/specifications/test_core/unversioned') # replace the namespace dataset with a serialized dict without the version key new_ns = ('{"namespaces":[{"doc":"a test namespace","schema":[{"source":"test"}],"name":"test_core"}]}') f['/specifications/test_core/unversioned/namespace'][()] = new_ns # load the namespace from file ns_catalog = NamespaceCatalog() msg = ("Loaded namespace '%s' is missing the required key 'version'. Version will be set to " "'%s'. Please notify the extension author." % (CORE_NAMESPACE, SpecNamespace.UNVERSIONED)) with self.assertWarnsWith(UserWarning, msg): HDF5IO.load_namespaces(ns_catalog, self.path) def test_load_namespaces_path(self): """Test that loading namespaces given a path is OK and returns the correct dictionary.""" ns_catalog = NamespaceCatalog() d = HDF5IO.load_namespaces(ns_catalog, self.path) self.assertEqual(d, {'test_core': {}}) # test_core has no dependencies def test_load_namespaces_no_path_no_file(self): """Test that loading namespaces without a path or file raises an error.""" ns_catalog = NamespaceCatalog() msg = "Either the 'path' or 'file' argument must be supplied." with self.assertRaisesWith(ValueError, msg): HDF5IO.load_namespaces(ns_catalog) def test_load_namespaces_file_no_path(self): """ Test that loading namespaces from an h5py.File not backed by a file on disk is OK and does not close the file. """ with open(self.path, 'rb') as raw_file: buffer = BytesIO(raw_file.read()) file_obj = h5py.File(buffer, 'r') ns_catalog = NamespaceCatalog() d = HDF5IO.load_namespaces(ns_catalog, file=file_obj) self.assertTrue(file_obj.__bool__()) # check file object is still open self.assertEqual(d, {'test_core': {}}) file_obj.close() def test_load_namespaces_file_path_matched(self): """Test that loading namespaces given an h5py.File and path is OK and does not close the file.""" with h5py.File(self.path, 'r') as file_obj: ns_catalog = NamespaceCatalog() d = HDF5IO.load_namespaces(ns_catalog, path=self.path, file=file_obj) self.assertTrue(file_obj.__bool__()) # check file object is still open self.assertEqual(d, {'test_core': {}}) def test_load_namespaces_file_path_mismatched(self): """Test that loading namespaces given an h5py.File and path that are mismatched raises an error.""" with h5py.File(self.path, 'r') as file_obj: ns_catalog = NamespaceCatalog() msg = "You argued 'different_path' as this object's path, but supplied a file with filename: %s" % self.path with self.assertRaisesWith(ValueError, msg): HDF5IO.load_namespaces(ns_catalog, path='different_path', file=file_obj) def test_load_namespaces_with_pathlib_path(self): """Test that loading a namespace using a valid pathlib Path is OK and returns the correct dictionary.""" pathlib_path = Path(self.path) ns_catalog = NamespaceCatalog() d = HDF5IO.load_namespaces(ns_catalog, pathlib_path) self.assertEqual(d, {'test_core': {}}) # test_core has no dependencies def test_load_namespaces_with_dependencies(self): """Test loading namespaces where one includes another.""" file_spec = GroupSpec(doc="A FooFile", data_type_def='FooFile') spec_catalog = SpecCatalog() name = 'test_core2' namespace = SpecNamespace( doc='a test namespace', name=name, schema=[{'source': 'test.yaml', 'namespace': 'test_core'}], # depends on test_core version='0.1.0', catalog=spec_catalog ) spec_catalog.register_spec(file_spec, 'test.yaml') namespace_catalog = NamespaceCatalog() namespace_catalog.add_namespace(name, namespace) type_map = TypeMap(namespace_catalog) type_map.register_container_type(name, 'FooFile', FooFile) manager = BuildManager(type_map) container = FooFile() with HDF5IO(self.path, manager=manager, mode='a') as io: # append to file io.write(container) ns_catalog = NamespaceCatalog() d = HDF5IO.load_namespaces(ns_catalog, self.path) self.assertEqual(d, {'test_core': {}, 'test_core2': {'test_core': ('Foo', 'FooBucket', 'FooFile')}}) def test_load_namespaces_no_specloc(self): """Test loading namespaces where the file does not contain a SPEC_LOC_ATTR.""" # delete the spec location attribute from the file with h5py.File(self.path, mode='r+') as f: del f.attrs[SPEC_LOC_ATTR] # load the namespace from file ns_catalog = NamespaceCatalog() msg = "No cached namespaces found in %s" % self.path with self.assertWarnsWith(UserWarning, msg): ret = HDF5IO.load_namespaces(ns_catalog, self.path) self.assertDictEqual(ret, {}) def test_load_namespaces_resolve_custom_deps(self): """Test that reading a file with a cached namespace and different def/inc keys works.""" # Setup all the data we need foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) foobucket = FooBucket('bucket1', [foo1]) foofile = FooFile([foobucket]) with HDF5IO(self.path, manager=self.manager, mode='w') as io: io.write(foofile) with h5py.File(self.path, mode='r+') as f: # add two types where one extends the other and overrides an attribute # check that the inherited attribute resolves correctly despite having a different def/inc key than those # used in the namespace catalog added_types = (',{"data_type_def":"BigFoo","data_type_inc":"Foo","doc":"doc","attributes":[' '{"name":"my_attr","dtype":"text","doc":"an attr"}]},' '{"data_type_def":"BiggerFoo","data_type_inc":"BigFoo","doc":"doc"}]}') old_test_source = f['/specifications/test_core/0.1.0/test'] old_test_source[()] = old_test_source[()][0:-2] + added_types # strip the ]} from end, then add to groups new_ns = ('{"namespaces":[{"doc":"a test namespace","schema":[' '{"namespace":"test_core","my_data_types":["Foo"]},' '{"source":"test-ext.extensions"}' '],"name":"test-ext","version":"0.1.0"}]}') f.create_dataset('/specifications/test-ext/0.1.0/namespace', data=new_ns) new_ext = '{"groups":[{"my_data_type_def":"FooExt","my_data_type_inc":"Foo","doc":"doc"}]}' f.create_dataset('/specifications/test-ext/0.1.0/test-ext.extensions', data=new_ext) # load the namespace from file ns_catalog = NamespaceCatalog(CustomGroupSpec, CustomDatasetSpec, CustomSpecNamespace) namespace_deps = HDF5IO.load_namespaces(ns_catalog, self.path) # test that the dependencies are correct expected = ('Foo',) self.assertTupleEqual((namespace_deps['test-ext']['test_core']), expected) # test that the types are loaded types = ns_catalog.get_types('test-ext.extensions') expected = ('FooExt',) self.assertTupleEqual(types, expected) # test that the def_key is updated for test-ext ns foo_ext_spec = ns_catalog.get_spec('test-ext', 'FooExt') self.assertTrue('my_data_type_def' in foo_ext_spec) self.assertTrue('my_data_type_inc' in foo_ext_spec) # test that the data_type_def is replaced with my_data_type_def for test_core ns bigger_foo_spec = ns_catalog.get_spec('test_core', 'BiggerFoo') self.assertTrue('my_data_type_def' in bigger_foo_spec) self.assertTrue('my_data_type_inc' in bigger_foo_spec) # test that my_attr is properly inherited in BiggerFoo from BigFoo and attr1, attr3 are inherited from Foo self.assertTrue(len(bigger_foo_spec.attributes) == 3) class TestGetNamespaces(TestCase): def create_test_namespace(self, name, version): file_spec = GroupSpec(doc="A FooFile", data_type_def='FooFile') spec_catalog = SpecCatalog() namespace = SpecNamespace( doc='a test namespace', name=name, schema=[{'source': 'test.yaml'}], version=version, catalog=spec_catalog ) spec_catalog.register_spec(file_spec, 'test.yaml') return namespace def write_test_file(self, name, version, mode): namespace = self.create_test_namespace(name, version) namespace_catalog = NamespaceCatalog() namespace_catalog.add_namespace(name, namespace) type_map = TypeMap(namespace_catalog) type_map.register_container_type(name, 'FooFile', FooFile) manager = BuildManager(type_map) with HDF5IO(self.path, manager=manager, mode=mode) as io: io.write(self.container) def setUp(self): self.path = get_temp_filepath() self.container = FooFile() def tearDown(self): if os.path.exists(self.path): os.remove(self.path) # see other tests for path & file match/mismatch testing in TestLoadNamespaces def test_get_namespaces_with_path(self): """Test getting namespaces given a path.""" self.write_test_file('test_core', '0.1.0', 'w') ret = HDF5IO.get_namespaces(path=self.path) self.assertEqual(ret, {'test_core': '0.1.0'}) def test_get_namespaces_with_file(self): """Test getting namespaces given a file object.""" self.write_test_file('test_core', '0.1.0', 'w') with File(self.path, 'r') as f: ret = HDF5IO.get_namespaces(file=f) self.assertEqual(ret, {'test_core': '0.1.0'}) self.assertTrue(f.__bool__()) # check file object is still open def test_get_namespaces_different_versions(self): """Test getting namespaces with multiple versions given a path.""" # write file with spec with smaller version string self.write_test_file('test_core', '0.0.10', 'w') # append to file with spec with larger version string self.write_test_file('test_core', '0.1.0', 'a') ret = HDF5IO.get_namespaces(path=self.path) self.assertEqual(ret, {'test_core': '0.1.0'}) def test_get_namespaces_multiple_namespaces(self): """Test getting multiple namespaces given a path.""" self.write_test_file('test_core1', '0.0.10', 'w') self.write_test_file('test_core2', '0.1.0', 'a') ret = HDF5IO.get_namespaces(path=self.path) self.assertEqual(ret, {'test_core1': '0.0.10', 'test_core2': '0.1.0'}) def test_get_namespaces_none_version(self): """Test getting namespaces where file has one None-versioned namespace.""" self.write_test_file('test_core', '0.1.0', 'w') # make the file have group name "None" instead of "0.1.0" (namespace version is used as group name) # and set the version key to "None" with h5py.File(self.path, mode='r+') as f: # rename the group f.move('/specifications/test_core/0.1.0', '/specifications/test_core/None') # replace the namespace dataset with a serialized dict with the version key set to 'None' new_ns = ('{"namespaces":[{"doc":"a test namespace","schema":[{"source":"test"}],"name":"test_core",' '"version":"None"}]}') f['/specifications/test_core/None/namespace'][()] = new_ns ret = HDF5IO.get_namespaces(path=self.path) self.assertEqual(ret, {'test_core': 'None'}) def test_get_namespaces_none_and_other_version(self): """Test getting namespaces file has a namespace with a normal version and an 'None" version.""" self.write_test_file('test_core', '0.1.0', 'w') # make the file have group name "None" instead of "0.1.0" (namespace version is used as group name) # and set the version key to "None" with h5py.File(self.path, mode='r+') as f: # rename the group f.move('/specifications/test_core/0.1.0', '/specifications/test_core/None') # replace the namespace dataset with a serialized dict with the version key set to 'None' new_ns = ('{"namespaces":[{"doc":"a test namespace","schema":[{"source":"test"}],"name":"test_core",' '"version":"None"}]}') f['/specifications/test_core/None/namespace'][()] = new_ns # append to file with spec with a larger version string self.write_test_file('test_core', '0.2.0', 'a') ret = HDF5IO.get_namespaces(path=self.path) self.assertEqual(ret, {'test_core': '0.2.0'}) def test_get_namespaces_unversioned(self): """Test getting namespaces where file has one unversioned namespace.""" self.write_test_file('test_core', '0.1.0', 'w') # make the file have group name "unversioned" instead of "0.1.0" (namespace version is used as group name) with h5py.File(self.path, mode='r+') as f: # rename the group f.move('/specifications/test_core/0.1.0', '/specifications/test_core/unversioned') # replace the namespace dataset with a serialized dict without the version key new_ns = ('{"namespaces":[{"doc":"a test namespace","schema":[{"source":"test"}],"name":"test_core"}]}') f['/specifications/test_core/unversioned/namespace'][()] = new_ns ret = HDF5IO.get_namespaces(path=self.path) self.assertEqual(ret, {'test_core': 'unversioned'}) def test_get_namespaces_unversioned_and_other(self): """Test getting namespaces file has a namespace with a normal version and an 'unversioned" version.""" self.write_test_file('test_core', '0.1.0', 'w') # make the file have group name "unversioned" instead of "0.1.0" (namespace version is used as group name) with h5py.File(self.path, mode='r+') as f: # rename the group f.move('/specifications/test_core/0.1.0', '/specifications/test_core/unversioned') # replace the namespace dataset with a serialized dict without the version key new_ns = ('{"namespaces":[{"doc":"a test namespace","schema":[{"source":"test"}],"name":"test_core"}]}') f['/specifications/test_core/unversioned/namespace'][()] = new_ns # append to file with spec with a larger version string self.write_test_file('test_core', '0.2.0', 'a') ret = HDF5IO.get_namespaces(path=self.path) self.assertEqual(ret, {'test_core': '0.2.0'}) def test_get_namespaces_no_specloc(self): """Test getting namespaces where the file does not contain a SPEC_LOC_ATTR.""" self.write_test_file('test_core', '0.1.0', 'w') # delete the spec location attribute from the file with h5py.File(self.path, mode='r+') as f: del f.attrs[SPEC_LOC_ATTR] # load the namespace from file msg = "No cached namespaces found in %s" % self.path with self.assertWarnsWith(UserWarning, msg): ret = HDF5IO.get_namespaces(path=self.path) self.assertDictEqual(ret, {}) class TestExport(TestCase): """Test exporting HDF5 to HDF5 using HDF5IO.export_container_to_hdf5.""" def setUp(self): self.paths = [ get_temp_filepath(), get_temp_filepath(), get_temp_filepath(), get_temp_filepath(), ] self.ios = [] def tearDown(self): for io in self.ios: io.close_linked_files() for p in self.paths: if os.path.exists(p): os.remove(p) def test_basic(self): """Test that exporting a written container works.""" foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) foobucket = FooBucket('bucket1', [foo1]) foofile = FooFile([foobucket]) with HDF5IO(self.paths[0], manager=_get_manager(), mode='w') as write_io: write_io.write(foofile) with HDF5IO(self.paths[0], manager=_get_manager(), mode='r') as read_io: with HDF5IO(self.paths[1], mode='w') as export_io: export_io.export(src_io=read_io) self.assertTrue(os.path.exists(self.paths[1])) self.assertEqual(foofile.container_source, self.paths[0]) with HDF5IO(self.paths[1], manager=_get_manager(), mode='r') as read_io: read_foofile = read_io.read() self.assertEqual(read_foofile.container_source, self.paths[1]) self.assertContainerEqual(foofile, read_foofile, ignore_hdmf_attrs=True) self.assertEqual(os.path.abspath(read_foofile.buckets['bucket1'].foos['foo1'].my_data.file.filename), self.paths[1]) def test_basic_container(self): """Test that exporting a written container, passing in the container arg, works.""" foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) foobucket = FooBucket('bucket1', [foo1]) foofile = FooFile([foobucket]) with HDF5IO(self.paths[0], manager=_get_manager(), mode='w') as write_io: write_io.write(foofile) with HDF5IO(self.paths[0], manager=_get_manager(), mode='r') as read_io: read_foofile = read_io.read() with HDF5IO(self.paths[1], mode='w') as export_io: export_io.export(src_io=read_io, container=read_foofile) self.assertTrue(os.path.exists(self.paths[1])) self.assertEqual(foofile.container_source, self.paths[0]) with HDF5IO(self.paths[1], manager=_get_manager(), mode='r') as read_io: read_foofile = read_io.read() self.assertEqual(read_foofile.container_source, self.paths[1]) self.assertContainerEqual(foofile, read_foofile, ignore_hdmf_attrs=True) def test_container_part(self): """Test that exporting a part of a written container raises an error.""" foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) foobucket = FooBucket('bucket1', [foo1]) foofile = FooFile([foobucket]) with HDF5IO(self.paths[0], manager=_get_manager(), mode='w') as write_io: write_io.write(foofile) with HDF5IO(self.paths[0], manager=_get_manager(), mode='r') as read_io: read_foofile = read_io.read() with HDF5IO(self.paths[1], mode='w') as export_io: msg = ("The provided container must be the root of the hierarchy of the source used to read the " "container.") with self.assertRaisesWith(ValueError, msg): export_io.export(src_io=read_io, container=read_foofile.buckets['bucket1']) def test_container_unknown(self): """Test that exporting a container that did not come from the src_io object raises an error.""" foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) foobucket = FooBucket('bucket1', [foo1]) foofile = FooFile([foobucket]) with HDF5IO(self.paths[0], manager=_get_manager(), mode='w') as write_io: write_io.write(foofile) with HDF5IO(self.paths[0], manager=_get_manager(), mode='r') as read_io: with HDF5IO(self.paths[1], mode='w') as export_io: dummy_file = FooFile([]) msg = "The provided container must have been read by the provided src_io." with self.assertRaisesWith(ValueError, msg): export_io.export(src_io=read_io, container=dummy_file) def test_cache_spec(self): """Test that exporting with cache_spec works.""" foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) foobucket = FooBucket('bucket1', [foo1]) foofile = FooFile([foobucket]) with HDF5IO(self.paths[0], manager=_get_manager(), mode='w') as write_io: write_io.write(foofile) with HDF5IO(self.paths[0], manager=_get_manager(), mode='r') as read_io: read_foofile = read_io.read() with HDF5IO(self.paths[1], mode='w') as export_io: export_io.export( src_io=read_io, container=read_foofile, cache_spec=False, ) with File(self.paths[1], 'r') as f: self.assertNotIn('specifications', f) def test_soft_link_group(self): """Test that exporting a written file with soft linked groups keeps links within the file.""" foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) foobucket = FooBucket('bucket1', [foo1]) foofile = FooFile([foobucket], foo_link=foo1) with HDF5IO(self.paths[0], manager=_get_manager(), mode='w') as write_io: write_io.write(foofile) with HDF5IO(self.paths[0], manager=_get_manager(), mode='r') as read_io: with HDF5IO(self.paths[1], mode='w') as export_io: export_io.export(src_io=read_io) with HDF5IO(self.paths[1], manager=_get_manager(), mode='r') as read_io: self.ios.append(read_io) # track IO objects for tearDown read_foofile2 = read_io.read() # make sure the linked group is within the same file self.assertEqual(read_foofile2.foo_link.container_source, self.paths[1]) def test_soft_link_dataset(self): """Test that exporting a written file with soft linked datasets keeps links within the file.""" foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) foobucket = FooBucket('bucket1', [foo1]) foofile = FooFile([foobucket], foofile_data=foo1.my_data) with HDF5IO(self.paths[0], manager=_get_manager(), mode='w') as write_io: write_io.write(foofile) with HDF5IO(self.paths[0], manager=_get_manager(), mode='r') as read_io: self.ios.append(read_io) # track IO objects for tearDown with HDF5IO(self.paths[1], mode='w') as export_io: export_io.export(src_io=read_io) with HDF5IO(self.paths[1], manager=_get_manager(), mode='r') as read_io: self.ios.append(read_io) # track IO objects for tearDown read_foofile2 = read_io.read() # make sure the linked dataset is within the same file self.assertEqual(read_foofile2.foofile_data.file.filename, self.paths[1]) def test_external_link_group(self): """Test that exporting a written file with external linked groups maintains the links.""" foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) foobucket = FooBucket('bucket1', [foo1]) foofile = FooFile([foobucket]) with HDF5IO(self.paths[0], manager=_get_manager(), mode='w') as read_io: read_io.write(foofile) manager = _get_manager() with HDF5IO(self.paths[0], manager=manager, mode='r') as read_io: read_foofile = read_io.read() # make external link to existing group foofile2 = FooFile(foo_link=read_foofile.buckets['bucket1'].foos['foo1']) with HDF5IO(self.paths[1], manager=manager, mode='w') as write_io: write_io.write(foofile2) with HDF5IO(self.paths[1], manager=_get_manager(), mode='r') as read_io: self.ios.append(read_io) # track IO objects for tearDown read_foofile2 = read_io.read() with HDF5IO(self.paths[2], mode='w') as export_io: export_io.export(src_io=read_io) with HDF5IO(self.paths[2], manager=_get_manager(), mode='r') as read_io: self.ios.append(read_io) # track IO objects for tearDown read_foofile2 = read_io.read() # make sure the linked group is read from the first file self.assertEqual(read_foofile2.foo_link.container_source, self.paths[0]) def test_external_link_dataset(self): """Test that exporting a written file with external linked datasets maintains the links.""" foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) foobucket = FooBucket('bucket1', [foo1]) foofile = FooFile([foobucket], foofile_data=[1, 2, 3]) with HDF5IO(self.paths[0], manager=_get_manager(), mode='w') as write_io: write_io.write(foofile) manager = _get_manager() with HDF5IO(self.paths[0], manager=manager, mode='r') as read_io: read_foofile = read_io.read() foofile2 = FooFile(foofile_data=read_foofile.foofile_data) # make external link to existing dataset with HDF5IO(self.paths[1], manager=manager, mode='w') as write_io: write_io.write(foofile2) with HDF5IO(self.paths[1], manager=_get_manager(), mode='r') as read_io: self.ios.append(read_io) # track IO objects for tearDown with HDF5IO(self.paths[2], mode='w') as export_io: export_io.export(src_io=read_io) with HDF5IO(self.paths[2], manager=_get_manager(), mode='r') as read_io: self.ios.append(read_io) # track IO objects for tearDown read_foofile2 = read_io.read() # make sure the linked dataset is read from the first file self.assertEqual(read_foofile2.foofile_data.file.filename, self.paths[0]) def test_external_link_link(self): """Test that exporting a written file with external links to external links maintains the links.""" foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) foobucket = FooBucket('bucket1', [foo1]) foofile = FooFile([foobucket]) with HDF5IO(self.paths[0], manager=_get_manager(), mode='w') as write_io: write_io.write(foofile) manager = _get_manager() with HDF5IO(self.paths[0], manager=manager, mode='r') as read_io: read_foofile = read_io.read() # make external link to existing group foofile2 = FooFile(foo_link=read_foofile.buckets['bucket1'].foos['foo1']) with HDF5IO(self.paths[1], manager=manager, mode='w') as write_io: write_io.write(foofile2) manager = _get_manager() with HDF5IO(self.paths[1], manager=manager, mode='r') as read_io: self.ios.append(read_io) # track IO objects for tearDown read_foofile2 = read_io.read() foofile3 = FooFile(foo_link=read_foofile2.foo_link) # make external link to external link with HDF5IO(self.paths[2], manager=manager, mode='w') as write_io: write_io.write(foofile3) with HDF5IO(self.paths[2], manager=_get_manager(), mode='r') as read_io: self.ios.append(read_io) # track IO objects for tearDown with HDF5IO(self.paths[3], mode='w') as export_io: export_io.export(src_io=read_io) with HDF5IO(self.paths[3], manager=_get_manager(), mode='r') as read_io: self.ios.append(read_io) # track IO objects for tearDown read_foofile3 = read_io.read() # make sure the linked group is read from the first file self.assertEqual(read_foofile3.foo_link.container_source, self.paths[0]) def test_attr_reference(self): """Test that exporting a written file with attribute references maintains the references.""" foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) foobucket = FooBucket('bucket1', [foo1]) foofile = FooFile([foobucket], foo_ref_attr=foo1) with HDF5IO(self.paths[0], manager=_get_manager(), mode='w') as read_io: read_io.write(foofile) with HDF5IO(self.paths[0], manager=_get_manager(), mode='r') as read_io: with HDF5IO(self.paths[1], mode='w') as export_io: export_io.export(src_io=read_io) with HDF5IO(self.paths[1], manager=_get_manager(), mode='r') as read_io: read_foofile2 = read_io.read() # make sure the attribute reference resolves to the container within the same file self.assertIs(read_foofile2.foo_ref_attr, read_foofile2.buckets['bucket1'].foos['foo1']) with File(self.paths[1], 'r') as f: self.assertIsInstance(f.attrs['foo_ref_attr'], h5py.Reference) def test_pop_data(self): """Test that exporting a written container after removing an element from it works.""" foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) foobucket = FooBucket('bucket1', [foo1]) foofile = FooFile([foobucket]) with HDF5IO(self.paths[0], manager=_get_manager(), mode='w') as write_io: write_io.write(foofile) with HDF5IO(self.paths[0], manager=_get_manager(), mode='r') as read_io: read_foofile = read_io.read() read_foofile.remove_bucket('bucket1') # remove child group with HDF5IO(self.paths[1], mode='w') as export_io: export_io.export(src_io=read_io, container=read_foofile) with HDF5IO(self.paths[1], manager=_get_manager(), mode='r') as read_io: read_foofile2 = read_io.read() # make sure the read foofile has no buckets self.assertDictEqual(read_foofile2.buckets, {}) # check that file size of file 2 is smaller self.assertTrue(os.path.getsize(self.paths[0]) > os.path.getsize(self.paths[1])) def test_pop_linked_group(self): """Test that exporting a written container after removing a linked element from it works.""" foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) foobucket = FooBucket('bucket1', [foo1]) foofile = FooFile([foobucket], foo_link=foo1) with HDF5IO(self.paths[0], manager=_get_manager(), mode='w') as write_io: write_io.write(foofile) with HDF5IO(self.paths[0], manager=_get_manager(), mode='r') as read_io: read_foofile = read_io.read() read_foofile.buckets['bucket1'].remove_foo('foo1') # remove child group with HDF5IO(self.paths[1], mode='w') as export_io: msg = ("links (links): Linked Foo 'foo1' has no parent. Remove the link or ensure the linked " "container is added properly.") with self.assertRaisesWith(OrphanContainerBuildError, msg): export_io.export(src_io=read_io, container=read_foofile) def test_append_data(self): """Test that exporting a written container after adding groups, links, and references to it works.""" foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) foobucket = FooBucket('bucket1', [foo1]) foofile = FooFile([foobucket]) with HDF5IO(self.paths[0], manager=_get_manager(), mode='w') as write_io: write_io.write(foofile) with HDF5IO(self.paths[0], manager=_get_manager(), mode='r') as read_io: read_foofile = read_io.read() # create a foo with link to existing dataset my_data, add the foo to new foobucket # this should make a soft link within the exported file foo2 = Foo('foo2', read_foofile.buckets['bucket1'].foos['foo1'].my_data, "I am foo2", 17, 3.14) foobucket2 = FooBucket('bucket2', [foo2]) read_foofile.add_bucket(foobucket2) # also add link from foofile to new foo2 container read_foofile.foo_link = foo2 # also add link from foofile to new foo2.my_data dataset which is a link to foo1.my_data dataset read_foofile.foofile_data = foo2.my_data # also add reference from foofile to new foo2 read_foofile.foo_ref_attr = foo2 with HDF5IO(self.paths[1], mode='w') as export_io: export_io.export(src_io=read_io, container=read_foofile) with HDF5IO(self.paths[1], manager=_get_manager(), mode='r') as read_io: self.ios.append(read_io) # track IO objects for tearDown read_foofile2 = read_io.read() # test new soft link to dataset in file self.assertIs(read_foofile2.buckets['bucket1'].foos['foo1'].my_data, read_foofile2.buckets['bucket2'].foos['foo2'].my_data) # test new soft link to group in file self.assertIs(read_foofile2.foo_link, read_foofile2.buckets['bucket2'].foos['foo2']) # test new soft link to new soft link to dataset in file self.assertIs(read_foofile2.buckets['bucket1'].foos['foo1'].my_data, read_foofile2.foofile_data) # test new attribute reference to new group in file self.assertIs(read_foofile2.foo_ref_attr, read_foofile2.buckets['bucket2'].foos['foo2']) with File(self.paths[1], 'r') as f: self.assertEqual(f['foofile_data'].file.filename, self.paths[1]) self.assertIsInstance(f.attrs['foo_ref_attr'], h5py.Reference) def test_append_external_link_data(self): """Test that exporting a written container after adding a link with link_data=True creates external links.""" foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) foobucket = FooBucket('bucket1', [foo1]) foofile = FooFile([foobucket]) with HDF5IO(self.paths[0], manager=_get_manager(), mode='w') as write_io: write_io.write(foofile) foofile2 = FooFile([]) with HDF5IO(self.paths[1], manager=_get_manager(), mode='w') as write_io: write_io.write(foofile2) manager = _get_manager() with HDF5IO(self.paths[0], manager=manager, mode='r') as read_io1: self.ios.append(read_io1) # track IO objects for tearDown read_foofile1 = read_io1.read() with HDF5IO(self.paths[1], manager=manager, mode='r') as read_io2: self.ios.append(read_io2) read_foofile2 = read_io2.read() # create a foo with link to existing dataset my_data (not in same file), add the foo to new foobucket # this should make an external link within the exported file foo2 = Foo('foo2', read_foofile1.buckets['bucket1'].foos['foo1'].my_data, "I am foo2", 17, 3.14) foobucket2 = FooBucket('bucket2', [foo2]) read_foofile2.add_bucket(foobucket2) # also add link from foofile to new foo2.my_data dataset which is a link to foo1.my_data dataset # this should make an external link within the exported file read_foofile2.foofile_data = foo2.my_data with HDF5IO(self.paths[2], mode='w') as export_io: export_io.export(src_io=read_io2, container=read_foofile2) with HDF5IO(self.paths[0], manager=_get_manager(), mode='r') as read_io1: self.ios.append(read_io1) # track IO objects for tearDown read_foofile3 = read_io1.read() with HDF5IO(self.paths[2], manager=_get_manager(), mode='r') as read_io2: self.ios.append(read_io2) # track IO objects for tearDown read_foofile4 = read_io2.read() self.assertEqual(read_foofile4.buckets['bucket2'].foos['foo2'].my_data, read_foofile3.buckets['bucket1'].foos['foo1'].my_data) self.assertEqual(read_foofile4.foofile_data, read_foofile3.buckets['bucket1'].foos['foo1'].my_data) with File(self.paths[2], 'r') as f: self.assertEqual(f['buckets/bucket2/foo_holder/foo2/my_data'].file.filename, self.paths[0]) self.assertEqual(f['foofile_data'].file.filename, self.paths[0]) self.assertIsInstance(f.get('buckets/bucket2/foo_holder/foo2/my_data', getlink=True), h5py.ExternalLink) self.assertIsInstance(f.get('foofile_data', getlink=True), h5py.ExternalLink) def test_append_external_link_copy_data(self): """Test that exporting a written container after adding a link with link_data=False copies the data.""" foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) foobucket = FooBucket('bucket1', [foo1]) foofile = FooFile([foobucket]) with HDF5IO(self.paths[0], manager=_get_manager(), mode='w') as write_io: write_io.write(foofile) foofile2 = FooFile([]) with HDF5IO(self.paths[1], manager=_get_manager(), mode='w') as write_io: write_io.write(foofile2) manager = _get_manager() with HDF5IO(self.paths[0], manager=manager, mode='r') as read_io1: self.ios.append(read_io1) # track IO objects for tearDown read_foofile1 = read_io1.read() with HDF5IO(self.paths[1], manager=manager, mode='r') as read_io2: self.ios.append(read_io2) read_foofile2 = read_io2.read() # create a foo with link to existing dataset my_data (not in same file), add the foo to new foobucket # this would normally make an external link but because link_data=False, data will be copied foo2 = Foo('foo2', read_foofile1.buckets['bucket1'].foos['foo1'].my_data, "I am foo2", 17, 3.14) foobucket2 = FooBucket('bucket2', [foo2]) read_foofile2.add_bucket(foobucket2) # also add link from foofile to new foo2.my_data dataset which is a link to foo1.my_data dataset # this would normally make an external link but because link_data=False, data will be copied read_foofile2.foofile_data = foo2.my_data with HDF5IO(self.paths[2], mode='w') as export_io: export_io.export(src_io=read_io2, container=read_foofile2, write_args={'link_data': False}) with HDF5IO(self.paths[0], manager=_get_manager(), mode='r') as read_io1: self.ios.append(read_io1) # track IO objects for tearDown read_foofile3 = read_io1.read() with HDF5IO(self.paths[2], manager=_get_manager(), mode='r') as read_io2: self.ios.append(read_io2) # track IO objects for tearDown read_foofile4 = read_io2.read() # check that file can be read self.assertNotEqual(read_foofile4.buckets['bucket2'].foos['foo2'].my_data, read_foofile3.buckets['bucket1'].foos['foo1'].my_data) self.assertNotEqual(read_foofile4.foofile_data, read_foofile3.buckets['bucket1'].foos['foo1'].my_data) self.assertNotEqual(read_foofile4.foofile_data, read_foofile4.buckets['bucket2'].foos['foo2'].my_data) with File(self.paths[2], 'r') as f: self.assertEqual(f['buckets/bucket2/foo_holder/foo2/my_data'].file.filename, self.paths[2]) self.assertEqual(f['foofile_data'].file.filename, self.paths[2]) def test_export_io(self): """Test that exporting a written container using HDF5IO.export_io works.""" foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) foobucket = FooBucket('bucket1', [foo1]) foofile = FooFile([foobucket]) with HDF5IO(self.paths[0], manager=_get_manager(), mode='w') as write_io: write_io.write(foofile) with HDF5IO(self.paths[0], manager=_get_manager(), mode='r') as read_io: HDF5IO.export_io(src_io=read_io, path=self.paths[1]) self.assertTrue(os.path.exists(self.paths[1])) self.assertEqual(foofile.container_source, self.paths[0]) with HDF5IO(self.paths[1], manager=_get_manager(), mode='r') as read_io: read_foofile = read_io.read() self.assertEqual(read_foofile.container_source, self.paths[1]) self.assertContainerEqual(foofile, read_foofile, ignore_hdmf_attrs=True) def test_export_dset_refs(self): """Test that exporting a written container with a dataset of references works.""" bazs = [] num_bazs = 10 for i in range(num_bazs): bazs.append(Baz(name='baz%d' % i)) baz_data = BazData(name='baz_data1', data=bazs) bucket = BazBucket(name='bucket1', bazs=bazs.copy(), baz_data=baz_data) with HDF5IO(self.paths[0], manager=_get_baz_manager(), mode='w') as write_io: write_io.write(bucket) with HDF5IO(self.paths[0], manager=_get_baz_manager(), mode='r') as read_io: read_bucket1 = read_io.read() # NOTE: reference IDs might be the same between two identical files # adding a Baz with a smaller name should change the reference IDs on export new_baz = Baz(name='baz000') read_bucket1.add_baz(new_baz) with HDF5IO(self.paths[1], mode='w') as export_io: export_io.export(src_io=read_io, container=read_bucket1) with HDF5IO(self.paths[1], manager=_get_baz_manager(), mode='r') as read_io: read_bucket2 = read_io.read() # remove and check the appended child, then compare the read container with the original read_new_baz = read_bucket2.remove_baz('baz000') self.assertContainerEqual(new_baz, read_new_baz, ignore_hdmf_attrs=True) self.assertContainerEqual(bucket, read_bucket2, ignore_name=True, ignore_hdmf_attrs=True) for i in range(num_bazs): baz_name = 'baz%d' % i self.assertIs(read_bucket2.baz_data.data[i], read_bucket2.bazs[baz_name]) def test_export_cpd_dset_refs(self): """Test that exporting a written container with a compound dataset with references works.""" bazs = [] baz_pairs = [] num_bazs = 10 for i in range(num_bazs): b = Baz(name='baz%d' % i) bazs.append(b) baz_pairs.append((i, b)) baz_cpd_data = BazCpdData(name='baz_cpd_data1', data=baz_pairs) bucket = BazBucket(name='bucket1', bazs=bazs.copy(), baz_cpd_data=baz_cpd_data) with HDF5IO(self.paths[0], manager=_get_baz_manager(), mode='w') as write_io: write_io.write(bucket) with HDF5IO(self.paths[0], manager=_get_baz_manager(), mode='r') as read_io: read_bucket1 = read_io.read() # NOTE: reference IDs might be the same between two identical files # adding a Baz with a smaller name should change the reference IDs on export new_baz = Baz(name='baz000') read_bucket1.add_baz(new_baz) with HDF5IO(self.paths[1], mode='w') as export_io: export_io.export(src_io=read_io, container=read_bucket1) with HDF5IO(self.paths[1], manager=_get_baz_manager(), mode='r') as read_io: read_bucket2 = read_io.read() # remove and check the appended child, then compare the read container with the original read_new_baz = read_bucket2.remove_baz(new_baz.name) self.assertContainerEqual(new_baz, read_new_baz, ignore_hdmf_attrs=True) self.assertContainerEqual(bucket, read_bucket2, ignore_name=True, ignore_hdmf_attrs=True) for i in range(num_bazs): baz_name = 'baz%d' % i self.assertEqual(read_bucket2.baz_cpd_data.data[i][0], i) self.assertIs(read_bucket2.baz_cpd_data.data[i][1], read_bucket2.bazs[baz_name]) def test_non_manager_container(self): """Test that exporting with a src_io without a manager raises an error.""" foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) foobucket = FooBucket('bucket1', [foo1]) foofile = FooFile([foobucket]) with HDF5IO(self.paths[0], manager=_get_manager(), mode='w') as write_io: write_io.write(foofile) class OtherIO(HDMFIO): def read_builder(self): pass def write_builder(self, **kwargs): pass def open(self): pass def close(self): pass with OtherIO() as read_io: with HDF5IO(self.paths[1], mode='w') as export_io: msg = 'When a container is provided, src_io must have a non-None manager (BuildManager) property.' with self.assertRaisesWith(ValueError, msg): export_io.export(src_io=read_io, container=foofile, write_args={'link_data': False}) def test_non_HDF5_src_link_data_true(self): """Test that exporting with a src_io without a manager raises an error.""" foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) foobucket = FooBucket('bucket1', [foo1]) foofile = FooFile([foobucket]) with HDF5IO(self.paths[0], manager=_get_manager(), mode='w') as write_io: write_io.write(foofile) class OtherIO(HDMFIO): def __init__(self, manager): super().__init__(manager=manager) def read_builder(self): pass def write_builder(self, **kwargs): pass def open(self): pass def close(self): pass with OtherIO(manager=_get_manager()) as read_io: with HDF5IO(self.paths[1], mode='w') as export_io: msg = "Cannot export from non-HDF5 backend OtherIO to HDF5 with write argument link_data=True." with self.assertRaisesWith(UnsupportedOperation, msg): export_io.export(src_io=read_io, container=foofile) def test_wrong_mode(self): """Test that exporting with a src_io without a manager raises an error.""" foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) foobucket = FooBucket('bucket1', [foo1]) foofile = FooFile([foobucket]) with HDF5IO(self.paths[0], manager=_get_manager(), mode='w') as write_io: write_io.write(foofile) with HDF5IO(self.paths[0], mode='r') as read_io: with HDF5IO(self.paths[1], mode='a') as export_io: msg = "Cannot export to file %s in mode 'a'. Please use mode 'w'." % self.paths[1] with self.assertRaisesWith(UnsupportedOperation, msg): export_io.export(src_io=read_io) class TestDatasetRefs(TestCase): def test_roundtrip(self): self.path = get_temp_filepath() bazs = [] num_bazs = 10 for i in range(num_bazs): bazs.append(Baz(name='baz%d' % i)) baz_data = BazData(name='baz_data1', data=bazs) bucket = BazBucket(name='bucket1', bazs=bazs.copy(), baz_data=baz_data) with HDF5IO(self.path, manager=_get_baz_manager(), mode='w') as write_io: write_io.write(bucket) with HDF5IO(self.path, manager=_get_baz_manager(), mode='r') as read_io: read_bucket = read_io.read() self.assertContainerEqual(bucket, read_bucket, ignore_name=True) for i in range(num_bazs): baz_name = 'baz%d' % i self.assertIs(read_bucket.baz_data.data[i], read_bucket.bazs[baz_name]) class TestCpdDatasetRefs(TestCase): def test_roundtrip(self): self.path = get_temp_filepath() bazs = [] baz_pairs = [] num_bazs = 10 for i in range(num_bazs): b = Baz(name='baz%d' % i) bazs.append(b) baz_pairs.append((i, b)) baz_cpd_data = BazCpdData(name='baz_cpd_data1', data=baz_pairs) bucket = BazBucket(name='bucket1', bazs=bazs.copy(), baz_cpd_data=baz_cpd_data) with HDF5IO(self.path, manager=_get_baz_manager(), mode='w') as write_io: write_io.write(bucket) with HDF5IO(self.path, manager=_get_baz_manager(), mode='r') as read_io: read_bucket = read_io.read() self.assertContainerEqual(bucket, read_bucket, ignore_name=True) for i in range(num_bazs): baz_name = 'baz%d' % i self.assertEqual(read_bucket.baz_cpd_data.data[i][0], i) self.assertIs(read_bucket.baz_cpd_data.data[i][1], read_bucket.bazs[baz_name]) class Baz(Container): pass class BazData(Data): pass class BazCpdData(Data): pass class BazBucket(Container): @docval({'name': 'name', 'type': str, 'doc': 'the name of this bucket'}, {'name': 'bazs', 'type': list, 'doc': 'the Baz objects in this bucket'}, {'name': 'baz_data', 'type': BazData, 'doc': 'dataset of Baz references', 'default': None}, {'name': 'baz_cpd_data', 'type': BazCpdData, 'doc': 'dataset of Baz references', 'default': None}) def __init__(self, **kwargs): name, bazs, baz_data, baz_cpd_data = getargs('name', 'bazs', 'baz_data', 'baz_cpd_data', kwargs) super().__init__(name=name) self.__bazs = {b.name: b for b in bazs} # note: collections of groups are unordered in HDF5 for b in bazs: b.parent = self self.__baz_data = baz_data if self.__baz_data is not None: self.__baz_data.parent = self self.__baz_cpd_data = baz_cpd_data if self.__baz_cpd_data is not None: self.__baz_cpd_data.parent = self @property def bazs(self): return self.__bazs @property def baz_data(self): return self.__baz_data @property def baz_cpd_data(self): return self.__baz_cpd_data def add_baz(self, baz): self.__bazs[baz.name] = baz baz.parent = self def remove_baz(self, baz_name): baz = self.__bazs.pop(baz_name) self._remove_child(baz) return baz def _get_baz_manager(): baz_spec = GroupSpec( doc='A test group specification with a data type', data_type_def='Baz', ) baz_data_spec = DatasetSpec( doc='A test dataset of references specification with a data type', name='baz_data', data_type_def='BazData', dtype=RefSpec('Baz', 'object'), shape=[None], ) baz_cpd_data_spec = DatasetSpec( doc='A test compound dataset with references specification with a data type', name='baz_cpd_data', data_type_def='BazCpdData', dtype=[DtypeSpec(name='part1', doc='doc', dtype='int'), DtypeSpec(name='part2', doc='doc', dtype=RefSpec('Baz', 'object'))], shape=[None], ) baz_holder_spec = GroupSpec( doc='group of bazs', name='bazs', groups=[GroupSpec(doc='Baz', data_type_inc='Baz', quantity=ONE_OR_MANY)], ) baz_bucket_spec = GroupSpec( doc='A test group specification for a data type containing data type', data_type_def='BazBucket', groups=[baz_holder_spec], datasets=[DatasetSpec(doc='doc', data_type_inc='BazData', quantity=ZERO_OR_ONE), DatasetSpec(doc='doc', data_type_inc='BazCpdData', quantity=ZERO_OR_ONE)], ) spec_catalog = SpecCatalog() spec_catalog.register_spec(baz_spec, 'test.yaml') spec_catalog.register_spec(baz_data_spec, 'test.yaml') spec_catalog.register_spec(baz_cpd_data_spec, 'test.yaml') spec_catalog.register_spec(baz_bucket_spec, 'test.yaml') namespace = SpecNamespace( 'a test namespace', CORE_NAMESPACE, [{'source': 'test.yaml'}], version='0.1.0', catalog=spec_catalog) namespace_catalog = NamespaceCatalog() namespace_catalog.add_namespace(CORE_NAMESPACE, namespace) type_map = TypeMap(namespace_catalog) type_map.register_container_type(CORE_NAMESPACE, 'Baz', Baz) type_map.register_container_type(CORE_NAMESPACE, 'BazData', BazData) type_map.register_container_type(CORE_NAMESPACE, 'BazCpdData', BazCpdData) type_map.register_container_type(CORE_NAMESPACE, 'BazBucket', BazBucket) class BazBucketMapper(ObjectMapper): def __init__(self, spec): super().__init__(spec) baz_holder_spec = spec.get_group('bazs') self.unmap(baz_holder_spec) baz_spec = baz_holder_spec.get_data_type('Baz') self.map_spec('bazs', baz_spec) type_map.register_map(BazBucket, BazBucketMapper) manager = BuildManager(type_map) return manager
;;; ;;; Methoden (Theorie: lock-res) ;;; (in-package "OMEGA") (infer~defmethod derive-meth (outline-mappings (((existent existent existent existent existent nonexistent nonexistent nonexistent nonexistent nonexistent ) derive-meth-m-b))) (help "A method for prooving derivability goals with derivability assumtpions.")) ;; Diese Methode kommt im Verlauf des Beweises des Disjunktionslemmas zum Zuge. Sie ;; konstruiert eine Ableitung in der Form, dass sie eine Ableitung einer Klausel cl1 und ;; eine Ableitung einer Klausel cl2 aneinanderhaengt, und um die Resolvente dieser beiden ;; Klauseln erweitert. Dabei hat man als Voraussetzung, dass die Ableitungseigenschaft der ;; beiden Teilableitungen als Voaussetzung zur Verfuegun steht. ;; Anschliessend fuehrt die Mehtode eine Fallunterscheidung durch: ;; Beim Beweis, dass die konstruierte Liste eine Ableitung ist, wird bei der zufaelligen ;; Wahl eine beliebigen Listenelementes unterschieden, ob das Element ein Element der ;; ersten Liste (Ableitung), der zweiten Liste (Ableitung) oder das Schlusselement ist. ;; Die einzelnen Faelle koennen dann unmittelbar auf die Voraussetzungen zurueck gefuehrt werden. (meth~defmethod derive-meth-m-b derive-meth (in lock-res) (rating 30) (reasoning :planning) (declarations (constants ) (sorted-meta-variables (cl1 (o form) term) (cl2 (o form) term) ;; Die beiden Klauseln die aus K abgeleitet werden ;; koennen. entweder Uespruengliche Klauseln oder ;; die Klauseln plus LI (cl3 (o form) term) (cl4 (o form) term) ;;(helper (o form) term) (aset(o (o form)) term) (li1 form term ) (li2 form term) (concat glist term) (aseq1 glist term) (aseq2 glist term) (goal (o form) term) (ait item term) (apos8 o pos) ) ) (parameters ) (premises (- l99) (- l89) (- l80) (- l78) (+ l11) (+ l24) (+ l37) (+ l50) (+ l26) ) (application-condition ) (outline-actions (l26 (sponsor l80)) (l26 (sponsor l78)) (l11 (sponsor l97)) (l11 (sponsor l87)) (l37 (sponsor l49)) (l37 (sponsor l70)) (l37 (sponsor l85)) (l37 (sponsor l69a)) (l50 (sponsor l65)) (l50 (sponsor l70)) (l50 (sponsor l85)) (l50 (sponsor l69a)) ) (outline-orderings (before l26 l50) (before l50 l37) (before l37 l24) (before l24 l11) ) (outline-computations (apos8 (:position (1 1 1 0 1 0 1))) (aseq1 (type-newconst (:type glist))) (aseq2 (type-newconst (:type glist))) (ait (type-newconst (:type item))) ; (cl1 (type-newconst (:type (o form)))) ; (cl2 (type-newconst (:type (o form)))) ; (li1 (type-newconst (:type form))) ; (li2 (type-newconst (:type form))) (concat (:term (append aseq1 (append (push-idx aseq2 (glist-length aseq1)) (cons (der-item-constr res-res goal (cons (form2item li1) (cons (form2item li2) NULL)) (cons (num2item (glist-length aseq1)) (cons (num2item (plus (glist-length aseq1) (glist-length aseq2))) NULL))) NULL))))) ) (conclusions (- ltp)) (decl-content ;; Wichtige Annahme: Die Klausel cl1 ist in weniger als cx12 Schritten ;; aus K ableitbar. Wichtig ist ;; die Tatsache, dass man die Existenz einer Ableitung von cl1 ;; voraussetzen kann. Zeilen l99 bis l95. Der Name fuer diese Ableitung ;; ist aseq1 (l99 () (derivable cl1 aset crule-set) ) (l98 () (exists (lam (seq glist) (derivation-of aset crule-set seq cl1))) ("DefnE" (derivable) (l99))) (l97 () (derivation-of aset crule-set aseq1 cl1) ("Hyp"()()) ) ; (l96 () (and (= (der-item-info (last aseq1)) cl1) ; (derivation aset crule-set aseq1)) ("DefnE" (derivation-of) (l97))) ; ; (l95 () (derivation aset crule-set aseq1) ("AndER" () (l96))) ;; -------------------- ;; Ebenso wie Zeile l99. Die IH aus dem Induktionsbeweis des ;; Disjunktionslemmas besagt, dass cl2 ableitbar ist. Der Name fuer diese ;; Ableitung ist aseq2 (l89 () (derivable cl2 aset crule-set) ) (l88 () (exists (lam (seq glist) (derivation-of aset crule-set seq cl2))) ("defnE" (derivable)(l89))) (l87 () (derivation-of aset crule-set aseq2 cl2) ("Hyp"()()) ); (l86 () (and (= (der-item-info (last aseq2)) cl2) (derivation aset crule-set aseq2)) ("DefnE" (derivation-of) (l87))) (l85 () (derivation aset crule-set aseq2) ("AndER" ()(l86))) ;; --------------------------------------- ;; Wichtige Voraussetzung ist, dass cl3 und cl4 auch resolvierbar sind. (l80 () (resolvable-b cl3 cl4 li1 li2 ) ) (l79 () (= goal (resolvent-of cl3 cl4 li1 li2 ) ) ("abstract"()())) ;; Zeile l79 direkt aus l80 nach definition ; (l78 () (resolvable-s cl1 cl2) ) (l70 () (is-component ait concat) ("Hyp"()())) ; (l69 () (forall (lam (x item) ; (implies (and (is-component x concat) ; (and (leq one (position x concat)) ; (leq (position x concat) ; (glist-length aseq1)))) ; (= x (glist-nth (position x concat) ; aseq1))))) ("abstract"()())) (l69a () (forall (lam (x item) (implies (and (is-component x concat) (and (leq (plus (glist-length aseq1) one) (position x concat)) (leq (position x concat) (plus (glist-length aseq1) (glist-length aseq2))))) (= (idx-minus (glist-length aseq1) x) (glist-nth (minus (position x concat) (glist-length aseq1)) aseq2))))) ("abstract"()())) ; (l68 () (forall (lam (x item) ; (implies (= (position x concat) ; (plus one ; (plus (glist-length aseq1) ; (glist-length aseq2)))) ; (= x ; (der-item-constr res-res ; goal ; (cons (form2item li1) ; (cons (form2item li2) ; NULL)) ; (cons (num2item (glist-length aseq1)) ; (cons (num2item ; (plus (glist-length aseq1) ; (glist-length ; aseq2))) ; NULL))))))) ("abstract"()())) ; ; ;; ------------------------------------- ; ; (l67 () (or (= (position ait concat) ; (plus one ; (plus (glist-length aseq1) ; (glist-length aseq2)))) ; (or (and (leq one (position ait concat)) ; (leq (position ait concat) ; (glist-length aseq1))) ; (and (leq (plus (glist-length aseq1) ; one) ; (position ait concat)) ; (leq (position ait concat) ; (plus (glist-length aseq1) ; (glist-length aseq2)))))) ; ("Abstract"()())) (l66 () (or (and (leq one (position ait concat)) (leq (position ait concat) (glist-length aseq1))) (and (leq (plus (glist-length aseq1) one) (position ait concat)) (leq (position ait concat) (plus (glist-length aseq1) (glist-length aseq2))))) ("Hyp"()())) (l65 () (and (leq one (position ait concat)) (leq (position ait concat) (glist-length aseq1))) ("Hyp"()())) ;; Diesen Teilbeweis in eine andere Methode packen ; (l64 () (implies (and (is-component ait concat) ; (and (leq one (position ait concat)) ; (leq (position ait concat) ; (glist-length aseq1)))) ; (= ait (glist-nth (position ait concat) ; aseq1))) ("ForallE" (ait) (l69))) ; ; (l63 (l65 l70) (and (is-component ait concat) ; (and (leq one (position ait concat)) ; (leq (position ait concat) ; (glist-length aseq1)))) ("AndI" () (l65 l70))) ; ; (l62 (l65 l70) (= ait (glist-nth (position ait concat) ; aseq1)) ("ImpE"() (l64 l63))) ; ; (l61 (l69 l65) (= (poslist2infolist (der-item-prems ait) concat) ; (poslist2infolist (der-item-prems (glist-nth (position ait concat) aseq1)) aseq1)) ; ("abstract"()())) ; ; (l60 (l69 l65) (= (position (glist-nth (position ait concat) aseq1) concat) ; (position (glist-nth (position ait concat) aseq1) aseq1)) ("Abstract"()())) (l50 (l97 l87 l70 l66 l65) (and (and (crule-set (der-item-crule ait)) (crule-applicable (der-item-crule ait) (append (append (der-item-inp ait) (poslist2infolist (der-item-prems ait) concat)) (cons (cl2item (der-item-info ait)) NULL)) aset)) (and (forall (lam (y num) (implies (is-component (num2item y) (der-item-prems ait)) (less y (position ait concat))))) (= (der-item-info ait) (crule-application (der-item-crule ait) (append (append (der-item-inp ait) (poslist2infolist (der-item-prems ait) concat)) (cons (cl2item (der-item-info ait)) NULL)) aset)))) ("Open"()())) ;; ---------------------------------------------------------- (l49 () (and (leq (plus (glist-length aseq1) one) (position ait concat)) (leq (position ait concat) (plus (glist-length aseq1) (glist-length aseq2)))) ("Hyp"()())) (l37 (l97 l87 l85 l70 l66 l49) (and (and (crule-set (der-item-crule ait)) (crule-applicable (der-item-crule ait) (append (append (der-item-inp ait) (poslist2infolist (der-item-prems ait) concat)) (cons (cl2item (der-item-info ait)) NULL)) aset)) (and (forall (lam (y num) (implies (is-component (num2item y) (der-item-prems ait)) (less y (position ait concat))))) (= (der-item-info ait) (crule-application (der-item-crule ait) (append (append (der-item-inp ait) (poslist2infolist (der-item-prems ait) concat)) (cons (cl2item (der-item-info ait)) NULL)) aset)))) ("Open"()())) ; (l36 (l97 l87 l70 l66)(and (and (crule-set (der-item-crule ait)) ; (crule-applicable (der-item-crule ait) ; (append (append ; (der-item-inp ait) ; (poslist2infolist (der-item-prems ait) concat)) ; (cons (cl2item (der-item-info ait)) ; NULL)) ; aset)) ; (and (forall (lam (y num) ; (implies (is-component (num2item y) (der-item-prems ait)) ; (less y ; (position ait concat))))) ; (= (der-item-info ait) ; (crule-application (der-item-crule ait) ; (append (append ; (der-item-inp ait) ; (poslist2infolist (der-item-prems ait) concat)) ; (cons (cl2item ; (der-item-info ait)) ; NULL)) ; aset)))) ("OrE"()(l66 l37 l50))) (l35 () (= (position ait concat) (plus one (plus (glist-length aseq1) (glist-length aseq2)))) ("Hyp"()())) (l26 (l97 l87 l70 l35) (and (and (crule-set (der-item-crule ait)) (crule-applicable (der-item-crule ait) (append (append (der-item-inp ait) (poslist2infolist (der-item-prems ait) concat)) (cons (cl2item (der-item-info ait)) NULL)) aset)) (and (forall (lam (y num) (implies (is-component (num2item y) (der-item-prems ait)) (less y (position ait concat))))) (= (der-item-info ait) (crule-application (der-item-crule ait) (append (append (der-item-inp ait) (poslist2infolist (der-item-prems ait) concat)) (cons (cl2item (der-item-info ait)) NULL)) aset)))) ("Open"()())) ; (l25 (l97 l87 l70) (and (and (crule-set (der-item-crule ait)) ; (crule-applicable (der-item-crule ait) ; (append (append ; (der-item-inp ait) ; (poslist2infolist (der-item-prems ait) concat)) ; (cons (cl2item (der-item-info ait)) ; NULL)) ; aset)) ; (and (forall (lam (y num) ; (implies (is-component (num2item y) (der-item-prems ait)) ; (less y ; (position ait concat))))) ; (= (der-item-info ait) ; (crule-application (der-item-crule ait) ; (append (append ; (der-item-inp ait) ; (poslist2infolist (der-item-prems ait) concat)) ; (cons (cl2item ; (der-item-info ait)) ; NULL)) ; aset)))) ("OrE"()(l67 l26 l36))) ;; ------------------------------------------------------- (l24 (l97 l87 l70) (free-derivation-cond concat) ("Open"()())) ; ; ;; ------------------------------------------------------ ; ; (l23 (l97 l87 l70) (and (free-derivation-cond concat) ; (and (and (crule-set (der-item-crule ait)) ; (crule-applicable (der-item-crule ait) ; (append (append ; (der-item-inp ait) ; (poslist2infolist (der-item-prems ait) concat)) ; (cons (cl2item (der-item-info ait)) ; NULL)) ; aset)) ; (and (forall (lam (y num) ; (implies (is-component (num2item y) (der-item-prems ait)) ; (less y ; (position ait concat))))) ; (= (der-item-info ait) ; (crule-application (der-item-crule ait) ; (append (append ; (der-item-inp ait) ; (poslist2infolist (der-item-prems ait) concat)) ; (cons (cl2item ; (der-item-info ait)) ; NULL)) ; aset))))) ("Open"()())) ; ;;("AndI"()(l24 l25))) ; ; (l22 (l97 l87) (implies (is-component ait concat) ; (and (free-derivation-cond concat) ; (and (and (crule-set (der-item-crule ait)) ; (crule-applicable (der-item-crule ait) ; (append (append ; (der-item-inp ait) ; (poslist2infolist (der-item-prems ait) concat)) ; (cons (cl2item (der-item-info ait)) ; NULL)) ; aset)) ; (and (forall (lam (y num) ; (implies (is-component (num2item y) (der-item-prems ait)) ; (less y ; (position ait concat))))) ; (= (der-item-info ait) ; (crule-application (der-item-crule ait) ; (append (append ; (der-item-inp ait) ; (poslist2infolist (der-item-prems ait) concat)) ; (cons (cl2item ; (der-item-info ait)) ; NULL)) ; aset)))))) ("ImpI"()(l23 l70))) ; ; (l21 (l97 l87) (forall (lam (x item) ; (implies (is-component x concat) ; (and (free-derivation-cond concat) ; (and (and (crule-set (der-item-crule x)) ; (crule-applicable (der-item-crule x) ; (append (append ; (der-item-inp x) ; (poslist2infolist (der-item-prems x) concat)) ; (cons (cl2item (der-item-info x)) ; NULL)) ; aset)) ; (and (forall (lam (y num) ; (implies (is-component (num2item y) (der-item-prems x)) ; (less y ; (position x concat))))) ; (= (der-item-info x) ; (crule-application (der-item-crule x) ; (append (append ; (der-item-inp x) ; (poslist2infolist (der-item-prems x) concat)) ; (cons (cl2item ; (der-item-info x)) ; NULL)) ; aset)))))))) ; ("ForallI" (ait) (l22))) ; ;; Nachweis der Ableitungseigenschaft von concat ;; Unterscheide 3 Faelle ;; l26 : expliziet fuer das letzte Element von concat ;; l37 : ait liegt in der ersten Ableitung ;; l50 : ait liegt in der zweiten Ableitung ;; Zunaechst bis l23 standard Aufloesung ; (l20 (l97 l87) (derivation aset crule-set concat) ("DefnI"(derivation) (l21))) ;; ------------------------------------------------------------- (l15 () (= (last concat) (der-item-constr res-res goal (cons (form2item li1) (cons (form2item li2) NULL)) (cons (num2item (glist-length aseq1)) (cons (num2item (plus (glist-length aseq1) (glist-length aseq2))) NULL)))) ("abstract"()())) (l11 (l97 l87) (= (der-item-info (der-item-constr res-res goal (cons (form2item li1) (cons (form2item li2) NULL)) (cons (num2item (glist-length aseq1)) (cons (num2item (plus (glist-length aseq1) (glist-length aseq2))) NULL)))) goal) ("Open" () ())) ;; Kann gemaess der Konstruktion von concat bewiesen werden: Beweis gekuerzt l11 l15 (l10 (l97 l87) (= (der-item-info (last concat)) goal) ("Subst="()(l15 l11))) ;; --------------------------------------------------------------------- (l5 (l97 l87) (and (= (der-item-info (last concat)) goal) (derivation aset crule-set concat)) ("AndI" () (l10 l20))) (l4 (l97 l87) (derivation-of aset crule-set concat goal) ("DefnI" () (l5))) (l3 (l97 l87) (exists (lam (seq glist) (derivation-of aset crule-set seq goal))) ("ExistsI" (concat) (l4))) (l2 (l97 l87) (derivable goal aset crule-set) ("DefnI" () (l3 ))) (l1 (l97) (derivable goal aset crule-set) ("abstract"()())) ;;("ExistsE"(aseq2)(l2 l88))) ;; ------------------------------------------------------------------- ;; ZIEL: goal ist aus aset ableitbar. goal ist belibige Klausel, ;; entstanden beim Beweis des Disjunktionslemma. Ist eine Klauselmenge K ;; goal ist in cx12 Schritten ableibar. (ltp () (derivable goal aset crule-set) ("Open"()())) ;; ("ExistsE"(aseq1)(l1 l98))) ) (proc-content schema-interpreter) (remark "A method for prooving derivability goals with derivability assumtpions.") ) (infer~defmethod derive-meth2 (outline-mappings (((existent ;; existent ;; existent ;; existent ;;existent ) derive-meth2-m-b))) (help "A method for prooving derivability goals with derivability assumtpions.")) (meth~defmethod derive-meth2-m-b derive-meth2 (in lock-res) (rating 30) (reasoning :planning) (declarations (constants ) (sorted-meta-variables (apos10 o pos)(apos11 o pos)(apos12 o pos)(apos13 o pos)(apos14 o pos)(apos15 o pos)(apos16 o pos) (apos17 o pos)(apos18 o pos)(apos19 o pos)(apos20 o pos)(apos21 o pos)(apos31 o pos)(apos32 o pos) (apos33 o pos)(apos40 o pos)(apos41 o pos) (ait item term) (aco num term) (concat glist term) (aseq1 glist term) (aseq2 glist term) (aset (o (o form)) term) (lobo num term) (upbo num term) (a-num-const num term) ) ) (parameters ) (premises ;; (- lh0) ;; (- lh1) ;; (- lh3) ;;(- lh4) ) (application-condition ) (outline-actions ) (outline-orderings ) (outline-computations (aterm (:term (glist-nth (minus (position ait concat) (glist-length aseq1)) aseq2))) ; (apos10 (:position (1 2 3))) ; (apos11 (:position (1 2 3))) ; (apos12 (:position (1 2 3))) ; (apos13 (:position (1 2 3))) ; (apos14 (:position (1 2 3))) ; (apos15 (:position (1 2 3))) ; (apos16 (:position (1 2 3))) ; (apos17 (:position (1 2 3))) ; (apos18 (:position (1 2 3))) ; (apos19 (:position (1 2 3))) ; (apos20 (:position (1 2 3))) ; (apos21 (:position (1 2 3))) ; (apos31 (:position (1 2 3))) ; (apos32 (:position (1 2 3))) ; (apos33 (:position (1 2 3))) ; (apos40 (:position (1 2 3))) ; (apos41 (:position (1 2 3))) ) (conclusions (- ltp)) (decl-content (lh0 () (greater aco (s zero)) ) (lh3 () (is-component ait concat) ) ;; muss vorhanden sein (lh4 () (and (leq lobo (position ait concat)) (leq (position ait concat) upbo)) ) ;; muss vorhanden sein (lh1 () (derivation aset crule-set aseq2) ) (lh2 () (forall (lam (x item) (implies (and (is-component x concat) (and (leq lobo (position x concat)) (leq (position x concat) upbo))) (= (idx-minus a-num-const x) (glist-nth (minus (position x concat) (glist-length aseq1)) aseq2))))) ) ;; -------------------------------------------------------------------- (l1 () (implies (and (is-component ait concat) (and (leq lobo (position ait concat)) (leq (position ait concat) upbo))) (= (idx-minus a-num-const ait) (glist-nth (minus (position ait concat) (glist-length aseq1)) aseq2))) ("ForallE" (ait)(lh2))) (l2 () (and (is-component ait concat) (and (leq lobo (position ait concat)) (leq (position ait concat) upbo))) ("AndI" () (lh3 lh4))) ; (l3 () (= (idx-minus a-num-const ait) ; (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) ("ImpE" ()(l1 l2))) ; ; ; ;; Hinfuehrung zum Ziel ; ; ;; --------------------------------------------------------------------------- ; ; (l4 () (forall (lam (x item) ; (implies (is-component x aseq2) ; (and (free-derivation-cond aseq2) ; (and (and (crule-set (der-item-crule x)) ; (crule-applicable (der-item-crule x) ; (append (append ; (der-item-inp x) ; (poslist2infolist (der-item-prems x) aseq2)) ; (cons (cl2item (der-item-info x)) ; NULL)) ; aset)) ; (and (forall (lam (y num) ; (implies (is-component (num2item y) (der-item-prems x)) ; (less y ; (position x aseq2))))) ; (= (der-item-info x) ; (crule-application (der-item-crule x) ; (append (append ; (der-item-inp x) ; (poslist2infolist (der-item-prems x) aseq2)) ; (cons (cl2item ; (der-item-info x)) ; NULL)) ; aset)))))))) ("DefnE" (derivation)(lh1))) ; ; (l5 () (implies (is-component (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2) aseq2) ; (and (free-derivation-cond aseq2) ; (and (and (crule-set (der-item-crule (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2))) ; (crule-applicable (der-item-crule (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) ; (append (append ; (der-item-inp (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) ; (poslist2infolist (der-item-prems (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) aseq2)) ; (cons (cl2item (der-item-info (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2))) ; NULL)) ; aset)) ; (and (forall (lam (y num) ; (implies (is-component (num2item y) (der-item-prems (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2))) ; (less y ; (position (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2) aseq2))))) ; (= (der-item-info (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) ; (crule-application (der-item-crule (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) ; (append (append ; (der-item-inp (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) ; (poslist2infolist (der-item-prems (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) aseq2)) ; (cons (cl2item ; (der-item-info (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2))) ; NULL)) ; aset)))))) ("ForallE" (aterm) ; (l4))) ; ; (l6 () (is-component (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2) aseq2) ("abstract"()())) ; ; (l7 () (and (free-derivation-cond aseq2) ; (and (and (crule-set (der-item-crule (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2))) ; (crule-applicable (der-item-crule (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) ; (append (append ; (der-item-inp (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) ; (poslist2infolist (der-item-prems (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) aseq2)) ; (cons (cl2item (der-item-info (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2))) ; NULL)) ; aset)) ; (and (forall (lam (y num) ; (implies (is-component (num2item y) (der-item-prems (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2))) ; (less y ; (position (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2) aseq2))))) ; (= (der-item-info (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) ; (crule-application (der-item-crule (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) ; (append (append ; (der-item-inp (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) ; (poslist2infolist (der-item-prems (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) aseq2)) ; (cons (cl2item ; (der-item-info (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2))) ; NULL)) ; aset))))) ("ImpE" ()(l6 l5))) ; ; (l8 () (and (and (crule-set (der-item-crule (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2))) ; (crule-applicable (der-item-crule (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) ; (append (append ; (der-item-inp (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) ; (poslist2infolist (der-item-prems (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) aseq2)) ; (cons (cl2item (der-item-info (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2))) ; NULL)) ; aset)) ; (and (forall (lam (y num) ; (implies (is-component (num2item y) (der-item-prems (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2))) ; (less y ; (position (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2) aseq2))))) ; (= (der-item-info (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) ; (crule-application (der-item-crule (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) ; (append (append ; (der-item-inp (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) ; (poslist2infolist (der-item-prems (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) aseq2)) ; (cons (cl2item ; (der-item-info (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2))) ; NULL)) ; aset)))) ("AndER"() (l7))) ; ; (l9 () (and (and (crule-set (der-item-crule (idx-minus a-num-const ait))) ; (crule-applicable (der-item-crule (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) ; (append (append ; (der-item-inp (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) ; (poslist2infolist (der-item-prems (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) aseq2)) ; (cons (cl2item (der-item-info (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2))) ; NULL)) ; aset)) ; (and (forall (lam (y num) ; (implies (is-component (num2item y) (der-item-prems (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2))) ; (less y ; (position (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2) aseq2))))) ; (= (der-item-info (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) ; (crule-application (der-item-crule (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) ; (append (append ; (der-item-inp (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) ; (poslist2infolist (der-item-prems (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) aseq2)) ; (cons (cl2item ; (der-item-info (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2))) ; NULL)) ; aset)))) ("Subst="(apos10) ; ( l3 l8))) ; ; (l10 () (and (and (crule-set (der-item-crule (idx-minus a-num-const ait))) ; (crule-applicable (der-item-crule (idx-minus a-num-const ait)) ; (append (append ; (der-item-inp (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) ; (poslist2infolist (der-item-prems (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) aseq2)) ; (cons (cl2item (der-item-info (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2))) ; NULL)) ; aset)) ; (and (forall (lam (y num) ; (implies (is-component (num2item y) (der-item-prems (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2))) ; (less y ; (position (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2) aseq2))))) ; (= (der-item-info (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) ; (crule-application (der-item-crule (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) ; (append (append ; (der-item-inp (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) ; (poslist2infolist (der-item-prems (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) aseq2)) ; (cons (cl2item ; (der-item-info (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2))) ; NULL)) ; aset)))) ("Subst=" (apos11) ; ( l3 l9))) ; ; (l11 () (and (and (crule-set (der-item-crule (idx-minus a-num-const ait))) ; (crule-applicable (der-item-crule (idx-minus a-num-const ait)) ; (append (append ; (der-item-inp (idx-minus a-num-const ait)) ; (poslist2infolist (der-item-prems (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) aseq2)) ; (cons (cl2item (der-item-info (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2))) ; NULL)) ; aset)) ; (and (forall (lam (y num) ; (implies (is-component (num2item y) (der-item-prems (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2))) ; (less y ; (position (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2) aseq2))))) ; (= (der-item-info (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) ; (crule-application (der-item-crule (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) ; (append (append ; (der-item-inp (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) ; (poslist2infolist (der-item-prems (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) aseq2)) ; (cons (cl2item ; (der-item-info (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2))) ; NULL)) ; aset)))) ("Subst="(apos12) ; (l3 l10))) ; ; (l12 () (and (and (crule-set (der-item-crule (idx-minus a-num-const ait))) ; (crule-applicable (der-item-crule (idx-minus a-num-const ait)) ; (append (append ; (der-item-inp (idx-minus a-num-const ait)) ; (poslist2infolist ; (der-item-prems ; (idx-minus a-num-const ait)) aseq2)) ; (cons (cl2item (der-item-info (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2))) ; NULL)) ; aset)) ; (and (forall (lam (y num) ; (implies (is-component (num2item y) (der-item-prems (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2))) ; (less y ; (position (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2) aseq2))))) ; (= (der-item-info (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) ; (crule-application (der-item-crule (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) ; (append (append ; (der-item-inp (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) ; (poslist2infolist (der-item-prems (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) aseq2)) ; (cons (cl2item ; (der-item-info (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2))) ; NULL)) ; aset)))) ("Subst=" (apos13) ; (l3 l11))) ; ; (l13 () (and (and (crule-set (der-item-crule (idx-minus a-num-const ait))) ; (crule-applicable (der-item-crule (idx-minus a-num-const ait)) ; (append (append ; (der-item-inp (idx-minus a-num-const ait)) ; (poslist2infolist ; (der-item-prems ; (idx-minus a-num-const ait)) aseq2)) ; (cons (cl2item ; (der-item-info ; (idx-minus a-num-const ait))) NULL)) ; aset)) ; (and (forall (lam (y num) ; (implies (is-component (num2item y) (der-item-prems (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2))) ; (less y ; (position (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2) aseq2))))) ; (= (der-item-info (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) ; (crule-application (der-item-crule (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) ; (append (append ; (der-item-inp (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) ; (poslist2infolist (der-item-prems (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) aseq2)) ; (cons (cl2item ; (der-item-info (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2))) ; NULL)) ; aset)))) ("Subst=" (apos14) ; (l3 l12))) ; ; ; (l14 () (and (and (crule-set (der-item-crule (idx-minus a-num-const ait))) ; (crule-applicable (der-item-crule (idx-minus a-num-const ait)) ; (append (append ; (der-item-inp (idx-minus a-num-const ait)) ; (poslist2infolist ; (der-item-prems ; (idx-minus a-num-const ait)) aseq2)) ; (cons (cl2item ; (der-item-info ; (idx-minus a-num-const ait))) NULL)) ; aset)) ; (and (forall (lam (y num) ; (implies (is-component (num2item y) ; (der-item-prems ; (idx-minus a-num-const ait))) ; (less y ; (position (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2) aseq2))))) ; (= (der-item-info (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) ; (crule-application (der-item-crule (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) ; (append (append ; (der-item-inp (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) ; (poslist2infolist (der-item-prems (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) aseq2)) ; (cons (cl2item ; (der-item-info (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2))) ; NULL)) ; aset)))) ("Subst=" (apos15) ; (l3 l13))) ; ; (l15 () (and (and (crule-set (der-item-crule (idx-minus a-num-const ait))) ; (crule-applicable (der-item-crule (idx-minus a-num-const ait)) ; (append (append ; (der-item-inp (idx-minus a-num-const ait)) ; (poslist2infolist ; (der-item-prems ; (idx-minus a-num-const ait)) aseq2)) ; (cons (cl2item ; (der-item-info ; (idx-minus a-num-const ait))) NULL)) ; aset)) ; (and (forall (lam (y num) ; (implies (is-component (num2item y) ; (der-item-prems ; (idx-minus a-num-const ait))) ; (less y ; (position ; (idx-minus a-num-const ait) ; aseq2))))) ; (= (der-item-info (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) ; (crule-application (der-item-crule (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) ; (append (append ; (der-item-inp (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) ; (poslist2infolist (der-item-prems (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) aseq2)) ; (cons (cl2item ; (der-item-info (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2))) ; NULL)) ; aset)))) ("Subst=" (apos16) ; (l3 l14))) ; ; (l16 () (and (and (crule-set (der-item-crule (idx-minus a-num-const ait))) ; (crule-applicable (der-item-crule (idx-minus a-num-const ait)) ; (append (append ; (der-item-inp (idx-minus a-num-const ait)) ; (poslist2infolist ; (der-item-prems ; (idx-minus a-num-const ait)) aseq2)) ; (cons (cl2item ; (der-item-info ; (idx-minus a-num-const ait))) NULL)) ; aset)) ; (and (forall (lam (y num) ; (implies (is-component (num2item y) ; (der-item-prems ; (idx-minus a-num-const ait))) ; (less y ; (position ; (idx-minus a-num-const ait) ; aseq2))))) ; (= (der-item-info (idx-minus a-num-const ait)) ; (crule-application (der-item-crule (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) ; (append (append ; (der-item-inp (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) ; (poslist2infolist (der-item-prems (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) aseq2)) ; (cons (cl2item ; (der-item-info (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2))) ; NULL)) ; aset)))) ("Subst=" (apos17) ; (l3 l15))) ; ; (l17 () (and (and (crule-set (der-item-crule (idx-minus a-num-const ait))) ; (crule-applicable (der-item-crule (idx-minus a-num-const ait)) ; (append (append ; (der-item-inp (idx-minus a-num-const ait)) ; (poslist2infolist ; (der-item-prems ; (idx-minus a-num-const ait)) aseq2)) ; (cons (cl2item ; (der-item-info ; (idx-minus a-num-const ait))) NULL)) ; aset)) ; (and (forall (lam (y num) ; (implies (is-component (num2item y) ; (der-item-prems ; (idx-minus a-num-const ait))) ; (less y ; (position ; (idx-minus a-num-const ait) ; aseq2))))) ; (= (der-item-info (idx-minus a-num-const ait)) ; (crule-application (der-item-crule (idx-minus a-num-const ait)) ; (append (append ; (der-item-inp (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) ; (poslist2infolist (der-item-prems (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) aseq2)) ; (cons (cl2item ; (der-item-info (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2))) ; NULL)) ; aset)))) ("Subst=" (apos18) ; (l3 l16))) ; ; (l18 () (and (and (crule-set (der-item-crule (idx-minus a-num-const ait))) ; (crule-applicable (der-item-crule (idx-minus a-num-const ait)) ; (append (append ; (der-item-inp (idx-minus a-num-const ait)) ; (poslist2infolist ; (der-item-prems ; (idx-minus a-num-const ait)) aseq2)) ; (cons (cl2item ; (der-item-info ; (idx-minus a-num-const ait))) NULL)) ; aset)) ; (and (forall (lam (y num) ; (implies (is-component (num2item y) ; (der-item-prems ; (idx-minus a-num-const ait))) ; (less y ; (position ; (idx-minus a-num-const ait) ; aseq2))))) ; (= (der-item-info (idx-minus a-num-const ait)) ; (crule-application (der-item-crule (idx-minus a-num-const ait)) ; (append (append ; (der-item-inp (idx-minus a-num-const ait)) ; (poslist2infolist (der-item-prems (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2)) aseq2)) ; (cons (cl2item ; (der-item-info (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2))) ; NULL)) ; aset)))) ("Subst=" (apos19) (l3 l17))) ; ; (l19 () (and (and (crule-set (der-item-crule (idx-minus a-num-const ait))) ; (crule-applicable (der-item-crule (idx-minus a-num-const ait)) ; (append (append ; (der-item-inp (idx-minus a-num-const ait)) ; (poslist2infolist ; (der-item-prems ; (idx-minus a-num-const ait)) aseq2)) ; (cons (cl2item ; (der-item-info ; (idx-minus a-num-const ait))) NULL)) ; aset)) ; (and (forall (lam (y num) ; (implies (is-component (num2item y) ; (der-item-prems ; (idx-minus a-num-const ait))) ; (less y ; (position ; (idx-minus a-num-const ait) ; aseq2))))) ; (= (der-item-info (idx-minus a-num-const ait)) ; (crule-application (der-item-crule (idx-minus a-num-const ait)) ; (append (append ; (der-item-inp (idx-minus a-num-const ait)) ; (poslist2infolist ; (der-item-prems ; (idx-minus a-num-const ait)) aseq2)) ; (cons (cl2item ; (der-item-info (glist-nth (minus (position ait concat) ; (glist-length aseq1)) ; aseq2))) ; NULL)) ; aset)))) ("Subst=" (apos20) ; (l2 l18))) ; ; (l20 ()(and (and (crule-set (der-item-crule (idx-minus a-num-const ait))) ; (crule-applicable (der-item-crule (idx-minus a-num-const ait)) ; (append (append ; (der-item-inp (idx-minus a-num-const ait)) ; (poslist2infolist ; (der-item-prems ; (idx-minus a-num-const ait)) aseq2)) ; (cons (cl2item ; (der-item-info ; (idx-minus a-num-const ait))) NULL)) ; aset)) ; (and (forall (lam (y num) ; (implies (is-component (num2item y) ; (der-item-prems ; (idx-minus a-num-const ait))) ; (less y ; (position ; (idx-minus a-num-const ait) ; aseq2))))) ; (= (der-item-info (idx-minus a-num-const ait)) ; (crule-application (der-item-crule (idx-minus a-num-const ait)) ; (append (append ; (der-item-inp (idx-minus a-num-const ait)) ; (poslist2infolist ; (der-item-prems ; (idx-minus a-num-const ait)) aseq2)) ; (cons (cl2item ; (der-item-info ; (idx-minus a-num-const ait))) ; NULL)) ; aset)))) ("Subst=" (apos21) ; (l3 l19))) ; ; (l21 () (= (der-item-crule (idx-minus a-num-const ait)) ; (der-item-crule ait)) ("abstract"()())) ; ; (l22 () (and (and (crule-set (der-item-crule ait)) ; (crule-applicable (der-item-crule (idx-minus a-num-const ait)) ; (append (append ; (der-item-inp (idx-minus a-num-const ait)) ; (poslist2infolist ; (der-item-prems ; (idx-minus a-num-const ait)) aseq2)) ; (cons (cl2item ; (der-item-info ; (idx-minus a-num-const ait))) NULL)) ; aset)) ; (and (forall (lam (y num) ; (implies (is-component (num2item y) ; (der-item-prems ; (idx-minus a-num-const ait))) ; (less y ; (position ; (idx-minus a-num-const ait) ; aseq2))))) ; (= (der-item-info (idx-minus a-num-const ait)) ; (crule-application (der-item-crule (idx-minus a-num-const ait)) ; (append (append ; (der-item-inp (idx-minus a-num-const ait)) ; (poslist2infolist ; (der-item-prems ; (idx-minus a-num-const ait)) aseq2)) ; (cons (cl2item ; (der-item-info ; (idx-minus a-num-const ait))) ; NULL)) ; aset)))) ("subst=" (apos31) ; (l21 l20))) ; ; (l23 () (and (and (crule-set (der-item-crule ait)) ; (crule-applicable (der-item-crule ait) ; (append (append ; (der-item-inp (idx-minus a-num-const ait)) ; (poslist2infolist ; (der-item-prems ; (idx-minus a-num-const ait)) aseq2)) ; (cons (cl2item ; (der-item-info ; (idx-minus a-num-const ait))) NULL)) ; aset)) ; (and (forall (lam (y num) ; (implies (is-component (num2item y) ; (der-item-prems ; (idx-minus a-num-const ait))) ; (less y ; (position ; (idx-minus a-num-const ait) ; aseq2))))) ; (= (der-item-info (idx-minus a-num-const ait)) ; (crule-application (der-item-crule (idx-minus a-num-const ait)) ; (append (append ; (der-item-inp (idx-minus a-num-const ait)) ; (poslist2infolist ; (der-item-prems ; (idx-minus a-num-const ait)) aseq2)) ; (cons (cl2item ; (der-item-info ; (idx-minus a-num-const ait))) ; NULL)) ; aset)))) ("subst=" (apos32) ; (l21 l22))) ; ; (l24 () (and (and (crule-set (der-item-crule ait)) ; (crule-applicable (der-item-crule ait) ; (append (append ; (der-item-inp (idx-minus a-num-const ait)) ; (poslist2infolist ; (der-item-prems ; (idx-minus a-num-const ait)) aseq2)) ; (cons (cl2item ; (der-item-info ; (idx-minus a-num-const ait))) NULL)) ; aset)) ; (and (forall (lam (y num) ; (implies (is-component (num2item y) ; (der-item-prems ; (idx-minus a-num-const ait))) ; (less y ; (position ; (idx-minus a-num-const ait) ; aseq2))))) ; (= (der-item-info (idx-minus a-num-const ait)) ; (crule-application (der-item-crule ait) ; (append (append ; (der-item-inp (idx-minus a-num-const ait)) ; (poslist2infolist ; (der-item-prems ; (idx-minus a-num-const ait)) aseq2)) ; (cons (cl2item ; (der-item-info ; (idx-minus a-num-const ait))) ; NULL)) ; aset)))) ("subst=" (apos33) ; (l21 l23))) ; ; (l25 () (= (der-item-inp (idx-minus a-num-const ait)) ; (der-item-inp ait)) ("abstract"()())) ; ; (l26 () (and (and (crule-set (der-item-crule ait)) ; (crule-applicable (der-item-crule ait) ; (append (append ; (der-item-inp ait) ; (poslist2infolist ; (der-item-prems ; (idx-minus a-num-const ait)) aseq2)) ; (cons (cl2item ; (der-item-info ; (idx-minus a-num-const ait))) NULL)) ; aset)) ; (and (forall (lam (y num) ; (implies (is-component (num2item y) ; (der-item-prems ; (idx-minus a-num-const ait))) ; (less y ; (position ; (idx-minus a-num-const ait) ; aseq2))))) ; (= (der-item-info (idx-minus a-num-const ait)) ; (crule-application (der-item-crule ait) ; (append (append ; (der-item-inp (idx-minus a-num-const ait)) ; (poslist2infolist ; (der-item-prems ; (idx-minus a-num-const ait)) aseq2)) ; (cons (cl2item ; (der-item-info ; (idx-minus a-num-const ait))) ; NULL)) ; aset)))) ("Subst" (apos40) (l25 l24))) ; ; (l27 ()(and (and (crule-set (der-item-crule ait)) ; (crule-applicable (der-item-crule ait) ; (append (append ; (der-item-inp ait) ; (poslist2infolist ; (der-item-prems (idx-minus a-num-const ait)) aseq2)) ; (cons (cl2item ; (der-item-info ; (idx-minus a-num-const ait))) NULL)) ; aset)) ; (and (forall (lam (y num) ; (implies (is-component (num2item y) ; (der-item-prems ; (idx-minus a-num-const ait))) ; (less y ; (position ; (idx-minus a-num-const ait) ; aseq2))))) ; (= (der-item-info (idx-minus a-num-const ait)) ; (crule-application (der-item-crule ait) ; (append (append ; (der-item-inp ait) ; (poslist2infolist ; (der-item-prems ; (idx-minus a-num-const ait)) aseq2)) ; (cons (cl2item ; (der-item-info ; (idx-minus a-num-const ait))) ; NULL)) ; aset)))) ("Subst" (apos41) (l25 l26))) ;; Die folgenden 3 Gleicheiten muessen noch substituiert werden, dann ;; ist die zu zeigende Zeile bewiesen ; (l28 () (= (poslist2infolist ; (der-item-prems (idx-minus a-num-const ait)) aseq2) ; (poslist2infolist (der-item-prems ait) concat) ("abstract"()())) ; ; (l29 () (= (der-item-info (idx-minus a-num-const ait)) ; (der-item-info ait)) ("abstract"()())) ; ; (l30 () (= (forall (lam (y num) ; (implies (is-component (num2item y) ; (der-item-prems ; (idx-minus a-num-const ait))) ; (less y ; (position ; (idx-minus a-num-const ait) ; aseq2))))) ; (forall (lam (y num) ; (implies (is-component (num2item y) (der-item-prems ait)) ; (less y ; (position ait concat)))))) ("abstract"()())) ;; ---------------------------------------------------------------------------------- (ltp () (and (and (crule-set (der-item-crule ait)) (crule-applicable (der-item-crule ait) (append (append (der-item-inp ait) (poslist2infolist (der-item-prems ait) concat)) (cons (cl2item (der-item-info ait)) NULL)) aset)) (and (forall (lam (y num) (implies (is-component (num2item y) (der-item-prems ait)) (less y (position ait concat))))) (= (der-item-info ait) (crule-application (der-item-crule ait) (append (append (der-item-inp ait) (poslist2infolist (der-item-prems ait) concat)) (cons (cl2item (der-item-info ait)) NULL)) aset)))) ("Open"()())) ) (proc-content schema-interpreter) (remark "A method for prooving derivability goals with derivability assumtpions.") ) (infer~defmethod pureSetTh (help "Justification for a - as atomic - abstracted subgoal")) ;; These subgoals are solvebale declaratif or by a goaldirected atp-call. (infer~defmethod derive-meth3 (outline-mappings (((existent existent existent existent existent existent existent nonexistent ) derive-meth3-m-b))) (help "A method for prooving derivability goals with derivability assumtpions.")) (meth~defmethod derive-meth3-m-b derive-meth3 (in lock-res) (rating 30) (reasoning :planning) (declarations (constants ) (sorted-meta-variables (li1 form term) (li2 form term) (cl1 (o form) term) (cl2 (o form) term) (cl3 (o form) term) (cl4 (o form) term) (aseq1 glist term) (aseq2 glist term) (aset (o (o form)) term) (ait item term) (concat glist term) (goal (o form) term) (co8 (o form) term) ) ) (parameters ) (premises (- lh1) (- lh2) (- lh3) (- lh6) (- lh4) (- lh5) (+ l43) ;; (+ l99) ) (application-condition ) (outline-actions ;; (l99 (sponsor lh41)) (l43 (sponsor lh5)) ) (outline-orderings ; (before l99 l43) ) (outline-computations ) (conclusions (- ltp)) (decl-content ;; Concat ist der Term: ; (append aseq1 ; (append (push-idx aseq2 (glist-length aseq1)) ; (cons (der-item-constr res-res ; goal ; (cons (form2item li1) ; (cons (form2item li2) NULL)) ; (cons (num2item (glist-length aseq1)) ; (cons ; (num2item (plus (glist-length aseq1) ; ; (glist-length aseq2))) ; NULL))) ; NULL))); ; (lh1 () (= (position ait (append aseq1 (append (push-idx aseq2 (glist-length aseq1)) (cons (der-item-constr res-res goal (cons (form2item li1) (cons (form2item li2) NULL)) (cons (num2item (glist-length aseq1)) (cons (num2item (plus (glist-length aseq1) (glist-length aseq2))) NULL))) NULL)))) (plus one (plus (glist-length aseq1) (glist-length aseq2)))) ) (lh2 () (derivation-of aset crule-set aseq1 cl1) ) (lh3 () (derivation-of aset crule-set aseq2 cl2) ) (lh6 () (resolvable-s cl1 cl2) ) (lh4 () (= co8 (resolvent-of cl3 cl4 li1 li2)) ) (lh41 () (= co8 (setminus (setminus (union cl3 cl4) (singleton li1)) (singleton li2))) ("abstract"()())) (lh5 () (resolvable-b cl3 cl4 li1 li2) ) ; (l100 () (= ait ; (der-item-constr res-res ; goal ; (cons (form2item li1) ; (cons (form2item li2) NULL)) ; (cons (num2item (glist-length aseq1)) ; (cons ; (num2item (plus (glist-length aseq1) ; ; (glist-length aseq2))) ; NULL)))) ("abstract" ()())) ; (l70 () (= (der-item-info ait) ; goal) ("abstract"()())) ; (l69 () (= ; (der-item-crule ait) res-res) ("abstract" ()())) ; ; (l68 () (= (append (append ; (der-item-inp ait) ; (poslist2infolist (der-item-prems ait) concat)) ; (cons (cl2item ; (der-item-info ait)) ; NULL)) ; (cons (cl2item cl1) ; (cons (cl2item cl2) ; (cons (form2item li1) ; (cons (form2item li2) ; (cons (cl2item goal) ; NULL)))))) ("abstract"()())) ; ; (l67 () (= (crule-application res-res ; (cons (cl2item cl1) ; (cons (cl2item cl2) ; (cons (form2item li1) ; (cons (form2item li2) ; (cons (cl2item goal) ; NULL))))) ; aset) ; (resolvent-of cl1 cl2 li1 li2)) ("abstract"()())) ; (l66 () (= (that (lam (rk (o form)) ; (set= rk ; (setminus (setminus (union cl1 cl2) ; (singleton li1)) ; (singleton li2))))) ; (setminus (setminus (union cl1 cl2) ; (singleton li1)) ; (singleton li2))) ("abstract"()())) (l99 () (= goal (setminus (setminus (union cl1 cl2); (singleton li1)) (singleton li2))) ("pureSetTh"()())) ; (l65 () (= goal ; (that (lam (rk (o form)) ; (set= rk ; (setminus (setminus (union cl1 cl2) ; (singleton li1)) ; (singleton li2)))))) ("Subst="(apos10)(l66 l99))) ; ; (l64 () (= goal ; (resolvent-of cl1 cl2 li1 li2)) ("defnI" (resolvent-of) (l65))) ; ; (l63 () (= goal ; (crule-application res-res ; (cons (cl2item cl1) ; (cons (cl2item cl2) ; (cons (form2item li1) ; (cons (form2item li2) ; (cons (cl2item goal) ; NULL))))) ; aset)) ("subst=" (apos6) (l64 l67))) ; ; (l62 () (= goal ; (crule-application res-res ; (append (append ; (der-item-inp ait) ; (poslist2infolist (der-item-prems ait) concat)) ; (cons (cl2item ; (der-item-info ait)) ; NULL)) ; aset)) ("Subst=" (apos5) (l63 l68))) ; ; (l61 () (= goal ; (crule-application (der-item-crule ait) ; (append (append ; (der-item-inp ait) ; (poslist2infolist (der-item-prems ait) concat)) ; (cons (cl2item ; (der-item-info ait)) ; NULL)) ; aset)) ("Subst=" (apos4) (l62 l69))) ; ; (l6 () (= (der-item-info ait) ; (crule-application (der-item-crule ait) ; (append (append ; (der-item-inp ait) ; (poslist2infolist (der-item-prems ait) concat)) ; (cons (cl2item ; (der-item-info ait)) ; NULL)) ; aset)) ("Subst=" (apos3) (l61 l70))) ; ; ;; --------------------------------------------------------------------------- ; ; (l5 () (forall (lam (y num) ; (implies (is-component (num2item y) (der-item-prems ait)) ; (less y ; (position ait concat))))) ("abstract"()())) ; ; ;; ------------------------------------------------------------------- ; (l43 () (resolvable-b cl2 cl1 li1 li2) ("Open"()())) ; (l42 () (crule-applicable res-res ; (cons (cl2item cl1) ; (cons (cl2item cl2) ; (cons (form2item li1) ; (cons (form2item li2) ; (cons (cl2item goal) ; NULL))))) ; aset) ("Subst=" (apos9) (l43 l49))) ; ; (l41 () (crule-applicable res-res ; (append (append ; (der-item-inp ait) ; (poslist2infolist (der-item-prems ait) concat)) ; (cons (cl2item (der-item-info ait)) ; NULL)) ; aset) ("subst=" (apos8) (l42 l68))) ; ; (l4 () (crule-applicable (der-item-crule ait) ; (append (append ; (der-item-inp ait) ; (poslist2infolist (der-item-prems ait) concat)) ; (cons (cl2item (der-item-info ait)) ; NULL)) ; aset) ("subst=" (apos7) (l41 l69))) ; ; ;; ---------------------------------------------------------------- ; ; (l33 () (= (der-item-crule (der-item-constr res-res ; goal ; (cons (form2item li1) ; (cons (form2item li2) NULL)) ; (cons (num2item (glist-length aseq1)) ; (cons ; (num2item (plus (glist-length aseq1) ; ; (glist-length aseq2))) ; NULL)))) ; res-res) ("abstract"()())) ; ; (l32 () (crule-set res-res) ("abstract"()())) ; ; (l31 () (crule-set (der-item-crule (der-item-constr res-res ; goal ; (cons (form2item li1) ; (cons (form2item li2) NULL)) ; (cons (num2item (glist-length aseq1)) ; (cons ; (num2item (plus (glist-length aseq1) ; (glist-length aseq2))) ; NULL))))) ; ("Subst=" (apos2) (l32 l33))) ; ; (l3 () (crule-set (der-item-crule ait)) ("Subst=" (apos1) (l100 l31))) ; ; (l2 () (and (forall (lam (y num) ; (implies (is-component (num2item y) (der-item-prems ait)) ; (less y ; (position ait concat))))) ; (= (der-item-info ait) ; (crule-application (der-item-crule ait) ; (append (append ; (der-item-inp ait) ; (poslist2infolist (der-item-prems ait) concat)) ; (cons (cl2item ; (der-item-info ait)) ; NULL)) ; aset))) ("AndI" ()(l5 l6))) ; ; (l1 () (and (crule-set (der-item-crule ait)) ; (crule-applicable (der-item-crule ait) ; (append (append ; (der-item-inp ait) ; (poslist2infolist (der-item-prems ait) concat)) ; (cons (cl2item (der-item-info ait)) ; NULL)) ; aset)) ("AndI" ()(l3 l4))) ;; ------------------------------------------------------ ;; zunaechst standard aufloesung der AND (ltp () (and (and (crule-set (der-item-crule ait)) (crule-applicable (der-item-crule ait) (append (append (der-item-inp ait) (poslist2infolist (der-item-prems ait) concat)) (cons (cl2item (der-item-info ait)) NULL)) aset)) (and (forall (lam (y num) (implies (is-component (num2item y) (der-item-prems ait)) (less y (position ait concat))))) (= (der-item-info ait) (crule-application (der-item-crule ait) (append (append (der-item-inp ait) (poslist2infolist (der-item-prems ait) concat)) (cons (cl2item (der-item-info ait)) NULL)) aset)))) ("abstract"()())) ;; ("AndI"()(l1 l2))) ) (proc-content schema-interpreter) (remark "A method for prooving derivability goals with derivability assumtpions.") ) ;;; ========================================================= ;;; ;;; ELN METHODEN ;;; ;;; ========================================================= (infer~defmethod eln-ind-bc1-m (outline-mappings (((existent nonexistent nonexistent) eln-ind-bc1-m-b))) (help ".")) (meth~defmethod eln-ind-bc1-m-b eln-ind-bc1-m (in lock-res) (rating 30) (declarations (type-variables rr) (type-constants o i num form) (constants (dum-cl-set (o (o form)))) (sorted-meta-variables ;;(meta-var type sort) (x1 (o form) term) (y1 (o (o form)) term) (listbox glist term)) ) (parameters ) (premises (+ l7) (+ l8) ) (application-condition ) (outline-actions ) (outline-orderings ) (outline-computations (y1 (type-newconst (termtype dum-cl-set))) (x1 (type-newconst (termtype empty-cl))) (listbox (:term (cons (der-item-constr res-start x1 NULL NULL) NULL))) ) (conclusions (- ltp)) (decl-content (l9 () (in x1 y1) ("Hyp"()())) (l8 (l9) (derivation y1 crule-set (cons (der-item-constr res-start x1 NULL NULL) NULL)) ("Open" ()())) (l7 (l9) (= (der-item-info (last (cons (der-item-constr res-start x1 NULL NULL) NULL))) x1) ("Open" ()())) (l6 (l9) (AND (= (DER-ITEM-INFO (LAST (cons (der-item-constr res-start x1 NULL NULL) NULL))) X1) (DERIVATION Y1 CRULE-SET (cons (der-item-constr res-start x1 NULL NULL) NULL))) ("AndI" () (l7 l8))) (l5 (l9) (derivation-of y1 crule-set (cons (der-item-constr res-start x1 NULL NULL) NULL) x1) ("DefnI" (derivation-of)(l6))) (l4 (l9) (exists (lam (L glist) (derivation-of y1 crule-set L x1))) ("ExistsI" (listbox) (l5))) (l3 (l9) (derivable x1 y1 crule-set) ("DefnI" (derivable) (l4))) (l2 () (implies (in x1 y1) (derivable x1 y1 crule-set)) ("ImpI" () (l3))) (l1 () (forall (lam (y (o (o form))) (implies (in x1 y) (derivable x1 y crule-set)))) ("ForallI" (y1) (l2))) ;; ======================================================= (ltp () (forall (lam (x (o form)) (forall (lam (y (o (o form))) (implies (in x y) (derivable x y crule-set)))))) ("ForallI" (x1)(l1))) ) (proc-content schema-interpreter) (remark "") ) (infer~defmethod eln-ind-bc1-1-m (outline-mappings (((existent nonexistent nonexistent nonexistent nonexistent) eln-ind-bc1-1-m-b))) (help ".")) (meth~defmethod eln-ind-bc1-1-m-b eln-ind-bc1-1-m (in lock-res) (rating 30) (declarations (type-variables rr) (type-constants o i num form) (constants (dum-cl-set (o (o form)))) (sorted-meta-variables ;;(meta-var type sort) (y1 (o (o form)) term) (const6 (o (o form)) term) (const7 (o form) term) (ru crule term) (el (o form) term) (aanc form term)(pr glist term) (inp glist term) (pos211 o pos) (pos212 o pos) (pos21 o pos) (pos2 o pos) (alist o list) ) ) (parameters ) (premises (+ l9) (+ la3) (+ la4) (+ la5) ) (application-condition ) (outline-actions ) (outline-orderings ) (outline-computations (pos2211 (:position (2 2 1 1))) (pos2212 (:position (2 2 1 2))) (pos22 (:position (2 2))) (pos2 (:position (2))) ) (conclusions (- ltp)) (decl-content ; (ax1 () (forall (lam (ru crule) (forall (lam (el (o form)) ; (forall (lam (pr glist) (forall (lam (inp glist) ; (= (der-item-inp (der-item-constr ru el pr inp)) ; inp))))))))) ("Axiom"()())) ; ; (la1 () (= (der-item-inp ; (der-item-constr res-start ; const7 ; NULL ; NULL)) ; NULL) ("ForallE*+"()(ax1))) ; ; (ax2 () (forall (lam (ru crule) (forall (lam (el (o form)) ; (forall (lam (pr glist) (forall (lam (inp glist) ; (= (der-item-prems (der-item-constr ru el pr inp)) ; pr))))))))) ("Axiom"()())) ; ; (la2 () (= (der-item-prems ; (der-item-constr ; res-start ; const7 ; NULL ; NULL)) ; NULL) ("ForallE*+"()(ax2))) (la3 () (= (POSLIST2INFOLIST NULL (CONS (DER-ITEM-CONSTR RES-START CONST7 NULL NULL) NULL)) NULL) ("Open"()())) (la4 () (= (append NULL NULL) NULL) ("Open"()())) (la5 () (= (append NULL (CONS (CL2ITEM (DER-ITEM-INFO (DER-ITEM-CONSTR RES-START CONST7 NULL NULL))) NULL)) (CONS (CL2ITEM (DER-ITEM-INFO (DER-ITEM-CONSTR RES-START CONST7 NULL NULL))) NULL)) ("Open"()())) ; (ax6 () (forall (lam (seq glist) (forall (lam (S (o (o form))) ; (equiv (crule-applicable res-start seq S) ; (in (item2cl (first seq)) S)))))) ("Axiom"()())) ; ; (la61 () (equiv (crule-applicable ; res-start ; (CONS ; (CL2ITEM ; (DER-ITEM-INFO ; (DER-ITEM-CONSTR ; RES-START ; CONST7 ; NULL ; NULL))) ; NULL) ; const6) ; (in (item2cl (first (CONS ; (CL2ITEM ; (DER-ITEM-INFO ; (DER-ITEM-CONSTR ; RES-START ; CONST7 ; NULL ; NULL))) ; NULL))) const6)) ("ForallE*+"()(ax6))) ; ; (la62 () (implies (in (item2cl (first (CONS ; (CL2ITEM ; (DER-ITEM-INFO ; (DER-ITEM-CONSTR ; RES-START ; CONST7 ; NULL ; NULL))) ; NULL))) const6) ; (crule-applicable ; res-start ; (CONS ; (CL2ITEM ; (DER-ITEM-INFO ; (DER-ITEM-CONSTR ; RES-START ; CONST7 ; NULL ; NULL))) ; NULL) ; const6)) ("EquivER"()(la61))) ; ; (ax7 () (forall (lam (x item) (forall (lam (L glist) ; (= (first (cons x L)) x))))) ("Axiom"()())) ; ; (la7 () (= (first (cons (CL2ITEM ; (DER-ITEM-INFO ; (DER-ITEM-CONSTR ; RES-START ; CONST7 ; NULL ; NULL))) NULL)) ; (CL2ITEM ; (DER-ITEM-INFO ; (DER-ITEM-CONSTR ; RES-START ; CONST7 ; NULL ; NULL)))) ("ForallE*+"()(ax7))) ; ; (ax8 () (forall (lam (akl (o form)) ; (= (item2cl (cl2item akl)) ; akl))) ("Axiom"()())) ; ; (la8 () (= (item2cl (cl2item (DER-ITEM-INFO ; (DER-ITEM-CONSTR ; RES-START ; CONST7 ; NULL ; NULL)))) ; (DER-ITEM-INFO ; (DER-ITEM-CONSTR ; RES-START ; CONST7 ; NULL ; NULL))) ("ForallE*+" () (ax8))) ; ; (ax9 () (forall (lam (ru crule) (forall (lam (el (o form)) ; (forall (lam (pr glist) (forall (lam (inp glist) ; (= (der-item-info (der-item-constr ru el pr inp)) ; el))))))))) ("Axiom"()())) ; ; (la9 () (= (DER-ITEM-INFO ; (DER-ITEM-CONSTR ; RES-START ; CONST7 ; NULL ; NULL)) ; const7) ("forallE*+" () (ax9))) (l9 () (in const7 const6) ("Open"()())) ; (l8 () (in (DER-ITEM-INFO ; (DER-ITEM-CONSTR ; RES-START ; CONST7 ; NULL ; NULL)) ; const6) ("Subst=" (pos1) (l9 la9))) ; ; (l7 () (in (item2cl (CL2ITEM ; (DER-ITEM-INFO ; (DER-ITEM-CONSTR ; RES-START ; CONST7 ; NULL ; NULL)))) const6) ("Subst=" (pos1) (l8 la8))) ; ; (l6 () (in (item2cl (first (CONS ; (CL2ITEM ; (DER-ITEM-INFO ; (DER-ITEM-CONSTR ; RES-START ; CONST7 ; NULL ; NULL))) ; NULL))) const6) ("Subst=" (pos11) (l7 la7))) ; ; (l5 () (CRULE-APPLICABLE ; RES-START ; (CONS ; (CL2ITEM ; (DER-ITEM-INFO ; (DER-ITEM-CONSTR ; RES-START ; CONST7 ; NULL ; NULL))) ; NULL) ; CONST6) ("ImpE" ()(la62 l6))) ; ; (l4 () (CRULE-APPLICABLE ; RES-START ; (APPEND ; NULL ; (CONS ; (CL2ITEM ; (DER-ITEM-INFO ; (DER-ITEM-CONSTR ; RES-START ; CONST7 ; NULL ; NULL))) ; NULL)) ; CONST6) ("subst=" (pos2) (l5 la5))) ; ; (l3 () (CRULE-APPLICABLE ; RES-START ; (APPEND ; (APPEND ; NULL ; NULL) ; (CONS ; (CL2ITEM ; (DER-ITEM-INFO ; (DER-ITEM-CONSTR ; RES-START ; CONST7 ; NULL ; NULL))) ; NULL)) ; CONST6) ("subst" (pos21) (l4 la4))) ; ; (l2 () (CRULE-APPLICABLE ; RES-START ; (APPEND ; (APPEND ; NULL ; (POSLIST2INFOLIST ; NULL ; (CONS ; (DER-ITEM-CONSTR ; RES-START ; CONST7 ; NULL ; NULL) ; NULL))) ; (CONS ; (CL2ITEM ; (DER-ITEM-INFO ; (DER-ITEM-CONSTR ; RES-START ; CONST7 ; NULL ; NULL))) ; NULL)) ; CONST6) ("subst=" (pos212) (l3 la3))) ; ; (l1 () (CRULE-APPLICABLE ; RES-START ; (APPEND ; (APPEND ; NULL ; (POSLIST2INFOLIST ; (DER-ITEM-PREMS ; (DER-ITEM-CONSTR ; RES-START ; CONST7 ; NULL ; NULL)) ; (CONS ; (DER-ITEM-CONSTR ; RES-START ; CONST7 ; NULL ; NULL) ; NULL))) ; (CONS ; (CL2ITEM ; (DER-ITEM-INFO ; (DER-ITEM-CONSTR ; RES-START ; CONST7 ; NULL ; NULL))) ; NULL)) ; CONST6) ("Subst="(pos2121) (l2 la2))) (ltp () (CRULE-APPLICABLE ;;RES-START (DER-ITEM-CRULE (DER-ITEM-CONSTR RES-START const7 NULL NULL)) (APPEND (APPEND (DER-ITEM-INP (DER-ITEM-CONSTR RES-START CONST7 NULL NULL)) (POSLIST2INFOLIST (DER-ITEM-PREMS (DER-ITEM-CONSTR RES-START CONST7 NULL NULL)) (CONS (DER-ITEM-CONSTR RES-START const7 NULL NULL) NULL))) (CONS (CL2ITEM (DER-ITEM-INFO (DER-ITEM-CONSTR RES-START CONST7 NULL NULL))) NULL)) CONST6) ("Open"()())) ;;("Subst=" (pos211) (l1 la1))) ) (proc-content schema-interpreter) (remark "") ) (infer~defmethod eln-ind-bc1-2-m (outline-mappings (((existent nonexistent nonexistent nonexistent nonexistent) eln-ind-bc1-2-m-b))) (help ".")) (meth~defmethod eln-ind-bc1-2-m-b eln-ind-bc1-2-m (in lock-res) (rating 30) (declarations (type-variables rr) (type-constants o i num form) (constants (dum-cl-set (o (o form)))) (sorted-meta-variables ;;(meta-var type sort) (y1 (o (o form)) term) (const6 (o (o form)) term) (const7 (o form) term) (ru crule term) (el (o form) term) (pr glist term) (inp glist term) (pos211 o pos) (pos212 o pos) (pos21 o pos) (pos2 o pos) (alist o list) ) ) (parameters ) (premises (+ l8) (+ la3) (+ la4) (+ la5) ) (application-condition ) (outline-actions ) (outline-orderings ) (outline-computations (pos2211 (:position (2 2 1 1))) (pos2212 (:position (2 2 1 2))) (pos22 (:position (2 2))) (pos2 (:position (2))) ) (conclusions (- ltp)) (decl-content ; (ax1 () (forall (lam (ru crule) (forall (lam (el (o form)) ; (forall (lam (pr glist) (forall (lam (inp glist) ; (= (der-item-inp (der-item-constr ru el pr inp)) ; inp))))))))) ("Axiom"()())) ; ; (la1 () (= (der-item-inp ; (der-item-constr res-start ; const7 ; NULL ; NULL)) ; NULL) ("ForallE*+"()(ax1))) ; (ax2 () (forall (lam (ru crule) (forall (lam (el (o form)) ; (forall (lam (pr glist) (forall (lam (inp glist) ; (= (der-item-prems (der-item-constr ru el pr inp)) ; pr))))))))) ("Axiom"()())) ; ; (la2 () (= (der-item-prems ; (der-item-constr ; res-start ; const7 ; NULL ; NULL)) ; NULL) ("ForallE*+"()(ax2))) (la3 () (= (POSLIST2INFOLIST NULL (CONS (DER-ITEM-CONSTR RES-START CONST7 NULL NULL) NULL)) NULL) ("Open"()())) (la4 () (= (append NULL NULL) NULL) ("Open"()())) (la5 () (= (APPEND NULL (CONS (CL2ITEM CONST7) NULL)) (CONS (CL2ITEM CONST7) NULL))("Open"()())) (ax6 () (forall (lam (seq glist) (forall (lam (S (o (o form))) (= (crule-application res-start seq S) (item2cl (first seq)))))))("Axiom"()())) (la6 () (= (crule-application res-start (CONS (CL2ITEM CONST7) NULL) CONST6) (item2cl (first (CONS (CL2ITEM CONST7) NULL)))) ("ForallE*+"()(ax6))) (ax7 () (forall (lam (x item) (forall (lam (L glist) (= (first (cons x L)) x))))) ("Axiom"()())) (la7 () (= (first (cons (CL2ITEM CONST7) NULL)) (CL2ITEM CONST7)) ("ForallE*+"()(ax8))) (ax8 () (forall (lam (akl (o form)) (= (item2cl (cl2item akl)) akl))) ("Axiom"()())) (la8 () (= (item2cl (cl2item CONST7)) CONST7) ("ForallE*+"()(ax8))) (l8 () (= CONST7 CONST7) ("Open"()())) (l7 () (= CONST7 (item2cl(CL2ITEM CONST7))) ("subst=" (pos2) (l8 la8))) (l6 () (= CONST7 (item2cl (first (CONS (CL2ITEM CONST7) NULL)))) ("subst=" (pos21)(l7 la7))) (l5 () (= CONST7 (CRULE-APPLICATION RES-START (CONS (CL2ITEM CONST7) NULL) CONST6)) ("Subst=" (pos22)(l6 la6))) (l4 () (= CONST7 (CRULE-APPLICATION RES-START (APPEND NULL (CONS (CL2ITEM CONST7) NULL)) CONST6)) ("subst=" (pos222)(l5 la5))) (l3 () (= CONST7 (CRULE-APPLICATION RES-START (APPEND (APPEND NULL NULL) (CONS (CL2ITEM CONST7) NULL)) CONST6)) ("subst=" (pos221) (l4 la4))) (l2 () (= CONST7 (CRULE-APPLICATION RES-START (APPEND (APPEND NULL (POSLIST2INFOLIST NULL (CONS (DER-ITEM-CONSTR RES-START CONST7 NULL NULL) NULL))) (CONS (CL2ITEM CONST7) NULL)) CONST6)) ("subst="(pos2212)(l3 la3))) (l1 () (= CONST7 (CRULE-APPLICATION RES-START (APPEND (APPEND NULL (POSLIST2INFOLIST (DER-ITEM-PREMS (DER-ITEM-CONSTR RES-START CONST7 NULL NULL)) (CONS (DER-ITEM-CONSTR RES-START CONST7 NULL NULL) NULL))) (CONS (CL2ITEM CONST7) NULL)) CONST6)) ("Subst=" (pos22121) (l2 la2))) (ltp () (= CONST7 (CRULE-APPLICATION (DER-ITEM-CRULE (DER-ITEM-CONSTR RES-START const7 NULL NULL)) (APPEND (APPEND (DER-ITEM-INP (DER-ITEM-CONSTR RES-START CONST7 NULL NULL)) (POSLIST2INFOLIST (DER-ITEM-PREMS (DER-ITEM-CONSTR RES-START CONST7 NULL NULL)) (CONS (DER-ITEM-CONSTR RES-START CONST7 NULL NULL) NULL))) (CONS (CL2ITEM CONST7) NULL)) CONST6)) ("Subst="(pos2211)(l1 la1))) ) (proc-content schema-interpreter) (remark "") ) (infer~defmethod eln-ind-bc2-1-m (outline-mappings (((existent nonexistent nonexistent nonexistent nonexistent) eln-ind-bc2-1-m-b))) (help "Methode zur Vereinfachung des ELN-Ind-Schrittes.")) (meth~defmethod eln-ind-bc2-1-m-b eln-ind-bc2-1-m (in lock-res) (rating 30) (declarations (type-variables rr) (type-constants o i num form) (sorted-meta-variables ;;(meta-var type sort) (y1 (o (o form)) term) (const6 form term) (const7 form term) (ru crule term) (el (o form) term) (pr glist term) (inp glist term) (pos211 o pos) (pos212 o pos) (pos21 o pos) (pos2 o pos) (alist o list) )) (parameters ) (premises (+ ng1) (+ ax3) (+ ax5) (+ ax6)) (application-condition ) (outline-actions ) (outline-orderings ) (outline-computations ;; (alist (mlist ru el pr inp)) (pos211 (:position (2 1 1))) (pos212 (:position (2 1 2))) (pos21 (:position (2 1))) (pos2 (:position (2))) ) (conclusions (- ltp)) (decl-content (ax1 () (forall (lam (ru crule) (forall (lam (el (o form)) (forall (lam (pr glist) (forall (lam (inp glist) (= (der-item-inp (der-item-constr ru el pr inp)) inp))))))))) ("Axiom"()())) (lax1-1 () (= (der-item-inp (der-item-constr res-res empty-cl (CONS (NUM2ITEM ZERO) (CONS (NUM2ITEM (S ZERO)) NULL)) (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) NULL)))) (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) NULL))) ("ForallE*+" ()(ax1))) ;; (res-res empty-cl ;; (CONS (NUM2ITEM ZERO) (CONS (NUM2ITEM (S ZERO)) NULL)) ;; (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) NULL)))))) (ax2 () (forall (lam (ru crule) (forall (lam (el (o form)) (forall (lam (pr glist) (forall (lam (inp glist) (= (der-item-prems (der-item-constr ru el pr inp)) pr))))))))) ("Axiom"()())) (lax2-1 () (= (der-item-prems (der-item-constr res-res empty-cl (CONS (NUM2ITEM ZERO) (CONS (NUM2ITEM (S ZERO)) NULL)) (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) NULL)))) (CONS (NUM2ITEM ZERO) (CONS (NUM2ITEM (S ZERO)) NULL))) ("forallE*+" ()(ax2))) ;; (res-res empty-cl ;; (CONS (NUM2ITEM ZERO) (CONS (NUM2ITEM (S ZERO)) NULL)) ;; (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) NULL)))) ;; (ax2))) (ax3 () (= (POSLIST2INFOLIST (CONS (NUM2ITEM ZERO) (CONS (NUM2ITEM (S ZERO)) NULL)) (CONS (DER-ITEM-CONSTR RES-START (SINGLETON CONST6) NULL NULL) (CONS (DER-ITEM-CONSTR RES-START (SINGLETON CONST7) NULL NULL) (CONS (DER-ITEM-CONSTR RES-RES EMPTY-CL (CONS (NUM2ITEM ZERO) (CONS (NUM2ITEM (S ZERO)) NULL)) (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) NULL))) NULL)))) (cons (cl2item (SINGLETON CONST6)) (cons (cl2item (SINGLETON CONST7)) NULL))) ("Open"()())) (ax4 () (forall (lam (ru crule) (forall (lam (el (o form)) (forall (lam (pr glist) (forall (lam (inp glist) (= (der-item-info (der-item-constr ru el pr inp)) el))))))))) ("Axiom" ()())) ; (lax4-1 () (= (der-item-info (der-item-constr res-res ; empty-cl ; (CONS (NUM2ITEM ZERO) (CONS (NUM2ITEM (S ZERO)) NULL)) ; (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) NULL)))) ; empty-cl) ("ForallE*+" ()(ax4))) ;; (res-res empty-cl ;; (CONS (NUM2ITEM ZERO) (CONS (NUM2ITEM (S ZERO)) NULL)) ;; (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) NULL)))) ;; (ax4))) (ax5 () (= (APPEND (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) NULL)) (cons (cl2item (SINGLETON CONST6)) (cons (cl2item (SINGLETON CONST7)) NULL))) (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) (cons (cl2item (SINGLETON CONST6)) (cons (cl2item (SINGLETON CONST7)) NULL))))) ("Open"()())) (ax6 () (= (APPEND (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) (cons (cl2item (SINGLETON CONST6)) (cons (cl2item (SINGLETON CONST7)) NULL)))) (CONS (CL2ITEM empty-cl) NULL)) (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) (cons (cl2item (SINGLETON CONST6)) (cons (cl2item (SINGLETON CONST7)) (CONS (CL2ITEM empty-cl) NULL) ))))) ("Open"()())) ;; --------------------------------- (ng1 () (CRULE-APPLICABLE RES-RES (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) (cons (cl2item (SINGLETON CONST6)) (cons (cl2item (SINGLETON CONST7)) (CONS (CL2ITEM empty-cl) NULL) )))) Y1) ("Open"()())) ;; ---------------------------------- (l5 () (CRULE-APPLICABLE RES-RES (APPEND (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) (cons (cl2item (SINGLETON CONST6)) (cons (cl2item (SINGLETON CONST7)) NULL)))) (CONS (CL2ITEM empty-cl) NULL)) Y1) ("Subst=" (pos2) (ax6 ng1))) (l4 () (CRULE-APPLICABLE RES-RES (APPEND (APPEND (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) NULL)) (cons (cl2item (SINGLETON CONST6)) (cons (cl2item (SINGLETON CONST7)) NULL))) (CONS (CL2ITEM empty-cl) NULL)) Y1) ("Subst=" (pos21) (ax5 l5))) (l3 () (CRULE-APPLICABLE RES-RES (APPEND (APPEND (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) NULL)) (cons (cl2item (SINGLETON CONST6)) (cons (cl2item (SINGLETON CONST7)) NULL))) (CONS (CL2ITEM (DER-ITEM-INFO (DER-ITEM-CONSTR RES-RES EMPTY-CL (CONS (NUM2ITEM ZERO) (CONS (NUM2ITEM (S ZERO)) NULL)) (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) NULL))))) NULL)) Y1) ("Subst=" ()(lax4-1 l4))) (l2 () (CRULE-APPLICABLE RES-RES (APPEND (APPEND (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) NULL)) (POSLIST2INFOLIST (CONS (NUM2ITEM ZERO) (CONS (NUM2ITEM (S ZERO)) NULL)) (CONS (DER-ITEM-CONSTR RES-START (SINGLETON CONST6) NULL NULL) (CONS (DER-ITEM-CONSTR RES-START (SINGLETON CONST7) NULL NULL) (CONS (DER-ITEM-CONSTR RES-RES EMPTY-CL (CONS (NUM2ITEM ZERO) (CONS (NUM2ITEM (S ZERO)) NULL)) (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) NULL))) NULL))))) (CONS (CL2ITEM (DER-ITEM-INFO (DER-ITEM-CONSTR RES-RES EMPTY-CL (CONS (NUM2ITEM ZERO) (CONS (NUM2ITEM (S ZERO)) NULL)) (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) NULL))))) NULL)) Y1) ("Subst="(pos212) (lax3 l3))) (l1 () (CRULE-APPLICABLE RES-RES (APPEND (APPEND (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) NULL)) (POSLIST2INFOLIST (DER-ITEM-PREMS (DER-ITEM-CONSTR RES-RES EMPTY-CL (CONS (NUM2ITEM ZERO) (CONS (NUM2ITEM (S ZERO)) NULL)) (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) NULL)))) (CONS (DER-ITEM-CONSTR RES-START (SINGLETON CONST6) NULL NULL) (CONS (DER-ITEM-CONSTR RES-START (SINGLETON CONST7) NULL NULL) (CONS (DER-ITEM-CONSTR RES-RES EMPTY-CL (CONS (NUM2ITEM ZERO) (CONS (NUM2ITEM (S ZERO)) NULL)) (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) NULL))) NULL))))) (CONS (CL2ITEM (DER-ITEM-INFO (DER-ITEM-CONSTR RES-RES EMPTY-CL (CONS (NUM2ITEM ZERO) (CONS (NUM2ITEM (S ZERO)) NULL)) (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) NULL))))) NULL)) Y1) ("Subst=" (pos) (lax2-1 l2))) (ltp () (CRULE-APPLICABLE ;;RES-RES (DER-ITEM-CRULE (DER-ITEM-CONSTR RES-RES EMPTY-CL (CONS (NUM2ITEM ZERO) (CONS (NUM2ITEM (S ZERO)) NULL)) (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) NULL)))) (APPEND (APPEND (DER-ITEM-INP (DER-ITEM-CONSTR RES-RES EMPTY-CL (CONS (NUM2ITEM ZERO) (CONS (NUM2ITEM (S ZERO)) NULL)) (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) NULL)))) (POSLIST2INFOLIST (DER-ITEM-PREMS (DER-ITEM-CONSTR RES-RES EMPTY-CL (CONS (NUM2ITEM ZERO) (CONS (NUM2ITEM (S ZERO)) NULL)) (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) NULL)))) (CONS (DER-ITEM-CONSTR RES-START (SINGLETON CONST6) NULL NULL) (CONS (DER-ITEM-CONSTR RES-START (SINGLETON CONST7) NULL NULL) (CONS (DER-ITEM-CONSTR RES-RES EMPTY-CL (CONS (NUM2ITEM ZERO) (CONS (NUM2ITEM (S ZERO)) NULL)) (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) NULL))) NULL))))) (CONS (CL2ITEM (DER-ITEM-INFO (DER-ITEM-CONSTR RES-RES EMPTY-CL (CONS (NUM2ITEM ZERO) (CONS (NUM2ITEM (S ZERO)) NULL)) (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) NULL))))) NULL)) Y1) ("Subst=" (pos211) (l1 lax1-1))) ) (proc-content schema-interpreter) (remark "Method to simplify the eln-ind base-case.") ) (infer~defmethod eln-ind-bc2-2-m (outline-mappings (((existent nonexistent nonexistent nonexistent nonexistent) eln-ind-bc2-2-m-b))) (help "Methode zur Vereinfachung des ELN-Ind-Schrittes.")) (meth~defmethod eln-ind-bc2-2-m-b eln-ind-bc2-2-m (in lock-res) (rating 30) (declarations (type-variables rr) (type-constants o i num form) (sorted-meta-variables ;;(meta-var type sort) (y1 (o (o form)) term) (const6 form term) (const7 form term) (cost7 form term) (ru crule term) (el (o form) term) (pr glist term) (inp glist term) (pos211 o pos) (pos212 o pos) (pos21 o pos) (pos2 o pos) (alist o list) (acl-const (o form) term) )) (parameters ) (premises (+ l9) (+ ax3) (+ ax4) (+ ax5)) (application-condition ) (outline-actions ) (outline-orderings ) (outline-computations ;; (alist (mlist ru el pr inp)) (pos2211 (:position (2 2 1 1))) (pos2212 (:position (2 2 1 2))) (pos22 (:position (2 2))) (pos2 (:position (2))) (pos11111 (:position (1 1 1 1 1))) (pos111 (:position (1 1 1))) (pos1 (:position (1))) ) (conclusions (- ltp)) (decl-content ; (ax1 () (forall (lam (ru crule) (forall (lam (el (o form)) ; (forall (lam (pr glist) (forall (lam (inp glist) ; (= (der-item-inp (der-item-constr ru el pr inp)) ; inp))))))))) ("Axiom"()())) ; ; (la1 () (= (der-item-inp ; (der-item-constr res-start ; (singleton const7) ; NULL NULL)) ; NULL) ("Foralle*+"()())) ; ; (ax2 () (forall (lam (ru crule) (forall (lam (el (o form)) ; (forall (lam (pr glist) (forall (lam (inp glist) ; (= (der-item-prems (der-item-constr ru el pr inp)) ; pr))))))))) ("Axiom" ()())) ; ; (la2 () (= (der-item-prems ; (der-item-constr res-start ; (SINGLETON CONST7) ; NULL ; NULL)) ; NULL) ("ForallE*+"()())) (ax3 () (= (POSLIST2INFOLIST NULL (CONS (DER-ITEM-CONSTR RES-START (SINGLETON CONST6) NULL NULL) (CONS (DER-ITEM-CONSTR RES-START (SINGLETON CONST7) NULL NULL) (CONS (DER-ITEM-CONSTR RES-RES EMPTY-CL (CONS (NUM2ITEM ZERO) (CONS (NUM2ITEM (S ZERO)) NULL)) (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) NULL))) NULL)))) NULL) ("Open"()())) (ax4 () (= (APPEND NULL NULL) NULL) ("Open"()())) (ax5 () (= (APPEND NULL (CONS (CL2ITEM (DER-ITEM-INFO (DER-ITEM-CONSTR RES-START (SINGLETON CONST7) NULL NULL))) NULL)) (CONS (CL2ITEM (DER-ITEM-INFO (DER-ITEM-CONSTR RES-START (SINGLETON CONST7) NULL NULL))) NULL)) ("Open"()())) ; ; (ax6 () (forall (lam (seq glist) (forall (lam (S (o (o form))) ; (equiv (crule-applicable res-start seq S) ; (in (item2cl (first seq)) S)))))) ("axiom"()())) ; ; (la6 () (equiv (crule-applicable res-start ; (CONS ; (CL2ITEM ; (DER-ITEM-INFO ; (DER-ITEM-CONSTR ; RES-START ; (SINGLETON CONST7) ; NULL ; NULL))) ; NULL) ; Y1) ; (in (item2cl (first (CONS ; (CL2ITEM ; (DER-ITEM-INFO ; (DER-ITEM-CONSTR ; RES-START ; (SINGLETON CONST7) ; NULL ; NULL))) ; NULL) )) Y1)) ; ("forallE*+"()(ax6))) ; ; (la61 () (implies (in (item2cl (first (CONS ; (CL2ITEM ; (DER-ITEM-INFO ; (DER-ITEM-CONSTR ; RES-START ; (SINGLETON CONST7) ; NULL ; NULL))) ; NULL) )) Y1) ; (crule-applicable res-start ; (CONS ; (CL2ITEM ; (DER-ITEM-INFO ; (DER-ITEM-CONSTR ; RES-START ; (SINGLETON CONST7) ; NULL ; NULL))) ; NULL) ; Y1)) ; ("EquiveR" () (la6))) ; ; ; (ax7 () (forall (lam (ru crule) (forall (lam (el (o form)) ; (forall (lam (pr glist) (forall (lam (inp glist) ; (= (der-item-info (der-item-constr ru el pr inp)) ; el))))))))) ("Axiom"()())) ; ; (la7 () (= (der-item-info ; (der-item-constr ; res-start ; (SINGLETON CONST7) ; NULL NULL)) ; (singleton const7)) ("ForallE*+"()(ax7))) ; ; (ax8 () (forall (lam (x item) (forall (lam (L glist) ; (= (first (cons x L)) x))))) ("Axiom"()())) ; ; (la8 () (= (first (cons (CL2ITEM (singleton const7)) ; NULL )) ; (CL2ITEM (singleton const7))) ("ForallE*+"()(ax8))) ; ; (ax9 () (forall (lam (akl (o form)) ; (= (item2cl (cl2item akl)) ; akl))) ("Axiom"()())) ; ; (la9 () (= (item2cl (CL2ITEM ; (singleton const7))) ; (singleton const7)) ("ForallE*+"()(ax9))) (l9 () (in (singleton cost7) Y1) ("Open"()())) ; (l8 () (in (item2cl (CL2ITEM ; (singleton const7))) ; Y1) ("Subst=" (pos1) (l9 la9))) ; ; (l7 () (in (item2cl (first (CONS ; (CL2ITEM ; (singleton const7)) ; NULL) )) ; Y1) ("Subst="(pos111) (l8 la8))) ; ; (l6 () (in (item2cl (first (CONS ; (CL2ITEM ; (DER-ITEM-INFO ; (DER-ITEM-CONSTR ; RES-START ; (SINGLETON CONST7) ; NULL ; NULL))) ; NULL) )) Y1) ("subst=" (pos11111) (l7 la7))) ; ; (l5 (l6) (CRULE-APPLICABLE ; RES-START ; (CONS ; (CL2ITEM ; (DER-ITEM-INFO ; (DER-ITEM-CONSTR ; RES-START ; (SINGLETON CONST7) ; NULL ; NULL))) ; NULL) ; Y1) ("ImpE"()(l6 la61))) ; ; (l4 () (CRULE-APPLICABLE ; RES-START ; (APPEND ; NULL ; (CONS ; (CL2ITEM ; (DER-ITEM-INFO ; (DER-ITEM-CONSTR ; RES-START ; (SINGLETON CONST7) ; NULL ; NULL))) ; NULL)) ; Y1) ("subst=" (pos2) (l5 ax5))) ; ; (l3 () (CRULE-APPLICABLE ; RES-START ; (APPEND ; (APPEND NULL NULL) ; (CONS ; (CL2ITEM ; (DER-ITEM-INFO ; (DER-ITEM-CONSTR ; RES-START ; (SINGLETON CONST7) ; NULL ; NULL))) ; NULL)) ; Y1) ("Subst=" (pos21) (l4 ax4))) ; ; (l2 () (CRULE-APPLICABLE ; RES-START ; (APPEND ; (APPEND ; NULL ; (POSLIST2INFOLIST ; NULL ; (CONS ; (DER-ITEM-CONSTR ; RES-START ; (SINGLETON CONST6) ; NULL ; NULL) ; (CONS ; (DER-ITEM-CONSTR ; RES-START ; (SINGLETON CONST7) ; NULL ; NULL) ; (CONS ; (DER-ITEM-CONSTR ; RES-RES ; EMPTY-CL ; (CONS ; (NUM2ITEM ZERO) ; (CONS ; (NUM2ITEM (S ZERO)) ; NULL)) ; (CONS ; (FORM2ITEM CONST6) ; (CONS ; (FORM2ITEM CONST7) ; NULL))) ; NULL))))) ; (CONS ; (CL2ITEM ; (DER-ITEM-INFO ; (DER-ITEM-CONSTR ; RES-START ; (SINGLETON CONST7) ; NULL ; NULL))) ; NULL)) ; Y1) ("subst=" (pos212) (l3 ax3))) ; ; (l1 () (CRULE-APPLICABLE ; RES-START ; (APPEND ; (APPEND ; NULL ; (POSLIST2INFOLIST ; (DER-ITEM-PREMS ; (DER-ITEM-CONSTR ; RES-START ; (SINGLETON CONST7) ; NULL ; NULL)) ; (CONS ; (DER-ITEM-CONSTR ; RES-START ; (SINGLETON CONST6) ; NULL ; NULL) ; (CONS ; (DER-ITEM-CONSTR ; RES-START ; (SINGLETON CONST7) ; NULL ; NULL) ; (CONS ; (DER-ITEM-CONSTR ; RES-RES ; EMPTY-CL ; (CONS ; (NUM2ITEM ZERO) ; (CONS ; (NUM2ITEM (S ZERO)) ; NULL)) ; (CONS ; (FORM2ITEM CONST6) ; (CONS ; (FORM2ITEM CONST7) ; NULL))) ; NULL))))) ; (CONS ; (CL2ITEM ; (DER-ITEM-INFO ; (DER-ITEM-CONSTR ; RES-START ; (SINGLETON CONST7) ; NULL ; NULL))) ; NULL)) ; Y1) ("Subst=" (pos2121) (l2 la2))) (ltp () (CRULE-APPLICABLE (DER-ITEM-CRULE (DER-ITEM-CONSTR RES-START (singleton cost7) NULL NULL)) (APPEND (APPEND (DER-ITEM-INP (DER-ITEM-CONSTR RES-START (SINGLETON COST7) ;; Cost7 noch noch oben expabdieren in ;; die restlichen Zeilen NULL NULL)) (POSLIST2INFOLIST (DER-ITEM-PREMS (DER-ITEM-CONSTR RES-START (SINGLETON COST7) NULL NULL)) (CONS (DER-ITEM-CONSTR RES-START (SINGLETON CONST6) NULL NULL) (CONS (DER-ITEM-CONSTR RES-START (SINGLETON CONST7) NULL NULL) (CONS (DER-ITEM-CONSTR RES-RES EMPTY-CL (CONS (NUM2ITEM ZERO) (CONS (NUM2ITEM (S ZERO)) NULL)) (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) NULL))) NULL))))) (CONS (CL2ITEM (DER-ITEM-INFO (DER-ITEM-CONSTR RES-START (SINGLETON COST7) NULL NULL))) NULL)) Y1) ("Open"()())) ;; ("Subst="(pos22)(l1 la1))) ) (proc-content schema-interpreter) (remark "Method to simplify the eln-ind base-case.") ) (infer~defmethod eln-ind-bc2-3-m (outline-mappings (((existent nonexistent) eln-ind-bc2-3-m-b))) (help "Methode zur Vereinfachung des ELN-Ind-Schrittes.")) (meth~defmethod eln-ind-bc2-3-m-b eln-ind-bc2-3-m (in lock-res) (rating 30) (declarations (type-variables rr) (type-constants o i num form) (sorted-meta-variables ;;(meta-var type sort) (y1 (o (o form)) term) (const6 form term) (const7 form term) )) (parameters ) (premises (+ l1)) (application-condition ) (outline-actions ) (outline-orderings ) (outline-computations ;; (alist (mlist ru el pr inp)) ) (conclusions (- ltp)) (decl-content (l1 () (RESOLVABLE-B (SINGLETON CONST6) (SINGLETON CONST7) const6 const7 ) ("Open"()())) (ltp () (RESOLVABLE-B (INPUT-FIRST (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) (CONS (CL2ITEM (SINGLETON CONST6)) (CONS (CL2ITEM (SINGLETON CONST7)) (CONS (CL2ITEM EMPTY-CL) NULL)))))) (INPUT-SECOND (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) (CONS (CL2ITEM (SINGLETON CONST6)) (CONS (CL2ITEM (SINGLETON CONST7)) (CONS (CL2ITEM EMPTY-CL) NULL)))))) (INPUT-THIRD (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) (CONS (CL2ITEM (SINGLETON CONST6)) (CONS (CL2ITEM (SINGLETON CONST7)) (CONS (CL2ITEM EMPTY-CL) NULL)))))) (INPUT-FOURTH (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) (CONS (CL2ITEM (SINGLETON CONST6)) (CONS (CL2ITEM (SINGLETON CONST7)) (CONS (CL2ITEM EMPTY-CL) NULL))))))) ("Defni"()(l1))) ) (proc-content schema-interpreter) (remark "Method to simplify the eln-ind base-case.") ) (infer~defmethod eln-ind-bc2-4-m (outline-mappings (((existent nonexistent nonexistent nonexistent nonexistent) eln-ind-bc2-4-m-b))) (help "Methode zur Vereinfachung des ELN-Ind-Schrittes.")) (meth~defmethod eln-ind-bc2-4-m-b eln-ind-bc2-4-m (in lock-res) (rating 30) (declarations (type-variables rr) (type-constants o i num form) (sorted-meta-variables ;;(meta-var type sort) (y1 (o (o form)) term) (const6 form term) (const7 form term) (ru crule term) (el (o form) term) (pr glist term) (inp glist term) (pos211 o pos) (pos212 o pos) (pos21 o pos) (pos2 o pos) (alist o list) ) ) (parameters ) (premises (+ l8) (+ ax4) (+ ax5) (+ ax6)) (application-condition ) (outline-actions ) (outline-orderings ) (outline-computations ;; (alist (mlist ru el pr inp)) (pos2211 (:position (2 2 1 1))) (pos2212 (:position (2 2 1 2))) (pos22 (:position (2 2))) (pos2 (:position (2))) ) (conclusions (- ltp)) (decl-content (ax1 () (FORALL (lam (SEQ GLIST) (forall (lam (S (O (O FORM))) (= (CRULE-APPLICATION RES-RES SEQ S) (RESOLVENT-OF (INPUT-FIRST SEQ) (INPUT-SECOND SEQ) (INPUT-THIRD SEQ) (INPUT-FOURTH SEQ))))))) ("Axiom"()())) (ax2 () (forall (lam (ru crule) (forall (lam (el (o form)) (forall (lam (pr glist) (forall (lam (inp glist) (= (der-item-inp (der-item-constr ru el pr inp)) inp))))))))) ("Axiom"()())) (l3ax1 () (= (der-item-inp (der-item-constr RES-RES EMPTY-CL (CONS (NUM2ITEM ZERO) (CONS (NUM2ITEM (S ZERO)) NULL)) (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) NULL)))) (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) NULL)) ) ("ForallE*+"()(ax2))) (ax3 () (forall (lam (ru crule) (forall (lam (el (o form)) (forall (lam (pr glist) (forall (lam (inp glist) (= (der-item-prems (der-item-constr ru el pr inp)) pr))))))))) ("axion"()())) (l3ax3 () (= (der-item-prems (der-item-constr RES-RES EMPTY-CL (CONS (NUM2ITEM ZERO) (CONS (NUM2ITEM (S ZERO)) NULL)) (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) NULL)))) (CONS (NUM2ITEM ZERO) (CONS (NUM2ITEM (S ZERO)) NULL))) ("ForallE*+"()(ax3))) (ax4 () (= (POSLIST2INFOLIST (CONS (NUM2ITEM ZERO) (CONS (NUM2ITEM (S ZERO)) NULL)) (CONS (DER-ITEM-CONSTR RES-START (SINGLETON CONST6) NULL NULL) (CONS (DER-ITEM-CONSTR RES-START (SINGLETON CONST7) NULL NULL) (CONS (DER-ITEM-CONSTR RES-RES EMPTY-CL (CONS (NUM2ITEM ZERO) (CONS (NUM2ITEM (S ZERO)) NULL)) (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) NULL))) NULL)))) (cons (cl2item (SINGLETON CONST6)) (cons (cl2item (SINGLETON CONST7)) NULL))) ("Open"()())) (ax5 () (= (APPEND (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) NULL)) (cons (cl2item (SINGLETON CONST6)) (cons (cl2item (SINGLETON CONST7)) NULL))) (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) (cons (cl2item (SINGLETON CONST6)) (cons (cl2item (SINGLETON CONST7)) NULL)) ))) ("Open"()())) (ax6 () (= (APPEND (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) (cons (cl2item (SINGLETON CONST6)) (cons (cl2item (SINGLETON CONST7)) NULL)))) (CONS (CL2ITEM EMPTY-CL) NULL)) (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) (cons (cl2item (SINGLETON CONST6)) (cons (cl2item (SINGLETON CONST7)) (CONS (CL2ITEM EMPTY-CL) NULL)))))) ("Open"()())) (ax7 () (forall (lam (seq glist) (forall (lam (S (o (o form))) (= (crule-application res-res seq S) (resolvent-of (input-first seq) (input-second seq) (input-third seq) (input-fourth seq))))))) ("Axiom"()())) (l37 () (= (crule-application res-res (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) (cons (cl2item (SINGLETON CONST6)) (cons (cl2item (SINGLETON CONST7)) (CONS (CL2ITEM EMPTY-CL) NULL))))) Y1) (resolvent-of (input-first (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) (cons (cl2item (SINGLETON CONST6)) (cons (cl2item (SINGLETON CONST7)) (CONS (CL2ITEM EMPTY-CL) NULL)))))) (input-second (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) (cons (cl2item (SINGLETON CONST6)) (cons (cl2item (SINGLETON CONST7)) (CONS (CL2ITEM EMPTY-CL) NULL)))))) (input-third (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) (cons (cl2item (SINGLETON CONST6)) (cons (cl2item (SINGLETON CONST7)) (CONS (CL2ITEM EMPTY-CL) NULL)))))) (input-fourth (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) (cons (cl2item (SINGLETON CONST6)) (cons (cl2item (SINGLETON CONST7)) (CONS (CL2ITEM EMPTY-CL) NULL)))))))) ("ForallE*+"()(ax7))) (l8 () (= EMPTY-CL (that (lam (rk (o form)) (set= rk (setminus (setminus (union (singleton const6)(singleton const7)) (singleton const6)) (singleton const7)))))) ("Open"()())) ;; Dieser Zeilensprung ist abgekuerztz und falsch (von l6 nach l7) (l7 () (= EMPTY-CL (resolvent-of (singleton const6) (singleton const7) const6 const7 )) ("DefnI"(resolvemt-of)(l8))) (l6 () (= EMPTY-CL (resolvent-of (input-first (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) (cons (cl2item (SINGLETON CONST6)) (cons (cl2item (SINGLETON CONST7)) (CONS (CL2ITEM EMPTY-CL) NULL)))))) (input-second (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) (cons (cl2item (SINGLETON CONST6)) (cons (cl2item (SINGLETON CONST7)) (CONS (CL2ITEM EMPTY-CL) NULL)))))) (input-third (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) (cons (cl2item (SINGLETON CONST6)) (cons (cl2item (SINGLETON CONST7)) (CONS (CL2ITEM EMPTY-CL) NULL)))))) (input-fourth (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) (cons (cl2item (SINGLETON CONST6)) (cons (cl2item (SINGLETON CONST7)) (CONS (CL2ITEM EMPTY-CL) NULL)))))))) ("Foralle*+"()(l7))) (l5 () (= EMPTY-CL (CRULE-APPLICATION RES-RES (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) (cons (cl2item (SINGLETON CONST6)) (cons (cl2item (SINGLETON CONST7)) (CONS (CL2ITEM EMPTY-CL) NULL))))) Y1)) ("subst="(pos2)(l37 l6))) (l4 () (= EMPTY-CL (CRULE-APPLICATION RES-RES (APPEND (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) (cons (cl2item (SINGLETON CONST6)) (cons (cl2item (SINGLETON CONST7)) NULL)))) (CONS (CL2ITEM EMPTY-CL) NULL)) Y1)) ("subst=" (pos22) (l5 ax6))) (l3 () (= EMPTY-CL (CRULE-APPLICATION RES-RES (APPEND (APPEND (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) NULL)) (cons (cl2item (SINGLETON CONST6)) (cons (cl2item (SINGLETON CONST7)) NULL)) ) (CONS (CL2ITEM EMPTY-CL) NULL)) Y1)) ("Subst="(pos221)(ax5 l4))) (l2 () (= EMPTY-CL (CRULE-APPLICATION RES-RES (APPEND (APPEND (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) NULL)) (POSLIST2INFOLIST (CONS (NUM2ITEM ZERO) (CONS (NUM2ITEM (S ZERO)) NULL)) (CONS (DER-ITEM-CONSTR RES-START (SINGLETON CONST6) NULL NULL) (CONS (DER-ITEM-CONSTR RES-START (SINGLETON CONST7) NULL NULL) (CONS (DER-ITEM-CONSTR RES-RES EMPTY-CL (CONS (NUM2ITEM ZERO) (CONS (NUM2ITEM (S ZERO)) NULL)) (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) NULL))) NULL))))) (CONS (CL2ITEM EMPTY-CL) NULL)) Y1)) ("Subst=" (pos222) (ax4 l3))) (l1 () (= EMPTY-CL (CRULE-APPLICATION RES-RES (APPEND (APPEND (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) NULL)) (POSLIST2INFOLIST (DER-ITEM-PREMS (DER-ITEM-CONSTR RES-RES EMPTY-CL (CONS (NUM2ITEM ZERO) (CONS (NUM2ITEM (S ZERO)) NULL)) (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) NULL)))) (CONS (DER-ITEM-CONSTR RES-START (SINGLETON CONST6) NULL NULL) (CONS (DER-ITEM-CONSTR RES-START (SINGLETON CONST7) NULL NULL) (CONS (DER-ITEM-CONSTR RES-RES EMPTY-CL (CONS (NUM2ITEM ZERO) (CONS (NUM2ITEM (S ZERO)) NULL)) (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) NULL))) NULL))))) (CONS (CL2ITEM EMPTY-CL) NULL)) Y1)) ("subst="(pos22121) (l3ax3 l2))) (ltp () (= EMPTY-CL (CRULE-APPLICATION ;;RES-RES (DER-ITEM-CRULE (DER-ITEM-CONSTR RES-RES EMPTY-CL (CONS (NUM2ITEM ZERO) (CONS (NUM2ITEM (S ZERO)) NULL)) (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) NULL)))) (APPEND (APPEND (DER-ITEM-INP (DER-ITEM-CONSTR RES-RES EMPTY-CL (CONS (NUM2ITEM ZERO) (CONS (NUM2ITEM (S ZERO)) NULL)) (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) NULL)))) (POSLIST2INFOLIST (DER-ITEM-PREMS (DER-ITEM-CONSTR RES-RES EMPTY-CL (CONS (NUM2ITEM ZERO) (CONS (NUM2ITEM (S ZERO)) NULL)) (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) NULL)))) (CONS (DER-ITEM-CONSTR RES-START (SINGLETON CONST6) NULL NULL) (CONS (DER-ITEM-CONSTR RES-START (SINGLETON CONST7) NULL NULL) (CONS (DER-ITEM-CONSTR RES-RES EMPTY-CL (CONS (NUM2ITEM ZERO) (CONS (NUM2ITEM (S ZERO)) NULL)) (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) NULL))) NULL))))) (CONS (CL2ITEM EMPTY-CL) NULL)) Y1)) ("Subst=" (pos2211)(l3ax1 l1))) ) (proc-content schema-interpreter) (remark "Method to simplify the eln-ind base-case.") ) (infer~defmethod eln-ind-bc2-5-m (outline-mappings (((existent nonexistent nonexistent nonexistent nonexistent) eln-ind-bc2-5-m-b))) (help "Methode zur Vereinfachung des ELN-Ind-Schrittes.")) (meth~defmethod eln-ind-bc2-5-m-b eln-ind-bc2-5-m (in lock-res) (rating 30) (declarations (type-variables rr) (type-constants o i num form) (sorted-meta-variables ;;(meta-var type sort) (y1 (o (o form)) term) (const6 form term) (const7 form term) (cost7 form term) (ru crule term) (el (o form) term) (pr glist term) (inp glist term) (pos211 o pos) (pos212 o pos) (pos21 o pos) (pos2 o pos) (alist o list) )) (parameters ) (premises (+ l8) (+ la3) (+ la4) (+ la5)) (application-condition ) (outline-actions ) (outline-orderings ) (outline-computations ;; (alist (mlist ru el pr inp)) (pos2211 (:position (2 2 1 1))) (pos2212 (:position (2 2 1 2))) (pos22 (:position (2 2))) (pos2 (:position (2))) ) (conclusions (- ltp)) (decl-content (ax1 () (forall (lam (ru crule) (forall (lam (el (o form)) (forall (lam (pr glist) (forall (lam (inp glist) (= (der-item-inp (der-item-constr ru el pr inp)) inp))))))))) ("Axiom" ()())) (la1 () (= (der-item-inp (der-item-constr res-start (singleton const7) NULL NULL)) NULL) ("ForallE*+"()(ax1))) (ax2 () (forall (lam (ru crule) (forall (lam (el (o form)) (forall (lam (pr glist) (forall (lam (inp glist) (= (der-item-prems (der-item-constr ru el pr inp)) pr))))))))) ("Axiom"()())) (la2 () (= (der-item-prems (der-item-constr res-start (singleton const7) NULL NULL)) NULL) ("ForallE*+"()(ax2))) (la3 () (= (POSLIST2INFOLIST NULL (CONS (DER-ITEM-CONSTR RES-START (SINGLETON CONST6) NULL NULL) (CONS (DER-ITEM-CONSTR RES-START (SINGLETON CONST7) NULL NULL) (CONS (DER-ITEM-CONSTR RES-RES EMPTY-CL (CONS (NUM2ITEM ZERO) (CONS (NUM2ITEM (S ZERO)) NULL)) (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) NULL))) NULL)))) NULL) ("Open"()())) (la4 () (= (append NULL NULL) NULL) ("Open"()())) (la5 () (= (APPEND NULL (CONS (CL2ITEM (SINGLETON CONST7)) NULL)) (CONS (CL2ITEM (SINGLETON CONST7)) NULL)) ("Open"()())) (ax6 () (forall (lam (seq glist) (forall (lam (S (o (o form))) (= (crule-application res-start seq S) (item2cl (first seq))))))) ("Axiom"()())) (la6 () (= (crule-application res-start (CONS (CL2ITEM (SINGLETON CONST7)) NULL) y1) (item2cl (first (CONS (CL2ITEM (SINGLETON CONST7)) NULL)))) ("ForallE*+"()(ax6))) (ax7 () (forall (lam (x item) (forall (lam (L glist) (= (first (cons x L)) x))))) ("Axiom"()())) (la7 () (= (first (cons (CL2ITEM (SINGLETON CONST7)) NULL)) (CL2ITEM (SINGLETON CONST7))) ("ForallE*+" () (ax7))) (ax8 () (forall (lam (akl (o form)) (= (item2cl (cl2item akl)) akl))) ("Axiom"()())) (la8 () (= (item2cl (cl2item (SINGLETON CONST7))) (SINGLETON CONST7)) ("Foralle*+" ()(ax8))) (l8 () (= (SINGLETON COST7) (SINGLETON COST7)) ("Open"()())) (l7 () (= (SINGLETON CONST7) (item2cl (CL2ITEM (SINGLETON CONST7)))) ("Subst=" (pos2)(l8 la8))) (l6 () (= (SINGLETON CONST7) (item2cl (first (CONS (CL2ITEM (SINGLETON CONST7)) NULL)))) ("Subst=" (pos21) (l7 la7))) (l5 () (= (SINGLETON CONST7) (CRULE-APPLICATION RES-START (CONS (CL2ITEM (SINGLETON CONST7)) NULL) Y1)) ("Subst=" (pos2) (l6 la6))) (l4 () (= (SINGLETON CONST7) (CRULE-APPLICATION RES-START (APPEND NULL (CONS (CL2ITEM (SINGLETON CONST7)) NULL)) Y1)) ("Subst=" (pos22) (l5 la5))) (l3 () (= (SINGLETON CONST7) (CRULE-APPLICATION RES-START (APPEND (APPEND NULL NULL) (CONS (CL2ITEM (SINGLETON CONST7)) NULL)) Y1)) ("Subst=" (pos221) (l4 la4))) (l2 () (= (SINGLETON CONST7) (CRULE-APPLICATION RES-START (APPEND (APPEND NULL (POSLIST2INFOLIST NULL (CONS (DER-ITEM-CONSTR RES-START (SINGLETON CONST6) NULL NULL) (CONS (DER-ITEM-CONSTR RES-START (SINGLETON CONST7) NULL NULL) (CONS (DER-ITEM-CONSTR RES-RES EMPTY-CL (CONS (NUM2ITEM ZERO) (CONS (NUM2ITEM (S ZERO)) NULL)) (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) NULL))) NULL))))) (CONS (CL2ITEM (SINGLETON CONST7)) NULL)) Y1)) ("Subst=" (pos2212) (l3 la3))) (l1 () (= (SINGLETON CONST7) (CRULE-APPLICATION RES-START (APPEND (APPEND NULL (POSLIST2INFOLIST (DER-ITEM-PREMS (DER-ITEM-CONSTR RES-START (SINGLETON CONST7) NULL NULL)) (CONS (DER-ITEM-CONSTR RES-START (SINGLETON CONST6) NULL NULL) (CONS (DER-ITEM-CONSTR RES-START (SINGLETON CONST7) NULL NULL) (CONS (DER-ITEM-CONSTR RES-RES EMPTY-CL (CONS (NUM2ITEM ZERO) (CONS (NUM2ITEM (S ZERO)) NULL)) (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) NULL))) NULL))))) (CONS (CL2ITEM (SINGLETON CONST7)) NULL)) Y1)) ("Subst="(pos22121)(l2 la2))) (ltp () (= (SINGLETON COST7) (CRULE-APPLICATION (DER-ITEM-CRULE (DER-ITEM-CONSTR RES-START (singleton cost7) NULL NULL)) (APPEND (APPEND (DER-ITEM-INP (DER-ITEM-CONSTR RES-START (SINGLETON COST7) NULL NULL)) (POSLIST2INFOLIST (DER-ITEM-PREMS (DER-ITEM-CONSTR RES-START (SINGLETON COST7) NULL NULL)) (CONS (DER-ITEM-CONSTR RES-START (SINGLETON CONST6) NULL NULL) (CONS (DER-ITEM-CONSTR RES-START (SINGLETON CONST7) NULL NULL) (CONS (DER-ITEM-CONSTR RES-RES EMPTY-CL (CONS (NUM2ITEM ZERO) (CONS (NUM2ITEM (S ZERO)) NULL)) (CONS (FORM2ITEM CONST6) (CONS (FORM2ITEM CONST7) NULL))) NULL))))) (CONS (CL2ITEM (SINGLETON COST7)) NULL)) Y1))("Subst=" (pos2211)(l1 la1))) ) (proc-content schema-interpreter) (remark "Method to simplify the eln-ind base-case.") ) (infer~defmethod eln-ind-bc2-m (outline-mappings (((existent nonexistent nonexistent) eln-ind-bc2-m-b))) (help "Methode zur Vereinfachung des ELN-Ind-Schrittes.")) (meth~defmethod eln-ind-bc2-m-b eln-ind-bc2-m (in lock-res) (rating 30) (declarations (type-variables rr) (type-constants o i num form) (constants (dum-cl-set (o (o form)))) (sorted-meta-variables ;;(meta-var type sort) (y1 (o (o form)) term) (cl1 form term) (cl2 form term) )) (parameters ) (premises (+ ng1) (+ l3)) (application-condition ) (outline-actions (l3 (sponsor l14)) ) (outline-orderings ) (outline-computations (cl1 (type-newconst (:type form))) (cl2 (type-newconst (:type form))) (term (:term (cons (der-item-constr res-start (singleton cl1) NULL NULL) (cons (der-item-constr res-start (singleton cl2) NULL NULL) (cons (der-item-constr res-res empty-cl (cons (num2item zero) (cons (num2item (s zero)) NULL)) (cons (form2item cl1) (cons (form2item cl2) NULL))) NULL))))) ) (conclusions (- ltp)) (decl-content (h1 () (AND (FORALL (lam (X (O FORM)) (IMPLIES (IN X Y1) (SETUNIT X)))) (UNSAT-CL-SET Y1)) ) (ng1 () (exists (lam (l1 form) (exists (lam (l2 form) (and (and (y1 (singleton l1)) (y1 (singleton l2))) (com-pair l1 l2)))))) ("Open"()())) (l15 () (exists (lam (l2 form) (and (and (y1 (singleton cl1)) (y1 (singleton l2))) (com-pair cl1 l2)))) ("Hyp"()())) (l14 () (and (and (y1 (singleton cl1)) (y1 (singleton cl2))) (com-pair cl1 cl2)) ("Hyp"()())) (l3 (l14) (DERIVATION-OF Y1 CRULE-SET (cons (der-item-constr res-start (singleton cl1) NULL NULL) (cons (der-item-constr res-start (singleton cl2) NULL NULL) (cons (der-item-constr res-res empty-cl (cons (num2item zero) (cons (num2item (s zero)) NULL)) (cons (form2item cl1) (cons (form2item cl2) NULL))) NULL))) EMPTY-CL) ("Open"()())) (l2 (l15 l14) (EXISTS (lam (dc-308 glist) (DERIVATION-OF Y1 CRULE-SET DC-308 EMPTY-CL))) ("ExistsI" (term) (l3))) (l1 (l15) (EXISTS (lam (dc-308 glist) (DERIVATION-OF Y1 CRULE-SET DC-308 EMPTY-CL))) ("ExistsE"(cl2)(l2 l15))) ;; -------------------------------------------------------------------- (ltp () (EXISTS (lam (dc-308 glist) (DERIVATION-OF Y1 CRULE-SET DC-308 EMPTY-CL) )) ("ExistsE" (cl1) (l1 ng1))) ) (proc-content schema-interpreter) (remark "Proof, that y ist last Element of an list.") ) ;; ======================================================================= ;; ;; DISJUNCTION LEMMA METODEN ;; ;; ======================================================================= (infer~defmethod disj-ind (outline-mappings (((existent existent nonexistent nonexistent nonexistent nonexistent nonexistent nonexistent nonexistent ) disj-ind-m-b))) (help "Methode zur Nutzung der Menge K1")) (meth~defmethod disjl-ind-m-b disj-ind (in lock-res) (rating 30) (reasoning :planning) (declarations (constants ) (sorted-meta-variables (co8 (o form) term) (co9 (o (o form)) term) (dc43 glist term) (cx12 num term) (lastdc43 item term) (sL glist term) (li1 form term) (li2 form term) (ih1-seq glist term) (ih2-seq glist term) (somenum num term) (numc1 num term) (numc2 num term) (aseq1 glist term) (aseq2 glist term) ) ) (parameters ) (premises (- h0) (+ l122) ;; Trivialfall: co8 ist in co9 (+ l53) (+ l61) (+ l82) (+ l96) (+ as7) (+ as8) ;; Anschluss an die Induktionsvoraussetzung eigentlich ;; auch as5 und as6 ) (application-condition ) (outline-actions (l122 (sponsor l30)) ; (l61 (sponsor n20)) (l61 (sponsor n3)) (l61 (sponsor l67)) (l61 (sponsor l68)) (l61 (sponsor l69)) ; (l53 (sponsor n21)) (l53 (sponsor n3)) (l53 (sponsor l57)) (l53 (sponsor l59)) (l53 (sponsor l69)) ; (l82 (sponsor n22)) (l82 (sponsor n3)) (l82 (sponsor l93)) (l82 (sponsor l94)) (l82 (sponsor l110)) ; (l96 (sponsor n23)) (l96 (sponsor n3)) (l96 (sponsor l108)) (l96 (sponsor l109)) (l96 (sponsor l110)) ; (as7 (sponsor as3)) (as7 (sponsor as5)) ; (as8 (sponsor as4)) (as8 (sponsor as6)) ) (outline-orderings (before l53 l61) (before l61 l82) (before l82 l96) (before l96 l122) (before l122 as7) (before as7 as8) ) (outline-computations (lastdc43 (:term (last dc43))) (sL (type-newconst (:type glist))) (numc1 (type-newconst (:type num))) (numc2 (type-newconst (:type num))) (li1 (type-newconst (:type form))) (li2 (type-newconst (:type form))) (co8 (type-newconst (:type (o form)))) (aseq1 (type-newconst (:type glist))) (aseq2 (type-newconst (:type glist))) (ih1-seq (type-newconst (:type glist))) (ih2-seq (type-newconst (:type glist))) ) (conclusions (- ltp)) (decl-content (h0 () (greater cx12 somenum) ) (h1 () (= (minus (glist-length dc43) one) cx12) ("Hyp"()())) (h2 () (derivation-of (union (setminus co9 (singleton (good-clause co9))) (singleton (setminus (good-clause co9) (singleton (good-literal (good-clause co9)))))) crule-set dc43 co8) ("Hyp"()())) (n1 () (or (and (and (less numc1 cx12) (less numc2 cx12)) (= dc43 (append sL (cons (der-item-constr res-res co8 (cons (form2item li1) (cons (form2item li2) NULL)) (cons (num2item numc1) (cons (num2item numc2) NULL))) NULL)))) (= dc43 (append sL (cons (der-item-constr res-start co8 NULL NULL) NULL)))) ("abstract"()())) (n20 () (resolvable-b (der-item-info (glist-nth numc1 dc43)) (der-item-info (glist-nth numc2 dc43)) li1 li2) ("abstract" ()())) (n21 () (resolvable-b (der-item-info (glist-nth numc1 dc43)) (der-item-info (glist-nth numc2 dc43)) li1 li2) ("abstract" ()())) (n22 () (resolvable-b (der-item-info (glist-nth numc1 dc43)) (der-item-info (glist-nth numc2 dc43)) li1 li2) ("abstract" ()())) (n23 () (resolvable-b (der-item-info (glist-nth numc1 dc43)) (der-item-info (glist-nth numc2 dc43)) li1 li2) ("abstract" ()())) (n3 () (= co8 (resolvent-of (der-item-info (glist-nth numc1 dc43)) (der-item-info (glist-nth numc2 dc43)) li1 li2)) ("abstract" ()())) ;; ---------------------------------------------------------------------------- ;; K1 leitet co8 mit Hilfe der Startregel ab und ist deshalb kein ;; Trivialfall: h4 zeigt die struktur von dc43 diese wird aufgeloest in ;; der as-Zeilen (h4 () (and (and (less numc1 cx12) (less numc2 cx12)) (= dc43 (append sL (cons (der-item-constr res-res co8 (cons (form2item li1) (cons (form2item li2) NULL)) (cons (num2item numc1) (cons (num2item numc2) NULL))) NULL)))) ("Hyp"()())) (as1 () (and (less numc1 cx12) (less numc2 cx12)) ("AndEL" ()(h4))) (as2 () (= dc43 (append sL (cons (der-item-constr res-res co8 (cons (form2item li1) (cons (form2item li2) NULL)) (cons (num2item numc1) (cons (num2item numc2) NULL))) NULL))) ("AndER" ()(h4))) (as3 () (less numc1 cx12) ("AndEL"()(as1))) (as4 () (less numc2 cx12) ("AndER"()(as1))) ;; ih1/2-seq wird durch (prefix numc1/2 dc43) ersetzt (in as5/6) ;; dann ist auch das abstract in ordnung (as5 () (and (less (minus (glist-length ih1-seq) one) cx12) (derivation-of (union (setminus co9 (singleton (good-clause co9))) (singleton (setminus (good-clause co9) (singleton (good-literal (good-clause co9)))))) crule-set ih1-seq (der-item-info (glist-nth numc1 dc43)))) ("abstract"()())) (as6 () (and (less (minus (glist-length ih2-seq) one) cx12) (derivation-of (union (setminus co9 (singleton (good-clause co9))) (singleton (setminus (good-clause co9) (singleton (good-literal (good-clause co9)))))) crule-set ih2-seq (der-item-info (glist-nth numc2 dc43)))) ("abstract"()())) (as7 (as5 as3) (or (derivable (der-item-info (glist-nth numc1 dc43)) co9 crule-set) (derivable (union (der-item-info (glist-nth numc1 dc43)) (singleton (good-literal (good-clause co9)))) co9 crule-set)) ("Open"()())) (as8 (as6 as4) (or (derivable (der-item-info (glist-nth numc2 dc43)) co9 crule-set) (derivable (union (der-item-info (glist-nth numc2 dc43)) (singleton (good-literal (good-clause co9)))) co9 crule-set)) ("Open"()())) ;; ===================================================================================== (l110 () (derivable (union (der-item-info (glist-nth numc2 dc43)) (singleton (good-literal (good-clause co9)))) co9 crule-set) ("Hyp"()())) (l109 () (derivable (union (der-item-info (glist-nth numc1 dc43)) (singleton (good-literal (good-clause co9)))) co9 crule-set) ("Hyp"()())) (l108 () (resolvable-s (union (der-item-info (glist-nth numc2 dc43)) (singleton (good-literal (good-clause co9)))) (union (der-item-info (glist-nth numc1 dc43)) (singleton (good-literal (good-clause co9)))) ) ("Hyp"()())) (l96 (h1 h2 h4 n23 n3 l110 l109 l108) (derivable (union co8 (singleton (good-literal (good-clause co9)))) co9 crule-set) ("Open"()())) ; (l95 (h1 h2 h4 l110 l109) (or (derivable co8 co9 crule-set) ; (derivable (union co8 ; (singleton (good-literal (good-clause co9)))) ; co9 crule-set)) ("OrIR" ()(l96))) ; ; ;; ------------------------------------- (l94 () (derivable (der-item-info (glist-nth numc1 dc43)) co9 crule-set) ("Hyp" ()())) (l93 () (resolvable-s (der-item-info (glist-nth numc1 dc43)) (union (der-item-info (glist-nth numc2 dc43)) (singleton (good-literal (good-clause co9))))) ("hyp"()())) (l82 (h1 h2 h4 n22 n3 l110 l94 l93) (derivable (union co8 (singleton (good-literal (good-clause co9)))) co9 crule-set) ("Open"()())) ; (l81 (h1 h2 h4 l110 l94) (or (derivable co8 co9 crule-set) ; (derivable (union co8 ; (singleton (good-literal (good-clause co9)))) ; co9 crule-set)) ("OrIR"()(l82))) ; ; (l80 (h1 h2 h4 l110) (or (derivable co8 co9 crule-set) ; (derivable (union co8 ; (singleton (good-literal (good-clause co9)))) ; co9 crule-set)) ("OrE"()(as7 l81 l95))) ; ; ;; =================== (l69 () (derivable (der-item-info (glist-nth numc2 dc43)) co9 crule-set) ("Hyp"()())) (l68 () (derivable (union (der-item-info (glist-nth numc1 dc43)) (singleton (good-literal (good-clause co9)))) co9 crule-set) ("Hyp"()())) (l67 () (resolvable-s (der-item-info (glist-nth numc2 dc43)) (union (der-item-info (glist-nth numc1 dc43)) (singleton (good-literal (good-clause co9))))) ("Hyp"()())) (l61 (h1 h2 h4 n20 n3 l69 l68 l67) (derivable (union co8 (singleton (good-literal (good-clause co9)))) co9 crule-set) ("Open"()())) ; (l60 (h1 h2 h4 l69 l68) (or (derivable co8 co9 crule-set) ; (derivable (union co8 ; (singleton (good-literal (good-clause co9)))) ; co9 crule-set)) ("OrIR"()(l61))) ; ;; -------------------------- (l59 () (derivable (der-item-info (glist-nth numc1 dc43)) co9 crule-set) ("Hyp"()())) (l57 () (resolvable-s (der-item-info (glist-nth numc2 dc43)) (der-item-info (glist-nth numc1 dc43)) ) ("Hyp"()())) (l53 (h1 h2 h4 n21 n3 l69 l59 l57) (derivable co8 co9 crule-set) ("Open"()())) ; (l52 (h1 h2 h4 l69 l59) (or (derivable co8 co9 crule-set) ; (derivable (union co8 ; (singleton (good-literal (good-clause co9)))) ; co9 crule-set)) ("OrIL"()(l53))) ; ; (l51 (h1 h2 h4 l69) (or (derivable co8 co9 crule-set) ; (derivable (union co8 ; (singleton (good-literal (good-clause co9)))) ; co9 crule-set)) ("OrE"()(as7 l52 l60))) ; ; ;; co8 wurde aus K1 mit Hilfe der resolutionsregel abgeleitet. (l50 (h1 h2 h4) (or (derivable co8 co9 crule-set) (derivable (union co8 (singleton (good-literal (good-clause co9)))) co9 crule-set)) ("OrE"()(as8 l51 l80))) ;; T R I V I A L F A L L T E I L B E W E I S ;; ============================================= (h3 () (= dc43 (append sL (cons (der-item-constr res-start co8 NULL NULL) NULL))) ("Hyp"()())) (l5 () (and (= (der-item-info (last dc43)) co8) (derivation (union (setminus co9 (singleton (good-clause co9))) (singleton (setminus (good-clause co9) (singleton (good-literal (good-clause co9)))))) crule-set dc43)) ("DefnE" (derivation-of) (h2))) (l6 () (derivation (union (setminus co9 (singleton (good-clause co9))) (singleton (setminus (good-clause co9) (singleton (good-literal (good-clause co9)))))) crule-set dc43) ("AndER"()(l5))) (l7 () (forall (lam (x item) (implies (is-component x dc43) (and (free-derivation-cond dc43) (and (and (crule-set (der-item-crule x)) (crule-applicable (der-item-crule x) (append (append (der-item-inp x) (poslist2infolist (der-item-prems x) dc43)) (cons (cl2item (der-item-info x)) NULL)) (union (setminus co9 (singleton (good-clause co9))) (singleton (setminus (good-clause co9) (singleton (good-literal (good-clause co9)))))))) (and (forall (lam (y num) (implies (is-component (num2item y) (der-item-prems x)) (less y (position x dc43))))) (= (der-item-info x) (crule-application (der-item-crule x) (append (append (der-item-inp x) (poslist2infolist (der-item-prems x) dc43)) (cons (cl2item (der-item-info x)) NULL)) (union (setminus co9 (singleton (good-clause co9))) (singleton (setminus (good-clause co9) (singleton (good-literal (good-clause co9)))))))))))))) ("DefnE" (derivation) (l6))) (l8 () (implies (is-component lastdc43 dc43) (and (free-derivation-cond dc43) (and (and (crule-set (der-item-crule lastdc43)) (crule-applicable (der-item-crule lastdc43) (append (append (der-item-inp lastdc43) (poslist2infolist (der-item-prems lastdc43) dc43)) (cons (cl2item (der-item-info lastdc43)) NULL)) (union (setminus co9 (singleton (good-clause co9))) (singleton (setminus (good-clause co9) (singleton (good-literal (good-clause co9)))))))) (and (forall (lam (y num) (implies (is-component (num2item y) (der-item-prems lastdc43)) (less y (position lastdc43 dc43))))) (= (der-item-info lastdc43) (crule-application (der-item-crule lastdc43) (append (append (der-item-inp lastdc43) (poslist2infolist (der-item-prems lastdc43) dc43)) (cons (cl2item (der-item-info lastdc43)) NULL)) (union (setminus co9 (singleton (good-clause co9))) (singleton (setminus (good-clause co9) (singleton (good-literal (good-clause co9)))))))))))) ("ForallE" (lastdc43) (l7))) (l9 () (is-component (last dc43) dc43) ("abstract"()())) (l10 () (and (free-derivation-cond dc43) (and (and (crule-set (der-item-crule lastdc43)) (crule-applicable (der-item-crule lastdc43) (append (append (der-item-inp lastdc43) (poslist2infolist (der-item-prems lastdc43) dc43)) (cons (cl2item (der-item-info lastdc43)) NULL)) (union (setminus co9 (singleton (good-clause co9))) (singleton (setminus (good-clause co9) (singleton (good-literal (good-clause co9)))))))) (and (forall (lam (y num) (implies (is-component (num2item y) (der-item-prems lastdc43)) (less y (position lastdc43 dc43))))) (= (der-item-info lastdc43) (crule-application (der-item-crule lastdc43) (append (append (der-item-inp lastdc43) (poslist2infolist (der-item-prems lastdc43) dc43)) (cons (cl2item (der-item-info lastdc43)) NULL)) (union (setminus co9 (singleton (good-clause co9))) (singleton (setminus (good-clause co9) (singleton (good-literal (good-clause co9))))))))))) ("ImpE" ()(l8 l9))) (l11 () (and (and (crule-set (der-item-crule lastdc43)) (crule-applicable (der-item-crule lastdc43) (append (append (der-item-inp lastdc43) (poslist2infolist (der-item-prems lastdc43) dc43)) (cons (cl2item (der-item-info lastdc43)) NULL)) (union (setminus co9 (singleton (good-clause co9))) (singleton (setminus (good-clause co9) (singleton (good-literal (good-clause co9)))))))) (and (forall (lam (y num) (implies (is-component (num2item y) (der-item-prems lastdc43)) (less y (position lastdc43 dc43))))) (= (der-item-info lastdc43) (crule-application (der-item-crule lastdc43) (append (append (der-item-inp lastdc43) (poslist2infolist (der-item-prems lastdc43) dc43)) (cons (cl2item (der-item-info lastdc43)) NULL)) (union (setminus co9 (singleton (good-clause co9))) (singleton (setminus (good-clause co9) (singleton (good-literal (good-clause co9)))))))))) ("AndER"() (l10))) (l12 () (and (crule-set (der-item-crule lastdc43)) (crule-applicable (der-item-crule lastdc43) (append (append (der-item-inp lastdc43) (poslist2infolist (der-item-prems lastdc43) dc43)) (cons (cl2item (der-item-info lastdc43)) NULL)) (union (setminus co9 (singleton (good-clause co9))) (singleton (setminus (good-clause co9) (singleton (good-literal (good-clause co9)))))))) ("AndEL" ()(l11))) (l13 () (crule-applicable (der-item-crule lastdc43) (append (append (der-item-inp lastdc43) (poslist2infolist (der-item-prems lastdc43) dc43)) (cons (cl2item (der-item-info lastdc43)) NULL)) (union (setminus co9 (singleton (good-clause co9))) (singleton (setminus (good-clause co9) (singleton (good-literal (good-clause co9))))))) ("AndER" ()(l12))) ; (l16 () (= (der-item-inp (last dc43)) ; NULL) ("abstract"()())) ; ;; Diesen Teilbeweis noch innerhalb dieser Methode expandieren ; ; (l17 () (crule-applicable res-start ; (append (append ; NULL ; (poslist2infolist (der-item-prems (last dc43)) dc43)) ; (cons (cl2item (der-item-info (last dc43))) ; NULL)) ; (union (setminus co9 (singleton (good-clause co9))) ; (singleton ; (setminus (good-clause co9) ; (singleton (good-literal ; (good-clause co9))))))) ; ("Subst=" (apos2) (l16 l15))) ; ; (l18 () (= (poslist2infolist (der-item-prems (last dc43)) dc43) ; NULL) ("abstract"()())) ; ; (l19 () (crule-applicable res-start ; (append (append NULL NULL) ; (cons (cl2item (der-item-info (last dc43))) ; NULL)) ; (union (setminus co9 (singleton (good-clause co9))) ; (singleton ; (setminus (good-clause co9) ; (singleton (good-literal ; (good-clause co9))))))) ; ("Subst=" (apos3) (l18 l17))) ; ; (l20 () (= (append NULL NULL) NULL) ("abstract"()())) ; ; (l21 () (crule-applicable res-start ; (append NULL ; (cons (cl2item (der-item-info (last dc43))) ; NULL)) ; (union (setminus co9 (singleton (good-clause co9))) ; (singleton ; (setminus (good-clause co9) ; (singleton (good-literal ; (good-clause co9))))))) ; ("Subst=" (apos4)(l20 l19))) ; ; (l22 () (= (der-item-info (last dc43)) co8) ("abstract"()())) ; ; (l23 () (crule-applicable res-start ; (append NULL (cons (cl2item co8) NULL)) ; (union (setminus co9 (singleton (good-clause co9))) ; (singleton ; (setminus (good-clause co9) ; (singleton (good-literal ; (good-clause co9))))))) ; ("Subst=" (apos5) (l22 l21))) ; ; (l24 () (= (append NULL (cons (cl2item co8) NULL)) (cons (cl2item co8) NULL)) ("abstract"()())) ; ; (l25 () (crule-applicable res-start ; (cons (cl2item co8) NULL) ; (union (setminus co9 (singleton (good-clause co9))) ; (singleton ; (setminus (good-clause co9) ; (singleton (good-literal ; (good-clause co9))))))) ; ("Subst=" (apos6) (l24 l23))) ; ; (lb1 () (forall (lam (seq glist) (forall (lam (S (o (o form))) ; (equiv (crule-applicable res-start seq S) ; (in (item2cl (first seq)) S)))))) ("Axiom"()())) ; ; (lb2 () (forall (lam (S (o (o form))) ; (equiv (crule-applicable res-start ; (cons (cl2item co8) NULL)S) ; (in (item2cl (first (cons (cl2item co8) NULL))) S)))) ("ForallE"(bterm1)(lb1))) ; ; (lb3 () (equiv (crule-applicable res-start ; (cons (cl2item co8) NULL) ; (union (setminus co9 (singleton (good-clause co9))) ; (singleton ; (setminus (good-clause co9) ; (singleton (good-literal ; (good-clause co9))))))) ; (in (item2cl (first (cons (cl2item co8) NULL))) ; (union (setminus co9 (singleton (good-clause co9))) ; (singleton ; (setminus (good-clause co9) ; (singleton (good-literal ; (good-clause co9)))))))) ; ("ForallE" (bterm2) (lb2))) ; ; (l26 () (implies (crule-applicable res-start ; (cons (cl2item co8) NULL) ; (union (setminus co9 (singleton (good-clause co9))) ; (singleton ; (setminus (good-clause co9) ; (singleton (good-literal ; (good-clause co9))))))) ; (in (item2cl (first (cons (cl2item co8) NULL))) ; (union (setminus co9 (singleton (good-clause co9))) ; (singleton ; (setminus (good-clause co9) ; (singleton (good-literal ; (good-clause co9)))))))) ; ("EquivEL"()(lb3))) ; ; (l27 () (in (item2cl (first (cons (cl2item co8) NULL))) ; (union (setminus co9 (singleton (good-clause co9))) ; (singleton ; (setminus (good-clause co9) ; (singleton (good-literal ; (good-clause co9))))))) ; ("ImpE"()(l26 l25))) ; ; (l28 () (= (item2cl (first (cons (cl2item co8) NULL))) ; co8) ("abstract"()())) ; (l29 () (in co8 (union (setminus co9 (singleton (good-clause co9))) (singleton (setminus (good-clause co9) (singleton (good-literal (good-clause co9))))))) ("Open"()())) ;; ("subst=" (apos7)(l28 l27))) ;; dieses Ziel ist expandierbar (l30 () (co9 co8) ("abstract"()())) ;; Dieses Ziel ist loesbar mit Zeile l30 analog dem Induktionsanfang. (l122 (h1 h2 h3 l11 l30) (derivable co8 co9 crule-set) ("Open"()())) ; ; (l4 (h1 h2 h3) (derivable co8 co9 crule-set) ("ExistsE" (res-start) (l122 l10))) ; ; (l3 (h1 h2 h3) (or (derivable co8 co9 crule-set) ; (derivable (union co8 ; (singleton (good-literal (good-clause co9)))) ; co9 crule-set)) ("OrIL"()(l4))) ;; =============================================================================== ;; Aufspaltung in Trivialfall und Resolutionsfall mit Hilfe der Zeile n1 ;; ganz oben. Man unterscheidet ob co8 aus K1 mit der Startregel oder der ;; Resolutionsregel erzeugt wurde. (l2 (h1 h2) (or (derivable co8 co9 crule-set) (derivable (union co8 (singleton (good-literal (good-clause co9)))) co9 crule-set)) ("Abstract"()()) ;; ("OrE" ()(n1 l3 l50)) ) (l1z (h1) (implies (derivation-of (union (setminus co9 (singleton (good-clause co9))) (singleton (setminus (good-clause co9) (singleton (good-literal (good-clause co9)))))) crule-set dc43 co8) (or (derivable co8 co9 crule-set) (derivable (union co8 (singleton (good-literal (good-clause co9)))) co9 crule-set))) ("ImpI"()(l2))) (l1 (h1) (forall (lam (co8x (o form)) (implies (derivation-of (union (setminus co9 (singleton (good-clause co9))) (singleton (setminus (good-clause co9) (singleton (good-literal (good-clause co9)))))) crule-set dc43 co8x) (or (derivable co8x co9 crule-set) (derivable (union co8x (singleton (good-literal (good-clause co9)))) co9 crule-set))))) ("ForallI" (co8x) (l1z))) ;; Diese Zeile behauptet: ;; WENN aus K1 in n Schritten mittels der Ableitung dc43 die Klausel c8 ;; ableitbar ist, ;; DANN ist co8x oder co8x+li aus K ableitbar, wobei K = co9 ist. ;; Bis l2 werden die implicationen standardmaessig aufgeloest. (ltp () (implies (= (minus (glist-length dc43) one) cx12) (forall (lam (co8x (o form)) (implies (derivation-of (union (setminus co9 (singleton (good-clause co9))) (singleton (setminus (good-clause co9) (singleton (good-literal (good-clause co9)))))) crule-set dc43 co8x) (or (derivable co8x co9 crule-set) (derivable (union co8x (singleton (good-literal (good-clause co9)))) co9 crule-set)))))) ("ImpI"()(l1))) ) (proc-content schema-interpreter) (remark "Proof the step case of an eln-induction-step with help of k1 and k2.") ) (infer~defmethod dsjk-base (outline-mappings (((existent existent existent existent nonexistent nonexistent) dsjk-basem-b))) (help "Spezialmethode zum Beweis des DISJL")) (meth~defmethod dsjk-basem-b dsjk-base (in lock-res) (rating 1) (declarations (type-variables rr) (type-constants o i) (sorted-meta-variables (c31 num term) (dc glist term) (c2 (o (o form)) term) (c1 (o form) term) (ct glist term) (ct1 o term) (ct2 item term) (c3 (o form) term) (pos1110101 o pos) (pos11110 o pos) (pos1110 o pos) (pos111 o pos) (pos11 o pos) (pos1110110 o pos) (pos11101 o pos) (pos101 o pos) (pos10 o pos) ) ) (parameters) (premises (- lh1) (- lh2) (- lh3) (+ ls10) (+ ls20)) (application-condition ) (outline-actions (ls20 (sponsor ls21)) (ls10 (sponsor ls11)) ) (outline-orderings ) (outline-computations (ct (:term (cons (der-item-constr res-start c1 NULL NULL) NULL))) (ct1 (:term (= c1 (SETMINUS (GOOD-CLAUSE C2) (SINGLETON (GOOD-LITERAL (good-clause c2))))))) (ct2 (:term (last dc))) (pos1110101 (:position (1 1 1 0 1 0 1))) (pos11110 (:position (1 1 1 1 0))) (pos1110 (:position (1 1 1 0))) (pos111 (:position (1 1 1))) (pos11 (:position (1 1))) (pos1110110 (:position (1 1 1 0 1 1 0))) (pos11101 (:position (1 1 1 0 1))) (pos101 (:position (1 0 1))) (pos10 (:position (1 0))) ) (conclusions (- ltp) ) (decl-content (lh1 () (= c31 zero) ) (lh2 () (= (minus (glist-length dc) one) zero) ) (lh3 () (DERIVATION-OF (UNION (SETMINUS C2 (SINGLETON (GOOD-CLAUSE C2))) (SINGLETON (SETMINUS (GOOD-CLAUSE C2) (SINGLETON (GOOD-LITERAL (good-clause c2)))))) CRULE-SET dc c1) ) (h1 () (and (= (der-item-info (last dc)) c1) (derivation (UNION (SETMINUS C2 (SINGLETON (GOOD-CLAUSE C2))) (SINGLETON (SETMINUS (GOOD-CLAUSE C2) (SINGLETON (GOOD-LITERAL (good-clause c2)))))) crule-set dc)) ("DefnE" (derivation-of)(lh3))) (h2 () (derivation (UNION (SETMINUS C2 (SINGLETON (GOOD-CLAUSE C2))) (SINGLETON (SETMINUS (GOOD-CLAUSE C2) (SINGLETON (GOOD-LITERAL (good-clause c2)))))) crule-set dc) ("AndER" ()(h1))) (h3 () (forall (lam (x item) (implies (is-component x dc) (exists (lam (r crule) (and (free-derivation-cond dc) (and (and (crule-set r) (crule-applicable r (append (append (der-item-inp x) (poslist2infolist (der-item-prems x) dc)) (cons (cl2item (der-item-info x)) NULL)) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2)))))))) (and (forall (lam (y num) (implies (is-component (num2item y) (der-item-prems x)) (less y (position x dc))))) (= (der-item-info x) (crule-application r (append (append (der-item-inp x) (poslist2infolist (der-item-prems x) dc)) (cons (cl2item (der-item-info x)) NULL)) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2)))))))))))))))) ("DefnE" (derivation) (h2))) (h4 () (implies (is-component (last dc) dc) (exists (lam (r crule) (and (free-derivation-cond dc) (and (and (crule-set r) (crule-applicable r (append (append (der-item-inp (last dc)) (poslist2infolist (der-item-prems (last dc)) dc)) (cons (cl2item (der-item-info (last dc))) NULL)) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2)))))))) (and (forall (lam (y num) (implies (is-component (num2item y) (der-item-prems (last dc))) (less y (position (last dc) dc))))) (= (der-item-info (last dc)) (crule-application r (append (append (der-item-inp (last dc)) (poslist2infolist (der-item-prems (last dc)) dc)) (cons (cl2item (der-item-info (last dc))) NULL)) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2)))))))))))))) ("ForallE" (ct2) (h3))) (h5 () (is-component (last dc) dc) ("Optional"()())) (h6 () (exists (lam (r crule) (and (free-derivation-cond dc) (and (and (crule-set r) (crule-applicable r (append (append (der-item-inp (last dc)) (poslist2infolist (der-item-prems (last dc)) dc)) (cons (cl2item (der-item-info (last dc))) NULL)) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2)))))))) (and (forall (lam (y num) (implies (is-component (num2item y) (der-item-prems (last dc))) (less y (position (last dc) dc))))) (= (der-item-info (last dc)) (crule-application r (append (append (der-item-inp (last dc)) (poslist2infolist (der-item-prems (last dc)) dc)) (cons (cl2item (der-item-info (last dc))) NULL)) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2))))))))))))) ("ImpE"()(h4 h5))) (h7 () (and (free-derivation-cond dc) (and (and (crule-set res-start) (crule-applicable res-start (append (append (der-item-inp (last dc)) (poslist2infolist (der-item-prems (last dc)) dc)) (cons (cl2item (der-item-info (last dc))) NULL)) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2)))))))) (and (forall (lam (y num) (implies (is-component (num2item y) (der-item-prems (last dc))) (less y (position (last dc) dc))))) (= (der-item-info (last dc)) (crule-application res-start (append (append (der-item-inp (last dc)) (poslist2infolist (der-item-prems (last dc)) dc)) (cons (cl2item (der-item-info (last dc))) NULL)) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2))))))))))) ("Hyp"()())) (h8 () (and (and (crule-set res-start) (crule-applicable res-start (append (append (der-item-inp (last dc)) (poslist2infolist (der-item-prems (last dc)) dc)) (cons (cl2item (der-item-info (last dc))) NULL)) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2)))))))) (and (forall (lam (y num) (implies (is-component (num2item y) (der-item-prems (last dc))) (less y (position (last dc) dc))))) (= (der-item-info (last dc)) (crule-application res-start (append (append (der-item-inp (last dc)) (poslist2infolist (der-item-prems (last dc)) dc)) (cons (cl2item (der-item-info (last dc))) NULL)) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2)))))))))) ("AndER"()(h7))) (h9 () (and (crule-set res-start) (crule-applicable res-start (append (append (der-item-inp (last dc)) (poslist2infolist (der-item-prems (last dc)) dc)) (cons (cl2item (der-item-info (last dc))) NULL)) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2)))))))) ("AndEL"()(h8))) (h10 () (crule-applicable res-start (append (append (der-item-inp (last dc)) (poslist2infolist (der-item-prems (last dc)) dc)) (cons (cl2item (der-item-info (last dc))) NULL)) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2))))))) ("AndER" ()(h9))) (h11 (l1a) (crule-applicable res-start (append (append (der-item-inp (der-item-constr res-start c1 NULL NULL)) (poslist2infolist (der-item-prems (last dc)) dc)) (cons (cl2item (der-item-info (last dc))) NULL)) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2))))))) ("=Subst" (pos1110101) (l1a))) (ax1a () (= NULL (der-item-inp (der-item-constr res-start c1 NULL NULL))) ("Optional"()())) (h12 (l1a) (crule-applicable res-start (append (append NULL (poslist2infolist (der-item-prems (last dc)) dc)) (cons (cl2item (der-item-info (last dc))) NULL)) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2))))))) ("=Subst" (pos11110) (ax1a h11))) (ax1b () (= (poslist2infolist (der-item-prems (last dc)) dc) (append NULL (poslist2infolist (der-item-prems (last dc)) dc))) ("Optional"()())) (h13 (l1a) (crule-applicable res-start (append (poslist2infolist (der-item-prems (last dc)) dc) (cons (cl2item (der-item-info (last dc))) NULL)) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2))))))) ("=Subst" (pos1110) (ax1b h12))) (ax1c () (= (der-item-prems (last dc)) NULL)) (h14 (l1a) (crule-applicable res-start (append (poslist2infolist NULL dc) (cons (cl2item (der-item-info (last dc))) NULL)) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2))))))) ("=Subst" (pos1110)(ax1c h13))) (ax1d () (= (poslist2infolist NULL dc) NULL) ("Optional"()())) (h15 (l1a) (crule-applicable res-start (append NULL (cons (cl2item (der-item-info (last dc))) NULL)) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2))))))) ("=Subst"(pos111)(ax1d h14))) (ax1e () (= (append NULL (cons (cl2item (der-item-info (last dc))) NULL)) (cons (cl2item (der-item-info (last dc))) NULL)) ("Optional"()())) (h16 (l1a) (crule-applicable res-start (cons (cl2item (der-item-info (last dc))) NULL) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2))))))) ("=Subst" (pos11) (ax1e h15))) (h17 (l1a) (crule-applicable res-start (cons (cl2item (der-item-info (der-item-constr res-start c1 NULL NULL))) NULL) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2))))))) ("=Subst" (pos1110110) (l1a h16))) (ax1f () (= (der-item-info (der-item-constr res-start c1 NULL NULL)) c1) ("Optional"()())) (h18 (l1a) (crule-applicable res-start (cons (cl2item c1) NULL) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2))))))) ("=Subst"(pos11101)(ax1f h17))) (ax1g () (equiv (crule-applicable res-start (cons (cl2item c1) NULL) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2))))))) (in (item2cl (first (cons (cl2item c1) NULL))) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2)))))))) ("Optional"()())) (h19 () (in (item2cl (first (cons (cl2item c1) NULL))) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2))))))) ("EquivER" ()(ax1g h18))) (ax1h () (= (first (cons (cl2item c1) NULL)) (cl2item c1)) ("Optional"()())) (h20 () (in (item2cl (cl2item c1)) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2))))))) ("=Subst" (pos101) (ax1h h19))) (ax1i () (= (item2cl (cl2item c1)) c1) ("Optional"()())) (h21 () (in c1 (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2))))))) ("=Subst" (pos10) (ax1i)(h20))) (ax1j () (in c1 c2) ("Optional" ()())) ;; ================================================================== (ls11 () (c2 (UNION C1 (SINGLETON (GOOD-LITERAL (good-clause c2)))) ) ("Optional"()())) (ls10 (l1 ls11 h7) (DERIVABLE (UNION C1 (SINGLETON (GOOD-LITERAL (good-clause c2)))) C2 CRULE-SET) ("Open"()())) (lsg1 (l1) (DERIVABLE (UNION C1 (SINGLETON (GOOD-LITERAL (good-clause c2)))) C2 CRULE-SET) ("ExistsE" (res-start)(h6 ls10))) ;; ---------------------------------------------------------------- (ls21 () (c2 c1) ("Optional"()())) (ls20 (l1 ls21 h7) (DERIVABLE C1 C2 CRULE-SET) ("Open" ()())) (lsg2 (l1) (DERIVABLE C1 C2 CRULE-SET) ("ExistsE" (res-start)(h6 ls20))) ;; ---------------------------------------------- (l1 () (= dc (cons (der-item-constr res-start c1 NULL NULL) NULL)) ("Optional"()())) (l1a () (= (last dc) (der-item-constr res-start c1 NULL NULL)) ("Optional"()())) ;; ==================================================================== (l2 () (forall (lam (x o) (or x (not x)))) ("Axiom"()())) (l3 () (or (= (SETMINUS (GOOD-CLAUSE C2) (SINGLETON (GOOD-LITERAL (good-clause c2)))) c1) (not (= (SETMINUS (GOOD-CLAUSE C2) (SINGLETON (GOOD-LITERAL (good-clause c2)))) c1))) ("ForallE"(ct1)(l2))) (l4 () (= (SETMINUS (GOOD-CLAUSE C2) (SINGLETON (GOOD-LITERAL (good-clause c2)))) c1) ("Hyp" ()())) (l5 (l4) (OR (DERIVABLE C1 C2 CRULE-SET) (DERIVABLE (UNION C1 (SINGLETON (GOOD-LITERAL (good-clause c2)))) C2 CRULE-SET)) ("OrIR" ()(lsg1))) (l6 () (not (= (SETMINUS (GOOD-CLAUSE C2) (SINGLETON (GOOD-LITERAL (good-clause c2)))) c1)) ("Hyp"()())) (l7 (l6) (OR (DERIVABLE C1 C2 CRULE-SET) (DERIVABLE (UNION C1 (SINGLETON (GOOD-LITERAL (good-clause c2)))) C2 CRULE-SET)) ("OriL" ()(lsg2))) (l30 () (OR (DERIVABLE C1 C2 CRULE-SET) (DERIVABLE (UNION C1 (SINGLETON (GOOD-LITERAL (good-clause c2)))) C2 CRULE-SET)) ("OrE" ()(l3 l5 l7))) ;; =========================================================== (ltp () (OR (DERIVABLE C1 C2 CRULE-SET) (DERIVABLE (UNION C1 (SINGLETON (GOOD-LITERAL (good-clause c2)))) C2 CRULE-SET)) ("Weaken" ()(l30))) ) (proc-content schema-interpreter) (remark "Special method for proving disjunctionlemma.") ) (infer~defmethod dsjk-base1 (outline-mappings (((existent existent existent existent nonexistent nonexistent);;4 x nonexistent dsjk-base1-b))) (help "Spezialmethode zum Beweis des DISJL")) (meth~defmethod dsjk-base1-b dsjk-base1 (in lock-res) (rating 1) (declarations (type-variables rr) (type-constants o i) (sorted-meta-variables (c31 num term) (dc glist term) (c2 (o (o form)) term) (c1 (o form) term) (ct glist term) (ct1 o term) (ct2 item term) (c3 (o form) term) (pos1110101 o pos) (pos11110 o pos) (pos1110 o pos) (pos111 o pos) (pos11 o pos) (pos1110110 o pos) (pos11101 o pos) (pos101 o pos) (pos10 o pos) ) ) (parameters) (premises (- lh1) (- lh2) (- lh3) (+ ls11) (+ ls20)) (application-condition ) (outline-actions (ls20 (sponsor ax1j)) (ls11 (sponsor ls12)) ) (outline-orderings ) (outline-computations (c3 (type-newconst (:type (o form)))) (ct (:term (cons (der-item-constr res-start c3 NULL NULL) (cons (der-item-constr res-start (good-clause c2) NULL NULL) NULL)))) (ct1 (:term (= c1 (SETMINUS (GOOD-CLAUSE C2) (SINGLETON (GOOD-LITERAL (good-clause c2))))))) (ct2 (:term (last dc))) (pos1110101 (:position (1 1 1 0 1 0 1))) (pos11110 (:position (1 1 1 1 0))) (pos1110 (:position (1 1 1 0))) (pos111 (:position (1 1 1))) (pos11 (:position (1 1))) (pos1110110 (:position (1 1 1 0 1 1 0))) (pos11101 (:position (1 1 1 0 1))) (pos101 (:position (1 0 1))) (pos10 (:position (1 0))) ) (conclusions (- ltp) ) (decl-content (lh1 () (= c31 (s zero)) ) (lh2 () (= (minus (glist-length dc) one) (s zero)) ) (lh3 () (DERIVATION-OF (UNION (SETMINUS C2 (SINGLETON (GOOD-CLAUSE C2))) (SINGLETON (SETMINUS (GOOD-CLAUSE C2) (SINGLETON (GOOD-LITERAL (good-clause c2)))))) CRULE-SET dc c1) ) (h1 () (and (= (der-item-info (last dc)) c1) (derivation (UNION (SETMINUS C2 (SINGLETON (GOOD-CLAUSE C2))) (SINGLETON (SETMINUS (GOOD-CLAUSE C2) (SINGLETON (GOOD-LITERAL (good-clause c2)))))) crule-set dc)) ("DefnE" (derivation-of)(lh3))) (h2 () (derivation (UNION (SETMINUS C2 (SINGLETON (GOOD-CLAUSE C2))) (SINGLETON (SETMINUS (GOOD-CLAUSE C2) (SINGLETON (GOOD-LITERAL (good-clause c2)))))) crule-set dc) ("AndER" ()(h1))) (h3 () (forall (lam (x item) (implies (is-component x dc) (exists (lam (r crule) (and (free-derivation-cond dc) (and (and (crule-set r) (crule-applicable r (append (append (der-item-inp x) (poslist2infolist (der-item-prems x) dc)) (cons (cl2item (der-item-info x)) NULL)) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2)))))))) (and (forall (lam (y num) (implies (is-component (num2item y) (der-item-prems x)) (less y (position x dc))))) (= (der-item-info x) (crule-application r (append (append (der-item-inp x) (poslist2infolist (der-item-prems x) dc)) (cons (cl2item (der-item-info x)) NULL)) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2)))))))))))))))) ("DefnE" (derivation) (h2))) (h4 () (implies (is-component (last dc) dc) (exists (lam (r crule) (and (free-derivation-cond dc) (and (and (crule-set r) (crule-applicable r (append (append (der-item-inp (last dc)) (poslist2infolist (der-item-prems (last dc)) dc)) (cons (cl2item (der-item-info (last dc))) NULL)) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2)))))))) (and (forall (lam (y num) (implies (is-component (num2item y) (der-item-prems (last dc))) (less y (position (last dc) dc))))) (= (der-item-info (last dc)) (crule-application r (append (append (der-item-inp (last dc)) (poslist2infolist (der-item-prems (last dc)) dc)) (cons (cl2item (der-item-info (last dc))) NULL)) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2)))))))))))))) ("ForallE" (ct2) (h3))) (h5 () (is-component (last dc) dc) ("Optional"()())) (h6 () (exists (lam (r crule) (and (free-derivation-cond dc) (and (and (crule-set r) (crule-applicable r (append (append (der-item-inp (last dc)) (poslist2infolist (der-item-prems (last dc)) dc)) (cons (cl2item (der-item-info (last dc))) NULL)) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2)))))))) (and (forall (lam (y num) (implies (is-component (num2item y) (der-item-prems (last dc))) (less y (position (last dc) dc))))) (= (der-item-info (last dc)) (crule-application r (append (append (der-item-inp (last dc)) (poslist2infolist (der-item-prems (last dc)) dc)) (cons (cl2item (der-item-info (last dc))) NULL)) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2))))))))))))) ("ImpE"()(h4 h5))) (h7 () (and (free-derivation-cond dc) (and (and (crule-set res-start) (crule-applicable res-start (append (append (der-item-inp (last dc)) (poslist2infolist (der-item-prems (last dc)) dc)) (cons (cl2item (der-item-info (last dc))) NULL)) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2)))))))) (and (forall (lam (y num) (implies (is-component (num2item y) (der-item-prems (last dc))) (less y (position (last dc) dc))))) (= (der-item-info (last dc)) (crule-application res-start (append (append (der-item-inp (last dc)) (poslist2infolist (der-item-prems (last dc)) dc)) (cons (cl2item (der-item-info (last dc))) NULL)) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2))))))))))) ("Hyp"()())) (h8 () (and (and (crule-set res-start) (crule-applicable res-start (append (append (der-item-inp (last dc)) (poslist2infolist (der-item-prems (last dc)) dc)) (cons (cl2item (der-item-info (last dc))) NULL)) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2)))))))) (and (forall (lam (y num) (implies (is-component (num2item y) (der-item-prems (last dc))) (less y (position (last dc) dc))))) (= (der-item-info (last dc)) (crule-application res-start (append (append (der-item-inp (last dc)) (poslist2infolist (der-item-prems (last dc)) dc)) (cons (cl2item (der-item-info (last dc))) NULL)) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2)))))))))) ("AndER"()(h7))) (h9 () (and (crule-set res-start) (crule-applicable res-start (append (append (der-item-inp (last dc)) (poslist2infolist (der-item-prems (last dc)) dc)) (cons (cl2item (der-item-info (last dc))) NULL)) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2)))))))) ("AndEL"()(h8))) (h10 () (crule-applicable res-start (append (append (der-item-inp (last dc)) (poslist2infolist (der-item-prems (last dc)) dc)) (cons (cl2item (der-item-info (last dc))) NULL)) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2))))))) ("AndER" ()(h9))) (h11 (l1a) (crule-applicable res-start (append (append (der-item-inp (der-item-constr res-start c1 NULL NULL)) (poslist2infolist (der-item-prems (last dc)) dc)) (cons (cl2item (der-item-info (last dc))) NULL)) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2))))))) ("=Subst" (pos1110101) (l1a h10))) (ax1a () (= NULL (der-item-inp (der-item-constr res-start c1 NULL NULL))) ("Optional"()())) (h12 (l1a) (crule-applicable res-start (append (append NULL (poslist2infolist (der-item-prems (last dc)) dc)) (cons (cl2item (der-item-info (last dc))) NULL)) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2))))))) ("=Subst" (pos11110) (ax1a h11))) (ax1b () (= (poslist2infolist (der-item-prems (last dc)) dc) (append NULL (poslist2infolist (der-item-prems (last dc)) dc))) ("Optional"()())) (h13 (l1a) (crule-applicable res-start (append (poslist2infolist (der-item-prems (last dc)) dc) (cons (cl2item (der-item-info (last dc))) NULL)) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2))))))) ("=Subst" (pos1110) (ax1b h12))) (ax1c () (= (der-item-prems (last dc)) NULL) ("Optional"()())) (h14 (l1a) (crule-applicable res-start (append (poslist2infolist NULL dc) (cons (cl2item (der-item-info (last dc))) NULL)) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2))))))) ("=Subst" (pos1110)(ax1c h13))) (ax1d () (= (poslist2infolist NULL dc) NULL) ("Optional"()())) (h15 (l1a) (crule-applicable res-start (append NULL (cons (cl2item (der-item-info (last dc))) NULL)) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2))))))) ("=Subst"(pos111)(ax1d h14))) (ax1e () (= (append NULL (cons (cl2item (der-item-info (last dc))) NULL)) (cons (cl2item (der-item-info (last dc))) NULL)) ("Optional"()())) (h16 (l1a) (crule-applicable res-start (cons (cl2item (der-item-info (last dc))) NULL) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2))))))) ("=Subst" (pos11) (ax1e h15))) (h17 (l1a) (crule-applicable res-start (cons (cl2item (der-item-info (der-item-constr res-start c1 NULL NULL))) NULL) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2))))))) ("=Subst" (pos1110110) (l1a h16))) (ax1f () (= (der-item-info (der-item-constr res-start c1 NULL NULL)) c1) ("Optional"()())) (h18 (l1a) (crule-applicable res-start (cons (cl2item c1) NULL) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2))))))) ("=Subst"(pos11101)(ax1f h17))) (ax1g () (equiv (crule-applicable res-start (cons (cl2item c1) NULL) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2))))))) (in (item2cl (first (cons (cl2item c1) NULL))) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2)))))))) ("Optional"()())) (h19 () (in (item2cl (first (cons (cl2item c1) NULL))) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2))))))) ("EquivER" ()(ax1g h18))) (ax1h () (= (first (cons (cl2item c1) NULL)) (cl2item c1)) ("Optional"()())) (h20 () (in (item2cl (cl2item c1)) (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2))))))) ("=Subst" (pos101) (ax1h h19))) (ax1i () (= (item2cl (cl2item c1)) c1) ("Optional"()())) (h21 () (in c1 (union (setminus c2 (singleton (good-clause c2))) (singleton (setminus (good-clause c2) (singleton (good-literal (good-clause c2))))))) ("=Subst" (pos10) (ax1i)(h20))) (ax1j () (c2 c1) ("abstract" ()())) ;; ------------------------------------------------------ ; (= (SETMINUS (GOOD-CLAUSE C2) ; (SINGLETON ; (GOOD-LITERAL (good-clause c2)))) ; c1) (ls12 () (c2 (UNION C1 (SINGLETON (GOOD-LITERAL (good-clause c2)))) ) ("abstract" ()())) (ls11 (l1 ls12 h7) (DERIVABLE (UNION C1 (SINGLETON (GOOD-LITERAL (good-clause c2)))) C2 CRULE-SET) ("Open" ()())) (lsg1 (l1) (DERIVABLE (UNION C1 (SINGLETON (GOOD-LITERAL (good-clause c2)))) C2 CRULE-SET) ("ExistsE" (res-start) (ls11 h6))) ;; ================================================================== (ls20 (l1 h7 ax1j) (DERIVABLE C1 C2 CRULE-SET) ("Open"()())) (lsg2 (l1) (DERIVABLE C1 C2 CRULE-SET) ("ExistsE"(res-start)(ls20 h6))) ;; =================================================================== (l1 () (= dc (cons (der-item-constr res-start c3 NULL NULL) (cons (der-item-constr res-start c1 NULL NULL) NULL))) ("Optional"()())) (l1a () (= (last dc) (der-item-constr res-start c1 NULL NULL)) ("Optional"()())) (l2 () (forall (lam (x o) (or x (not x)))) ("Axiom"()())) (l3 () (or (= (SETMINUS (GOOD-CLAUSE C2) (SINGLETON (GOOD-LITERAL (good-clause c2)))) c1) (not (= (SETMINUS (GOOD-CLAUSE C2) (SINGLETON (GOOD-LITERAL (good-clause c2)))) c1))) ("ForallE"(ct1)(l2))) (l4 () (= (SETMINUS (GOOD-CLAUSE C2) (SINGLETON (GOOD-LITERAL (good-clause c2)))) c1) ("Hyp" ()())) (l5 (l4) (OR (DERIVABLE C1 C2 CRULE-SET) (DERIVABLE (UNION C1 (SINGLETON (GOOD-LITERAL (good-clause c2)))) C2 CRULE-SET)) ("OrIR" ()(lsg1))) (l6 () (not (= (SETMINUS (GOOD-CLAUSE C2) (SINGLETON (GOOD-LITERAL (good-clause c2)))) c1)) ("Hyp"()())) (l7 (l6) (OR (DERIVABLE C1 C2 CRULE-SET) (DERIVABLE (UNION C1 (SINGLETON (GOOD-LITERAL (good-clause c2)))) C2 CRULE-SET)) ("OriL" ()(lsg2))) (l30 () (OR (DERIVABLE C1 C2 CRULE-SET) (DERIVABLE (UNION C1 (SINGLETON (GOOD-LITERAL (good-clause c2) ))) C2 CRULE-SET)) ("OrE" ()(l3 l7 l5))) ;; =========================================================== (ltp () (OR (DERIVABLE C1 C2 CRULE-SET) (DERIVABLE (UNION C1 (SINGLETON (GOOD-LITERAL (good-clause c2)))) C2 CRULE-SET)) ("weaken" ()(l30))) ) (proc-content schema-interpreter) (remark "Special method for proving disjunctionlemma.") ) (infer~defmethod disj-ih (outline-mappings (((existent existent existent existent ;; existent ) disj-ih-m-b))) (help "Application of the ind-hyp for the ")) (meth~defmethod disj-ih-m-b disj-ih (in lock-res) (rating 30) (reasoning :planning) (declarations (constants ) (sorted-meta-variables (co9 (o (o form)) term) (numc num term) (ih-seq glist term) (dc55 glist term) (cx12 num term) ) ) (parameters ) (premises (- l49) (- l52) ;;(- l51) ;; (- l50) ) (application-condition ) (outline-actions ) (outline-orderings ) (outline-computations ) (conclusions (- ltp)) (decl-content ; (l54 () (derivation-of (union (setminus co9 (singleton (good-clause co9))) ; (singleton ; (setminus (good-clause co9) ; (singleton (good-literal ; (good-clause co9)))))) ; crule-set ih-seq (der-item-info (glist-nth ; numc ; dc55))) ("AndER"()(l52))) ; ; (l53 () (less (minus (glist-length ih-seq) one) ; cx12) ("andEL" ()(l52))) ; (l52 () (and (less (minus (glist-length ih-seq) one) cx12) (derivation-of (union (setminus co9 (singleton (good-clause co9))) (singleton (setminus (good-clause co9) (singleton (good-literal (good-clause co9)))))) crule-set ih-seq (der-item-info (glist-nth numc dc55)))) ) (l51 () (greater cx12 (s zero)) ) (l50 () (less numc cx12) ) (l49 () (forall (lam (cx2 num) (implies (and (greater cx12 (s zero)) (less cx2 cx12)) (forall (lam (dc54 glist) (implies (= (minus (glist-length dc54) one) cx2) (forall (lam (co8 (o form)) (implies (derivation-of (union (setminus co9 (singleton (good-clause co9))) (singleton (setminus (good-clause co9) (singleton (good-literal (good-clause co9)))))) crule-set dc54 co8) (or (derivable co8 co9 crule-set) (derivable (union co8 (singleton (good-literal (good-clause co9)))) co9 crule-set))))))))))) ) (l48 () (implies (and (greater cx12 (s zero)) (less numc cx12)) (forall (lam (dc54 glist) (implies (= (minus (glist-length dc54) one) numc) (forall (lam (co8 (o form)) (implies (derivation-of (union (setminus co9 (singleton (good-clause co9))) (singleton (setminus (good-clause co9) (singleton (good-literal (good-clause co9)))))) crule-set dc54 co8) (or (derivable co8 co9 crule-set) (derivable (union co8 (singleton (good-literal (good-clause co9)))) co9 crule-set))))))))) ("forallE" (numc) (l49))) (l47 () (and (greater cx12 (s zero)) (less numc cx12)) ("AndI" () (l50 l51))) (l46 () (forall (lam (dc54 glist) (implies (= (minus (glist-length dc54) one) numc) (forall (lam (co8 (o form)) (implies (derivation-of (union (setminus co9 (singleton (good-clause co9))) (singleton (setminus (good-clause co9) (singleton (good-literal (good-clause co9)))))) crule-set dc54 co8) (or (derivable co8 co9 crule-set) (derivable (union co8 (singleton (good-literal (good-clause co9)))) co9 crule-set)))))))) ("ImpE" ()(l47 l48))) (l45 () (implies (= (minus (glist-length ih-seq) one) numc) (forall (lam (co8 (o form)) (implies (derivation-of (union (setminus co9 (singleton (good-clause co9))) (singleton (setminus (good-clause co9) (singleton (good-literal (good-clause co9)))))) crule-set ih-seq co8) (or (derivable co8 co9 crule-set) (derivable (union co8 (singleton (good-literal (good-clause co9)))) co9 crule-set)))))) ("forallE" (ih-seq) (l46))) (l44 () (= (minus (glist-length ih-seq) one) numc) ("abstract"()())) (l43 () (forall (lam (co8 (o form)) (implies (derivation-of (union (setminus co9 (singleton (good-clause co9))) (singleton (setminus (good-clause co9) (singleton (good-literal (good-clause co9)))))) crule-set ih-seq co8) (or (derivable co8 co9 crule-set) (derivable (union co8 (singleton (good-literal (good-clause co9)))) co9 crule-set))))) ("impE"()(l44 l45))) (l42 () (implies (derivation-of (union (setminus co9 (singleton (good-clause co9))) (singleton (setminus (good-clause co9) (singleton (good-literal (good-clause co9)))))) crule-set ih-seq (DER-ITEM-INFO (GLIST-NTH NUMC DC55))) (or (derivable (DER-ITEM-INFO (GLIST-NTH NUMC DC55)) co9 crule-set) (derivable (union (DER-ITEM-INFO (GLIST-NTH NUMC DC55)) (singleton (good-literal (good-clause co9)))) co9 crule-set))) ("forallE"(substterm)(l43))) ;; ========================================================================== (ltp () (or (DERIVABLE (DER-ITEM-INFO (GLIST-NTH NUMC DC55)) CO9 CRULE-SET) (DERIVABLE (UNION (DER-ITEM-INFO (GLIST-NTH NUMC DC55)) (SINGLETON (GOOD-LITERAL (GOOD-CLAUSE CO9)))) CO9 CRULE-SET)) ("impe" () (l42 l54))) ) (proc-content schema-interpreter) (remark "") ) (infer~defmethod simp-djl (outline-mappings (((existent nonexistent) simp-djl-m-b))) (help "Lemma to simplify the Disjunctionlemma.")) (meth~defmethod simp-djl-m-b simp-djl (in lock-res) (rating 30) (declarations (type-constants o i num crule glist) (type-variables bb rr) (sorted-meta-variables ;;(meta-var type sort) (nk (o form) term) (nkm (o (o form)) term) (fterm (o form) term) (sterm form term) (tterm glist term) ) ) (premises (+ l14) ) (application-condition ) (outline-orderings ) (outline-computations (nk (type-newconst (:type (o form)))) (nkm (type-newconst (:type (o (o form))))) (fterm (:term (good-clause nkm))) (sterm (:term (good-literal (good-clause nkm)))) (tterm (type-newconst (:type glist))) ) (conclusions (- ltp)) (decl-content (h () (and (in nkm all-clause-sets) (exists (lam (kl1 (o form)) (and (nkm kl1) (card>2 kl1))))) ("Hyp"()())) (k () (derivable nk (union (setminus nkm (singleton fterm)) (singleton (setminus fterm (singleton sterm)))) crule-set) ("Hyp"()())) (k1 (k) (exists (lam (seq glist) (derivation-of (union (setminus nkm (singleton fterm)) (singleton (setminus fterm (singleton sterm)))) crule-set seq nk ))) ("DefnE" (derivable) (k))) (k2 (k) (derivation-of (union (setminus nkm (singleton fterm)) (singleton (setminus fterm (singleton sterm)))) crule-set tterm nk ) ("Hyp"()())) (l14 (h k k2) (forall (lam (av glist) (forall (lam (x (o form)) (implies (derivation-of (union (setminus nkm (singleton fterm)) (singleton (setminus fterm (singleton sterm)))) crule-set av x ) (or (derivable x nkm crule-set) (derivable (union x (singleton sterm)) nkm crule-set))))))) ("Open" ()())) (l13 (h k k2) (forall (lam (x (o form)) (implies (derivation-of (union (setminus nkm (singleton fterm)) (singleton (setminus fterm (singleton sterm)))) crule-set tterm x ) (or (derivable x nkm crule-set) (derivable (union x (singleton sterm)) nkm crule-set))))) ("ForallE" (tterm) (l14))) (l12 (h k k2) (implies (derivation-of (union (setminus nkm (singleton fterm)) (singleton (setminus fterm (singleton sterm)))) crule-set tterm nk ) (or (derivable nk nkm crule-set) (derivable (union nk (singleton sterm)) nkm crule-set))) ("ForallE" (nk) (l13))) (l11 (h k k2) (or (derivable nk nkm crule-set) (derivable (union nk (singleton sterm)) nkm crule-set)) ("ImpE" ()(l12 k2))) (l10 (h k) (or (derivable nk nkm crule-set) (derivable (union nk (singleton sterm)) nkm crule-set)) ("ExistsE" (tterm) (l11 k1))) (l9 (h) (implies (derivable nk (union (setminus nkm (singleton fterm)) (singleton (setminus fterm (singleton sterm)))) crule-set) (or (derivable nk nkm crule-set) (derivable (union nk (singleton sterm)) nkm crule-set))) ("ImpI" ()(l10))) (l8 (h) (fterm sterm) ("Open"()())) (l7 (h) (and (implies (derivable nk (union (setminus nkm (singleton fterm)) (singleton (setminus fterm (singleton sterm)))) crule-set) (or (derivable nk nkm crule-set) (derivable (union nk (singleton sterm)) nkm crule-set))) (fterm sterm)) ("AndI" ()(l9 l8))) (l6 (h) (and (nkm fterm) (card>2 fterm)) ("Open" ()())) (l5 (h) (and (and (implies (derivable nk (union (setminus nkm (singleton fterm)) (singleton (setminus fterm (singleton sterm)))) crule-set) (or (derivable nk nkm crule-set) (derivable (union nk (singleton sterm)) nkm crule-set))) (fterm sterm)) (and (nkm fterm) (card>2 fterm))) ("AndI" ()(l7 l6))) (l4 (h) (exists (lam (l form) (and (and (implies (derivable nk (union (setminus nkm (singleton fterm)) (singleton (setminus fterm (singleton l)))) crule-set) (or (derivable nk nkm crule-set) (derivable (union nk (singleton l)) nkm crule-set))) (fterm l)) (and (nkm fterm) (card>2 fterm))))) ("ExistsI" (sterm)(l5))) (l3 (h) (exists (lam (kl (o form)) (exists (lam (l form) (and (and (implies (derivable nk (union (setminus nkm (singleton kl)) (singleton (setminus kl (singleton l)))) crule-set) (or (derivable nk nkm crule-set) (derivable (union nk (singleton l)) nkm crule-set))) (kl l)) (and (nkm kl) (card>2 kl))))))) ("ExistsI" (fterm)(l4))) (l2 () (implies (and (in nkm all-clause-sets) (exists (lam (kl1 (o form)) (and (nkm kl1) (card>2 kl1))))) (exists (lam (kl (o form)) (exists (lam (l form) (and (and (implies (derivable nk (union (setminus nkm (singleton kl)) (singleton (setminus kl (singleton l)))) crule-set) (or (derivable nk nkm crule-set) (derivable (union nk (singleton l)) nkm crule-set))) (kl l)) (and (nkm kl) (card>2 kl)))))))) ("ImpI" () (l3))) (l1 () (forall (lam (gkl (o form)) (implies (and (in nkm all-clause-sets) (exists (lam (kl1 (o form)) (and (nkm kl1) (card>2 kl1))))) (exists (lam (kl (o form)) (exists (lam (l form) (and (and (implies (derivable gkl (union (setminus nkm (singleton kl)) (singleton (setminus kl (singleton l)))) crule-set) (or (derivable gkl nkm crule-set) (derivable (union gkl (singleton l)) nkm crule-set))) (kl l)) (and (nkm kl) (card>2 kl)))))))))) ("ForallI"(nk)(l2))) (ltp () (forall (lam (klm (o (o form)))(forall (lam (gkl (o form)) (implies (and (in klm all-clause-sets) (exists (lam (kl1 (o form)) (and (klm kl1) (card>2 kl1))))) (exists (lam (kl (o form)) (exists (lam (l form) (and (and (implies (derivable gkl (union (setminus klm (singleton kl)) (singleton (setminus kl (singleton l)))) crule-set) (or (derivable gkl klm crule-set) (derivable (union gkl (singleton l)) klm crule-set))) (kl l)) (and (klm kl) (card>2 kl)))))))))))) ("ForallI"(nkm)(l1))) ) (proc-content schema-interpreter) (remark "Method to prove a lockosition by strong induction on natural numbers.") ) (infer~defmethod simp-fact4 (outline-mappings (((existent nonexistent) simp-fact4-m-b))) (help "Lemma to simplify the Disjunctionlemma.")) (meth~defmethod simp-fact4-m-b simp-fact4 (in lock-res) (rating 30) (declarations (type-constants o i num crule glist) (type-variables bb rr) (sorted-meta-variables ;;(meta-var type sort) (nk (o form) term) (nkm (o (o form)) term) (nl form term) (fterm (o form) term) (sterm form term) (av glist term) ) ) (premises (+ l7) ) (application-condition ) (outline-orderings ) (outline-computations (nk (type-newconst (:type (o form)))) (nkm (type-newconst (:type (o (o form))))) (nl (type-newconst (:type form))) (av (type-newconst (:type glist))) (fterm (:term (good-clause nkm))) (sterm (:term (good-literal (good-clause nkm)))) (tterm (type-newconst (:type glist))) ) (conclusions (- ltp)) (decl-content (la1 () (AND (AND (nKM nK) (nK nL)) (AND (DERIVABLE (UNION EMPTY-CL (SINGLETON nL)) nKM CRULE-SET) (DERIVABLE EMPTY-CL (UNION (SETMINUS nKM (SINGLETON nK)) (SINGLETON (SINGLETON nL))) CRULE-SET))) ("Hyp"()())) (la2 () (AND (DERIVABLE (UNION EMPTY-CL (SINGLETON nL)) nKM CRULE-SET) (DERIVABLE EMPTY-CL (UNION (SETMINUS nKM (SINGLETON nK)) (SINGLETON (SINGLETON nL))) CRULE-SET)) ("AndER"()(la1))) (la3 () (DERIVABLE (UNION EMPTY-CL (SINGLETON nL)) nKM CRULE-SET) ("AndEL"()(la2))) (la4 () (exists (lam (seq glist) (derivation-of nKM CRULE-SET seq (UNION EMPTY-CL (SINGLETON nL))))) ("DefnE" (derivable)(la3))) (lb1 () (derivation-of nKM CRULE-SET av (UNION EMPTY-CL (SINGLETON nL))) ("Hyp"()())) (l7 () (forall (lam (ad glist) (implies (derivation-of nKM CRULE-SET av (UNION EMPTY-CL (SINGLETON nL))) (DERIVABLE EMPTY-CL nKM CRULE-SET)))) ("Open"()())) (l6 () (implies (derivation-of nKM CRULE-SET av (UNION EMPTY-CL (SINGLETON nL))) (DERIVABLE EMPTY-CL nKM CRULE-SET)) ("forallE" (av) (l7))) (l5 (la1 lb1)(DERIVABLE EMPTY-CL nKM CRULE-SET) ("ImpE" ()(l6 lb1))) (l4 (la1) (DERIVABLE EMPTY-CL nKM CRULE-SET) ("ExistsE"(av)(la4 l5))) (l3 () (IMPLIES (AND (AND (nKM nK) (nK nL)) (AND (DERIVABLE (UNION EMPTY-CL (SINGLETON nL)) nKM CRULE-SET) (DERIVABLE EMPTY-CL (UNION (SETMINUS nKM (SINGLETON nK)) (SINGLETON (SINGLETON nL))) CRULE-SET))) (DERIVABLE EMPTY-CL nKM CRULE-SET)) ("ImpI"()(l4 la1))) (l2 () (forall (lam (L FORM) (IMPLIES (AND (AND (nKM nK) (nK L)) (AND (DERIVABLE (UNION EMPTY-CL (SINGLETON L)) nKM CRULE-SET) (DERIVABLE EMPTY-CL (UNION (SETMINUS nKM (SINGLETON nK)) (SINGLETON (SINGLETON L))) CRULE-SET))) (DERIVABLE EMPTY-CL nKM CRULE-SET)))) ("ForallI"(nl)(l3))) (l1 () (forall (lam (KL (O FORM)) (forall (lam (L FORM) (IMPLIES (AND (AND (nKM KL) (KL L)) (AND (DERIVABLE (UNION EMPTY-CL (SINGLETON L)) nKM CRULE-SET) (DERIVABLE EMPTY-CL (UNION (SETMINUS nKM (SINGLETON KL)) (SINGLETON (SINGLETON L))) CRULE-SET))) (DERIVABLE EMPTY-CL nKM CRULE-SET)))))) ("ForallI" (nk) (l2))) (ltp () (FORALL (lam (KLM (O (O FORM))) (forall (lam (KL (O FORM)) (forall (lam (L FORM) (IMPLIES (AND (AND (KLM KL) (KL L)) (AND (DERIVABLE (UNION EMPTY-CL (SINGLETON L)) KLM CRULE-SET) (DERIVABLE EMPTY-CL (UNION (SETMINUS KLM (SINGLETON KL)) (SINGLETON (SINGLETON L))) CRULE-SET))) (DERIVABLE EMPTY-CL KLM CRULE-SET)))))))) ("ForallI"(nkm)(l1))) ) (proc-content schema-interpreter) (remark "Method to prepare the fact4-lemma for a natural induction application.") ) (infer~defmethod abstract (outline-mappings (((existent) abstract-m-b))) (help "Close abstractable goals ind eln-technique.")) (meth~defmethod abstract-m-b abstract (in lock-res) (rating 10) (reasoning :planning) (declarations (type-constants o i) (sorted-meta-variables (phi o term) ) ) (parameters ) (premises ) (application-condition (eln-abstractable phi)) (outline-actions ) (outline-orderings ) (outline-computations ) (conclusions (- ltp) ) (decl-content (ltp () phi ("Open"()())) ) (proc-content schema-interpreter) (remark "Close abstractable goal while applying eln-technique.") ) (infer~defmethod eln-ind-sc-k1 (outline-mappings (((existent existent nonexistent nonexistent nonexistent ;; nonexistent ) eln-ind-sc-k1-m-b))) (help "Methode zur Nutzung der Menge K1")) (meth~defmethod eln-ind-sc-k1-m-b eln-ind-sc-k1 (in lock-res) (rating 30) (reasoning :planning) (declarations (type-variables rr) (type-constants o i) (constants (skl (o form)) (sli form)) (sorted-meta-variables (vli form const) (vkl (o form) term) (vkm (o (o form)) term) (md o term) ) ) (parameters ) (premises (- l100) (+ l3) (+ l0) (+ l11) ;; (+ f4h) (+ f41) ) (application-condition ) (outline-actions (l16 (sponsor l6)) (l16 (sponsor l15)) ) (outline-orderings (before l3 l0) (before l0 l11) (before l11 f4h) (before f4h f41) ) (outline-computations (vli (type-newconst (termtype sli))) (vkl (type-newconst (termtype skl))) ;(klmx (type-newvar (:type (o (o form))))) ;(gklx (type-newvar (:type (o form)))) ;; (gklx1 (type-newvar (:type (o form)))) ;; (md (eln=set-globals vkl vli)) ) (conclusions (- ltp)) (decl-content (l100 () (not (vkm empty-cl)) ) (l0 () (forall (lam (klmx (o (o form))) (forall (lam (gklx (o form)) (implies (and (in klmx all-clause-sets) (exists (lam (kl1 (o form)) (and (klmx kl1) (card>2 kl1))))) (exists (lam (kl (o form)) (exists (lam (l form) (and (and (implies (derivable gklx (union (setminus klmx (singleton kl)) (singleton (setminus kl (singleton l)))) crule-set) (or (derivable gklx klmx crule-set) (derivable (union gklx (singleton l)) klmx crule-set))) (kl l)) (and (klmx kl) (card>2 kl)))))))))))) ("Open"()())) (l1 () (forall (lam (gklx1 (o form)) (implies (and (in vkm all-clause-sets) (exists (lam (kl1 (o form)) (card>2 kl1)))) (exists (lam (kl (o form)) (exists (lam (l form) (and (and (implies (derivable gklx1 (union (setminus vkm (singleton kl)) (singleton (setminus kl (singleton l)))) crule-set) (or (derivable gklx1 vkm crule-set) (derivable (union gklx1 (singleton l)) vkm crule-set))) (kl l)) (and (vkm kl) (card>2 kl)))))))))) ("ForallE"(vkm)(l0))) (l2 () (implies (and (in vkm all-clause-sets) (exists (lam (kl1 (o form)) (card>2 kl1)))) (exists (lam (kl (o form)) (exists (lam (l form) (and (and (implies (derivable empty-cl (union (setminus vkm (singleton kl)) (singleton (setminus kl (singleton l)))) crule-set) (or (derivable empty-cl vkm crule-set) (derivable (union empty-cl (singleton l)) vkm crule-set))) (kl l)) (and (vkm kl) (card>2 kl)))))))) ("ForallE"(empty-cl)(l1))) (l3 () (and (in vkm all-clause-sets) (exists (lam (kl1 (o form)) (card>2 kl1)))) ("Open"()())) (l4 () (exists (lam (kl (o form)) (exists (lam (l form) (and (and (implies (derivable empty-cl (union (setminus vkm (singleton kl)) (singleton (setminus kl (singleton l)))) crule-set) (or (derivable empty-cl vkm crule-set) (derivable (union empty-cl (singleton l)) vkm crule-set))) (kl l)) (and (vkm kl) (card>2 kl))))))) ("ImpE"()(l3 l2))) (l5 () (exists (lam (l form) (and (and (implies (derivable empty-cl (union (setminus vkm (singleton vkl)) (singleton (setminus vkl (singleton l)))) crule-set) (or (derivable empty-cl vkm crule-set) (derivable (union empty-cl (singleton l)) vkm crule-set))) (vkl l)) (and (vkm vkl) (card>2 vkl))))) ("Hyp"()())) (l6 () (and (and (implies (derivable empty-cl (union (setminus vkm (singleton vkl)) (singleton (setminus vkl (singleton vli)))) crule-set) (or (derivable empty-cl vkm crule-set) (derivable (union empty-cl (singleton vli)) vkm crule-set))) (vkl vli)) (and (vkm vkl) (card>2 vkl))) ("Hyp" () ())) (l7 () (and (implies (derivable empty-cl (union (setminus vkm (singleton vkl)) (singleton (setminus vkl (singleton vli)))) crule-set) (or (derivable empty-cl vkm crule-set) (derivable (union empty-cl (singleton vli)) vkm crule-set))) (vkl vli)) ("AndEL" ()(l6))) (l8 () (and (vkm vkl) (card>2 vkl)) ("AndER" ()(l6))) (l9 () (implies (derivable empty-cl (union (setminus vkm (singleton vkl)) (singleton (setminus vkl (singleton vli)))) crule-set) (or (derivable empty-cl vkm crule-set) (derivable (union empty-cl (singleton vli)) vkm crule-set))) ("AndEL" () (l7))) (l10 () (vkl vli) ("AndER" () (l7))) (l11 () (derivable empty-cl (union (setminus vkm (singleton vkl)) (singleton (setminus vkl (singleton vli)))) crule-set) ("Open"()())) (l12 () (or (derivable empty-cl vkm crule-set) (derivable (union empty-cl (singleton vli)) vkm crule-set)) ("ImpE"()(l9 l11))) (l13 () (derivable empty-cl vkm crule-set) ("Hyp"()())) (l14 (l13 l5 l6) (derivable empty-cl vkm crule-set) ("Weaken"()(l13))) (l15 () (derivable (union empty-cl (singleton vli)) vkm crule-set) ("Hyp" () ())) (f41 () (forall (lam (klm (o (o form))) (forall (lam (kl (o form)) (forall (lam (l form) (implies (and (and (klm kl) (kl l)) (and (derivable (union empty-cl (singleton l)) klm crule-set) (derivable empty-cl (union (setminus klm (singleton kl)) (singleton (singleton l))) crule-set))) (derivable empty-cl klm crule-set)))))))) ("Open"()())) (f42 () (forall (lam (kl (o form)) (forall (lam (l form) (implies (and (and (vkm kl) (kl l)) (and (derivable (union empty-cl (singleton l)) vkm crule-set) (derivable empty-cl (union (setminus vkm (singleton kl)) (singleton (singleton l))) crule-set))) (derivable empty-cl vkm crule-set)))))) ("ForallE" (vkm) (f41))) (f43 () (forall (lam (l form) (implies (and (and (vkm vkl) (vkl l)) (and (derivable (union empty-cl (singleton l)) vkm crule-set) (derivable empty-cl (union (setminus vkm (singleton vkl)) (singleton (singleton l))) crule-set))) (derivable empty-cl vkm crule-set)))) ("ForallE" (vkl)(f42))) (f44 () (implies (and (and (vkm vkl) (vkl vli)) (and (derivable (union empty-cl (singleton vli)) vkm crule-set) (derivable empty-cl (union (setminus vkm (singleton vkl)) (singleton (singleton vli))) crule-set))) (derivable empty-cl vkm crule-set)) ("ForallE"(vli) (f43))) (f4h () (and (and (vkm vkl) (vkl vli)) (and (derivable (union empty-cl (singleton vli)) vkm crule-set) (derivable empty-cl (union (setminus vkm (singleton vkl)) (singleton (singleton vli))) crule-set))) ("Open"()())) ;; --------------------------------------------------------- (l16 (l6 l5 l15 f4h) (derivable empty-cl vkm crule-set) ("ImpE"()(f4h f44))) (l17 (l5 l6) (derivable empty-cl vkm crule-set) ("OrE" ()(l14 l16 l12))) (l18 (l5) (derivable empty-cl vkm crule-set) ("ExistsE" (vli) (l5 l17))) ;; -------------------------------------------------------------------- (ltp () (derivable empty-cl vkm crule-set) ("ExistsE" (vkl)(l4 l18))) ) (proc-content schema-interpreter) (remark "Proof the step case of an eln-induction-step with help of k1 and k2.") )
input := StringTools:-Trim(FileTools:-Text:-ReadFile("AoC-2021-15-input.txt")); grid := Matrix(map(s->parse~(StringTools:-Explode(s)),StringTools:-Split(input,"\n"))): (gridw,gridl) := upperbound(grid); nbs := proc(i,j,gridsize) local out := NULL; if i < gridsize then out := out, [i+1, j]; end if; if j < gridsize then out := out, [i, j+1]; end if; if i > 1 then out := out, [i-1,j]; end if; if j > 1 then out := out, [i, j-1]; end if; return [out]; end proc: Dijkstra := proc(start, theend, grid) local pq, costsofar, curr, nb, newcost, pt, gridsize; uses priqueue; gridsize := upperbound(grid)[1]; costsofar := table(sparse=infinity): initialize(pq): insert([0,start], pq): costsofar[start] := 0: while pq[0] <> 0 do curr := extract(pq)[2]; if curr = theend then return costsofar[theend]; end if; nb := nbs(curr[], gridsize); for pt in nb do newcost := costsofar[curr] + grid[pt[]]; if newcost < costsofar[pt] then costsofar[pt] := newcost; insert([-newcost,pt], pq); end if; end do; end do: end proc: answer1 := Dijkstra([1,1], [gridl,gridw], grid); # should really do this lazily inc := a -> (a mod 9) +~ 1; biggrid:= Matrix([seq([seq((inc@@(i+j-2))(grid),j=1..5)],i=1..5)] ); (biggridw,biggridl) := upperbound(biggrid); answer2 := Dijkstra([1,1], [biggridl,biggridw], biggrid);
\chapter{Introduction} Programming has come a very long way from writing basic binary instructions. Over time, the emergence of different programming languages has widened the availability and range of applications of possible software projects. One of the most critical advances provided by newer programming languages is the level of abstraction they offer. Different features of programming languages, such as data types and garbage collection, have helped programmers move past machine-specific details to focus on more complex problems. Although software development has made significant advances over the past several decades, improved performance continues to be one of the chief concerns of both software producers and consumers. Principal concerns regarding performance include program speed and efficient resource usage, such as memory and I/O devices, and are inherent to all programming languages regardless of abstraction level. Today, large software projects can be expected to contain at least millions of lines of code\cite{google}, written by different developers in relatively isolated settings. Such large codebases provide numerous opportunities for software optimization; although individual developers can attempt to optimize certain sections of the software by hand, this approach is infeasible on a larger scale. Additionally, software development often makes tradeoffs between performance and readability; for certain software teams, code readability may be more useful in some situations than pure efficiency. Thus, the only practical approach for optimizing such large programs is through an automated process, such as an optimization pass through a compiler. One such component of software optimization is alias analysis, which attempts to determine which variables in a program refer to the same area in memory; this is used to move instructions in a way that improve performance without interfering with program execution. Several alias analyses have been proposed over the past few decades, having varying degrees of precision and time and space complexity. However, few studies have been conducted to compare these techniques with one another, nor to measure with program data to confirm their accuracy. Normally, this is out of the scope of alias analyses because these processes are static, and can only rely upon the input source code. This thesis addresses the limitations of previous studies by examining data from several benchmarks and comparing this data to commonly used alias analyses to objectively measure their accuracy. Additionally, we also gather additional program statistics to further determine which programs are the most suitable for evaluating subsequent alias analysis techniques.
module TicTacToe.GameState import TicTacToe.Player %default total %access export public export data EndState = Draw | Won Player public export data GameState = InPlay | Ended EndState Show EndState where show Draw = "Draw" show (Won p) = "Won " ++ show p Show GameState where show InPlay = "InPlay" show (Ended s) = "Ended " ++ show s
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveDataTypeable, DeriveGeneric #-} -- | -- Module : Statistics.Distribution.Poisson -- Copyright : (c) 2009, 2011 Bryan O'Sullivan -- License : BSD3 -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- The Poisson distribution. This is the discrete probability -- distribution of a number of events occurring in a fixed interval if -- these events occur with a known average rate, and occur -- independently from each other within that interval. module Statistics.Distribution.Poisson ( PoissonDistribution -- * Constructors , poisson , poissonE -- * Accessors , poissonLambda -- * References -- $references ) where import Control.Applicative import Data.Data (Data, Typeable) import GHC.Generics (Generic) import Numeric.SpecFunctions (incompleteGamma,logFactorial) import Numeric.MathFunctions.Constants (m_neg_inf) import qualified Statistics.Distribution as D import qualified Statistics.Distribution.Poisson.Internal as I import Statistics.Internal newtype PoissonDistribution = PD { poissonLambda :: Double } deriving (Eq, Typeable, Data, Generic) instance Show PoissonDistribution where showsPrec i (PD l) = defaultShow1 "poisson" l i instance Read PoissonDistribution where readPrec = defaultReadPrecM1 "poisson" poissonE instance D.Distribution PoissonDistribution where cumulative (PD lambda) x | x < 0 = 0 | isInfinite x = 1 | isNaN x = error "Statistics.Distribution.Poisson.cumulative: NaN input" | otherwise = 1 - incompleteGamma (fromIntegral (floor x + 1 :: Int)) lambda instance D.DiscreteDistr PoissonDistribution where probability (PD lambda) x = I.probability lambda (fromIntegral x) logProbability (PD lambda) i | i < 0 = m_neg_inf | otherwise = log lambda * fromIntegral i - logFactorial i - lambda instance D.Variance PoissonDistribution where variance = poissonLambda instance D.Mean PoissonDistribution where mean = poissonLambda instance D.MaybeMean PoissonDistribution where maybeMean = Just . D.mean instance D.MaybeVariance PoissonDistribution where maybeStdDev = Just . D.stdDev instance D.Entropy PoissonDistribution where entropy (PD lambda) = I.poissonEntropy lambda instance D.MaybeEntropy PoissonDistribution where maybeEntropy = Just . D.entropy -- | Create Poisson distribution. poisson :: Double -> PoissonDistribution poisson l = maybe (error $ errMsg l) id $ poissonE l -- | Create Poisson distribution. poissonE :: Double -> Maybe PoissonDistribution poissonE l | l >= 0 = Just (PD l) | otherwise = Nothing errMsg :: Double -> String errMsg l = "Statistics.Distribution.Poisson.poisson: lambda must be non-negative. Got " ++ show l -- $references -- -- * Loader, C. (2000) Fast and Accurate Computation of Binomial -- Probabilities. <http://projects.scipy.org/scipy/raw-attachment/ticket/620/loader2000Fast.pdf> -- * Adell, J., Lekuona, A., and Yu, Y. (2010) Sharp Bounds on the -- Entropy of the Poisson Law and Related Quantities -- <http://arxiv.org/pdf/1001.2897.pdf>
""" return true / false based on hard thresholding of magnitudes above bandwidth """ function boxcar_accept(proposalDistance::G, bandwidth::G) where G <: Real return abs(proposalDistance) < bandwidth end function boxcar_accept(proposalDistance::Array{G, 1}, bandwidth::Array{G, 1}) where G <: Real for (dist, bw) in zip(proposalDistance, bandwidth) if dist >= bw return false end end return true end """ return true / false based on gaussian kernel acceptance probability """ function gaussian_accept(proposalDistance::G, bandwidth::G) where G <: Real scaledDistane = proposalDistance / bandwidth return rand() < exp(-0.5 * scaledDistane ^ 2) end function gaussian_accept(proposalDistance::Array{G, 1}, bandwidth::Array{G, 1}) where G <: Real for (dist, bw) in zip(proposalDistance, bandwidth) scaledDistane = dist / bw if rand() >= exp(-0.5 * scaledDistane ^ 2) return false end end return true end
# quant-econ Solutions: Finite Markov Chains Solutions for * http://quant-econ.net/py/linear_algebra.html * http://quant-econ.net/jl/linear_algebra.html Thanks to Willem Hekman and Guanlong Ren for providing this solution. ## Solution to Exercise 1 We have an optimization problem: $$ v(x) = \max_{y,u} \{ -y'Py - u'Qu \} $$ s.t. $$ y = Ax + Bu $$ with primitives - $P$ be a symmetric and positive semidefinite $n \times n$ matrix. - $Q$ be a symmetric and positive semidefinite $m \times m$ matrix. - $A$ an $n \times n$ matrix. - $B$ an $n \times m$ matrix. The associated Lagrangian is : $$L = -y'Py - u'Qu + \lambda' \lbrack Ax + Bu - y \rbrack$$ ### 1. Differentiating Lagrangian equation w.r.t y and setting its derivative equal to zero yields $$ \frac{ \partial L}{\partial y} = - (P + P') y - \lambda = - 2 P y - \lambda = 0 \:,$$ since P is symmetric. Accordingly, the first-oder condition for maximizing L w.r.t. y implies $$ \lambda = -2 Py \:.$$ ### 2. Differentiating Lagrangian equation w.r.t. u and setting its derivative equal to zero yields $$ \frac{ \partial L}{\partial u} = - (Q + Q') u - B'\lambda = - 2Qu + B'\lambda = 0 \:.$$ Substituting $\lambda = -2 P y$ gives $$ Qu + B'Py = 0 \:.$$ Substituting the linear constraint $y = Ax + Bu$ into above equation gives $$ Qu + B'P(Ax + Bu) = 0 $$ $$ (Q + B'PB)u + B'PAx = 0 $$ which is the first-oder condition for maximizing L w.r.t. u. Thus, the optimial choice of u must satisfy $$ u = -(Q + B'PB)^{-1}B'PAx \:,$$ which follows from the definition of the first-oder conditions for Lagrangian equation. ### 3. Rewriting our problem by substituting the constraint into the objective function, we get $$ v(x) = \max_{u} \{ -(Ax+ Bu)'P(Ax+Bu) - u'Qu \} \:.$$ Since we know the optimial choice of u satisfies $ u = -(Q + B'PB)^{-1}B'PAx $, then $$ v(x) = -(Ax+ B u)'P(Ax+B u) - u'Q u \,\,\,\, with \,\,\,\, u = -(Q + B'PB)^{-1}B'PAx $$ To evaluate the function \begin{align} v(x) &= -(Ax+ B u)'P(Ax+Bu) - u'Q u \\ &= -(x'A' + u'B')P(Ax+Bu) - u'Q u \\ &= - x'A'PAx - u'B'PAx - x'A'PBu - u'B'PBu - u'Qu \\ &= - x'A'PAx - 2u'B'PAx - u'(Q + B'PB) u \end{align} For simplicity, denote by $S := (Q + B'PB)^{-1} B'PA$, then $ u = -Sx$. Regarding the second term $- 2u'B'PAx$, \begin{align} - 2u'B'PAx &= -2 x'S'B'PAx \\ & = 2 x'A'PB( Q + B'PB)^{-1} B'PAx \end{align} Notice that the term $(Q + B'PB)^{-1}$ is symmetic as both P and Q are symmetric. Regarding the third term $- u'(Q + B'PB) u$, \begin{align} - u'(Q + B'PB) u &= - x'S' (Q + B'PB)Sx \\ &= -x'A'PB(Q + B'PB)^{-1}B'PAx \end{align} Hence, the summation of second and third terms is $x'A'PB(Q + B'PB)^{-1}B'PAx$. This implies that \begin{align} v(x) &= - x'A'PAx - 2u'B'PAx - u'(Q + B'PB) u\\ &= - x'A'PAx + x'A'PB(Q + B'PB)^{-1}B'PAx \\ &= -x'[A'PA - A'PB(Q + B'PB)^{-1}B'PA] x \end{align} Therefore, the solution to the optimization problem $v(x) = -x' \tilde{P}x$ follows the above result by denoting $\tilde{P} := A'PA - A'PB(Q + B'PB)^{-1}B'PA$. ```python ```
function [cMap]=iwarmcold(varargin) % function [cMap]=iwarmcold(n) % ------------------------------------------------------------------------ % Creates the colormap data for n levels for the inverse warm-cold % colormap. % % Kevin Mattheus Moerman % [email protected] % % 2018/03/21 %------------------------------------------------------------------------ switch nargin case 0 n=250; case 1 n=varargin{1}; end cf=[213 15 37; 238 178 17;]./255; c=rot90(cf,2); h=cf; h=resampleColormap(h,3); c=resampleColormap(c,3); cMap=[c; [0 0 0]; h]; [cMap]=resampleColormap(cMap,n); %% % _*GIBBON footer text*_ % % License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE> % % GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for % image segmentation, image-based modeling, meshing, and finite element % analysis. % % Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors % % This program is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program. If not, see <http://www.gnu.org/licenses/>.
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 conj13synthconj6 : forall (lv0 : natural) (lv1 : natural), (@eq natural (plus lv0 (Succ lv1)) (plus lv1 (Succ lv0))). Admitted. QuickChick conj13synthconj6.
% ReadSegyTraceHeaderValue : Read a spedicifc trace header value % % Call: % % By Name % cdp=ReadSegyTraceHeaderValue(filename,'key','cdp'); % SourceX=ReadSegyTraceHeaderValue(filename,'key','SourceX'); % SourceY=ReadSegyTraceHeaderValue(filename,'key','SourceY'); % % % By location in Trace Header % SourceX=ReadSegyTraceHeaderValue(filename,'pos',72,'precision','int32'); % % % Call 'TraceHeaderDef(1)' to see a list of TraceHeader 'key' names % % See also WriteSegyTraceHeaderValue, TraceHeaderDef % % function hval=ReadSegyTraceHeaderValue(filename,varargin);%pos,type) pos=0; precision='int32'; ninput=nargin; % TRANSFORM VARARGING INTO PARAMETERS cargin=1; while (cargin<ninput) % ENDIAN FORMAT endian='ieee-be'; % Big Endian is default if strcmp(varargin{cargin},'endian') cargin=cargin+1; eval(['endian_tight=varargin{cargin};']) if endian_tight=='l', disp(['USING LITTLE ENDIAN TYPE']) endian='ieee-le'; else disp(['USING BIG ENDIAN TYPE']) end end if strcmp(varargin{cargin},'pos') cargin=cargin+1; eval(['pos=',num2str(varargin{cargin}),';']); disp(['Reading at header postision : pos=',num2str(pos+1)]) end if strcmp(varargin{cargin},'precision') cargin=cargin+1; eval(['precision=''',varargin{cargin},''';']); disp(['precision : ',precision]) end if strcmp(varargin{cargin},'key') cargin=cargin+1; eval(['key=''',varargin{cargin},''';']); STH=TraceHeaderDef; try pos=STH.(key).pos; precision=STH.(key).precision; catch disp(sprintf('Trace Header Value %s not defined',key)) pos=0; precision='int32'; hval=[]; return end SegymatVerbose(sprintf('key=%s, startpos=%d, precision=%s ',key,pos+1,precision)) end cargin=cargin+1; end if nargin<2 pos=0; end if nargin<3 type='int32'; end if exist('endian')==1, segyid = fopen(filename,'r',endian); else segyid = fopen(filename,'r','ieee-be'); % ALL DISK FILES ARE IN BIG end % ENDIAN FORMAT, ACCORDING TO [SegyHeader]=ReadSegyHeader(filename); Revision=SegyHeader.SegyFormatRevisionNumber; if Revision>0, Revision=1; end if (SegyHeader.DataSampleFormat>length(SegyHeader.Rev(Revision+1).DataSampleFormat)); SegymatVerbose([mfilename,' : WARNING : YOU HAVE SELECTED (OR THE FILE IS FORMATTED SUCH THAT) A DATASAMPLE FORMAT THAT IS NOT DEFINED. \nREMEBER IEEE IS NOT SPECIFIED IN THE SEGY REV0 STANDARD !']) if (Revision==0) SegymatVerbose([mfilename,' : TRYING TO USE REVISION 1 AS OPPOSED TO REVISION 0']) Revision=1; if (SegyHeader.DataSampleFormat>length(SegyHeader.Rev(Revision+1).DataSampleFormat)); SegymatVerbose([mfilename,' : FATAL ERROR : STILL THE DATASAMPLE FORMAT IS NOT SUPPRTED - EXITING (Report error to [email protected])']) else SegymatVerbose([mfilename,' : APPARENT SUCCES CHANING FROM Revision 0 to 1 - Continuing']) SegyHeader.SegyFormatRevisionNumber=1; % FORCING REVISION TO BE 1 !!! end end end FormatName=SegyHeader.Rev(Revision+1).DataSampleFormat(SegyHeader.DataSampleFormat).name; Format=SegyHeader.Rev(Revision+1).DataSampleFormat(SegyHeader.DataSampleFormat).format; BPS=SegyHeader.Rev(Revision+1).DataSampleFormat(SegyHeader.DataSampleFormat).bps; txt=['SegyRevision ',sprintf('%0.4g',Revision),', ',FormatName,'(',num2str(SegyHeader.DataSampleFormat),')']; %Revision=SegyHeader.SegyFormatRevisionNumber; %if Revision>0, Revision=1; end %FormatName=SegyHeader.Rev(Revision+1).DataSampleFormat(SegyHeader.DataSampleFormat).name; %Format=SegyHeader.Rev(Revision+1).DataSampleFormat(SegyHeader.DataSampleFormat).format; %BPS=SegyHeader.Rev(Revision+1).DataSampleFormat(SegyHeader.DataSampleFormat).bps; %txt=['SegyRevision ',sprintf('%0.4g',Revision),', %',FormatName,'(',num2str(SegyHeader.DataSampleFormat),')'];% fseek(segyid,0,'eof'); DataEnd=ftell(segyid); DataStart=3600+3200*SegyHeader.NumberOfExtTextualHeaders; fseek(segyid,DataStart,'bof'); % Go to the beginning of the file ntraces=(DataEnd-DataStart)./(240+(SegyHeader.ns)*(BPS/8)); hval=zeros(1,ntraces); for itrace=1:ntraces if ((itrace/10000)==round(itrace/10000)) progress_txt(itrace,ntraces,'Trace #') end %GOTO START OF TRACE HEADER skip=DataStart+(itrace-1)*(240+(BPS/8)*SegyHeader.ns); fseek(segyid,skip,'bof'); fseek(segyid,pos,'cof'); hval(itrace)=fread(segyid,1,precision); end fclose(segyid);
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_rng.h> #define N 65536 //the final number of nodes #define I 2 // the initial number of nodes #define MI 0 //the initial trial number #define MF 33 //(the final trial number) - 1 #define RS 35382 //seed of the random number generator int main() { FILE *fp; double delta=sqrt(1.5); int tout[]={512,1024,2048,4096,8192,16384,32768,65536,131072}; int i,j,k,l,m,t,tt; int tmp,flag; int **nb; //neighbors of each node int x; //new node int vdx; //virtual degree of the node x int *tmparr; int z; int nzsize; int *nz; int *deg; //degree of each node double degav; //average degree double *knn; //average degree of the nearest neighbors of each node double *cc; //local clustering coefficient of each node double ccav; //average local clustering coefficient char filename[100]; const gsl_rng_type * TYPE; gsl_rng * ran; gsl_rng_env_setup(); TYPE=gsl_rng_default; ran=gsl_rng_alloc(TYPE); gsl_rng_set(ran,RS); tmparr=malloc(sizeof(int)*N); nz=malloc(sizeof(int)*N); deg=malloc(sizeof(int)*N); knn=malloc(sizeof(double)*N); cc=malloc(sizeof(double)*N); nb=malloc(sizeof(int*)*N); for (i=0;i<N;i++){ nb[i]=malloc(sizeof(int)*N); } for (m=MI;m<MF;m++){ //generation of the initial network for (i=0;i<I;i++){ deg[i]=0; for (j=0;j<I;j++){ if (j!=i){ nb[i][deg[i]]=j; deg[i]++; } } } tt=0; for (t=I;t<N;t++){ //adding (t+1)-th node: copying degree step x=(int)(gsl_rng_uniform(ran)*t); vdx=1+(int)(gsl_rng_uniform(ran)*ceil(delta*deg[x])); deg[t]=0; /*//new OPA pre-adjunction rule j=0; for (i=0;i<t;i++){ if (vdx<=ceil(delta*deg[i])){ tmparr[j]=i; j++; } } z=tmparr[(int)(gsl_rng_uniform(ran)*j)]; nzsize=deg[z]+1; for (i=0;i<nzsize-1;i++){ nz[i]=nb[z][i]; } nz[nzsize-1]=z; */ /*//OPA pre-adjunction rule nzsize=0; for (i=0;i<t;i++){ if (vdx<=ceil(delta*deg[i])){ nz[nzsize]=i; nzsize++; } } */ //OPA adjunction rule tmp=t; for (i=0;i<t;i++){ if (vdx<=ceil(delta*deg[i]) && deg[i]<tmp)tmp=deg[i]; } nzsize=0; for (i=0;i<t;i++){ if (deg[i]==tmp){ nz[nzsize]=i; nzsize++; } } //choosing the targets of the new node x if (vdx>=nzsize){ for (i=0;i<nzsize;i++){ nb[nz[i]][deg[nz[i]]]=t; deg[nz[i]]++; nb[t][deg[t]]=nz[i]; deg[t]++; } } else{ for (j=0;j<vdx;j++){ i=j+(int)(gsl_rng_uniform(ran)*(nzsize-j)); nb[nz[i]][deg[nz[i]]]=t; deg[nz[i]]++; nb[t][deg[t]]=nz[i]; deg[t]++; tmp=nz[j]; nz[j]=nz[i]; nz[i]=tmp; } } //output if (t+1==tout[tt]){ //degav degav=0.0; for (i=0;i<t+1;i++){ degav+=deg[i]; } degav/=(t+1); //knn for (i=0;i<t+1;i++){ knn[i]=0.0; for (j=0;j<deg[i];j++){ knn[i]+=deg[nb[i][j]]; } if (deg[i]>0)knn[i]/=deg[i]; } //cc ccav=0.0; for (i=0;i<t+1;i++){ tmp=0; for (j=0;j<deg[i];j++){ for (k=j+1;k<deg[i];k++){ flag=0; for (l=0;l<deg[nb[i][j]];l++){ if (nb[nb[i][j]][l]==nb[i][k]){ flag=1; break; } } if (flag==1)tmp++; } } if (deg[i]>1)cc[i]=2.0*tmp/(deg[i]*(deg[i]-1)); else cc[i]=0.0; ccav+=cc[i]; } ccav/=(t+1); sprintf(filename,"id-deg-knn-cc_t%d_trial%d.txt",t+1,m); fp=fopen(filename,"w"); for (i=0;i<t+1;i++){ fprintf(fp,"%d %d %.15f %.15f\n",i,deg[i],knn[i],cc[i]); } fclose(fp); printf("m=%d t=%d degav=%f ccav=%f\n",m,t+1,degav,ccav); tt++; }//end of output }//end of t-loop }//end of m-loop free(tmparr); free(nz); free(deg); free(knn); free(cc); for (i=0;i<N;i++){ free(nb[i]); } free(nb); return 0; }
\subsection{Separable first-order Ordinary Differential Equations} For some we can write: \(\dfrac{dy}{dt}=f(t,y)\) \(\dfrac{dy}{dt}=\dfrac{g(t)}{h(y)}\) We can then do the following: \(h(y)\dfrac{dy}{dt}=g(t)\) \(\int h(y)\dfrac{dy}{dt}dt=\int g(t)dt + C\) \(\int h(y)dy=\int g(t)dt + C\) In some cases, these functions can then be integrated and solved.
open import SOAS.Common open import SOAS.Families.Core open import Categories.Object.Initial open import SOAS.Coalgebraic.Strength import SOAS.Metatheory.MetaAlgebra -- Traversals parametrised by a pointed coalgebra module SOAS.Metatheory.Traversal {T : Set} (⅀F : Functor 𝔽amiliesₛ 𝔽amiliesₛ) (⅀:Str : Strength ⅀F) (𝔛 : Familyₛ) (open SOAS.Metatheory.MetaAlgebra ⅀F 𝔛) (𝕋:Init : Initial 𝕄etaAlgebras) where open import SOAS.Context open import SOAS.Variable open import SOAS.Abstract.Hom import SOAS.Abstract.Coalgebra as →□ ; open →□.Sorted import SOAS.Abstract.Box as □ ; open □.Sorted open import SOAS.Metatheory.Algebra ⅀F open import SOAS.Metatheory.Semantics ⅀F ⅀:Str 𝔛 𝕋:Init open Strength ⅀:Str private variable Γ Δ Θ Π : Ctx α β : T 𝒫 𝒬 𝒜 : Familyₛ -- Parametrised interpretation into an internal hom module Traversal (𝒫ᴮ : Coalgₚ 𝒫)(𝑎𝑙𝑔 : ⅀ 𝒜 ⇾̣ 𝒜) (φ : 𝒫 ⇾̣ 𝒜)(χ : 𝔛 ⇾̣ 〖 𝒜 , 𝒜 〗) where open Coalgₚ 𝒫ᴮ -- Under the assumptions 𝒜 and 〖 𝒫 , 𝒜 〗 are both meta-algebras 𝒜ᵃ : MetaAlg 𝒜 𝒜ᵃ = record { 𝑎𝑙𝑔 = 𝑎𝑙𝑔 ; 𝑣𝑎𝑟 = λ x → φ (η x) ; 𝑚𝑣𝑎𝑟 = χ } Travᵃ : MetaAlg 〖 𝒫 , 𝒜 〗 Travᵃ = record { 𝑎𝑙𝑔 = λ t σ → 𝑎𝑙𝑔 (str 𝒫ᴮ 𝒜 t σ) ; 𝑣𝑎𝑟 = λ x σ → φ (σ x) ; 𝑚𝑣𝑎𝑟 = λ 𝔪 ε σ → χ 𝔪 (λ 𝔫 → ε 𝔫 σ) } -- 〖 𝒫 , 𝒜 〗 is also a pointed □-coalgebra Travᵇ : Coalg 〖 𝒫 , 𝒜 〗 Travᵇ = record { r = λ h ρ σ → h (σ ∘ ρ) ; counit = refl ; comult = refl } Travᴮ : Coalgₚ 〖 𝒫 , 𝒜 〗 Travᴮ = record { ᵇ = Travᵇ ; η = λ x σ → φ (σ x) ; r∘η = refl } open Semantics Travᵃ public renaming (𝕤𝕖𝕞 to 𝕥𝕣𝕒𝕧) -- Traversal-specific homomorphism properties that incorporate a substitution 𝕥⟨𝕧⟩ : {σ : Γ ~[ 𝒫 ]↝ Δ}{x : ℐ α Γ} → 𝕥𝕣𝕒𝕧 (𝕧𝕒𝕣 x) σ ≡ φ (σ x) 𝕥⟨𝕧⟩ {σ = σ} = cong (λ - → - σ) ⟨𝕧⟩ 𝕥⟨𝕞⟩ : {σ : Γ ~[ 𝒫 ]↝ Δ}{𝔪 : 𝔛 α Π}{ε : Π ~[ 𝕋 ]↝ Γ} → 𝕥𝕣𝕒𝕧 (𝕞𝕧𝕒𝕣 𝔪 ε) σ ≡ χ 𝔪 (λ p → 𝕥𝕣𝕒𝕧 (ε p) σ) 𝕥⟨𝕞⟩ {σ = σ} = cong (λ - → - σ) ⟨𝕞⟩ 𝕥⟨𝕒⟩ : {σ : Γ ~[ 𝒫 ]↝ Δ}{t : ⅀ 𝕋 α Γ} → 𝕥𝕣𝕒𝕧 (𝕒𝕝𝕘 t) σ ≡ 𝑎𝑙𝑔 (str 𝒫ᴮ 𝒜 (⅀₁ 𝕥𝕣𝕒𝕧 t) σ) 𝕥⟨𝕒⟩ {σ = σ} = cong (λ - → - σ) ⟨𝕒⟩ -- Congruence in the two arguments of 𝕥𝕣𝕒𝕧 𝕥≈₁ : {σ : Γ ~[ 𝒫 ]↝ Δ}{t₁ t₂ : 𝕋 α Γ} → t₁ ≡ t₂ → 𝕥𝕣𝕒𝕧 t₁ σ ≡ 𝕥𝕣𝕒𝕧 t₂ σ 𝕥≈₁ {σ = σ} p = cong (λ - → 𝕥𝕣𝕒𝕧 - σ) p 𝕥≈₂ : {σ₁ σ₂ : Γ ~[ 𝒫 ]↝ Δ}{t : 𝕋 α Γ} → ({τ : T}{x : ℐ τ Γ} → σ₁ x ≡ σ₂ x) → 𝕥𝕣𝕒𝕧 t σ₁ ≡ 𝕥𝕣𝕒𝕧 t σ₂ 𝕥≈₂ {t = t} p = cong (𝕥𝕣𝕒𝕧 t) (dext′ p) -- A pointed meta-Λ-algebra induces 𝕒𝕝𝕘 traversal into □ 𝒜 module □Traversal {𝒜} (𝒜ᵃ : MetaAlg 𝒜) = Traversal ℐᴮ (MetaAlg.𝑎𝑙𝑔 𝒜ᵃ) (MetaAlg.𝑣𝑎𝑟 𝒜ᵃ) (MetaAlg.𝑚𝑣𝑎𝑟 𝒜ᵃ) -- Corollary: □ lifts to an endofunctor on pointed meta-Λ-algebras □ᵃ : (𝒜ᵃ : MetaAlg 𝒜) → MetaAlg (□ 𝒜) □ᵃ = □Traversal.Travᵃ -- Helper records for proving equality of maps f, g out of 𝕋, -- with 0, 1 or 2 parameters record MapEq₀ (𝒜 : Familyₛ)(f g : 𝕋 ⇾̣ 𝒜) : Set where field ᵃ : MetaAlg 𝒜 open Semantics ᵃ open 𝒜 field f⟨𝑣⟩ : {x : ℐ α Γ} → f (𝕧𝕒𝕣 x) ≡ 𝑣𝑎𝑟 x f⟨𝑚⟩ : {𝔪 : 𝔛 α Π}{ε : Π ~[ 𝕋 ]↝ Γ} → f (𝕞𝕧𝕒𝕣 𝔪 ε) ≡ 𝑚𝑣𝑎𝑟 𝔪 (f ∘ ε) f⟨𝑎⟩ : {t : ⅀ 𝕋 α Γ} → f (𝕒𝕝𝕘 t) ≡ 𝑎𝑙𝑔 (⅀₁ f t) g⟨𝑣⟩ : {x : ℐ α Γ} → g (𝕧𝕒𝕣 x) ≡ 𝑣𝑎𝑟 x g⟨𝑚⟩ : {𝔪 : 𝔛 α Π}{ε : Π ~[ 𝕋 ]↝ Γ} → g (𝕞𝕧𝕒𝕣 𝔪 ε) ≡ 𝑚𝑣𝑎𝑟 𝔪 (g ∘ ε) g⟨𝑎⟩ : {t : ⅀ 𝕋 α Γ} → g (𝕒𝕝𝕘 t) ≡ 𝑎𝑙𝑔 (⅀₁ g t) fᵃ : MetaAlg⇒ 𝕋ᵃ ᵃ f fᵃ = record { ⟨𝑎𝑙𝑔⟩ = f⟨𝑎⟩ ; ⟨𝑣𝑎𝑟⟩ = f⟨𝑣⟩ ; ⟨𝑚𝑣𝑎𝑟⟩ = f⟨𝑚⟩ } gᵃ : MetaAlg⇒ 𝕋ᵃ ᵃ g gᵃ = record { ⟨𝑎𝑙𝑔⟩ = g⟨𝑎⟩ ; ⟨𝑣𝑎𝑟⟩ = g⟨𝑣⟩ ; ⟨𝑚𝑣𝑎𝑟⟩ = g⟨𝑚⟩ } ≈ : (t : 𝕋 α Γ) → f t ≡ g t ≈ t = eq fᵃ gᵃ t record MapEq₁ (𝒫ᴮ : Coalgₚ 𝒫)(𝑎𝑙𝑔 : ⅀ 𝒜 ⇾̣ 𝒜) (f g : 𝕋 ⇾̣ 〖 𝒫 , 𝒜 〗) : Set where field φ : 𝒫 ⇾̣ 𝒜 χ : 𝔛 ⇾̣ 〖 𝒜 , 𝒜 〗 open Traversal 𝒫ᴮ 𝑎𝑙𝑔 φ χ field f⟨𝑣⟩ : {σ : Γ ~[ 𝒫 ]↝ Δ}{x : ℐ α Γ} → f (𝕧𝕒𝕣 x) σ ≡ φ (σ x) f⟨𝑚⟩ : {σ : Γ ~[ 𝒫 ]↝ Δ}{𝔪 : 𝔛 α Π}{ε : Π ~[ 𝕋 ]↝ Γ} → f (𝕞𝕧𝕒𝕣 𝔪 ε) σ ≡ χ 𝔪 (λ p → f (ε p) σ) f⟨𝑎⟩ : {σ : Γ ~[ 𝒫 ]↝ Δ}{t : ⅀ 𝕋 α Γ} → f (𝕒𝕝𝕘 t) σ ≡ 𝑎𝑙𝑔 (str 𝒫ᴮ 𝒜 (⅀₁ f t) σ) g⟨𝑣⟩ : {σ : Γ ~[ 𝒫 ]↝ Δ}{x : ℐ α Γ} → g (𝕧𝕒𝕣 x) σ ≡ φ (σ x) g⟨𝑚⟩ : {σ : Γ ~[ 𝒫 ]↝ Δ}{𝔪 : 𝔛 α Π}{ε : Π ~[ 𝕋 ]↝ Γ} → g (𝕞𝕧𝕒𝕣 𝔪 ε) σ ≡ χ 𝔪 (λ p → g (ε p) σ) g⟨𝑎⟩ : {σ : Γ ~[ 𝒫 ]↝ Δ}{t : ⅀ 𝕋 α Γ} → g (𝕒𝕝𝕘 t) σ ≡ 𝑎𝑙𝑔 (str 𝒫ᴮ 𝒜 (⅀₁ g t) σ) fᵃ : MetaAlg⇒ 𝕋ᵃ Travᵃ f fᵃ = record { ⟨𝑎𝑙𝑔⟩ = dext′ f⟨𝑎⟩ ; ⟨𝑣𝑎𝑟⟩ = dext′ f⟨𝑣⟩ ; ⟨𝑚𝑣𝑎𝑟⟩ = dext′ f⟨𝑚⟩ } gᵃ : MetaAlg⇒ 𝕋ᵃ Travᵃ g gᵃ = record { ⟨𝑎𝑙𝑔⟩ = dext′ g⟨𝑎⟩ ; ⟨𝑣𝑎𝑟⟩ = dext′ g⟨𝑣⟩ ; ⟨𝑚𝑣𝑎𝑟⟩ = dext′ g⟨𝑚⟩ } ≈ : {σ : Γ ~[ 𝒫 ]↝ Δ}(t : 𝕋 α Γ) → f t σ ≡ g t σ ≈ {σ = σ} t = cong (λ - → - σ) (eq fᵃ gᵃ t) record MapEq₂ (𝒫ᴮ : Coalgₚ 𝒫)(𝒬ᴮ : Coalgₚ 𝒬)(𝑎𝑙𝑔 : ⅀ 𝒜 ⇾̣ 𝒜) (f g : 𝕋 ⇾̣ 〖 𝒫 , 〖 𝒬 , 𝒜 〗 〗) : Set where field φ : 𝒬 ⇾̣ 𝒜 ϕ : 𝒫 ⇾̣ 〖 𝒬 , 𝒜 〗 χ : 𝔛 ⇾̣ 〖 𝒜 , 𝒜 〗 open Traversal 𝒫ᴮ (Traversal.𝒜.𝑎𝑙𝑔 𝒬ᴮ 𝑎𝑙𝑔 φ χ) ϕ (λ 𝔪 ε σ → χ 𝔪 (λ 𝔫 → ε 𝔫 σ)) field f⟨𝑣⟩ : {σ : Γ ~[ 𝒫 ]↝ Δ}{ς : Δ ~[ 𝒬 ]↝ Θ}{x : ℐ α Γ} → f (𝕧𝕒𝕣 x) σ ς ≡ ϕ (σ x) ς f⟨𝑚⟩ : {σ : Γ ~[ 𝒫 ]↝ Δ}{ς : Δ ~[ 𝒬 ]↝ Θ}{𝔪 : 𝔛 α Π}{ε : Π ~[ 𝕋 ]↝ Γ} → f (𝕞𝕧𝕒𝕣 𝔪 ε) σ ς ≡ χ 𝔪 (λ 𝔫 → f (ε 𝔫) σ ς) f⟨𝑎⟩ : {σ : Γ ~[ 𝒫 ]↝ Δ}{ς : Δ ~[ 𝒬 ]↝ Θ}{t : ⅀ 𝕋 α Γ} → f (𝕒𝕝𝕘 t) σ ς ≡ 𝑎𝑙𝑔 (str 𝒬ᴮ 𝒜 (str 𝒫ᴮ 〖 𝒬 , 𝒜 〗 (⅀₁ f t) σ) ς) g⟨𝑣⟩ : {σ : Γ ~[ 𝒫 ]↝ Δ}{ς : Δ ~[ 𝒬 ]↝ Θ}{x : ℐ α Γ} → g (𝕧𝕒𝕣 x) σ ς ≡ ϕ (σ x) ς g⟨𝑚⟩ : {σ : Γ ~[ 𝒫 ]↝ Δ}{ς : Δ ~[ 𝒬 ]↝ Θ}{𝔪 : 𝔛 α Π}{ε : Π ~[ 𝕋 ]↝ Γ} → g (𝕞𝕧𝕒𝕣 𝔪 ε) σ ς ≡ χ 𝔪 (λ 𝔫 → g (ε 𝔫) σ ς) g⟨𝑎⟩ : {σ : Γ ~[ 𝒫 ]↝ Δ}{ς : Δ ~[ 𝒬 ]↝ Θ}{t : ⅀ 𝕋 α Γ} → g (𝕒𝕝𝕘 t) σ ς ≡ 𝑎𝑙𝑔 (str 𝒬ᴮ 𝒜 (str 𝒫ᴮ 〖 𝒬 , 𝒜 〗 (⅀₁ g t) σ) ς) fᵃ : MetaAlg⇒ 𝕋ᵃ Travᵃ f fᵃ = record { ⟨𝑎𝑙𝑔⟩ = dext′ (dext′ f⟨𝑎⟩) ; ⟨𝑣𝑎𝑟⟩ = dext′ (dext′ f⟨𝑣⟩) ; ⟨𝑚𝑣𝑎𝑟⟩ = dext′ (dext′ f⟨𝑚⟩) } gᵃ : MetaAlg⇒ 𝕋ᵃ Travᵃ g gᵃ = record { ⟨𝑎𝑙𝑔⟩ = dext′ (dext′ g⟨𝑎⟩) ; ⟨𝑣𝑎𝑟⟩ = dext′ (dext′ g⟨𝑣⟩) ; ⟨𝑚𝑣𝑎𝑟⟩ = dext′ (dext′ g⟨𝑚⟩) } ≈ : {σ : Γ ~[ 𝒫 ]↝ Δ}{ς : Δ ~[ 𝒬 ]↝ Θ}(t : 𝕋 α Γ) → f t σ ς ≡ g t σ ς ≈ {σ = σ}{ς} t = cong (λ - → - σ ς) (eq fᵃ gᵃ t) -- Interaction of traversal and interpretation module _ (𝒫ᴮ : Coalgₚ 𝒫)(𝒜ᵃ : MetaAlg 𝒜)(φ : 𝒫 ⇾̣ 𝒜) where open MetaAlg 𝒜ᵃ open Coalgₚ 𝒫ᴮ open Semantics 𝒜ᵃ open Traversal 𝒫ᴮ 𝑎𝑙𝑔 φ 𝑚𝑣𝑎𝑟 using (𝕥𝕣𝕒𝕧 ; 𝕥⟨𝕒⟩ ; 𝕥⟨𝕧⟩ ; 𝕥⟨𝕞⟩) open ≡-Reasoning -- Traversal with the point of 𝒫 is the same as direct interpretation 𝕥𝕣𝕒𝕧-η≈𝕤𝕖𝕞 : (φ∘η≈𝑣𝑎𝑟 : ∀{α Γ}{v : ℐ α Γ} → φ (η v) ≡ 𝑣𝑎𝑟 v){t : 𝕋 α Γ} → 𝕥𝕣𝕒𝕧 t η ≡ 𝕤𝕖𝕞 t 𝕥𝕣𝕒𝕧-η≈𝕤𝕖𝕞 φ∘η≈𝑣𝑎𝑟 {t = t} = Semantics.eq 𝒜ᵃ (record { ⟨𝑎𝑙𝑔⟩ = λ{ {t = t} → trans 𝕥⟨𝕒⟩ (cong 𝑎𝑙𝑔 (begin str 𝒫ᴮ 𝒜 (⅀₁ 𝕥𝕣𝕒𝕧 t) η ≡⟨ str-nat₁ (ηᴮ⇒ 𝒫ᴮ) (⅀₁ 𝕥𝕣𝕒𝕧 t) id ⟩ str ℐᴮ 𝒜 (⅀₁ (λ{ h ρ → h (η ∘ ρ)}) ((⅀₁ 𝕥𝕣𝕒𝕧 t))) id ≡⟨ str-unit 𝒜 ((⅀₁ (λ{ h ρ → h (η ∘ ρ)}) ((⅀₁ 𝕥𝕣𝕒𝕧 t)))) ⟩ ⅀₁ (i 𝒜) (⅀₁ (λ { h ρ → h (η ∘ ρ) }) (⅀₁ 𝕥𝕣𝕒𝕧 t)) ≡˘⟨ trans ⅀.homomorphism ⅀.homomorphism ⟩ ⅀₁ (λ t → 𝕥𝕣𝕒𝕧 t η) t ∎))} ; ⟨𝑣𝑎𝑟⟩ = λ{ {v = v} → trans 𝕥⟨𝕧⟩ φ∘η≈𝑣𝑎𝑟 } ; ⟨𝑚𝑣𝑎𝑟⟩ = λ{ {𝔪}{ε} → 𝕥⟨𝕞⟩ } }) 𝕤𝕖𝕞ᵃ⇒ t -- Traversal with the point of 𝒫 into 𝕋 is the identity 𝕥𝕣𝕒𝕧-η≈id : (𝒫ᴮ : Coalgₚ 𝒫)(open Coalgₚ 𝒫ᴮ)(φ : 𝒫 ⇾̣ 𝕋) (φ∘η≈𝑣𝑎𝑟 : ∀{α Γ}{v : ℐ α Γ} → φ (η v) ≡ 𝕧𝕒𝕣 v){t : 𝕋 α Γ} → Traversal.𝕥𝕣𝕒𝕧 𝒫ᴮ 𝕒𝕝𝕘 φ 𝕞𝕧𝕒𝕣 t η ≡ t 𝕥𝕣𝕒𝕧-η≈id 𝒫ᴮ φ φ∘η≈𝑣𝑎𝑟 = trans (𝕥𝕣𝕒𝕧-η≈𝕤𝕖𝕞 𝒫ᴮ 𝕋ᵃ φ φ∘η≈𝑣𝑎𝑟) 𝕤𝕖𝕞-id -- Corollaries for ℐ-parametrised traversals □𝕥𝕣𝕒𝕧-id≈𝕤𝕖𝕞 : (𝒜ᵃ : MetaAlg 𝒜){t : 𝕋 α Γ} → □Traversal.𝕥𝕣𝕒𝕧 𝒜ᵃ t id ≡ Semantics.𝕤𝕖𝕞 𝒜ᵃ t □𝕥𝕣𝕒𝕧-id≈𝕤𝕖𝕞 𝒜ᵃ {t} = 𝕥𝕣𝕒𝕧-η≈𝕤𝕖𝕞 ℐᴮ 𝒜ᵃ (MetaAlg.𝑣𝑎𝑟 𝒜ᵃ) refl □𝕥𝕣𝕒𝕧-id≈id : {t : 𝕋 α Γ} → □Traversal.𝕥𝕣𝕒𝕧 𝕋ᵃ t id ≡ t □𝕥𝕣𝕒𝕧-id≈id = 𝕥𝕣𝕒𝕧-η≈id ℐᴮ 𝕧𝕒𝕣 refl
[STATEMENT] lemma bounded_simple_path_image: "simple_path g \<Longrightarrow> bounded(path_image g)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. simple_path g \<Longrightarrow> bounded (path_image g) [PROOF STEP] by (metis bounded_path_image simple_path_imp_path)
\section{Extrema of a Function}\label{sec:ExtremaSection} In calculus, there is much emphasis placed on analyzing the behaviour of a function $f$ on an interval $I$. Does $f$ have a maximum value on $I$? Does it have a minimum value? How does the interval $I$ impact our discussion of extrema? % % % % % % % % % % % % % Subsections to include \input{5-applications-of-derivatives/5-2-1-local-extrema} \input{5-applications-of-derivatives/5-2-2-absolute-extrema} % Exercises are at the end of each subsection above
# Complex biophysical models in NeuroDyn ## Overview In the **NeuroDyn Python model** notebook we have seen how we can define Hodgkin-Huxley and NeuroDyn models, how to simulate them, as well as how to fit the parameters of the NeuroDyn model in order to replicate the biophysical data of the squid giant axon. Although the forms of the NeuroDyn currents are fixed to the forms of the three currents of the original Hodgkin-Huxley paper, the chip offers full flexibility in defining the dynamics of the gating variables, as well as changing the conductance parameters such as maximal conductances and reversal potentials. This flexibility allows us to use the NeuroDyn equations to replicate different types of neurons. This notebook provides an introduction to understanding how more complex biological neurons can be replicated within the NeuroDyn architecture. We start with a biological motivation, by considering the famous model of a bursting neuron Aplysia R-15 and how its dynamical structure leads to the generation of bursts of spikes. Next, we try to mimick this basic dynamical structure using purely an interconnection of Hodgkin-Huxley models. By using the fitting techniques shown in the previous notebook, this technique can be explored to design interconnections of NeuroDyn neurons that would showcase more complex dynamical behaviors such as neuronal bursting and post-inhibitory rebound. ## Neuronal bursting Bursting is one of the fundamental signalling modes of neurons and is ubiquitous in many different types of neurons and neural networks. Importantly, generating a burst of spikes after a hyperpolarizing current pulse is a crucial mechanism for the generation of intrinsic rhythms in half-center oscillators, which themselves are the building blocks of more complex central pattern generating networks. <div> <caption><center> <b>Fig. 1: </b>Bursting in subthalamic nucleus neuron (<i>Beurrier, 1999</i>) </center></caption> </div> Intrinsic generation of bursts of spikes stems from the interplay of fast processes that generate individual spikes and the slower processes that modulate the spiking behavior and define the burst duration. We have seen in the previous notebook how NeuroDyn can be set up to replicate the spiking behavior of the Hodgkin-Huxley model. In contrast, bursting models of neurons are generally more complex, consisting of several additional ionic currents that modulate the slower burst-generating process. These currents are mostly calcium-dependent and act to initiate and terminate the fast spike-generating processes dictated by the sodium and potassium currents. Since we cannot add additional ionic currents to a single NeuroDyn neuron, we can achieve a similar affect by *interconnecting* several NeuroDyn neurons through resistive connections or short circuits. To motivate this, let's first look at an example model of bursting and understand how the slower currents compare to the faster currents of the Hodgkin-Huxley model. ### Example model (Aplysia R-15) As an example, let's take a look at the Aplysia R-15 bursting neuronal model, a well-studied bursting neuron. The membrane equation has five ionic currents: the leak, sodium and potassium currents that are common to the Hodgkin-Huxley model, and in addition, an inward calcium current and an outward calcium-activated potassium current. The calcium current is slower than the potassium current and its activation has an *excitatory* effect, while the calcium-activated potassium current is significantly slower than this and has an *inhibitory* effect. The calcium and the calcium-activated potassium can be thought of as playing the roles of the standard sodium and potassium currents respectively, but in a *slower* timescale. This way, we can think of these currents being responsible for *slow excitability*, i.e. the generation of slow spikes, in contrast to the Hodgkin-Huxley currents, which generate fast spikes and therefore give rise to the *fast excitability*. This **fast + slow** structure is what we aim to recreate through the interconnection of basic Hodgkin-Huxley or NeuroDyn blocks. Let's take a look at the model to get a clearer picture of this. The membrane equation has the following form: \begin{equation} C\frac{dV}{dt} = - I_l - I_{Na} - I_K - I_{Ca} - I_{K-Ca} + I_{app}, \end{equation} The Hodgkin-Huxley currents have the same forms as previously discussed, while the two additional currents $I_{Ca}$ and $I_{K-Ca}$ are modelled as: \begin{align} \label{eq:calcium} I_{Ca} &= \bar{g}_{Ca} \, x (V - E_{Ca})\\ \label{eq:calcium_activated_potassium} I_{K-Ca} &= \bar{g}_{K-Ca} \, \frac{c}{0.5 + c} (V - E_K) \end{align} The calcium activation variable $x$ and the calcium concentration $c$ have the first-order dynamics: \begin{align} \label{eq:xdot} \tau_x \dot{x} &= x_{\infty}(V) - x \\ \label{eq:cdot} \tau_{c}\dot{c} &= (K_c x (E_{Ca} - V) - c) \end{align} First, let's check the time plot of the membrane equation to see how the neuron behaves with the default parameters: ```python # Aplysia R-15 neuronal model import matplotlib.pyplot as plt import numpy as np np.seterr(all="ignore") from scipy.integrate import solve_ivp # Alpha activation function for variable x def alphafun(V, x): if (x == 'm'): V = np.asarray(V) y = np.zeros(V.shape) y[V != 50] = 0.1 * (50 - V) / (np.exp((50 - V)/10) - 1) y[V == 50] = 1 if (x == 'h'): y = 0.07 * np.exp((25-V)/20) if (x == 'n'): V = np.asarray(V) y = np.zeros(V.shape) y[V != 55] = 0.01 * (55 - V) / (np.exp((55 - V)/10) - 1) y[V == 55] = 0.1 return y # Beta activation function for variable x def betafun(V, x): if (x == 'm'): y = 4 * np.exp((25-V)/18) if (x == 'h'): y = 1 / (np.exp((55-V)/10) + 1) if (x == 'n'): y = 0.125 * np.exp((45-V)/80) return y # x_inf(V) function for variable 'x' def x_inf(V, x): # Define constants for gating variable 'x' A = 0.15 B = -50 # Shifted voltage constants C1 = 127 / 105 C2 = 8265 / 105 # Constant for Ca dynamics Kc = 0.0085 if (x == 'x'): y = 1 / (np.exp(A * (B - V)) + 1) elif(x == 'c'): c = (Kc / (np.exp(A * (B - V)) + 1)) * (Eca - V) y = c / (0.5 + c) else: V = C1*V + C2 y = alphafun(V,x) / (alphafun(V,x) + betafun(V,x)) return y # tau(V) function for variable 'x' def tau(V, x): # Shifted voltage constants C1 = 127 / 105 C2 = 8265 / 105 V = np.asarray(V) if (x == 'x'): y = np.ones(V.shape) * 235 elif (x == 'c'): y = np.ones(V.shape) * 1 / 0.003 else: # If x == 'n' or x == 'h' V = C1*V + C2 y = 12.5 / (alphafun(V,x) + betafun(V,x)) # includes *1/lambda = 12.5 return y # Calcium dynamics constants rho = 0.0003 Kc = 0.0085 # Maximum conductances in mmho/ cm^2 gna = 4 gk = 0.3 gca = 0.004 gkca = 0.03 gl = 0.003 # Nernst potentials in mV # Note: resting potential != 0mV, not normalized as in Hodgkin-Huxley Ena = 30 Ek = -75 Eca = 140 El = -40 # Constant current stimulus (in uA / cm^2) I0 = 0 def Iapp(t): return I0 # Length of simulation (in ms) T = 80*1000 t = (0, T) # Initial state x = [V0, h0, n0, x0, c0] y0 = np.array([0, 0, 0, 0, 0]) # Dynamics of the model def ode(t, y): V, h, n, x, c = y I = Iapp(t) dV = -gna * x_inf(V,'m')**3 * h * (V - Ena) - gca * x * (V - Eca) - (gk*n**4 + gkca * c / (0.5 + c)) * (V - Ek) -gl * (V - El) + I dh = (x_inf(V,'h') - h) / tau(V,'h') dn = (x_inf(V,'n') - n) / tau(V,'n') dx = (x_inf(V,'x') - x) / tau(V,'x') dc = rho * (Kc*x*(Eca - V) - c) dy = np.asarray([dV, dh, dn, dx, dc]) return dy # Simulate the model sol = solve_ivp(ode, t, y0) plt.figure() plt.plot(sol.t, sol.y[0]) plt.show() ``` As we can see, the neuron generates a bursting waveform without an external stimulus. In order to get a better idea of the underlying dynamics, let's take a look at the gating variable forms. We want to get an understanding of the qualitative differences between the two slow currents $I_{Ca}$ and $I_{K-Ca}$ compared to the faster sodium and potassium currents. Let's first look at the steady-state functions of the gating variables (note that the $I_{K-Ca}$ has a different form to other currents, but we can analyze it in a similar way). ```python V = np.arange(Ek, Ena, 0.1) plt.figure() plt.plot(V, x_inf(V, 'm'), label='m') plt.plot(V, x_inf(V, 'h'), label='h') plt.plot(V, x_inf(V, 'n'), label='n') plt.plot(V, x_inf(V, 'x'), label='x') plt.plot(V, x_inf(V, 'c'), label='c / (0.5 + c)') plt.legend(loc = 'lower right') plt.show() ``` Notice that the activation of the calcium current $x$, and the activation of the calcium-activated potassium current $\frac{c}{0.5+c}$ activate at a lower voltage compared to the activation of sodium $m$ and activation of potassium $n$. Let's take a look at this seperately by comparing the activation of sodium with calcium, and potassium with calcium-activated potassium: ```python plt.figure() plt.plot(V, x_inf(V, 'm'), label='m') plt.plot(V, x_inf(V, 'x'), label='x') plt.legend() plt.figure() plt.plot(V, x_inf(V, 'n'), label='n') plt.plot(V, x_inf(V, 'c'), label='c / (0.5 + c)') plt.legend() plt.show() ``` We can see that both slow gating variables activate at *lower* voltages than the faster gating variables of sodium and potassium. This ensures that the threshold of the slow spiking is lower than the threshold of the fast spiking. Now, let's take a look at the time-constants of the gating variables. We can plot the time-constant functions on a log scale for a clearer overview: ```python V = np.arange(Ek, Ena, 0.1) plt.figure() plt.semilogy(V, tau(V, 'm'), label='m') plt.semilogy(V, tau(V, 'h'), label='h') plt.semilogy(V, tau(V, 'n'), label='n') plt.semilogy(V, tau(V, 'x'), label='x') plt.semilogy(V, tau(V, 'c'), label='c') plt.legend() plt.show() ``` We can clearly see the separation of the timescales: the activation variables of the calcium and calcium-activated potassium are significantly slower than the gating variables of the Hodgkin-Huxley currents. Let's take a look again one by one, comparing sodium with calcium, and potassium with calcium-activated potassium: ```python plt.figure() plt.semilogy(V, tau(V, 'm'), label='m') plt.semilogy(V, tau(V, 'x'), label='x') plt.legend() plt.figure() plt.semilogy(V, tau(V, 'n'), label='n') plt.semilogy(V, tau(V, 'c'), label='c') plt.legend() plt.show() ``` Summarizing, we can see that bursting can be achieved by adding additional currents to the Hodgkin-Huxley equation that have a similar effect as sodium and potassium, but with slower activations. These currents activate in a **lower voltage range**, ensuring that the slow threshold is below the threshold of fast spiking, and they activate on a **slower timescale**. Let's see if we can recreate this structure using only interconnections of Hodgkin-Huxley neurons, changing the parameters of the additional currents so that they retain these two important properties. ## Bursting through interconnection of Hodgkin-Huxley neurons Let's see how we can construct a bursting neurons throgh the interconnection of Hodgkin-Huxley neurons. Similar to our biological example, we would like the first neuron to act as a standard Hodgkin-Huxley model, generating *fast excitability*. In turn, the second model needs to provide the *slow excitability*, so that the interconnection of the two will lead to the creation of bursts of spikes. ### Loading the model First, let's load the model and the required modules: ```python import matplotlib.pyplot as plt from cb_models import HHModel, NeuroDynModel, ShortCircuit # **Ignore overflow warnings** import numpy as np d = np.seterr(all="ignore") ``` ### Short-circuiting neurons Now let's start by defining two Hodgkin-Huxley neurons and short circuiting them. We can use the class `ShortCircuit` for this, which takes a list of neurons, and short-circuits them so that the membrane voltages of all the neurons are equal. Alternatively, we can create a network of neurons and connect them with a low-resistance connections, mirroring the structure of multiple compartment models. The network class is described in the notebook **Networks in NeuroDyn**. Let's try this out on the default Hodgkin-Huxley models first. If we interconnect two identical neurons like this, the capacitance and all maximal conductance parameters will effectively double due to the parallel interconnection of all the elements. This means that by also doubling the injected current compared to a single Hodgkin-Huxley neuron, we would expect to see the same behavior. Let's try this out: ```python neuron1 = HHModel() neuron2 = HHModel() neuron_connection = ShortCircuit([neuron1, neuron2]) T = 200 t = (0, T) I0 = 8 iapp1 = lambda t: I0 iapp2 = lambda t: 2*I0 x01 = [0,0,0,0] x02 = x01 + [0,0,0] sol1 = neuron1.simulate(t, x01, iapp1) sol2 = neuron_connection.simulate(t, x02, iapp2) plt.figure() plt.plot(sol1.t, sol1.y[0]) plt.plot(sol2.t, sol2.y[0]) plt.show() ``` We see that the interconnection seems to work - we get the same behavior with the two-neuron interconnection as with the original neuron! Note that we need to pass an initial state vector of the appropriate size: in this case we had two neurons with six gating variable dynamics in total, and a single membrane voltage. ### Setting the parameters of the second neuron Let's see now if by appropriately changing the parameters of the second neuron, we can get the interconnection to burst. To do this, we can follow the underlying principles discussed for the Aplysia R-15 model. #### Turning off sodium inactivation To start, we can fix the sodium inactivation to $1$ so that it resembles more the calcium current with a single activation variable. This can be done by setting $\beta_h(V) = 0$ since then the $h$ equation becomes \begin{equation} \dot{h} = \alpha_h(V) (1 - h) \end{equation} so that the steady-state value is $h = 1$ for all $V$. We can do this by setting the parameter `bA` of the gating variable to `0`. ```python # Set h = 1 V = np.arange(neuron1.Ek, neuron1.Ena, 0.1) neuron2.h.bA = 0 plt.figure() plt.title("$h_{\infty}(V)$") plt.plot(V, neuron2.h.inf(V)) plt.show() ``` #### Shifting the steady-state functions of $m$ and $n$ Now, let's shift the steady-state functions of sodium and potassium activation to a lower voltage range, so that the threshold voltage is also shifted as a result. Remember that \begin{equation} m_{\infty}(V) = \frac{\alpha_m(V)}{\alpha_m(V) + \beta_m(V)} \end{equation} so that adding the same voltage shift to $\alpha_m(V + \delta V)$ and $\beta_m(V + \delta V)$ functions will shift $m_{\infty}(V + \delta V)$ by the same amount. We can do that by changing the parameter $V_h$ of the $m$ and $n$ variables, which represents the half-activation voltage. We need to change this parameter for both $\alpha(V)$ and $\beta(V)$ functions, so the corresponding variable names are `aVh` and `bVh`. We can then apply this to both $m$ and $n$ gating variables. ```python # Shift m and n for neuron 2 vshift = 20 # Shift m neuron2.m.aVh = neuron1.m.aVh - vshift neuron2.m.bVh = neuron1.m.bVh - vshift # Shift n neuron2.n.aVh = neuron1.n.aVh - vshift neuron2.n.bVh = neuron1.n.bVh - vshift plt.figure() plt.plot(V, neuron1.m.inf(V), label = 'm1') plt.plot(V, neuron2.m.inf(V), label = 'm2') plt.legend() plt.show() plt.figure() plt.plot(V, neuron1.n.inf(V), label = 'n1') plt.plot(V, neuron2.n.inf(V), label = 'n2') plt.legend() plt.show() ``` #### Scaling the time constants of $m$ and $n$ The changes we have done so far had no effect on the timescales of the gating variables $m$ and $n$ and purely affected the steady-state functions. Let's now scale the time constants of the activation variables so that they activate more slowly compared to the original Hodgkin-Huxley currents. Remember that the time constant functions are defined as \begin{equation} \tau(V) = \frac{1}{\alpha(V) + \beta(V)} \end{equation} so that for example multiplying both $\alpha(V)$ and $\beta(V)$ by $0.1$ will make the time constant $10$ times larger. We can again do this by scaling the gain constants of the $\alpha(V)$ and $\beta(V)$ functions, represented by the parameters `aA` and `bA` within the gating variables. ```python # Scaling the time constants for m and n in neuron 2 t_scale1 = 15 t_scale2 = 30 # Scale the timescale for neuron 2 m variable neuron2.m.aA = neuron1.m.aA / t_scale1 neuron2.m.bA = neuron1.m.bA / t_scale1 # Scale the timescale for neuron 2 n variable neuron2.n.aA = neuron1.n.aA / t_scale2 neuron2.n.bA = neuron1.n.bA / t_scale2 plt.figure() plt.semilogy(V, neuron1.m.tau(V), label = 'm1') plt.semilogy(V, neuron2.m.tau(V), label = 'm2') plt.legend() plt.show() plt.figure() plt.semilogy(V, neuron1.n.tau(V), label = 'n1') plt.semilogy(V, neuron2.n.tau(V), label = 'n2') plt.legend() plt.show() ``` #### Setting the maximal conductances and reversal potentials Finally, we need to change the maximal conductance parameters, as well as the reversal potentials. Firstly, we can set the maximal conductance of the leak to $g_l = 0$ since the leak current can be solely provided by the first neuron. Secondly, we can set the reversal potential for the sodium current to be higher, so that it reflects the calcium reversal potential for which $E_{Ca} > E_{Na}$. For the potassium current, we keep the same reversal potential as we are trying to emulate a slow *potassium* current. The maximal conductance parameters of the sodium and potassium we can use as the control variables in order to tune the bursting oscillation. ```python # Turn off leak current for neuron 2 neuron2.gl = 0 # Set reversal potential for neuron 2 sodium to calcium reversal neuron2.Ena = 200 # Change maximal conductances of sodium and potassium for neuron 2 neuron2.gna = 1 neuron2.gk = 3 ``` #### Simulating the interconnection Let's now look at how the system behaves over time. We can go back to the previous sections and change the parameters to see how it changes the oscillating behavior. ```python # Simulate HH short-circuit T = 2000 t = (0, T) I0 = -5 iapp = lambda t: I0 x0 = [0,0,0,0,0,0,0] sol = neuron_connection.simulate(t, x0, iapp) plt.figure() plt.plot(sol.t, sol.y[0]) plt.show() ``` We should now observe that the interconnected system exhibits intrinsic bursting! You can try changing the parameters of the two slow currents in order to see how they affect the bursting behavior, as well as try obtaining different types of bursting waveforms. ### Post-inhibitory rebound An important consequence of the internal burst-generating dynamics is what is called a **post-inhibitory rebound** (PIR). This is a phenomenon where an initially silent neuron can fire a transient burst of spikes after a prolonged period of hyperpolarization. This mechanism is fundamental for the generation of sustained oscillations in half-center oscillators, where mutually inhibiting neurons hyperpolarize each other as a result of firing a burst of spikes. Let's see how our model behaves in response to a long hyperpolarizing pulse: ```python # Post-inhibitory rebound def pulse(t, t_start, t_length, mag): I = (t>=t_start)*mag - (t>=(t_start+t_length))*mag return I T = 3000 t = (0, T) I0 = -6 pulse_mag = 2 def Iapp(t): t_start = T / 2 t_length = T / 5 return I0 - pulse(t, t_start, t_length, pulse_mag) x0 = [0,0,0,0,0,0,0] sol = neuron_connection.simulate(t, x0, Iapp) plt.figure() plt.plot(sol.t, sol.y[0]) plt.show() ``` We can try different values of the pulse magnitude - you should notice that for a small pulse the system will generate a small rebound bump. In this case, the rebound is not large enough to activate the fast spiking dynamics and the system goes back to rest after the transient. However, if the pulse is large enough the rebound will move the system through the spiking regime before returning to rest, thus creating a transient burst. We can use the post-inhibitory rebound as the basic mechanism for generating bursting oscillations in inhibitory networks. ## Next step: bursting through interconnection of NeuroDyn circuits The procedure discussed so far can be used as a first step to designing more complex neuronal behaviors in NeuroDyn hardware. By using the fitting procedures described in the **NeuroDyn Python model** notebook, we can first design an interconnection of Hodgkin-Huxley models that would give us the desired behavior of the system, and then translate the Hodgkin-Huxley parameters to the parameters that can be set within the hardware. The additional challenge here is ensuring that the parameters can be fitted within the physical constraints. Due to this, we might find that certain regimes may not be directly translated to the NeuroDyn equations. Importantly, remember that the current $I_{master}$ in NeuroDyn determines the effective scale of the maximal conductances and $\alpha$ and $\beta$ coefficients. By decreasing the $I_{master}$ of a neuron, its time-scale is also effictively decreased, and we can use this to design the slower neuron. ```python ```
lemma connected_Icc[simp]: "connected {a..b}" for a b :: "'a::linear_continuum_topology"
%!TEX root = ceres.tex \chapter{Building Ceres} \label{chapter:build} Ceres source code and documentation is hosted at \url{http://code.google.com/p/ceres-solver/}. \section{Dependencies} Ceres relies on a number of open source libraries, some of which are optional. However, we recommend that you start out by building Ceres with all its dependencies. For details on customizing the build process, please see Section~\ref{sec:custom}. \begin{enumerate} \item{\cmake~\footnote{\url{http://www.cmake.org/}}} is the cross-platform build system used by Ceres. \item{\eigen~\footnote{\url{http://eigen.tuxfamily.org}}} is used for doing all the low level matrix and linear algebra operations. \item{\glog~\footnote{\url{http://code.google.com/p/google-glog}}} is used for error checking and logging. Note: Ceres requires \texttt{glog}\ version 0.3.1 or later. Version 0.3 (which ships with Fedora 16) has a namespace bug which prevents Ceres from building. \item{\gflags~\footnote{\url{http://code.google.com/p/gflags}}} is used by the code in \texttt{examples}. It is also used by some of the tests. Strictly speaking it is not required to build the core library, we do not recommend building Ceres without it. \item{\suitesparse~\footnote{\url{http://www.cise.ufl.edu/research/sparse/suitesparse/}}} is used for sparse matrix analysis, ordering and factorization. In particular Ceres uses the \amd, \colamd\ and \cholmod\ libraries. This is an optional dependency. \item{\blas\ and \lapack} are needed by \suitesparse. We recommend either \texttt{GotoBlas2}~\footnote{\url{http://www.tacc.utexas.edu/tacc-projects/gotoblas2}} or \texttt{ATLAS}~\footnote{\url{http://math-atlas.sourceforge.net/}}, both of which ship with \blas\ and \lapack\ routines. \item{\texttt{protobuf}~\footnote{\url{http://code.google.com/p/protobuf/}}} is an optional dependency that is used for serializing and deserializing linear least squares problems to disk. This is useful for debugging and testing. Without it, some of the tests will be disabled. \end{enumerate} Currently we support building on Linux and MacOS X. Support for other platforms is forthcoming. \section{Building on Linux} We will use Ubuntu as our example platform. \begin{enumerate} \item{\cmake} \begin{minted}{bash} sudo apt-get install cmake \end{minted} \item{\gflags} can either be installed from source via the \texttt{autoconf} invocation \begin{minted}{bash} tar -xvzf gflags-2.0.tar.gz cd gflags-2.0 ./configure --prefix=/usr/local make sudo make install. \end{minted} or via the \texttt{deb} or \texttt{rpm} packages available on the \gflags\ website. \item{\glog} must be configured to use the previously installed \gflags, rather than the stripped down version that is bundled with \glog. Assuming you have it installed in \texttt{/usr/local} the following \texttt{autoconf} invocation installs it. \begin{minted}{bash} tar -xvzf glog-0.3.2.tar.gz cd glog-0.3.2 ./configure --with-gflags=/usr/local/ make sudo make install \end{minted} \item{\eigen} \begin{minted}{bash} sudo apt-get install libeigen3-dev \end{minted} \item{\suitesparse} \begin{minted}{bash} sudo apt-get install libsuitesparse-dev \end{minted} This should automatically bring in the necessary \blas\ and \lapack\ dependencies. \item{\texttt{protobuf}} \begin{minted}{bash} sudo apt-get install libprotobuf-dev \end{minted} \end{enumerate} We are now ready to build and test Ceres. Note that \texttt{cmake} requires the exact path to the \texttt{libglog.a} and \texttt{libgflag.a} \begin{minted}{bash} tar zxf ceres-solver-1.0.tar.gz mkdir ceres-bin cd ceres-bin cmake ../ceres-solver-1.0 make -j3 make test \end{minted} You can also try running the command line bundling application with one of the included problems, which comes from the University of Washington's BAL dataset~\cite{Agarwal10bal}: \begin{minted}{bash} examples/simple_bundle_adjuster \ ../ceres-solver-1.0/data/problem-16-22106-pre.txt \ \end{minted} This runs Ceres for a maximum of 10 iterations using the \denseschur\ linear solver. The output should look something like this. \clearpage \begin{minted}{bash} 0: f: 1.598216e+06 d: 0.00e+00 g: 5.67e+18 h: 0.00e+00 rho: 0.00e+00 mu: 1.00e-04 li: 0 1: f: 1.116401e+05 d: 1.49e+06 g: 1.42e+18 h: 5.48e+02 rho: 9.50e-01 mu: 3.33e-05 li: 1 2: f: 4.923547e+04 d: 6.24e+04 g: 8.57e+17 h: 3.21e+02 rho: 6.79e-01 mu: 3.18e-05 li: 1 3: f: 1.884538e+04 d: 3.04e+04 g: 1.45e+17 h: 1.25e+02 rho: 9.81e-01 mu: 1.06e-05 li: 1 4: f: 1.807384e+04 d: 7.72e+02 g: 3.88e+16 h: 6.23e+01 rho: 9.57e-01 mu: 3.53e-06 li: 1 5: f: 1.803397e+04 d: 3.99e+01 g: 1.35e+15 h: 1.16e+01 rho: 9.99e-01 mu: 1.18e-06 li: 1 6: f: 1.803390e+04 d: 6.16e-02 g: 6.69e+12 h: 7.31e-01 rho: 1.00e+00 mu: 3.93e-07 li: 1 Ceres Solver Report ------------------- Original Reduced Parameter blocks 22122 22122 Parameters 66462 66462 Residual blocks 83718 83718 Residual 167436 167436 Given Used Linear solver DENSE_SCHUR DENSE_SCHUR Preconditioner N/A N/A Ordering SCHUR SCHUR num_eliminate_blocks N/A 22106 Threads: 1 1 Linear Solver Threads: 1 1 Cost: Initial 1.598216e+06 Final 1.803390e+04 Change 1.580182e+06 Number of iterations: Successful 6 Unsuccessful 0 Total 6 Time (in seconds): Preprocessor 0.000000e+00 Minimizer 2.000000e+00 Total 2.000000e+00 Termination: FUNCTION_TOLERANCE \end{minted} \section{Building on OS X} On OS X, we recommend using the \texttt{homebrew}~\footnote{\url{http://mxcl.github.com/homebrew/}} package manager. \begin{enumerate} \item{\cmake} \begin{minted}{bash} brew install cmake \end{minted} \item{\texttt{glog}\ and \texttt{gflags}} Installing \texttt{\glog} takes also brings in \texttt{gflags} as a dependency. \begin{minted}{bash} brew install glog \end{minted} \item{\eigen} \begin{minted}{bash} brew install eigen \end{minted} \item{\suitesparse} \begin{minted}{bash} brew install suite-sparse \end{minted} \item{\texttt{protobuf}} \begin{minted}{bash} brew install protobuf \end{minted} \end{enumerate} We are now ready to build and test Ceres. \begin{minted}{bash} tar zxf ceres-solver-1.0.tar.gz mkdir ceres-bin cd ceres-bin cmake ../ceres-solver-1.0 make -j3 make test \end{minted} Like the Linux build, you should now be able to run \texttt{examples/simple\_bundle\_adjuster}. \section{Customizing the Build Process} \label{sec:custom} It is possible to reduce the libraries needed to build Ceres and customize the build process by passing appropriate flags to \texttt{cmake}. But unless you really know what you are doing, we recommend against disabling any of the following flags. \begin{enumerate} \item{\texttt{protobuf}} Protocol Buffers is a big dependency and if you do not care for the tests that depend on it and the logging support it enables, you can turn it off by using \begin{minted}{bash} -DPROTOBUF=OFF. \end{minted} \item{\suitesparse} By default, Ceres will only link to SuiteSparse if all its dependencies are present. To build Ceres without \suitesparse\ use \begin{minted}{bash} -DSUITESPARSE=OFF. \end{minted} This will also disable dependency checking for \lapack\ and \blas. This saves on binary size, but the resulting version of Ceres is not suited to large scale problems due to the lack of a sparse Cholesky solver. This will reduce Ceres' dependencies down to \eigen, \gflags\ and \glog. \item{\gflags} To build Ceres without \gflags, use \begin{minted}{bash} -DGFLAGS=OFF. \end{minted} Disabling this flag will prevent some of the example code from building. \item{Template Specializations} If you are concerned about binary size/compilation time over some small (10-20\%) performance gains in the \sparseschur\ solver, you can disable some of the template specializations by using \begin{minted}{bash} -DSCHUR_SPECIALIZATIONS=OFF. \end{minted} \item{\texttt{OpenMP}} On certain platforms like Android, multithreading with OpenMP is not supported. OpenMP support can be disabled by using \begin{minted}{bash} -DOPENMP=OFF. \end{minted} \end{enumerate}
# Copyright (c) 2018-2021, Carnegie Mellon University # See LICENSE for details EmptyCS := [ Compile.pullDataDeclsRefs, Compile.declareVars ]; BaseCS := [ c -> Compile.pullDataDeclsRefs(c), c -> Compile.fastScalarize(c), c -> UnrollCode(c), c -> FlattenCode(c), c -> UntangleChain(c), CopyPropagate, (c, opts) -> HashConsts(c, opts), ]; NoCSE := Concatenation(BaseCS, [ Compile.declareVars ]); NoSchedCSE_CS := Concatenation(BaseCS, [ (c, opts) -> BinSplit(c, opts), CSE, MarkDefUse, CopyPropagate, Compile.declareVars ]); SimpleCS := Concatenation(BaseCS, [ (c, opts) -> BinSplit(c, opts), CSE, MarkDefUse, DFSChain, CopyPropagate, Compile.declareVars ]); # IsCoarseType: checks if <coarse_t> is more general version of <fine_t> data type as defined by UnifyPair. # ex: TReal is a general version of T_Real(32) data type. IsCoarseType := (coarse_t, fine_t) -> When( coarse_t = fine_t, false, Try(UnifyPair(fine_t, coarse_t)) = [true, fine_t] ); # FixValueTypes: unifies value type with the type of surrounding expression. # SSE unparser needs this for figuring out actual data type of constants. # Fixed point backends rely on this to convert constants to fixed point... # FixValueTypes := c -> SubstTopDownRulesNR(c, rec( fixValueTypes := Rule( @@(1, Value, (x, cx) -> ObjId(Last(cx.parents)) in [add, sub, mul, bin_and, bin_xor, bin_or, absdiff, absdiff2, idiv, ddiv] and IsCoarseType(x.t, Last(cx.parents).t) and not IsPtrT(Last(cx.parents).t)), (e, cx) -> Last(cx.parents).t.value(e.v) ) )); DerefNthCode := c -> SubstTopDownRules(c, rec( deref_nth := Rule( [nth, @(1).cond(e -> not(ObjId(e) in [Value, param])), @(2)], e -> let( b := @(1).val, idx := @(2).val, Cond( ObjId(idx) = add, deref(ApplyFunc(add, [b] :: idx.args)), ObjId(idx) = sub, deref(ApplyFunc(add, [b] :: [idx.args[1], neg(idx.args)])), deref(b + idx)))) )); NthDerefCode := c -> SubstTopDownRules(c, rec( deref_var := Rule([deref, @(1, var)], e -> nth(@(1).val, TInt.value(0))), deref_add := Rule([deref, [add, @(1, var), @(2, Value)]], e -> nth(@(1).val, @(2).val)) )); BaseIndicesCS := [ c -> Compile.pullDataDeclsRefs(c), c -> Compile.fastScalarize(c), c -> UnrollCode(c), c -> FlattenCode(c), c -> UntangleChain(c), (c, opts) -> CopyPropagate.initial(c, opts), (c, opts) -> HashConsts(c, opts), c -> MarkDefUse(c), (c, opts) -> BinSplit(c, opts), c -> MarkDefUse(c), CopyPropagate, # does CSE ]; # Uses a fast (no strength reduction) final CopyPropagate pass, which # kicks out vars used only once. Sometimes (MMM?) its not good (prevents hoisting) # and then IndicesCS2 should be used. # IndicesCS0 := Concatenation(BaseIndicesCS, [ c -> MarkDefUse(c), # kicks out vars used only once or never (c, opts) -> CopyPropagate.fast(c, CopyFields(opts, rec(autoinline := true))), (c, opts) -> Cond(opts.finalBinSplit, BinSplit(c, opts), c), (c, opts) -> Cond(IsBound(opts.scheduler), opts.scheduler(c, opts), c), c -> Compile.declareVars(c), ]); # Uses a full final CopyPropagate pass, which kicks out vars used only once # and properly simplifies out redundant double butterfly structures, i.e. F(2)*F(2) # IndicesCS := Concatenation(BaseIndicesCS, [ c -> MarkDefUse(c), (c, opts) -> CopyPropagate(c, CopyFields(opts, rec(autoinline := true))), c -> MarkDefUse(c), (c, opts) -> CopyPropagate(c, CopyFields(opts, rec(autoinline := true))), (c, opts) -> Cond(opts.finalBinSplit, BinSplit(c, opts), c), (c, opts) -> Cond(IsBound(opts.scheduler), opts.scheduler(c, opts), c), c -> FixValueTypes(c), c -> Compile.declareVars(c) ]); # IndicesCS + extra CopyPropagate pass to do DAG pruning IndicesCS_Prune := Concatenation(BaseIndicesCS, [ c -> MarkDefUse(c), (c, opts) -> CopyPropagate(c, CopyFields(opts, rec(autoinline := true))), c -> MarkDefUse(c), (c, opts) -> CopyPropagate(c, CopyFields(opts, rec(autoinline := true))), (c, opts) -> Cond(opts.finalBinSplit, BinSplit(c, opts), c), (c, opts) -> Cond(IsBound(opts.scheduler), opts.scheduler(c, opts), c), c -> FixValueTypes(c), c -> Compile.declareVars(c) ]); # Does not use a final CopyPropagate pass, to keep variables used once, and # not prevent hoisting. # IndicesCS2 := Concatenation(BaseIndicesCS, [ # - kicking out variables never used is fine. # - kicking out variables used once should be a GLOBAL pass because # - right now it prevents hoisting (c, opts) -> Cond(opts.finalBinSplit, BinSplit(c, opts), c), (c, opts) -> Cond(IsBound(opts.scheduler), opts.scheduler(c, opts), c), c -> FixValueTypes(c), c -> Compile.declareVars(c) ]); IndicesCS_FMA := Concatenation(BaseIndicesCS, [ DoFMA, MarkDefUse, # (c, opts) -> CopyPropagate(c, CopyFields(opts, rec(autoinline := true))), (c, opts) -> Cond(opts.finalBinSplit, BinSplit(c, opts), c), (c, opts) -> Cond(IsBound(opts.scheduler), opts.scheduler(c, opts), c), c -> FixValueTypes(c), c -> Compile.declareVars(c) ]); IndicesCS_Fixed := (bitwidth, fracbits) -> ( IndicesCS :: [ c -> FixedPointCode(c, bitwidth, fracbits) ] ); IndicesCS_FixedNew := IndicesCS :: [ (c, opts) -> FixedPointCode2(c) ]; IndicesCS2_FMA := Concatenation(BaseIndicesCS, [ DoFMA, CopyPropagate, (c, opts) -> Cond(opts.finalBinSplit, BinSplit(c, opts), c), (c, opts) -> Cond(IsBound(opts.scheduler), opts.scheduler(c, opts), c), c -> FixValueTypes(c), c -> Compile.declareVars(c) ]); IndicesCS_CXFMA := Concatenation(BaseIndicesCS, [ DoCXFMA, MarkDefUse, # (c, opts) -> CopyPropagate(c, CopyFields(opts, rec(autoinline := true))), (c, opts) -> Cond(opts.finalBinSplit, BinSplit(c, opts), c), (c, opts) -> Cond(IsBound(opts.scheduler), opts.scheduler(c, opts), c), c -> FixValueTypes(c), c -> Compile.declareVars(c) ]); IndicesCS2_CXFMA := Concatenation(BaseIndicesCS, [ DoCXFMA, CopyPropagate, (c, opts) -> Cond(opts.finalBinSplit, BinSplit(c, opts), c), (c, opts) -> Cond(IsBound(opts.scheduler), opts.scheduler(c, opts), c), c -> FixValueTypes(c), c -> Compile.declareVars(c) ]); # OLD STUFF # RCSE_CS := Concatenation(BaseCS, [ # (c, opts) -> BinSplit(c, opts), RCSE, # MarkDefUse, DFSChain, CopyPropagate, # Compile.declareVars # ]); # FFTW_CS := Concatenation(BaseCS, [ # (c, opts) -> BinSplit(c, opts), RCSE, # MarkDefUse, FFTWScheduleAssignments, CopyPropagate, # Compile.declareVars # ]); # # FMA # FMA_CS := Concatenation(BaseCS, [ (c, opts) -> BinSplit(c, opts), (c, opts) -> BinSplit(c, opts), CSE, MarkDefUse, DFSChain, CopyPropagate, DoFMA, Compile.declareVars ]); FMA_FFTW_CS := Concatenation(BaseCS, [ (c, opts) -> BinSplit(c, opts), (c, opts) -> BinSplit(c, opts), CSE, MarkDefUse, FMA, ClearDefUse, MarkDefUse, FFTWScheduleAssignments, CopyPropagate, DoFMA, Compile.declareVars ]); # # seems to be slower # NewUnrollCS := [ # myUnrollCode, CopyPropagate, # HashConstantsCode, # MarkDefUse, DFSChain, CopyPropagate, # Compile.declareVars # ]; # CompileStrategyFull := [ # Compile.pullDataDeclsRefs, # UnrollCode, FlattenCode, SSA, CopyPropagate, # FoldIf, SSA, CopyPropagate, # Remove dead IF branches # # Compile.scalarize, # SSA, CopyPropagate, # EliminatePhiSSA, CopyPropagate, # Eliminate Phi functions # HashConstantsCode, # (c, opts) -> BinSplit(c, opts), CSE, CopyPropagate, # CSE # MarkDefUse, #DFSChain, # Compile.declareVars # ]; # This compile strategy is safe for IFs inside basic blocks. but does not # fully perform copy propagation. Thus the name 'conservative'. To fully and # safely optimize, we need to extend the CopyPropagate pass # conservativeCompileSSA := [ Compile.pullDataDeclsRefs, # -- 1 Compile.fastScalarize, # -- 2 UnrollCode, # -- 3 FlattenCode, # -- 4 # SimpIndicesCode, # -- 5 (YSV: simpIndices was disabled before, not clear why) FoldIf, # -- 6 FoldIf happens before SSA and SSA has to happen before Copyprop SSA, # -- 7 UntangleChain, # -- 8 (c, opts) -> CopyPropagate(c, CopyFields(opts, rec(doScalarReplacement:=false))), # -- 9 (c, opts) -> HashConsts(c, opts), # -- 10 (c, opts) -> When(IsBound(opts.useDeref) and opts.useDeref, DerefNthCode(c), c), # -- 11 MarkPreds, (c, opts) -> BinSplit(c, opts), # -- 12, 13 MarkDefUse, (c, opts) -> CopyPropagate(c, CopyFields(opts, rec(doScalarReplacement:=false))), # 14 EliminatePhiSSA, Compile.declareVars ]; CompileSSA := [ Compile.pullDataDeclsRefs, Compile.fastScalarize, UnrollCode, FlattenCode, FoldIf, UntangleChain, CopyPropagate, SSA, (c, opts) -> HashConsts(c, opts), (c, opts) -> When(IsBound(opts.useDeref) and opts.useDeref, DerefNthCode(c), c), MarkPreds, (c, opts) -> BinSplit(c, opts), ClearDefUse, MarkDefUse, CopyPropagate, EliminatePhiSSA, CopyPropagate, Compile.declareVars ];
During the era of log floating , <unk> sometimes occurred when logs struck an obstacle . Log rafts floating down the West Branch had to pass through chutes in canal dams . The rafts were commonly 28 feet ( 9 m ) wide — narrow enough to pass through the chutes — and 150 feet ( 46 m ) to 200 feet ( 61 m ) long . In 1874 , a large raft got wedged in the chute of the Dunnstown Dam and caused a jam that blocked the channel from bank to bank with a pile of logs 16 feet ( 5 m ) high . The jam eventually trapped another 200 log rafts , and 2 canal boats , The Mammoth of Newport and The Sarah Dunbar .
[STATEMENT] lemma NSLIMSEQ_minus: "X \<longlonglongrightarrow>\<^sub>N\<^sub>S a \<Longrightarrow> (\<lambda>n. - X n) \<longlonglongrightarrow>\<^sub>N\<^sub>S - a" [PROOF STATE] proof (prove) goal (1 subgoal): 1. X \<longlonglongrightarrow>\<^sub>N\<^sub>S a \<Longrightarrow> (\<lambda>n. - X n) \<longlonglongrightarrow>\<^sub>N\<^sub>S - a [PROOF STEP] by (auto simp add: NSLIMSEQ_def)
You are currently browsing the tag archive for the ‘Atonement’ tag. Based on this verse, if Caleb’s brother was the son of Kenaz, would that not imply Caleb was the son of Kenaz? This would fit with the title of “the Kenizzite.” Although this does not fit with the prior established relationship to the tribe of Judah because Kenaz was a descendant of Esau. Personally, I do not have the answer as to whether Caleb was a Jew or Gentile. What we do know is that he was the head of the tribe of Judah, that he fully followed G-d, he had a different spirit, and he received an inheritance in the land. The most important aspect of Caleb, and what was emphasized throughout Scripture was his actions, not his ethnicity. Paul toiled in sharing with many that being a Jew is not the way to eternal life. It is only through the blood of Messiah Yeshua. Speaking of blood, the following verse is an interesting description of blood and atonement. The context of this verse was the various rules regarding a murderer, manslayer, and avenger of blood. Clearly Numbers 35:33 contains the additional command not to pollute the land through bloodshed. Although the second part of the verse implies that atonement cannot occur without blood. Nor can there be the forgiveness of sins without blood. (Heb. 9:22) Added onto the truth of blood as a requirement for atonement, Numbers 35:33 specified the source of atoning blood as “of the one who shed it.” Essentially blood pollutes AND atones? It is a bit easier to understand by adding more detail based on context. In other words, innocent blood pollutes the land because of the murderer’s sin, but it is the blood of the murderer (or administering of justice) that atones for the land. The Hebrew word for “shed” is shaphak and the first usage is in Genesis 9. This verse further explains the execution of justice G-d requires in regard to a murderer. Does it not make sense why the shedding of innocent blood “pollutes the land?” The word for pollute in Hebrew is chaneph which literally means “to be profaned.”1 Since man was made in G-d’s own image an act of murder also profanes G-d in addition to the land. Both sins bear the death penalty. Both sins require blood for atonement. If the blood of an animal or a convicted murderer can provide atonement than how much more can the blood of an innocent righteous man provide atonement in an eternal sense? “Said R. Ammi, Wherefore is the account of Miriam’s death placed next to the [laws of the] red heifer? To inform you that even as the red heifer afforded atonement [by the ritual use of its ashes], so does the death of the righteous afford atonement [for the living they have left behind]. Stringing together the various passages describing atonement and including quotes from Talumdic Sages reveal the nature of G-d’s justice, conditions of atonement, and the role His Son plays. The more we study these passages the more we will understand the incredible sacrifice of Messiah Yeshua. And hopefully these passages will fan the passionate flames in our hearts to sanctify His Name in this world and proclaim the Gospel!
[STATEMENT] lemma poly_eq_by_eval: fixes P Q :: "'a::{comm_ring_1,ring_no_zero_divisors,ring_char_0} poly" assumes h: "\<And>x. poly P x = poly Q x" shows "P = Q" [PROOF STATE] proof (prove) goal (1 subgoal): 1. P = Q [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. P = Q [PROOF STEP] have "poly P = poly Q" [PROOF STATE] proof (prove) goal (1 subgoal): 1. poly P = poly Q [PROOF STEP] using h [PROOF STATE] proof (prove) using this: poly P ?x = poly Q ?x goal (1 subgoal): 1. poly P = poly Q [PROOF STEP] by fast [PROOF STATE] proof (state) this: poly P = poly Q goal (1 subgoal): 1. P = Q [PROOF STEP] thus ?thesis [PROOF STATE] proof (prove) using this: poly P = poly Q goal (1 subgoal): 1. P = Q [PROOF STEP] by (auto simp: poly_eq_poly_eq_iff) [PROOF STATE] proof (state) this: P = Q goal: No subgoals! [PROOF STEP] qed
Lady-to-Lady Conference is an extraordinary conference where the presence of God is experienced tangibly and has a special place in God's heart. The conference carries with it an experience that words cannot perfectly express. While we will love to describe this experience, we are equally aware that no words could perfectly express such experience hence why you will have to be present to experience it yourself. All we can say is that the experience inspires and brings about Hope, Faith and Love. Each year is different and 2018 edition will not be an exception. The theme for 2018 is The Glory ​. You will be clothed in His Glory that will separate and position you for greater works, which will be evident for all to see. As it is written, "The glory of the latter will surely surpass the former". Glory! Are you ready to move to the next level in aAre you pregnant with a dream, a vision or an idea that you are ready to birth? Then Lady-to-Lady conference 2018 is the right place to be. Lady-to-Lady will continually be on a mission to impact ladies to be confident in who they are in Christ and live out their God given purpose here on earth.
!*********************************************************************** ! * SUBROUTINE BRINT5 (IA,IB,IC,ID,NU,TEGRAL) ! * ! Returns integrals for the transverse photon interaction. * ! Integrals are stored in ordered lists. If the integral cannot * ! be read from a list, it is computed by calling BRINTF. * ! * ! Observ that it is not possible to use more than 100 orbitals when * ! the Breit interaction is included. If 100 orbitals are used then * ! NU <= 19. * ! * ! Call(s) to: [LIB92]: ALLOC, RALLOC. * ! [RCI92]: BRINTF * ! * ! Written by Farid A Parpia Last update: 09 Oct 1992 * ! * !*********************************************************************** !...Translated by Pacific-Sierra Research 77to90 4.3E 14:04:58 1/ 3/07 !...Modified by Charlotte Froese Fischer ! Gediminas Gaigalas 10/05/17 !----------------------------------------------- ! M o d u l e s !----------------------------------------------- USE vast_kind_param, ONLY: DOUBLE USE memory_man USE bilst_C USE orb_C, ONLY: ncf, nw, iqa !----------------------------------------------- ! I n t e r f a c e B l o c k s !----------------------------------------------- USE brintf_I IMPLICIT NONE !----------------------------------------------- ! D u m m y A r g u m e n t s !----------------------------------------------- INTEGER, INTENT(IN) :: ia, ib, ic, id, nu REAL(DOUBLE), INTENT(out) :: tegral !----------------------------------------------- ! L o c a l P a r a m e t e r s !----------------------------------------------- LOGICAL :: FOUND INTEGER :: key, index, loc, ju, jl, jm, newsiz, i !----------------------------------------------- ! KEY = NW + 1 ! ! Compute the integral label ! INDEX = (((NU*KEY+IA)*KEY+IB)*KEY+IC)*KEY+ID ! IF (.NOT. FIRST(5)) THEN ! ! This branch is executed on all entries except the first ! IF (INDEX .GT. INDTP5(NTPI(5))) THEN ! ! The index is greater than the largest stored ! FOUND = .FALSE. LOC = NTPI(5) ! ELSEIF (INDEX .LT. INDTP5(1)) THEN ! ! The index is less than the smallest stored ! FOUND = .FALSE. LOC = 0 ! ELSE ! ! The index is within the range of the indices stored; search ! for it in the list of indices ! JU = NTPI(5) JL = 1 1 IF (JU-JL .GT. 1) THEN JM = (JU+JL)/2 IF (INDTP5(JM) .GT. INDEX) THEN JU = JM ELSE JL = JM ENDIF GOTO 1 ! ELSE ! ! The range is bracketed to the extent possible ! IF (INDEX .EQ. INDTP5(JU)) THEN ! FOUND = .TRUE. LOC = JU ! ELSEIF (INDEX .EQ. INDTP5(JL)) THEN ! FOUND = .TRUE. LOC = JL ! ELSE ! FOUND = .FALSE. LOC = JL ! ENDIF ! ENDIF ! ENDIF ! IF (FOUND) THEN ! ! Found the index in the list; return the value of the integral ! from storage ! TEGRAL = VALTP5(LOC) ! ELSE ! ! Index not found; compute the integral ! TEGRAL = BRINTF (5,IA,IB,IC,ID,NU) ! ! Increment the integral counter ! NTPI(5) = NTPI(5)+1 ! ! Increase array length by half the present length if the latter ! is inadequate to store another pair ! ! IF (NTPI(5) .GT. NDTPA(5)) THEN NEWSIZ = NDTPA(5)+NDTPA(5)/2 CALL RALLOC (INDTP5,NEWSIZ,'INDTP5', 'BRINT5') CALL RALLOC (VALTP5,NEWSIZ,'VALTP5', 'BRINT5') NDTPA(5)= NEWSIZ ENDIF DO 4 I = NTPI(5),LOC+2,-1 INDTP5(I) = INDTP5(I-1) VALTP5(I) = VALTP5(I-1) 4 CONTINUE ! ! Put the new index and value into storage ! INDTP5(LOC+1) = INDEX VALTP5(LOC+1) = TEGRAL ! ENDIF ! ELSE ! ! This branch is executed only once per type of integral ! FIRST(5) = .FALSE. ! ! Designate the initial storage for arrays INDTPx and VALTPx; ! Array NDTPA stores the array dimensions ! NDTPA(5) = 10000 ! ! Compute the integral's value ! TEGRAL = BRINTF (5,IA,IB,IC,ID,NU) ! ! Initialise the integral counter ! NTPI(5) = 1 ! ! Store the integral and its value ! CALL ALLOC (INDTP5,NDTPA(5),'INDTP5', 'BRINT5') CALL ALLOC (VALTP5,NDTPA(5),'VALTP5', 'BRINT5') INDTP5(1) = INDEX VALTP5(1) = TEGRAL ! ENDIF ! RETURN END
State Before: M : Type u_1 A : Type ?u.43722 B : Type ?u.43725 inst✝ : MulOneClass M S T : Submonoid M ⊢ ∀ {x : M}, x ∈ S → x ∈ S ⊔ T State After: M : Type u_1 A : Type ?u.43722 B : Type ?u.43725 inst✝ : MulOneClass M S T : Submonoid M ⊢ S ≤ S ⊔ T Tactic: rw [←SetLike.le_def] State Before: M : Type u_1 A : Type ?u.43722 B : Type ?u.43725 inst✝ : MulOneClass M S T : Submonoid M ⊢ S ≤ S ⊔ T State After: no goals Tactic: exact le_sup_left
If $f$ is a continuous function on the triangle with vertices $a$, $b$, and $c$, and $c$ is a multiple of $b - a$, then the sum of the integrals of $f$ around the three sides of the triangle is zero.
Donate to Stanmore Public School's Building Fund before June 30 and claim a deduction when submitting your tax return for this financial year. Our Building Fund is a great opportunity to actively participate in the growth of your children’s school. The Building Fund operates on a non-profit basis and is a Deductible Gift Recipient (DGR) as defined by the ATO. Therefore any donation over $2.00 to the building fund is tax deductible. The use of the school building fund is solely for providing money to acquire, construct or maintain the school buildings for the purposes of using that building as a school. An example of this would be the funding of the Kitchen for the SAKG program. A school building fund cannot provide funds for a non-school building, the non-school use of a school building or other facilities that are not buildings. Note: This information does not constitute financial advice. If you have any questions about the tax benefits you should seek your own independent advice. Please provide your personal details for the tax receipt. Please fill in your city or suburb. Note: A PayPal transaction fee of 2.6% + $0.30 is added to each donation to cover our costs. Card transactions are processed securely via PayPal. No PayPal account is required. Just select "Pay with Debit or Credit Card" on the PayPal page.
-- | -- Module : Control.Monad.Bayes.Class -- Description : Types for probabilistic modelling -- Copyright : (c) Adam Scibior, 2015-2020 -- License : MIT -- Maintainer : [email protected] -- Stability : experimental -- Portability : GHC -- -- This module defines 'MonadInfer', which can be used to represent a simple model -- like the following: -- -- @ -- import Control.Monad (when) -- import Control.Monad.Bayes.Class -- -- model :: MonadInfer m => m Bool -- model = do -- rain <- bernoulli 0.3 -- sprinkler <- -- bernoulli $ -- if rain -- then 0.1 -- else 0.4 -- let wetProb = -- case (rain, sprinkler) of -- (True, True) -> 0.98 -- (True, False) -> 0.80 -- (False, True) -> 0.90 -- (False, False) -> 0.00 -- score wetProb -- return rain -- @ module Control.Monad.Bayes.Class ( MonadSample, random, uniform, normal, gamma, beta, bernoulli, categorical, logCategorical, uniformD, geometric, poisson, dirichlet, MonadCond, score, factor, condition, MonadInfer, normalPdf, ) where import Control.Monad (when) import Control.Monad.Trans.Class import Control.Monad.Trans.Cont import Control.Monad.Trans.Identity import Control.Monad.Trans.List import Control.Monad.Trans.Maybe import Control.Monad.Trans.RWS hiding (tell) import Control.Monad.Trans.Reader import Control.Monad.Trans.State import Control.Monad.Trans.Writer import qualified Data.Vector as V import Data.Vector.Generic as VG import Numeric.Log import Statistics.Distribution import Statistics.Distribution.Beta (betaDistr) import Statistics.Distribution.Gamma (gammaDistr) import Statistics.Distribution.Geometric (geometric0) import Statistics.Distribution.Normal (normalDistr) import qualified Statistics.Distribution.Poisson as Poisson import Statistics.Distribution.Uniform (uniformDistr) -- | Monads that can draw random variables. class Monad m => MonadSample m where -- | Draw from a uniform distribution. random :: -- | \(\sim \mathcal{U}(0, 1)\) m Double -- | Draw from a uniform distribution. uniform :: -- | lower bound a Double -> -- | upper bound b Double -> -- | \(\sim \mathcal{U}(a, b)\). m Double uniform a b = draw (uniformDistr a b) -- | Draw from a normal distribution. normal :: -- | mean μ Double -> -- | standard deviation σ Double -> -- | \(\sim \mathcal{N}(\mu, \sigma^2)\) m Double normal m s = draw (normalDistr m s) -- | Draw from a gamma distribution. gamma :: -- | shape k Double -> -- | scale θ Double -> -- | \(\sim \Gamma(k, \theta)\) m Double gamma shape scale = draw (gammaDistr shape scale) -- | Draw from a beta distribution. beta :: -- | shape α Double -> -- | shape β Double -> -- | \(\sim \mathrm{Beta}(\alpha, \beta)\) m Double beta a b = draw (betaDistr a b) -- | Draw from a Bernoulli distribution. bernoulli :: -- | probability p Double -> -- | \(\sim \mathrm{B}(1, p)\) m Bool bernoulli p = fmap (< p) random -- | Draw from a categorical distribution. categorical :: Vector v Double => -- | event probabilities v Double -> -- | outcome category m Int categorical ps = fromPMF (ps !) -- | Draw from a categorical distribution in the log domain. logCategorical :: (Vector v (Log Double), Vector v Double) => -- | event probabilities v (Log Double) -> -- | outcome category m Int logCategorical = categorical . VG.map (exp . ln) -- | Draw from a discrete uniform distribution. uniformD :: -- | observable outcomes @xs@ [a] -> -- | \(\sim \mathcal{U}\{\mathrm{xs}\}\) m a uniformD xs = do let n = Prelude.length xs i <- categorical $ V.replicate n (1 / fromIntegral n) return (xs !! i) -- | Draw from a geometric distribution. geometric :: -- | success rate p Double -> -- | \(\sim\) number of failed Bernoulli trials with success probability p before first success m Int geometric = discrete . geometric0 -- | Draw from a Poisson distribution. poisson :: -- | parameter λ Double -> -- | \(\sim \mathrm{Pois}(\lambda)\) m Int poisson = discrete . Poisson.poisson -- | Draw from a Dirichlet distribution. dirichlet :: Vector v Double => -- | concentration parameters @as@ v Double -> -- | \(\sim \mathrm{Dir}(\mathrm{as})\) m (v Double) dirichlet as = do xs <- VG.mapM (`gamma` 1) as let s = VG.sum xs let ys = VG.map (/ s) xs return ys -- | Draw from a continuous distribution using the inverse cumulative density -- function. draw :: (ContDistr d, MonadSample m) => d -> m Double draw d = fmap (quantile d) random -- | Draw from a discrete distribution using a sequence of draws from -- Bernoulli. fromPMF :: MonadSample m => (Int -> Double) -> m Int fromPMF p = f 0 1 where f i r = do when (r < 0) $ error "fromPMF: total PMF above 1" let q = p i when (q < 0 || q > 1) $ error "fromPMF: invalid probability value" b <- bernoulli (q / r) if b then pure i else f (i + 1) (r - q) -- | Draw from a discrete distributions using the probability mass function. discrete :: (DiscreteDistr d, MonadSample m) => d -> m Int discrete = fromPMF . probability -- | Monads that can score different execution paths. class Monad m => MonadCond m where -- | Record a likelihood. score :: -- | likelihood of the execution path Log Double -> m () -- | Synonym for 'score'. factor :: MonadCond m => -- | likelihood of the execution path Log Double -> m () factor = score -- | Hard conditioning. condition :: MonadCond m => Bool -> m () condition b = score $ if b then 1 else 0 -- | Monads that support both sampling and scoring. class (MonadSample m, MonadCond m) => MonadInfer m -- | Probability density function of the normal distribution. normalPdf :: -- | mean μ Double -> -- | standard deviation σ Double -> -- | sample x Double -> -- | relative likelihood of observing sample x in \(\mathcal{N}(\mu, \sigma^2)\) Log Double normalPdf mu sigma x = Exp $ logDensity (normalDistr mu sigma) x ---------------------------------------------------------------------------- -- Instances that lift probabilistic effects to standard tranformers. instance MonadSample m => MonadSample (IdentityT m) where random = lift random bernoulli = lift . bernoulli instance MonadCond m => MonadCond (IdentityT m) where score = lift . score instance MonadInfer m => MonadInfer (IdentityT m) instance MonadSample m => MonadSample (MaybeT m) where random = lift random instance MonadCond m => MonadCond (MaybeT m) where score = lift . score instance MonadInfer m => MonadInfer (MaybeT m) instance MonadSample m => MonadSample (ReaderT r m) where random = lift random bernoulli = lift . bernoulli instance MonadCond m => MonadCond (ReaderT r m) where score = lift . score instance MonadInfer m => MonadInfer (ReaderT r m) instance (Monoid w, MonadSample m) => MonadSample (WriterT w m) where random = lift random bernoulli = lift . bernoulli categorical = lift . categorical instance (Monoid w, MonadCond m) => MonadCond (WriterT w m) where score = lift . score instance (Monoid w, MonadInfer m) => MonadInfer (WriterT w m) instance MonadSample m => MonadSample (StateT s m) where random = lift random bernoulli = lift . bernoulli categorical = lift . categorical instance MonadCond m => MonadCond (StateT s m) where score = lift . score instance MonadInfer m => MonadInfer (StateT s m) instance (MonadSample m, Monoid w) => MonadSample (RWST r w s m) where random = lift random instance (MonadCond m, Monoid w) => MonadCond (RWST r w s m) where score = lift . score instance (MonadInfer m, Monoid w) => MonadInfer (RWST r w s m) instance MonadSample m => MonadSample (ListT m) where random = lift random bernoulli = lift . bernoulli categorical = lift . categorical instance MonadCond m => MonadCond (ListT m) where score = lift . score instance MonadInfer m => MonadInfer (ListT m) instance MonadSample m => MonadSample (ContT r m) where random = lift random instance MonadCond m => MonadCond (ContT r m) where score = lift . score instance MonadInfer m => MonadInfer (ContT r m)
State Before: α : Type u β : Type v ι : Sort w a : α s✝ s₁ s₂ t✝ : Set α p p₁ p₂ : α → Prop inst✝ : TopologicalSpace α s t : Set α ⊢ s \ t ⊆ closure t ↔ s ⊆ closure t State After: no goals Tactic: rw [diff_subset_iff, union_eq_self_of_subset_left subset_closure]
# Import Packages ```python %load_ext autoreload %autoreload 2 ``` ```python %matplotlib inline import matplotlib.pyplot as plt import numpy as np import os import pandas as pd import sympy as sym import statsmodels.api as sm import typing as tp ``` Bad key "text.kerning_factor" on line 4 in /Users/michaelnowotny/anaconda3/envs/continuous_time_mcmc/lib/python3.7/site-packages/matplotlib/mpl-data/stylelib/_classic_test_patch.mplstyle. You probably need to get an updated matplotlibrc file from https://github.com/matplotlib/matplotlib/blob/v3.1.3/matplotlibrc.template or from the matplotlib source distribution ```python from state_space.data_reader import ( load_monthly_and_annual_ff_factors, compute_monthly_returns ) ``` ```python from state_space import ( SymbolicStateSpaceModelViaMaximumLikelihood, LambdaParameterTransformation, RectangularParameterTransformation, linearize_vector_valued_state_function ) ``` # Load Data ```python data_directory_name = 'data' ford_data_filename = os.path.join(data_directory_name, 'F_monthly.csv') gspc_data_filename = os.path.join(data_directory_name, '^GSPC_monthly.csv') ff_data_filename = os.path.join(data_directory_name, 'F-F_Research_Data_Factors_monthly.CSV') ``` ```python ford_prices = pd.read_csv(ford_data_filename).set_index('Date') gspc_prices = pd.read_csv(gspc_data_filename).set_index('Date') ``` Load Fama-French factors ```python ff_monthly, ff_annual = load_monthly_and_annual_ff_factors(ff_data_filename) ``` # Prepare Data Compute Ford returns ```python ford_returns = compute_monthly_returns(ford_prices, name='ford') ``` Compute S&P 500 index returns ```python gspc_returns = compute_monthly_returns(gspc_prices, name='gspc') ``` Compute excess returns on both ```python gspc_excess_returns = gspc_returns - ff_monthly['RF'] ford_excess_returns = ford_returns - ff_monthly['RF'] ``` Put Ford and S&P 500 returns in a single dataframe ```python joint_returns = pd.DataFrame({'ford': ford_returns, 'gspc': gspc_returns, 'rf': ff_monthly['RF']}).dropna() ``` ```python joint_excess_returns = pd.DataFrame({'ford': ford_excess_returns, 'gspc': gspc_excess_returns}).dropna() ``` Restrict the time horizon from 1990 to 2004 ```python restricted_joint_excess_returns = joint_excess_returns.query('Date >= 1990 and Date < 2004') ``` # Conditional Factor Model and State-Space Representation ## Stochastic Process Model Consider a univariate linear factor model with time-varying coefficients, where the factor is the return on an equity index. This model can be written as $r_t = \alpha_t + \beta_t r_{M, t} + e_t$ $\alpha_{t+1} = \alpha_t + \eta_t$ $\beta_{t+1} = \beta_t + \epsilon_t$ where $r_t$ is the excess return of the stock over period $t$ and $r_{M, t}$ is the excess return of the market over period $t$. The innovations $e$, $\eta$, and $\epsilon$ are both serially and mutually independent and distributed as follows: $e_t \sim N(0, \sigma^2_e)$ $\eta_t \sim N(0, \sigma^2_{\eta})$ $\epsilon_t \sim N(0, \sigma^2_{\epsilon})$ ## State Space Representation This model can be represented in statespace form as: $s_t = \begin{pmatrix} \alpha_t \\ \beta_t \end{pmatrix}$ (state), $y_t = r_t$ (observation) $s_{t+1} = \begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix} \cdot s_t + \begin{pmatrix} \eta_t \\ \epsilon_t \end{pmatrix}$ $y_t = \begin{pmatrix} 1 & r_{M, t} \end{pmatrix} \cdot s_t + e_t $ We can further combine the processes $\begin{pmatrix} s_{t+1} \\ y_t \end{pmatrix} = \delta_t + \Phi_t s_t + u_t$, where $\delta_t = \begin{pmatrix} 0 \\ 0 \\ 0 \end{pmatrix}$, $\Phi_t = \begin{pmatrix} 1 & 0 \\ 0 & 1 \\ 1 & r_{M, t} \end{pmatrix}$, $u_t = \begin{pmatrix} \eta_t \\ \epsilon_t \\ e_t \end{pmatrix}$ ## Representation in SymPy Initialize symbols ```python sigma_e, sigma_eta, sigma_epsilon, alpha, beta, r, r_M = \ sym.symbols('sigma_e, sigma_eta, sigma_epsilon, alpha, beta, r, r_M') ``` Model parameters to be estimated ```python parameter_symbols = (sigma_e, sigma_eta, sigma_epsilon) ``` Define the state vector ```python state_vector_symbols = (alpha, beta) ``` Define the vector of observations ```python observation_vector_symbols = (r, ) ``` Define mapping between data symbols and Pandas series/NumPy arrays ```python data_symbol_to_data_map = {r: restricted_joint_excess_returns['ford'], r_M: restricted_joint_excess_returns['gspc']} ``` Set starting values for the maximum likelihood estimation via numerical optimization ```python ford_return_std = np.std(restricted_joint_excess_returns['ford']) parameter_symbols_to_start_parameters_map = {sigma_e: ford_return_std, sigma_eta: ford_return_std, sigma_epsilon: ford_return_std} ``` Define transformation functions to ensure that the variance parameters remain positive (the optimizer is unconstrained) Option A: Using a vectorized transformation function (the same for all parameters) ```python parameter_transformation = \ LambdaParameterTransformation(transform_function=lambda x: x**2, untransform_function=lambda x: x**0.5) ``` Option B: Using individual lower and upper bounds ```python # parameter_transformation = \ # RectangularParameterTransformation(parameter_symbols=parameter_symbols, # parameter_symbol_to_bounds_map={sigma_e: (0, np.inf), # sigma_eta: (0, np.inf), # sigma_epsilon: (0, np.inf)}) ``` Construct transition matrix in SymPy ```python transition_matrix = sym.eye(2) transition_matrix ``` $\displaystyle \left[\begin{matrix}1 & 0\\0 & 1\end{matrix}\right]$ Construct design matrix in SymPy ```python design_matrix = sym.Matrix([[1, r_M]]) design_matrix ``` $\displaystyle \left[\begin{matrix}1 & r_{M}\end{matrix}\right]$ We can alternatively express the transition and observation functions as a vector valued functions of state variables and linearize the function. For non-linear transition and observation functions this leads in the extended Kalman filter (EKF). ```python f = sym.Matrix([[alpha], [beta]]) g = sym.Matrix([[alpha + beta * r_M]]) ``` ```python state_intercept_vector_ekf, transition_matrix_ekf = \ linearize_vector_valued_state_function(f, state_vector_symbols=state_vector_symbols) print(state_intercept_vector_ekf) print(transition_matrix_ekf) ``` Matrix([[0], [0]]) Matrix([[1, 0], [0, 1]]) ```python observation_intercept_vector_ekf, design_matrix_ekf = \ linearize_vector_valued_state_function(g, state_vector_symbols=state_vector_symbols) print(observation_intercept_vector_ekf) print(design_matrix_ekf) ``` Matrix([[0]]) Matrix([[1, r_M]]) Construct selection matrix in SymPy ```python selection_matrix = sym.eye(2) selection_matrix ``` $\displaystyle \left[\begin{matrix}1 & 0\\0 & 1\end{matrix}\right]$ Construct state covariance matrix matrix in SymPy ```python state_covariance_matrix = sym.diagonalize_vector(sym.Matrix([sigma_eta**2, sigma_epsilon**2])) state_covariance_matrix ``` $\displaystyle \left[\begin{matrix}\sigma_{\eta}^{2} & 0\\0 & \sigma_{\epsilon}^{2}\end{matrix}\right]$ Construct observation covariance matrix matrix in SymPy ```python observation_covariance_matrix = sym.Matrix([[sigma_e**2]]) ``` Compile numeric state space representation for MLE from the symbolic definition ```python conditional_factor_model = \ SymbolicStateSpaceModelViaMaximumLikelihood(parameter_symbols=parameter_symbols, state_vector_symbols=state_vector_symbols, observation_vector_symbols=observation_vector_symbols, data_symbol_to_data_map=data_symbol_to_data_map, parameter_symbols_to_start_parameters_map=parameter_symbols_to_start_parameters_map, parameter_transformation=parameter_transformation, design_matrix=design_matrix, observation_covariance_matrix=observation_covariance_matrix, selection_matrix=selection_matrix, state_covariance_matrix=state_covariance_matrix, transition_matrix=transition_matrix) ``` # Estimation Fit the model using MLE (recall that we are fitting the three variance parameters) ```python res = conditional_factor_model.fit(disp=False) ``` ## Estimates ```python print(res.summary()) ``` Statespace Model Results ======================================================================================================= Dep. Variable: y No. Observations: 168 Model: SymbolicStateSpaceModelViaMaximumLikelihood Log Likelihood 148.798 Date: Fri, 16 Apr 2021 AIC -291.596 Time: 21:09:05 BIC -282.260 Sample: 0 HQIC -287.806 - 168 Covariance Type: opg ================================================================================= coef std err z P>|z| [0.025 0.975] --------------------------------------------------------------------------------- sigma_e 0.0929 0.004 22.945 0.000 0.085 0.101 sigma_eta 0.0024 0.002 1.342 0.179 -0.001 0.006 sigma_epsilon 0.1192 0.085 1.398 0.162 -0.048 0.286 =================================================================================== Ljung-Box (Q): 42.51 Jarque-Bera (JB): 38.55 Prob(Q): 0.36 Prob(JB): 0.00 Heteroskedasticity (H): 1.09 Skew: 0.73 Prob(H) (two-sided): 0.76 Kurtosis: 4.86 =================================================================================== Warnings: [1] Covariance matrix calculated using the outer product of gradients (complex-step). ## Filtered and Smoothed State Filtered $\alpha$ ```python plt.plot(restricted_joint_excess_returns.index, res.filtered_state[0, :]); ``` Smoothed $\alpha$ ```python plt.plot(restricted_joint_excess_returns.index, res.smoothed_state[0, :]); ``` Filtered $\beta$ ```python plt.plot(restricted_joint_excess_returns.index, res.filtered_state[1, :]); ``` Smoothed $\beta$ ```python plt.plot(restricted_joint_excess_returns.index, res.smoothed_state[1, :]); ``` ```python ```
C ********************************************************* C * * C * TEST NUMBER: 04.02.05.03/13 * C * TEST TITLE : Network inheritance and * C * initialization of edge index * C * * C * PHIGS Validation Tests, produced by NIST * C * * C ********************************************************* COMMON /GLOBNU/ CTLHND, ERRSIG, ERRFIL, IERRCT, UNERR, 1 TESTCT, IFLERR, PASSSW, ERRSW, MAXLIN, 2 CONID, MEMUN, WKID, WTYPE, GLBLUN, INDLUN, 3 DUMINT, DUMRL INTEGER CTLHND, ERRSIG, ERRFIL, IERRCT, UNERR, 1 TESTCT, IFLERR, PASSSW, ERRSW, MAXLIN, 2 CONID, MEMUN, WKID, WTYPE, GLBLUN, INDLUN, 3 DUMINT(20), ERRIND REAL DUMRL(20) COMMON /GLOBCH/ PIDENT, GLBERR, TSTMSG, FUNCID, 1 DUMCH CHARACTER PIDENT*40, GLBERR*60, TSTMSG*900, FUNCID*80, 1 DUMCH(20)*20 COMMON /DIALOG/ DOUTYP, DINTYP, DSTDNR, DSTRID, PSTRID, DTCLIM, 1 SCRMOD, DTXCI, SPECWT, 2 DSIZE, EFRAC, DYXRAT, SYXRAT, MTRPDC, WCPDC, QVIS INTEGER DOUTYP, DINTYP, DSTDNR, DSTRID, PSTRID, DTCLIM, 1 SCRMOD, DTXCI, SPECWT REAL DSIZE, EFRAC, DYXRAT, SYXRAT, MTRPDC, WCPDC, QVIS C aspect source INTEGER PBUNDL, PINDIV PARAMETER (PBUNDL = 0, PINDIV = 1) C composition type INTEGER PCPRE, PCPOST, PCREPL PARAMETER (PCPRE = 0,PCPOST=1, PCREPL = 2) C interior style INTEGER PHOLLO, PSOLID, PPATTR, PHATCH, PISEMP PARAMETER (PHOLLO=0, PSOLID=1, PPATTR=2, PHATCH=3, PISEMP=4) C off/on switch for edge flag and error handling mode INTEGER POFF, PON PARAMETER (POFF = 0, PON = 1) C colour model INTEGER PRGB, PCIE, PHSV, PHLS PARAMETER (PRGB = 1, PCIE = 2, PHSV = 3, PHLS = 4) C aspect identifier INTEGER PLN, PLWSC, PPLCI, PMK, PMKSC PARAMETER (PLN = 0, PLWSC= 1, PPLCI= 2, PMK = 3, PMKSC= 4) INTEGER PPMCI, PTXFN, PTXPR, PCHXP, PCHSP PARAMETER (PPMCI= 5, PTXFN= 6, PTXPR= 7, PCHXP= 8, PCHSP= 9) INTEGER PTXCI, PIS, PISI, PICI, PEDFG PARAMETER (PTXCI=10, PIS =11, PISI =12, PICI =13, PEDFG=14) INTEGER PICSTR, TXCI, IX, IY, SIZ INTEGER NUMET, NUMEW, EDFLG(5), LEDTYP(5), DSEDGE INTEGER EXPDX(14), THISED, FCOL, COLIND(5), PERM(14) INTEGER IDUM1, IDUM2, IDUM3 REAL ALTEW1, ALTEW2, AVG1, AVG2, Z, U, SHIFTY, FXPTY REAL SCALEY, XFORM(3,3), RDUM1, RDUM2, RDUM3 REAL XACT(3), XEXP(3), YLOCEL, NOMEW, MINEW, MAXEW CALL INITGL ('04.02.05.03/13') C open PHIGS CALL XPOPPH (ERRFIL, MEMUN) C set-up of workstation and dialogue area PICSTR = 101 TXCI = 1 CALL SETDLG (PICSTR, 801,TXCI) CALL PSCMD (WKID, PRGB) C All test cases use same basic structure network for testing C inheritance. C C default = val#1 C | 102 C | / prim 2 C | / attr = val#3 val#3 C V val#1/ exec 103---------------103 C 101 / prim 8 prim 3 C prim 1 / attr = val#4 C exec 102/ prim 4 C prim 9 exec 104\ C attr = val#2 prim 7 \ val#4 C prim 10 \ C transform val#2 \ C exec 104-----------------------------------------------------104 C un-transform prim 5/11 C prim 13 attr = val#5 C prim 14 prim 6/12 C exec 105---------->105 C expected values C C *** *** *** inheritance for edge index *** *** *** C numet = number of edgetypes C numew = number of available edge-widths C nomew = nominal edge-width (DC) C minew,maxew = minimum,maximum edge-width (DC) CALL PQEDF (SPECWT, 0, ERRIND, NUMET, IDUM2, NUMEW, NOMEW, 1 MINEW, MAXEW, IDUM3) CALL CHKINQ ('pqedf', ERRIND) C x-location of actual / expected triangle CALL SETRVS ('0.2,0.2,0.5',XACT,SIZ) CALL SETRVS ('0.6,0.6,0.9',XEXP,SIZ) C set edge flag DO 50 IX = 1,5 EDFLG(IX) = PON 50 CONTINUE IF (NUMET .EQ. 1) EDFLG(3) = POFF C distinct edgetypes DSEDGE = MIN (5, ABS(NUMET)) C pick no more than 5 out of whatever is available CALL RNSET (DSEDGE, ABS(NUMET), PERM) DO 100 IX = 1, 5 IF (IX .LE. DSEDGE) THEN CALL PQEDF (SPECWT, PERM(IX), ERRIND,IDUM1,THISED,IDUM2, 1 RDUM1,RDUM2,RDUM3, IDUM3) CALL CHKINQ ('pqedf', ERRIND) LEDTYP(IX) = THISED ELSE LEDTYP(IX) = LEDTYP(IX-DSEDGE) ENDIF 100 CONTINUE C get alternative edgewidth scale values: C altew1, altew2 = max, min edgewidth scale factor ALTEW1 = MAXEW/NOMEW ALTEW2 = MINEW/NOMEW C but, altew1 should not exceed .05 (WC) to avoid overlap - distance C between edges will be 1/15 = .06666 ALTEW1 = MIN(ALTEW1,(0.0666-0.05)/(NOMEW * WCPDC)) C if default (1.0) is near altew1 or altew2, set alternate so as to C maximize the smallest gap among altew1, altew2, and 1.0: AVG1 = (ALTEW1 + 1) / 2 AVG2 = (ALTEW2 + 1) / 2 IF (ABS(ALTEW1-1) .LT. ABS(AVG2-1)) THEN ALTEW1 = AVG2 ELSEIF (ABS(ALTEW2-1) .LT. ABS(AVG1-1)) THEN ALTEW2 = AVG1 ENDIF C call DISCOL to try to get 5 distinct foreground colors, C returning fcol = actual number of foreground colors CALL DISCOL (5, WKID, FCOL) CALL SETVAL ('1,2,3,4,5', COLIND) C if (fcol < 5) copy 1st valid part of list to tail of list IF (FCOL .LT. 5) THEN IY = 1 DO 300 IX = FCOL+1, 5 COLIND(IX) = COLIND(IY) IY = IY+1 300 CONTINUE ENDIF C set up bundles 1-5 CALL PSEDR (WKID, 1, EDFLG(1), LEDTYP(1), 1.0, COLIND(1)) CALL PSEDR (WKID, 2, EDFLG(2), LEDTYP(2), ALTEW1, COLIND(2)) CALL PSEDR (WKID, 3, EDFLG(3), LEDTYP(3), ALTEW2, COLIND(3)) CALL PSEDR (WKID, 4, EDFLG(4), LEDTYP(4), ALTEW1, COLIND(4)) CALL PSEDR (WKID, 5, EDFLG(5), LEDTYP(5), ALTEW2, COLIND(5)) C display 14 pairs of triangles, using bundles 1-5 C randomize location of edges CALL RN1SHF (14, PERM) C set up CSS as described above C structure #101 CALL POPST (PICSTR) C by convention , view #1 is for picture CALL PSVWI (1) C use bundled attributes CALL SETASF (PBUNDL) C set interior style attribute ASFs to INDIVIDUAL CALL PSIASF (PIS, PINDIV) CALL PSIASF (PICI, PINDIV) C set interior style = EMPTY, interior color index = 1 CALL PSIS (PISEMP) CALL PSICI (1) CALL LOCTRI (PERM(1), XACT) CALL PEXST (102) CALL LOCTRI (PERM(9), XACT) CALL PSEDI (2) CALL LOCTRI (PERM(10), XACT) Z = 0.0 U = 1.0 FXPTY = YLOCEL (PERM(5)) SHIFTY = YLOCEL (PERM(11)) - YLOCEL (PERM(5)) SCALEY = (YLOCEL (PERM(12)) - YLOCEL (PERM(11))) / 1 (YLOCEL (PERM(06)) - YLOCEL (PERM(05))) CALL PBLTM (Z, FXPTY, Z, SHIFTY, Z, U, SCALEY, ERRIND, XFORM) CALL CHKINQ ('pbltm', ERRIND) CALL PSLMT (XFORM, PCREPL) C execute structure #104 CALL PEXST (104) C now, cancel out transformation CALL IDMAT (3, XFORM) CALL PSLMT (XFORM, PCREPL) CALL LOCTRI (PERM(13), XACT) CALL LOCTRI (PERM(14), XACT) CALL PEXST (105) CALL PCLST C structure #102 CALL POPST (102) CALL LOCTRI (PERM(2), XACT) CALL PSEDI (3) CALL PEXST (103) CALL LOCTRI (PERM(8), XACT) CALL PCLST C structure #103 CALL POPST (103) CALL LOCTRI (PERM(3), XACT) CALL PSEDI (4) CALL LOCTRI (PERM(4), XACT) CALL PEXST (104) CALL LOCTRI (PERM(7), XACT) CALL PCLST C structure #104 CALL POPST (104) CALL LOCTRI (PERM(5), XACT) CALL PSEDI (5) CALL LOCTRI (PERM(6), XACT) CALL PCLST C Expected attrubutes: structure #105 CALL POPST (105) CALL SETVAL ('1,1,3,4,4,5,4,3,1,2,2,5,2,3', EXPDX) DO 400 IX = 1,14 CALL PSEDI (EXPDX(IX)) CALL LOCTRI (PERM(IX), XEXP) 400 CONTINUE C draw labels CALL NUMLAB (14, 0.15, YLOCEL(1), 1.0/15) CALL PCLST CALL SETMSG ('3 5 6 8 9', 'The edge index should be saved and ' // 1 'restored by <execute structure> during traversal.') CALL DCHPFV ('STRUCTURE NETWORK INHERITANCE FOR EDGE INDEX: ' // 1 'Which pair of triangles does NOT match?', 2 14, PERM(14)) 666 CONTINUE C wrap it up. CALL ENDIT END
I am originally from Towanda, Pennsylvania. Towanda is Algonquin for "Hills were the great dead are buried", something I find to be an interesting coincidence in the relationship to the vast majority of my work; it is also a terrific case of irony, being that I was technically born in a old graveyard. I received my B.F.A. from Edinboro University of Pennsylvania and my M.F.A. from the University of North Dakota. I am a Ceramics Instructor at Century College. I am currently located in Minneapolis, MN.
||| Matrix operations with vector space dimensionalities enforced ||| at the type level. Uses operations from the Num type class. module Data.Matrix.Numeric import public Data.Matrix %default total infixr 2 <:> -- vector inner product infixr 2 >< -- vector outer product infixr 2 <<>> -- matrix commutator infixr 2 >><< -- matrix anticommutator infixl 3 <\> -- row times a matrix infixr 4 </> -- matrix times a column infixr 5 <> -- matrix multiplication infixl 5 <#> -- matrix rescale infixl 5 <# -- vector rescale infixr 7 \&\ -- vector tensor product infixr 7 <&> -- matrix tensor product ----------------------------------------------------------------------- -- Vectors as members of Num ----------------------------------------------------------------------- instance Num a => Num (Vect n a) where (+) = zipWith (+) (*) = zipWith (*) fromInteger n = replicate _ (fromInteger n) instance Neg a => Neg (Vect n a) where (-) = zipWith (-) abs = map abs negate = map negate ----------------------------------------------------------------------- -- Vector functions ----------------------------------------------------------------------- ||| Inner product of ring vectors (<:>) : Num a => Vect n a -> Vect n a -> a (<:>) w v = sum $ zipWith (*) w v ||| Scale a numeric vector by a scalar (<#) : Num a => a -> Vect n a -> Vect n a (<#) r = map (r *) ||| Tensor multiply (⊗) numeric vectors (\&\) : Num a => Vect n a -> Vect m a -> Vect (n * m) a (\&\) {n} {m} v w = zipWith (*) (oextend m v) (orep n w) where orep : (n : Nat) -> Vect m a -> Vect (n * m) a orep n v = concat $ replicate n v oextend : (n : Nat) -> Vect k a -> Vect (k * n) a oextend n w = concat $ map (replicate n) w ||| Standard basis vector with one nonzero entry, numeric data type and vector-length unfixed basis : Num a => (Fin d) -> Vect d a basis i = replaceAt i 1 0 ----------------------------------------------------------------------- -- Matrix functions ----------------------------------------------------------------------- ||| Matrix times a column vector (</>) : Num a => Matrix n m a -> Vect m a -> Vect n a (</>) m v = map (v <:>) m ||| Matrix times a row vector (<\>) : Num a => Vect n a -> Matrix n m a -> Vect m a (<\>) r m = map (r <:>) $ transpose m ||| Matrix multiplication (<>) : Num a => Matrix n k a -> Matrix k m a -> Matrix n m a (<>) m1 m2 = map (<\> m2) m1 ||| Scale matrix by a scalar (<#>) : Num a => a -> Matrix n m a -> Matrix n m a (<#>) r = map (r <#) ||| Tensor multiply (⊗) for numeric matrices (<&>) : Num a => Matrix h1 w1 a -> Matrix h2 w2 a -> Matrix (h1 * h2) (w1 * w2) a (<&>) m1 m2 = zipWith (\&\) (stepOne m1 m2) (stepTwo m1 m2) where stepOne : Matrix h1 w1 a -> Matrix h2 w2 a -> Matrix (h1 * h2) w1 a stepOne {h2} m1 m2 = concat $ map (replicate h2) m1 stepTwo : Matrix h1 w1 a -> Matrix h2 w2 a -> Matrix (h1 * h2) w2 a stepTwo {h1} m1 m2 = concat $ replicate h1 m2 ||| Outer product between numeric vectors (><) : Num a => Vect n a -> Vect m a -> Matrix n m a (><) x y = col x <> row y ||| Matrix commutator (<<>>) : Neg a => Matrix n n a -> Matrix n n a -> Matrix n n a (<<>>) m1 m2 = (m1 <> m2) - (m2 <> m1) ||| Matrix anti-commutator (>><<) : Num a => Matrix n n a -> Matrix n n a -> Matrix n n a (>><<) m1 m2 = (m1 <> m2) + (m2 <> m1) ||| Identity matrix Id : Num a => Matrix d d a Id = map (\n => basis n) (fins _) ||| Square matrix from diagonal elements diag_ : Num a => Vect n a -> Matrix n n a diag_ = zipWith (\f => \x => replaceAt f x 0) (fins _) ||| Combine two matrices to make a new matrix in block diagonal form blockDiag : Num a => Matrix n n a -> Matrix m m a -> Matrix (n+m) (n+m) a blockDiag {n} {m} g h = map (++ replicate m 0) g ++ map ((replicate n 0) ++) h ----------------------------------------------------------------------- -- Determinants ----------------------------------------------------------------------- ||| Alternating sum altSum : Neg a => Vect n a -> a altSum (x::y::zs) = (x - y) + altSum zs altSum [x] = x altSum [] = 0 ||| Determinant of a 2-by-2 matrix det2 : Neg a => Matrix 2 2 a -> a det2 [[x1,x2],[y1,y2]] = x1*y2 - x2*y1 ||| Determinant of a square matrix det : Neg a => Matrix (S (S n)) (S (S n)) a -> a det {n} m = case n of Z => det2 m (S k) => altSum . map (\c => indices FZ c m * det (subMatrix FZ c m)) $ fins (S (S (S k)))
# 1. Kernel Ridge Regression \begin{align*} \text{Primal form:}~&\Vert Ax - y \Vert_2^2 + \lambda \Vert x \Vert_2^2\\ \textbf{Closed-form solution:}~&x = \left(A^TA + \lambda I_n\right)^{-1}A^Ty\\ \end{align*} From the identity $\left(A^TA + \lambda I_n\right)^{-1}A^T = A^T\left(AA^T + \lambda I_m\right)^{-1}$, we can obtain a closed-form solution with the alternate form: \begin{align*} \textbf{Alternate closed-form solution:}~x = A^T\left(AA^T + \lambda I_m\right)^{-1}y \end{align*} Let $A$ have $m$ rows and $n$ columns, such that each row is a data-point (or sample) and each column is a feature. In typical applications of kernel ridge regression, $m >> n$. This means that computing $\alpha$ directly requires computing the $m \times m$ matrix, $AA^T$. For very large $m$ this can be an expensive $m^2n$ operation and, in the extreme, we many not even have space to store $AA^T$. The Kernelized variant of ridge regression replaces the $m \times n$ matrix $A$ with a high-dimensional feature space for each sample $\Phi(A)$. $\Phi(A)$ is computational-expensive to form, especially when the chosen kernel function has infinite-dimensional feature space (e.g. Radial Basis Function). However, the $m \times m$ kernel matrix $K$ can be computed since the kernel functions are defined by $K_{i,j} = \sum k(a_i, a_j)$, where $a_i$ is the $i$-th row of $A$ and $k(...)$ is a user-defined kernel function. One example of such a kernel function, is the polynomial kernel: $k(a_i, a_j) = (a_ia_j^T + r)^d$ s.t. $r \geq 0$ and $d \geq 1$. *When $r = 0$ and $d = 1$, we obtain a simple dot-product (or linear kernel).* In replacing the dot-products with a kernel function, we obtain a feature-space that can have very high dimensions (possibly infinite-dimensions). This means that computing the solution, $x$, is often very expensive. So instead, we will focus on obtaining the solution: \begin{align*} \bf \text{Alternate solution:}~&\alpha = \left(\frac{1}{\lambda}K + I_m\right)^{-1}y\\ \text{and}~&w = \frac{1}{\lambda}\Phi(A)^T\alpha \end{align*} # 2. Subspace Iteration for Kernel Ridge Regression Note that the kernel matrix, $K$, is more expensive to compute than $AA^T$ (due to the kernel function), so we will instead compute the solution to $\alpha$ iteratively using ***subspace iteration*** by selecting, and solving for a few samples (row of $A$) every iteration. \begin{align*} \text{Dual form:}~&\Vert \alpha - y \Vert_2^2 + \frac{1}{\lambda} \Vert \Phi(A)^T\alpha \Vert_2^2\\ \bf\text{Iterative update:}~&\alpha_h = \alpha_{h-1} + \mathbb{I}_h^T {u_h}\\ \end{align*} The matrix $\mathbb{I}_h$ has $b$ rows and $m$ columns such that rows of $\mathbb{I}_h$ are sub-sampled rows of the $m$-dimensional identity matrix, $I_m$. By substituting the iterative update into the dual form, we obtain the following minimization problem: \begin{align*} {\arg\min}~\left\Vert \alpha_{h-1} + \mathbb{I}_h^Tu_h - y \right\Vert_2^2 + \frac{1}{\lambda} \left\Vert \Phi(A)^T\alpha_{h-1} + \Phi(A)^T\mathbb{I}_h^T u_h\right\Vert_2^2 \end{align*} By taking the derivative w.r.t $u_h$ we can obtain the gradient for just the $b$ rows of $A$ that we are sampling at every iteration: \begin{align*} 0 &= \mathbb{I}_h\alpha_{h-1} + u_h - \mathbb{I}_hy + \frac{1}{\lambda} \mathbb{I}_h \Phi(A)\Phi(A)^T\alpha_{h-1} + \frac{1}{\lambda}\mathbb{I}_h\Phi(A)\Phi(A)^T\mathbb{I}_h^T u_h\\ \textbf{Gradient w.r.t chosen samples: }u_h &= \left(\frac{1}{\lambda} \mathbb{I}_h\Phi(A)\Phi(A)^T\mathbb{I}_h^T + I_b \right)^{-1}\left(\mathbb{I}_h y - \mathbb{I}_h \alpha_{h-1} - \frac{1}{\lambda}\mathbb{I}_h \Phi(A)\Phi(A)^T\alpha_{h-1}\right) \end{align*} Notice that the term $\mathbb{I}_h \Phi(A)\Phi(A)^T \alpha_{h-1}$ does not permit the use of an auxiliary vector to represent $\Phi(A)^T \alpha_{h-1}$ due to the kernelization. This means that we will have to explicitly compute $\mathbb{I}_h\Phi(A)\Phi(A)^T$ at every iteration. Additionally, the quantity $\mathbb{I}_h\Phi(A)\Phi(A)^T\mathbb{I}_h^T$ does not need to be computed at every iteration because we can simply select the relevant columns (namely the columns defined by right-multiplying by $\mathbb{I}_h^T)$ from the quantity $\mathbb{I}_h\Phi(A)\Phi(A)^T$. # 3. Communication-Avoiding Subspace Iteration for Kernel Ridge Regression In this section, we will derive the communication-avoiding variant of subspace iteration for solving the Kernel Ridge Regression problem. Lets start by re-stating the subspace iteration's update step: \begin{align*} u_{h+1} &= \left(\frac{1}{\lambda} \mathbb{I}_{h+1}\Phi(A)\Phi(A)^T\mathbb{I}_{h+1}^T + I_b \right)^{-1}\left(\mathbb{I}_{h+1} y - \mathbb{I}_{h+1} \alpha_{h} - \frac{1}{\lambda}\mathbb{I}_{h+1} \Phi(A)\Phi(A)^T\alpha_{h}\right)\\ \alpha_{h+1} &= \alpha_{h} + \mathbb{I}_{h+1}^T u_{h+1} \end{align*} Given this two-line recurrence, we can write the next update for iteration $h+2$ as: \begin{align} u_{h+2} &= \left(\frac{1}{\lambda} \mathbb{I}_{h+2}\Phi(A)\Phi(A)^T\mathbb{I}_{h+2}^T + I_b \right)^{-1}\left(\mathbb{I}_{h+2} y - \mathbb{I}_{h+2} \alpha_{h+1} - \frac{1}{\lambda}\mathbb{I}_{h+2} \Phi(A)\Phi(A)^T\alpha_{h+1}\right)\tag{1}\\ \alpha_{h+2} &= \alpha_{h+1} + \mathbb{I}_{h+2}^T u_{h+2}.\tag{2} \end{align} Notice that in the update step above, we can replace all instances of $\alpha_{h}$ with $\alpha_{h-1} + \mathbb{I}_h^T u_h$. By doing this, we can write the update steps for $u_{h+1}$ and $\alpha_{h+1}$ in terms of $\alpha_{h-1}$ and $u_h$, instead of $\alpha_h$: \begin{align*} u_{h+2} &= \left(\frac{1}{\lambda} \mathbb{I}_{h+2}\Phi(A)\Phi(A)^T\mathbb{I}_{h+2}^T + I_b \right)^{-1}\left(\mathbb{I}_{h+2} y \color{blue}{- \mathbb{I}_{h+2} \alpha_{h} - \frac{1}{\lambda}\mathbb{I}_{h+2} \Phi(A)\Phi(A)^T\alpha_{h}} \color{red}{- \mathbb{I}_{h+2}\mathbb{I}_{h+1}^T u_{h+1} - \frac{1}{\lambda}\mathbb{I}_{h+2} \Phi(A)\Phi(A)^T\mathbb{I}_{h+1}^T u_{h+1}}\right)\tag{3}\\ \alpha_{h+2} &= \alpha_{h} \color{red}{+ \mathbb{I}_{h+1}^Tu_{h+1} + \mathbb{I}_{h+2}^T u_{h+2}}. \end{align*} Comparing eq. (3) and (1), we can see that the terms in blue differ in that they depend on $\alpha_{h}$ instead of $\alpha_{h+1}$. The terms in red in eq. (3) are additional corrections which depend on the previous iteration's gradient, $u_{h+1}$, which also depend on $\alpha_{h}$. Finally, we can update $\alpha_{h+2}$ by summing the gradients $u_{h+1}$ and $u_{h+2}$. The example above performs a recurrence unrolling of two iterations (i.e. computing $\alpha_{h+2}$ w.r.t $\alpha_h$), but we can unroll for an arbitrary number of iterations. We will use the variable $s$ to represent the number of iterations we unroll the recurrences. Notice that we still compute all of the gradients, $\{u_h, u_{h+1}, \ldots, u_{h+s}\}$, but only need $\alpha_h$ in order to compute $\alpha_{h+s}$. This means that we can defer updates to $\alpha$ for $s$ iterations. \begin{align*} u_{h + j} &= \left(\frac{1}{\lambda} \mathbb{I}_{h + j}\Phi(A)\Phi(A)^T\mathbb{I}_{h + j}^T + I_b\right)^{-1}\left(\mathbb{I}_{h+j} y \color{blue}{- \mathbb{I}_{h+j}\alpha_{h} - \frac{1}{\lambda}\mathbb{I}_{h+j}\Phi(A)\Phi(A)^T\alpha_{h}} \color{red}{- \sum_{k = 1}^{j-1}\mathbb{I}_{h + j}\mathbb{I}_{h + k}^T u_{h + k} - \sum_{k = 1}^{j-1} \frac{1}{\lambda}\mathbb{I}_{h+j}\Phi(A)\Phi(A)^T\mathbb{I}_{h + k}^T u_{h + k}}\right)\\ \alpha_{h+j} &= \alpha_{h} \color{red}{+ \sum_{k = 1}^{j} \mathbb{I}_{h + k}^T u_{h + k}}.\\ \text{for } j &= \{1, 2, \ldots, s\} \text{ where $s$ is a free parameter.} \end{align*} Notice that in the summation $\sum_{k = 1}^{j-1} \mathbb{I}_{h+k}\mathbb{I}_{k + j}^T u_k$, the computation $\mathbb{I}_{h+k}\mathbb{I}_k^T$ is computing a $b \times b$ identity-like matrix. This matrix is essentially computing the intersection between the sampled indices from iteration $h + j$ and iterations $h + k$ (where $k$ goes from $1$ to $j - 1$). This is crucial to ensure that gradient updates computed at iterations $h + k$ are incorporated into the iteration $h + j$. ```python import numpy as np import scipy as sp from sklearn.metrics import pairwise_distances import matplotlib.pyplot as plt class Kernel_Ridge_Regression(object): def __init__(self, data, labels, kernel_params={'kernel_type': 'gaussian', 'sigma': 1e-1}): self.kernel_params = kernel_params self.nsamples, self.nfeatures = data.shape if self.nsamples != len(labels): raise ValueError('len(labels) != data.shape[1].') self.data = data self.labels = labels self._set_kernel_function(kernel_params['kernel_type']) self.alpha = np.zeros(self.nsamples) def _set_kernel_function(self, kernel_type): kernel_type = kernel_type.lower() if kernel_type == 'gaussian': self.kernel_function = self._gaussian_kernel elif kernel_type == 'polynomial': self.kernel_function = self._polynomial_kernel else: raise ValueError("Invalid kernel choice: {}".format(kernel_type)) def _gaussian_kernel(self, subsamples, samples): kernel_matrix = pairwise_distances(subsamples, samples, metric='euclidean')**2 kernel_matrix = np.exp(-kernel_matrix/self.kernel_params['sigma']**2) return kernel_matrix def _polynomial_kernel(self, subsamples, samples): kernel_matrix = (subsamples.dot(samples.T) + self.kernel_params['shift']) ** self.kernel_params['dim'] return kernel_matrix def compute_objective(self): obj_val = np.linalg.norm(self.alpha - self.labels)**2 obj_val += 1/self.C * (self.alpha.T.dot(self.kernel_function(self.data, self.data).dot(self.alpha))) return obj_val def block_coordinate_descent(self, idxs): blkrow_kernel_matrix = self.kernel_function(self.data[idxs, :], self.data) residual = self.labels[idxs] - self.alpha[idxs] - (1/self.C)*blkrow_kernel_matrix.dot(self.alpha) blkdiag_kernel_matrix = ((1/self.C) * blkrow_kernel_matrix[:, idxs]) + 1 gradient = np.linalg.solve(blkdiag_kernel_matrix, residual) self.alpha[idxs] += gradient def commavoid_block_coordinate_descent(self, idxs): gradient = np.zeros(self.s*self.block_size) blkrow_kernel_matrix = self.kernel_function(self.data[idxs, :], self.data) residual = self.labels[idxs] - self.alpha[idxs] - (1/self.C)*blkrow_kernel_matrix.dot(self.alpha) # compute 's' gradients. blk_residual = residual[0:self.block_size] blkdiag_kernel_matrix = ((1/self.C) * blkrow_kernel_matrix[0:self.block_size, idxs[0:self.block_size]]) + 1 gradient[0:self.block_size] = np.linalg.solve(blkdiag_kernel_matrix, blk_residual) for i in range(1, self.s): residual_correction = np.zeros(self.block_size) blk_idxs = range(i*self.block_size, (i+1)*self.block_size) blk_residual = residual[blk_idxs] blkdiag_kernel_matrix = ((1/self.C) * blkrow_kernel_matrix[blk_idxs, idxs[blk_idxs]]) + 1 for j in range(i): blk_gradient = gradient[j*self.block_size:(j+1)*self.block_size] innerblk_idxs = idxs[j*self.block_size, (j+1)*self.block_size] commonvals, idxof_outerblk, idxof_innerblk = np.intersect1d(blk_idxs, innerblk_idxs, assume_unique=True, return_indices=True) residual_correction[idxof_outerblk] = blk_gradient[idxof_innerblk] residual_correction += (1/self.C) * (blkrow_kernel_matrix[blk_idxs, j*self.block_size:(j+1)*self.block_size].dot(blk_gradient)) blk_residual -= residual_correction gradient[blk_idxs] = np.linalg.solve(blkdiag_kernel_matrix, blk_residual) self.alpha[idxs] += gradient def train(self, epochs=100, optimizer='bcd', optimizer_params={'C': 1e-5, 'block_size': 1, 'shuffle': True}): if optimizer.lower() == 'bcd': optimizer = self.block_coordinate_descent elif optimizer.lower() == 'cabcd': optimizer = self.commavoid_block_coordinate_descent self.s = optimizer_params['s'] else: raise ValueError('Invalid optimizer choice: {}'.format(optimizer)) self.C = optimizer_params['C'] self.block_size = optimizer_params['block_size'] self.shuffle = optimizer_params['shuffle'] loss_history = [] for epoch in range(1,epochs+1): if self.shuffle: idxs = np.random.choice(self.nsamples, size=self.nsamples, replace=False) else: idxs = np.arange(self.nsamples) nblocks = len(idxs)/self.block_size for block in np.array_split(idxs, nblocks): if len(block) < 1: break optimizer(block) loss_history.append(self.compute_objective()) epoch_strlen = len(str(epochs)) print('[{}] loss {:.16f}.'.format(str(epoch).zfill(epoch_strlen), loss_history[-1])) plt.plot(loss_history) def test(self): raise NotImplementedError() ``` ```python from sklearn.datasets import load_svmlight_file (data, labels) = load_svmlight_file('../data/abalone') krr = Kernel_Ridge_Regression(data, labels) krr.train(epochs=100) ```
-- Andreas, 2012-01-11 module Issue551a where data Box (A : Set) : Set where [_] : A → Box A implicit : {A : Set}{{a : A}} -> A implicit {{a}} = a postulate A : Set .a : A -- this irrelevant definition needs to be ignored by instance search a' : Box A a' = [ implicit ] -- this should fail
[STATEMENT] lemma Inr_qbs_morphism: "Inr \<in> Y \<rightarrow>\<^sub>Q X <+>\<^sub>Q Y" [PROOF STATE] proof (prove) goal (1 subgoal): 1. Inr \<in> Y \<rightarrow>\<^sub>Q X <+>\<^sub>Q Y [PROOF STEP] proof(rule qbs_morphismI) [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>\<alpha>. \<alpha> \<in> qbs_Mx Y \<Longrightarrow> Inr \<circ> \<alpha> \<in> qbs_Mx (X <+>\<^sub>Q Y) [PROOF STEP] fix \<alpha> [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>\<alpha>. \<alpha> \<in> qbs_Mx Y \<Longrightarrow> Inr \<circ> \<alpha> \<in> qbs_Mx (X <+>\<^sub>Q Y) [PROOF STEP] assume "\<alpha> \<in> qbs_Mx Y" [PROOF STATE] proof (state) this: \<alpha> \<in> qbs_Mx Y goal (1 subgoal): 1. \<And>\<alpha>. \<alpha> \<in> qbs_Mx Y \<Longrightarrow> Inr \<circ> \<alpha> \<in> qbs_Mx (X <+>\<^sub>Q Y) [PROOF STEP] moreover [PROOF STATE] proof (state) this: \<alpha> \<in> qbs_Mx Y goal (1 subgoal): 1. \<And>\<alpha>. \<alpha> \<in> qbs_Mx Y \<Longrightarrow> Inr \<circ> \<alpha> \<in> qbs_Mx (X <+>\<^sub>Q Y) [PROOF STEP] have "Inr \<circ> \<alpha> = (\<lambda>r. Inr (\<alpha> r))" [PROOF STATE] proof (prove) goal (1 subgoal): 1. Inr \<circ> \<alpha> = (\<lambda>r. Inr (\<alpha> r)) [PROOF STEP] by auto [PROOF STATE] proof (state) this: Inr \<circ> \<alpha> = (\<lambda>r. Inr (\<alpha> r)) goal (1 subgoal): 1. \<And>\<alpha>. \<alpha> \<in> qbs_Mx Y \<Longrightarrow> Inr \<circ> \<alpha> \<in> qbs_Mx (X <+>\<^sub>Q Y) [PROOF STEP] ultimately [PROOF STATE] proof (chain) picking this: \<alpha> \<in> qbs_Mx Y Inr \<circ> \<alpha> = (\<lambda>r. Inr (\<alpha> r)) [PROOF STEP] show "Inr \<circ> \<alpha> \<in> qbs_Mx (X <+>\<^sub>Q Y)" [PROOF STATE] proof (prove) using this: \<alpha> \<in> qbs_Mx Y Inr \<circ> \<alpha> = (\<lambda>r. Inr (\<alpha> r)) goal (1 subgoal): 1. Inr \<circ> \<alpha> \<in> qbs_Mx (X <+>\<^sub>Q Y) [PROOF STEP] by(auto intro!: bexI[where x=UNIV] simp add: copair_qbs_Mx_def) [PROOF STATE] proof (state) this: Inr \<circ> \<alpha> \<in> qbs_Mx (X <+>\<^sub>Q Y) goal: No subgoals! [PROOF STEP] qed
!********************************************************************************************************************************** ! FAST_Solver.f90, FAST_Subs.f90, FAST_Lin.f90, and FAST_Mods.f90 make up the FAST glue code in the FAST Modularization Framework. ! FAST_Prog.f90, FAST_Library.f90, FAST_Prog.c are different drivers for this code. !.................................................................................................................................. ! LICENSING ! Copyright (C) 2013-2016 National Renewable Energy Laboratory ! ! This file is part of FAST. ! ! Licensed under the Apache License, Version 2.0 (the "License"); ! you may not use this file except in compliance with the License. ! You may obtain a copy of the License at ! ! http://www.apache.org/licenses/LICENSE-2.0 ! ! Unless required by applicable law or agreed to in writing, software ! distributed under the License is distributed on an "AS IS" BASIS, ! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ! See the License for the specific language governing permissions and ! limitations under the License. !********************************************************************************************************************************** MODULE FAST_Subs USE FAST_Solver USE FAST_Linear IMPLICIT NONE CONTAINS !++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ! INITIALIZATION ROUTINES !++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ !> a wrapper routine to call FAST_Initialize a the full-turbine simulation level (makes easier to write top-level driver) SUBROUTINE FAST_InitializeAll_T( t_initial, TurbID, Turbine, ErrStat, ErrMsg, InFile, ExternInitData ) REAL(DbKi), INTENT(IN ) :: t_initial !< initial time INTEGER(IntKi), INTENT(IN ) :: TurbID !< turbine Identifier (1-NumTurbines) TYPE(FAST_TurbineType), INTENT(INOUT) :: Turbine !< all data for one instance of a turbine INTEGER(IntKi), INTENT( OUT) :: ErrStat !< Error status of the operation CHARACTER(*), INTENT( OUT) :: ErrMsg !< Error message if ErrStat /= ErrID_None CHARACTER(*), OPTIONAL,INTENT(IN ) :: InFile !< A CHARACTER string containing the name of the primary FAST input file (if not present, we'll get it from the command line) TYPE(FAST_ExternInitType),OPTIONAL,INTENT(IN ) :: ExternInitData !< Initialization input data from an external source (Simulink) Turbine%TurbID = TurbID IF (PRESENT(InFile)) THEN IF (PRESENT(ExternInitData)) THEN CALL FAST_InitializeAll( t_initial, Turbine%p_FAST, Turbine%y_FAST, Turbine%m_FAST, & Turbine%ED, Turbine%BD, Turbine%SrvD, Turbine%AD14, Turbine%AD, Turbine%IfW, Turbine%OpFM, Turbine%SC,& Turbine%HD, Turbine%SD, Turbine%ExtPtfm, Turbine%MAP, Turbine%FEAM, Turbine%MD, Turbine%Orca, & Turbine%IceF, Turbine%IceD, Turbine%MeshMapData, ErrStat, ErrMsg, InFile, ExternInitData ) ELSE CALL FAST_InitializeAll( t_initial, Turbine%p_FAST, Turbine%y_FAST, Turbine%m_FAST, & Turbine%ED, Turbine%BD, Turbine%SrvD, Turbine%AD14, Turbine%AD, Turbine%IfW, Turbine%OpFM, Turbine%SC, & Turbine%HD, Turbine%SD, Turbine%ExtPtfm, Turbine%MAP, Turbine%FEAM, Turbine%MD, Turbine%Orca, & Turbine%IceF, Turbine%IceD, Turbine%MeshMapData, ErrStat, ErrMsg, InFile ) END IF ELSE CALL FAST_InitializeAll( t_initial, Turbine%p_FAST, Turbine%y_FAST, Turbine%m_FAST, & Turbine%ED, Turbine%BD, Turbine%SrvD, Turbine%AD14, Turbine%AD, Turbine%IfW, Turbine%OpFM, Turbine%SC, & Turbine%HD, Turbine%SD, Turbine%ExtPtfm, Turbine%MAP, Turbine%FEAM, Turbine%MD, Turbine%Orca, & Turbine%IceF, Turbine%IceD, Turbine%MeshMapData, ErrStat, ErrMsg ) END IF END SUBROUTINE FAST_InitializeAll_T !---------------------------------------------------------------------------------------------------------------------------------- !> Routine to call Init routine for each module. This routine sets all of the init input data for each module. SUBROUTINE FAST_InitializeAll( t_initial, p_FAST, y_FAST, m_FAST, ED, BD, SrvD, AD14, AD, IfW, OpFM, SC, HD, SD, ExtPtfm, & MAPp, FEAM, MD, Orca, IceF, IceD, MeshMapData, ErrStat, ErrMsg, InFile, ExternInitData ) use ElastoDyn_Parameters, only: Method_RK4 REAL(DbKi), INTENT(IN ) :: t_initial !< initial time TYPE(FAST_ParameterType), INTENT(INOUT) :: p_FAST !< Parameters for the glue code TYPE(FAST_OutputFileType),INTENT(INOUT) :: y_FAST !< Output variables for the glue code TYPE(FAST_MiscVarType), INTENT(INOUT) :: m_FAST !< Miscellaneous variables TYPE(ElastoDyn_Data), INTENT(INOUT) :: ED !< ElastoDyn data TYPE(BeamDyn_Data), INTENT(INOUT) :: BD !< BeamDyn data TYPE(ServoDyn_Data), INTENT(INOUT) :: SrvD !< ServoDyn data TYPE(AeroDyn14_Data), INTENT(INOUT) :: AD14 !< AeroDyn14 data TYPE(AeroDyn_Data), INTENT(INOUT) :: AD !< AeroDyn data TYPE(InflowWind_Data), INTENT(INOUT) :: IfW !< InflowWind data TYPE(OpenFOAM_Data), INTENT(INOUT) :: OpFM !< OpenFOAM data TYPE(SuperController_Data), INTENT(INOUT) :: SC !< SuperController data TYPE(HydroDyn_Data), INTENT(INOUT) :: HD !< HydroDyn data TYPE(SubDyn_Data), INTENT(INOUT) :: SD !< SubDyn data TYPE(ExtPtfm_Data), INTENT(INOUT) :: ExtPtfm !< ExtPtfm_MCKF data TYPE(MAP_Data), INTENT(INOUT) :: MAPp !< MAP data TYPE(FEAMooring_Data), INTENT(INOUT) :: FEAM !< FEAMooring data TYPE(MoorDyn_Data), INTENT(INOUT) :: MD !< Data for the MoorDyn module TYPE(OrcaFlex_Data), INTENT(INOUT) :: Orca !< OrcaFlex interface data TYPE(IceFloe_Data), INTENT(INOUT) :: IceF !< IceFloe data TYPE(IceDyn_Data), INTENT(INOUT) :: IceD !< All the IceDyn data used in time-step loop TYPE(FAST_ModuleMapType), INTENT(INOUT) :: MeshMapData !< Data for mapping between modules INTEGER(IntKi), INTENT( OUT) :: ErrStat !< Error status of the operation CHARACTER(*), INTENT( OUT) :: ErrMsg !< Error message if ErrStat /= ErrID_None CHARACTER(*), OPTIONAL, INTENT(IN ) :: InFile !< A CHARACTER string containing the name of the primary FAST input file (if not present, we'll get it from the command line) TYPE(FAST_ExternInitType), OPTIONAL, INTENT(IN) :: ExternInitData !< Initialization input data from an external source (Simulink) ! local variables CHARACTER(1024) :: InputFile !< A CHARACTER string containing the name of the primary FAST input file TYPE(FAST_InitData) :: Init !< Initialization data for all modules REAL(ReKi) :: AirDens ! air density for initialization/normalization of OpenFOAM data REAL(DbKi) :: dt_IceD ! tmp dt variable to ensure IceDyn doesn't specify different dt values for different legs (IceDyn instances) REAL(DbKi) :: dt_BD ! tmp dt variable to ensure BeamDyn doesn't specify different dt values for different instances INTEGER(IntKi) :: ErrStat2 INTEGER(IntKi) :: IceDim ! dimension we're pre-allocating for number of IceDyn legs/instances INTEGER(IntKi) :: I ! generic loop counter INTEGER(IntKi) :: k ! blade loop counter logical :: CallStart CHARACTER(ErrMsgLen) :: ErrMsg2 CHARACTER(*), PARAMETER :: RoutineName = 'FAST_InitializeAll' !.......... ErrStat = ErrID_None ErrMsg = "" y_FAST%UnSum = -1 ! set the summary file unit to -1 to indicate it's not open y_FAST%UnOu = -1 ! set the text output file unit to -1 to indicate it's not open y_FAST%UnGra = -1 ! set the binary graphics output file unit to -1 to indicate it's not open p_FAST%WrVTK = VTK_Unknown ! set this so that we can potentially output VTK information on initialization error p_FAST%VTK_tWidth = 1 ! initialize in case of error before reading the full file p_FAST%n_VTKTime = 1 ! initialize in case of error before reading the full file y_FAST%VTK_LastWaveIndx = 1 ! Start looking for wave data at the first index y_FAST%VTK_count = 0 ! first VTK file has 0 as output y_FAST%n_Out = 0 ! set the number of ouptut channels to 0 to indicate there's nothing to write to the binary file p_FAST%ModuleInitialized = .FALSE. ! (array initialization) no modules are initialized ! Get the current time CALL DATE_AND_TIME ( Values=m_FAST%StrtTime ) ! Let's time the whole simulation CALL CPU_TIME ( m_FAST%UsrTime1 ) ! Initial time (this zeros the start time when used as a MATLAB function) m_FAST%UsrTime1 = MAX( 0.0_ReKi, m_FAST%UsrTime1 ) ! CPU_TIME: If a meaningful time cannot be returned, a processor-dependent negative value is returned m_FAST%t_global = t_initial - 20. ! initialize this to a number < t_initial for error message in ProgAbort m_FAST%calcJacobian = .TRUE. ! we need to calculate the Jacobian m_FAST%NextJacCalcTime = m_FAST%t_global ! We want to calculate the Jacobian on the first step p_FAST%TDesc = '' ! p_FAST%CheckHSSBrTrqC = .false. y_FAST%Lin%WindSpeed = 0.0_ReKi if (present(ExternInitData)) then CallStart = .not. ExternInitData%FarmIntegration ! .and. ExternInitData%TurbineID == 1 if (ExternInitData%TurbineID > 0) p_FAST%TDesc = 'T'//trim(num2lstr(ExternInitData%TurbineID)) else CallStart = .true. end if ! Init NWTC_Library, display copyright and version information: if (CallStart) then AbortErrLev = ErrID_Fatal ! Until we read otherwise from the FAST input file, we abort only on FATAL errors CALL FAST_ProgStart( FAST_Ver ) p_FAST%WrSttsTime = .TRUE. else ! if we don't call the start data (e.g., from FAST.Farm), we won't override AbortErrLev either CALL DispNVD( FAST_Ver ) p_FAST%WrSttsTime = .FALSE. end if IF (PRESENT(InFile)) THEN p_FAST%UseDWM = .FALSE. InputFile = InFile ELSE CALL GetInputFileName(InputFile,p_FAST%UseDWM,ErrStat2,ErrMsg2) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) IF (ErrStat >= AbortErrLev) THEN CALL Cleanup() RETURN END IF END IF ! ... Open and read input files ... ! also, set turbine reference position for graphics output if (PRESENT(ExternInitData)) then p_FAST%TurbinePos = ExternInitData%TurbinePos if (ExternInitData%FarmIntegration) then ! we're integrating with FAST.Farm CALL FAST_Init( p_FAST, m_FAST, y_FAST, t_initial, InputFile, ErrStat2, ErrMsg2, ExternInitData%TMax, OverrideAbortLev=.false., RootName=ExternInitData%RootName ) else CALL FAST_Init( p_FAST, m_FAST, y_FAST, t_initial, InputFile, ErrStat2, ErrMsg2, ExternInitData%TMax, ExternInitData%TurbineID ) ! We have the name of the input file and the simulation length from somewhere else (e.g. Simulink) end if else p_FAST%TurbinePos = 0.0_ReKi CALL FAST_Init( p_FAST, m_FAST, y_FAST, t_initial, InputFile, ErrStat2, ErrMsg2 ) ! We have the name of the input file from somewhere else (e.g. Simulink) end if CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) IF (ErrStat >= AbortErrLev) THEN CALL Cleanup() RETURN END IF !............................................................................................................................... p_FAST%dt_module = p_FAST%dt ! initialize time steps for each module ! ........................ ! initialize ElastoDyn (must be done first) ! ........................ ALLOCATE( ED%Input( p_FAST%InterpOrder+1 ), ED%InputTimes( p_FAST%InterpOrder+1 ),STAT = ErrStat2 ) IF (ErrStat2 /= 0) THEN CALL SetErrStat(ErrID_Fatal,"Error allocating ED%Input and ED%InputTimes.",ErrStat,ErrMsg,RoutineName) CALL Cleanup() RETURN END IF Init%InData_ED%Linearize = p_FAST%Linearize Init%InData_ED%InputFile = p_FAST%EDFile IF ( p_FAST%CompAero == Module_AD14 ) THEN Init%InData_ED%ADInputFile = p_FAST%AeroFile ELSE Init%InData_ED%ADInputFile = "" END IF Init%InData_ED%RootName = TRIM(p_FAST%OutFileRoot)//'.'//TRIM(y_FAST%Module_Abrev(Module_ED)) Init%InData_ED%CompElast = p_FAST%CompElast == Module_ED CALL ED_Init( Init%InData_ED, ED%Input(1), ED%p, ED%x(STATE_CURR), ED%xd(STATE_CURR), ED%z(STATE_CURR), ED%OtherSt(STATE_CURR), & ED%y, ED%m, p_FAST%dt_module( MODULE_ED ), Init%OutData_ED, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) p_FAST%ModuleInitialized(Module_ED) = .TRUE. CALL SetModuleSubstepTime(Module_ED, p_FAST, y_FAST, ErrStat2, ErrMsg2) CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) ! bjj: added this check per jmj; perhaps it would be better in ElastoDyn, but I'll leave it here for now: IF ( p_FAST%TurbineType == Type_Offshore_Floating ) THEN IF ( ED%p%TowerBsHt < 0.0_ReKi .AND. .NOT. EqualRealNos( ED%p%TowerBsHt, 0.0_ReKi ) ) THEN CALL SetErrStat(ErrID_Fatal,"ElastoDyn TowerBsHt must not be negative for floating offshore systems.",ErrStat,ErrMsg,RoutineName) END IF END IF allocate( y_FAST%Lin%Modules(MODULE_ED)%Instance(1), stat=ErrStat2) if (ErrStat2 /= 0 ) then call SetErrStat(ErrID_Fatal, "Error allocating Lin%Modules(ED).", ErrStat, ErrMsg, RoutineName ) else if (allocated(Init%OutData_ED%LinNames_y)) call move_alloc(Init%OutData_ED%LinNames_y,y_FAST%Lin%Modules(MODULE_ED)%Instance(1)%Names_y) if (allocated(Init%OutData_ED%LinNames_x)) call move_alloc(Init%OutData_ED%LinNames_x,y_FAST%Lin%Modules(MODULE_ED)%Instance(1)%Names_x) if (allocated(Init%OutData_ED%LinNames_u)) call move_alloc(Init%OutData_ED%LinNames_u,y_FAST%Lin%Modules(MODULE_ED)%Instance(1)%Names_u) if (allocated(Init%OutData_ED%RotFrame_y)) call move_alloc(Init%OutData_ED%RotFrame_y,y_FAST%Lin%Modules(MODULE_ED)%Instance(1)%RotFrame_y) if (allocated(Init%OutData_ED%RotFrame_x)) call move_alloc(Init%OutData_ED%RotFrame_x,y_FAST%Lin%Modules(MODULE_ED)%Instance(1)%RotFrame_x) if (allocated(Init%OutData_ED%DerivOrder_x)) call move_alloc(Init%OutData_ED%DerivOrder_x,y_FAST%Lin%Modules(MODULE_ED)%Instance(1)%DerivOrder_x) if (allocated(Init%OutData_ED%RotFrame_u)) call move_alloc(Init%OutData_ED%RotFrame_u,y_FAST%Lin%Modules(MODULE_ED)%Instance(1)%RotFrame_u) if (allocated(Init%OutData_ED%IsLoad_u )) call move_alloc(Init%OutData_ED%IsLoad_u ,y_FAST%Lin%Modules(MODULE_ED)%Instance(1)%IsLoad_u ) if (allocated(Init%OutData_ED%WriteOutputHdr)) y_FAST%Lin%Modules(MODULE_ED)%Instance(1)%NumOutputs = size(Init%OutData_ED%WriteOutputHdr) end if IF (ErrStat >= AbortErrLev) THEN CALL Cleanup() RETURN END IF if (p_FAST%CalcSteady) then if ( EqualRealNos(Init%OutData_ED%RotSpeed, 0.0_ReKi) ) then p_FAST%TrimCase = TrimCase_none p_FAST%NLinTimes = 1 p_FAST%LinInterpOrder = 0 ! constant values elseif ( Init%OutData_ED%isFixed_GenDOF ) then p_FAST%TrimCase = TrimCase_none end if end if ! ........................ ! initialize BeamDyn ! ........................ IF ( p_FAST%CompElast == Module_BD ) THEN p_FAST%nBeams = Init%OutData_ED%NumBl ! initialize number of BeamDyn instances = number of blades ELSE p_FAST%nBeams = 0 END IF ALLOCATE( BD%Input( p_FAST%InterpOrder+1, p_FAST%nBeams ), BD%InputTimes( p_FAST%InterpOrder+1, p_FAST%nBeams ), STAT = ErrStat2 ) IF (ErrStat2 /= 0) THEN CALL SetErrStat(ErrID_Fatal,"Error allocating BD%Input and BD%InputTimes.",ErrStat,ErrMsg,RoutineName) CALL Cleanup() RETURN END IF ALLOCATE( BD%x( p_FAST%nBeams,2), & BD%xd( p_FAST%nBeams,2), & BD%z( p_FAST%nBeams,2), & BD%OtherSt( p_FAST%nBeams,2), & BD%p( p_FAST%nBeams ), & BD%u( p_FAST%nBeams ), & BD%y( p_FAST%nBeams ), & BD%m( p_FAST%nBeams ), & Init%OutData_BD(p_FAST%nBeams ), & STAT = ErrStat2 ) IF (ErrStat2 /= 0) THEN CALL SetErrStat(ErrID_Fatal,"Error allocating BeamDyn state, input, and output data.",ErrStat,ErrMsg,RoutineName) CALL Cleanup() RETURN END IF IF (p_FAST%CompElast == Module_BD) THEN Init%InData_BD%DynamicSolve = .TRUE. ! FAST can only couple to BeamDyn when dynamic solve is used. Init%InData_BD%Linearize = p_FAST%Linearize Init%InData_BD%gravity = (/ 0.0_ReKi, 0.0_ReKi, -Init%OutData_ED%Gravity /) ! "Gravitational acceleration" m/s^2 ! now initialize BeamDyn for all beams dt_BD = p_FAST%dt_module( MODULE_BD ) Init%InData_BD%HubPos = ED%y%HubPtMotion%Position(:,1) Init%InData_BD%HubRot = ED%y%HubPtMotion%RefOrientation(:,:,1) p_FAST%BD_OutputSibling = .true. allocate( y_FAST%Lin%Modules(MODULE_BD)%Instance(p_FAST%nBeams), stat=ErrStat2) if (ErrStat2 /= 0 ) then call SetErrStat(ErrID_Fatal, "Error allocating Lin%Modules(BD).", ErrStat, ErrMsg, RoutineName ) CALL Cleanup() RETURN end if DO k=1,p_FAST%nBeams Init%InData_BD%RootName = TRIM(p_FAST%OutFileRoot)//'.'//TRIM(y_FAST%Module_Abrev(Module_BD))//TRIM( Num2LStr(k) ) Init%InData_BD%InputFile = p_FAST%BDBldFile(k) Init%InData_BD%GlbPos = ED%y%BladeRootMotion(k)%Position(:,1) ! {:} - - "Initial Position Vector of the local blade coordinate system" Init%InData_BD%GlbRot = ED%y%BladeRootMotion(k)%RefOrientation(:,:,1) ! {:}{:} - - "Initial direction cosine matrix of the local blade coordinate system" Init%InData_BD%RootDisp = ED%y%BladeRootMotion(k)%TranslationDisp(:,1) ! {:} - - "Initial root displacement" Init%InData_BD%RootOri = ED%y%BladeRootMotion(k)%Orientation(:,:,1) ! {:}{:} - - "Initial root orientation" Init%InData_BD%RootVel(1:3) = ED%y%BladeRootMotion(k)%TranslationVel(:,1) ! {:} - - "Initial root velocities and angular veolcities" Init%InData_BD%RootVel(4:6) = ED%y%BladeRootMotion(k)%RotationVel(:,1) ! {:} - - "Initial root velocities and angular veolcities" CALL BD_Init( Init%InData_BD, BD%Input(1,k), BD%p(k), BD%x(k,STATE_CURR), BD%xd(k,STATE_CURR), BD%z(k,STATE_CURR), & BD%OtherSt(k,STATE_CURR), BD%y(k), BD%m(k), dt_BD, Init%OutData_BD(k), ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) !bjj: we're going to force this to have the same timestep because I don't want to have to deal with n BD modules with n timesteps. IF ( k == 1 ) THEN p_FAST%dt_module( MODULE_BD ) = dt_BD p_FAST%ModuleInitialized(Module_BD) = .TRUE. ! this really should be once per BD instance, but BD doesn't care so I won't go through the effort to track this CALL SetModuleSubstepTime(Module_BD, p_FAST, y_FAST, ErrStat2, ErrMsg2) CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) ELSEIF ( .NOT. EqualRealNos( p_FAST%dt_module( MODULE_BD ),dt_BD )) THEN CALL SetErrStat(ErrID_Fatal,"All instances of BeamDyn (one per blade) must have the same time step.",ErrStat,ErrMsg,RoutineName) END IF ! We're going to do fewer computations if the BD input and output meshes that couple to AD are siblings: if (BD%p(k)%BldMotionNodeLoc /= BD_MESH_QP) p_FAST%BD_OutputSibling = .false. if (ErrStat>=AbortErrLev) exit !exit this loop so we don't get p_FAST%nBeams of the same errors if (allocated(Init%OutData_BD(k)%LinNames_y)) call move_alloc(Init%OutData_BD(k)%LinNames_y, y_FAST%Lin%Modules(MODULE_BD)%Instance(k)%Names_y ) if (allocated(Init%OutData_BD(k)%LinNames_x)) call move_alloc(Init%OutData_BD(k)%LinNames_x, y_FAST%Lin%Modules(MODULE_BD)%Instance(k)%Names_x ) if (allocated(Init%OutData_BD(k)%LinNames_u)) call move_alloc(Init%OutData_BD(k)%LinNames_u, y_FAST%Lin%Modules(MODULE_BD)%Instance(k)%Names_u ) if (allocated(Init%OutData_BD(k)%RotFrame_y)) call move_alloc(Init%OutData_BD(k)%RotFrame_y, y_FAST%Lin%Modules(MODULE_BD)%Instance(k)%RotFrame_y ) if (allocated(Init%OutData_BD(k)%RotFrame_x)) call move_alloc(Init%OutData_BD(k)%RotFrame_x, y_FAST%Lin%Modules(MODULE_BD)%Instance(k)%RotFrame_x ) if (allocated(Init%OutData_BD(k)%RotFrame_u)) call move_alloc(Init%OutData_BD(k)%RotFrame_u, y_FAST%Lin%Modules(MODULE_BD)%Instance(k)%RotFrame_u ) if (allocated(Init%OutData_BD(k)%IsLoad_u )) call move_alloc(Init%OutData_BD(k)%IsLoad_u , y_FAST%Lin%Modules(MODULE_BD)%Instance(k)%IsLoad_u ) if (allocated(Init%OutData_BD(k)%DerivOrder_x )) call move_alloc(Init%OutData_BD(k)%DerivOrder_x , y_FAST%Lin%Modules(MODULE_BD)%Instance(k)%DerivOrder_x ) if (allocated(Init%OutData_BD(k)%WriteOutputHdr)) y_FAST%Lin%Modules(MODULE_BD)%Instance(k)%NumOutputs = size(Init%OutData_BD(k)%WriteOutputHdr) END DO IF (ErrStat >= AbortErrLev) THEN CALL Cleanup() RETURN END IF END IF ! ........................ ! initialize AeroDyn ! ........................ ALLOCATE( AD14%Input( p_FAST%InterpOrder+1 ), AD14%InputTimes( p_FAST%InterpOrder+1 ), STAT = ErrStat2 ) IF (ErrStat2 /= 0) THEN CALL SetErrStat(ErrID_Fatal,"Error allocating AD14%Input and AD14%InputTimes.",ErrStat,ErrMsg,RoutineName) CALL Cleanup() RETURN END IF ALLOCATE( AD%Input( p_FAST%InterpOrder+1 ), AD%InputTimes( p_FAST%InterpOrder+1 ), STAT = ErrStat2 ) IF (ErrStat2 /= 0) THEN CALL SetErrStat(ErrID_Fatal,"Error allocating AD%Input and AD%InputTimes.",ErrStat,ErrMsg,RoutineName) CALL Cleanup() RETURN END IF IF ( p_FAST%CompAero == Module_AD14 ) THEN CALL AD_SetInitInput(Init%InData_AD14, Init%OutData_ED, ED%y, p_FAST, ErrStat2, ErrMsg2) ! set the values in Init%InData_AD14 CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) CALL AD14_Init( Init%InData_AD14, AD14%Input(1), AD14%p, AD14%x(STATE_CURR), AD14%xd(STATE_CURR), AD14%z(STATE_CURR), & AD14%OtherSt(STATE_CURR), AD14%y, AD14%m, p_FAST%dt_module( MODULE_AD14 ), Init%OutData_AD14, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) p_FAST%ModuleInitialized(Module_AD14) = .TRUE. CALL SetModuleSubstepTime(Module_AD14, p_FAST, y_FAST, ErrStat2, ErrMsg2) CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) ! bjj: this really shouldn't be in the FAST glue code, but I'm going to put this check here so people don't use an invalid model ! and send me emails to debug numerical issues in their results. IF ( AD14%p%TwrProps%PJM_Version .AND. p_FAST%TurbineType == Type_Offshore_Floating ) THEN CALL SetErrStat(ErrID_Fatal,'AeroDyn v14 tower influence model "NEWTOWER" is invalid for models of floating offshore turbines.',ErrStat,ErrMsg,RoutineName) END IF AirDens = Init%OutData_AD14%AirDens IF (ErrStat >= AbortErrLev) THEN CALL Cleanup() RETURN END IF ELSEIF ( p_FAST%CompAero == Module_AD ) THEN ! set initialization data for AD CALL AllocAry( Init%InData_AD%BladeRootPosition, 3, Init%OutData_ED%NumBl, 'Init%InData_AD%BladeRootPosition', errStat2, ErrMsg2) CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) CALL AllocAry( Init%InData_AD%BladeRootOrientation,3, 3, Init%OutData_ED%NumBl, 'Init%InData_AD%BladeRootOrientation', errStat2, ErrMsg2) CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) IF (ErrStat >= AbortErrLev) THEN CALL Cleanup() RETURN END IF Init%InData_AD%Gravity = Init%OutData_ED%Gravity Init%InData_AD%Linearize = p_FAST%Linearize Init%InData_AD%InputFile = p_FAST%AeroFile Init%InData_AD%NumBlades = Init%OutData_ED%NumBl Init%InData_AD%RootName = p_FAST%OutFileRoot Init%InData_AD%HubPosition = ED%y%HubPtMotion%Position(:,1) Init%InData_AD%HubOrientation = ED%y%HubPtMotion%RefOrientation(:,:,1) do k=1,Init%OutData_ED%NumBl Init%InData_AD%BladeRootPosition(:,k) = ED%y%BladeRootMotion(k)%Position(:,1) Init%InData_AD%BladeRootOrientation(:,:,k) = ED%y%BladeRootMotion(k)%RefOrientation(:,:,1) end do CALL AD_Init( Init%InData_AD, AD%Input(1), AD%p, AD%x(STATE_CURR), AD%xd(STATE_CURR), AD%z(STATE_CURR), & AD%OtherSt(STATE_CURR), AD%y, AD%m, p_FAST%dt_module( MODULE_AD ), Init%OutData_AD, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) p_FAST%ModuleInitialized(Module_AD) = .TRUE. CALL SetModuleSubstepTime(Module_AD, p_FAST, y_FAST, ErrStat2, ErrMsg2) CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) allocate( y_FAST%Lin%Modules(MODULE_AD)%Instance(1), stat=ErrStat2) if (ErrStat2 /= 0 ) then call SetErrStat(ErrID_Fatal, "Error allocating Lin%Modules(AD).", ErrStat, ErrMsg, RoutineName ) else if (allocated(Init%OutData_AD%LinNames_u )) call move_alloc(Init%OutData_AD%LinNames_u ,y_FAST%Lin%Modules(MODULE_AD)%Instance(1)%Names_u ) if (allocated(Init%OutData_AD%LinNames_y )) call move_alloc(Init%OutData_AD%LinNames_y ,y_FAST%Lin%Modules(MODULE_AD)%Instance(1)%Names_y ) if (allocated(Init%OutData_AD%LinNames_x )) call move_alloc(Init%OutData_AD%LinNames_x ,y_FAST%Lin%Modules(MODULE_AD)%Instance(1)%Names_x ) if (allocated(Init%OutData_AD%RotFrame_u )) call move_alloc(Init%OutData_AD%RotFrame_u ,y_FAST%Lin%Modules(MODULE_AD)%Instance(1)%RotFrame_u ) if (allocated(Init%OutData_AD%RotFrame_y )) call move_alloc(Init%OutData_AD%RotFrame_y ,y_FAST%Lin%Modules(MODULE_AD)%Instance(1)%RotFrame_y ) if (allocated(Init%OutData_AD%RotFrame_x )) call move_alloc(Init%OutData_AD%RotFrame_x ,y_FAST%Lin%Modules(MODULE_AD)%Instance(1)%RotFrame_x ) if (allocated(Init%OutData_AD%IsLoad_u )) call move_alloc(Init%OutData_AD%IsLoad_u ,y_FAST%Lin%Modules(MODULE_AD)%Instance(1)%IsLoad_u ) if (allocated(Init%OutData_AD%DerivOrder_x)) call move_alloc(Init%OutData_AD%DerivOrder_x,y_FAST%Lin%Modules(MODULE_AD)%Instance(1)%DerivOrder_x ) if (allocated(Init%OutData_AD%WriteOutputHdr)) y_FAST%Lin%Modules(MODULE_AD)%Instance(1)%NumOutputs = size(Init%OutData_AD%WriteOutputHdr) end if IF (ErrStat >= AbortErrLev) THEN CALL Cleanup() RETURN END IF AirDens = Init%OutData_AD%AirDens ELSE AirDens = 0.0_ReKi END IF ! CompAero ! ........................ ! initialize InflowWind ! ........................ ALLOCATE( IfW%Input( p_FAST%InterpOrder+1 ), IfW%InputTimes( p_FAST%InterpOrder+1 ), STAT = ErrStat2 ) IF (ErrStat2 /= 0) THEN CALL SetErrStat(ErrID_Fatal,"Error allocating IfW%Input and IfW%InputTimes.",ErrStat,ErrMsg,RoutineName) CALL Cleanup() RETURN END IF IF ( p_FAST%CompInflow == Module_IfW ) THEN Init%InData_IfW%Linearize = p_FAST%Linearize Init%InData_IfW%InputFileName = p_FAST%InflowFile Init%InData_IfW%RootName = TRIM(p_FAST%OutFileRoot)//'.'//TRIM(y_FAST%Module_Abrev(Module_IfW)) Init%InData_IfW%UseInputFile = .TRUE. Init%InData_IfW%NumWindPoints = 0 IF ( p_FAST%CompServo == Module_SrvD ) Init%InData_IfW%NumWindPoints = Init%InData_IfW%NumWindPoints + 1 IF ( p_FAST%CompAero == Module_AD14 ) THEN Init%InData_IfW%NumWindPoints = Init%InData_IfW%NumWindPoints + Init%OutData_ED%NumBl * AD14%Input(1)%InputMarkers(1)%NNodes + AD14%Input(1)%Twr_InputMarkers%NNodes ELSEIF ( p_FAST%CompAero == Module_AD ) THEN Init%InData_IfW%NumWindPoints = Init%InData_IfW%NumWindPoints + AD%Input(1)%TowerMotion%NNodes DO k=1,Init%OutData_ED%NumBl Init%InData_IfW%NumWindPoints = Init%InData_IfW%NumWindPoints + AD%Input(1)%BladeMotion(k)%NNodes END DO if (allocated(AD%OtherSt(STATE_CURR)%WakeLocationPoints)) then Init%InData_IfW%NumWindPoints = Init%InData_IfW%NumWindPoints + size(AD%OtherSt(STATE_CURR)%WakeLocationPoints,DIM=2) end if END IF ! lidar Init%InData_IfW%lidar%Tmax = p_FAST%TMax Init%InData_IfW%lidar%HubPosition = ED%y%HubPtMotion%Position(:,1) IF ( PRESENT(ExternInitData) ) THEN Init%InData_IfW%Use4Dext = ExternInitData%FarmIntegration if (Init%InData_IfW%Use4Dext) then Init%InData_IfW%FDext%n = ExternInitData%windGrid_n Init%InData_IfW%FDext%delta = ExternInitData%windGrid_delta Init%InData_IfW%FDext%pZero = ExternInitData%windGrid_pZero end if ! bjj: these lidar inputs should come from an InflowWind input file; I'm hard coding them here for now Init%InData_IfW%lidar%SensorType = ExternInitData%SensorType Init%InData_IfW%lidar%LidRadialVel = ExternInitData%LidRadialVel Init%InData_IfW%lidar%RotorApexOffsetPos = 0.0 Init%InData_IfW%lidar%NumPulseGate = 0 ELSE Init%InData_IfW%lidar%SensorType = SensorType_None Init%InData_IfW%Use4Dext = .false. END IF CALL InflowWind_Init( Init%InData_IfW, IfW%Input(1), IfW%p, IfW%x(STATE_CURR), IfW%xd(STATE_CURR), IfW%z(STATE_CURR), & IfW%OtherSt(STATE_CURR), IfW%y, IfW%m, p_FAST%dt_module( MODULE_IfW ), Init%OutData_IfW, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) p_FAST%ModuleInitialized(Module_IfW) = .TRUE. CALL SetModuleSubstepTime(Module_IfW, p_FAST, y_FAST, ErrStat2, ErrMsg2) CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) allocate( y_FAST%Lin%Modules(MODULE_IfW)%Instance(1), stat=ErrStat2) if (ErrStat2 /= 0 ) then call SetErrStat(ErrID_Fatal, "Error allocating Lin%Modules(IfW).", ErrStat, ErrMsg, RoutineName ) else if (allocated(Init%OutData_IfW%LinNames_y)) call move_alloc(Init%OutData_IfW%LinNames_y,y_FAST%Lin%Modules(MODULE_IfW)%Instance(1)%Names_y ) if (allocated(Init%OutData_IfW%LinNames_u)) call move_alloc(Init%OutData_IfW%LinNames_u,y_FAST%Lin%Modules(MODULE_IfW)%Instance(1)%Names_u ) if (allocated(Init%OutData_IfW%RotFrame_y)) call move_alloc(Init%OutData_IfW%RotFrame_y,y_FAST%Lin%Modules(MODULE_IfW)%Instance(1)%RotFrame_y ) if (allocated(Init%OutData_IfW%RotFrame_u)) call move_alloc(Init%OutData_IfW%RotFrame_u,y_FAST%Lin%Modules(MODULE_IfW)%Instance(1)%RotFrame_u ) if (allocated(Init%OutData_IfW%IsLoad_u )) call move_alloc(Init%OutData_IfW%IsLoad_u ,y_FAST%Lin%Modules(MODULE_IfW)%Instance(1)%IsLoad_u ) if (allocated(Init%OutData_IfW%WriteOutputHdr)) y_FAST%Lin%Modules(MODULE_IfW)%Instance(1)%NumOutputs = size(Init%OutData_IfW%WriteOutputHdr) y_FAST%Lin%WindSpeed = Init%OutData_IfW%WindFileInfo%MWS end if IF (ErrStat >= AbortErrLev) THEN CALL Cleanup() RETURN END IF ELSEIF ( p_FAST%CompInflow == Module_OpFM ) THEN IF ( PRESENT(ExternInitData) ) THEN Init%InData_OpFM%NumSC2Ctrl = ExternInitData%NumSC2Ctrl Init%InData_OpFM%NumCtrl2SC = ExternInitData%NumCtrl2SC Init%InData_OpFM%NumActForcePtsBlade = ExternInitData%NumActForcePtsBlade Init%InData_OpFM%NumActForcePtsTower = ExternInitData%NumActForcePtsTower ELSE CALL SetErrStat( ErrID_Fatal, 'OpenFOAM integration can be used only with external input data (not the stand-alone executable).', ErrStat, ErrMsg, RoutineName ) CALL Cleanup() RETURN END IF Init%InData_OpFM%BladeLength = Init%OutData_ED%BladeLength Init%InData_OpFM%TowerHeight = Init%OutData_ED%TowerHeight Init%InData_OpFM%TowerBaseHeight = Init%OutData_ED%TowerBaseHeight ALLOCATE(Init%InData_OpFM%StructBldRNodes( SIZE(Init%OutData_ED%BldRNodes)), STAT=ErrStat2) Init%InData_OpFM%StructBldRNodes(:) = Init%OutData_ED%BldRNodes(:) ALLOCATE(Init%InData_OpFM%StructTwrHNodes( SIZE(Init%OutData_ED%TwrHNodes)), STAT=ErrStat2) Init%InData_OpFM%StructTwrHNodes(:) = Init%OutData_ED%TwrHNodes(:) IF (ErrStat2 /= 0) THEN CALL SetErrStat(ErrID_Fatal,"Error allocating OpFM%InitInput.",ErrStat,ErrMsg,RoutineName) CALL Cleanup() RETURN END IF ! set up the data structures for integration with OpenFOAM CALL Init_OpFM( Init%InData_OpFM, p_FAST, AirDens, AD14%Input(1), AD%Input(1), Init%OutData_AD, AD%y, ED%y, OpFM, Init%OutData_OpFM, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) IF (ErrStat >= AbortErrLev) THEN CALL Cleanup() RETURN END IF !bjj: fix me!!! to do Init%OutData_IfW%WindFileInfo%MWS = 0.0_ReKi ELSE Init%OutData_IfW%WindFileInfo%MWS = 0.0_ReKi END IF ! CompInflow ! ........................ ! initialize SuperController ! ........................ IF ( PRESENT(ExternInitData) ) THEN Init%InData_SC%NumSC2Ctrl = ExternInitData%NumSC2Ctrl Init%InData_SC%NumCtrl2SC = ExternInitData%NumCtrl2SC ELSE Init%InData_SC%NumSC2Ctrl = 0 Init%InData_SC%NumCtrl2SC = 0 END IF ! set up the data structures for integration with supercontroller CALL Init_SC( Init%InData_SC, SC, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) IF (ErrStat >= AbortErrLev) THEN CALL Cleanup() RETURN END IF ! ........................ ! some checks for AeroDyn14's Dynamic Inflow with Mean Wind Speed from InflowWind: ! (DO NOT COPY THIS CODE!) ! bjj: AeroDyn14 should not need this rule of thumb; it should check the instantaneous values when the code runs ! ........................ IF ( p_FAST%CompAero == Module_AD14 ) THEN IF (AD14%p%DynInfl) THEN IF ( Init%OutData_IfW%WindFileInfo%MWS < 8.0 ) THEN CALL SetErrStat(ErrID_Fatal,'AeroDyn v14 "DYNINFL" InfModel is invalid for models with wind speeds less than 8 m/s.',ErrStat,ErrMsg,RoutineName) !CALL SetErrStat(ErrID_Info,'Estimated average inflow wind speed is less than 8 m/s. Dynamic Inflow will be turned off.',ErrStat,ErrMess,RoutineName ) END IF END IF END IF ! ........................ ! initialize ServoDyn ! ........................ ALLOCATE( SrvD%Input( p_FAST%InterpOrder+1 ), SrvD%InputTimes( p_FAST%InterpOrder+1 ), STAT = ErrStat2 ) IF (ErrStat2 /= 0) THEN CALL SetErrStat(ErrID_Fatal,"Error allocating SrvD%Input and SrvD%InputTimes.",ErrStat,ErrMsg,RoutineName) CALL Cleanup() RETURN END IF IF ( p_FAST%CompServo == Module_SrvD ) THEN Init%InData_SrvD%InputFile = p_FAST%ServoFile Init%InData_SrvD%RootName = TRIM(p_FAST%OutFileRoot)//'.'//TRIM(y_FAST%Module_Abrev(Module_SrvD)) Init%InData_SrvD%NumBl = Init%OutData_ED%NumBl Init%InData_SrvD%gravity = Init%OutData_ED%gravity Init%InData_SrvD%r_N_O_G = ED%Input(1)%NacelleLoads%Position(:,1) Init%InData_SrvD%r_TwrBase = Init%OutData_ED%TwrBasePos Init%InData_SrvD%TMax = p_FAST%TMax Init%InData_SrvD%AirDens = AirDens Init%InData_SrvD%AvgWindSpeed = Init%OutData_IfW%WindFileInfo%MWS Init%InData_SrvD%Linearize = p_FAST%Linearize Init%InData_SrvD%TrimCase = p_FAST%TrimCase Init%InData_SrvD%TrimGain = p_FAST%TrimGain Init%InData_SrvD%RotSpeedRef = Init%OutData_ED%RotSpeed IF ( PRESENT(ExternInitData) ) THEN Init%InData_SrvD%NumSC2Ctrl = ExternInitData%NumSC2Ctrl Init%InData_SrvD%NumCtrl2SC = ExternInitData%NumCtrl2SC ELSE Init%InData_SrvD%NumSC2Ctrl = 0 Init%InData_SrvD%NumCtrl2SC = 0 END IF CALL AllocAry(Init%InData_SrvD%BlPitchInit, Init%OutData_ED%NumBl, 'BlPitchInit', ErrStat2, ErrMsg2) CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) if (ErrStat >= abortErrLev) then ! make sure allocatable arrays are valid before setting them CALL Cleanup() RETURN end if Init%InData_SrvD%BlPitchInit = Init%OutData_ED%BlPitch CALL SrvD_Init( Init%InData_SrvD, SrvD%Input(1), SrvD%p, SrvD%x(STATE_CURR), SrvD%xd(STATE_CURR), SrvD%z(STATE_CURR), & SrvD%OtherSt(STATE_CURR), SrvD%y, SrvD%m, p_FAST%dt_module( MODULE_SrvD ), Init%OutData_SrvD, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) p_FAST%ModuleInitialized(Module_SrvD) = .TRUE. !IF ( Init%OutData_SrvD%CouplingScheme == ExplicitLoose ) THEN ... bjj: abort if we're doing anything else! CALL SetModuleSubstepTime(Module_SrvD, p_FAST, y_FAST, ErrStat2, ErrMsg2) CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) !! initialize SrvD%y%ElecPwr and SrvD%y%GenTq because they are one timestep different (used as input for the next step)? allocate( y_FAST%Lin%Modules(MODULE_SrvD)%Instance(1), stat=ErrStat2) if (ErrStat2 /= 0 ) then call SetErrStat(ErrID_Fatal, "Error allocating Lin%Modules(SrvD).", ErrStat, ErrMsg, RoutineName ) else if (allocated(Init%OutData_SrvD%LinNames_y)) call move_alloc(Init%OutData_SrvD%LinNames_y,y_FAST%Lin%Modules(MODULE_SrvD)%Instance(1)%Names_y ) if (allocated(Init%OutData_SrvD%LinNames_u)) call move_alloc(Init%OutData_SrvD%LinNames_u,y_FAST%Lin%Modules(MODULE_SrvD)%Instance(1)%Names_u ) if (allocated(Init%OutData_SrvD%RotFrame_y)) call move_alloc(Init%OutData_SrvD%RotFrame_y,y_FAST%Lin%Modules(MODULE_SrvD)%Instance(1)%RotFrame_y ) if (allocated(Init%OutData_SrvD%RotFrame_u)) call move_alloc(Init%OutData_SrvD%RotFrame_u,y_FAST%Lin%Modules(MODULE_SrvD)%Instance(1)%RotFrame_u ) if (allocated(Init%OutData_SrvD%IsLoad_u )) call move_alloc(Init%OutData_SrvD%IsLoad_u ,y_FAST%Lin%Modules(MODULE_SrvD)%Instance(1)%IsLoad_u ) if (allocated(Init%OutData_SrvD%WriteOutputHdr)) y_FAST%Lin%Modules(MODULE_SrvD)%Instance(1)%NumOutputs = size(Init%OutData_SrvD%WriteOutputHdr) end if IF (ErrStat >= AbortErrLev) THEN CALL Cleanup() RETURN END IF ! ........................ ! some checks for AeroDyn and ElastoDyn inputs with the high-speed shaft brake hack in ElastoDyn: ! (DO NOT COPY THIS CODE!) ! ........................ ! bjj: this is a hack to get high-speed shaft braking in FAST v8 IF ( Init%OutData_SrvD%UseHSSBrake ) THEN IF ( p_FAST%CompAero == Module_AD14 ) THEN IF ( AD14%p%DYNINFL ) THEN CALL SetErrStat(ErrID_Fatal,'AeroDyn v14 "DYNINFL" InfModel is invalid for models with high-speed shaft braking.',ErrStat,ErrMsg,RoutineName) END IF END IF IF ( ED%p%method == Method_RK4 ) THEN ! bjj: should be using ElastoDyn's Method_ABM4 Method_AB4 parameters CALL SetErrStat(ErrID_Fatal,'ElastoDyn must use the AB4 or ABM4 integration method to implement high-speed shaft braking.',ErrStat,ErrMsg,RoutineName) ENDIF END IF ! Init%OutData_SrvD%UseHSSBrake END IF ! ........................ ! set some VTK parameters required before HydroDyn init (so we can get wave elevations for visualization) ! ........................ ! get wave elevation data for visualization if ( p_FAST%WrVTK > VTK_None ) then call SetVTKParameters_B4HD(p_FAST, Init%OutData_ED, Init%InData_HD, BD, ErrStat2, ErrMsg2) CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) IF (ErrStat >= AbortErrLev) THEN CALL Cleanup() RETURN END IF end if ! ........................ ! initialize HydroDyn ! ........................ ALLOCATE( HD%Input( p_FAST%InterpOrder+1 ), HD%InputTimes( p_FAST%InterpOrder+1 ), STAT = ErrStat2 ) IF (ErrStat2 /= 0) THEN CALL SetErrStat(ErrID_Fatal,"Error allocating HD%Input and HD%InputTimes.",ErrStat,ErrMsg,RoutineName) CALL Cleanup() RETURN END IF IF ( p_FAST%CompHydro == Module_HD ) THEN Init%InData_HD%Gravity = Init%OutData_ED%Gravity Init%InData_HD%UseInputFile = .TRUE. Init%InData_HD%InputFile = p_FAST%HydroFile Init%InData_HD%OutRootName = p_FAST%OutFileRoot Init%InData_HD%TMax = p_FAST%TMax Init%InData_HD%hasIce = p_FAST%CompIce /= Module_None Init%InData_HD%Linearize = p_FAST%Linearize ! if wave field needs an offset, modify these values (added at request of SOWFA developers): Init%InData_HD%PtfmLocationX = p_FAST%TurbinePos(1) Init%InData_HD%PtfmLocationY = p_FAST%TurbinePos(2) CALL HydroDyn_Init( Init%InData_HD, HD%Input(1), HD%p, HD%x(STATE_CURR), HD%xd(STATE_CURR), HD%z(STATE_CURR), & HD%OtherSt(STATE_CURR), HD%y, HD%m, p_FAST%dt_module( MODULE_HD ), Init%OutData_HD, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) p_FAST%ModuleInitialized(Module_HD) = .TRUE. CALL SetModuleSubstepTime(Module_HD, p_FAST, y_FAST, ErrStat2, ErrMsg2) CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) allocate( y_FAST%Lin%Modules(MODULE_HD)%Instance(1), stat=ErrStat2) if (ErrStat2 /= 0 ) then call SetErrStat(ErrID_Fatal, "Error allocating Lin%Modules(HD).", ErrStat, ErrMsg, RoutineName ) else if (allocated(Init%OutData_HD%LinNames_y)) call move_alloc(Init%OutData_HD%LinNames_y,y_FAST%Lin%Modules(MODULE_HD)%Instance(1)%Names_y ) if (allocated(Init%OutData_HD%LinNames_u)) call move_alloc(Init%OutData_HD%LinNames_u,y_FAST%Lin%Modules(MODULE_HD)%Instance(1)%Names_u ) if (allocated(Init%OutData_HD%LinNames_x)) call move_alloc(Init%OutData_HD%LinNames_x, y_FAST%Lin%Modules(MODULE_HD)%Instance(1)%Names_x ) if (allocated(Init%OutData_HD%DerivOrder_x)) call move_alloc(Init%OutData_HD%DerivOrder_x,y_FAST%Lin%Modules(MODULE_HD)%Instance(1)%DerivOrder_x) if (allocated(Init%OutData_HD%IsLoad_u )) call move_alloc(Init%OutData_HD%IsLoad_u ,y_FAST%Lin%Modules(MODULE_HD)%Instance(1)%IsLoad_u ) if (allocated(Init%OutData_HD%WriteOutputHdr)) y_FAST%Lin%Modules(MODULE_HD)%Instance(1)%NumOutputs = size(Init%OutData_HD%WriteOutputHdr) end if IF (ErrStat >= AbortErrLev) THEN CALL Cleanup() RETURN END IF END IF ! CompHydro ! ........................ ! initialize SubDyn or ExtPtfm_MCKF ! ........................ ALLOCATE( SD%Input( p_FAST%InterpOrder+1 ), SD%InputTimes( p_FAST%InterpOrder+1 ), STAT = ErrStat2 ) IF (ErrStat2 /= 0) THEN CALL SetErrStat(ErrID_Fatal,"Error allocating SD%Input and SD%InputTimes.",ErrStat,ErrMsg,RoutineName) CALL Cleanup() RETURN END IF ALLOCATE( ExtPtfm%Input( p_FAST%InterpOrder+1 ), ExtPtfm%InputTimes( p_FAST%InterpOrder+1 ), STAT = ErrStat2 ) IF (ErrStat2 /= 0) THEN CALL SetErrStat(ErrID_Fatal,"Error allocating ExtPtfm%Input and ExtPtfm%InputTimes.",ErrStat,ErrMsg,RoutineName) CALL Cleanup() RETURN END IF IF ( p_FAST%CompSub == Module_SD ) THEN IF ( p_FAST%CompHydro == Module_HD ) THEN Init%InData_SD%WtrDpth = Init%OutData_HD%WtrDpth ELSE Init%InData_SD%WtrDpth = 0.0_ReKi END IF Init%InData_SD%Linearize = p_FAST%Linearize Init%InData_SD%g = Init%OutData_ED%Gravity !Ini%tInData_SD%UseInputFile = .TRUE. Init%InData_SD%SDInputFile = p_FAST%SubFile Init%InData_SD%RootName = p_FAST%OutFileRoot Init%InData_SD%TP_RefPoint = ED%y%PlatformPtMesh%Position(:,1) ! "Interface point" where loads will be transferred to Init%InData_SD%SubRotateZ = 0.0 ! Used by driver to rotate structure around z CALL SD_Init( Init%InData_SD, SD%Input(1), SD%p, SD%x(STATE_CURR), SD%xd(STATE_CURR), SD%z(STATE_CURR), & SD%OtherSt(STATE_CURR), SD%y, SD%m, p_FAST%dt_module( MODULE_SD ), Init%OutData_SD, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) p_FAST%ModuleInitialized(Module_SD) = .TRUE. CALL SetModuleSubstepTime(Module_SD, p_FAST, y_FAST, ErrStat2, ErrMsg2) CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) allocate( y_FAST%Lin%Modules(MODULE_SD)%Instance(1), stat=ErrStat2) if (ErrStat2 /= 0 ) then call SetErrStat(ErrID_Fatal, "Error allocating Lin%Modules(SD).", ErrStat, ErrMsg, RoutineName ) else if (allocated(Init%OutData_SD%LinNames_y)) call move_alloc(Init%OutData_SD%LinNames_y,y_FAST%Lin%Modules(MODULE_SD)%Instance(1)%Names_y) if (allocated(Init%OutData_SD%LinNames_x)) call move_alloc(Init%OutData_SD%LinNames_x,y_FAST%Lin%Modules(MODULE_SD)%Instance(1)%Names_x) if (allocated(Init%OutData_SD%LinNames_u)) call move_alloc(Init%OutData_SD%LinNames_u,y_FAST%Lin%Modules(MODULE_SD)%Instance(1)%Names_u) if (allocated(Init%OutData_SD%RotFrame_y)) call move_alloc(Init%OutData_SD%RotFrame_y,y_FAST%Lin%Modules(MODULE_SD)%Instance(1)%RotFrame_y) if (allocated(Init%OutData_SD%RotFrame_x)) call move_alloc(Init%OutData_SD%RotFrame_x,y_FAST%Lin%Modules(MODULE_SD)%Instance(1)%RotFrame_x) if (allocated(Init%OutData_SD%RotFrame_u)) call move_alloc(Init%OutData_SD%RotFrame_u,y_FAST%Lin%Modules(MODULE_SD)%Instance(1)%RotFrame_u) if (allocated(Init%OutData_SD%IsLoad_u )) call move_alloc(Init%OutData_SD%IsLoad_u ,y_FAST%Lin%Modules(MODULE_SD)%Instance(1)%IsLoad_u ) if (allocated(Init%OutData_SD%WriteOutputHdr)) y_FAST%Lin%Modules(MODULE_SD)%Instance(1)%NumOutputs = size(Init%OutData_SD%WriteOutputHdr) if (allocated(Init%OutData_SD%DerivOrder_x)) call move_alloc(Init%OutData_SD%DerivOrder_x,y_FAST%Lin%Modules(MODULE_SD)%Instance(1)%DerivOrder_x) end if IF (ErrStat >= AbortErrLev) THEN CALL Cleanup() RETURN END IF ELSE IF ( p_FAST%CompSub == Module_ExtPtfm ) THEN Init%InData_ExtPtfm%InputFile = p_FAST%SubFile Init%InData_ExtPtfm%RootName = trim(p_FAST%OutFileRoot)//'.'//TRIM(y_FAST%Module_Abrev(Module_ExtPtfm)) Init%InData_ExtPtfm%Linearize = p_FAST%Linearize Init%InData_ExtPtfm%PtfmRefzt = ED%p%PtfmRefzt ! Required CALL ExtPtfm_Init( Init%InData_ExtPtfm, ExtPtfm%Input(1), ExtPtfm%p, & ExtPtfm%x(STATE_CURR), ExtPtfm%xd(STATE_CURR), ExtPtfm%z(STATE_CURR), ExtPtfm%OtherSt(STATE_CURR), & ExtPtfm%y, ExtPtfm%m, p_FAST%dt_module( MODULE_ExtPtfm ), Init%OutData_ExtPtfm, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) p_FAST%ModuleInitialized(MODULE_ExtPtfm) = .TRUE. CALL SetModuleSubstepTime(MODULE_ExtPtfm, p_FAST, y_FAST, ErrStat2, ErrMsg2) CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) allocate( y_FAST%Lin%Modules(MODULE_ExtPtfm)%Instance(1), stat=ErrStat2) if (ErrStat2 /= 0 ) then call SetErrStat(ErrID_Fatal, "Error allocating Lin%Modules(ExtPtfm).", ErrStat, ErrMsg, RoutineName ) else if (allocated(Init%OutData_ExtPtfm%LinNames_y)) call move_alloc(Init%OutData_ExtPtfm%LinNames_y,y_FAST%Lin%Modules(MODULE_ExtPtfm)%Instance(1)%Names_y) if (allocated(Init%OutData_ExtPtfm%LinNames_x)) call move_alloc(Init%OutData_ExtPtfm%LinNames_x,y_FAST%Lin%Modules(MODULE_ExtPtfm)%Instance(1)%Names_x) if (allocated(Init%OutData_ExtPtfm%LinNames_u)) call move_alloc(Init%OutData_ExtPtfm%LinNames_u,y_FAST%Lin%Modules(MODULE_ExtPtfm)%Instance(1)%Names_u) if (allocated(Init%OutData_ExtPtfm%RotFrame_y)) call move_alloc(Init%OutData_ExtPtfm%RotFrame_y,y_FAST%Lin%Modules(MODULE_ExtPtfm)%Instance(1)%RotFrame_y) if (allocated(Init%OutData_ExtPtfm%RotFrame_x)) call move_alloc(Init%OutData_ExtPtfm%RotFrame_x,y_FAST%Lin%Modules(MODULE_ExtPtfm)%Instance(1)%RotFrame_x) if (allocated(Init%OutData_ExtPtfm%RotFrame_u)) call move_alloc(Init%OutData_ExtPtfm%RotFrame_u,y_FAST%Lin%Modules(MODULE_ExtPtfm)%Instance(1)%RotFrame_u) if (allocated(Init%OutData_ExtPtfm%IsLoad_u )) call move_alloc(Init%OutData_ExtPtfm%IsLoad_u ,y_FAST%Lin%Modules(MODULE_ExtPtfm)%Instance(1)%IsLoad_u ) if (allocated(Init%OutData_ExtPtfm%WriteOutputHdr)) y_FAST%Lin%Modules(MODULE_ExtPtfm)%Instance(1)%NumOutputs = size(Init%OutData_ExtPtfm%WriteOutputHdr) if (allocated(Init%OutData_ExtPtfm%DerivOrder_x)) call move_alloc(Init%OutData_ExtPtfm%DerivOrder_x,y_FAST%Lin%Modules(MODULE_ExtPtfm)%Instance(1)%DerivOrder_x) end if IF (ErrStat >= AbortErrLev) THEN CALL Cleanup() RETURN END IF END IF ! ------------------------------ ! initialize CompMooring modules ! ------------------------------ ALLOCATE( MAPp%Input( p_FAST%InterpOrder+1 ), MAPp%InputTimes( p_FAST%InterpOrder+1 ), STAT = ErrStat2 ) IF (ErrStat2 /= 0) THEN CALL SetErrStat(ErrID_Fatal,"Error allocating MAPp%Input and MAPp%InputTimes.",ErrStat,ErrMsg,RoutineName) CALL Cleanup() RETURN END IF ALLOCATE( MD%Input( p_FAST%InterpOrder+1 ), MD%InputTimes( p_FAST%InterpOrder+1 ), STAT = ErrStat2 ) IF (ErrStat2 /= 0) THEN CALL SetErrStat(ErrID_Fatal,"Error allocating MD%Input and MD%InputTimes.",ErrStat,ErrMsg,RoutineName) CALL Cleanup() RETURN END IF ALLOCATE( FEAM%Input( p_FAST%InterpOrder+1 ), FEAM%InputTimes( p_FAST%InterpOrder+1 ), STAT = ErrStat2 ) IF (ErrStat2 /= 0) THEN CALL SetErrStat(ErrID_Fatal,"Error allocating FEAM%Input and FEAM%InputTimes.",ErrStat,ErrMsg,RoutineName) CALL Cleanup() RETURN END IF ALLOCATE( Orca%Input( p_FAST%InterpOrder+1 ), Orca%InputTimes( p_FAST%InterpOrder+1 ), STAT = ErrStat2 ) IF (ErrStat2 /= 0) THEN CALL SetErrStat(ErrID_Fatal,"Error allocating Orca%Input and Orca%InputTimes.",ErrStat,ErrMsg,RoutineName) CALL Cleanup() RETURN END IF ! ........................ ! initialize MAP ! ........................ IF (p_FAST%CompMooring == Module_MAP) THEN !bjj: until we modify this, MAP requires HydroDyn to be used. (perhaps we could send air density from AeroDyn or something...) CALL WrScr(NewLine) !bjj: I'm printing two blank lines here because MAP seems to be writing over the last line on the screen. ! Init%InData_MAP%rootname = p_FAST%OutFileRoot ! Output file name Init%InData_MAP%gravity = Init%OutData_ED%Gravity ! This need to be according to g used in ElastoDyn Init%InData_MAP%sea_density = Init%OutData_HD%WtrDens ! This needs to be set according to seawater density in HydroDyn Init%InData_MAP%depth = Init%OutData_HD%WtrDpth ! This need to be set according to the water depth in HydroDyn ! differences for MAP++ Init%InData_MAP%file_name = p_FAST%MooringFile ! This needs to be set according to what is in the FAST input file. Init%InData_MAP%summary_file_name = TRIM(p_FAST%OutFileRoot)//'.MAP.sum' ! Output file name Init%InData_MAP%depth = -Init%OutData_HD%WtrDpth ! This need to be set according to the water depth in HydroDyn Init%InData_MAP%LinInitInp%Linearize = p_FAST%Linearize CALL MAP_Init( Init%InData_MAP, MAPp%Input(1), MAPp%p, MAPp%x(STATE_CURR), MAPp%xd(STATE_CURR), MAPp%z(STATE_CURR), MAPp%OtherSt, & MAPp%y, p_FAST%dt_module( MODULE_MAP ), Init%OutData_MAP, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) p_FAST%ModuleInitialized(Module_MAP) = .TRUE. CALL SetModuleSubstepTime(Module_MAP, p_FAST, y_FAST, ErrStat2, ErrMsg2) CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) allocate( y_FAST%Lin%Modules(Module_MAP)%Instance(1), stat=ErrStat2) if (ErrStat2 /= 0 ) then call SetErrStat(ErrID_Fatal, "Error allocating Lin%Modules(MAP).", ErrStat, ErrMsg, RoutineName ) else if (allocated(Init%OutData_MAP%LinInitOut%LinNames_y)) call move_alloc(Init%OutData_MAP%LinInitOut%LinNames_y,y_FAST%Lin%Modules(Module_MAP)%Instance(1)%Names_y ) if (allocated(Init%OutData_MAP%LinInitOut%LinNames_u)) call move_alloc(Init%OutData_MAP%LinInitOut%LinNames_u,y_FAST%Lin%Modules(Module_MAP)%Instance(1)%Names_u ) if (allocated(Init%OutData_MAP%LinInitOut%IsLoad_u )) call move_alloc(Init%OutData_MAP%LinInitOut%IsLoad_u ,y_FAST%Lin%Modules(Module_MAP)%Instance(1)%IsLoad_u ) if (allocated(Init%OutData_MAP%WriteOutputHdr)) y_FAST%Lin%Modules(Module_MAP)%Instance(1)%NumOutputs = size(Init%OutData_MAP%WriteOutputHdr) end if IF (ErrStat >= AbortErrLev) THEN CALL Cleanup() RETURN END IF ! ........................ ! initialize MoorDyn ! ........................ ELSEIF (p_FAST%CompMooring == Module_MD) THEN Init%InData_MD%FileName = p_FAST%MooringFile ! This needs to be set according to what is in the FAST input file. Init%InData_MD%RootName = p_FAST%OutFileRoot Init%InData_MD%PtfmInit = Init%OutData_ED%PlatformPos !ED%x(STATE_CURR)%QT(1:6) ! initial position of the platform !bjj: this should come from Init%OutData_ED, not x_ED Init%InData_MD%g = Init%OutData_ED%Gravity ! This need to be according to g used in ElastoDyn Init%InData_MD%rhoW = Init%OutData_HD%WtrDens ! This needs to be set according to seawater density in HydroDyn Init%InData_MD%WtrDepth = Init%OutData_HD%WtrDpth ! This need to be set according to the water depth in HydroDyn CALL MD_Init( Init%InData_MD, MD%Input(1), MD%p, MD%x(STATE_CURR), MD%xd(STATE_CURR), MD%z(STATE_CURR), & MD%OtherSt(STATE_CURR), MD%y, MD%m, p_FAST%dt_module( MODULE_MD ), Init%OutData_MD, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) p_FAST%ModuleInitialized(Module_MD) = .TRUE. CALL SetModuleSubstepTime(Module_MD, p_FAST, y_FAST, ErrStat2, ErrMsg2) CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) IF (ErrStat >= AbortErrLev) THEN CALL Cleanup() RETURN END IF ! ........................ ! initialize FEAM ! ........................ ELSEIF (p_FAST%CompMooring == Module_FEAM) THEN Init%InData_FEAM%InputFile = p_FAST%MooringFile ! This needs to be set according to what is in the FAST input file. Init%InData_FEAM%RootName = TRIM(p_FAST%OutFileRoot)//'.'//TRIM(y_FAST%Module_Abrev(Module_FEAM)) Init%InData_FEAM%PtfmInit = Init%OutData_ED%PlatformPos !ED%x(STATE_CURR)%QT(1:6) ! initial position of the platform !bjj: this should come from Init%OutData_ED, not x_ED Init%InData_FEAM%NStepWave = 1 ! an arbitrary number > 0 (to set the size of the wave data, which currently contains all zero values) Init%InData_FEAM%gravity = Init%OutData_ED%Gravity ! This need to be according to g used in ElastoDyn Init%InData_FEAM%WtrDens = Init%OutData_HD%WtrDens ! This needs to be set according to seawater density in HydroDyn ! Init%InData_FEAM%depth = Init%OutData_HD%WtrDpth ! This need to be set according to the water depth in HydroDyn CALL FEAM_Init( Init%InData_FEAM, FEAM%Input(1), FEAM%p, FEAM%x(STATE_CURR), FEAM%xd(STATE_CURR), FEAM%z(STATE_CURR), & FEAM%OtherSt(STATE_CURR), FEAM%y, FEAM%m, p_FAST%dt_module( MODULE_FEAM ), Init%OutData_FEAM, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) p_FAST%ModuleInitialized(Module_FEAM) = .TRUE. CALL SetModuleSubstepTime(Module_FEAM, p_FAST, y_FAST, ErrStat2, ErrMsg2) CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) IF (ErrStat >= AbortErrLev) THEN CALL Cleanup() RETURN END IF ! ........................ ! initialize OrcaFlex Interface ! ........................ ELSEIF (p_FAST%CompMooring == Module_Orca) THEN Init%InData_Orca%InputFile = p_FAST%MooringFile Init%InData_Orca%RootName = p_FAST%OutFileRoot Init%InData_Orca%TMax = p_FAST%TMax CALL Orca_Init( Init%InData_Orca, Orca%Input(1), Orca%p, Orca%x(STATE_CURR), Orca%xd(STATE_CURR), Orca%z(STATE_CURR), Orca%OtherSt(STATE_CURR), & Orca%y, Orca%m, p_FAST%dt_module( MODULE_Orca ), Init%OutData_Orca, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) p_FAST%ModuleInitialized(MODULE_Orca) = .TRUE. CALL SetModuleSubstepTime(MODULE_Orca, p_FAST, y_FAST, ErrStat2, ErrMsg2) CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) IF (ErrStat >= AbortErrLev) THEN CALL Cleanup() RETURN END IF END IF ! ------------------------------ ! initialize CompIce modules ! ------------------------------ ALLOCATE( IceF%Input( p_FAST%InterpOrder+1 ), IceF%InputTimes( p_FAST%InterpOrder+1 ), STAT = ErrStat2 ) IF (ErrStat2 /= 0) THEN CALL SetErrStat(ErrID_Fatal,"Error allocating IceF%Input and IceF%InputTimes.",ErrStat,ErrMsg,RoutineName) CALL Cleanup() RETURN END IF ! We need this to be allocated (else we have issues passing nonallocated arrays and using the first index of Input(), ! but we don't need the space of IceD_MaxLegs if we're not using it. IF ( p_FAST%CompIce /= Module_IceD ) THEN IceDim = 1 ELSE IceDim = IceD_MaxLegs END IF ! because there may be multiple instances of IceDyn, we'll allocate arrays for that here ! we could allocate these after ALLOCATE( IceD%Input( p_FAST%InterpOrder+1, IceDim ), IceD%InputTimes( p_FAST%InterpOrder+1, IceDim ), STAT = ErrStat2 ) IF (ErrStat2 /= 0) THEN CALL SetErrStat(ErrID_Fatal,"Error allocating IceD%Input and IceD%InputTimes.",ErrStat,ErrMsg,RoutineName) CALL Cleanup() RETURN END IF ALLOCATE( IceD%x( IceDim,2), & IceD%xd( IceDim,2), & IceD%z( IceDim,2), & IceD%OtherSt( IceDim,2), & IceD%p( IceDim ), & IceD%u( IceDim ), & IceD%y( IceDim ), & IceD%m( IceDim ), & STAT = ErrStat2 ) IF (ErrStat2 /= 0) THEN CALL SetErrStat(ErrID_Fatal,"Error allocating IceD state, input, and output data.",ErrStat,ErrMsg,RoutineName) CALL Cleanup() RETURN END IF ! ........................ ! initialize IceFloe ! ........................ IF ( p_FAST%CompIce == Module_IceF ) THEN Init%InData_IceF%InputFile = p_FAST%IceFile Init%InData_IceF%RootName = TRIM(p_FAST%OutFileRoot)//'.'//TRIM(y_FAST%Module_Abrev(Module_IceF)) Init%InData_IceF%simLength = p_FAST%TMax !bjj: IceFloe stores this as single-precision (ReKi) TMax is DbKi Init%InData_IceF%MSL2SWL = Init%OutData_HD%MSL2SWL Init%InData_IceF%gravity = Init%OutData_ED%Gravity CALL IceFloe_Init( Init%InData_IceF, IceF%Input(1), IceF%p, IceF%x(STATE_CURR), IceF%xd(STATE_CURR), IceF%z(STATE_CURR), & IceF%OtherSt(STATE_CURR), IceF%y, IceF%m, p_FAST%dt_module( MODULE_IceF ), Init%OutData_IceF, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) p_FAST%ModuleInitialized(Module_IceF) = .TRUE. CALL SetModuleSubstepTime(Module_IceF, p_FAST, y_FAST, ErrStat2, ErrMsg2) CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) IF (ErrStat >= AbortErrLev) THEN CALL Cleanup() RETURN END IF ! ........................ ! initialize IceDyn ! ........................ ELSEIF ( p_FAST%CompIce == Module_IceD ) THEN Init%InData_IceD%InputFile = p_FAST%IceFile Init%InData_IceD%RootName = TRIM(p_FAST%OutFileRoot)//'.'//TRIM(y_FAST%Module_Abrev(Module_IceD))//'1' Init%InData_IceD%MSL2SWL = Init%OutData_HD%MSL2SWL Init%InData_IceD%WtrDens = Init%OutData_HD%WtrDens Init%InData_IceD%gravity = Init%OutData_ED%Gravity Init%InData_IceD%TMax = p_FAST%TMax Init%InData_IceD%LegNum = 1 CALL IceD_Init( Init%InData_IceD, IceD%Input(1,1), IceD%p(1), IceD%x(1,STATE_CURR), IceD%xd(1,STATE_CURR), IceD%z(1,STATE_CURR), & IceD%OtherSt(1,STATE_CURR), IceD%y(1), IceD%m(1), p_FAST%dt_module( MODULE_IceD ), Init%OutData_IceD, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) p_FAST%ModuleInitialized(Module_IceD) = .TRUE. CALL SetModuleSubstepTime(Module_IceD, p_FAST, y_FAST, ErrStat2, ErrMsg2) CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) ! now initialize IceD for additional legs (if necessary) dt_IceD = p_FAST%dt_module( MODULE_IceD ) p_FAST%numIceLegs = Init%OutData_IceD%numLegs IF (p_FAST%numIceLegs > IceD_MaxLegs) THEN CALL SetErrStat(ErrID_Fatal,'IceDyn-FAST coupling is supported for up to '//TRIM(Num2LStr(IceD_MaxLegs))//' legs, but ' & //TRIM(Num2LStr(p_FAST%numIceLegs))//' legs were specified.',ErrStat,ErrMsg,RoutineName) END IF DO i=2,p_FAST%numIceLegs ! basically, we just need IceDyn to set up its meshes for inputs/outputs and possibly initial values for states Init%InData_IceD%LegNum = i Init%InData_IceD%RootName = TRIM(p_FAST%OutFileRoot)//'.'//TRIM(y_FAST%Module_Abrev(Module_IceD))//TRIM(Num2LStr(i)) CALL IceD_Init( Init%InData_IceD, IceD%Input(1,i), IceD%p(i), IceD%x(i,STATE_CURR), IceD%xd(i,STATE_CURR), IceD%z(i,STATE_CURR), & IceD%OtherSt(i,STATE_CURR), IceD%y(i), IceD%m(i), dt_IceD, Init%OutData_IceD, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) !bjj: we're going to force this to have the same timestep because I don't want to have to deal with n IceD modules with n timesteps. IF (.NOT. EqualRealNos( p_FAST%dt_module( MODULE_IceD ),dt_IceD )) THEN CALL SetErrStat(ErrID_Fatal,"All instances of IceDyn (one per support-structure leg) must be the same",ErrStat,ErrMsg,RoutineName) END IF END DO IF (ErrStat >= AbortErrLev) THEN CALL Cleanup() RETURN END IF END IF ! ........................ ! Set up output for glue code (must be done after all modules are initialized so we have their WriteOutput information) ! ........................ CALL FAST_InitOutput( p_FAST, y_FAST, Init, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) ! ------------------------------------------------------------------------- ! Initialize mesh-mapping data ! ------------------------------------------------------------------------- CALL InitModuleMappings(p_FAST, ED, BD, AD14, AD, HD, SD, ExtPtfm, SrvD, MAPp, FEAM, MD, Orca, IceF, IceD, MeshMapData, ErrStat2, ErrMsg2) CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) IF (ErrStat >= AbortErrLev) THEN CALL Cleanup() RETURN ELSEIF (ErrStat /= ErrID_None) THEN ! a little work-around in case the mesh mapping info messages get too long CALL WrScr( NewLine//TRIM(ErrMsg)//NewLine ) ErrStat = ErrID_None ErrMsg = "" END IF ! ------------------------------------------------------------------------- ! Initialize for linearization: ! ------------------------------------------------------------------------- if ( p_FAST%Linearize ) then ! NOTE: In the following call, we use Init%OutData_AD%BladeProps(1)%NumBlNds as the number of aero nodes on EACH blade, which ! is consistent with the current AD implementation, but if AD changes this, then it must be handled here, too! if (p_FAST%CompAero == MODULE_AD) then call Init_Lin(p_FAST, y_FAST, m_FAST, AD, ED, Init%OutData_ED%NumBl, Init%OutData_AD%BladeProps(1)%NumBlNds, ErrStat2, ErrMsg2) else call Init_Lin(p_FAST, y_FAST, m_FAST, AD, ED, Init%OutData_ED%NumBl, -1, ErrStat2, ErrMsg2) endif call SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) if (ErrStat >= AbortErrLev) then call Cleanup() return end if end if ! ------------------------------------------------------------------------- ! Initialize data for VTK output ! ------------------------------------------------------------------------- if ( p_FAST%WrVTK > VTK_None ) then call SetVTKParameters(p_FAST, Init%OutData_ED, Init%OutData_AD, Init%InData_HD, Init%OutData_HD, ED, BD, AD, HD, ErrStat2, ErrMsg2) call SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) end if ! ------------------------------------------------------------------------- ! Write initialization data to FAST summary file: ! ------------------------------------------------------------------------- if (p_FAST%SumPrint) then CALL FAST_WrSum( p_FAST, y_FAST, MeshMapData, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) endif ! ------------------------------------------------------------------------- ! other misc variables initialized here: ! ------------------------------------------------------------------------- m_FAST%t_global = t_initial ! Initialize external inputs for first step if ( p_FAST%CompServo == MODULE_SrvD ) then m_FAST%ExternInput%GenTrq = SrvD%Input(1)%ExternalGenTrq !0.0_ReKi m_FAST%ExternInput%ElecPwr = SrvD%Input(1)%ExternalElecPwr m_FAST%ExternInput%YawPosCom = SrvD%Input(1)%ExternalYawPosCom m_FAST%ExternInput%YawRateCom = SrvD%Input(1)%ExternalYawRateCom m_FAST%ExternInput%HSSBrFrac = SrvD%Input(1)%ExternalHSSBrFrac do i=1,SIZE(SrvD%Input(1)%ExternalBlPitchCom) m_FAST%ExternInput%BlPitchCom(i) = SrvD%Input(1)%ExternalBlPitchCom(i) end do end if m_FAST%ExternInput%LidarFocus = 1.0_ReKi ! make this non-zero (until we add the initial position in the InflowWind input file) !............................................................................................................................... ! Destroy initializion data !............................................................................................................................... CALL Cleanup() CONTAINS SUBROUTINE Cleanup() !............................................................................................................................... ! Destroy initializion data !............................................................................................................................... CALL FAST_DestroyInitData( Init, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) END SUBROUTINE Cleanup END SUBROUTINE FAST_InitializeAll !---------------------------------------------------------------------------------------------------------------------------------- !> This function returns a string describing the glue code and some of the compilation options we're using. FUNCTION GetVersion(ThisProgVer) ! Passed Variables: TYPE(ProgDesc), INTENT( IN ) :: ThisProgVer !< program name/date/version description CHARACTER(1024) :: GetVersion !< String containing a description of the compiled precision. CHARACTER(200) :: git_commit GetVersion = TRIM(GetNVD(ThisProgVer))//', compiled' IF ( Cmpl4SFun ) THEN ! FAST has been compiled as an S-Function for Simulink GetVersion = TRIM(GetVersion)//' as a DLL S-Function for Simulink' ELSEIF ( Cmpl4LV ) THEN ! FAST has been compiled as a DLL for Labview GetVersion = TRIM(GetVersion)//' as a DLL for LabVIEW' ENDIF GetVersion = TRIM(GetVersion)//' as a '//TRIM(Num2LStr(BITS_IN_ADDR))//'-bit application using' ! determine precision IF ( ReKi == SiKi ) THEN ! Single precision GetVersion = TRIM(GetVersion)//' single' ELSEIF ( ReKi == R8Ki ) THEN ! Double precision GetVersion = TRIM(GetVersion)// ' double' ELSE ! Unknown precision GetVersion = TRIM(GetVersion)//' unknown' ENDIF ! GetVersion = TRIM(GetVersion)//' precision with '//OS_Desc GetVersion = TRIM(GetVersion)//' precision' ! add git info git_commit = QueryGitVersion() GetVersion = TRIM(GetVersion)//' at commit '//git_commit RETURN END FUNCTION GetVersion !---------------------------------------------------------------------------------------------------------------------------------- !> This subroutine is called at the start (or restart) of a FAST program (or FAST.Farm). It initializes the NWTC subroutine library, !! displays the copyright notice, and displays some version information (including addressing scheme and precision). SUBROUTINE FAST_ProgStart(ThisProgVer) TYPE(ProgDesc), INTENT(IN) :: ThisProgVer !< program name/date/version description ! ... Initialize NWTC Library (open console, set pi constants) ... ! sets the pi constants, open console for output, etc... CALL NWTC_Init( ProgNameIN=ThisProgVer%Name, EchoLibVer=.FALSE. ) ! Display the copyright notice CALL DispCopyrightLicense( ThisProgVer%Name ) CALL DispCompileRuntimeInfo END SUBROUTINE FAST_ProgStart !---------------------------------------------------------------------------------------------------------------------------------- !> This routine gets the name of the FAST input file from the command line. It also returns a logical indicating if this there !! was a "DWM" argument after the file name. SUBROUTINE GetInputFileName(InputFile,UseDWM,ErrStat,ErrMsg) CHARACTER(*), INTENT(OUT) :: InputFile !< A CHARACTER string containing the name of the primary FAST input file (if not present, we'll get it from the command line) LOGICAL, INTENT(OUT) :: UseDWM !< whether the last argument from the command line is "DWM" INTEGER(IntKi), INTENT(OUT) :: ErrStat !< Error status CHARACTER(*), INTENT(OUT) :: ErrMsg !< Error message INTEGER(IntKi) :: ErrStat2 ! local error stat CHARACTER(1024) :: LastArg ! A second command-line argument that will allow DWM module to be used in AeroDyn ErrStat = ErrID_None ErrMsg = '' UseDWM = .FALSE. ! by default, we're not going to use the DWM module InputFile = "" ! initialize to empty string to make sure it's input from the command line CALL CheckArgs( InputFile, ErrStat2, LastArg ) ! if ErrStat2 /= ErrID_None, we'll ignore and deal with the problem when we try to read the input file IF (LEN_TRIM(InputFile) == 0) THEN ! no input file was specified ErrStat = ErrID_Fatal ErrMsg = 'The required input file was not specified on the command line.' RETURN END IF IF (LEN_TRIM(LastArg) > 0) THEN ! see if DWM was specified as the second option CALL Conv2UC( LastArg ) IF ( TRIM(LastArg) == "DWM" ) THEN UseDWM = .TRUE. END IF END IF END SUBROUTINE GetInputFileName !---------------------------------------------------------------------------------------------------------------------------------- !> This subroutine checks for command-line arguments, gets the root name of the input files !! (including full path name), and creates the names of the output files. SUBROUTINE FAST_Init( p, m_FAST, y_FAST, t_initial, InputFile, ErrStat, ErrMsg, TMax, TurbID, OverrideAbortLev, RootName ) IMPLICIT NONE ! Passed variables TYPE(FAST_ParameterType), INTENT(INOUT) :: p !< The parameter data for the FAST (glue-code) simulation TYPE(FAST_MiscVarType), INTENT(INOUT) :: m_FAST !< Miscellaneous variables TYPE(FAST_OutputFileType),INTENT(INOUT) :: y_FAST !< The output data for the FAST (glue-code) simulation REAL(DbKi), INTENT(IN) :: t_initial !< the beginning time of the simulation INTEGER(IntKi), INTENT(OUT) :: ErrStat !< Error status CHARACTER(*), INTENT(OUT) :: ErrMsg !< Error message CHARACTER(*), INTENT(IN) :: InputFile !< A CHARACTER string containing the name of the primary FAST input file (if not present, we'll get it from the command line) REAL(DbKi), INTENT(IN), OPTIONAL :: TMax !< the length of the simulation (from Simulink or FAST.Farm) INTEGER(IntKi), INTENT(IN), OPTIONAL :: TurbID !< an ID for naming the tubine output file LOGICAL, INTENT(IN), OPTIONAL :: OverrideAbortLev !< whether or not we should override the abort error level (e.g., FAST.Farm) CHARACTER(*), INTENT(IN), OPTIONAL :: RootName !< A CHARACTER string containing the root name of FAST output files, overriding normal naming convention ! Local variables INTEGER :: i ! loop counter !CHARACTER(1024) :: DirName ! A CHARACTER string containing the path of the current working directory LOGICAL :: OverrideAbortErrLev CHARACTER(*), PARAMETER :: RoutineName = "FAST_Init" INTEGER(IntKi) :: ErrStat2 CHARACTER(ErrMsgLen) :: ErrMsg2 ! Initialize some variables ErrStat = ErrID_None ErrMsg = '' IF (PRESENT(OverrideAbortLev)) THEN OverrideAbortErrLev = OverrideAbortLev ELSE OverrideAbortErrLev = .true. END IF !............................................................................................................................... ! Set the root name of the output files based on the input file name !............................................................................................................................... if (present(RootName)) then p%OutFileRoot = RootName else ! Determine the root name of the primary file (will be used for output files) CALL GetRoot( InputFile, p%OutFileRoot ) IF ( Cmpl4SFun ) p%OutFileRoot = TRIM( p%OutFileRoot )//'.SFunc' IF ( PRESENT(TurbID) ) THEN IF ( TurbID > 0 ) THEN p%OutFileRoot = TRIM( p%OutFileRoot )//'.T'//TRIM(Num2LStr(TurbID)) END IF END IF end if p%VTK_OutFileRoot = p%OutFileRoot !initialize this here in case of error before it is set later !............................................................................................................................... ! Initialize the module name/date/version info: !............................................................................................................................... DO i=1,NumModules y_FAST%Module_Ver(i)%Date = 'unknown date' y_FAST%Module_Ver(i)%Ver = 'unknown version' END DO y_FAST%Module_Ver( Module_IfW )%Name = 'InflowWind' y_FAST%Module_Ver( Module_OpFM )%Name = 'OpenFOAM integration' y_FAST%Module_Ver( Module_ED )%Name = 'ElastoDyn' y_FAST%Module_Ver( Module_BD )%Name = 'BeamDyn' y_FAST%Module_Ver( Module_AD14 )%Name = 'AeroDyn14' y_FAST%Module_Ver( Module_AD )%Name = 'AeroDyn' y_FAST%Module_Ver( Module_SrvD )%Name = 'ServoDyn' y_FAST%Module_Ver( Module_HD )%Name = 'HydroDyn' y_FAST%Module_Ver( Module_SD )%Name = 'SubDyn' y_FAST%Module_Ver( Module_ExtPtfm)%Name = 'ExtPtfm_MCKF' y_FAST%Module_Ver( Module_MAP )%Name = 'MAP' y_FAST%Module_Ver( Module_FEAM )%Name = 'FEAMooring' y_FAST%Module_Ver( Module_MD )%Name = 'MoorDyn' y_FAST%Module_Ver( Module_Orca )%Name = 'OrcaFlexInterface' y_FAST%Module_Ver( Module_IceF )%Name = 'IceFloe' y_FAST%Module_Ver( Module_IceD )%Name = 'IceDyn' y_FAST%Module_Abrev( Module_IfW ) = 'IfW' y_FAST%Module_Abrev( Module_OpFM ) = 'OpFM' y_FAST%Module_Abrev( Module_ED ) = 'ED' y_FAST%Module_Abrev( Module_BD ) = 'BD' y_FAST%Module_Abrev( Module_AD14 ) = 'AD' y_FAST%Module_Abrev( Module_AD ) = 'AD' y_FAST%Module_Abrev( Module_SrvD ) = 'SrvD' y_FAST%Module_Abrev( Module_HD ) = 'HD' y_FAST%Module_Abrev( Module_SD ) = 'SD' y_FAST%Module_Abrev( Module_ExtPtfm) = 'ExtPtfm' y_FAST%Module_Abrev( Module_MAP ) = 'MAP' y_FAST%Module_Abrev( Module_FEAM ) = 'FEAM' y_FAST%Module_Abrev( Module_MD ) = 'MD' y_FAST%Module_Abrev( Module_Orca ) = 'Orca' y_FAST%Module_Abrev( Module_IceF ) = 'IceF' y_FAST%Module_Abrev( Module_IceD ) = 'IceD' p%n_substeps = 1 ! number of substeps for between modules and global/FAST time p%BD_OutputSibling = .false. !............................................................................................................................... ! Read the primary file for the glue code: !............................................................................................................................... CALL FAST_ReadPrimaryFile( InputFile, p, m_FAST, OverrideAbortErrLev, ErrStat2, ErrMsg2 ) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) ! make sure some linearization variables are consistant if (.not. p%Linearize) p%CalcSteady = .false. if (.not. p%CalcSteady) p%TrimCase = TrimCase_none m_FAST%Lin%FoundSteady = .false. p%LinInterpOrder = p%InterpOrder ! 1 ! always use linear (or constant) interpolation on rotor? ! overwrite TMax if necessary) IF (PRESENT(TMax)) THEN p%TMax = TMax !p%TMax = MAX( TMax, p%TMax ) END IF IF ( ErrStat >= AbortErrLev ) RETURN p%KMax = 1 ! after more checking, we may put this in the input file... !IF (p%CompIce == Module_IceF) p%KMax = 2 p%SizeJac_Opt1 = 0 ! initialize this vector to zero; after we figure out what size the ED/SD/HD/BD meshes are, we'll fill this p%numIceLegs = 0 ! initialize number of support-structure legs in contact with ice (IceDyn will set this later) p%nBeams = 0 ! initialize number of BeamDyn instances (will be set later) ! determine what kind of turbine we're modeling: IF ( p%CompHydro == Module_HD ) THEN IF ( p%CompSub == Module_SD ) THEN p%TurbineType = Type_Offshore_Fixed ELSE p%TurbineType = Type_Offshore_Floating END IF ELSEIF ( p%CompMooring == Module_Orca ) THEN p%TurbineType = Type_Offshore_Floating ELSEIF ( p%CompSub == Module_ExtPtfm ) THEN p%TurbineType = Type_Offshore_Fixed ELSE p%TurbineType = Type_LandBased END IF p%n_TMax_m1 = CEILING( ( (p%TMax - t_initial) / p%DT ) ) - 1 ! We're going to go from step 0 to n_TMax (thus the -1 here) if (p%TMax < 1.0_DbKi) then ! log10(0) gives floating point divide-by-zero error p%TChanLen = MinChanLen else p%TChanLen = max( MinChanLen, int(log10(p%TMax))+7 ) end if p%OutFmt_t = 'F'//trim(num2lstr( p%TChanLen ))//'.4' ! 'F10.4' !............................................................................................................................... ! Do some error checking on the inputs (validation): !............................................................................................................................... call ValidateInputData(p, m_FAST, ErrStat2, ErrMsg2) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) IF ( ErrStat >= AbortErrLev ) RETURN RETURN END SUBROUTINE FAST_Init !---------------------------------------------------------------------------------------------------------------------------------- !> This routine validates FAST data. SUBROUTINE ValidateInputData(p, m_FAST, ErrStat, ErrMsg) TYPE(FAST_ParameterType), INTENT(INOUT) :: p !< The parameter data for the FAST (glue-code) simulation TYPE(FAST_MiscVarType), INTENT(IN ) :: m_FAST !< The misc data for the FAST (glue-code) simulation INTEGER(IntKi), INTENT( OUT) :: ErrStat !< Error status CHARACTER(*), INTENT( OUT) :: ErrMsg !< Error message REAL(DbKi) :: TmpTime ! A temporary variable for error checking INTEGER(IntKi) :: i INTEGER(IntKi) :: ErrStat2 CHARACTER(ErrMsgLen) :: ErrMsg2 CHARACTER(*), PARAMETER :: RoutineName='ValidateInputData' ErrStat = ErrID_None ErrMsg = "" IF ( p%TMax < 0.0_DbKi ) THEN CALL SetErrStat( ErrID_Fatal, 'TMax must not be a negative number.', ErrStat, ErrMsg, RoutineName ) ELSE IF ( p%TMax < p%TStart ) THEN CALL SetErrStat( ErrID_Fatal, 'TMax must not be less than TStart.', ErrStat, ErrMsg, RoutineName ) END IF IF ( p%n_ChkptTime < p%n_TMax_m1 ) THEN if (.NOT. p%WrBinOutFile) CALL SetErrStat( ErrID_Severe, 'It is highly recommended that time-marching output files be generated in binary format when generating checkpoint files.', ErrStat, ErrMsg, RoutineName ) if (p%CompMooring==MODULE_Orca) CALL SetErrStat( ErrID_Fatal, 'Restart capability for OrcaFlexInterface is not supported. Set ChkptTime larger than TMax.', ErrStat, ErrMsg, RoutineName ) ! also check for other features that aren't supported with restart (like ServoDyn's user-defined control routines) END IF IF ( p%DT <= 0.0_DbKi ) THEN CALL SetErrStat( ErrID_Fatal, 'DT must be greater than 0.', ErrStat, ErrMsg, RoutineName ) ELSE ! Test DT and TMax to ensure numerical stability -- HINT: see the use of OnePlusEps TmpTime = p%TMax*EPSILON(p%DT) IF ( p%DT <= TmpTime ) THEN CALL SetErrStat( ErrID_Fatal, 'DT must be greater than '//TRIM ( Num2LStr( TmpTime ) )//' seconds.', ErrStat, ErrMsg, RoutineName ) END IF END IF ! Check that InputFileData%OutFmt is a valid format specifier and will fit over the column headings CALL ChkRealFmtStr( p%OutFmt, 'OutFmt', p%FmtWidth, ErrStat2, ErrMsg2 ) call SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) IF ( p%WrTxtOutFile .and. p%FmtWidth < MinChanLen ) CALL SetErrStat( ErrID_Warn, 'OutFmt produces a column width of '// & TRIM(Num2LStr(p%FmtWidth))//'), which may be too small.', ErrStat, ErrMsg, RoutineName ) IF ( p%WrTxtOutFile .AND. p%TChanLen > ChanLen ) THEN ! ( p%TMax > 9999.999_DbKi ) CALL SetErrStat( ErrID_Warn, 'TMax is too large for a '//trim(num2lstr(ChanLen))//'-character time column in text tabular (time-marching) output files.'// & ' Postprocessors with this limitation may not work.', ErrStat, ErrMsg, RoutineName ) END IF IF ( p%TStart < 0.0_DbKi ) CALL SetErrStat( ErrID_Fatal, 'TStart must not be less than 0 seconds.', ErrStat, ErrMsg, RoutineName ) ! IF ( p%SttsTime <= 0.0_DbKi ) CALL SetErrStat( ErrID_Fatal, 'SttsTime must be greater than 0 seconds.', ErrStat, ErrMsg, RoutineName ) IF ( p%n_SttsTime < 1_IntKi ) CALL SetErrStat( ErrID_Fatal, 'SttsTime must be greater than 0 seconds.', ErrStat, ErrMsg, RoutineName ) IF ( p%n_ChkptTime < 1_IntKi ) CALL SetErrStat( ErrID_Fatal, 'ChkptTime must be greater than 0 seconds.', ErrStat, ErrMsg, RoutineName ) IF ( p%KMax < 1_IntKi ) CALL SetErrStat( ErrID_Fatal, 'KMax must be greater than 0.', ErrStat, ErrMsg, RoutineName ) IF (p%CompElast == Module_Unknown) CALL SetErrStat( ErrID_Fatal, 'CompElast must be 1 (ElastoDyn) or 2 (BeamDyn).', ErrStat, ErrMsg, RoutineName ) IF (p%CompAero == Module_Unknown) CALL SetErrStat( ErrID_Fatal, 'CompAero must be 0 (None), 1 (AeroDyn14), or 2 (AeroDyn).', ErrStat, ErrMsg, RoutineName ) IF (p%CompServo == Module_Unknown) CALL SetErrStat( ErrID_Fatal, 'CompServo must be 0 (None) or 1 (ServoDyn).', ErrStat, ErrMsg, RoutineName ) IF (p%CompHydro == Module_Unknown) CALL SetErrStat( ErrID_Fatal, 'CompHydro must be 0 (None) or 1 (HydroDyn).', ErrStat, ErrMsg, RoutineName ) IF (p%CompSub == Module_Unknown) CALL SetErrStat( ErrID_Fatal, 'CompSub must be 0 (None), 1 (SubDyn), or 2 (ExtPtfm_MCKF).', ErrStat, ErrMsg, RoutineName ) IF (p%CompMooring == Module_Unknown) CALL SetErrStat( ErrID_Fatal, 'CompMooring must be 0 (None), 1 (MAP), 2 (FEAMooring), 3 (MoorDyn), or 4 (OrcaFlex).', ErrStat, ErrMsg, RoutineName ) IF (p%CompIce == Module_Unknown) CALL SetErrStat( ErrID_Fatal, 'CompIce must be 0 (None) or 1 (IceFloe).', ErrStat, ErrMsg, RoutineName ) IF (p%CompHydro /= Module_HD) THEN IF (p%CompMooring == Module_MAP) THEN CALL SetErrStat( ErrID_Fatal, 'HydroDyn must be used when MAP is used. Set CompHydro > 0 or CompMooring = 0 in the FAST input file.', ErrStat, ErrMsg, RoutineName ) ELSEIF (p%CompMooring == Module_FEAM) THEN CALL SetErrStat( ErrID_Fatal, 'HydroDyn must be used when FEAMooring is used. Set CompHydro > 0 or CompMooring = 0 in the FAST input file.', ErrStat, ErrMsg, RoutineName ) ELSEIF (p%CompMooring == Module_MD) THEN CALL SetErrStat( ErrID_Fatal, 'HydroDyn must be used when MoorDyn is used. Set CompHydro > 0 or CompMooring = 0 in the FAST input file.', ErrStat, ErrMsg, RoutineName ) END IF ELSE IF (p%CompMooring == Module_Orca) CALL SetErrStat( ErrID_Fatal, 'HydroDyn cannot be used if OrcaFlex is used. Set CompHydro = 0 or CompMooring < 4 in the FAST input file.', ErrStat, ErrMsg, RoutineName ) IF (p%CompSub == Module_ExtPtfm) CALL SetErrStat( ErrID_Fatal, 'HydroDyn cannot be used if ExtPtfm_MCKF is used. Set CompHydro = 0 or CompSub < 2 in the FAST input file.', ErrStat, ErrMsg, RoutineName ) END IF IF (p%CompIce == Module_IceF) THEN IF (p%CompSub /= Module_SD) CALL SetErrStat( ErrID_Fatal, 'SubDyn must be used when IceFloe is used. Set CompSub > 0 or CompIce = 0 in the FAST input file.', ErrStat, ErrMsg, RoutineName ) IF (p%CompHydro /= Module_HD) CALL SetErrStat( ErrID_Fatal, 'HydroDyn must be used when IceFloe is used. Set CompHydro > 0 or CompIce = 0 in the FAST input file.', ErrStat, ErrMsg, RoutineName ) ELSEIF (p%CompIce == Module_IceD) THEN IF (p%CompSub /= Module_SD) CALL SetErrStat( ErrID_Fatal, 'SubDyn must be used when IceDyn is used. Set CompSub > 0 or CompIce = 0 in the FAST input file.', ErrStat, ErrMsg, RoutineName ) IF (p%CompHydro /= Module_HD) CALL SetErrStat( ErrID_Fatal, 'HydroDyn must be used when IceDyn is used. Set CompHydro > 0 or CompIce = 0 in the FAST input file.', ErrStat, ErrMsg, RoutineName ) END IF IF (p%CompElast == Module_BD .and. p%CompAero == Module_AD14 ) CALL SetErrStat( ErrID_Fatal, 'AeroDyn14 cannot be used when BeamDyn is used. Change CompAero or CompElast in the FAST input file.', ErrStat, ErrMsg, RoutineName ) ! IF ( p%InterpOrder < 0 .OR. p%InterpOrder > 2 ) THEN IF ( p%InterpOrder < 1 .OR. p%InterpOrder > 2 ) THEN CALL SetErrStat( ErrID_Fatal, 'InterpOrder must be 1 or 2.', ErrStat, ErrMsg, RoutineName ) ! 5/13/14 bjj: MAS and JMJ compromise for certain integrators is that InterpOrder cannot be 0 p%InterpOrder = 1 ! Avoid problems in error handling by setting this to 0 END IF IF ( p%NumCrctn < 0_IntKi ) THEN CALL SetErrStat( ErrID_Fatal, 'NumCrctn must be 0 or greater.', ErrStat, ErrMsg, RoutineName ) END IF if ( p%WrVTK == VTK_Unknown ) then call SetErrStat(ErrID_Fatal, 'WrVTK must be 0 (none), 1 (initialization only), 2 (animation), or 3 (mode shapes).', ErrStat, ErrMsg, RoutineName) else if ( p%VTK_type == VTK_Unknown ) then call SetErrStat(ErrID_Fatal, 'VTK_type must be 1 (surfaces), 2 (basic meshes:lines/points), or 3 (all meshes).', ErrStat, ErrMsg, RoutineName) ! note I'm not going to write that 4 (old) is an option end if if (p%WrVTK == VTK_ModeShapes .and. .not. p%Linearize) then call SetErrStat(ErrID_Fatal, 'WrVTK cannot be 3 (mode shapes) when Linearize is false. (Mode shapes require linearization analysis.)', ErrStat, ErrMsg, RoutineName) end if end if if (p%Linearize) then if (p%CalcSteady) then if (p%NLinTimes < 1) call SetErrStat(ErrID_Fatal,'NLinTimes must be at least 1 for linearization analysis.',ErrStat, ErrMsg, RoutineName) if (p%TrimCase /= TrimCase_yaw .and. p%TrimCase /= TrimCase_torque .and. p%TrimCase /= TrimCase_pitch) then call SetErrStat(ErrID_Fatal,'TrimCase must be either 1, 2, or 3.',ErrStat, ErrMsg, RoutineName) end if if (p%TrimTol <= epsilon(p%TrimTol)) call SetErrStat(ErrID_Fatal,'TrimTol must be larger than '//trim(num2lstr(epsilon(p%TrimTol)))//'.',ErrStat, ErrMsg, RoutineName) if (p%Twr_Kdmp < 0.0_ReKi) call SetErrStat(ErrID_Fatal,'Twr_Kdmp must not be negative.',ErrStat, ErrMsg, RoutineName) if (p%Bld_Kdmp < 0.0_ReKi) call SetErrStat(ErrID_Fatal,'Bld_Kdmp must not be negative.',ErrStat, ErrMsg, RoutineName) else if (.not. allocated(m_FAST%Lin%LinTimes)) then call SetErrStat(ErrID_Fatal, 'NLinTimes must be at least 1 for linearization analysis.',ErrStat, ErrMsg, RoutineName) else do i=1,p%NLinTimes if (m_FAST%Lin%LinTimes(i) < 0) call SetErrStat(ErrID_Fatal,'LinTimes must be positive values.',ErrStat, ErrMsg, RoutineName) end do do i=2,p%NLinTimes if (m_FAST%Lin%LinTimes(i) <= m_FAST%Lin%LinTimes(i-1)) call SetErrStat(ErrID_Fatal,'LinTimes must be unique values entered in increasing order.',ErrStat, ErrMsg, RoutineName) end do if (m_FAST%Lin%LinTimes(p%NLinTimes) > p%TMax) call SetErrStat(ErrID_Info, 'Tmax is less than the last linearization time. Linearization analysis will not be performed after TMax.',ErrStat, ErrMsg, RoutineName) end if end if if (p%LinInputs < LIN_NONE .or. p%LinInputs > LIN_ALL) call SetErrStat(ErrID_Fatal,'LinInputs must be 0, 1, or 2.',ErrStat, ErrMsg, RoutineName) if (p%LinOutputs < LIN_NONE .or. p%LinOutputs > LIN_ALL) call SetErrStat(ErrID_Fatal,'LinOutputs must be 0, 1, or 2.',ErrStat, ErrMsg, RoutineName) if (p%LinOutJac) then if ( p%LinInputs /= LIN_ALL .or. p%LinOutputs /= LIN_ALL) then call SetErrStat(ErrID_Info,'LinOutJac can be used only when LinInputs=LinOutputs=2.',ErrStat, ErrMsg, RoutineName) p%LinOutJac = .false. end if end if ! now, make sure we haven't asked for any modules that we can't yet linearize: if (p%CompInflow == MODULE_OpFM) call SetErrStat(ErrID_Fatal,'Linearization is not implemented for the OpenFOAM coupling.',ErrStat, ErrMsg, RoutineName) if (p%CompAero == MODULE_AD14) call SetErrStat(ErrID_Fatal,'Linearization is not implemented for the AeroDyn v14 module.',ErrStat, ErrMsg, RoutineName) !if (p%CompSub == MODULE_SD) call SetErrStat(ErrID_Fatal,'Linearization is not implemented for the SubDyn module.',ErrStat, ErrMsg, RoutineName) if (p%CompSub /= MODULE_None .and. p%CompSub /= MODULE_SD ) call SetErrStat(ErrID_Fatal,'Linearization is not implemented for the ExtPtfm_MCKF substructure module.',ErrStat, ErrMsg, RoutineName) if (p%CompMooring /= MODULE_None .and. p%CompMooring /= MODULE_MAP) call SetErrStat(ErrID_Fatal,'Linearization is not implemented for the FEAMooring or MoorDyn mooring modules.',ErrStat, ErrMsg, RoutineName) if (p%CompIce /= MODULE_None) call SetErrStat(ErrID_Fatal,'Linearization is not implemented for any of the ice loading modules.',ErrStat, ErrMsg, RoutineName) end if if ( p%TurbineType /= Type_LandBased .and. .not. EqualRealNos(p%TurbinePos(3), 0.0_SiKi) ) then call SetErrStat(ErrID_Fatal, 'Height of turbine location, TurbinePos(3), must be 0 for offshore turbines.', ErrStat, ErrMsg, RoutineName) end if !............................................................................................................................... ! temporary check on p_FAST%DT_out IF ( .NOT. EqualRealNos( p%DT_out, p%DT ) ) THEN IF ( p%DT_out < p%DT ) THEN CALL SetErrStat( ErrID_Fatal, 'DT_out must be at least DT ('//TRIM(Num2LStr(p%DT))//' s).', ErrStat, ErrMsg, RoutineName ) ELSEIF ( .NOT. EqualRealNos( p%DT_out, p%DT * p%n_DT_Out ) ) THEN CALL SetErrStat( ErrID_Fatal, 'DT_out must be an integer multiple of DT.', ErrStat, ErrMsg, RoutineName ) END IF END IF END SUBROUTINE ValidateInputData !---------------------------------------------------------------------------------------------------------------------------------- !> This routine initializes the output for the glue code, including writing the header for the primary output file. SUBROUTINE FAST_InitOutput( p_FAST, y_FAST, Init, ErrStat, ErrMsg ) IMPLICIT NONE ! Passed variables TYPE(FAST_ParameterType), INTENT(IN) :: p_FAST !< Glue-code simulation parameters TYPE(FAST_OutputFileType), INTENT(INOUT) :: y_FAST !< Glue-code simulation outputs TYPE(FAST_InitData), INTENT(IN) :: Init !< Initialization data for all modules INTEGER(IntKi), INTENT(OUT) :: ErrStat !< Error status CHARACTER(*), INTENT(OUT) :: ErrMsg !< Error message corresponding to ErrStat ! Local variables. INTEGER(IntKi) :: I, J ! Generic index for DO loops. INTEGER(IntKi) :: indxNext ! The index of the next value to be written to an array INTEGER(IntKi) :: NumOuts ! number of channels to be written to the output file(s) !...................................................... ! Set the description lines to be printed in the output file !...................................................... y_FAST%FileDescLines(1) = 'Predictions were generated on '//CurDate()//' at '//CurTime()//' using '//TRIM(GetVersion(FAST_Ver)) y_FAST%FileDescLines(2) = 'linked with ' //' '//TRIM(GetNVD(NWTC_Ver )) ! we'll get the rest of the linked modules in the section below y_FAST%FileDescLines(3) = 'Description from the FAST input file: '//TRIM(p_FAST%FTitle) !...................................................... ! We'll fill out the rest of FileDescLines(2), ! and save the module version info for later use, too: !...................................................... y_FAST%Module_Ver( Module_ED ) = Init%OutData_ED%Ver y_FAST%FileDescLines(2) = TRIM(y_FAST%FileDescLines(2) ) //'; '//TRIM(GetNVD(y_FAST%Module_Ver( Module_ED ) )) IF ( p_FAST%CompElast == Module_BD ) THEN y_FAST%Module_Ver( Module_BD ) = Init%OutData_BD(1)%Ver ! call copy routine for this type if it every uses dynamic memory y_FAST%FileDescLines(2) = TRIM(y_FAST%FileDescLines(2) ) //'; '//TRIM(GetNVD(y_FAST%Module_Ver( Module_BD ))) END IF IF ( p_FAST%CompInflow == Module_IfW ) THEN y_FAST%Module_Ver( Module_IfW ) = Init%OutData_IfW%Ver ! call copy routine for this type if it every uses dynamic memory y_FAST%FileDescLines(2) = TRIM(y_FAST%FileDescLines(2) ) //'; '//TRIM(GetNVD(y_FAST%Module_Ver( Module_IfW ))) ELSEIF ( p_FAST%CompInflow == Module_OpFM ) THEN y_FAST%Module_Ver( Module_OpFM ) = Init%OutData_OpFM%Ver ! call copy routine for this type if it every uses dynamic memory y_FAST%FileDescLines(2) = TRIM(y_FAST%FileDescLines(2) ) //'; '//TRIM(GetNVD(y_FAST%Module_Ver( Module_OpFM ))) END IF IF ( p_FAST%CompAero == Module_AD14 ) THEN y_FAST%Module_Ver( Module_AD14 ) = Init%OutData_AD14%Ver y_FAST%FileDescLines(2) = TRIM(y_FAST%FileDescLines(2) ) //'; '//TRIM(GetNVD(y_FAST%Module_Ver( Module_AD14 ) )) ELSEIF ( p_FAST%CompAero == Module_AD ) THEN y_FAST%Module_Ver( Module_AD ) = Init%OutData_AD%Ver y_FAST%FileDescLines(2) = TRIM(y_FAST%FileDescLines(2) ) //'; '//TRIM(GetNVD(y_FAST%Module_Ver( Module_AD ) )) END IF IF ( p_FAST%CompServo == Module_SrvD ) THEN y_FAST%Module_Ver( Module_SrvD ) = Init%OutData_SrvD%Ver y_FAST%FileDescLines(2) = TRIM(y_FAST%FileDescLines(2) ) //'; '//TRIM(GetNVD(y_FAST%Module_Ver( Module_SrvD ))) END IF IF ( p_FAST%CompHydro == Module_HD ) THEN y_FAST%Module_Ver( Module_HD ) = Init%OutData_HD%Ver y_FAST%FileDescLines(2) = TRIM(y_FAST%FileDescLines(2) ) //'; '//TRIM(GetNVD(y_FAST%Module_Ver( Module_HD ))) END IF IF ( p_FAST%CompSub == Module_SD ) THEN y_FAST%Module_Ver( Module_SD ) = Init%OutData_SD%Ver y_FAST%FileDescLines(2) = TRIM(y_FAST%FileDescLines(2) ) //'; '//TRIM(GetNVD(y_FAST%Module_Ver( Module_SD ))) ELSE IF ( p_FAST%CompSub == Module_ExtPtfm ) THEN y_FAST%Module_Ver( Module_ExtPtfm ) = Init%OutData_ExtPtfm%Ver y_FAST%FileDescLines(2) = TRIM(y_FAST%FileDescLines(2) ) //'; '//TRIM(GetNVD(y_FAST%Module_Ver( Module_ExtPtfm ))) END IF IF ( p_FAST%CompMooring == Module_MAP ) THEN y_FAST%Module_Ver( Module_MAP ) = Init%OutData_MAP%Ver y_FAST%FileDescLines(2) = TRIM(y_FAST%FileDescLines(2) ) //'; '//TRIM(GetNVD(y_FAST%Module_Ver( Module_MAP ))) ELSEIF ( p_FAST%CompMooring == Module_MD ) THEN y_FAST%Module_Ver( Module_MD ) = Init%OutData_MD%Ver y_FAST%FileDescLines(2) = TRIM(y_FAST%FileDescLines(2) ) //'; '//TRIM(GetNVD(y_FAST%Module_Ver( Module_MD ))) ELSEIF ( p_FAST%CompMooring == Module_FEAM ) THEN y_FAST%Module_Ver( Module_FEAM ) = Init%OutData_FEAM%Ver y_FAST%FileDescLines(2) = TRIM(y_FAST%FileDescLines(2) ) //'; '//TRIM(GetNVD(y_FAST%Module_Ver( Module_FEAM ))) ELSEIF ( p_FAST%CompMooring == Module_Orca ) THEN y_FAST%Module_Ver( Module_Orca ) = Init%OutData_Orca%Ver y_FAST%FileDescLines(2) = TRIM(y_FAST%FileDescLines(2) ) //'; '//TRIM(GetNVD(y_FAST%Module_Ver( Module_Orca))) END IF IF ( p_FAST%CompIce == Module_IceF ) THEN y_FAST%Module_Ver( Module_IceF ) = Init%OutData_IceF%Ver y_FAST%FileDescLines(2) = TRIM(y_FAST%FileDescLines(2) ) //'; '//TRIM(GetNVD(y_FAST%Module_Ver( Module_IceF ))) ELSEIF ( p_FAST%CompIce == Module_IceD ) THEN y_FAST%Module_Ver( Module_IceD ) = Init%OutData_IceD%Ver y_FAST%FileDescLines(2) = TRIM(y_FAST%FileDescLines(2) ) //'; '//TRIM(GetNVD(y_FAST%Module_Ver( Module_IceD ))) END IF !...................................................... ! Set the number of output columns from each module !...................................................... y_FAST%numOuts = 0 ! Inintialize entire array !y_FAST%numOuts(Module_InfW) = 3 !hack for now: always output 3 wind speeds at hub-height IF ( ALLOCATED( Init%OutData_IfW%WriteOutputHdr ) ) y_FAST%numOuts(Module_IfW) = SIZE(Init%OutData_IfW%WriteOutputHdr) IF ( ALLOCATED( Init%OutData_OpFM%WriteOutputHdr ) ) y_FAST%numOuts(Module_OpFM) = SIZE(Init%OutData_OpFM%WriteOutputHdr) IF ( ALLOCATED( Init%OutData_ED%WriteOutputHdr ) ) y_FAST%numOuts(Module_ED) = SIZE(Init%OutData_ED%WriteOutputHdr) do i=1,p_FAST%nBeams IF ( ALLOCATED( Init%OutData_BD(i)%WriteOutputHdr) ) y_FAST%numOuts(Module_BD) = y_FAST%numOuts(Module_BD) + SIZE(Init%OutData_BD(i)%WriteOutputHdr) end do !ad14 doesn't have outputs: y_FAST%numOuts(Module_AD14) = 0 IF ( ALLOCATED( Init%OutData_AD%WriteOutputHdr ) ) y_FAST%numOuts(Module_AD) = SIZE(Init%OutData_AD%WriteOutputHdr) IF ( ALLOCATED( Init%OutData_SrvD%WriteOutputHdr ) ) y_FAST%numOuts(Module_SrvD) = SIZE(Init%OutData_SrvD%WriteOutputHdr) IF ( ALLOCATED( Init%OutData_HD%WriteOutputHdr ) ) y_FAST%numOuts(Module_HD) = SIZE(Init%OutData_HD%WriteOutputHdr) IF ( ALLOCATED( Init%OutData_SD%WriteOutputHdr ) ) y_FAST%numOuts(Module_SD) = SIZE(Init%OutData_SD%WriteOutputHdr) IF ( ALLOCATED( Init%OutData_ExtPtfm%WriteOutputHdr) ) y_FAST%numOuts(Module_ExtPtfm)= SIZE(Init%OutData_ExtPtfm%WriteOutputHdr) IF ( ALLOCATED( Init%OutData_MAP%WriteOutputHdr ) ) y_FAST%numOuts(Module_MAP) = SIZE(Init%OutData_MAP%WriteOutputHdr) IF ( ALLOCATED( Init%OutData_FEAM%WriteOutputHdr ) ) y_FAST%numOuts(Module_FEAM) = SIZE(Init%OutData_FEAM%WriteOutputHdr) IF ( ALLOCATED( Init%OutData_MD%WriteOutputHdr ) ) y_FAST%numOuts(Module_MD) = SIZE(Init%OutData_MD%WriteOutputHdr) IF ( ALLOCATED( Init%OutData_Orca%WriteOutputHdr ) ) y_FAST%numOuts(Module_Orca) = SIZE(Init%OutData_Orca%WriteOutputHdr) IF ( ALLOCATED( Init%OutData_IceF%WriteOutputHdr ) ) y_FAST%numOuts(Module_IceF) = SIZE(Init%OutData_IceF%WriteOutputHdr) IF ( ALLOCATED( Init%OutData_IceD%WriteOutputHdr ) ) y_FAST%numOuts(Module_IceD) = SIZE(Init%OutData_IceD%WriteOutputHdr)*p_FAST%numIceLegs !...................................................... ! Initialize the output channel names and units !...................................................... NumOuts = 1 + SUM( y_FAST%numOuts ) CALL AllocAry( y_FAST%ChannelNames,NumOuts, 'ChannelNames', ErrStat, ErrMsg ) IF ( ErrStat /= ErrID_None ) RETURN CALL AllocAry( y_FAST%ChannelUnits,NumOuts, 'ChannelUnits', ErrStat, ErrMsg ) IF ( ErrStat /= ErrID_None ) RETURN y_FAST%ChannelNames(1) = 'Time' y_FAST%ChannelUnits(1) = '(s)' indxNext = 2 DO i=1,y_FAST%numOuts(Module_IfW) !InflowWind y_FAST%ChannelNames(indxNext) = Init%OutData_IfW%WriteOutputHdr(i) y_FAST%ChannelUnits(indxNext) = Init%OutData_IfW%WriteOutputUnt(i) indxNext = indxNext + 1 END DO DO i=1,y_FAST%numOuts(Module_OpFM) !OpenFOAM y_FAST%ChannelNames(indxNext) = Init%OutData_OpFM%WriteOutputHdr(i) y_FAST%ChannelUnits(indxNext) = Init%OutData_OpFM%WriteOutputUnt(i) indxNext = indxNext + 1 END DO DO i=1,y_FAST%numOuts(Module_ED) !ElastoDyn y_FAST%ChannelNames(indxNext) = Init%OutData_ED%WriteOutputHdr(i) y_FAST%ChannelUnits(indxNext) = Init%OutData_ED%WriteOutputUnt(i) indxNext = indxNext + 1 END DO IF ( y_FAST%numOuts(Module_BD) > 0_IntKi ) THEN !BeamDyn do i=1,p_FAST%nBeams if ( allocated(Init%OutData_BD(i)%WriteOutputHdr) ) then do j=1,size(Init%OutData_BD(i)%WriteOutputHdr) y_FAST%ChannelNames(indxNext) = 'B'//TRIM(Num2Lstr(i))//trim(Init%OutData_BD(i)%WriteOutputHdr(j)) y_FAST%ChannelUnits(indxNext) = Init%OutData_BD(i)%WriteOutputUnt(j) indxNext = indxNext + 1 end do ! j end if end do END IF ! none for AeroDyn14 DO i=1,y_FAST%numOuts(Module_AD) !AeroDyn y_FAST%ChannelNames(indxNext) = Init%OutData_AD%WriteOutputHdr(i) y_FAST%ChannelUnits(indxNext) = Init%OutData_AD%WriteOutputUnt(i) indxNext = indxNext + 1 END DO DO i=1,y_FAST%numOuts(Module_SrvD) !ServoDyn y_FAST%ChannelNames(indxNext) = Init%OutData_SrvD%WriteOutputHdr(i) y_FAST%ChannelUnits(indxNext) = Init%OutData_SrvD%WriteOutputUnt(i) indxNext = indxNext + 1 END DO DO i=1,y_FAST%numOuts(Module_HD) !HydroDyn y_FAST%ChannelNames(indxNext) = Init%OutData_HD%WriteOutputHdr(i) y_FAST%ChannelUnits(indxNext) = Init%OutData_HD%WriteOutputUnt(i) indxNext = indxNext + 1 END DO DO i=1,y_FAST%numOuts(Module_SD) !SubDyn y_FAST%ChannelNames(indxNext) = Init%OutData_SD%WriteOutputHdr(i) y_FAST%ChannelUnits(indxNext) = Init%OutData_SD%WriteOutputUnt(i) indxNext = indxNext + 1 END DO DO i=1,y_FAST%numOuts(Module_ExtPtfm) !ExtPtfm_MCKF y_FAST%ChannelNames(indxNext) = Init%OutData_ExtPtfm%WriteOutputHdr(i) y_FAST%ChannelUnits(indxNext) = Init%OutData_ExtPtfm%WriteOutputUnt(i) indxNext = indxNext + 1 END DO DO i=1,y_FAST%numOuts(Module_MAP) !MAP y_FAST%ChannelNames(indxNext) = Init%OutData_MAP%WriteOutputHdr(i) y_FAST%ChannelUnits(indxNext) = Init%OutData_MAP%WriteOutputUnt(i) indxNext = indxNext + 1 END DO DO i=1,y_FAST%numOuts(Module_MD) !MoorDyn y_FAST%ChannelNames(indxNext) = Init%OutData_MD%WriteOutputHdr(i) y_FAST%ChannelUnits(indxNext) = Init%OutData_MD%WriteOutputUnt(i) indxNext = indxNext + 1 END DO DO i=1,y_FAST%numOuts(Module_FEAM) !FEAMooring y_FAST%ChannelNames(indxNext) = Init%OutData_FEAM%WriteOutputHdr(i) y_FAST%ChannelUnits(indxNext) = Init%OutData_FEAM%WriteOutputUnt(i) indxNext = indxNext + 1 END DO DO i=1,y_FAST%numOuts(Module_Orca) !OrcaFlex y_FAST%ChannelNames(indxNext) = Init%OutData_Orca%WriteOutputHdr(i) y_FAST%ChannelUnits(indxNext) = Init%OutData_Orca%WriteOutputUnt(i) indxNext = indxNext + 1 END DO DO i=1,y_FAST%numOuts(Module_IceF) !IceFloe y_FAST%ChannelNames(indxNext) = Init%OutData_IceF%WriteOutputHdr(i) y_FAST%ChannelUnits(indxNext) = Init%OutData_IceF%WriteOutputUnt(i) indxNext = indxNext + 1 END DO IF ( y_FAST%numOuts(Module_IceD) > 0_IntKi ) THEN !IceDyn DO I=1,p_FAST%numIceLegs DO J=1,SIZE(Init%OutData_IceD%WriteOutputHdr) y_FAST%ChannelNames(indxNext) =TRIM(Init%OutData_IceD%WriteOutputHdr(J))//'L'//TRIM(Num2Lstr(I)) !bjj: do we want this "Lx" at the end? y_FAST%ChannelUnits(indxNext) = Init%OutData_IceD%WriteOutputUnt(J) indxNext = indxNext + 1 END DO ! J END DO ! I END IF !...................................................... ! Open the text output file and print the headers !...................................................... IF (p_FAST%WrTxtOutFile) THEN y_FAST%ActualChanLen = max( MinChanLen, p_FAST%FmtWidth ) DO I=1,NumOuts y_FAST%ActualChanLen = max( y_FAST%ActualChanLen, LEN_TRIM(y_FAST%ChannelNames(I)) ) y_FAST%ActualChanLen = max( y_FAST%ActualChanLen, LEN_TRIM(y_FAST%ChannelUnits(I)) ) ENDDO ! I y_FAST%OutFmt_a = '"'//p_FAST%Delim//'"'//p_FAST%OutFmt ! format for array elements from individual modules if (p_FAST%FmtWidth < y_FAST%ActualChanLen) then y_FAST%OutFmt_a = trim(y_FAST%OutFmt_a)//','//trim(num2lstr(y_FAST%ActualChanLen - p_FAST%FmtWidth))//'x' end if CALL GetNewUnit( y_FAST%UnOu, ErrStat, ErrMsg ) IF ( ErrStat >= AbortErrLev ) RETURN CALL OpenFOutFile ( y_FAST%UnOu, TRIM(p_FAST%OutFileRoot)//'.out', ErrStat, ErrMsg ) IF ( ErrStat >= AbortErrLev ) RETURN ! Add some file information: WRITE (y_FAST%UnOu,'(/,A)') TRIM( y_FAST%FileDescLines(1) ) WRITE (y_FAST%UnOu,'(1X,A)') TRIM( y_FAST%FileDescLines(2) ) WRITE (y_FAST%UnOu,'()' ) !print a blank line WRITE (y_FAST%UnOu,'(A)' ) TRIM( y_FAST%FileDescLines(3) ) WRITE (y_FAST%UnOu,'()' ) !print a blank line !...................................................... ! Write the names of the output parameters on one line: !...................................................... if (p_FAST%Delim /= " ") then ! trim trailing spaces if not space delimited: CALL WrFileNR ( y_FAST%UnOu, trim(y_FAST%ChannelNames(1)) ) ! first one is time, with a special format DO I=2,NumOuts CALL WrFileNR ( y_FAST%UnOu, p_FAST%Delim//trim(y_FAST%ChannelNames(I)) ) ENDDO ! I else CALL WrFileNR ( y_FAST%UnOu, y_FAST%ChannelNames(1)(1:p_FAST%TChanLen) ) ! first one is time, with a special format DO I=2,NumOuts CALL WrFileNR ( y_FAST%UnOu, p_FAST%Delim//y_FAST%ChannelNames(I)(1:y_FAST%ActualChanLen) ) ENDDO ! I end if WRITE (y_FAST%UnOu,'()') !...................................................... ! Write the units of the output parameters on one line: !...................................................... if (p_FAST%Delim /= " ") then CALL WrFileNR ( y_FAST%UnOu, trim(y_FAST%ChannelUnits(1)) ) DO I=2,NumOuts CALL WrFileNR ( y_FAST%UnOu, p_FAST%Delim//trim(y_FAST%ChannelUnits(I)) ) ENDDO ! I else CALL WrFileNR ( y_FAST%UnOu, y_FAST%ChannelUnits(1)(1:p_FAST%TChanLen) ) DO I=2,NumOuts CALL WrFileNR ( y_FAST%UnOu, p_FAST%Delim//y_FAST%ChannelUnits(I)(1:y_FAST%ActualChanLen) ) ENDDO ! I end if WRITE (y_FAST%UnOu,'()') END IF !...................................................... ! Allocate data for binary output file !...................................................... IF (p_FAST%WrBinOutFile) THEN ! calculate the size of the array of outputs we need to store y_FAST%NOutSteps = CEILING ( (p_FAST%TMax - p_FAST%TStart) / p_FAST%DT_OUT ) + 1 CALL AllocAry( y_FAST%AllOutData, NumOuts-1, y_FAST%NOutSteps, 'AllOutData', ErrStat, ErrMsg ) y_FAST%AllOutData = 0.0_ReKi IF ( ErrStat >= AbortErrLev ) RETURN IF ( p_FAST%WrBinMod == FileFmtID_WithTime ) THEN ! we store the entire time array CALL AllocAry( y_FAST%TimeData, y_FAST%NOutSteps, 'TimeData', ErrStat, ErrMsg ) IF ( ErrStat >= AbortErrLev ) RETURN ELSE CALL AllocAry( y_FAST%TimeData, 2_IntKi, 'TimeData', ErrStat, ErrMsg ) IF ( ErrStat >= AbortErrLev ) RETURN y_FAST%TimeData(1) = 0.0_DbKi ! This is the first output time, which we will set later y_FAST%TimeData(2) = p_FAST%DT_out ! This is the (constant) time between subsequent writes to the output file END IF y_FAST%n_Out = 0 !number of steps actually written to the file END IF y_FAST%VTK_count = 0 ! first VTK file has 0 as output RETURN END SUBROUTINE FAST_InitOutput !---------------------------------------------------------------------------------------------------------------------------------- !> This routine reads in the primary FAST input file, does some validation, and places the values it reads in the !! parameter structure (p). It prints to an echo file if requested. SUBROUTINE FAST_ReadPrimaryFile( InputFile, p, m_FAST, OverrideAbortErrLev, ErrStat, ErrMsg ) IMPLICIT NONE ! Passed variables TYPE(FAST_ParameterType), INTENT(INOUT) :: p !< The parameter data for the FAST (glue-code) simulation TYPE(FAST_MiscVarType), INTENT(INOUT) :: m_FAST !< Miscellaneous variables CHARACTER(*), INTENT(IN) :: InputFile !< Name of the file containing the primary input data LOGICAL, INTENT(IN) :: OverrideAbortErrLev !< Determines if we should override AbortErrLev INTEGER(IntKi), INTENT(OUT) :: ErrStat !< Error status CHARACTER(*), INTENT(OUT) :: ErrMsg !< Error message ! Local variables: REAL(DbKi) :: TmpRate ! temporary variable to read VTK_fps before converting to #steps based on DT REAL(DbKi) :: TmpTime ! temporary variable to read SttsTime and ChkptTime before converting to #steps based on DT INTEGER(IntKi) :: I ! loop counter INTEGER(IntKi) :: UnIn ! Unit number for reading file INTEGER(IntKi) :: UnEc ! I/O unit for echo file. If > 0, file is open for writing. INTEGER(IntKi) :: IOS ! Temporary Error status INTEGER(IntKi) :: ErrStat2 ! Temporary Error status INTEGER(IntKi) :: OutFileFmt ! An integer that indicates what kind of tabular output should be generated (1=text, 2=binary, 3=both) LOGICAL :: Echo ! Determines if an echo file should be written LOGICAL :: TabDelim ! Determines if text output should be delimited by tabs (true) or space (false) CHARACTER(ErrMsgLen) :: ErrMsg2 ! Temporary Error message CHARACTER(1024) :: PriPath ! Path name of the primary file CHARACTER(10) :: AbortLevel ! String that indicates which error level should be used to abort the program: WARNING, SEVERE, or FATAL CHARACTER(30) :: Line ! string for default entry in input file CHARACTER(*), PARAMETER :: RoutineName = 'FAST_ReadPrimaryFile' ! Initialize some variables: UnEc = -1 Echo = .FALSE. ! Don't echo until we've read the "Echo" flag CALL GetPath( InputFile, PriPath ) ! Input files will be relative to the path where the primary input file is located. ! Get an available unit number for the file. CALL GetNewUnit( UnIn, ErrStat, ErrMsg ) IF ( ErrStat >= AbortErrLev ) RETURN ! Open the Primary input file. CALL OpenFInpFile ( UnIn, InputFile, ErrStat2, ErrMsg2 ) CALL SetErrStat( ErrStat2, ErrMsg2,ErrStat,ErrMsg,RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if ! Read the lines up/including to the "Echo" simulation control variable ! If echo is FALSE, don't write these lines to the echo file. ! If Echo is TRUE, rewind and write on the second try. I = 1 !set the number of times we've read the file DO !-------------------------- HEADER --------------------------------------------- CALL ReadCom( UnIn, InputFile, 'File header: Module Version (line 1)', ErrStat2, ErrMsg2, UnEc ) CALL SetErrStat( ErrStat2, ErrMsg2,ErrStat,ErrMsg,RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if CALL ReadStr( UnIn, InputFile, p%FTitle, 'FTitle', 'File Header: File Description (line 2)', ErrStat2, ErrMsg2, UnEc ) CALL SetErrStat( ErrStat2, ErrMsg2,ErrStat,ErrMsg,RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if !---------------------- SIMULATION CONTROL -------------------------------------- CALL ReadCom( UnIn, InputFile, 'Section Header: Simulation Control', ErrStat2, ErrMsg2, UnEc ) CALL SetErrStat( ErrStat2, ErrMsg2,ErrStat,ErrMsg,RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if ! Echo - Echo input data to <RootName>.ech (flag): CALL ReadVar( UnIn, InputFile, Echo, "Echo", "Echo input data to <RootName>.ech (flag)", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2,ErrStat,ErrMsg,RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if IF (.NOT. Echo .OR. I > 1) EXIT !exit this loop ! Otherwise, open the echo file, then rewind the input file and echo everything we've read I = I + 1 ! make sure we do this only once (increment counter that says how many times we've read this file) CALL OpenEcho ( UnEc, TRIM(p%OutFileRoot)//'.ech', ErrStat2, ErrMsg2, FAST_Ver ) CALL SetErrStat( ErrStat2, ErrMsg2,ErrStat,ErrMsg,RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if IF ( UnEc > 0 ) WRITE (UnEc,'(/,A,/)') 'Data from '//TRIM(FAST_Ver%Name)//' primary input file "'//TRIM( InputFile )//'":' REWIND( UnIn, IOSTAT=ErrStat2 ) IF (ErrStat2 /= 0_IntKi ) THEN CALL SetErrStat( ErrID_Fatal, 'Error rewinding file "'//TRIM(InputFile)//'".',ErrStat,ErrMsg,RoutineName) call cleanup() RETURN END IF END DO CALL WrScr( TRIM(FAST_Ver%Name)//' input file heading:' ) CALL WrScr( ' '//TRIM( p%FTitle ) ) CALL WrScr('') ! AbortLevel - Error level when simulation should abort: CALL ReadVar( UnIn, InputFile, AbortLevel, "AbortLevel", "Error level when simulation should abort (string)", & ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2,ErrStat,ErrMsg,RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if IF (OverrideAbortErrLev) THEN ! Let's set the abort level here.... knowing that everything before this aborted only on FATAL errors! CALL Conv2UC( AbortLevel ) !convert to upper case SELECT CASE( TRIM(AbortLevel) ) CASE ( "WARNING" ) AbortErrLev = ErrID_Warn CASE ( "SEVERE" ) AbortErrLev = ErrID_Severe CASE ( "FATAL" ) AbortErrLev = ErrID_Fatal CASE DEFAULT CALL SetErrStat( ErrID_Fatal, 'Invalid AbortLevel specified in FAST input file. '// & 'Valid entries are "WARNING", "SEVERE", or "FATAL".',ErrStat,ErrMsg,RoutineName) call cleanup() RETURN END SELECT END IF ! TMax - Total run time (s): CALL ReadVar( UnIn, InputFile, p%TMax, "TMax", "Total run time (s)", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if ! DT - Recommended module time step (s): CALL ReadVar( UnIn, InputFile, p%DT, "DT", "Recommended module time step (s)", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if if ( EqualRealNos(p%DT, 0.0_DbKi) ) then ! add a fatal error here because we're going to divide by DT later in this routine: CALL SetErrStat( ErrID_Fatal, 'DT cannot be zero.', ErrStat, ErrMsg, RoutineName) call cleanup() return end if ! InterpOrder - Interpolation order for inputs and outputs {0=nearest neighbor ,1=linear, 2=quadratic} CALL ReadVar( UnIn, InputFile, p%InterpOrder, "InterpOrder", "Interpolation order "//& "for inputs and outputs {0=nearest neighbor ,1=linear, 2=quadratic} (-)", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if ! NumCrctn - Number of predictor-corrector iterations {1=explicit calculation, i.e., no corrections} CALL ReadVar( UnIn, InputFile, p%NumCrctn, "NumCrctn", "Number of corrections"//& "{0=explicit calculation, i.e., no corrections} (-)", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if ! DT_UJac - Time between calls to get Jacobians (s) CALL ReadVar( UnIn, InputFile, p%DT_UJac, "DT_UJac", "Time between calls to get Jacobians (s)", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if ! UJacSclFact - Scaling factor used in Jacobians (-) CALL ReadVar( UnIn, InputFile, p%UJacSclFact, "UJacSclFact", "Scaling factor used in Jacobians (-)", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if !---------------------- FEATURE SWITCHES AND FLAGS -------------------------------- CALL ReadCom( UnIn, InputFile, 'Section Header: Feature Switches and Flags', ErrStat2, ErrMsg2, UnEc ) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if ! CompElast - Compute structural dynamics (switch) {1=ElastoDyn; 2=ElastoDyn + BeamDyn for blades}: CALL ReadVar( UnIn, InputFile, p%CompElast, "CompElast", "Compute structural dynamics (switch) {1=ElastoDyn; 2=ElastoDyn + BeamDyn for blades}", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if ! immediately convert to values used inside the code: IF ( p%CompElast == 1 ) THEN p%CompElast = Module_ED ELSEIF ( p%CompElast == 2 ) THEN p%CompElast = Module_BD ELSE p%CompElast = Module_Unknown END IF ! CompInflow - inflow wind velocities (switch) {0=still air; 1=InflowWind}: CALL ReadVar( UnIn, InputFile, p%CompInflow, "CompInflow", "inflow wind velocities (switch) {0=still air; 1=InflowWind}", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if ! immediately convert to values used inside the code: IF ( p%CompInflow == 0 ) THEN p%CompInflow = Module_NONE ELSEIF ( p%CompInflow == 1 ) THEN p%CompInflow = Module_IfW ELSEIF ( p%CompInflow == 2 ) THEN p%CompInflow = Module_OpFM ELSE p%CompInflow = Module_Unknown END IF ! CompAero - Compute aerodynamic loads (switch) {0=None; 1=AeroDyn}: CALL ReadVar( UnIn, InputFile, p%CompAero, "CompAero", "Compute aerodynamic loads (switch) {0=None; 1=AeroDyn}", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if ! immediately convert to values used inside the code: IF ( p%CompAero == 0 ) THEN p%CompAero = Module_NONE ELSEIF ( p%CompAero == 1 ) THEN p%CompAero = Module_AD14 ELSEIF ( p%CompAero == 2 ) THEN p%CompAero = Module_AD ELSE p%CompAero = Module_Unknown END IF ! CompServo - Compute control and electrical-drive dynamics (switch) {0=None; 1=ServoDyn}: CALL ReadVar( UnIn, InputFile, p%CompServo, "CompServo", "Compute control and electrical-drive dynamics (switch) {0=None; 1=ServoDyn}", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if ! immediately convert to values used inside the code: IF ( p%CompServo == 0 ) THEN p%CompServo = Module_NONE ELSEIF ( p%CompServo == 1 ) THEN p%CompServo = Module_SrvD ELSE p%CompServo = Module_Unknown END IF ! CompHydro - Compute hydrodynamic loads (switch) {0=None; 1=HydroDyn}: CALL ReadVar( UnIn, InputFile, p%CompHydro, "CompHydro", "Compute hydrodynamic loads (switch) {0=None; 1=HydroDyn}", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if ! immediately convert to values used inside the code: IF ( p%CompHydro == 0 ) THEN p%CompHydro = Module_NONE ELSEIF ( p%CompHydro == 1 ) THEN p%CompHydro = Module_HD ELSE p%CompHydro = Module_Unknown END IF ! CompSub - Compute sub-structural dynamics (switch) {0=None; 1=SubDyn; 2=ExtPtfm_MCKF}: CALL ReadVar( UnIn, InputFile, p%CompSub, "CompSub", "Compute sub-structural dynamics (switch) {0=None; 1=SubDyn}", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if ! immediately convert to values used inside the code: IF ( p%CompSub == 0 ) THEN p%CompSub = Module_NONE ELSEIF ( p%CompSub == 1 ) THEN p%CompSub = Module_SD ELSEIF ( p%CompSub == 2 ) THEN p%CompSub = Module_ExtPtfm ELSE p%CompSub = Module_Unknown END IF ! CompMooring - Compute mooring line dynamics (flag): CALL ReadVar( UnIn, InputFile, p%CompMooring, "CompMooring", "Compute mooring system (switch) {0=None; 1=MAP; 2=FEAMooring; 3=MoorDyn; 4=OrcaFlex}", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if ! immediately convert to values used inside the code: IF ( p%CompMooring == 0 ) THEN p%CompMooring = Module_NONE ELSEIF ( p%CompMooring == 1 ) THEN p%CompMooring = Module_MAP ELSEIF ( p%CompMooring == 2 ) THEN p%CompMooring = Module_FEAM ELSEIF ( p%CompMooring == 3 ) THEN p%CompMooring = Module_MD ELSEIF ( p%CompMooring == 4 ) THEN p%CompMooring = Module_Orca ELSE p%CompMooring = Module_Unknown END IF ! CompIce - Compute ice loads (switch) {0=None; 1=IceFloe}: CALL ReadVar( UnIn, InputFile, p%CompIce, "CompIce", "Compute ice loads (switch) {0=None; 1=IceFloe}", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if ! immediately convert to values used inside the code: IF ( p%CompIce == 0 ) THEN p%CompIce = Module_NONE ELSEIF ( p%CompIce == 1 ) THEN p%CompIce = Module_IceF ELSEIF ( p%CompIce == 2 ) THEN p%CompIce = Module_IceD ELSE p%CompIce = Module_Unknown END IF !---------------------- INPUT FILES --------------------------------------------- CALL ReadCom( UnIn, InputFile, 'Section Header: Input Files', ErrStat2, ErrMsg2, UnEc ) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if ! EDFile - Name of file containing ElastoDyn input parameters (-): CALL ReadVar( UnIn, InputFile, p%EDFile, "EDFile", "Name of file containing ElastoDyn input parameters (-)", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if IF ( PathIsRelative( p%EDFile ) ) p%EDFile = TRIM(PriPath)//TRIM(p%EDFile) DO i=1,MaxNBlades ! BDBldFile - Name of file containing BeamDyn blade input parameters (-): CALL ReadVar( UnIn, InputFile, p%BDBldFile(i), "BDBldFile("//TRIM(num2LStr(i))//")", "Name of file containing BeamDyn blade "//trim(num2lstr(i))//"input parameters (-)", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if IF ( PathIsRelative( p%BDBldFile(i) ) ) p%BDBldFile(i) = TRIM(PriPath)//TRIM(p%BDBldFile(i)) END DO ! InflowFile - Name of file containing inflow wind input parameters (-): CALL ReadVar( UnIn, InputFile, p%InflowFile, "InflowFile", "Name of file containing inflow wind input parameters (-)", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if IF ( PathIsRelative( p%InflowFile ) ) p%InflowFile = TRIM(PriPath)//TRIM(p%InflowFile) ! AeroFile - Name of file containing aerodynamic input parameters (-): CALL ReadVar( UnIn, InputFile, p%AeroFile, "AeroFile", "Name of file containing aerodynamic input parameters (-)", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if IF ( PathIsRelative( p%AeroFile ) ) p%AeroFile = TRIM(PriPath)//TRIM(p%AeroFile) ! ServoFile - Name of file containing control and electrical-drive input parameters (-): CALL ReadVar( UnIn, InputFile, p%ServoFile, "ServoFile", "Name of file containing control and electrical-drive input parameters (-)", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if IF ( PathIsRelative( p%ServoFile ) ) p%ServoFile = TRIM(PriPath)//TRIM(p%ServoFile) ! HydroFile - Name of file containing hydrodynamic input parameters (-): CALL ReadVar( UnIn, InputFile, p%HydroFile, "HydroFile", "Name of file containing hydrodynamic input parameters (-)", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if IF ( PathIsRelative( p%HydroFile ) ) p%HydroFile = TRIM(PriPath)//TRIM(p%HydroFile) ! SubFile - Name of file containing sub-structural input parameters (-): CALL ReadVar( UnIn, InputFile, p%SubFile, "SubFile", "Name of file containing sub-structural input parameters (-)", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if IF ( PathIsRelative( p%SubFile ) ) p%SubFile = TRIM(PriPath)//TRIM(p%SubFile) ! MooringFile - Name of file containing mooring system input parameters (-): CALL ReadVar( UnIn, InputFile, p%MooringFile, "MooringFile", "Name of file containing mooring system input parameters (-)", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if IF ( PathIsRelative( p%MooringFile ) ) p%MooringFile = TRIM(PriPath)//TRIM(p%MooringFile) ! IceFile - Name of file containing ice input parameters (-): CALL ReadVar( UnIn, InputFile, p%IceFile, "IceFile", "Name of file containing ice input parameters (-)", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if IF ( PathIsRelative( p%IceFile ) ) p%IceFile = TRIM(PriPath)//TRIM(p%IceFile) !---------------------- OUTPUT -------------------------------------------------- CALL ReadCom( UnIn, InputFile, 'Section Header: Output', ErrStat2, ErrMsg2, UnEc ) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if ! SumPrint - Print summary data to <RootName>.sum (flag): CALL ReadVar( UnIn, InputFile, p%SumPrint, "SumPrint", "Print summary data to <RootName>.sum (flag)", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if ! SttsTime - Amount of time between screen status messages (s): CALL ReadVar( UnIn, InputFile, TmpTime, "SttsTime", "Amount of time between screen status messages (s)", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if IF (TmpTime > p%TMax) THEN p%n_SttsTime = HUGE(p%n_SttsTime) ELSE p%n_SttsTime = NINT( TmpTime / p%DT ) END IF ! ChkptTime - Amount of time between creating checkpoint files for potential restart (s): CALL ReadVar( UnIn, InputFile, TmpTime, "ChkptTime", "Amount of time between creating checkpoint files for potential restart (s)", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if IF (TmpTime > p%TMax) THEN p%n_ChkptTime = HUGE(p%n_ChkptTime) ELSE p%n_ChkptTime = NINT( TmpTime / p%DT ) END IF ! DT_Out - Time step for tabular output (s): CALL ReadVar( UnIn, InputFile, Line, "DT_Out", "Time step for tabular output (s)", ErrStat2, ErrMsg2, UnEc) !CALL ReadVar( UnIn, InputFile, p%DT_Out, "DT_Out", "Time step for tabular output (s)", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if CALL Conv2UC( Line ) IF ( INDEX(Line, "DEFAULT" ) == 1 ) THEN p%DT_Out = p%DT ELSE ! If it's not "default", read this variable; otherwise use the value in p%DT READ( Line, *, IOSTAT=IOS) p%DT_Out CALL CheckIOS ( IOS, InputFile, 'DT_Out', NumType, ErrStat2, ErrMsg2 ) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if END IF p%n_DT_Out = NINT( p%DT_Out / p%DT ) ! TStart - Time to begin tabular output (s): CALL ReadVar( UnIn, InputFile, p%TStart, "TStart", "Time to begin tabular output (s)", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if !> OutFileFmt - Format for tabular (time-marching) output file (switch) {1: text file [<RootName>.out], 2: binary file [<RootName>.outb], 4: HDF5 [<RootName>.h5], add for combinations} !! !! Combinations of output files are possible by adding the values corresponding to each file. The possible combination of options are therefore !! !! | `OutFileFmt` | Description | !! |:------------:|:---------------------------------------------------------------------| !! | 1 | Text file only `<RootName>.out` | !! | 2 | Binary file only `<RootName>.outb` | !! | 3 | Text and binary files | !! | 4 | uncompressed binary file `<RootName>.outbu` | !! | 5 | Text and uncompressed binary files | !! | 6 => 4 | Binary (not written) and uncompressed binary files; same as 4 | !! | 7 => 5 | Text, Binary (not written), and uncompressed binary files; same as 5 | !! ! OutFileFmt - Format for tabular (time-marching) output file(s) (1: text file [<RootName>.out], 2: binary file [<RootName>.outb], 3: both) (-): CALL ReadVar( UnIn, InputFile, OutFileFmt, "OutFileFmt", "Format for tabular (time-marching) output file(s) {0: uncompressed binary and text file, 1: text file [<RootName>.out], 2: compressed binary file [<RootName>.outb], 3: both text and compressed binary, 4: uncompressed binary <RootName>.outb]; add for combinations) (-)", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if if (OutFileFmt == 0) OutFileFmt = 5 ! convert integer to binary representation of which file formats to generate: p%WrTxtOutFile = mod(OutFileFmt,2) == 1 OutFileFmt = OutFileFmt / 2 ! integer division p%WrBinOutFile = mod(OutFileFmt,2) == 1 OutFileFmt = OutFileFmt / 2 ! integer division if (mod(OutFileFmt,2) == 1) then ! This is a feature for the regression testing system. It writes binary output stored as uncompressed double floating point data instead of compressed int16 data. ! If the compressed binary version was requested, that will not be generated if (p%WrBinOutFile) then call SetErrStat(ErrID_Warn,'Binary compressed file will not be generated because the uncompressed version was also requested.', ErrStat, ErrMsg, RoutineName) else p%WrBinOutFile = .true. end if p%WrBinMod = FileFmtID_NoCompressWithoutTime ! A format specifier for the binary output file format (3=don't include time channel and do not pack data) else p%WrBinMod = FileFmtID_ChanLen_In ! A format specifier for the binary output file format (4=don't include time channel; do include channel width; do pack data) end if OutFileFmt = OutFileFmt / 2 ! integer division if (OutFileFmt /= 0) then call SetErrStat( ErrID_Fatal, "OutFileFmt must be 0, 1, 2, or 3.",ErrStat,ErrMsg,RoutineName) call cleanup() return end if ! TabDelim - Use tab delimiters in text tabular output file? (flag): CALL ReadVar( UnIn, InputFile, TabDelim, "TabDelim", "Use tab delimiters in text tabular output file? (flag)", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if IF ( TabDelim ) THEN p%Delim = TAB ELSE p%Delim = ' ' END IF ! OutFmt - Format used for text tabular output (except time). Resulting field should be 10 characters. (-): CALL ReadVar( UnIn, InputFile, p%OutFmt, "OutFmt", "Format used for text tabular output (except time). Resulting field should be 10 characters. (-)", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if !---------------------- LINEARIZATION ----------------------------------------------- CALL ReadCom( UnIn, InputFile, 'Section Header: Linearization', ErrStat2, ErrMsg2, UnEc ) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if ! Linearize - Linearization analysis (flag) CALL ReadVar( UnIn, InputFile, p%Linearize, "Linearize", "Linearization analysis (flag)", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if ! CalcSteady - Calculate a steady-state periodic operating point before linearization? [unused if Linearize=False] (flag) CALL ReadVar( UnIn, InputFile, p%CalcSteady, "CalcSteady", "Calculate a steady-state periodic operating point before linearization? (flag)", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) ! TrimCase - Controller parameter to be trimmed {1:yaw; 2:torque; 3:pitch} [used only if CalcSteady=True] (-) CALL ReadVar( UnIn, InputFile, p%TrimCase, "TrimCase", "Controller parameter to be trimmed {1:yaw; 2:torque; 3:pitch} (-)", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) ! TrimTol - Tolerance for the rotational speed convergence [used only if CalcSteady=True] (-) CALL ReadVar( UnIn, InputFile, p%TrimTol, "TrimTol", "Tolerance for the rotational speed convergence (-)", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) ! TrimGain - Proportional gain for the rotational speed error (>0) [used only if CalcSteady=True] (rad/(rad/s) for yaw or pitch; Nm/(rad/s) for torque) CALL ReadVar( UnIn, InputFile, p%TrimGain, "TrimGain", "Proportional gain for the rotational speed error (>0) (rad/(rad/s) for yaw or pitch; Nm/(rad/s) for torque)", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) ! Twr_Kdmp - Damping factor for the tower [used only if CalcSteady=True] (N/(m/s)) CALL ReadVar( UnIn, InputFile, p%Twr_Kdmp, "Twr_Kdmp", "Damping factor for the tower (N/(m/s))", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) ! Bld_Kdmp - Damping factor for the blades [used only if CalcSteady=True] (N/(m/s)) CALL ReadVar( UnIn, InputFile, p%Bld_Kdmp, "Bld_Kdmp", "Damping factor for the blades (N/(m/s))", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if ! NLinTimes - Number of times to linearize (or number of equally spaced azimuth steps in periodic linearized model) (-) [>=1] CALL ReadVar( UnIn, InputFile, p%NLinTimes, "NLinTimes", "Number of times to linearize (-) [>=1]", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if if (.not. p%Linearize) then p%CalcSteady = .false. p%NLinTimes = 0 end if ! LinTimes - Times to linearize (s) [1 to NLinTimes] if (.not. p%CalcSteady .and. p%NLinTimes >= 1 ) then call AllocAry( m_FAST%Lin%LinTimes, p%NLinTimes, 'LinTimes', ErrStat2, ErrMsg2 ) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if CALL ReadAry( UnIn, InputFile, m_FAST%Lin%LinTimes, p%NLinTimes, "LinTimes", "Times to linearize (s) [1 to NLinTimes]", ErrStat2, ErrMsg2, UnEc) else CALL ReadCom( UnIn, InputFile, 'Times to linearize (s) [1 to NLinTimes] ', ErrStat2, ErrMsg2, UnEc ) end if CALL SetErrStat( ErrStat2, ErrMsg2,ErrStat,ErrMsg,RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if ! LinInputs - Include inputs in linearization (switch) {0=none; 1=standard; 2=all module inputs (debug)} CALL ReadVar( UnIn, InputFile, p%LinInputs, "LinInputs", "Include inputs in linearization (switch) {0=none; 1=standard; 2=all module inputs (debug)}", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if ! LinOutputs - Include outputs in linearization (switch) (0=none; 1=from OutList(s); 2=all module outputs (debug)) CALL ReadVar( UnIn, InputFile, p%LinOutputs, "LinOutputs", "Include outputs in linearization (switch) (0=none; 1=from OutList(s); 2=all module outputs (debug))", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if ! LinOutJac - Include full Jacabians in linearization output (for debug) (flag) CALL ReadVar( UnIn, InputFile, p%LinOutJac, "LinOutJac", "Include full Jacabians in linearization output (for debug) (flag)", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if ! LinOutMod - Write module-level linearization output files in addition to output for full system? (flag) CALL ReadVar( UnIn, InputFile, p%LinOutMod, "LinOutMod", "Write module-level linearization output files in addition to output for full system? (flag)", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if !---------------------- VISUALIZATION ----------------------------------------------- CALL ReadCom( UnIn, InputFile, 'Section Header: Visualization', ErrStat2, ErrMsg2, UnEc ) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if ! WrVTK - VTK Visualization data output: (switch) {0=none; 1=initialization data only; 2=animation; 3=mode shapes}: CALL ReadVar( UnIn, InputFile, p%WrVTK, "WrVTK", "Write VTK visualization files (0=none; 1=initialization data only; 2=animation; 3=mode shapes)", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if IF ( p%WrVTK < 0 .OR. p%WrVTK > 3 ) THEN p%WrVTK = VTK_Unknown END IF ! VTK_Type - Type of VTK visualization data: (switch) {1=surfaces; 2=basic meshes (lines/points); 3=all meshes (debug)}: CALL ReadVar( UnIn, InputFile, p%VTK_Type, "VTK_Type", "Type of VTK visualization data: (1=surfaces; 2=basic meshes (lines/points); 3=all meshes)", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if ! immediately convert to values used inside the code: IF ( p%VTK_Type == 0 ) THEN p%VTK_Type = VTK_None ELSEIF ( p%VTK_Type == 1 ) THEN p%VTK_Type = VTK_Surf ELSEIF ( p%VTK_Type == 2 ) THEN p%VTK_Type = VTK_Basic ELSEIF ( p%VTK_Type == 3 ) THEN p%VTK_Type = VTK_All ELSEIF ( p%VTK_Type == 4 ) THEN p%VTK_Type = VTK_Old ELSE p%VTK_Type = VTK_Unknown END IF !! equivalent: !IF ( p%VTK_Type < 0 .OR. p%VTK_Type > 4 ) THEN ! p%VTK_Type = VTK_Unknown !END IF ! VTK_fields - Write mesh fields to VTK data files? (flag) {true/false}: CALL ReadVar( UnIn, InputFile, p%VTK_fields, "VTK_fields", "Write mesh fields to VTK data files? (flag)", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if ! VTK_fps - Frame rate for VTK output (frames per second) {will use closest integer multiple of DT} CALL ReadVar( UnIn, InputFile, p%VTK_fps, "VTK_fps", "Frame rate for VTK output(fps)", ErrStat2, ErrMsg2, UnEc) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if ( ErrStat >= AbortErrLev ) then call cleanup() RETURN end if ! convert frames-per-second to seconds per sample: if ( EqualRealNos(p%VTK_fps, 0.0_DbKi) ) then TmpTime = p%TMax + p%DT else TmpTime = 1.0_DbKi / p%VTK_fps end if ! now save the number of time steps between VTK file output: IF (p%WrVTK == VTK_ModeShapes) THEN p%n_VTKTime = 1 ELSE IF (TmpTime > p%TMax) THEN p%n_VTKTime = HUGE(p%n_VTKTime) ELSE p%n_VTKTime = NINT( TmpTime / p%DT ) ! I'll warn if p%n_VTKTime*p%DT is not TmpTime IF (p%WrVTK == VTK_Animate) THEN TmpRate = p%n_VTKTime*p%DT if (.not. EqualRealNos(TmpRate, TmpTime)) then call SetErrStat(ErrID_Info, '1/VTK_fps is not an integer multiple of DT. FAST will output VTK information at '//& trim(num2lstr(1.0_DbKi/TmpRate))//' fps, the closest rate possible.',ErrStat,ErrMsg,RoutineName) end if END IF END IF call cleanup() RETURN CONTAINS !............................................................................................................................... subroutine cleanup() CLOSE( UnIn ) IF ( UnEc > 0 ) CLOSE ( UnEc ) end subroutine cleanup !............................................................................................................................... END SUBROUTINE FAST_ReadPrimaryFile !---------------------------------------------------------------------------------------------------------------------------------- !> This subroutine sets up some of the information needed for plotting VTK surfaces. It initializes only the data needed before !! HD initialization. (HD needs some of this data so it can return the wave elevation data we want.) SUBROUTINE SetVTKParameters_B4HD(p_FAST, InitOutData_ED, InitInData_HD, BD, ErrStat, ErrMsg) TYPE(FAST_ParameterType), INTENT(INOUT) :: p_FAST !< The parameters of the glue code TYPE(ED_InitOutputType), INTENT(IN ) :: InitOutData_ED !< The initialization output from structural dynamics module TYPE(HydroDyn_InitInputType), INTENT(INOUT) :: InitInData_HD !< The initialization input to HydroDyn TYPE(BeamDyn_Data), INTENT(IN ) :: BD !< BeamDyn data INTEGER(IntKi), INTENT( OUT) :: ErrStat !< Error status of the operation CHARACTER(*), INTENT( OUT) :: ErrMsg !< Error message if ErrStat /= ErrID_None REAL(SiKi) :: BladeLength, Width, WidthBy2 REAL(SiKi) :: dx, dy INTEGER(IntKi) :: i, j, n INTEGER(IntKi) :: ErrStat2 CHARACTER(ErrMsgLen) :: ErrMsg2 CHARACTER(*), PARAMETER :: RoutineName = 'SetVTKParameters_B4HD' ErrStat = ErrID_None ErrMsg = "" ! Get radius for ground (blade length + hub radius): if ( p_FAST%CompElast == Module_BD ) then BladeLength = TwoNorm(BD%y(1)%BldMotion%Position(:,1) - BD%y(1)%BldMotion%Position(:,BD%y(1)%BldMotion%Nnodes)) else BladeLength = InitOutData_ED%BladeLength end if p_FAST%VTK_Surface%HubRad = InitOutData_ED%HubRad p_FAST%VTK_Surface%GroundRad = BladeLength + p_FAST%VTK_Surface%HubRad !........................................................................................................ ! We don't use the rest of this routine for stick-figure output if (p_FAST%VTK_Type /= VTK_Surf) return !........................................................................................................ ! initialize wave elevation data: if ( p_FAST%CompHydro == Module_HD ) then p_FAST%VTK_surface%NWaveElevPts(1) = 25 p_FAST%VTK_surface%NWaveElevPts(2) = 25 call allocAry( InitInData_HD%WaveElevXY, 2, p_FAST%VTK_surface%NWaveElevPts(1)*p_FAST%VTK_surface%NWaveElevPts(2), 'WaveElevXY', ErrStat2, ErrMsg2) call SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) if (ErrStat >= AbortErrLev) return Width = p_FAST%VTK_Surface%GroundRad * VTK_GroundFactor dx = Width / (p_FAST%VTK_surface%NWaveElevPts(1) - 1) dy = Width / (p_FAST%VTK_surface%NWaveElevPts(2) - 1) WidthBy2 = Width / 2.0_SiKi n = 1 do i=1,p_FAST%VTK_surface%NWaveElevPts(1) do j=1,p_FAST%VTK_surface%NWaveElevPts(2) InitInData_HD%WaveElevXY(1,n) = dx*(i-1) - WidthBy2 !+ p_FAST%TurbinePos(1) ! HD takes p_FAST%TurbinePos into account already InitInData_HD%WaveElevXY(2,n) = dy*(j-1) - WidthBy2 !+ p_FAST%TurbinePos(2) n = n+1 end do end do end if END SUBROUTINE SetVTKParameters_B4HD !---------------------------------------------------------------------------------------------------------------------------------- !> This subroutine sets up the information needed for plotting VTK surfaces. SUBROUTINE SetVTKParameters(p_FAST, InitOutData_ED, InitOutData_AD, InitInData_HD, InitOutData_HD, ED, BD, AD, HD, ErrStat, ErrMsg) TYPE(FAST_ParameterType), INTENT(INOUT) :: p_FAST !< The parameters of the glue code TYPE(ED_InitOutputType), INTENT(IN ) :: InitOutData_ED !< The initialization output from structural dynamics module TYPE(AD_InitOutputType), INTENT(INOUT) :: InitOutData_AD !< The initialization output from AeroDyn TYPE(HydroDyn_InitInputType), INTENT(INOUT) :: InitInData_HD !< The initialization input to HydroDyn TYPE(HydroDyn_InitOutputType),INTENT(INOUT) :: InitOutData_HD !< The initialization output from HydroDyn TYPE(ElastoDyn_Data), INTENT(IN ) :: ED !< ElastoDyn data TYPE(BeamDyn_Data), INTENT(IN ) :: BD !< BeamDyn data TYPE(AeroDyn_Data), INTENT(IN ) :: AD !< AeroDyn data TYPE(HydroDyn_Data), INTENT(IN ) :: HD !< HydroDyn data INTEGER(IntKi), INTENT( OUT) :: ErrStat !< Error status of the operation CHARACTER(*), INTENT( OUT) :: ErrMsg !< Error message if ErrStat /= ErrID_None REAL(SiKi) :: RefPoint(3), RefLengths(2) REAL(SiKi) :: x, y REAL(SiKi) :: TwrDiam_top, TwrDiam_base, TwrRatio, TwrLength INTEGER(IntKi) :: topNode, baseNode INTEGER(IntKi) :: NumBl, k CHARACTER(1024) :: vtkroot INTEGER(IntKi) :: ErrStat2 CHARACTER(ErrMsgLen) :: ErrMsg2 CHARACTER(*), PARAMETER :: RoutineName = 'SetVTKParameters' ErrStat = ErrID_None ErrMsg = "" ! get the name of the output directory for vtk files (in a subdirectory called "vtk" of the output directory), and ! create the VTK directory if it does not exist call GetPath ( p_FAST%OutFileRoot, p_FAST%VTK_OutFileRoot, vtkroot ) ! the returned p_FAST%VTK_OutFileRoot includes a file separator character at the end p_FAST%VTK_OutFileRoot = trim(p_FAST%VTK_OutFileRoot) // 'vtk' call MKDIR( trim(p_FAST%VTK_OutFileRoot) ) p_FAST%VTK_OutFileRoot = trim( p_FAST%VTK_OutFileRoot ) // PathSep // trim(vtkroot) ! calculate the number of digits in 'y_FAST%NOutSteps' (Maximum number of output steps to be written) ! this will be used to pad the write-out step in the VTK filename with zeros in calls to MeshWrVTK() if (p_FAST%WrVTK == VTK_ModeShapes .AND. p_FAST%VTK_modes%VTKLinTim==1) then if (p_FAST%NLinTimes < 1) p_FAST%NLinTimes = 1 !in case we reached here with an error p_FAST%VTK_tWidth = CEILING( log10( real( p_FAST%NLinTimes) ) ) + 1 else p_FAST%VTK_tWidth = CEILING( log10( real(p_FAST%n_TMax_m1+1, ReKi) / p_FAST%n_VTKTime ) ) + 1 end if ! determine number of blades NumBl = InitOutData_ED%NumBl ! initialize the vtk data p_FAST%VTK_Surface%NumSectors = 25 ! NOTE: we set p_FAST%VTK_Surface%GroundRad and p_FAST%VTK_Surface%HubRad in SetVTKParameters_B4HD ! write the ground or seabed reference polygon: RefPoint = p_FAST%TurbinePos if (p_FAST%CompHydro == MODULE_HD) then RefLengths = p_FAST%VTK_Surface%GroundRad*VTK_GroundFactor/2.0_SiKi ! note that p_FAST%TurbinePos(3) must be 0 for offshore turbines RefPoint(3) = p_FAST%TurbinePos(3) - InitOutData_HD%WtrDpth call WrVTK_Ground ( RefPoint, RefLengths, trim(p_FAST%VTK_OutFileRoot) // '.SeabedSurface', ErrStat2, ErrMsg2 ) RefPoint(3) = p_FAST%TurbinePos(3) - InitOutData_HD%MSL2SWL call WrVTK_Ground ( RefPoint, RefLengths, trim(p_FAST%VTK_OutFileRoot) // '.StillWaterSurface', ErrStat2, ErrMsg2 ) else RefLengths = p_FAST%VTK_Surface%GroundRad !array = scalar call WrVTK_Ground ( RefPoint, RefLengths, trim(p_FAST%VTK_OutFileRoot) // '.GroundSurface', ErrStat2, ErrMsg2 ) end if !........................................................................................................ ! We don't use the rest of this routine for stick-figure output if (p_FAST%VTK_Type /= VTK_Surf) return !........................................................................................................ ! we're going to create a box using these dimensions y = ED%y%HubPtMotion%Position(3, 1) - ED%y%NacelleMotion%Position(3, 1) x = TwoNorm( ED%y%HubPtMotion%Position(1:2,1) - ED%y%NacelleMotion%Position(1:2,1) ) - p_FAST%VTK_Surface%HubRad p_FAST%VTK_Surface%NacelleBox(:,1) = (/ -x, y, 0.0_SiKi /) p_FAST%VTK_Surface%NacelleBox(:,2) = (/ x, y, 0.0_SiKi /) p_FAST%VTK_Surface%NacelleBox(:,3) = (/ x, -y, 0.0_SiKi /) p_FAST%VTK_Surface%NacelleBox(:,4) = (/ -x, -y, 0.0_SiKi /) p_FAST%VTK_Surface%NacelleBox(:,5) = (/ -x, -y, 2*y /) p_FAST%VTK_Surface%NacelleBox(:,6) = (/ x, -y, 2*y /) p_FAST%VTK_Surface%NacelleBox(:,7) = (/ x, y, 2*y /) p_FAST%VTK_Surface%NacelleBox(:,8) = (/ -x, y, 2*y /) !....................... ! tapered tower !....................... CALL AllocAry(p_FAST%VTK_Surface%TowerRad,ED%y%TowerLn2Mesh%NNodes,'VTK_Surface%TowerRad',ErrStat2,ErrMsg2) CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) IF (ErrStat >= AbortErrLev) RETURN topNode = ED%y%TowerLn2Mesh%NNodes - 1 baseNode = ED%y%TowerLn2Mesh%refNode TwrLength = TwoNorm( ED%y%TowerLn2Mesh%position(:,topNode) - ED%y%TowerLn2Mesh%position(:,baseNode) ) ! this is the assumed length of the tower TwrRatio = TwrLength / 87.6_SiKi ! use ratio of the tower length to the length of the 5MW tower TwrDiam_top = 3.87*TwrRatio TwrDiam_base = 6.0*TwrRatio TwrRatio = 0.5 * (TwrDiam_top - TwrDiam_base) / TwrLength do k=1,ED%y%TowerLn2Mesh%NNodes TwrLength = TwoNorm( ED%y%TowerLn2Mesh%position(:,k) - ED%y%TowerLn2Mesh%position(:,baseNode) ) p_FAST%VTK_Surface%TowerRad(k) = 0.5*TwrDiam_Base + TwrRatio*TwrLength end do !....................... ! blade surfaces !....................... allocate(p_FAST%VTK_Surface%BladeShape(NumBl),stat=ErrStat2) if (errStat2/=0) then call setErrStat(ErrID_Fatal,'Error allocating VTK_Surface%BladeShape.',ErrStat,ErrMsg,RoutineName) return end if IF ( p_FAST%CompAero == Module_AD ) THEN ! These meshes may have airfoil data associated with nodes... IF (ALLOCATED(InitOutData_AD%BladeShape)) THEN do k=1,NumBl call move_alloc( InitOutData_AD%BladeShape(k)%AirfoilCoords, p_FAST%VTK_Surface%BladeShape(k)%AirfoilCoords ) end do ELSE #ifndef USE_DEFAULT_BLADE_SURFACE call setErrStat(ErrID_Fatal,'Cannot do surface visualization without airfoil coordinates defined in AeroDyn.',ErrStat,ErrMsg,RoutineName) return END IF ELSE call setErrStat(ErrID_Fatal,'Cannot do surface visualization without using AeroDyn.',ErrStat,ErrMsg,RoutineName) return END IF #else ! AD used without airfoil coordinates specified rootNode = 1 DO K=1,NumBl tipNode = AD%Input(1)%BladeMotion(K)%NNodes cylNode = min(3,AD%Input(1)%BladeMotion(K)%Nnodes) call SetVTKDefaultBladeParams(AD%Input(1)%BladeMotion(K), p_FAST%VTK_Surface%BladeShape(K), tipNode, rootNode, cylNode, ErrStat2, ErrMsg2) CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) IF (ErrStat >= AbortErrLev) RETURN END DO END IF ELSE IF ( p_FAST%CompElast == Module_BD ) THEN rootNode = 1 DO K=1,NumBl tipNode = BD%y(k)%BldMotion%NNodes cylNode = min(3,BD%y(k)%BldMotion%NNodes) call SetVTKDefaultBladeParams(BD%y(k)%BldMotion, p_FAST%VTK_Surface%BladeShape(K), tipNode, rootNode, cylNode, ErrStat2, ErrMsg2) CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) IF (ErrStat >= AbortErrLev) RETURN END DO ELSE DO K=1,NumBl rootNode = ED%y%BladeLn2Mesh(K)%NNodes tipNode = ED%y%BladeLn2Mesh(K)%NNodes-1 cylNode = min(2,ED%y%BladeLn2Mesh(K)%NNodes) call SetVTKDefaultBladeParams(ED%y%BladeLn2Mesh(K), p_FAST%VTK_Surface%BladeShape(K), tipNode, rootNode, cylNode, ErrStat2, ErrMsg2) CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) IF (ErrStat >= AbortErrLev) RETURN END DO END IF #endif !....................... ! wave elevation !....................... !bjj: interpolate here instead of each time step? if ( allocated(InitOutData_HD%WaveElevSeries) ) then call move_alloc( InitInData_HD%WaveElevXY, p_FAST%VTK_Surface%WaveElevXY ) call move_alloc( InitOutData_HD%WaveElevSeries, p_FAST%VTK_Surface%WaveElev ) ! put the following lines in loops to avoid stack-size issues: do k=1,size(p_FAST%VTK_Surface%WaveElevXY,2) p_FAST%VTK_Surface%WaveElevXY(:,k) = p_FAST%VTK_Surface%WaveElevXY(:,k) + p_FAST%TurbinePos(1:2) end do ! note that p_FAST%TurbinePos(3) must be 0 for offshore turbines !do k=1,size(p_FAST%VTK_Surface%WaveElev,2) ! p_FAST%VTK_Surface%WaveElev(:,k) = p_FAST%VTK_Surface%WaveElev(:,k) + p_FAST%TurbinePos(3) ! not sure this is really accurate if p_FAST%TurbinePos(3) is non-zero !end do end if !....................... ! morison surfaces !....................... IF ( HD%Input(1)%Morison%Mesh%Committed ) THEN !TODO: FIX for visualization GJH 4/23/20 ! call move_alloc(InitOutData_HD%Morison%Morison_Rad, p_FAST%VTK_Surface%MorisonRad) END IF END SUBROUTINE SetVTKParameters !---------------------------------------------------------------------------------------------------------------------------------- !> This subroutine comes up with some default airfoils for blade surfaces for a given blade mesh, M. SUBROUTINE SetVTKDefaultBladeParams(M, BladeShape, tipNode, rootNode, cylNode, ErrStat, ErrMsg) TYPE(MeshType), INTENT(IN ) :: M !< The Mesh the defaults should be calculated for TYPE(FAST_VTK_BLSurfaceType), INTENT(INOUT) :: BladeShape !< BladeShape to set to default values INTEGER(IntKi), INTENT(IN ) :: rootNode !< Index of root node (innermost node) for this mesh INTEGER(IntKi), INTENT(IN ) :: tipNode !< Index of tip node (outermost node) for this mesh INTEGER(IntKi), INTENT(IN ) :: cylNode !< Index of last node to have a cylinder shape INTEGER(IntKi), INTENT( OUT) :: ErrStat !< Error status of the operation CHARACTER(*), INTENT( OUT) :: ErrMsg !< Error message if ErrStat /= ErrID_None REAL(SiKi) :: bladeLength, chord, pitchAxis REAL(SiKi) :: bladeLengthFract, bladeLengthFract2, ratio, posLength ! temporary quantities REAL(SiKi) :: cylinderLength, x, y, angle INTEGER(IntKi) :: i, j INTEGER(IntKi) :: ErrStat2 CHARACTER(ErrMsgLen) :: ErrMsg2 CHARACTER(*), PARAMETER :: RoutineName = 'SetVTKDefaultBladeParams' !Note: jmj does not like this default option integer, parameter :: N = 66 ! default airfoil shape coordinates; uses S809 values from http://wind.nrel.gov/airfoils/Shapes/S809_Shape.html: real, parameter, dimension(N) :: xc=(/ 1.0,0.996203,0.98519,0.967844,0.945073,0.917488,0.885293,0.848455,0.80747,0.763042,0.715952,0.667064,0.617331,0.56783,0.519832,0.474243,0.428461,0.382612,0.33726,0.29297,0.250247,0.209576,0.171409,0.136174,0.104263,0.076035,0.051823,0.03191,0.01659,0.006026,0.000658,0.000204,0.0,0.000213,0.001045,0.001208,0.002398,0.009313,0.02323,0.04232,0.065877,0.093426,0.124111,0.157653,0.193738,0.231914,0.271438,0.311968,0.35337,0.395329,0.438273,0.48192,0.527928,0.576211,0.626092,0.676744,0.727211,0.776432,0.823285,0.86663,0.905365,0.938474,0.965086,0.984478,0.996141,1.0 /) real, parameter, dimension(N) :: yc=(/ 0.0,0.000487,0.002373,0.00596,0.011024,0.017033,0.023458,0.03028,0.037766,0.045974,0.054872,0.064353,0.074214,0.084095,0.093268,0.099392,0.10176,0.10184,0.10007,0.096703,0.091908,0.085851,0.078687,0.07058,0.061697,0.052224,0.042352,0.032299,0.02229,0.012615,0.003723,0.001942,-0.00002,-0.001794,-0.003477,-0.003724,-0.005266,-0.011499,-0.020399,-0.030269,-0.040821,-0.051923,-0.063082,-0.07373,-0.083567,-0.092442,-0.099905,-0.105281,-0.108181,-0.108011,-0.104552,-0.097347,-0.086571,-0.073979,-0.060644,-0.047441,-0.0351,-0.024204,-0.015163,-0.008204,-0.003363,-0.000487,0.000743,0.000775,0.00029,0.0 /) call AllocAry(BladeShape%AirfoilCoords, 2, N, M%NNodes, 'BladeShape%AirfoilCoords', ErrStat2, ErrMsg2) CALL SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) IF (ErrStat >= AbortErrLev) RETURN ! Chord length and pitch axis location are given by scaling law bladeLength = TwoNorm( M%position(:,tipNode) - M%Position(:,rootNode) ) cylinderLength = TwoNorm( M%Position(:,cylNode) - M%Position(:,rootNode) ) bladeLengthFract = 0.22*bladeLength bladeLengthFract2 = bladeLength-bladeLengthFract != 0.78*bladeLength DO i=1,M%Nnodes posLength = TwoNorm( M%Position(:,i) - M%Position(:,rootNode) ) IF (posLength .LE. bladeLengthFract) THEN ratio = posLength/bladeLengthFract chord = (0.06 + 0.02*ratio)*bladeLength pitchAxis = 0.25 + 0.125*ratio ELSE chord = (0.08 - 0.06*(posLength-bladeLengthFract)/bladeLengthFract2)*bladeLength pitchAxis = 0.375 END IF IF (posLength .LE. cylinderLength) THEN ! create a cylinder for this node chord = chord/2.0_SiKi DO j=1,N ! normalized x,y coordinates for airfoil x = yc(j) y = xc(j) - 0.5 angle = ATAN2( y, x) ! x,y coordinates for cylinder BladeShape%AirfoilCoords(1,j,i) = chord*COS(angle) ! x (note that "chord" is really representing chord/2 here) BladeShape%AirfoilCoords(2,j,i) = chord*SIN(angle) ! y (note that "chord" is really representing chord/2 here) END DO ELSE ! create an airfoil for this node DO j=1,N ! normalized x,y coordinates for airfoil, assuming an upwind turbine x = yc(j) y = xc(j) - pitchAxis ! x,y coordinates for airfoil BladeShape%AirfoilCoords(1,j,i) = chord*x BladeShape%AirfoilCoords(2,j,i) = chord*y END DO END IF END DO ! nodes on mesh END SUBROUTINE SetVTKDefaultBladeParams !---------------------------------------------------------------------------------------------------------------------------------- !> This routine writes the ground or seabed reference surface information in VTK format. !! see VTK file information format for XML, here: http://www.vtk.org/wp-content/uploads/2015/04/file-formats.pdf SUBROUTINE WrVTK_Ground ( RefPoint, HalfLengths, FileRootName, ErrStat, ErrMsg ) REAL(SiKi), INTENT(IN) :: RefPoint(3) !< reference point (plane will be created around it) REAL(SiKi), INTENT(IN) :: HalfLengths(2) !< half of the X-Y lengths of plane surrounding RefPoint CHARACTER(*), INTENT(IN) :: FileRootName !< Name of the file to write the output in (excluding extension) INTEGER(IntKi), INTENT(OUT) :: ErrStat !< Indicates whether an error occurred (see NWTC_Library) CHARACTER(*), INTENT(OUT) :: ErrMsg !< Error message associated with the ErrStat ! local variables INTEGER(IntKi) :: Un ! fortran unit number INTEGER(IntKi) :: ix ! loop counters CHARACTER(1024) :: FileName INTEGER(IntKi), parameter :: NumberOfPoints = 4 INTEGER(IntKi), parameter :: NumberOfLines = 0 INTEGER(IntKi), parameter :: NumberOfPolys = 1 INTEGER(IntKi) :: ErrStat2 CHARACTER(ErrMsgLen) :: ErrMsg2 CHARACTER(*),PARAMETER :: RoutineName = 'WrVTK_Ground' ErrStat = ErrID_None ErrMsg = "" !................................................................. ! write the data that potentially changes each time step: !................................................................. ! PolyData (.vtp) - Serial vtkPolyData (unstructured) file FileName = TRIM(FileRootName)//'.vtp' call WrVTK_header( FileName, NumberOfPoints, NumberOfLines, NumberOfPolys, Un, ErrStat2, ErrMsg2 ) call SetErrStat(ErrStat2,ErrMsg2,ErrStat,ErrMsg,RoutineName) if (ErrStat >= AbortErrLev) return ! points (nodes, augmented with NumSegments): WRITE(Un,'(A)') ' <Points>' WRITE(Un,'(A)') ' <DataArray type="Float32" NumberOfComponents="3" format="ascii">' WRITE(Un,VTK_AryFmt) RefPoint(1) + HalfLengths(1) , RefPoint(2) + HalfLengths(2), RefPoint(3) WRITE(Un,VTK_AryFmt) RefPoint(1) + HalfLengths(1) , RefPoint(2) - HalfLengths(2), RefPoint(3) WRITE(Un,VTK_AryFmt) RefPoint(1) - HalfLengths(1) , RefPoint(2) - HalfLengths(2), RefPoint(3) WRITE(Un,VTK_AryFmt) RefPoint(1) - HalfLengths(1) , RefPoint(2) + HalfLengths(2), RefPoint(3) WRITE(Un,'(A)') ' </DataArray>' WRITE(Un,'(A)') ' </Points>' WRITE(Un,'(A)') ' <Polys>' WRITE(Un,'(A)') ' <DataArray type="Int32" Name="connectivity" format="ascii">' WRITE(Un,'('//trim(num2lstr(NumberOfPoints))//'(i7))') (ix, ix=0,NumberOfPoints-1) WRITE(Un,'(A)') ' </DataArray>' WRITE(Un,'(A)') ' <DataArray type="Int32" Name="offsets" format="ascii">' WRITE(Un,'(i7)') NumberOfPoints WRITE(Un,'(A)') ' </DataArray>' WRITE(Un,'(A)') ' </Polys>' call WrVTK_footer( Un ) END SUBROUTINE WrVTK_Ground !---------------------------------------------------------------------------------------------------------------------------------- !> This subroutine sets up the information needed to initialize AeroDyn, then initializes AeroDyn SUBROUTINE AD_SetInitInput(InitInData_AD14, InitOutData_ED, y_ED, p_FAST, ErrStat, ErrMsg) ! Passed variables: TYPE(AD14_InitInputType),INTENT(INOUT) :: InitInData_AD14 !< The initialization input to AeroDyn14 TYPE(ED_InitOutputType), INTENT(IN) :: InitOutData_ED !< The initialization output from structural dynamics module TYPE(ED_OutputType), INTENT(IN) :: y_ED !< The outputs of the structural dynamics module (meshes with position/RefOrientation set) TYPE(FAST_ParameterType),INTENT(IN) :: p_FAST !< The parameters of the glue code INTEGER(IntKi) :: ErrStat !< Error status of the operation CHARACTER(*) :: ErrMsg !< Error message if ErrStat /= ErrID_None ! Local variables !TYPE(AD_InitOptions) :: ADOptions ! Options for AeroDyn INTEGER :: K ErrStat = ErrID_None ErrMsg = "" ! Set up the AeroDyn parameters InitInData_AD14%ADFileName = p_FAST%AeroFile InitInData_AD14%OutRootName = p_FAST%OutFileRoot InitInData_AD14%WrSumFile = p_FAST%SumPrint InitInData_AD14%NumBl = InitOutData_ED%NumBl InitInData_AD14%UseDWM = p_FAST%UseDWM InitInData_AD14%DWM%IfW%InputFileName = p_FAST%InflowFile ! Hub position and orientation (relative here, but does not need to be) InitInData_AD14%TurbineComponents%Hub%Position(:) = y_ED%HubPtMotion14%Position(:,1) - y_ED%HubPtMotion14%Position(:,1) ! bjj: was 0; mesh was changed by adding p_ED%HubHt to 3rd component InitInData_AD14%TurbineComponents%Hub%Orientation(:,:) = y_ED%HubPtMotion14%RefOrientation(:,:,1) InitInData_AD14%TurbineComponents%Hub%TranslationVel = 0.0_ReKi ! bjj: we don't need this field InitInData_AD14%TurbineComponents%Hub%RotationVel = 0.0_ReKi ! bjj: we don't need this field ! Blade root position and orientation (relative here, but does not need to be) IF (.NOT. ALLOCATED( InitInData_AD14%TurbineComponents%Blade ) ) THEN ALLOCATE( InitInData_AD14%TurbineComponents%Blade( InitInData_AD14%NumBl ), STAT = ErrStat ) IF ( ErrStat /= 0 ) THEN ErrStat = ErrID_Fatal ErrMsg = ' Error allocating space for InitInData_AD%TurbineComponents%Blade.' RETURN ELSE ErrStat = ErrID_None !reset to ErrID_None, just in case ErrID_None /= 0 END IF END IF DO K=1, InitInData_AD14%NumBl InitInData_AD14%TurbineComponents%Blade(K)%Position = y_ED%BladeRootMotion14%Position(:,K) InitInData_AD14%TurbineComponents%Blade(K)%Orientation = y_ED%BladeRootMotion14%RefOrientation(:,:,K) InitInData_AD14%TurbineComponents%Blade(K)%TranslationVel = 0.0_ReKi ! bjj: we don't need this field InitInData_AD14%TurbineComponents%Blade(K)%RotationVel = 0.0_ReKi ! bjj: we don't need this field END DO ! Blade length IF (p_FAST%CompElast == Module_ED) THEN ! note, we can't get here if we're using BeamDyn.... InitInData_AD14%TurbineComponents%BladeLength = InitOutData_ED%BladeLength END IF ! Tower mesh ( here only because we currently need line2 meshes to contain the same nodes/elements ) InitInData_AD14%NumTwrNodes = y_ED%TowerLn2Mesh%NNodes - 2 IF (.NOT. ALLOCATED( InitInData_AD14%TwrNodeLocs ) ) THEN ALLOCATE( InitInData_AD14%TwrNodeLocs( 3, InitInData_AD14%NumTwrNodes ), STAT = ErrStat ) IF ( ErrStat /= 0 ) THEN ErrStat = ErrID_Fatal ErrMsg = ' Error allocating space for InitInData_AD%TwrNodeLocs.' RETURN ELSE ErrStat = ErrID_None END IF END IF IF ( InitInData_AD14%NumTwrNodes > 0 ) THEN InitInData_AD14%TwrNodeLocs = y_ED%TowerLn2Mesh%Position(:,1:InitInData_AD14%NumTwrNodes) ! ED has extra nodes at beginning and top and bottom of tower END IF ! hub height InitInData_AD14%HubHt = InitOutData_ED%HubHt RETURN END SUBROUTINE AD_SetInitInput !---------------------------------------------------------------------------------------------------------------------------------- !> This routine sets the number of subcycles (substeps) for modules at initialization, checking to make sure that their requested !! time step is valid. SUBROUTINE SetModuleSubstepTime(ModuleID, p_FAST, y_FAST, ErrStat, ErrMsg) INTEGER(IntKi), INTENT(IN ) :: ModuleID !< ID of the module to check time step and set TYPE(FAST_ParameterType), INTENT(INOUT) :: p_FAST !< Parameters for the glue code TYPE(FAST_OutputFileType),INTENT(IN ) :: y_FAST !< Output variables for the glue code INTEGER(IntKi), INTENT( OUT) :: ErrStat !< Error status of the operation CHARACTER(*), INTENT( OUT) :: ErrMsg !< Error message if ErrStat /= ErrID_None ErrStat = ErrID_None ErrMsg = "" IF ( EqualRealNos( p_FAST%dt_module( ModuleID ), p_FAST%dt ) ) THEN p_FAST%n_substeps(ModuleID) = 1 ELSE IF ( p_FAST%dt_module( ModuleID ) > p_FAST%dt ) THEN ErrStat = ErrID_Fatal ErrMsg = "The "//TRIM(y_FAST%Module_Ver(ModuleID)%Name)//" module time step ("//& TRIM(Num2LStr(p_FAST%dt_module( ModuleID )))// & " s) cannot be larger than FAST time step ("//TRIM(Num2LStr(p_FAST%dt))//" s)." ELSE ! calculate the number of subcycles: p_FAST%n_substeps(ModuleID) = NINT( p_FAST%dt / p_FAST%dt_module( ModuleID ) ) ! let's make sure THE module DT is an exact integer divisor of the global (FAST) time step: IF ( .NOT. EqualRealNos( p_FAST%dt, p_FAST%dt_module( ModuleID ) * p_FAST%n_substeps(ModuleID) ) ) THEN ErrStat = ErrID_Fatal ErrMsg = "The "//TRIM(y_FAST%Module_Ver(ModuleID)%Name)//" module time step ("//& TRIM(Num2LStr(p_FAST%dt_module( ModuleID )))// & " s) must be an integer divisor of the FAST time step ("//TRIM(Num2LStr(p_FAST%dt))//" s)." END IF END IF END IF RETURN END SUBROUTINE SetModuleSubstepTime !---------------------------------------------------------------------------------------------------------------------------------- !> This writes data to the FAST summary file. SUBROUTINE FAST_WrSum( p_FAST, y_FAST, MeshMapData, ErrStat, ErrMsg ) TYPE(FAST_ParameterType), INTENT(IN) :: p_FAST !< Glue-code simulation parameters TYPE(FAST_OutputFileType),INTENT(INOUT) :: y_FAST !< Glue-code simulation outputs (changes value of UnSum) TYPE(FAST_ModuleMapType), INTENT(IN) :: MeshMapData !< Data for mapping between modules INTEGER(IntKi), INTENT(OUT) :: ErrStat !< Error status (level) CHARACTER(*), INTENT(OUT) :: ErrMsg !< Message describing error reported in ErrStat ! local variables REAL(ReKi) :: TmpRate ! temporary rate for vtk output INTEGER(IntKi) :: I ! temporary counter INTEGER(IntKi) :: J ! temporary counter INTEGER(IntKi) :: Module_Number ! loop counter through the modules CHARACTER(200) :: Fmt ! temporary format string CHARACTER(200) :: DescStr ! temporary string to write text CHARACTER(*), PARAMETER :: NotUsedTxt = " [not called]" ! text written if a module is not called CHARACTER(ChanLen) :: ChanTxt(2) ! temp strings to help with formatting with unknown ChanLen size ! Get a unit number and open the file: CALL GetNewUnit( y_FAST%UnSum, ErrStat, ErrMsg ) IF ( ErrStat >= AbortErrLev ) RETURN CALL OpenFOutFile ( y_FAST%UnSum, TRIM(p_FAST%OutFileRoot)//'.sum', ErrStat, ErrMsg ) IF ( ErrStat >= AbortErrLev ) RETURN ! Add some file information: !.......................... Module Versions ..................................................... !bjj: modules in this list are ordered by the order they are specified in the FAST input file WRITE (y_FAST%UnSum,'(/A)') 'FAST Summary File' WRITE (y_FAST%UnSum,'(/A)') TRIM( y_FAST%FileDescLines(1) ) WRITE (y_FAST%UnSum,'(2X,A)' ) 'compiled with' Fmt = '(4x,A)' WRITE (y_FAST%UnSum,Fmt) TRIM( GetNVD( NWTC_Ver ) ) WRITE (y_FAST%UnSum,Fmt) TRIM( GetNVD( y_FAST%Module_Ver( Module_ED ) ) ) DescStr = GetNVD( y_FAST%Module_Ver( Module_BD ) ) IF ( p_FAST%CompElast /= Module_BD ) DescStr = TRIM(DescStr)//NotUsedTxt WRITE (y_FAST%UnSum,Fmt) TRIM( DescStr ) DescStr = GetNVD( y_FAST%Module_Ver( Module_IfW ) ) IF ( p_FAST%CompInflow /= Module_IfW ) DescStr = TRIM(DescStr)//NotUsedTxt WRITE (y_FAST%UnSum,Fmt) TRIM( DescStr ) ! I'm not going to write the openfoam module info to the summary file !DescStr = GetNVD( y_FAST%Module_Ver( Module_OpFM ) ) !IF ( p_FAST%CompInflow /= Module_OpFM ) DescStr = TRIM(DescStr)//NotUsedTxt !WRITE (y_FAST%UnSum,Fmt) TRIM( DescStr ) DescStr = GetNVD( y_FAST%Module_Ver( Module_AD14 ) ) IF ( p_FAST%CompAero /= Module_AD14 ) DescStr = TRIM(DescStr)//NotUsedTxt WRITE (y_FAST%UnSum,Fmt) TRIM( DescStr ) DescStr = GetNVD( y_FAST%Module_Ver( Module_AD ) ) IF ( p_FAST%CompAero /= Module_AD ) DescStr = TRIM(DescStr)//NotUsedTxt WRITE (y_FAST%UnSum,Fmt) TRIM( DescStr ) DescStr = GetNVD( y_FAST%Module_Ver( Module_SrvD ) ) IF ( p_FAST%CompServo /= Module_SrvD ) DescStr = TRIM(DescStr)//NotUsedTxt WRITE (y_FAST%UnSum,Fmt) TRIM( DescStr ) DescStr = GetNVD( y_FAST%Module_Ver( Module_HD ) ) IF ( p_FAST%CompHydro /= Module_HD ) DescStr = TRIM(DescStr)//NotUsedTxt WRITE (y_FAST%UnSum,Fmt) TRIM( DescStr ) DescStr = GetNVD( y_FAST%Module_Ver( Module_SD ) ) IF ( p_FAST%CompSub /= Module_SD ) DescStr = TRIM(DescStr)//NotUsedTxt WRITE (y_FAST%UnSum,Fmt) TRIM( DescStr ) DescStr = GetNVD( y_FAST%Module_Ver( Module_ExtPtfm ) ) IF ( p_FAST%CompSub /= Module_ExtPtfm ) DescStr = TRIM(DescStr)//NotUsedTxt WRITE (y_FAST%UnSum,Fmt) TRIM( DescStr ) DescStr = GetNVD( y_FAST%Module_Ver( Module_MAP ) ) IF ( p_FAST%CompMooring /= Module_MAP ) DescStr = TRIM(DescStr)//NotUsedTxt WRITE (y_FAST%UnSum,Fmt) TRIM( DescStr ) DescStr = GetNVD( y_FAST%Module_Ver( Module_FEAM ) ) IF ( p_FAST%CompMooring /= Module_FEAM ) DescStr = TRIM(DescStr)//NotUsedTxt WRITE (y_FAST%UnSum,Fmt) TRIM( DescStr ) DescStr = GetNVD( y_FAST%Module_Ver( Module_MD ) ) IF ( p_FAST%CompMooring /= Module_MD ) DescStr = TRIM(DescStr)//NotUsedTxt WRITE (y_FAST%UnSum,Fmt) TRIM( DescStr ) DescStr = GetNVD( y_FAST%Module_Ver( Module_Orca ) ) IF ( p_FAST%CompMooring /= Module_Orca ) DescStr = TRIM(DescStr)//NotUsedTxt WRITE (y_FAST%UnSum,Fmt) TRIM( DescStr ) DescStr = GetNVD( y_FAST%Module_Ver( Module_IceF ) ) IF ( p_FAST%CompIce /= Module_IceF ) DescStr = TRIM(DescStr)//NotUsedTxt WRITE (y_FAST%UnSum,Fmt) TRIM( DescStr ) DescStr = GetNVD( y_FAST%Module_Ver( Module_IceD ) ) IF ( p_FAST%CompIce /= Module_IceD ) DescStr = TRIM(DescStr)//NotUsedTxt WRITE (y_FAST%UnSum,Fmt) TRIM( DescStr ) !.......................... Information from FAST input File ...................................... ! OTHER information we could print here: ! current working directory ! output file root name ! output file time step ! output file format (text/binary) ! coupling method SELECT CASE ( p_FAST%TurbineType ) CASE ( Type_LandBased ) DescStr = 'Modeling a land-based turbine' CASE ( Type_Offshore_Fixed ) DescStr = 'Modeling a fixed-bottom offshore turbine' CASE ( Type_Offshore_Floating ) DescStr = 'Modeling a floating offshore turbine' CASE DEFAULT ! This should never happen DescStr="" END SELECT WRITE(y_FAST%UnSum,'(//A)') TRIM(DescStr) WRITE (y_FAST%UnSum,'(A)' ) 'Description from the FAST input file: ' WRITE (y_FAST%UnSum,'(2X,A)') TRIM(p_FAST%FTitle) !.......................... Requested Features ................................................... SELECT CASE ( p_FAST%InterpOrder ) CASE (0) DescStr = ' (nearest neighbor)' CASE (1) DescStr = ' (linear)' CASE (2) DescStr = ' (quadratic)' CASE DEFAULT DescStr = ' ( )' END SELECT WRITE(y_FAST%UnSum,'(/A,I1,A)' ) 'Interpolation order for input/output time histories: ', p_FAST%InterpOrder, TRIM(DescStr) WRITE(y_FAST%UnSum,'( A,I2)' ) 'Number of correction iterations: ', p_FAST%NumCrctn !.......................... Information About Coupling ................................................... IF ( ALLOCATED( MeshMapData%Jacobian_Opt1 ) ) then ! we're using option 1 IF ( p_FAST%CompSub /= Module_None .OR. p_FAST%CompElast == Module_BD .OR. p_FAST%CompMooring == Module_Orca ) THEN ! SubDyn-BeamDyn-HydroDyn-ElastoDyn-ExtPtfm DescStr = 'ElastoDyn, SubDyn, HydroDyn, OrcaFlex, ExtPtfm_MCKF, and/or BeamDyn' ELSE ! IF ( p_FAST%CompHydro == Module_HD ) THEN DescStr = "ElastoDyn to HydroDyn" END IF WRITE(y_FAST%UnSum,'( A,I6)' ) 'Number of rows in Jacobian matrix used for coupling '//TRIM(DescStr)//': ', & SIZE(MeshMapData%Jacobian_Opt1, 1) END IF !.......................... Time step information: ................................................... WRITE (y_FAST%UnSum,'(//,2X,A)') " Requested Time Steps " WRITE (y_FAST%UnSum, '(2X,A)') "-------------------------------------------------" Fmt = '(2X,A17,2X,A15,2X,A13)' WRITE (y_FAST%UnSum, Fmt ) "Component ", "Time Step (s) ", "Subcycles (-)" WRITE (y_FAST%UnSum, Fmt ) "-----------------", "---------------", "-------------" Fmt = '(2X,A17,2X,'//TRIM(p_FAST%OutFmt)//',:,T37,2X,I8,:,A)' WRITE (y_FAST%UnSum, Fmt ) "FAST (glue code) ", p_FAST%DT DO Module_Number=1,NumModules IF (p_FAST%ModuleInitialized(Module_Number)) THEN WRITE (y_FAST%UnSum, Fmt ) y_FAST%Module_Ver(Module_Number)%Name, p_FAST%DT_module(Module_Number), p_FAST%n_substeps(Module_Number) END IF END DO IF ( p_FAST%n_DT_Out == 1_IntKi ) THEN WRITE (y_FAST%UnSum, Fmt ) "FAST output files", p_FAST%DT_out, 1_IntKi ! we'll write "1" instead of "1^-1" ELSE WRITE (y_FAST%UnSum, Fmt ) "FAST output files", p_FAST%DT_out, p_FAST%n_DT_Out,"^-1" END IF IF (p_FAST%WrVTK == VTK_Animate) THEN TmpRate = p_FAST%DT*p_FAST%n_VTKTime IF ( p_FAST%n_VTKTime == 1_IntKi ) THEN WRITE (y_FAST%UnSum, Fmt ) "VTK output files ", p_FAST%DT, 1_IntKi ! we'll write "1" instead of "1^-1" ELSE WRITE (y_FAST%UnSum, Fmt ) "VTK output files ", TmpRate, p_FAST%n_VTKTime,"^-1" END IF ELSE TmpRate = p_FAST%VTK_fps END IF ! bjj: fix this; possibly add names of which files will be generated? IF (p_FAST%WrVTK == VTK_Animate .or. p_FAST%WrVTK == VTK_ModeShapes) THEN Fmt = '(2X,A17,2X,'//TRIM(p_FAST%OutFmt)//',:,T37,:,A)' WRITE (y_FAST%UnSum,'(//,2X,A)') " Requested Visualization Output" WRITE (y_FAST%UnSum, '(2X,A)') "-------------------------------------------------" WRITE (y_FAST%UnSum, Fmt ) "Frame rate", 1.0_DbKi/TmpRate, " fps" END IF !.......................... Requested Output Channels ............................................ WRITE (y_FAST%UnSum,'(//,2X,A)') " Requested Channels in FAST Output File(s) " WRITE (y_FAST%UnSum, '(2X,A)') "--------------------------------------------" Fmt = '(2X,A6,2(2X,A'//TRIM(num2lstr(ChanLen))//'),2X,A)' ChanTxt(1) = 'Name' ChanTxt(2) = 'Units' WRITE (y_FAST%UnSum, Fmt ) "Number", ChanTxt, "Generated by" ChanTxt = '--------------------' !this ought to be sufficiently long WRITE (y_FAST%UnSum, Fmt ) "------", ChanTxt, "------------" Fmt = '(4X,I4,2(2X,A'//TRIM(num2lstr(ChanLen))//'),2X,A)' I = 1 WRITE (y_FAST%UnSum, Fmt ) I, y_FAST%ChannelNames(I), y_FAST%ChannelUnits(I), TRIM(FAST_Ver%Name) DO Module_Number = 1,NumModules DO J = 1,y_FAST%numOuts( Module_Number ) I = I + 1 WRITE (y_FAST%UnSum, Fmt ) I, y_FAST%ChannelNames(I), y_FAST%ChannelUnits(I), TRIM(y_FAST%Module_Ver( Module_Number )%Name) END DO END DO !.......................... End of Summary File ............................................ ! bjj: note that I'm not closing the summary file here, though at the present time we don't write to this file again. ! In the future, we may want to write additional information to this file during the simulation. ! bjj 4/21/2015: closing the file now because of restart. If it needs to be open later, we can change it again. CLOSE( y_FAST%UnSum ) y_FAST%UnSum = -1 END SUBROUTINE FAST_WrSum !---------------------------------------------------------------------------------------------------------------------------------- !++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ! TIME-STEP SOLVER ROUTINES (includes initialization after first call to calcOutput at t=0) !++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ !> Routine that calls FAST_Solution0 for one instance of a Turbine data structure. This is a separate subroutine so that the FAST !! driver programs do not need to change or operate on the individual module level. SUBROUTINE FAST_Solution0_T(Turbine, ErrStat, ErrMsg) TYPE(FAST_TurbineType), INTENT(INOUT) :: Turbine !< all data for one instance of a turbine INTEGER(IntKi), INTENT( OUT) :: ErrStat !< Error status of the operation CHARACTER(*), INTENT( OUT) :: ErrMsg !< Error message if ErrStat /= ErrID_None CALL FAST_Solution0(Turbine%p_FAST, Turbine%y_FAST, Turbine%m_FAST, & Turbine%ED, Turbine%BD, Turbine%SrvD, Turbine%AD14, Turbine%AD, Turbine%IfW, Turbine%OpFM, & Turbine%HD, Turbine%SD, Turbine%ExtPtfm, Turbine%MAP, Turbine%FEAM, Turbine%MD, Turbine%Orca, & Turbine%IceF, Turbine%IceD, Turbine%MeshMapData, ErrStat, ErrMsg ) END SUBROUTINE FAST_Solution0_T !---------------------------------------------------------------------------------------------------------------------------------- !> Routine that calls CalcOutput for the first time of the simulation (at t=0). After the initial solve, data arrays are initialized. SUBROUTINE FAST_Solution0(p_FAST, y_FAST, m_FAST, ED, BD, SrvD, AD14, AD, IfW, OpFM, HD, SD, ExtPtfm, & MAPp, FEAM, MD, Orca, IceF, IceD, MeshMapData, ErrStat, ErrMsg ) TYPE(FAST_ParameterType), INTENT(IN ) :: p_FAST !< Parameters for the glue code TYPE(FAST_OutputFileType),INTENT(INOUT) :: y_FAST !< Output variables for the glue code TYPE(FAST_MiscVarType), INTENT(INOUT) :: m_FAST !< Miscellaneous variables TYPE(ElastoDyn_Data), INTENT(INOUT) :: ED !< ElastoDyn data TYPE(BeamDyn_Data), INTENT(INOUT) :: BD !< BeamDyn data TYPE(ServoDyn_Data), INTENT(INOUT) :: SrvD !< ServoDyn data TYPE(AeroDyn14_Data), INTENT(INOUT) :: AD14 !< AeroDyn14 data TYPE(AeroDyn_Data), INTENT(INOUT) :: AD !< AeroDyn data TYPE(InflowWind_Data), INTENT(INOUT) :: IfW !< InflowWind data TYPE(OpenFOAM_Data), INTENT(INOUT) :: OpFM !< OpenFOAM data TYPE(HydroDyn_Data), INTENT(INOUT) :: HD !< HydroDyn data TYPE(SubDyn_Data), INTENT(INOUT) :: SD !< SubDyn data TYPE(ExtPtfm_Data), INTENT(INOUT) :: ExtPtfm !< ExtPtfm_MCKF data TYPE(MAP_Data), INTENT(INOUT) :: MAPp !< MAP data TYPE(FEAMooring_Data), INTENT(INOUT) :: FEAM !< FEAMooring data TYPE(MoorDyn_Data), INTENT(INOUT) :: MD !< Data for the MoorDyn module TYPE(OrcaFlex_Data), INTENT(INOUT) :: Orca !< OrcaFlex interface data TYPE(IceFloe_Data), INTENT(INOUT) :: IceF !< IceFloe data TYPE(IceDyn_Data), INTENT(INOUT) :: IceD !< All the IceDyn data used in time-step loop TYPE(FAST_ModuleMapType), INTENT(INOUT) :: MeshMapData !< Data for mapping between modules INTEGER(IntKi), INTENT( OUT) :: ErrStat !< Error status of the operation CHARACTER(*), INTENT( OUT) :: ErrMsg !< Error message if ErrStat /= ErrID_None ! local variables INTEGER(IntKi), PARAMETER :: n_t_global = -1 ! loop counter INTEGER(IntKi), PARAMETER :: n_t_global_next = 0 ! loop counter REAL(DbKi) :: t_initial ! next simulation time (t_global_next) INTEGER(IntKi) :: ErrStat2 CHARACTER(ErrMsgLen) :: ErrMsg2 CHARACTER(*), PARAMETER :: RoutineName = 'FAST_Solution0' !NOTE: m_FAST%t_global is t_initial in this routine ErrStat = ErrID_None ErrMsg = "" t_initial = m_FAST%t_global ! which is used in place of t_global_next y_FAST%WriteThisStep = NeedWriteOutput(n_t_global_next, t_initial, p_FAST) IF (p_FAST%WrSttsTime) then CALL SimStatus_FirstTime( m_FAST%TiLstPrn, m_FAST%PrevClockTime, m_FAST%SimStrtTime, m_FAST%UsrTime2, t_initial, p_FAST%TMax, p_FAST%TDesc ) END IF ! Solve input-output relations; this section of code corresponds to Eq. (35) in Gasmi et al. (2013) ! This code will be specific to the underlying modules ! the initial ServoDyn and IfW/Lidar inputs from Simulink: IF ( p_FAST%CompServo == Module_SrvD ) CALL SrvD_SetExternalInputs( p_FAST, m_FAST, SrvD%Input(1) ) IF ( p_FAST%CompInflow == Module_IfW ) CALL IfW_SetExternalInputs( IfW%p, m_FAST, ED%y, IfW%Input(1) ) CALL CalcOutputs_And_SolveForInputs( n_t_global, t_initial, STATE_CURR, m_FAST%calcJacobian, m_FAST%NextJacCalcTime, & p_FAST, m_FAST, y_FAST%WriteThisStep, ED, BD, SrvD, AD14, AD, IfW, OpFM, HD, SD, ExtPtfm, & MAPp, FEAM, MD, Orca, IceF, IceD, MeshMapData, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) !---------------------------------------------------------------------------------------- ! Check to see if we should output data this time step: !---------------------------------------------------------------------------------------- CALL WriteOutputToFile(n_t_global_next, t_initial, p_FAST, y_FAST, ED, BD, AD14, AD, IfW, OpFM, HD, SD, ExtPtfm, SrvD, MAPp, FEAM, MD, Orca, IceF, IceD, MeshMapData, ErrStat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) ! turn off VTK output when if (p_FAST%WrVTK == VTK_InitOnly) then ! Write visualization data for initialization (and also note that we're ignoring any errors that occur doing so) call WriteVTK(t_initial, p_FAST, y_FAST, MeshMapData, ED, BD, AD, IfW, OpFM, HD, SD, ExtPtfm, SrvD, MAPp, FEAM, MD, Orca, IceF, IceD) end if !............... ! Copy values of these initial guesses for interpolation/extrapolation and ! initialize predicted states for j_pc loop (use MESH_NEWCOPY here so we can use MESH_UPDATE copy later) !............... ! Initialize Input-Output arrays for interpolation/extrapolation: CALL FAST_InitIOarrays( m_FAST%t_global, p_FAST, y_FAST, m_FAST, ED, BD, SrvD, AD14, AD, IfW, HD, SD, ExtPtfm, & MAPp, FEAM, MD, Orca, IceF, IceD, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) END SUBROUTINE FAST_Solution0 !---------------------------------------------------------------------------------------------------------------------------------- !> This routine initializes the input and output arrays stored for extrapolation. They are initialized after the first input-output solve so that the first !! extrapolations are used with values from the solution, not just initial guesses. It also creates new copies of the state variables, which need to !! be stored for the predictor-corrector loop. SUBROUTINE FAST_InitIOarrays( t_initial, p_FAST, y_FAST, m_FAST, ED, BD, SrvD, AD14, AD, IfW, HD, SD, ExtPtfm, & MAPp, FEAM, MD, Orca, IceF, IceD, ErrStat, ErrMsg ) REAL(DbKi), INTENT(IN ) :: t_initial !< start time of the simulation TYPE(FAST_ParameterType), INTENT(IN ) :: p_FAST !< Parameters for the glue code TYPE(FAST_OutputFileType),INTENT(IN ) :: y_FAST !< Output variables for the glue code TYPE(FAST_MiscVarType), INTENT(IN ) :: m_FAST !< Miscellaneous variables TYPE(ElastoDyn_Data), INTENT(INOUT) :: ED !< ElastoDyn data TYPE(BeamDyn_Data), INTENT(INOUT) :: BD !< BeamDyn data TYPE(ServoDyn_Data), INTENT(INOUT) :: SrvD !< ServoDyn data TYPE(AeroDyn14_Data), INTENT(INOUT) :: AD14 !< AeroDyn v14 data TYPE(AeroDyn_Data), INTENT(INOUT) :: AD !< AeroDyn data TYPE(InflowWind_Data), INTENT(INOUT) :: IfW !< InflowWind data TYPE(HydroDyn_Data), INTENT(INOUT) :: HD !< HydroDyn data TYPE(SubDyn_Data), INTENT(INOUT) :: SD !< SubDyn data TYPE(ExtPtfm_Data), INTENT(INOUT) :: ExtPtfm !< ExtPtfm_MCKF data TYPE(MAP_Data), INTENT(INOUT) :: MAPp !< MAP data TYPE(FEAMooring_Data), INTENT(INOUT) :: FEAM !< FEAMooring data TYPE(MoorDyn_Data), INTENT(INOUT) :: MD !< MoorDyn data TYPE(OrcaFlex_Data), INTENT(INOUT) :: Orca !< OrcaFlex interface data TYPE(IceFloe_Data), INTENT(INOUT) :: IceF !< IceFloe data TYPE(IceDyn_Data), INTENT(INOUT) :: IceD !< All the IceDyn data used in time-step loop INTEGER(IntKi), INTENT( OUT) :: ErrStat !< Error status of the operation CHARACTER(*), INTENT( OUT) :: ErrMsg !< Error message if ErrStat /= ErrID_None ! local variables INTEGER(IntKi) :: i, j, k ! loop counters INTEGER(IntKi) :: ErrStat2 CHARACTER(ErrMsgLen) :: ErrMsg2 CHARACTER(*), PARAMETER :: RoutineName = 'FAST_InitIOarrays' ErrStat = ErrID_None ErrMsg = "" ! We fill ED%InputTimes with negative times, but the ED%Input values are identical for each of those times; this allows ! us to use, e.g., quadratic interpolation that effectively acts as a zeroth-order extrapolation and first-order extrapolation ! for the first and second time steps. (The interpolation order in the ExtrapInput routines are determined as ! order = SIZE(ED%Input) DO j = 1, p_FAST%InterpOrder + 1 ED%InputTimes(j) = t_initial - (j - 1) * p_FAST%dt !ED_OutputTimes(j) = t_initial - (j - 1) * dt END DO DO j = 2, p_FAST%InterpOrder + 1 CALL ED_CopyInput (ED%Input(1), ED%Input(j), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) END DO CALL ED_CopyInput (ED%Input(1), ED%u, MESH_NEWCOPY, Errstat2, ErrMsg2) ! do this to initialize meshes/allocatable arrays for output of ExtrapInterp routine CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) ! Initialize predicted states for j_pc loop: CALL ED_CopyContState (ED%x( STATE_CURR), ED%x( STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL ED_CopyDiscState (ED%xd(STATE_CURR), ED%xd(STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL ED_CopyConstrState (ED%z( STATE_CURR), ED%z( STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL ED_CopyOtherState (ED%OtherSt( STATE_CURR), ED%OtherSt( STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) IF (p_FAST%CompElast == Module_BD ) THEN DO k = 1,p_FAST%nBeams ! Copy values for interpolation/extrapolation: DO j = 1, p_FAST%InterpOrder + 1 BD%InputTimes(j,k) = t_initial - (j - 1) * p_FAST%dt END DO DO j = 2, p_FAST%InterpOrder + 1 CALL BD_CopyInput (BD%Input(1,k), BD%Input(j,k), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) END DO CALL BD_CopyInput (BD%Input(1,k), BD%u(k), MESH_NEWCOPY, Errstat2, ErrMsg2) ! do this to initialize meshes/allocatable arrays for output of ExtrapInterp routine CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) ! Initialize predicted states for j_pc loop: CALL BD_CopyContState (BD%x( k,STATE_CURR), BD%x( k,STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL BD_CopyDiscState (BD%xd(k,STATE_CURR), BD%xd(k,STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL BD_CopyConstrState (BD%z( k,STATE_CURR), BD%z( k,STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL BD_CopyOtherState (BD%OtherSt( k,STATE_CURR), BD%OtherSt( k,STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) END DO ! nBeams END IF ! CompElast IF ( p_FAST%CompServo == Module_SrvD ) THEN ! Initialize Input-Output arrays for interpolation/extrapolation: DO j = 1, p_FAST%InterpOrder + 1 SrvD%InputTimes(j) = t_initial - (j - 1) * p_FAST%dt !SrvD_OutputTimes(j) = t_initial - (j - 1) * dt END DO DO j = 2, p_FAST%InterpOrder + 1 CALL SrvD_CopyInput (SrvD%Input(1), SrvD%Input(j), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) END DO CALL SrvD_CopyInput (SrvD%Input(1), SrvD%u, MESH_NEWCOPY, Errstat2, ErrMsg2) ! do this to initialize meshes/allocatable arrays for output of ExtrapInterp routine CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) ! Initialize predicted states for j_pc loop: CALL SrvD_CopyContState (SrvD%x( STATE_CURR), SrvD%x( STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL SrvD_CopyDiscState (SrvD%xd(STATE_CURR), SrvD%xd(STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL SrvD_CopyConstrState (SrvD%z( STATE_CURR), SrvD%z( STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL SrvD_CopyOtherState( SrvD%OtherSt(STATE_CURR), SrvD%OtherSt(STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) END IF ! CompServo IF ( p_FAST%CompAero == Module_AD14 ) THEN ! Copy values for interpolation/extrapolation: DO j = 1, p_FAST%InterpOrder + 1 AD14%InputTimes(j) = t_initial - (j - 1) * p_FAST%dt END DO DO j = 2, p_FAST%InterpOrder + 1 CALL AD14_CopyInput (AD14%Input(1), AD14%Input(j), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) END DO CALL AD14_CopyInput (AD14%Input(1), AD14%u, MESH_NEWCOPY, Errstat2, ErrMsg2) ! do this to initialize meshes/allocatable arrays for output of ExtrapInterp routine CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) ! Initialize predicted states for j_pc loop: CALL AD14_CopyContState (AD14%x( STATE_CURR), AD14%x( STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL AD14_CopyDiscState (AD14%xd(STATE_CURR), AD14%xd(STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL AD14_CopyConstrState (AD14%z( STATE_CURR), AD14%z( STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL AD14_CopyOtherState( AD14%OtherSt(STATE_CURR), AD14%OtherSt(STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) ELSEIF ( p_FAST%CompAero == Module_AD ) THEN ! Copy values for interpolation/extrapolation: DO j = 1, p_FAST%InterpOrder + 1 AD%InputTimes(j) = t_initial - (j - 1) * p_FAST%dt END DO DO j = 2, p_FAST%InterpOrder + 1 CALL AD_CopyInput (AD%Input(1), AD%Input(j), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) END DO CALL AD_CopyInput (AD%Input(1), AD%u, MESH_NEWCOPY, Errstat2, ErrMsg2) ! do this to initialize meshes/allocatable arrays for output of ExtrapInterp routine CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) ! Initialize predicted states for j_pc loop: CALL AD_CopyContState(AD%x(STATE_CURR), AD%x(STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL AD_CopyDiscState(AD%xd(STATE_CURR), AD%xd(STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL AD_CopyConstrState(AD%z(STATE_CURR), AD%z(STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL AD_CopyOtherState(AD%OtherSt(STATE_CURR), AD%OtherSt(STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) END IF ! CompAero == Module_AD IF ( p_FAST%CompInflow == Module_IfW ) THEN ! Copy values for interpolation/extrapolation: DO j = 1, p_FAST%InterpOrder + 1 IfW%InputTimes(j) = t_initial - (j - 1) * p_FAST%dt !IfW%OutputTimes(i) = t_initial - (j - 1) * dt END DO DO j = 2, p_FAST%InterpOrder + 1 CALL InflowWind_CopyInput (IfW%Input(1), IfW%Input(j), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) END DO CALL InflowWind_CopyInput (IfW%Input(1), IfW%u, MESH_NEWCOPY, Errstat2, ErrMsg2) ! do this to initialize meshes/allocatable arrays for output of ExtrapInterp routine CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) ! Initialize predicted states for j_pc loop: CALL InflowWind_CopyContState (IfW%x( STATE_CURR), IfW%x( STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL InflowWind_CopyDiscState (IfW%xd(STATE_CURR), IfW%xd(STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL InflowWind_CopyConstrState (IfW%z( STATE_CURR), IfW%z( STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL InflowWind_CopyOtherState( IfW%OtherSt(STATE_CURR), IfW%OtherSt(STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) END IF ! CompInflow == Module_IfW IF ( p_FAST%CompHydro == Module_HD ) THEN ! Copy values for interpolation/extrapolation: DO j = 1, p_FAST%InterpOrder + 1 HD%InputTimes(j) = t_initial - (j - 1) * p_FAST%dt !HD_OutputTimes(i) = t_initial - (j - 1) * dt END DO DO j = 2, p_FAST%InterpOrder + 1 CALL HydroDyn_CopyInput (HD%Input(1), HD%Input(j), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) END DO CALL HydroDyn_CopyInput (HD%Input(1), HD%u, MESH_NEWCOPY, Errstat2, ErrMsg2) ! do this to initialize meshes/allocatable arrays for output of ExtrapInterp routine CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) ! Initialize predicted states for j_pc loop: CALL HydroDyn_CopyContState (HD%x( STATE_CURR), HD%x( STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL HydroDyn_CopyDiscState (HD%xd(STATE_CURR), HD%xd(STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL HydroDyn_CopyConstrState (HD%z( STATE_CURR), HD%z( STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL HydroDyn_CopyOtherState( HD%OtherSt(STATE_CURR), HD%OtherSt(STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) END IF !CompHydro IF (p_FAST%CompSub == Module_SD ) THEN ! Copy values for interpolation/extrapolation: DO j = 1, p_FAST%InterpOrder + 1 SD%InputTimes(j) = t_initial - (j - 1) * p_FAST%dt !SD_OutputTimes(i) = t_initial - (j - 1) * dt END DO DO j = 2, p_FAST%InterpOrder + 1 CALL SD_CopyInput (SD%Input(1), SD%Input(j), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) END DO CALL SD_CopyInput (SD%Input(1), SD%u, MESH_NEWCOPY, Errstat2, ErrMsg2) ! do this to initialize meshes/allocatable arrays for output of ExtrapInterp routine CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) ! Initialize predicted states for j_pc loop: CALL SD_CopyContState (SD%x( STATE_CURR), SD%x( STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL SD_CopyDiscState (SD%xd(STATE_CURR), SD%xd(STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL SD_CopyConstrState (SD%z( STATE_CURR), SD%z( STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL SD_CopyOtherState( SD%OtherSt(STATE_CURR), SD%OtherSt(STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) ELSE IF (p_FAST%CompSub == Module_ExtPtfm ) THEN ! Copy values for interpolation/extrapolation: DO j = 1, p_FAST%InterpOrder + 1 ExtPtfm%InputTimes(j) = t_initial - (j - 1) * p_FAST%dt END DO DO j = 2, p_FAST%InterpOrder + 1 CALL ExtPtfm_CopyInput (ExtPtfm%Input(1), ExtPtfm%Input(j), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) END DO CALL ExtPtfm_CopyInput (ExtPtfm%Input(1), ExtPtfm%u, MESH_NEWCOPY, Errstat2, ErrMsg2) ! do this to initialize meshes/allocatable arrays for output of ExtrapInterp routine CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) ! Initialize predicted states for j_pc loop: CALL ExtPtfm_CopyContState (ExtPtfm%x( STATE_CURR), ExtPtfm%x( STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL ExtPtfm_CopyDiscState (ExtPtfm%xd(STATE_CURR), ExtPtfm%xd(STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL ExtPtfm_CopyConstrState (ExtPtfm%z( STATE_CURR), ExtPtfm%z( STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL ExtPtfm_CopyOtherState( ExtPtfm%OtherSt(STATE_CURR), ExtPtfm%OtherSt(STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) END IF ! CompSub IF (p_FAST%CompMooring == Module_MAP) THEN ! Copy values for interpolation/extrapolation: DO j = 1, p_FAST%InterpOrder + 1 MAPp%InputTimes(j) = t_initial - (j - 1) * p_FAST%dt !MAP_OutputTimes(i) = t_initial - (j - 1) * dt END DO DO j = 2, p_FAST%InterpOrder + 1 CALL MAP_CopyInput (MAPp%Input(1), MAPp%Input(j), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) END DO CALL MAP_CopyInput (MAPp%Input(1), MAPp%u, MESH_NEWCOPY, Errstat2, ErrMsg2) ! do this to initialize meshes/allocatable arrays for output of ExtrapInterp routine CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) ! Initialize predicted states for j_pc loop: CALL MAP_CopyContState (MAPp%x( STATE_CURR), MAPp%x( STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL MAP_CopyDiscState (MAPp%xd(STATE_CURR), MAPp%xd(STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL MAP_CopyConstrState (MAPp%z( STATE_CURR), MAPp%z( STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) IF ( p_FAST%n_substeps( MODULE_MAP ) > 1 ) THEN CALL MAP_CopyOtherState( MAPp%OtherSt, MAPp%OtherSt_old, MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) END IF ELSEIF (p_FAST%CompMooring == Module_MD) THEN ! Copy values for interpolation/extrapolation: DO j = 1, p_FAST%InterpOrder + 1 MD%InputTimes(j) = t_initial - (j - 1) * p_FAST%dt !MD_OutputTimes(i) = t_initial - (j - 1) * dt END DO DO j = 2, p_FAST%InterpOrder + 1 CALL MD_CopyInput (MD%Input(1), MD%Input(j), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) END DO CALL MD_CopyInput (MD%Input(1), MD%u, MESH_NEWCOPY, Errstat2, ErrMsg2) ! do this to initialize meshes/allocatable arrays for output of ExtrapInterp routine CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) ! Initialize predicted states for j_pc loop: CALL MD_CopyContState (MD%x( STATE_CURR), MD%x( STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL MD_CopyDiscState (MD%xd(STATE_CURR), MD%xd(STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL MD_CopyConstrState (MD%z( STATE_CURR), MD%z( STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL MD_CopyOtherState( MD%OtherSt(STATE_CURR), MD%OtherSt(STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) ELSEIF (p_FAST%CompMooring == Module_FEAM) THEN ! Copy values for interpolation/extrapolation: DO j = 1, p_FAST%InterpOrder + 1 FEAM%InputTimes(j) = t_initial - (j - 1) * p_FAST%dt !FEAM_OutputTimes(i) = t_initial - (j - 1) * dt END DO DO j = 2, p_FAST%InterpOrder + 1 CALL FEAM_CopyInput (FEAM%Input(1), FEAM%Input(j), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) END DO CALL FEAM_CopyInput (FEAM%Input(1), FEAM%u, MESH_NEWCOPY, Errstat2, ErrMsg2) ! do this to initialize meshes/allocatable arrays for output of ExtrapInterp routine CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) ! Initialize predicted states for j_pc loop: CALL FEAM_CopyContState (FEAM%x( STATE_CURR), FEAM%x( STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL FEAM_CopyDiscState (FEAM%xd(STATE_CURR), FEAM%xd(STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL FEAM_CopyConstrState (FEAM%z( STATE_CURR), FEAM%z( STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL FEAM_CopyOtherState( FEAM%OtherSt(STATE_CURR), FEAM%OtherSt(STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) ELSEIF (p_FAST%CompMooring == Module_Orca) THEN ! Copy values for interpolation/extrapolation: DO j = 1, p_FAST%InterpOrder + 1 Orca%InputTimes(j) = t_initial - (j - 1) * p_FAST%dt END DO DO j = 2, p_FAST%InterpOrder + 1 CALL Orca_CopyInput (Orca%Input(1), Orca%Input(j), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) END DO CALL Orca_CopyInput (Orca%Input(1), Orca%u, MESH_NEWCOPY, Errstat2, ErrMsg2) ! do this to initialize meshes/allocatable arrays for output of ExtrapInterp routine CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) ! Initialize predicted states for j_pc loop: CALL Orca_CopyContState (Orca%x( STATE_CURR), Orca%x( STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL Orca_CopyDiscState (Orca%xd(STATE_CURR), Orca%xd(STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL Orca_CopyConstrState (Orca%z( STATE_CURR), Orca%z( STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL Orca_CopyOtherState( Orca%OtherSt(STATE_CURR), Orca%OtherSt(STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) END IF ! CompMooring IF (p_FAST%CompIce == Module_IceF ) THEN ! Copy values for interpolation/extrapolation: DO j = 1, p_FAST%InterpOrder + 1 IceF%InputTimes(j) = t_initial - (j - 1) * p_FAST%dt !IceF_OutputTimes(i) = t_initial - (j - 1) * dt END DO DO j = 2, p_FAST%InterpOrder + 1 CALL IceFloe_CopyInput (IceF%Input(1), IceF%Input(j), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) END DO CALL IceFloe_CopyInput (IceF%Input(1), IceF%u, MESH_NEWCOPY, Errstat2, ErrMsg2) ! do this to initialize meshes/allocatable arrays for output of ExtrapInterp routine CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) ! Initialize predicted states for j_pc loop: CALL IceFloe_CopyContState (IceF%x( STATE_CURR), IceF%x( STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL IceFloe_CopyDiscState (IceF%xd(STATE_CURR), IceF%xd(STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL IceFloe_CopyConstrState (IceF%z( STATE_CURR), IceF%z( STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL IceFloe_CopyOtherState( IceF%OtherSt(STATE_CURR), IceF%OtherSt(STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) ELSEIF (p_FAST%CompIce == Module_IceD ) THEN DO i = 1,p_FAST%numIceLegs ! Copy values for interpolation/extrapolation: DO j = 1, p_FAST%InterpOrder + 1 IceD%InputTimes(j,i) = t_initial - (j - 1) * p_FAST%dt !IceD%OutputTimes(j,i) = t_initial - (j - 1) * dt END DO DO j = 2, p_FAST%InterpOrder + 1 CALL IceD_CopyInput (IceD%Input(1,i), IceD%Input(j,i), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) END DO CALL IceD_CopyInput (IceD%Input(1,i), IceD%u(i), MESH_NEWCOPY, Errstat2, ErrMsg2) ! do this to initialize meshes/allocatable arrays for output of ExtrapInterp routine CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) ! Initialize predicted states for j_pc loop: CALL IceD_CopyContState (IceD%x( i,STATE_CURR), IceD%x( i,STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL IceD_CopyDiscState (IceD%xd(i,STATE_CURR), IceD%xd(i,STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL IceD_CopyConstrState (IceD%z( i,STATE_CURR), IceD%z( i,STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL IceD_CopyOtherState( IceD%OtherSt(i,STATE_CURR), IceD%OtherSt(i,STATE_PRED), MESH_NEWCOPY, Errstat2, ErrMsg2) CALL SetErrStat( Errstat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) END DO ! numIceLegs END IF ! CompIce END SUBROUTINE FAST_InitIOarrays !---------------------------------------------------------------------------------------------------------------------------------- !> Routine that calls FAST_Solution for one instance of a Turbine data structure. This is a separate subroutine so that the FAST !! driver programs do not need to change or operate on the individual module level. SUBROUTINE FAST_Solution_T(t_initial, n_t_global, Turbine, ErrStat, ErrMsg ) REAL(DbKi), INTENT(IN ) :: t_initial !< initial time INTEGER(IntKi), INTENT(IN ) :: n_t_global !< loop counter TYPE(FAST_TurbineType), INTENT(INOUT) :: Turbine !< all data for one instance of a turbine INTEGER(IntKi), INTENT( OUT) :: ErrStat !< Error status of the operation CHARACTER(*), INTENT( OUT) :: ErrMsg !< Error message if ErrStat /= ErrID_None CALL FAST_Solution(t_initial, n_t_global, Turbine%p_FAST, Turbine%y_FAST, Turbine%m_FAST, & Turbine%ED, Turbine%BD, Turbine%SrvD, Turbine%AD14, Turbine%AD, Turbine%IfW, Turbine%OpFM, & Turbine%HD, Turbine%SD, Turbine%ExtPtfm, Turbine%MAP, Turbine%FEAM, Turbine%MD, Turbine%Orca, & Turbine%IceF, Turbine%IceD, Turbine%MeshMapData, ErrStat, ErrMsg ) END SUBROUTINE FAST_Solution_T !---------------------------------------------------------------------------------------------------------------------------------- !> This routine takes data from n_t_global and gets values at n_t_global + 1 SUBROUTINE FAST_Solution(t_initial, n_t_global, p_FAST, y_FAST, m_FAST, ED, BD, SrvD, AD14, AD, IfW, OpFM, HD, SD, ExtPtfm, & MAPp, FEAM, MD, Orca, IceF, IceD, MeshMapData, ErrStat, ErrMsg ) REAL(DbKi), INTENT(IN ) :: t_initial !< initial time INTEGER(IntKi), INTENT(IN ) :: n_t_global !< loop counter TYPE(FAST_ParameterType), INTENT(IN ) :: p_FAST !< Parameters for the glue code TYPE(FAST_OutputFileType),INTENT(INOUT) :: y_FAST !< Output variables for the glue code TYPE(FAST_MiscVarType), INTENT(INOUT) :: m_FAST !< Miscellaneous variables TYPE(ElastoDyn_Data), INTENT(INOUT) :: ED !< ElastoDyn data TYPE(BeamDyn_Data), INTENT(INOUT) :: BD !< BeamDyn data TYPE(ServoDyn_Data), INTENT(INOUT) :: SrvD !< ServoDyn data TYPE(AeroDyn14_Data), INTENT(INOUT) :: AD14 !< AeroDyn14 data TYPE(AeroDyn_Data), INTENT(INOUT) :: AD !< AeroDyn data TYPE(InflowWind_Data), INTENT(INOUT) :: IfW !< InflowWind data TYPE(OpenFOAM_Data), INTENT(INOUT) :: OpFM !< OpenFOAM data TYPE(HydroDyn_Data), INTENT(INOUT) :: HD !< HydroDyn data TYPE(SubDyn_Data), INTENT(INOUT) :: SD !< SubDyn data TYPE(ExtPtfm_Data), INTENT(INOUT) :: ExtPtfm !< ExtPtfm_MCKF data TYPE(MAP_Data), INTENT(INOUT) :: MAPp !< MAP data TYPE(FEAMooring_Data), INTENT(INOUT) :: FEAM !< FEAMooring data TYPE(MoorDyn_Data), INTENT(INOUT) :: MD !< Data for the MoorDyn module TYPE(OrcaFlex_Data), INTENT(INOUT) :: Orca !< OrcaFlex interface data TYPE(IceFloe_Data), INTENT(INOUT) :: IceF !< IceFloe data TYPE(IceDyn_Data), INTENT(INOUT) :: IceD !< All the IceDyn data used in time-step loop TYPE(FAST_ModuleMapType), INTENT(INOUT) :: MeshMapData !< Data for mapping between modules INTEGER(IntKi), INTENT( OUT) :: ErrStat !< Error status of the operation CHARACTER(*), INTENT( OUT) :: ErrMsg !< Error message if ErrStat /= ErrID_None ! local variables REAL(DbKi) :: t_global_next ! next simulation time (m_FAST%t_global + p_FAST%dt) INTEGER(IntKi) :: n_t_global_next ! n_t_global + 1 INTEGER(IntKi) :: j_pc ! predictor-corrector loop counter INTEGER(IntKi) :: NumCorrections ! number of corrections for this time step INTEGER(IntKi), parameter :: MaxCorrections = 20 ! maximum number of corrections allowed LOGICAL :: WriteThisStep ! Whether WriteOutput values will be printed INTEGER(IntKi) :: I, k ! generic loop counters !REAL(ReKi) :: ControlInputGuess ! value of controller inputs INTEGER(IntKi) :: ErrStat2 CHARACTER(ErrMsgLen) :: ErrMsg2 CHARACTER(*), PARAMETER :: RoutineName = 'FAST_Solution' ErrStat = ErrID_None ErrMsg = "" n_t_global_next = n_t_global+1 t_global_next = t_initial + n_t_global_next*p_FAST%DT ! = m_FAST%t_global + p_FAST%dt y_FAST%WriteThisStep = NeedWriteOutput(n_t_global_next, t_global_next, p_FAST) !! determine if the Jacobian should be calculated this time IF ( m_FAST%calcJacobian ) THEN ! this was true (possibly at initialization), so we'll advance the time for the next calculation of the Jacobian if (p_FAST%CompMooring == Module_Orca .and. n_t_global < 5) then m_FAST%NextJacCalcTime = m_FAST%t_global + p_FAST%DT ! the jacobian calculated with OrcaFlex at t=0 is incorrect, but is okay on the 2nd step (it's not okay for OrcaFlex version 10, so I increased this to 5) else m_FAST%NextJacCalcTime = m_FAST%t_global + p_FAST%DT_UJac end if END IF ! set number of corrections to be used for this time step: IF ( p_FAST%CompElast == Module_BD ) THEN ! BD accelerations have fewer spikes with these corrections on the first several time steps if (n_t_global > 2) then ! this 2 should probably be related to p_FAST%InterpOrder NumCorrections = p_FAST%NumCrctn elseif (n_t_global == 0) then NumCorrections = max(p_FAST%NumCrctn,16) else NumCorrections = max(p_FAST%NumCrctn,1) end if ELSE NumCorrections = p_FAST%NumCrctn END IF ! the ServoDyn inputs from Simulink are for t, not t+dt, so we're going to overwrite the inputs from ! the previous step before we extrapolate these inputs: IF ( p_FAST%CompServo == Module_SrvD ) CALL SrvD_SetExternalInputs( p_FAST, m_FAST, SrvD%Input(1) ) !++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ !! ## Step 1.a: Extrapolate Inputs !! !! gives predicted values at t+dt !++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ CALL FAST_ExtrapInterpMods( t_global_next, p_FAST, m_FAST, ED, BD, SrvD, AD14, AD, IfW, HD, SD, ExtPtfm, & MAPp, FEAM, MD, Orca, IceF, IceD, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) !! predictor-corrector loop: j_pc = 0 do while (j_pc <= NumCorrections) WriteThisStep = y_FAST%WriteThisStep .AND. j_pc==NumCorrections !++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ !! ## Step 1.b: Advance states (yield state and constraint values at t_global_next) !! !! STATE_CURR values of x, xd, z, and OtherSt contain values at m_FAST%t_global; !! STATE_PRED values contain values at t_global_next. !++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ CALL FAST_AdvanceStates( t_initial, n_t_global, p_FAST, m_FAST, ED, BD, SrvD, AD14, AD, IfW, OpFM, HD, SD, ExtPtfm, & MAPp, FEAM, MD, Orca, IceF, IceD, MeshMapData, ErrStat2, ErrMsg2, WriteThisStep ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) IF (ErrStat >= AbortErrLev) RETURN !++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ !! ## Step 1.c: Input-Output Solve !++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ! save predicted inputs for comparison with corrected value later !IF (p_FAST%CheckHSSBrTrqC) THEN ! ControlInputGuess = ED%Input(1)%HSSBrTrqC !END IF CALL CalcOutputs_And_SolveForInputs( n_t_global, t_global_next, STATE_PRED, m_FAST%calcJacobian, m_FAST%NextJacCalcTime, & p_FAST, m_FAST, WriteThisStep, ED, BD, SrvD, AD14, AD, IfW, OpFM, HD, SD, ExtPtfm, MAPp, FEAM, MD, Orca, IceF, IceD, MeshMapData, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) IF (ErrStat >= AbortErrLev) RETURN !++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ !! ## Step 2: Correct (continue in loop) !++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ j_pc = j_pc + 1 ! ! Check if the predicted inputs were significantly different than the corrected inputs ! ! (values before and after CalcOutputs_And_SolveForInputs) !if (j_pc > NumCorrections) then ! ! !if (p_FAST%CheckHSSBrTrqC) then ! ! if ( abs(ControlInputGuess - ED%Input(1)%HSSBrTrqC) > 50.0_ReKi ) then ! I randomly picked 50 N-m ! ! NumCorrections = min(p_FAST%NumCrctn + 1, MaxCorrections) ! ! ! print *, 'correction:', t_global_next, NumCorrections ! ! cycle ! ! end if ! !end if ! ! ! check pitch position input to structural code (not implemented, yet) !end if enddo ! j_pc !++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ !! ## Step 3: Save all final variables (advance to next time) !++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ !---------------------------------------------------------------------------------------- !! copy the final predicted states from step t_global_next to actual states for that step !---------------------------------------------------------------------------------------- ! ElastoDyn: copy final predictions to actual states CALL ED_CopyContState (ED%x( STATE_PRED), ED%x( STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL ED_CopyDiscState (ED%xd(STATE_PRED), ED%xd(STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL ED_CopyConstrState (ED%z( STATE_PRED), ED%z( STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL ED_CopyOtherState (ED%OtherSt( STATE_PRED), ED%OtherSt( STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) ! BeamDyn: copy final predictions to actual states IF ( p_FAST%CompElast == Module_BD ) THEN DO k=1,p_FAST%nBeams CALL BD_CopyContState (BD%x( k,STATE_PRED), BD%x( k,STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL BD_CopyDiscState (BD%xd(k,STATE_PRED), BD%xd(k,STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL BD_CopyConstrState (BD%z( k,STATE_PRED), BD%z( k,STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL BD_CopyOtherState (BD%OtherSt( k,STATE_PRED), BD%OtherSt( k,STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) END DO END IF ! AeroDyn: copy final predictions to actual states; copy current outputs to next IF ( p_FAST%CompAero == Module_AD14 ) THEN CALL AD14_CopyContState (AD14%x( STATE_PRED), AD14%x( STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL AD14_CopyDiscState (AD14%xd(STATE_PRED), AD14%xd(STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL AD14_CopyConstrState (AD14%z( STATE_PRED), AD14%z( STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL AD14_CopyOtherState (AD14%OtherSt(STATE_PRED), AD14%OtherSt(STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) ELSEIF ( p_FAST%CompAero == Module_AD ) THEN CALL AD_CopyContState (AD%x( STATE_PRED), AD%x( STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL AD_CopyDiscState (AD%xd(STATE_PRED), AD%xd(STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL AD_CopyConstrState (AD%z( STATE_PRED), AD%z( STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL AD_CopyOtherState (AD%OtherSt(STATE_PRED), AD%OtherSt(STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) END IF ! InflowWind: copy final predictions to actual states; copy current outputs to next IF ( p_FAST%CompInflow == Module_IfW ) THEN CALL InflowWind_CopyContState (IfW%x( STATE_PRED), IfW%x( STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL InflowWind_CopyDiscState (IfW%xd(STATE_PRED), IfW%xd(STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL InflowWind_CopyConstrState (IfW%z( STATE_PRED), IfW%z( STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL InflowWind_CopyOtherState (IfW%OtherSt( STATE_PRED), IfW%OtherSt( STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) END IF ! ServoDyn: copy final predictions to actual states; copy current outputs to next IF ( p_FAST%CompServo == Module_SrvD ) THEN CALL SrvD_CopyContState (SrvD%x( STATE_PRED), SrvD%x( STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL SrvD_CopyDiscState (SrvD%xd(STATE_PRED), SrvD%xd(STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL SrvD_CopyConstrState (SrvD%z( STATE_PRED), SrvD%z( STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL SrvD_CopyOtherState (SrvD%OtherSt( STATE_PRED), SrvD%OtherSt( STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) END IF ! HydroDyn: copy final predictions to actual states IF ( p_FAST%CompHydro == Module_HD ) THEN CALL HydroDyn_CopyContState (HD%x( STATE_PRED), HD%x( STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL HydroDyn_CopyDiscState (HD%xd(STATE_PRED), HD%xd(STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL HydroDyn_CopyConstrState (HD%z( STATE_PRED), HD%z( STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL HydroDyn_CopyOtherState (HD%OtherSt(STATE_PRED), HD%OtherSt(STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) END IF ! SubDyn: copy final predictions to actual states IF ( p_FAST%CompSub == Module_SD ) THEN CALL SD_CopyContState (SD%x( STATE_PRED), SD%x( STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL SD_CopyDiscState (SD%xd(STATE_PRED), SD%xd(STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL SD_CopyConstrState (SD%z( STATE_PRED), SD%z( STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL SD_CopyOtherState (SD%OtherSt(STATE_PRED), SD%OtherSt(STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) ELSE IF ( p_FAST%CompSub == Module_ExtPtfm ) THEN CALL ExtPtfm_CopyContState (ExtPtfm%x( STATE_PRED), ExtPtfm%x( STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL ExtPtfm_CopyDiscState (ExtPtfm%xd(STATE_PRED), ExtPtfm%xd(STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL ExtPtfm_CopyConstrState (ExtPtfm%z( STATE_PRED), ExtPtfm%z( STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL ExtPtfm_CopyOtherState (ExtPtfm%OtherSt(STATE_PRED), ExtPtfm%OtherSt(STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) END IF ! MAP: copy final predictions to actual states IF (p_FAST%CompMooring == Module_MAP) THEN CALL MAP_CopyContState (MAPp%x( STATE_PRED), MAPp%x( STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL MAP_CopyDiscState (MAPp%xd(STATE_PRED), MAPp%xd(STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL MAP_CopyConstrState (MAPp%z( STATE_PRED), MAPp%z( STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) !CALL MAP_CopyOtherState (MAPp%OtherSt(STATE_PRED), MAPp%OtherSt(STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) ! CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) ELSEIF (p_FAST%CompMooring == Module_MD) THEN CALL MD_CopyContState (MD%x( STATE_PRED), MD%x( STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL MD_CopyDiscState (MD%xd(STATE_PRED), MD%xd(STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL MD_CopyConstrState (MD%z( STATE_PRED), MD%z( STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL MD_CopyOtherState (MD%OtherSt(STATE_PRED), MD%OtherSt(STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) ELSEIF (p_FAST%CompMooring == Module_FEAM) THEN CALL FEAM_CopyContState (FEAM%x( STATE_PRED), FEAM%x( STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL FEAM_CopyDiscState (FEAM%xd(STATE_PRED), FEAM%xd(STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL FEAM_CopyConstrState (FEAM%z( STATE_PRED), FEAM%z( STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL FEAM_CopyOtherState (FEAM%OtherSt( STATE_PRED), FEAM%OtherSt( STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) ELSEIF (p_FAST%CompMooring == Module_Orca) THEN CALL Orca_CopyContState (Orca%x( STATE_PRED), Orca%x( STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL Orca_CopyDiscState (Orca%xd(STATE_PRED), Orca%xd(STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL Orca_CopyConstrState (Orca%z( STATE_PRED), Orca%z( STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL Orca_CopyOtherState (Orca%OtherSt( STATE_PRED), Orca%OtherSt( STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) END IF ! IceFloe: copy final predictions to actual states IF ( p_FAST%CompIce == Module_IceF ) THEN CALL IceFloe_CopyContState (IceF%x( STATE_PRED), IceF%x( STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL IceFloe_CopyDiscState (IceF%xd(STATE_PRED), IceF%xd(STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL IceFloe_CopyConstrState (IceF%z( STATE_PRED), IceF%z( STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL IceFloe_CopyOtherState (IceF%OtherSt(STATE_PRED), IceF%OtherSt(STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) ELSEIF ( p_FAST%CompIce == Module_IceD ) THEN DO i=1,p_FAST%numIceLegs CALL IceD_CopyContState (IceD%x( i,STATE_PRED), IceD%x( i,STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL IceD_CopyDiscState (IceD%xd(i,STATE_PRED), IceD%xd(i,STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL IceD_CopyConstrState (IceD%z( i,STATE_PRED), IceD%z( i,STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL IceD_CopyOtherState (IceD%OtherSt( i,STATE_PRED), IceD%OtherSt( i,STATE_CURR), MESH_UPDATECOPY, Errstat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) END DO END IF !++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ !! We've advanced everything to the next time step: !++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ !! update the global time m_FAST%t_global = t_global_next !---------------------------------------------------------------------------------------- !! Check to see if we should output data this time step: !---------------------------------------------------------------------------------------- CALL WriteOutputToFile(n_t_global_next, t_global_next, p_FAST, y_FAST, ED, BD, AD14, AD, IfW, OpFM, HD, SD, ExtPtfm, & SrvD, MAPp, FEAM, MD, Orca, IceF, IceD, MeshMapData, ErrStat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) !---------------------------------------------------------------------------------------- !! Display simulation status every SttsTime-seconds (i.e., n_SttsTime steps): !---------------------------------------------------------------------------------------- IF (p_FAST%WrSttsTime) then IF ( MOD( n_t_global_next, p_FAST%n_SttsTime ) == 0 ) THEN CALL SimStatus( m_FAST%TiLstPrn, m_FAST%PrevClockTime, m_FAST%t_global, p_FAST%TMax, p_FAST%TDesc ) ENDIF ENDIF END SUBROUTINE FAST_Solution !---------------------------------------------------------------------------------------------------------------------------------- ! ROUTINES TO OUTPUT WRITE DATA TO FILE AT EACH REQUSTED TIME STEP !---------------------------------------------------------------------------------------------------------------------------------- FUNCTION NeedWriteOutput(n_t_global, t_global, p_FAST) INTEGER(IntKi), INTENT(IN ) :: n_t_global !< Current global time step REAL(DbKi), INTENT(IN ) :: t_global !< Current global time TYPE(FAST_ParameterType), INTENT(IN ) :: p_FAST !< Parameters for the glue code LOGICAL :: NeedWriteOutput !< Function result; if true, WriteOutput values are needed on this time step IF ( t_global >= p_FAST%TStart ) THEN ! note that if TStart isn't an multiple of DT_out, we will not necessarially start output to the file at TStart NeedWriteOutput = MOD( n_t_global, p_FAST%n_DT_Out ) == 0 ELSE NeedWriteOutput = .FALSE. END IF END FUNCTION NeedWriteOutput !---------------------------------------------------------------------------------------------------------------------------------- !> This routine determines if it's time to write to the output files--based on a previous call to fast_subs::needwriteoutput--, and !! calls the routine to write to the files with the output data. It should be called after all the output solves for a given time !! have been completed, and assumes y_FAST\%WriteThisStep has been set. SUBROUTINE WriteOutputToFile(n_t_global, t_global, p_FAST, y_FAST, ED, BD, AD14, AD, IfW, OpFM, HD, SD, ExtPtfm, & SrvD, MAPp, FEAM, MD, Orca, IceF, IceD, MeshMapData, ErrStat, ErrMsg) !............................................................................................................................... INTEGER(IntKi), INTENT(IN ) :: n_t_global !< Current global time step REAL(DbKi), INTENT(IN ) :: t_global !< Current global time TYPE(FAST_ParameterType), INTENT(IN ) :: p_FAST !< Parameters for the glue code TYPE(FAST_OutputFileType),INTENT(INOUT) :: y_FAST !< Output variables for the glue code TYPE(ElastoDyn_Data), INTENT(IN ) :: ED !< ElastoDyn data TYPE(BeamDyn_Data), INTENT(IN ) :: BD !< BeamDyn data TYPE(ServoDyn_Data), INTENT(IN ) :: SrvD !< ServoDyn data TYPE(AeroDyn14_Data), INTENT(IN ) :: AD14 !< AeroDyn14 data TYPE(AeroDyn_Data), INTENT(IN ) :: AD !< AeroDyn data TYPE(InflowWind_Data), INTENT(IN ) :: IfW !< InflowWind data TYPE(OpenFOAM_Data), INTENT(IN ) :: OpFM !< OpenFOAM data TYPE(HydroDyn_Data), INTENT(IN ) :: HD !< HydroDyn data TYPE(SubDyn_Data), INTENT(IN ) :: SD !< SubDyn data TYPE(ExtPtfm_Data), INTENT(IN ) :: ExtPtfm !< ExtPtfm_MCKF data TYPE(MAP_Data), INTENT(IN ) :: MAPp !< MAP data TYPE(FEAMooring_Data), INTENT(IN ) :: FEAM !< FEAMooring data TYPE(MoorDyn_Data), INTENT(IN ) :: MD !< MoorDyn data TYPE(OrcaFlex_Data), INTENT(IN ) :: Orca !< OrcaFlex interface data TYPE(IceFloe_Data), INTENT(IN ) :: IceF !< IceFloe data TYPE(IceDyn_Data), INTENT(IN ) :: IceD !< All the IceDyn data used in time-step loop TYPE(FAST_ModuleMapType), INTENT(IN ) :: MeshMapData !< Data for mapping between modules INTEGER(IntKi), INTENT( OUT) :: ErrStat !< Error status of the operation CHARACTER(*), INTENT( OUT) :: ErrMsg !< Error message if ErrStat /= ErrID_None CHARACTER(*), PARAMETER :: RoutineName = 'WriteOutputToFile' ErrStat = ErrID_None ErrMsg = "" ! Write time-series channel data !y_FAST%WriteThisStep = NeedWriteOutput(n_t_global, t_global, p_FAST) IF ( y_FAST%WriteThisStep ) THEN ! Generate glue-code output file CALL WrOutputLine( t_global, p_FAST, y_FAST, IfW%y%WriteOutput, OpFM%y%WriteOutput, ED%y%WriteOutput, & AD%y%WriteOutput, SrvD%y%WriteOutput, HD%y%WriteOutput, SD%y%WriteOutput, ExtPtfm%y%WriteOutput, MAPp%y%WriteOutput, & FEAM%y%WriteOutput, MD%y%WriteOutput, Orca%y%WriteOutput, IceF%y%WriteOutput, IceD%y, BD%y, ErrStat, ErrMsg ) ENDIF ! Write visualization data (and also note that we're ignoring any errors that occur doing so) IF ( p_FAST%WrVTK == VTK_Animate ) THEN IF ( MOD( n_t_global, p_FAST%n_VTKTime ) == 0 ) THEN call WriteVTK(t_global, p_FAST, y_FAST, MeshMapData, ED, BD, AD, IfW, OpFM, HD, SD, ExtPtfm, SrvD, MAPp, FEAM, MD, Orca, IceF, IceD) END IF END IF END SUBROUTINE WriteOutputToFile !---------------------------------------------------------------------------------------------------------------------------------- !> This routine writes the module output to the primary output file(s). SUBROUTINE WrOutputLine( t, p_FAST, y_FAST, IfWOutput, OpFMOutput, EDOutput, ADOutput, SrvDOutput, HDOutput, SDOutput, ExtPtfmOutput,& MAPOutput, FEAMOutput, MDOutput, OrcaOutput, IceFOutput, y_IceD, y_BD, ErrStat, ErrMsg) IMPLICIT NONE ! Passed variables REAL(DbKi), INTENT(IN) :: t !< Current simulation time, in seconds TYPE(FAST_ParameterType), INTENT(IN) :: p_FAST !< Glue-code simulation parameters TYPE(FAST_OutputFileType),INTENT(INOUT) :: y_FAST !< Glue-code simulation outputs REAL(ReKi), INTENT(IN) :: IfWOutput (:) !< InflowWind WriteOutput values REAL(ReKi), INTENT(IN) :: OpFMOutput (:) !< OpenFOAM WriteOutput values REAL(ReKi), INTENT(IN) :: EDOutput (:) !< ElastoDyn WriteOutput values REAL(ReKi), INTENT(IN) :: ADOutput (:) !< AeroDyn WriteOutput values REAL(ReKi), INTENT(IN) :: SrvDOutput (:) !< ServoDyn WriteOutput values REAL(ReKi), INTENT(IN) :: HDOutput (:) !< HydroDyn WriteOutput values REAL(ReKi), INTENT(IN) :: SDOutput (:) !< SubDyn WriteOutput values REAL(ReKi), INTENT(IN) :: ExtPtfmOutput (:) !< ExtPtfm_MCKF WriteOutput values REAL(ReKi), INTENT(IN) :: MAPOutput (:) !< MAP WriteOutput values REAL(ReKi), INTENT(IN) :: FEAMOutput (:) !< FEAMooring WriteOutput values REAL(ReKi), INTENT(IN) :: MDOutput (:) !< MoorDyn WriteOutput values REAL(ReKi), INTENT(IN) :: OrcaOutput (:) !< OrcaFlex interface WriteOutput values REAL(ReKi), INTENT(IN) :: IceFOutput (:) !< IceFloe WriteOutput values TYPE(IceD_OutputType), INTENT(IN) :: y_IceD (:) !< IceDyn outputs (WriteOutput values are subset) TYPE(BD_OutputType), INTENT(IN) :: y_BD (:) !< BeamDyn outputs (WriteOutput values are subset) INTEGER(IntKi), INTENT(OUT) :: ErrStat !< Error status CHARACTER(*), INTENT(OUT) :: ErrMsg !< Error message ! Local variables. CHARACTER(200) :: Frmt ! A string to hold a format specifier CHARACTER(p_FAST%TChanLen) :: TmpStr ! temporary string to print the time output as text REAL(ReKi) :: OutputAry(SIZE(y_FAST%ChannelNames)-1) ErrStat = ErrID_None ErrMsg = '' CALL FillOutputAry(p_FAST, y_FAST, IfWOutput, OpFMOutput, EDOutput, ADOutput, SrvDOutput, HDOutput, SDOutput, ExtPtfmOutput, & MAPOutput, FEAMOutput, MDOutput, OrcaOutput, IceFOutput, y_IceD, y_BD, OutputAry) IF (p_FAST%WrTxtOutFile) THEN ! Write one line of tabular output: ! Frmt = '(F8.3,'//TRIM(Num2LStr(p%NumOuts))//'(:,A,'//TRIM( p%OutFmt )//'))' Frmt = '"'//p_FAST%Delim//'"'//p_FAST%OutFmt ! format for array elements from individual modules ! time WRITE( TmpStr, '('//trim(p_FAST%OutFmt_t)//')' ) t CALL WrFileNR( y_FAST%UnOu, TmpStr ) ! write the individual module output (convert to SiKi if necessary, so that we don't need to print so many digits in the exponent) CALL WrNumAryFileNR ( y_FAST%UnOu, REAL(OutputAry,SiKi), Frmt, ErrStat, ErrMsg ) !IF ( ErrStat >= AbortErrLev ) RETURN ! write a new line (advance to the next line) WRITE (y_FAST%UnOu,'()') END IF IF (p_FAST%WrBinOutFile) THEN ! Write data to array for binary output file IF ( y_FAST%n_Out == y_FAST%NOutSteps ) THEN ErrStat = ErrID_Warn ErrMsg = 'Not all data could be written to the binary output file.' !CALL ProgWarn( 'Not all data could be written to the binary output file.' ) !this really would only happen if we have an error somewhere else, right? !otherwise, we could allocate a new, larger array and move existing data ELSE y_FAST%n_Out = y_FAST%n_Out + 1 ! store time data IF ( y_FAST%n_Out == 1_IntKi .OR. p_FAST%WrBinMod == FileFmtID_WithTime ) THEN y_FAST%TimeData(y_FAST%n_Out) = t ! Time associated with these outputs END IF ! store individual module data y_FAST%AllOutData(:, y_FAST%n_Out) = OutputAry END IF END IF RETURN END SUBROUTINE WrOutputLine !---------------------------------------------------------------------------------------------------------------------------------- !> Routine that calls FillOutputAry for one instance of a Turbine data structure. This is a separate subroutine so that the FAST !! driver programs do not need to change or operate on the individual module level. (Called from Simulink interface.) SUBROUTINE FillOutputAry_T(Turbine, Outputs) TYPE(FAST_TurbineType), INTENT(IN ) :: Turbine !< all data for one instance of a turbine REAL(ReKi), INTENT( OUT) :: Outputs(:) !< single array of output CALL FillOutputAry(Turbine%p_FAST, Turbine%y_FAST, Turbine%IfW%y%WriteOutput, Turbine%OpFM%y%WriteOutput, & Turbine%ED%y%WriteOutput, Turbine%AD%y%WriteOutput, Turbine%SrvD%y%WriteOutput, & Turbine%HD%y%WriteOutput, Turbine%SD%y%WriteOutput, Turbine%ExtPtfm%y%WriteOutput, Turbine%MAP%y%WriteOutput, & Turbine%FEAM%y%WriteOutput, Turbine%MD%y%WriteOutput, Turbine%Orca%y%WriteOutput, & Turbine%IceF%y%WriteOutput, Turbine%IceD%y, Turbine%BD%y, Outputs) END SUBROUTINE FillOutputAry_T !---------------------------------------------------------------------------------------------------------------------------------- !> This routine concatenates all of the WriteOutput values from the module Output into one array to be written to the FAST !! output file. SUBROUTINE FillOutputAry(p_FAST, y_FAST, IfWOutput, OpFMOutput, EDOutput, ADOutput, SrvDOutput, HDOutput, SDOutput, ExtPtfmOutput, & MAPOutput, FEAMOutput, MDOutput, OrcaOutput, IceFOutput, y_IceD, y_BD, OutputAry) TYPE(FAST_ParameterType), INTENT(IN) :: p_FAST !< Glue-code simulation parameters TYPE(FAST_OutputFileType),INTENT(IN) :: y_FAST !< Glue-code simulation outputs REAL(ReKi), INTENT(IN) :: IfWOutput (:) !< InflowWind WriteOutput values REAL(ReKi), INTENT(IN) :: OpFMOutput (:) !< OpenFOAM WriteOutput values REAL(ReKi), INTENT(IN) :: EDOutput (:) !< ElastoDyn WriteOutput values REAL(ReKi), INTENT(IN) :: ADOutput (:) !< AeroDyn WriteOutput values REAL(ReKi), INTENT(IN) :: SrvDOutput (:) !< ServoDyn WriteOutput values REAL(ReKi), INTENT(IN) :: HDOutput (:) !< HydroDyn WriteOutput values REAL(ReKi), INTENT(IN) :: SDOutput (:) !< SubDyn WriteOutput values REAL(ReKi), INTENT(IN) :: ExtPtfmOutput (:) !< ExtPtfm_MCKF WriteOutput values REAL(ReKi), INTENT(IN) :: MAPOutput (:) !< MAP WriteOutput values REAL(ReKi), INTENT(IN) :: FEAMOutput (:) !< FEAMooring WriteOutput values REAL(ReKi), INTENT(IN) :: MDOutput (:) !< MoorDyn WriteOutput values REAL(ReKi), INTENT(IN) :: OrcaOutput (:) !< OrcaFlex interface WriteOutput values REAL(ReKi), INTENT(IN) :: IceFOutput (:) !< IceFloe WriteOutput values TYPE(IceD_OutputType), INTENT(IN) :: y_IceD (:) !< IceDyn outputs (WriteOutput values are subset) TYPE(BD_OutputType), INTENT(IN) :: y_BD (:) !< BeamDyn outputs (WriteOutput values are subset) REAL(ReKi), INTENT(OUT) :: OutputAry(:) !< single array of output INTEGER(IntKi) :: i ! loop counter INTEGER(IntKi) :: indxLast ! The index of the last row value to be written to AllOutData for this time step (column). INTEGER(IntKi) :: indxNext ! The index of the next row value to be written to AllOutData for this time step (column). ! store individual module data into one array for output indxLast = 0 indxNext = 1 IF ( y_FAST%numOuts(Module_IfW) > 0 ) THEN indxLast = indxNext + SIZE(IfWOutput) - 1 OutputAry(indxNext:indxLast) = IfWOutput indxNext = IndxLast + 1 ELSEIF ( y_FAST%numOuts(Module_OpFM) > 0 ) THEN indxLast = indxNext + SIZE(OpFMOutput) - 1 OutputAry(indxNext:indxLast) = OpFMOutput indxNext = IndxLast + 1 END IF IF ( y_FAST%numOuts(Module_ED) > 0 ) THEN indxLast = indxNext + SIZE(EDOutput) - 1 OutputAry(indxNext:indxLast) = EDOutput indxNext = IndxLast + 1 END IF IF ( y_FAST%numOuts(Module_BD) > 0 ) THEN do i=1,SIZE(y_BD) indxLast = indxNext + SIZE(y_BD(i)%WriteOutput) - 1 OutputAry(indxNext:indxLast) = y_BD(i)%WriteOutput indxNext = IndxLast + 1 end do END IF IF ( y_FAST%numOuts(Module_AD) > 0 ) THEN indxLast = indxNext + SIZE(ADOutput) - 1 OutputAry(indxNext:indxLast) = ADOutput indxNext = IndxLast + 1 END IF IF ( y_FAST%numOuts(Module_SrvD) > 0 ) THEN indxLast = indxNext + SIZE(SrvDOutput) - 1 OutputAry(indxNext:indxLast) = SrvDOutput indxNext = IndxLast + 1 END IF IF ( y_FAST%numOuts(Module_HD) > 0 ) THEN indxLast = indxNext + SIZE(HDOutput) - 1 OutputAry(indxNext:indxLast) = HDOutput indxNext = IndxLast + 1 END IF IF ( y_FAST%numOuts(Module_SD) > 0 ) THEN indxLast = indxNext + SIZE(SDOutput) - 1 OutputAry(indxNext:indxLast) = SDOutput indxNext = IndxLast + 1 ELSE IF ( y_FAST%numOuts(Module_ExtPtfm) > 0 ) THEN indxLast = indxNext + SIZE(ExtPtfmOutput) - 1 OutputAry(indxNext:indxLast) = ExtPtfmOutput indxNext = IndxLast + 1 END IF IF ( y_FAST%numOuts(Module_MAP) > 0 ) THEN indxLast = indxNext + SIZE(MAPOutput) - 1 OutputAry(indxNext:indxLast) = MAPOutput indxNext = IndxLast + 1 ELSEIF ( y_FAST%numOuts(Module_MD) > 0 ) THEN indxLast = indxNext + SIZE(MDOutput) - 1 OutputAry(indxNext:indxLast) = MDOutput indxNext = IndxLast + 1 ELSEIF ( y_FAST%numOuts(Module_FEAM) > 0 ) THEN indxLast = indxNext + SIZE(FEAMOutput) - 1 OutputAry(indxNext:indxLast) = FEAMOutput indxNext = IndxLast + 1 ELSEIF ( y_FAST%numOuts(Module_Orca) > 0 ) THEN indxLast = indxNext + SIZE(OrcaOutput) - 1 OutputAry(indxNext:indxLast) = OrcaOutput indxNext = IndxLast + 1 END IF IF ( y_FAST%numOuts(Module_IceF) > 0 ) THEN indxLast = indxNext + SIZE(IceFOutput) - 1 OutputAry(indxNext:indxLast) = IceFOutput indxNext = IndxLast + 1 ELSEIF ( y_FAST%numOuts(Module_IceD) > 0 ) THEN DO i=1,p_FAST%numIceLegs indxLast = indxNext + SIZE(y_IceD(i)%WriteOutput) - 1 OutputAry(indxNext:indxLast) = y_IceD(i)%WriteOutput indxNext = IndxLast + 1 END DO END IF END SUBROUTINE FillOutputAry !---------------------------------------------------------------------------------------------------------------------------------- SUBROUTINE WriteVTK(t_global, p_FAST, y_FAST, MeshMapData, ED, BD, AD, IfW, OpFM, HD, SD, ExtPtfm, SrvD, MAPp, FEAM, MD, Orca, IceF, IceD) REAL(DbKi), INTENT(IN ) :: t_global !< Current global time TYPE(FAST_ParameterType), INTENT(IN ) :: p_FAST !< Parameters for the glue code TYPE(FAST_OutputFileType),INTENT(INOUT) :: y_FAST !< Output variables for the glue code (only because we're updating VTK_LastWaveIndx) TYPE(FAST_ModuleMapType), INTENT(IN ) :: MeshMapData !< Data for mapping between modules TYPE(ElastoDyn_Data), INTENT(IN ) :: ED !< ElastoDyn data TYPE(BeamDyn_Data), INTENT(IN ) :: BD !< BeamDyn data TYPE(ServoDyn_Data), INTENT(IN ) :: SrvD !< ServoDyn data TYPE(AeroDyn_Data), INTENT(IN ) :: AD !< AeroDyn data TYPE(InflowWind_Data), INTENT(IN ) :: IfW !< InflowWind data TYPE(OpenFOAM_Data), INTENT(IN ) :: OpFM !< OpenFOAM data TYPE(HydroDyn_Data), INTENT(IN ) :: HD !< HydroDyn data TYPE(SubDyn_Data), INTENT(IN ) :: SD !< SubDyn data TYPE(ExtPtfm_Data), INTENT(IN ) :: ExtPtfm !< ExtPtfm_MCKF data TYPE(MAP_Data), INTENT(IN ) :: MAPp !< MAP data TYPE(FEAMooring_Data), INTENT(IN ) :: FEAM !< FEAMooring data TYPE(MoorDyn_Data), INTENT(IN ) :: MD !< MoorDyn data TYPE(OrcaFlex_Data), INTENT(IN ) :: Orca !< OrcaFlex interface data TYPE(IceFloe_Data), INTENT(IN ) :: IceF !< IceFloe data TYPE(IceDyn_Data), INTENT(IN ) :: IceD !< All the IceDyn data used in time-step loop INTEGER(IntKi) :: ErrStat2 CHARACTER(ErrMsgLen) :: ErrMSg2 CHARACTER(*), PARAMETER :: RoutineName = 'WriteVTK' IF ( p_FAST%VTK_Type == VTK_Surf ) THEN CALL WrVTK_Surfaces(t_global, p_FAST, y_FAST, MeshMapData, ED, BD, AD, IfW, OpFM, HD, SD, SrvD, MAPp, FEAM, MD, Orca, IceF, IceD) ELSE IF ( p_FAST%VTK_Type == VTK_Basic ) THEN CALL WrVTK_BasicMeshes(p_FAST, y_FAST, MeshMapData, ED, BD, AD, IfW, OpFM, HD, SD, SrvD, MAPp, FEAM, MD, Orca, IceF, IceD) ELSE IF ( p_FAST%VTK_Type == VTK_All ) THEN CALL WrVTK_AllMeshes(p_FAST, y_FAST, MeshMapData, ED, BD, AD, IfW, OpFM, HD, SD, ExtPtfm, SrvD, MAPp, FEAM, MD, Orca, IceF, IceD) ELSE IF (p_FAST%VTK_Type==VTK_Old) THEN CALL WriteInputMeshesToFile( ED%Input(1), AD%Input(1), SD%Input(1), HD%Input(1), MAPp%Input(1), BD%Input(1,:), TRIM(p_FAST%OutFileRoot)//'.InputMeshes.bin', ErrStat2, ErrMsg2) CALL WriteMotionMeshesToFile(t_global, ED%y, SD%Input(1), SD%y, HD%Input(1), MAPp%Input(1), BD%y, BD%Input(1,:), y_FAST%UnGra, ErrStat2, ErrMsg2, TRIM(p_FAST%OutFileRoot)//'.gra') !unOut = -1 !CALL MeshWrBin ( unOut, AD%y%BladeLoad(2), ErrStat2, ErrMsg2, 'AD_2_ED_loads.bin'); IF (ErrStat2 /= ErrID_None) CALL WrScr(TRIM(ErrMsg2)) !CALL MeshWrBin ( unOut, ED%Input(1)%BladePtLoads(2),ErrStat2, ErrMsg2, 'AD_2_ED_loads.bin'); IF (ErrStat2 /= ErrID_None) CALL WrScr(TRIM(ErrMsg2)) !CALL MeshMapWrBin( unOut, AD%y%BladeLoad(2), ED%Input(1)%BladePtLoads(2), MeshMapData%AD_L_2_BDED_B(2), ErrStat2, ErrMsg2, 'AD_2_ED_loads.bin' ); IF (ErrStat2 /= ErrID_None) CALL WrScr(TRIM(ErrMsg2)) !close( unOut ) END IF y_FAST%VTK_count = y_FAST%VTK_count + 1 END SUBROUTINE WriteVTK !---------------------------------------------------------------------------------------------------------------------------------- !> This routine writes all the committed meshes to VTK-formatted files. It doesn't bother with returning an error code. SUBROUTINE WrVTK_AllMeshes(p_FAST, y_FAST, MeshMapData, ED, BD, AD, IfW, OpFM, HD, SD, ExtPtfm, SrvD, MAPp, FEAM, MD, Orca, IceF, IceD) use FVW_IO, only: WrVTK_FVW TYPE(FAST_ParameterType), INTENT(IN ) :: p_FAST !< Parameters for the glue code TYPE(FAST_OutputFileType),INTENT(IN ) :: y_FAST !< Output variables for the glue code TYPE(FAST_ModuleMapType), INTENT(IN ) :: MeshMapData !< Data for mapping between modules TYPE(ElastoDyn_Data), INTENT(IN ) :: ED !< ElastoDyn data TYPE(BeamDyn_Data), INTENT(IN ) :: BD !< BeamDyn data TYPE(ServoDyn_Data), INTENT(IN ) :: SrvD !< ServoDyn data TYPE(AeroDyn_Data), INTENT(IN ) :: AD !< AeroDyn data TYPE(InflowWind_Data), INTENT(IN ) :: IfW !< InflowWind data TYPE(OpenFOAM_Data), INTENT(IN ) :: OpFM !< OpenFOAM data TYPE(HydroDyn_Data), INTENT(IN ) :: HD !< HydroDyn data TYPE(SubDyn_Data), INTENT(IN ) :: SD !< SubDyn data TYPE(ExtPtfm_Data), INTENT(IN ) :: ExtPtfm !< ExtPtfm data TYPE(MAP_Data), INTENT(IN ) :: MAPp !< MAP data TYPE(FEAMooring_Data), INTENT(IN ) :: FEAM !< FEAMooring data TYPE(MoorDyn_Data), INTENT(IN ) :: MD !< MoorDyn data TYPE(OrcaFlex_Data), INTENT(IN ) :: Orca !< OrcaFlex interface data TYPE(IceFloe_Data), INTENT(IN ) :: IceF !< IceFloe data TYPE(IceDyn_Data), INTENT(IN ) :: IceD !< All the IceDyn data used in time-step loop logical :: outputFields ! flag to determine if we want to output the HD mesh fields INTEGER(IntKi) :: NumBl, k INTEGER(IntKi) :: ErrStat2 CHARACTER(ErrMsgLen) :: ErrMSg2 CHARACTER(*), PARAMETER :: RoutineName = 'WrVTK_AllMeshes' NumBl = 0 if (allocated(ED%y%BladeRootMotion)) then NumBl = SIZE(ED%y%BladeRootMotion) end if ! I'm first going to just put all of the meshes that get mapped together, then decide if we're going to print/plot them all ! ElastoDyn if (allocated(ED%Input)) then ! ElastoDyn outputs (motions) DO K=1,NumBl !%BladeLn2Mesh(K) used only when not BD (see below) call MeshWrVTK(p_FAST%TurbinePos, ED%y%BladeRootMotion(K), trim(p_FAST%VTK_OutFileRoot)//'.ED_BladeRootMotion'//trim(num2lstr(k)), y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth ) END DO call MeshWrVTK(p_FAST%TurbinePos, ED%y%TowerLn2Mesh, trim(p_FAST%VTK_OutFileRoot)//'.ED_TowerLn2Mesh_motion', y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth ) ! these will get output with their sibling input meshes !call MeshWrVTK(p_FAST%TurbinePos, ED%y%HubPtMotion, trim(p_FAST%VTK_OutFileRoot)//'.ED_HubPtMotion', y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth ) !call MeshWrVTK(p_FAST%TurbinePos, ED%y%NacelleMotion, trim(p_FAST%VTK_OutFileRoot)//'.ED_NacelleMotion', y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth ) !call MeshWrVTK(p_FAST%TurbinePos, ED%y%PlatformPtMesh, trim(p_FAST%VTK_OutFileRoot)//'.ED_PlatformPtMesh_motion', y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth ) ! ElastoDyn inputs (loads) ! %BladePtLoads used only when not BD (see below) call MeshWrVTK(p_FAST%TurbinePos, ED%Input(1)%TowerPtLoads, trim(p_FAST%VTK_OutFileRoot)//'.ED_TowerPtLoads', y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth, ED%y%TowerLn2Mesh ) call MeshWrVTK(p_FAST%TurbinePos, ED%Input(1)%HubPtLoad, trim(p_FAST%VTK_OutFileRoot)//'.ED_Hub', y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth, ED%y%HubPtMotion ) call MeshWrVTK(p_FAST%TurbinePos, ED%Input(1)%NacelleLoads, trim(p_FAST%VTK_OutFileRoot)//'.ED_Nacelle' ,y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth, ED%y%NacelleMotion ) call MeshWrVTK(p_FAST%TurbinePos, ED%Input(1)%PlatformPtMesh, trim(p_FAST%VTK_OutFileRoot)//'.ED_PlatformPtMesh', y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth, ED%y%PlatformPtMesh ) end if ! BeamDyn IF ( p_FAST%CompElast == Module_BD .and. allocated(BD%Input) .and. allocated(BD%y)) THEN do K=1,NumBl ! BeamDyn inputs !call MeshWrVTK(p_FAST%TurbinePos, BD%Input(1,k)%RootMotion, trim(p_FAST%VTK_OutFileRoot)//'.BD_RootMotion'//trim(num2lstr(k)), y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth ) call MeshWrVTK(p_FAST%TurbinePos, BD%Input(1,k)%HubMotion, trim(p_FAST%VTK_OutFileRoot)//'.BD_HubMotion'//trim(num2lstr(k)), y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth ) end do if (allocated(MeshMapData%y_BD_BldMotion_4Loads)) then do K=1,NumBl call MeshWrVTK(p_FAST%TurbinePos, BD%Input(1,k)%DistrLoad, trim(p_FAST%VTK_OutFileRoot)//'.BD_DistrLoad'//trim(num2lstr(k)), y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth, MeshMapData%y_BD_BldMotion_4Loads(k) ) ! skipping PointLoad end do elseif (p_FAST%BD_OutputSibling) then do K=1,NumBl call MeshWrVTK(p_FAST%TurbinePos, BD%Input(1,k)%DistrLoad, trim(p_FAST%VTK_OutFileRoot)//'.BD_Blade'//trim(num2lstr(k)), y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth, BD%y(k)%BldMotion ) ! skipping PointLoad end do end if do K=1,NumBl ! BeamDyn outputs call MeshWrVTK(p_FAST%TurbinePos, BD%y(k)%ReactionForce, trim(p_FAST%VTK_OutFileRoot)//'.BD_ReactionForce_RootMotion'//trim(num2lstr(k)), y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth, BD%Input(1,k)%RootMotion ) end do if (.not. p_FAST%BD_OutputSibling) then !otherwise this mesh has been put with the DistrLoad mesh do K=1,NumBl ! BeamDyn outputs call MeshWrVTK(p_FAST%TurbinePos, BD%y(k)%BldMotion, trim(p_FAST%VTK_OutFileRoot)//'.BD_BldMotion'//trim(num2lstr(k)), y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth ) end do end if ELSE if (p_FAST%CompElast == Module_ED .and. allocated(ED%Input)) then ! ElastoDyn DO K=1,NumBl call MeshWrVTK(p_FAST%TurbinePos, ED%y%BladeLn2Mesh(K), trim(p_FAST%VTK_OutFileRoot)//'.ED_BladeLn2Mesh_motion'//trim(num2lstr(k)), y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth ) call MeshWrVTK(p_FAST%TurbinePos, ED%Input(1)%BladePtLoads(K), trim(p_FAST%VTK_OutFileRoot)//'.ED_BladePtLoads'//trim(num2lstr(k)), y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth, ED%y%BladeLn2Mesh(K) ) END DO END IF ! ServoDyn if (allocated(SrvD%Input)) then IF ( SrvD%Input(1)%NTMD%Mesh%Committed ) THEN !call MeshWrVTK(p_FAST%TurbinePos, SrvD%Input(1)%NTMD%Mesh, trim(p_FAST%VTK_OutFileRoot)//'.SrvD_NTMD_Motion', y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth ) call MeshWrVTK(p_FAST%TurbinePos, SrvD%y%NTMD%Mesh, trim(p_FAST%VTK_OutFileRoot)//'.SrvD_NTMD', y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth, SrvD%Input(1)%TTMD%Mesh ) END IF IF ( SrvD%Input(1)%TTMD%Mesh%Committed ) THEN !call MeshWrVTK(p_FAST%TurbinePos, SrvD%Input(1)%TTMD%Mesh, trim(p_FAST%VTK_OutFileRoot)//'.SrvD_TTMD_Motion', y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth ) call MeshWrVTK(p_FAST%TurbinePos, SrvD%y%TTMD%Mesh, trim(p_FAST%VTK_OutFileRoot)//'.SrvD_TTMD', y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth, SrvD%Input(1)%TTMD%Mesh ) END IF end if ! AeroDyn IF ( p_FAST%CompAero == Module_AD .and. allocated(AD%Input)) THEN if (allocated(AD%Input(1)%BladeRootMotion)) then DO K=1,NumBl call MeshWrVTK(p_FAST%TurbinePos, AD%Input(1)%BladeRootMotion(K), trim(p_FAST%VTK_OutFileRoot)//'.AD_BladeRootMotion'//trim(num2lstr(k)), y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth ) !call MeshWrVTK(p_FAST%TurbinePos, AD%Input(1)%BladeMotion(K), trim(p_FAST%VTK_OutFileRoot)//'.AD_BladeMotion'//trim(num2lstr(k)), y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth ) END DO call MeshWrVTK(p_FAST%TurbinePos, AD%Input(1)%HubMotion, trim(p_FAST%VTK_OutFileRoot)//'.AD_HubMotion', y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth ) !call MeshWrVTK(p_FAST%TurbinePos, AD%Input(1)%TowerMotion, trim(p_FAST%VTK_OutFileRoot)//'.AD_TowerMotion', y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth ) DO K=1,NumBl call MeshWrVTK(p_FAST%TurbinePos, AD%y%BladeLoad(K), trim(p_FAST%VTK_OutFileRoot)//'.AD_Blade'//trim(num2lstr(k)), y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth, AD%Input(1)%BladeMotion(k) ) END DO call MeshWrVTK(p_FAST%TurbinePos, AD%y%TowerLoad, trim(p_FAST%VTK_OutFileRoot)//'.AD_Tower', y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth, AD%Input(1)%TowerMotion ) end if ! FVW submodule of AD15 if (allocated(AD%m%FVW_u)) then if (allocated(AD%m%FVW_u(1)%WingsMesh)) then DO K=1,NumBl call MeshWrVTK(p_FAST%TurbinePos, AD%m%FVW_u(1)%WingsMesh(k), trim(p_FAST%VTK_OutFileRoot)//'.FVW_WingsMesh'//trim(num2lstr(k)), y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth, AD%Input(1)%BladeMotion(k) ) !call MeshWrVTK(p_FAST%TurbinePos, AD%Input(1)%BladeMotion(K), trim(p_FAST%OutFileRoot)//'.AD_BladeMotion'//trim(num2lstr(k)), y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2 ) END DO ! Free wake call WrVTK_FVW(AD%p%FVW, AD%x(1)%FVW, AD%z(1)%FVW, AD%m%FVW, trim(p_FAST%VTK_OutFileRoot)//'.FVW', y_FAST%VTK_count, p_FAST%VTK_tWidth, bladeFrame=.FALSE.) ! bladeFrame==.FALSE. to output in global coords end if end if END IF ! HydroDyn IF ( p_FAST%CompHydro == Module_HD .and. allocated(HD%Input)) THEN !TODO: Fix for Visualizaton GJH 4/23/20 !call MeshWrVTK(p_FAST%TurbinePos, HD%Input(1)%Mesh, trim(p_FAST%VTK_OutFileRoot)//'.HD_Mesh_motion', y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2 ) call MeshWrVTK(p_FAST%TurbinePos, HD%Input(1)%Morison%Mesh, trim(p_FAST%VTK_OutFileRoot)//'.HD_Morison_Motion', y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth ) if (HD%y%WamitMesh%Committed) then ! if (p_FAST%CompSub == Module_NONE) then !TODO call MeshWrVTK(p_FAST%TurbinePos, HD%y%WamitMesh, trim(p_FAST%VTK_OutFileRoot)//'.HD_Mesh', y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth, HD%Input(1)%WAMITMesh ) ! outputFields = .false. ! else call MeshWrVTK(p_FAST%TurbinePos, HD%y%WamitMesh, trim(p_FAST%VTK_OutFileRoot)//'.HD_Mesh', y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth, HD%Input(1)%WAMITMesh ) ! outputFields = p_FAST%VTK_fields ! end if endif if (HD%y%Morison%Mesh%Committed) then call MeshWrVTK(p_FAST%TurbinePos, HD%y%Morison%Mesh, trim(p_FAST%VTK_OutFileRoot)//'.HD_Morison', y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth, HD%Input(1)%Morison%Mesh ) endif END IF ! SubDyn IF ( p_FAST%CompSub == Module_SD .and. allocated(SD%Input)) THEN !call MeshWrVTK(p_FAST%TurbinePos, SD%Input(1)%TPMesh, trim(p_FAST%VTK_OutFileRoot)//'.SD_TPMesh_motion', y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth ) call MeshWrVTK(p_FAST%TurbinePos, SD%Input(1)%LMesh, trim(p_FAST%VTK_OutFileRoot)//'.SD_LMesh_y2Mesh', y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth, SD%y%y2Mesh ) call MeshWrVTK(p_FAST%TurbinePos, SD%y%y1Mesh, trim(p_FAST%VTK_OutFileRoot)//'.SD_y1Mesh_TPMesh', y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth, SD%Input(1)%TPMesh ) !call MeshWrVTK(p_FAST%TurbinePos, SD%y%y2Mesh, trim(p_FAST%VTK_OutFileRoot)//'.SD_y2Mesh_motion', y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth ) ELSE IF ( p_FAST%CompSub == Module_ExtPtfm .and. allocated(ExtPtfm%Input)) THEN call MeshWrVTK(p_FAST%TurbinePos, ExtPtfm%y%PtfmMesh, trim(p_FAST%VTK_OutFileRoot)//'.ExtPtfm', y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth, ExtPtfm%Input(1)%PtfmMesh ) END IF ! MAP IF ( p_FAST%CompMooring == Module_MAP ) THEN if (allocated(MAPp%Input)) then call MeshWrVTK(p_FAST%TurbinePos, MAPp%y%PtFairleadLoad, trim(p_FAST%VTK_OutFileRoot)//'.MAP_PtFairlead', y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth, MAPp%Input(1)%PtFairDisplacement ) !call MeshWrVTK(p_FAST%TurbinePos, MAPp%Input(1)%PtFairDisplacement, trim(p_FAST%VTK_OutFileRoot)//'.MAP_PtFair_motion', y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth ) end if ! MoorDyn ELSEIF ( p_FAST%CompMooring == Module_MD ) THEN if (allocated(MD%Input)) then call MeshWrVTK(p_FAST%TurbinePos, MD%y%PtFairleadLoad, trim(p_FAST%VTK_OutFileRoot)//'.MD_PtFairlead', y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth, MD%Input(1)%PtFairleadDisplacement ) !call MeshWrVTK(p_FAST%TurbinePos, MD%Input(1)%PtFairleadDisplacement, trim(p_FAST%VTK_OutFileRoot)//'.MD_PtFair_motion', y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth ) end if ! FEAMooring ELSEIF ( p_FAST%CompMooring == Module_FEAM ) THEN if (allocated(FEAM%Input)) then call MeshWrVTK(p_FAST%TurbinePos, FEAM%y%PtFairleadLoad, trim(p_FAST%VTK_OutFileRoot)//'.FEAM_PtFairlead', y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth, FEAM%Input(1)%PtFairleadDisplacement ) !call MeshWrVTK(p_FAST%TurbinePos, FEAM%Input(1)%PtFairleadDisplacement, trim(p_FAST%VTK_OutFileRoot)//'.FEAM_PtFair_motion', y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth ) end if ! Orca ELSEIF ( p_FAST%CompMooring == Module_Orca ) THEN if (allocated(Orca%Input)) then call MeshWrVTK(p_FAST%TurbinePos, Orca%y%PtfmMesh, trim(p_FAST%VTK_OutFileRoot)//'.Orca_PtfmMesh', y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth, Orca%Input(1)%PtfmMesh ) !call MeshWrVTK(p_FAST%TurbinePos, Orca%Input(1)%PtfmMesh, trim(p_FAST%VTK_OutFileRoot)//'.Orca_PtfmMesh_motion', y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth ) end if END IF ! IceFloe IF ( p_FAST%CompIce == Module_IceF ) THEN if (allocated(IceF%Input)) then call MeshWrVTK(p_FAST%TurbinePos, IceF%y%iceMesh, trim(p_FAST%VTK_OutFileRoot)//'.IceF_iceMesh', y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth, IceF%Input(1)%iceMesh ) !call MeshWrVTK(p_FAST%TurbinePos, IceF%Input(1)%iceMesh, trim(p_FAST%VTK_OutFileRoot)//'.IceF_iceMesh_motion', y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth ) end if ! IceDyn ELSEIF ( p_FAST%CompIce == Module_IceD ) THEN if (allocated(IceD%Input)) then DO k = 1,p_FAST%numIceLegs call MeshWrVTK(p_FAST%TurbinePos, IceD%y(k)%PointMesh, trim(p_FAST%VTK_OutFileRoot)//'.IceD_PointMesh'//trim(num2lstr(k)), y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth, IceD%Input(1,k)%PointMesh ) !call MeshWrVTK(p_FAST%TurbinePos, IceD%Input(1,k)%PointMesh, trim(p_FAST%VTK_OutFileRoot)//'.IceD_PointMesh_motion'//trim(num2lstr(k)), y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth ) END DO end if END IF END SUBROUTINE WrVTK_AllMeshes !---------------------------------------------------------------------------------------------------------------------------------- !> This routine writes a minimal subset of meshes (enough to visualize the turbine) to VTK-formatted files. It doesn't bother with !! returning an error code. SUBROUTINE WrVTK_BasicMeshes(p_FAST, y_FAST, MeshMapData, ED, BD, AD, IfW, OpFM, HD, SD, SrvD, MAPp, FEAM, MD, Orca, IceF, IceD) TYPE(FAST_ParameterType), INTENT(IN ) :: p_FAST !< Parameters for the glue code TYPE(FAST_OutputFileType),INTENT(IN ) :: y_FAST !< Output variables for the glue code TYPE(FAST_ModuleMapType), INTENT(IN ) :: MeshMapData !< Data for mapping between modules TYPE(ElastoDyn_Data), INTENT(IN ) :: ED !< ElastoDyn data TYPE(BeamDyn_Data), INTENT(IN ) :: BD !< BeamDyn data TYPE(ServoDyn_Data), INTENT(IN ) :: SrvD !< ServoDyn data TYPE(AeroDyn_Data), INTENT(IN ) :: AD !< AeroDyn data TYPE(InflowWind_Data), INTENT(IN ) :: IfW !< InflowWind data TYPE(OpenFOAM_Data), INTENT(IN ) :: OpFM !< OpenFOAM data TYPE(HydroDyn_Data), INTENT(IN ) :: HD !< HydroDyn data TYPE(SubDyn_Data), INTENT(IN ) :: SD !< SubDyn data TYPE(MAP_Data), INTENT(IN ) :: MAPp !< MAP data TYPE(FEAMooring_Data), INTENT(IN ) :: FEAM !< FEAMooring data TYPE(MoorDyn_Data), INTENT(IN ) :: MD !< MoorDyn data TYPE(OrcaFlex_Data), INTENT(IN ) :: Orca !< OrcaFlex interface data TYPE(IceFloe_Data), INTENT(IN ) :: IceF !< IceFloe data TYPE(IceDyn_Data), INTENT(IN ) :: IceD !< All the IceDyn data used in time-step loop logical :: OutputFields INTEGER(IntKi) :: NumBl, k INTEGER(IntKi) :: ErrStat2 CHARACTER(ErrMsgLen) :: ErrMSg2 CHARACTER(*), PARAMETER :: RoutineName = 'WrVTK_BasicMeshes' NumBl = 0 if (allocated(ED%y%BladeRootMotion)) then NumBl = SIZE(ED%y%BladeRootMotion) end if ! Blades IF ( p_FAST%CompAero == Module_AD ) THEN ! These meshes may have airfoil data associated with nodes... DO K=1,NumBl call MeshWrVTK(p_FAST%TurbinePos, AD%Input(1)%BladeMotion(K), trim(p_FAST%VTK_OutFileRoot)//'.AD_Blade'//trim(num2lstr(k)), & y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth, Sib=AD%y%BladeLoad(K) ) END DO ELSE IF ( p_FAST%CompElast == Module_BD ) THEN DO K=1,NumBl call MeshWrVTK(p_FAST%TurbinePos, BD%y(k)%BldMotion, trim(p_FAST%VTK_OutFileRoot)//'.BD_BldMotion'//trim(num2lstr(k)), & y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth ) END DO ELSE IF ( p_FAST%CompElast == Module_ED ) THEN DO K=1,NumBl call MeshWrVTK(p_FAST%TurbinePos, ED%y%BladeLn2Mesh(K), trim(p_FAST%VTK_OutFileRoot)//'.ED_BladeLn2Mesh_motion'//trim(num2lstr(k)), & y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth ) END DO END IF ! Nacelle call MeshWrVTK(p_FAST%TurbinePos, ED%y%NacelleMotion, trim(p_FAST%VTK_OutFileRoot)//'.ED_Nacelle', y_FAST%VTK_count, & p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth, Sib=ED%Input(1)%NacelleLoads ) ! Hub call MeshWrVTK(p_FAST%TurbinePos, ED%y%HubPtMotion, trim(p_FAST%VTK_OutFileRoot)//'.ED_Hub', y_FAST%VTK_count, & p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth, Sib=ED%Input(1)%HubPtLoad ) ! Tower motions call MeshWrVTK(p_FAST%TurbinePos, ED%y%TowerLn2Mesh, trim(p_FAST%VTK_OutFileRoot)//'.ED_TowerLn2Mesh_motion', & y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth ) ! Substructure ! call MeshWrVTK(p_FAST%TurbinePos, ED%y%PlatformPtMesh, trim(p_FAST%VTK_OutFileRoot)//'.ED_PlatformPtMesh_motion', y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth ) ! IF ( p_FAST%CompSub == Module_SD ) THEN ! call MeshWrVTK(p_FAST%TurbinePos, SD%Input(1)%TPMesh, trim(p_FAST%VTK_OutFileRoot)//'.SD_TPMesh_motion', y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth ) ! call MeshWrVTK(p_FAST%TurbinePos, SD%y%y2Mesh, trim(p_FAST%VTK_OutFileRoot)//'.SD_y2Mesh_motion', y_FAST%VTK_count, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth ) ! END IF IF ( p_FAST%CompHydro == Module_HD ) THEN if (p_FAST%CompSub == Module_NONE) then call MeshWrVTK(p_FAST%TurbinePos, HD%y%WAMITMesh, trim(p_FAST%VTK_OutFileRoot)//'.HD_AllHdroOrigin', y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth, HD%Input(1)%WAMITMesh ) outputFields = .false. else OutputFields = p_FAST%VTK_fields end if !TODO: Fix for Visualization GJH 4/23/20 call MeshWrVTK(p_FAST%TurbinePos, HD%Input(1)%Morison%Mesh, trim(p_FAST%VTK_OutFileRoot)//'.HD_Morison', & y_FAST%VTK_count, OutputFields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth, Sib=HD%y%Morison%Mesh ) END IF ! Mooring Lines? ! IF ( p_FAST%CompMooring == Module_MAP ) THEN ! call MeshWrVTK(p_FAST%TurbinePos, MAPp%Input(1)%PtFairDisplacement, trim(p_FAST%VTK_OutFileRoot)//'.MAP_PtFair_motion', y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth ) ! ELSEIF ( p_FAST%CompMooring == Module_MD ) THEN ! call MeshWrVTK(p_FAST%TurbinePos, MD%Input(1)%PtFairleadDisplacement, trim(p_FAST%VTK_OutFileRoot)//'.MD_PtFair_motion', y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth ) ! ELSEIF ( p_FAST%CompMooring == Module_FEAM ) THEN ! call MeshWrVTK(p_FAST%TurbinePos, FEAM%Input(1)%PtFairleadDisplacement, trim(p_FAST%VTK_OutFileRoot)//'FEAM_PtFair_motion', y_FAST%VTK_count, p_FAST%VTK_fields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth ) ! END IF END SUBROUTINE WrVTK_BasicMeshes !---------------------------------------------------------------------------------------------------------------------------------- !> This routine writes a minimal subset of meshes with surfaces to VTK-formatted files. It doesn't bother with !! returning an error code. SUBROUTINE WrVTK_Surfaces(t_global, p_FAST, y_FAST, MeshMapData, ED, BD, AD, IfW, OpFM, HD, SD, SrvD, MAPp, FEAM, MD, Orca, IceF, IceD) use FVW_IO, only: WrVTK_FVW REAL(DbKi), INTENT(IN ) :: t_global !< Current global time TYPE(FAST_ParameterType), INTENT(IN ) :: p_FAST !< Parameters for the glue code TYPE(FAST_OutputFileType),INTENT(INOUT) :: y_FAST !< Output variables for the glue code (only because we're updating VTK_LastWaveIndx) TYPE(FAST_ModuleMapType), INTENT(IN ) :: MeshMapData !< Data for mapping between modules TYPE(ElastoDyn_Data), INTENT(IN ) :: ED !< ElastoDyn data TYPE(BeamDyn_Data), INTENT(IN ) :: BD !< BeamDyn data TYPE(ServoDyn_Data), INTENT(IN ) :: SrvD !< ServoDyn data TYPE(AeroDyn_Data), INTENT(IN ) :: AD !< AeroDyn data TYPE(InflowWind_Data), INTENT(IN ) :: IfW !< InflowWind data TYPE(OpenFOAM_Data), INTENT(IN ) :: OpFM !< OpenFOAM data TYPE(HydroDyn_Data), INTENT(IN ) :: HD !< HydroDyn data TYPE(SubDyn_Data), INTENT(IN ) :: SD !< SubDyn data TYPE(MAP_Data), INTENT(IN ) :: MAPp !< MAP data TYPE(FEAMooring_Data), INTENT(IN ) :: FEAM !< FEAMooring data TYPE(MoorDyn_Data), INTENT(IN ) :: MD !< MoorDyn data TYPE(OrcaFlex_Data), INTENT(IN ) :: Orca !< OrcaFlex interface data TYPE(IceFloe_Data), INTENT(IN ) :: IceF !< IceFloe data TYPE(IceDyn_Data), INTENT(IN ) :: IceD !< All the IceDyn data used in time-step loop logical, parameter :: OutputFields = .FALSE. ! due to confusion about what fields mean on a surface, we are going to just output the basic meshes if people ask for fields INTEGER(IntKi) :: NumBl, k INTEGER(IntKi) :: ErrStat2 CHARACTER(ErrMsgLen) :: ErrMSg2 CHARACTER(*), PARAMETER :: RoutineName = 'WrVTK_Surfaces' NumBl = 0 if (allocated(ED%y%BladeRootMotion)) then NumBl = SIZE(ED%y%BladeRootMotion) end if ! Ground (written at initialization) ! Wave elevation if ( allocated( p_FAST%VTK_Surface%WaveElev ) ) call WrVTK_WaveElev( t_global, p_FAST, y_FAST, HD) ! Nacelle call MeshWrVTK_PointSurface (p_FAST%TurbinePos, ED%y%NacelleMotion, trim(p_FAST%VTK_OutFileRoot)//'.NacelleSurface', & y_FAST%VTK_count, OutputFields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth , verts = p_FAST%VTK_Surface%NacelleBox, Sib=ED%Input(1)%NacelleLoads ) ! Hub call MeshWrVTK_PointSurface (p_FAST%TurbinePos, ED%y%HubPtMotion, trim(p_FAST%VTK_OutFileRoot)//'.HubSurface', & y_FAST%VTK_count, OutputFields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth , & NumSegments=p_FAST%VTK_Surface%NumSectors, radius=p_FAST%VTK_Surface%HubRad, Sib=ED%Input(1)%HubPtLoad ) ! Tower motions call MeshWrVTK_Ln2Surface (p_FAST%TurbinePos, ED%y%TowerLn2Mesh, trim(p_FAST%VTK_OutFileRoot)//'.TowerSurface', & y_FAST%VTK_count, OutputFields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth, p_FAST%VTK_Surface%NumSectors, p_FAST%VTK_Surface%TowerRad ) ! Blades IF ( p_FAST%CompAero == Module_AD ) THEN ! These meshes may have airfoil data associated with nodes... DO K=1,NumBl call MeshWrVTK_Ln2Surface (p_FAST%TurbinePos, AD%Input(1)%BladeMotion(K), trim(p_FAST%VTK_OutFileRoot)//'.Blade'//trim(num2lstr(k))//'Surface', & y_FAST%VTK_count, OutputFields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth , verts=p_FAST%VTK_Surface%BladeShape(K)%AirfoilCoords & ,Sib=AD%y%BladeLoad(k) ) END DO ELSE IF ( p_FAST%CompElast == Module_BD ) THEN DO K=1,NumBl call MeshWrVTK_Ln2Surface (p_FAST%TurbinePos, BD%y(k)%BldMotion, trim(p_FAST%VTK_OutFileRoot)//'.Blade'//trim(num2lstr(k))//'Surface', & y_FAST%VTK_count, OutputFields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth , verts=p_FAST%VTK_Surface%BladeShape(K)%AirfoilCoords ) END DO ELSE IF ( p_FAST%CompElast == Module_ED ) THEN DO K=1,NumBl call MeshWrVTK_Ln2Surface (p_FAST%TurbinePos, ED%y%BladeLn2Mesh(K), trim(p_FAST%VTK_OutFileRoot)//'.Blade'//trim(num2lstr(k))//'Surface', & y_FAST%VTK_count, OutputFields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth , verts=p_FAST%VTK_Surface%BladeShape(K)%AirfoilCoords ) END DO END IF ! Free wake if (allocated(AD%m%FVW_u)) then if (allocated(AD%m%FVW_u(1)%WingsMesh)) then call WrVTK_FVW(AD%p%FVW, AD%x(1)%FVW, AD%z(1)%FVW, AD%m%FVW, trim(p_FAST%VTK_OutFileRoot)//'.FVW', y_FAST%VTK_count, p_FAST%VTK_tWidth, bladeFrame=.FALSE.) ! bladeFrame==.FALSE. to output in global coords end if end if ! Platform ! call MeshWrVTK_PointSurface (p_FAST%TurbinePos, ED%y%PlatformPtMesh, trim(p_FAST%VTK_OutFileRoot)//'.PlatformSurface', y_FAST%VTK_count, OutputFields, ErrStat2, ErrMsg2, Radius = p_FAST%VTK_Surface%GroundRad ) ! Substructure ! call MeshWrVTK(p_FAST%TurbinePos, ED%y%PlatformPtMesh, trim(p_FAST%VTK_OutFileRoot)//'.ED_PlatformPtMesh_motion', y_FAST%VTK_count, OutputFields, ErrStat2, ErrMsg2 ) ! IF ( p_FAST%CompSub == Module_SD ) THEN ! call MeshWrVTK(p_FAST%TurbinePos, SD%Input(1)%TPMesh, trim(p_FAST%VTK_OutFileRoot)//'.SD_TPMesh_motion', y_FAST%VTK_count, OutputFields, ErrStat2, ErrMsg2 ) ! call MeshWrVTK(p_FAST%TurbinePos, SD%y%y2Mesh, trim(p_FAST%VTK_OutFileRoot)//'.SD_y2Mesh_motion', y_FAST%VTK_count, OutputFields, ErrStat2, ErrMsg2 ) ! END IF !TODO: Fix below section for new Morison GJH 4/23/20 ! !IF ( HD%Input(1)%Morison%Mesh%Committed ) THEN ! !if ( p_FAST%CompSub == Module_NONE ) then ! floating ! ! OutputFields = .false. ! !else ! ! OutputFields = p_FAST%VTK_fields ! !end if ! ! call MeshWrVTK_Ln2Surface (p_FAST%TurbinePos, HD%Input(1)%Morison%Mesh, trim(p_FAST%VTK_OutFileRoot)//'.MorisonSurface', & ! y_FAST%VTK_count, OutputFields, ErrStat2, ErrMsg2, p_FAST%VTK_tWidth, p_FAST%VTK_Surface%NumSectors, & ! p_FAST%VTK_Surface%MorisonRad, Sib=HD%y%Morison%Mesh ) !END IF ! Mooring Lines? ! IF ( p_FAST%CompMooring == Module_MAP ) THEN ! call MeshWrVTK(p_FAST%TurbinePos, MAPp%Input(1)%PtFairDisplacement, trim(p_FAST%VTK_OutFileRoot)//'.MAP_PtFair_motion', y_FAST%VTK_count, OutputFields, ErrStat2, ErrMsg2 ) ! ELSEIF ( p_FAST%CompMooring == Module_MD ) THEN ! call MeshWrVTK(p_FAST%TurbinePos, MD%Input(1)%PtFairleadDisplacement, trim(p_FAST%VTK_OutFileRoot)//'.MD_PtFair_motion', y_FAST%VTK_count, OutputFields, ErrStat2, ErrMsg2 ) ! ELSEIF ( p_FAST%CompMooring == Module_FEAM ) THEN ! call MeshWrVTK(p_FAST%TurbinePos, FEAM%Input(1)%PtFairleadDisplacement, trim(p_FAST%VTK_OutFileRoot)//'FEAM_PtFair_motion', y_FAST%VTK_count, OutputFields, ErrStat2, ErrMsg2 ) ! END IF if (p_FAST%VTK_fields) then call WrVTK_BasicMeshes(p_FAST, y_FAST, MeshMapData, ED, BD, AD, IfW, OpFM, HD, SD, SrvD, MAPp, FEAM, MD, Orca, IceF, IceD) end if END SUBROUTINE WrVTK_Surfaces !---------------------------------------------------------------------------------------------------------------------------------- !> This subroutine writes the wave elevation data for a given time step SUBROUTINE WrVTK_WaveElev(t_global, p_FAST, y_FAST, HD) REAL(DbKi), INTENT(IN ) :: t_global !< Current global time TYPE(FAST_ParameterType), INTENT(IN ) :: p_FAST !< Parameters for the glue code TYPE(FAST_OutputFileType),INTENT(INOUT) :: y_FAST !< Output variables for the glue code TYPE(HydroDyn_Data), INTENT(IN ) :: HD !< HydroDyn data ! local variables INTEGER(IntKi) :: Un ! fortran unit number INTEGER(IntKi) :: n, iy, ix ! loop counters REAL(SiKi) :: t CHARACTER(1024) :: FileName INTEGER(IntKi) :: NumberOfPoints INTEGER(IntKi), parameter :: NumberOfLines = 0 INTEGER(IntKi) :: NumberOfPolys CHARACTER(1024) :: Tstr INTEGER(IntKi) :: ErrStat2 CHARACTER(ErrMsgLen) :: ErrMsg2 CHARACTER(*),PARAMETER :: RoutineName = 'WrVTK_WaveElev' NumberOfPoints = size(p_FAST%VTK_surface%WaveElevXY,2) ! I'm going to make triangles for now. we should probably just make this a structured file at some point NumberOfPolys = ( p_FAST%VTK_surface%NWaveElevPts(1) - 1 ) * & ( p_FAST%VTK_surface%NWaveElevPts(2) - 1 ) * 2 !................................................................. ! write the data that potentially changes each time step: !................................................................. ! construct the string for the zero-padded VTK write-out step write(Tstr, '(i' // trim(Num2LStr(p_FAST%VTK_tWidth)) //'.'// trim(Num2LStr(p_FAST%VTK_tWidth)) // ')') y_FAST%VTK_count ! PolyData (.vtp) - Serial vtkPolyData (unstructured) file FileName = TRIM(p_FAST%VTK_OutFileRoot)//'.WaveSurface.'//TRIM(Tstr)//'.vtp' call WrVTK_header( FileName, NumberOfPoints, NumberOfLines, NumberOfPolys, Un, ErrStat2, ErrMsg2 ) if (ErrStat2 >= AbortErrLev) return ! points (nodes, augmented with NumSegments): WRITE(Un,'(A)') ' <Points>' WRITE(Un,'(A)') ' <DataArray type="Float32" NumberOfComponents="3" format="ascii">' ! I'm not going to interpolate in time; I'm just going to get the index of the closest wave time value t = REAL(t_global,SiKi) call GetWaveElevIndx( t, HD%p%WaveTime, y_FAST%VTK_LastWaveIndx ) n = 1 do ix=1,p_FAST%VTK_surface%NWaveElevPts(1) do iy=1,p_FAST%VTK_surface%NWaveElevPts(2) WRITE(Un,VTK_AryFmt) p_FAST%VTK_surface%WaveElevXY(:,n), p_FAST%VTK_surface%WaveElev(y_FAST%VTK_LastWaveIndx,n) n = n+1 end do end do WRITE(Un,'(A)') ' </DataArray>' WRITE(Un,'(A)') ' </Points>' WRITE(Un,'(A)') ' <Polys>' WRITE(Un,'(A)') ' <DataArray type="Int32" Name="connectivity" format="ascii">' do ix=1,p_FAST%VTK_surface%NWaveElevPts(1)-1 do iy=1,p_FAST%VTK_surface%NWaveElevPts(2)-1 n = p_FAST%VTK_surface%NWaveElevPts(1)*(ix-1)+iy - 1 ! points start at 0 WRITE(Un,'(3(i7))') n, n+1, n+p_FAST%VTK_surface%NWaveElevPts(2) WRITE(Un,'(3(i7))') n+1, n+1+p_FAST%VTK_surface%NWaveElevPts(2), n+p_FAST%VTK_surface%NWaveElevPts(2) end do end do WRITE(Un,'(A)') ' </DataArray>' WRITE(Un,'(A)') ' <DataArray type="Int32" Name="offsets" format="ascii">' do n=1,NumberOfPolys WRITE(Un,'(i7)') 3*n end do WRITE(Un,'(A)') ' </DataArray>' WRITE(Un,'(A)') ' </Polys>' call WrVTK_footer( Un ) END SUBROUTINE WrVTK_WaveElev !---------------------------------------------------------------------------------------------------------------------------------- !> This function returns the index, Ind, of the XAry closest to XValIn, where XAry is assumed to be periodic. It starts !! searching at the value of Ind from a previous step. SUBROUTINE GetWaveElevIndx( XValIn, XAry, Ind ) ! Argument declarations. INTEGER, INTENT(INOUT) :: Ind ! Initial and final index into the arrays. REAL(SiKi), INTENT(IN) :: XAry (:) !< Array of X values to be interpolated. REAL(SiKi), INTENT(IN) :: XValIn !< X value to be found INTEGER :: AryLen ! Length of the arrays. REAL(SiKi) :: XVal !< X to be found (wrapped/periodic) AryLen = size(XAry) ! Wrap XValIn into the range XAry(1) to XAry(AryLen) XVal = MOD(XValIn, XAry(AryLen)) ! Let's check the limits first. IF ( XVal <= XAry(1) ) THEN Ind = 1 RETURN ELSE IF ( XVal >= XAry(AryLen) ) THEN Ind = AryLen RETURN ELSE ! Set the Ind to the first index if we are at the beginning of XAry IF ( XVal <= XAry(2) ) THEN Ind = 1 END IF END IF ! Let's interpolate! Ind = MAX( MIN( Ind, AryLen-1 ), 1 ) DO IF ( XVal < XAry(Ind) ) THEN Ind = Ind - 1 ELSE IF ( XVal >= XAry(Ind+1) ) THEN Ind = Ind + 1 ELSE ! XAry(Ind) <= XVal < XAry(Ind+1) ! this would make it the "closest" node, but I'm not going to worry about that for visualization purposes !if ( XVal > (XAry(Ind+1) + XAry(Ind))/2.0_SiKi ) Ind = Ind + 1 RETURN END IF END DO RETURN END SUBROUTINE GetWaveElevIndx !---------------------------------------------------------------------------------------------------------------------------------- !> This routine writes Input Mesh information to a binary file (for debugging). It both opens and closes the file. SUBROUTINE WriteInputMeshesToFile(u_ED, u_AD, u_SD, u_HD, u_MAP, u_BD, FileName, ErrStat, ErrMsg) TYPE(ED_InputType), INTENT(IN) :: u_ED !< ElastoDyn inputs TYPE(AD_InputType), INTENT(IN) :: u_AD !< AeroDyn inputs TYPE(SD_InputType), INTENT(IN) :: u_SD !< SubDyn inputs TYPE(HydroDyn_InputType), INTENT(IN) :: u_HD !< HydroDyn inputs TYPE(MAP_InputType), INTENT(IN) :: u_MAP !< MAP inputs TYPE(BD_InputType), INTENT(IN) :: u_BD(:) !< BeamDyn inputs CHARACTER(*), INTENT(IN) :: FileName !< Name of file to write this information to INTEGER(IntKi) :: ErrStat !< Error status of the operation CHARACTER(*) :: ErrMsg !< Error message if ErrStat /= ErrID_None INTEGER(IntKi) :: unOut INTEGER(IntKi) :: K_local INTEGER(B4Ki), PARAMETER :: File_ID = 3 INTEGER(B4Ki) :: NumBl ! Open the binary output file: unOut=-1 CALL GetNewUnit( unOut, ErrStat, ErrMsg ) CALL OpenBOutFile ( unOut, TRIM(FileName), ErrStat, ErrMsg ) IF (ErrStat /= ErrID_None) RETURN ! note that I'm not doing anything with the errors here, so it won't tell ! you there was a problem writing the data unless it was the last call. ! Add a file identification number (in case we ever have to change this): WRITE( unOut, IOSTAT=ErrStat ) File_ID ! Add how many blade meshes there are: NumBl = SIZE(u_ED%BladePtLoads,1) ! Note that NumBl is B4Ki WRITE( unOut, IOSTAT=ErrStat ) NumBl ! Add all of the input meshes: DO K_local = 1,NumBl CALL MeshWrBin( unOut, u_ED%BladePtLoads(K_local), ErrStat, ErrMsg ) END DO CALL MeshWrBin( unOut, u_ED%TowerPtLoads, ErrStat, ErrMsg ) CALL MeshWrBin( unOut, u_ED%PlatformPtMesh, ErrStat, ErrMsg ) CALL MeshWrBin( unOut, u_SD%TPMesh, ErrStat, ErrMsg ) CALL MeshWrBin( unOut, u_SD%LMesh, ErrStat, ErrMsg ) CALL MeshWrBin( unOut, u_HD%Morison%Mesh, ErrStat, ErrMsg ) CALL MeshWrBin( unOut, u_HD%WAMITMesh, ErrStat, ErrMsg ) CALL MeshWrBin( unOut, u_MAP%PtFairDisplacement, ErrStat, ErrMsg ) ! Add how many BD blade meshes there are: NumBl = SIZE(u_BD,1) ! Note that NumBl is B4Ki WRITE( unOut, IOSTAT=ErrStat ) NumBl DO K_local = 1,NumBl CALL MeshWrBin( unOut, u_BD(K_local)%RootMotion, ErrStat, ErrMsg ) CALL MeshWrBin( unOut, u_BD(K_local)%DistrLoad, ErrStat, ErrMsg ) END DO ! Add how many AD blade meshes there are: NumBl = SIZE(u_AD%BladeMotion,1) ! Note that NumBl is B4Ki WRITE( unOut, IOSTAT=ErrStat ) NumBl DO K_local = 1,NumBl CALL MeshWrBin( unOut, u_AD%BladeMotion(k_local), ErrStat, ErrMsg ) END DO ! Close the file CLOSE(unOut) END SUBROUTINE WriteInputMeshesToFile !---------------------------------------------------------------------------------------------------------------------------------- !> This routine writes motion mesh data to a binary file (for rudimentary visualization and debugging). If unOut < 0, a new file !! will be opened for writing (FileName). It is up to the caller of this routine to close the file. SUBROUTINE WriteMotionMeshesToFile(time, y_ED, u_SD, y_SD, u_HD, u_MAP, y_BD, u_BD, UnOut, ErrStat, ErrMsg, FileName) REAL(DbKi), INTENT(IN) :: time !< current simulation time TYPE(ED_OutputType), INTENT(IN) :: y_ED !< ElastoDyn outputs TYPE(SD_InputType), INTENT(IN) :: u_SD !< SubDyn inputs TYPE(SD_OutputType), INTENT(IN) :: y_SD !< SubDyn outputs TYPE(HydroDyn_InputType), INTENT(IN) :: u_HD !< HydroDyn inputs TYPE(MAP_InputType), INTENT(IN) :: u_MAP !< MAP inputs TYPE(BD_OutputType), INTENT(IN) :: y_BD(:) !< BeamDyn outputs TYPE(BD_InputType), INTENT(IN) :: u_BD(:) !< BeamDyn inputs INTEGER(IntKi) , INTENT(INOUT) :: unOut !< Unit number to write where this info should be written. If unOut < 0, a new file will be opened and the opened unit number will be returned. CHARACTER(*), INTENT(IN) :: FileName !< If unOut < 0, FileName will be opened for writing this mesh information. INTEGER(IntKi), INTENT(OUT) :: ErrStat !< Error status of the operation CHARACTER(*) , INTENT(OUT) :: ErrMsg !< Error message if ErrStat /= ErrID_None REAL(R8Ki) :: t INTEGER(IntKi) :: K_local INTEGER(B4Ki), PARAMETER :: File_ID = 101 INTEGER(B4Ki) :: NumBl t = time ! convert to 8-bytes if necessary (DbKi might not be R8Ki) ! note that I'm not doing anything with the errors here, so it won't tell ! you there was a problem writing the data unless it was the last call. ! Open the binary output file and write a header: if (unOut<0) then CALL GetNewUnit( unOut, ErrStat, ErrMsg ) CALL OpenBOutFile ( unOut, TRIM(FileName), ErrStat, ErrMsg ) IF (ErrStat /= ErrID_None) RETURN ! Add a file identification number (in case we ever have to change this): WRITE( unOut, IOSTAT=ErrStat ) File_ID ! Add how many blade meshes there are: NumBl = SIZE(y_ED%BladeLn2Mesh,1) ! Note that NumBl is B4Ki WRITE( unOut, IOSTAT=ErrStat ) NumBl NumBl = SIZE(y_BD,1) ! Note that NumBl is B4Ki WRITE( unOut, IOSTAT=ErrStat ) NumBl end if WRITE( unOut, IOSTAT=ErrStat ) t ! Add all of the meshes with motions: DO K_local = 1,SIZE(y_ED%BladeLn2Mesh,1) CALL MeshWrBin( unOut, y_ED%BladeLn2Mesh(K_local), ErrStat, ErrMsg ) END DO CALL MeshWrBin( unOut, y_ED%TowerLn2Mesh, ErrStat, ErrMsg ) CALL MeshWrBin( unOut, y_ED%PlatformPtMesh, ErrStat, ErrMsg ) CALL MeshWrBin( unOut, u_SD%TPMesh, ErrStat, ErrMsg ) CALL MeshWrBin( unOut, y_SD%y2Mesh, ErrStat, ErrMsg ) CALL MeshWrBin( unOut, u_HD%Morison%Mesh, ErrStat, ErrMsg ) CALL MeshWrBin( unOut, u_HD%WAMITMesh, ErrStat, ErrMsg ) CALL MeshWrBin( unOut, u_MAP%PtFairDisplacement, ErrStat, ErrMsg ) DO K_local = 1,SIZE(y_BD,1) CALL MeshWrBin( unOut, u_BD(K_local)%RootMotion, ErrStat, ErrMsg ) CALL MeshWrBin( unOut, y_BD(K_local)%BldMotion, ErrStat, ErrMsg ) END DO ! ! ! Close the file !CLOSE(unOut) ! END SUBROUTINE WriteMotionMeshesToFile !---------------------------------------------------------------------------------------------------------------------------------- !++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ! Linerization routines !++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ !> Routine that calls FAST_Linearize_T for an array of Turbine data structures if the linearization flag is set for each individual turbine. SUBROUTINE FAST_Linearize_Tary(t_initial, n_t_global, Turbine, ErrStat, ErrMsg) REAL(DbKi), INTENT(IN ) :: t_initial !< initial simulation time (almost always 0) INTEGER(IntKi), INTENT(IN ) :: n_t_global !< integer time step TYPE(FAST_TurbineType), INTENT(INOUT) :: Turbine(:) !< all data for one instance of a turbine INTEGER(IntKi), INTENT( OUT) :: ErrStat !< Error status of the operation CHARACTER(*), INTENT( OUT) :: ErrMsg !< Error message if ErrStat /= ErrID_None ! local variables INTEGER(IntKi) :: i_turb, NumTurbines INTEGER(IntKi) :: ErrStat2 ! local error status CHARACTER(ErrMsgLen) :: ErrMsg2 ! local error message CHARACTER(*), PARAMETER :: RoutineName = 'FAST_Linearize_Tary' NumTurbines = SIZE(Turbine) ErrStat = ErrID_None ErrMsg = "" DO i_turb = 1,NumTurbines CALL FAST_Linearize_T(t_initial, n_t_global, Turbine(i_turb), ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) IF (ErrStat >= AbortErrLev) RETURN END DO END SUBROUTINE FAST_Linearize_Tary !---------------------------------------------------------------------------------------------------------------------------------- !> Routine that performs lineaization at an operating point for a turbine. This is a separate subroutine so that the FAST !! driver programs do not need to change or operate on the individual module level. SUBROUTINE FAST_Linearize_T(t_initial, n_t_global, Turbine, ErrStat, ErrMsg) REAL(DbKi), INTENT(IN ) :: t_initial !< initial simulation time (almost always 0) INTEGER(IntKi), INTENT(IN ) :: n_t_global !< integer time step TYPE(FAST_TurbineType), INTENT(INOUT) :: Turbine !< all data for one instance of a turbine INTEGER(IntKi), INTENT( OUT) :: ErrStat !< Error status of the operation CHARACTER(*), INTENT( OUT) :: ErrMsg !< Error message if ErrStat /= ErrID_None ! local variables REAL(DbKi) :: t_global ! current simulation time REAL(DbKi) :: next_lin_time ! next simulation time where linearization analysis should be performed INTEGER(IntKi) :: iLinTime ! loop counter INTEGER(IntKi) :: ErrStat2 ! local error status CHARACTER(ErrMsgLen) :: ErrMsg2 ! local error message CHARACTER(*), PARAMETER :: RoutineName = 'FAST_Linearize_T' ErrStat = ErrID_None ErrMsg = "" if ( .not. Turbine%p_FAST%Linearize ) return if (.not. Turbine%p_FAST%CalcSteady) then if ( Turbine%m_FAST%Lin%NextLinTimeIndx <= Turbine%p_FAST%NLinTimes ) then !bjj: maybe this logic should go in FAST_Linearize_OP??? next_lin_time = Turbine%m_FAST%Lin%LinTimes( Turbine%m_FAST%Lin%NextLinTimeIndx ) t_global = t_initial + n_t_global*Turbine%p_FAST%dt if ( EqualRealNos( t_global, next_lin_time ) .or. t_global > next_lin_time ) then CALL FAST_Linearize_OP(t_global, Turbine%p_FAST, Turbine%y_FAST, Turbine%m_FAST, & Turbine%ED, Turbine%BD, Turbine%SrvD, Turbine%AD, Turbine%IfW, Turbine%OpFM, & Turbine%HD, Turbine%SD, Turbine%ExtPtfm, Turbine%MAP, Turbine%FEAM, Turbine%MD, Turbine%Orca, & Turbine%IceF, Turbine%IceD, Turbine%MeshMapData, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) IF (ErrStat >= AbortErrLev) RETURN if (Turbine%p_FAST%WrVTK == VTK_ModeShapes) then if (Turbine%m_FAST%Lin%NextLinTimeIndx > Turbine%p_FAST%NLinTimes) call WrVTKCheckpoint() end if end if end if else ! CalcSteady t_global = t_initial + n_t_global*Turbine%p_FAST%dt call FAST_CalcSteady( n_t_global, t_global, Turbine%p_FAST, Turbine%y_FAST, Turbine%m_FAST, Turbine%ED, Turbine%BD, Turbine%SrvD, & Turbine%AD, Turbine%IfW, Turbine%OpFM, Turbine%HD, Turbine%SD, Turbine%ExtPtfm, Turbine%MAP, Turbine%FEAM, Turbine%MD, & Turbine%Orca, Turbine%IceF, Turbine%IceD, ErrStat2, ErrMsg2 ) call SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) if (Turbine%m_FAST%Lin%FoundSteady) then do iLinTime=1,Turbine%p_FAST%NLinTimes t_global = Turbine%m_FAST%Lin%LinTimes(iLinTime) call SetOperatingPoint(iLinTime, Turbine%p_FAST, Turbine%y_FAST, Turbine%m_FAST, Turbine%ED, Turbine%BD, Turbine%SrvD, & Turbine%AD, Turbine%IfW, Turbine%OpFM, Turbine%HD, Turbine%SD, Turbine%ExtPtfm, & Turbine%MAP, Turbine%FEAM, Turbine%MD, Turbine%Orca, Turbine%IceF, Turbine%IceD, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) if (Turbine%p_FAST%DT_UJac < Turbine%p_FAST%TMax) then Turbine%m_FAST%calcJacobian = .true. Turbine%m_FAST%NextJacCalcTime = t_global end if CALL CalcOutputs_And_SolveForInputs( -1, t_global, STATE_CURR, Turbine%m_FAST%calcJacobian, Turbine%m_FAST%NextJacCalcTime, & Turbine%p_FAST, Turbine%m_FAST, .false., Turbine%ED, Turbine%BD, Turbine%SrvD, Turbine%AD14, Turbine%AD, Turbine%IfW, Turbine%OpFM, & Turbine%HD, Turbine%SD, Turbine%ExtPtfm, Turbine%MAP, Turbine%FEAM, Turbine%MD, Turbine%Orca, Turbine%IceF, Turbine%IceD, Turbine%MeshMapData, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) IF (ErrStat >= AbortErrLev) RETURN CALL FAST_Linearize_OP(t_global, Turbine%p_FAST, Turbine%y_FAST, Turbine%m_FAST, & Turbine%ED, Turbine%BD, Turbine%SrvD, Turbine%AD, Turbine%IfW, Turbine%OpFM, & Turbine%HD, Turbine%SD, Turbine%ExtPtfm, Turbine%MAP, Turbine%FEAM, Turbine%MD, Turbine%Orca, & Turbine%IceF, Turbine%IceD, Turbine%MeshMapData, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) IF (ErrStat >= AbortErrLev) RETURN end do if (Turbine%p_FAST%WrVTK == VTK_ModeShapes) CALL WrVTKCheckpoint() end if end if return contains subroutine WrVTKCheckpoint() ! we are creating a checkpoint file for each turbine, so setting NumTurbines=1 in the file CALL FAST_CreateCheckpoint_T(t_initial, Turbine%p_FAST%n_TMax_m1+1, 1, Turbine, TRIM(Turbine%p_FAST%OutFileRoot)//'.ModeShapeVTK', ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) end subroutine WrVTKCheckpoint END SUBROUTINE FAST_Linearize_T !---------------------------------------------------------------------------------------------------------------------------------- !++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ! PROGRAM EXIT ROUTINES !++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ !> Routine that calls ExitThisProgram for one instance of a Turbine data structure. This is a separate subroutine so that the FAST !! driver programs do not need to change or operate on the individual module level. !! This routine should be called from glue code only (e.g., FAST_Prog.f90). It should not be called in any of these driver routines. SUBROUTINE ExitThisProgram_T( Turbine, ErrLevel_in, StopTheProgram, ErrLocMsg, SkipRunTimeMsg ) TYPE(FAST_TurbineType), INTENT(INOUT) :: Turbine !< Data for one turbine instance INTEGER(IntKi), INTENT(IN) :: ErrLevel_in !< Error level when Error == .TRUE. (required when Error is .TRUE.) LOGICAL, INTENT(IN) :: StopTheProgram !< flag indicating if the program should end (false if there are more turbines to end) CHARACTER(*), OPTIONAL, INTENT(IN) :: ErrLocMsg !< an optional message describing the location of the error LOGICAL, OPTIONAL, INTENT(IN) :: SkipRunTimeMsg !< an optional message describing run-time stats LOGICAL :: SkipRunTimes IF (PRESENT(SkipRunTimeMsg)) THEN SkipRunTimes = SkipRunTimeMsg ELSE SkipRunTimes = .FALSE. END IF IF (PRESENT(ErrLocMsg)) THEN CALL ExitThisProgram( Turbine%p_FAST, Turbine%y_FAST, Turbine%m_FAST, & Turbine%ED, Turbine%BD, Turbine%SrvD, Turbine%AD14, Turbine%AD, Turbine%IfW, Turbine%OpFM, & Turbine%HD, Turbine%SD, Turbine%ExtPtfm, Turbine%MAP, Turbine%FEAM, Turbine%MD, Turbine%Orca, & Turbine%IceF, Turbine%IceD, Turbine%MeshMapData, ErrLevel_in, StopTheProgram, ErrLocMsg, SkipRunTimes ) ELSE CALL ExitThisProgram( Turbine%p_FAST, Turbine%y_FAST, Turbine%m_FAST, & Turbine%ED, Turbine%BD, Turbine%SrvD, Turbine%AD14, Turbine%AD, Turbine%IfW, Turbine%OpFM, & Turbine%HD, Turbine%SD, Turbine%ExtPtfm, Turbine%MAP, Turbine%FEAM, Turbine%MD, Turbine%Orca, & Turbine%IceF, Turbine%IceD, Turbine%MeshMapData, ErrLevel_in, StopTheProgram, SkipRunTimeMsg=SkipRunTimes ) END IF END SUBROUTINE ExitThisProgram_T !---------------------------------------------------------------------------------------------------------------------------------- !> This subroutine is called when FAST exits. It calls all the modules' end routines and cleans up variables declared in the !! main program. If there was an error, it also aborts. Otherwise, it prints the run times and performs a normal exit. !! This routine should not be called from glue code (e.g., FAST_Prog.f90) or ExitThisProgram_T only. It should not be called in any !! of these driver routines. SUBROUTINE ExitThisProgram( p_FAST, y_FAST, m_FAST, ED, BD, SrvD, AD14, AD, IfW, OpFM, HD, SD, ExtPtfm, & MAPp, FEAM, MD, Orca, IceF, IceD, MeshMapData, ErrLevel_in, StopTheProgram, ErrLocMsg, SkipRunTimeMsg ) !............................................................................................................................... ! Passed arguments TYPE(FAST_ParameterType), INTENT(INOUT) :: p_FAST !< Parameters for the glue code TYPE(FAST_OutputFileType),INTENT(INOUT) :: y_FAST !< Output variables for the glue code TYPE(FAST_MiscVarType), INTENT(INOUT) :: m_FAST !< Miscellaneous variables TYPE(ElastoDyn_Data), INTENT(INOUT) :: ED !< ElastoDyn data TYPE(BeamDyn_Data), INTENT(INOUT) :: BD !< BeamDyn data TYPE(ServoDyn_Data), INTENT(INOUT) :: SrvD !< ServoDyn data TYPE(AeroDyn14_Data), INTENT(INOUT) :: AD14 !< AeroDyn v14 data TYPE(AeroDyn_Data), INTENT(INOUT) :: AD !< AeroDyn data TYPE(InflowWind_Data), INTENT(INOUT) :: IfW !< InflowWind data TYPE(OpenFOAM_Data), INTENT(INOUT) :: OpFM !< OpenFOAM data TYPE(HydroDyn_Data), INTENT(INOUT) :: HD !< HydroDyn data TYPE(SubDyn_Data), INTENT(INOUT) :: SD !< SubDyn data TYPE(ExtPtfm_Data), INTENT(INOUT) :: ExtPtfm !< ExtPtfm_MCKF data TYPE(MAP_Data), INTENT(INOUT) :: MAPp !< MAP data TYPE(FEAMooring_Data), INTENT(INOUT) :: FEAM !< FEAMooring data TYPE(MoorDyn_Data), INTENT(INOUT) :: MD !< Data for the MoorDyn module TYPE(OrcaFlex_Data), INTENT(INOUT) :: Orca !< OrcaFlex interface data TYPE(IceFloe_Data), INTENT(INOUT) :: IceF !< IceFloe data TYPE(IceDyn_Data), INTENT(INOUT) :: IceD !< All the IceDyn data used in time-step loop TYPE(FAST_ModuleMapType), INTENT(INOUT) :: MeshMapData !< Data for mapping between modules INTEGER(IntKi), INTENT(IN) :: ErrLevel_in !< Error level when Error == .TRUE. (required when Error is .TRUE.) LOGICAL, INTENT(IN) :: StopTheProgram !< flag indicating if the program should end (false if there are more turbines to end) CHARACTER(*), OPTIONAL, INTENT(IN) :: ErrLocMsg !< an optional message describing the location of the error LOGICAL, OPTIONAL, INTENT(IN) :: SkipRunTimeMsg !< an optional message describing run-time stats ! Local variables: INTEGER(IntKi) :: ErrorLevel LOGICAL :: PrintRunTimes INTEGER(IntKi) :: ErrStat2 ! Error status CHARACTER(ErrMsgLen) :: ErrMsg2 ! Error message CHARACTER(1224) :: SimMsg ! optional message to print about where the error took place in the simulation CHARACTER(*), PARAMETER :: RoutineName = 'ExitThisProgram' ErrorLevel = ErrLevel_in ! for debugging, let's output the meshes and all of their fields IF ( ErrorLevel >= AbortErrLev .AND. p_FAST%WrVTK > VTK_None) THEN p_FAST%VTK_OutFileRoot = trim(p_FAST%VTK_OutFileRoot)//'.DebugError' p_FAST%VTK_fields = .true. CALL WrVTK_AllMeshes(p_FAST, y_FAST, MeshMapData, ED, BD, AD, IfW, OpFM, HD, SD, ExtPtfm, SrvD, MAPp, FEAM, MD, Orca, IceF, IceD) end if ! End all modules CALL FAST_EndMods( p_FAST, y_FAST, m_FAST, ED, BD, SrvD, AD14, AD, IfW, HD, SD, ExtPtfm, MAPp, FEAM, MD, Orca, IceF, IceD, ErrStat2, ErrMsg2 ) IF (ErrStat2 /= ErrID_None) THEN CALL WrScr( NewLine//RoutineName//':'//TRIM(ErrMsg2)//NewLine ) ErrorLevel = MAX(ErrorLevel,ErrStat2) END IF ! Destroy all data associated with FAST variables: CALL FAST_DestroyAll( p_FAST, y_FAST, m_FAST, ED, BD, SrvD, AD14, AD, IfW, OpFM, HD, SD, ExtPtfm, MAPp, FEAM, MD, Orca, IceF, IceD, MeshMapData, ErrStat2, ErrMsg2 ) IF (ErrStat2 /= ErrID_None) THEN CALL WrScr( NewLine//RoutineName//':'//TRIM(ErrMsg2)//NewLine ) ErrorLevel = MAX(ErrorLevel,ErrStat2) END IF !............................................................................................................................ ! Set exit error code if there was an error; !............................................................................................................................ IF ( ErrorLevel >= AbortErrLev ) THEN IF (PRESENT(ErrLocMsg)) THEN SimMsg = ErrLocMsg ELSE SimMsg = 'after the simulation completed' END IF IF (y_FAST%UnSum > 0) THEN CLOSE(y_FAST%UnSum) y_FAST%UnSum = -1 END IF SimMsg = 'FAST encountered an error '//TRIM(SimMsg)//'.'//NewLine//' Simulation error level: '//TRIM(GetErrStr(ErrorLevel)) if (StopTheProgram) then CALL ProgAbort( trim(SimMsg), TrapErrors=.FALSE., TimeWait=3._ReKi ) ! wait 3 seconds (in case they double-clicked and got an error) else CALL WrScr(trim(SimMsg)) end if END IF !............................................................................................................................ ! Write simulation times and stop !............................................................................................................................ if (present(SkipRunTimeMsg)) then PrintRunTimes = .not. SkipRunTimeMsg else PrintRunTimes = .true. end if IF (p_FAST%WrSttsTime .and. PrintRunTimes) THEN CALL RunTimes( m_FAST%StrtTime, m_FAST%UsrTime1, m_FAST%SimStrtTime, m_FAST%UsrTime2, m_FAST%t_global, UnSum=y_FAST%UnSum, DescStrIn=p_FAST%TDesc ) END IF IF (y_FAST%UnSum > 0) THEN CLOSE(y_FAST%UnSum) y_FAST%UnSum = -1 END IF if (StopTheProgram) then #if (defined COMPILE_SIMULINK || defined COMPILE_LABVIEW) ! for Simulink, this may not be a normal stop. It might call this after an error in the model. CALL WrScr( NewLine//' '//TRIM(FAST_Ver%Name)//' completed.'//NewLine ) #else CALL NormStop( ) #endif end if END SUBROUTINE ExitThisProgram !---------------------------------------------------------------------------------------------------------------------------------- !> This subroutine is called at program termination. It writes any additional output files, !! deallocates variables for FAST file I/O and closes files. SUBROUTINE FAST_EndOutput( p_FAST, y_FAST, m_FAST, ErrStat, ErrMsg ) TYPE(FAST_ParameterType), INTENT(INOUT) :: p_FAST !< FAST Parameters TYPE(FAST_OutputFileType),INTENT(INOUT) :: y_FAST !< FAST Output TYPE(FAST_MiscVarType), INTENT(IN ) :: m_FAST !< Miscellaneous variables (only for the final time) INTEGER(IntKi), INTENT(OUT) :: ErrStat !< Error status CHARACTER(*), INTENT(OUT) :: ErrMsg !< Message associated with errro status ! local variables CHARACTER(LEN(y_FAST%FileDescLines)*3) :: FileDesc ! The description of the run, to be written in the binary output file ! Initialize some values ErrStat = ErrID_None ErrMsg = '' !------------------------------------------------------------------------------------------------- ! Write the binary output file if requested !------------------------------------------------------------------------------------------------- IF (p_FAST%WrBinOutFile .AND. y_FAST%n_Out > 0) THEN FileDesc = TRIM(y_FAST%FileDescLines(1))//' '//TRIM(y_FAST%FileDescLines(2))//'; '//TRIM(y_FAST%FileDescLines(3)) CALL WrBinFAST(TRIM(p_FAST%OutFileRoot)//'.outb', Int(p_FAST%WrBinMod, B2Ki), TRIM(FileDesc), & y_FAST%ChannelNames, y_FAST%ChannelUnits, y_FAST%TimeData, y_FAST%AllOutData(:,1:y_FAST%n_Out), ErrStat, ErrMsg) IF ( ErrStat /= ErrID_None ) CALL WrScr( TRIM(GetErrStr(ErrStat))//' when writing binary output file: '//TRIM(ErrMsg) ) END IF !------------------------------------------------------------------------------------------------- ! Close the text tabular output file and summary file (if opened) !------------------------------------------------------------------------------------------------- IF (y_FAST%UnOu > 0) THEN ! I/O unit number for the tabular output file CLOSE( y_FAST%UnOu ) y_FAST%UnOu = -1 END IF IF (y_FAST%UnSum > 0) THEN ! I/O unit number for the tabular output file CLOSE( y_FAST%UnSum ) y_FAST%UnSum = -1 END IF IF (y_FAST%UnGra > 0) THEN ! I/O unit number for the graphics output file CLOSE( y_FAST%UnGra ) y_FAST%UnGra = -1 END IF !------------------------------------------------------------------------------------------------- ! Deallocate arrays !------------------------------------------------------------------------------------------------- ! Output IF ( ALLOCATED(y_FAST%AllOutData ) ) DEALLOCATE(y_FAST%AllOutData ) IF ( ALLOCATED(y_FAST%TimeData ) ) DEALLOCATE(y_FAST%TimeData ) IF ( ALLOCATED(y_FAST%ChannelNames ) ) DEALLOCATE(y_FAST%ChannelNames ) IF ( ALLOCATED(y_FAST%ChannelUnits ) ) DEALLOCATE(y_FAST%ChannelUnits ) END SUBROUTINE FAST_EndOutput !---------------------------------------------------------------------------------------------------------------------------------- !> This routine calls the end routines for each module that was previously initialized. SUBROUTINE FAST_EndMods( p_FAST, y_FAST, m_FAST, ED, BD, SrvD, AD14, AD, IfW, HD, SD, ExtPtfm, MAPp, FEAM, MD, Orca, IceF, IceD, ErrStat, ErrMsg ) TYPE(FAST_ParameterType), INTENT(INOUT) :: p_FAST !< Parameters for the glue code TYPE(FAST_OutputFileType),INTENT(INOUT) :: y_FAST !< Output variables for the glue code TYPE(FAST_MiscVarType), INTENT(INOUT) :: m_FAST !< Miscellaneous variables TYPE(ElastoDyn_Data), INTENT(INOUT) :: ED !< ElastoDyn data TYPE(BeamDyn_Data), INTENT(INOUT) :: BD !< BeamDyn data TYPE(ServoDyn_Data), INTENT(INOUT) :: SrvD !< ServoDyn data TYPE(AeroDyn14_Data), INTENT(INOUT) :: AD14 !< AeroDyn v14 data TYPE(AeroDyn_Data), INTENT(INOUT) :: AD !< AeroDyn data TYPE(InflowWind_Data), INTENT(INOUT) :: IfW !< InflowWind data TYPE(HydroDyn_Data), INTENT(INOUT) :: HD !< HydroDyn data TYPE(SubDyn_Data), INTENT(INOUT) :: SD !< SubDyn data TYPE(ExtPtfm_Data), INTENT(INOUT) :: ExtPtfm !< ExtPtfm data TYPE(MAP_Data), INTENT(INOUT) :: MAPp !< MAP data TYPE(FEAMooring_Data), INTENT(INOUT) :: FEAM !< FEAMooring data TYPE(MoorDyn_Data), INTENT(INOUT) :: MD !< Data for the MoorDyn module TYPE(OrcaFlex_Data), INTENT(INOUT) :: Orca !< OrcaFlex interface data TYPE(IceFloe_Data), INTENT(INOUT) :: IceF !< IceFloe data TYPE(IceDyn_Data), INTENT(INOUT) :: IceD !< All the IceDyn data used in time-step loop INTEGER(IntKi), INTENT( OUT) :: ErrStat !< Error status of the operation CHARACTER(*), INTENT( OUT) :: ErrMsg !< Error message if ErrStat /= ErrID_None ! local variables INTEGER(IntKi) :: i, k ! loop counter INTEGER(IntKi) :: ErrStat2 CHARACTER(ErrMsgLen) :: ErrMsg2 CHARACTER(*), PARAMETER :: RoutineName = 'FAST_EndMods' !............................................................................................................................... ! End all modules (and write binary FAST output file) !............................................................................................................................... ErrStat = ErrID_None ErrMsg = "" CALL FAST_EndOutput( p_FAST, y_FAST, m_FAST, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) IF ( p_FAST%ModuleInitialized(Module_ED) ) THEN CALL ED_End( ED%Input(1), ED%p, ED%x(STATE_CURR), ED%xd(STATE_CURR), ED%z(STATE_CURR), ED%OtherSt(STATE_CURR), & ED%y, ED%m, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) END IF IF ( p_FAST%ModuleInitialized(Module_BD) ) THEN DO k=1,p_FAST%nBeams CALL BD_End(BD%Input(1,k), BD%p(k), BD%x(k,STATE_CURR), BD%xd(k,STATE_CURR), BD%z(k,STATE_CURR), & BD%OtherSt(k,STATE_CURR), BD%y(k), BD%m(k), ErrStat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) END DO END IF IF ( p_FAST%ModuleInitialized(Module_AD14) ) THEN CALL AD14_End( AD14%Input(1), AD14%p, AD14%x(STATE_CURR), AD14%xd(STATE_CURR), AD14%z(STATE_CURR), & AD14%OtherSt(STATE_CURR), AD14%y, AD14%m, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) ELSEIF ( p_FAST%ModuleInitialized(Module_AD) ) THEN CALL AD_End( AD%Input(1), AD%p, AD%x(STATE_CURR), AD%xd(STATE_CURR), AD%z(STATE_CURR), & AD%OtherSt(STATE_CURR), AD%y, AD%m, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) END IF IF ( p_FAST%ModuleInitialized(Module_IfW) ) THEN CALL InflowWind_End( IfW%Input(1), IfW%p, IfW%x(STATE_CURR), IfW%xd(STATE_CURR), IfW%z(STATE_CURR), IfW%OtherSt(STATE_CURR), & IfW%y, IfW%m, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) END IF IF ( p_FAST%ModuleInitialized(Module_SrvD) ) THEN CALL SrvD_End( SrvD%Input(1), SrvD%p, SrvD%x(STATE_CURR), SrvD%xd(STATE_CURR), SrvD%z(STATE_CURR), SrvD%OtherSt(STATE_CURR), & SrvD%y, SrvD%m, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) END IF IF ( p_FAST%ModuleInitialized(Module_HD) ) THEN CALL HydroDyn_End( HD%Input(1), HD%p, HD%x(STATE_CURR), HD%xd(STATE_CURR), HD%z(STATE_CURR), HD%OtherSt(STATE_CURR), & HD%y, HD%m, ErrStat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) END IF IF ( p_FAST%ModuleInitialized(Module_SD) ) THEN CALL SD_End( SD%Input(1), SD%p, SD%x(STATE_CURR), SD%xd(STATE_CURR), SD%z(STATE_CURR), SD%OtherSt(STATE_CURR), & SD%y, SD%m, ErrStat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) ELSE IF ( p_FAST%ModuleInitialized(Module_ExtPtfm) ) THEN CALL ExtPtfm_End( ExtPtfm%Input(1), ExtPtfm%p, ExtPtfm%x(STATE_CURR), ExtPtfm%xd(STATE_CURR), ExtPtfm%z(STATE_CURR), & ExtPtfm%OtherSt(STATE_CURR), ExtPtfm%y, ExtPtfm%m, ErrStat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) END IF IF ( p_FAST%ModuleInitialized(Module_MAP) ) THEN CALL MAP_End( MAPp%Input(1), MAPp%p, MAPp%x(STATE_CURR), MAPp%xd(STATE_CURR), MAPp%z(STATE_CURR), MAPp%OtherSt, & MAPp%y, ErrStat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) ELSEIF ( p_FAST%ModuleInitialized(Module_MD) ) THEN CALL MD_End( MD%Input(1), MD%p, MD%x(STATE_CURR), MD%xd(STATE_CURR), MD%z(STATE_CURR), MD%OtherSt(STATE_CURR), & MD%y, MD%m, ErrStat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) ELSEIF ( p_FAST%ModuleInitialized(Module_FEAM) ) THEN CALL FEAM_End( FEAM%Input(1), FEAM%p, FEAM%x(STATE_CURR), FEAM%xd(STATE_CURR), FEAM%z(STATE_CURR), & FEAM%OtherSt(STATE_CURR), FEAM%y, FEAM%m, ErrStat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) ELSEIF ( p_FAST%ModuleInitialized(Module_Orca) ) THEN CALL Orca_End( Orca%Input(1), Orca%p, Orca%x(STATE_CURR), Orca%xd(STATE_CURR), Orca%z(STATE_CURR), Orca%OtherSt(STATE_CURR), & Orca%y, Orca%m, ErrStat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) END IF IF ( p_FAST%ModuleInitialized(Module_IceF) ) THEN CALL IceFloe_End(IceF%Input(1), IceF%p, IceF%x(STATE_CURR), IceF%xd(STATE_CURR), IceF%z(STATE_CURR), & IceF%OtherSt(STATE_CURR), IceF%y, IceF%m, ErrStat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) ELSEIF ( p_FAST%ModuleInitialized(Module_IceD) ) THEN DO i=1,p_FAST%numIceLegs CALL IceD_End(IceD%Input(1,i), IceD%p(i), IceD%x(i,STATE_CURR), IceD%xd(i,STATE_CURR), IceD%z(i,STATE_CURR), & IceD%OtherSt(i,STATE_CURR), IceD%y(i), IceD%m(i), ErrStat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) END DO END IF END SUBROUTINE FAST_EndMods !---------------------------------------------------------------------------------------------------------------------------------- !> This routine calls the destroy routines for each module. (It is basically a duplicate of FAST_DestroyTurbineType().) SUBROUTINE FAST_DestroyAll( p_FAST, y_FAST, m_FAST, ED, BD, SrvD, AD14, AD, IfW, OpFM, HD, SD, ExtPtfm, & MAPp, FEAM, MD, Orca, IceF, IceD, MeshMapData, ErrStat, ErrMsg ) TYPE(FAST_ParameterType), INTENT(INOUT) :: p_FAST !< Parameters for the glue code TYPE(FAST_OutputFileType),INTENT(INOUT) :: y_FAST !< Output variables for the glue code TYPE(FAST_MiscVarType), INTENT(INOUT) :: m_FAST !< Miscellaneous variables TYPE(ElastoDyn_Data), INTENT(INOUT) :: ED !< ElastoDyn data TYPE(BeamDyn_Data), INTENT(INOUT) :: BD !< BeamDyn data TYPE(ServoDyn_Data), INTENT(INOUT) :: SrvD !< ServoDyn data TYPE(AeroDyn14_Data), INTENT(INOUT) :: AD14 !< AeroDyn v14 data TYPE(AeroDyn_Data), INTENT(INOUT) :: AD !< AeroDyn data TYPE(InflowWind_Data), INTENT(INOUT) :: IfW !< InflowWind data TYPE(OpenFOAM_Data), INTENT(INOUT) :: OpFM !< OpenFOAM data TYPE(HydroDyn_Data), INTENT(INOUT) :: HD !< HydroDyn data TYPE(SubDyn_Data), INTENT(INOUT) :: SD !< SubDyn data TYPE(ExtPtfm_Data), INTENT(INOUT) :: ExtPtfm !< ExtPtfm data TYPE(MAP_Data), INTENT(INOUT) :: MAPp !< MAP data TYPE(FEAMooring_Data), INTENT(INOUT) :: FEAM !< FEAMooring data TYPE(MoorDyn_Data), INTENT(INOUT) :: MD !< Data for the MoorDyn module TYPE(OrcaFlex_Data), INTENT(INOUT) :: Orca !< OrcaFlex interface data TYPE(IceFloe_Data), INTENT(INOUT) :: IceF !< IceFloe data TYPE(IceDyn_Data), INTENT(INOUT) :: IceD !< All the IceDyn data used in time-step loop TYPE(FAST_ModuleMapType), INTENT(INOUT) :: MeshMapData !< Data for mapping between modules INTEGER(IntKi), INTENT( OUT) :: ErrStat !< Error status of the operation CHARACTER(*), INTENT( OUT) :: ErrMsg !< Error message if ErrStat /= ErrID_None ! local variables INTEGER(IntKi) :: ErrStat2 CHARACTER(ErrMsgLen) :: ErrMsg2 CHARACTER(*), PARAMETER :: RoutineName = 'FAST_DestroyAll' ! ------------------------------------------------------------------------- ! Deallocate/Destroy structures associated with mesh mapping ! ------------------------------------------------------------------------- ErrStat = ErrID_None ErrMsg = "" ! FAST CALL FAST_DestroyParam( p_FAST, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) CALL FAST_DestroyOutputFileType( y_FAST, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) CALL FAST_DestroyMisc( m_FAST, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) ! ElastoDyn CALL FAST_DestroyElastoDyn_Data( ED, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) ! BeamDyn CALL FAST_DestroyBeamDyn_Data( BD, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) ! ServoDyn CALL FAST_DestroyServoDyn_Data( SrvD, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) ! AeroDyn14 CALL FAST_DestroyAeroDyn14_Data( AD14, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) ! AeroDyn CALL FAST_DestroyAeroDyn_Data( AD, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) ! InflowWind CALL FAST_DestroyInflowWind_Data( IfW, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) ! OpenFOAM CALL FAST_DestroyOpenFOAM_Data( OpFM, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) ! HydroDyn CALL FAST_DestroyHydroDyn_Data( HD, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) ! SubDyn CALL FAST_DestroySubDyn_Data( SD, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) ! ExtPtfm CALL FAST_DestroyExtPtfm_Data( ExtPtfm, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) ! MAP CALL FAST_DestroyMAP_Data( MAPp, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) ! FEAMooring CALL FAST_DestroyFEAMooring_Data( FEAM, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) ! MoorDyn CALL FAST_DestroyMoorDyn_Data( MD, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) ! Orca CALL FAST_DestroyOrcaFlex_Data( Orca, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) ! IceFloe CALL FAST_DestroyIceFloe_Data( IceF, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) ! IceDyn CALL FAST_DestroyIceDyn_Data( IceD, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) ! Module (Mesh) Mapping data CALL FAST_DestroyModuleMapType( MeshMapData, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName) END SUBROUTINE FAST_DestroyAll !---------------------------------------------------------------------------------------------------------------------------------- !++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ! CHECKPOINT/RESTART ROUTINES !++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ !> Routine that calls FAST_CreateCheckpoint_T for an array of Turbine data structures. SUBROUTINE FAST_CreateCheckpoint_Tary(t_initial, n_t_global, Turbine, CheckpointRoot, ErrStat, ErrMsg) REAL(DbKi), INTENT(IN ) :: t_initial !< initial time INTEGER(IntKi), INTENT(IN ) :: n_t_global !< loop counter TYPE(FAST_TurbineType), INTENT(INOUT) :: Turbine(:) !< all data for all turbines CHARACTER(*), INTENT(IN ) :: CheckpointRoot !< Rootname of checkpoint file INTEGER(IntKi), INTENT( OUT) :: ErrStat !< Error status of the operation CHARACTER(*), INTENT( OUT) :: ErrMsg !< Error message if ErrStat /= ErrID_None ! local variables INTEGER(IntKi) :: NumTurbines ! Number of turbines in this simulation INTEGER(IntKi) :: i_turb INTEGER :: Unit INTEGER(IntKi) :: ErrStat2 ! local error status CHARACTER(ErrMsgLen) :: ErrMsg2 ! local error message CHARACTER(*), PARAMETER :: RoutineName = 'FAST_CreateCheckpoint_Tary' NumTurbines = SIZE(Turbine) ErrStat = ErrID_None ErrMsg = "" ! TRIM(CheckpointRoot)//'.'//TRIM(Num2LStr(Turbine%TurbID))// !! This allows us to put all the turbine data in one file. Unit = -1 DO i_turb = 1,NumTurbines CALL FAST_CreateCheckpoint_T(t_initial, n_t_global, NumTurbines, Turbine(i_turb), CheckpointRoot, ErrStat2, ErrMsg2, Unit ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) if (ErrStat >= AbortErrLev ) then if (Unit > 0) close(Unit) RETURN end if END DO END SUBROUTINE FAST_CreateCheckpoint_Tary !---------------------------------------------------------------------------------------------------------------------------------- !> Routine that packs all of the data from one turbine instance into arrays and writes checkpoint files. If Unit is present and !! greater than 0, it will append the data to an already open file. Otherwise, it opens a new file and writes header information !! before writing the turbine data to the file. SUBROUTINE FAST_CreateCheckpoint_T(t_initial, n_t_global, NumTurbines, Turbine, CheckpointRoot, ErrStat, ErrMsg, Unit ) USE BladedInterface, ONLY: CallBladedDLL ! Hack for Bladed-style DLL USE BladedInterface, ONLY: GH_DISCON_STATUS_CHECKPOINT REAL(DbKi), INTENT(IN ) :: t_initial !< initial time INTEGER(IntKi), INTENT(IN ) :: n_t_global !< loop counter INTEGER(IntKi), INTENT(IN ) :: NumTurbines !< Number of turbines in this simulation TYPE(FAST_TurbineType), INTENT(INOUT) :: Turbine !< all data for one instance of a turbine (INTENT(OUT) only because of hack for Bladed DLL) CHARACTER(*), INTENT(IN ) :: CheckpointRoot !< Rootname of checkpoint file INTEGER(IntKi), INTENT( OUT) :: ErrStat !< Error status of the operation CHARACTER(*), INTENT( OUT) :: ErrMsg !< Error message if ErrStat /= ErrID_None INTEGER(IntKi), OPTIONAL, INTENT(INOUT) :: Unit !< unit number for output file ! local variables: REAL(ReKi), ALLOCATABLE :: ReKiBuf(:) REAL(DbKi), ALLOCATABLE :: DbKiBuf(:) INTEGER(IntKi), ALLOCATABLE :: IntKiBuf(:) INTEGER(B4Ki) :: ArraySizes(3) INTEGER(IntKi) :: unOut ! unit number for output file INTEGER(IntKi) :: old_avrSwap1 ! previous value of avrSwap(1) !hack for Bladed DLL checkpoint/restore INTEGER(IntKi) :: ErrStat2 ! local error status CHARACTER(ErrMsgLen) :: ErrMsg2 ! local error message CHARACTER(*), PARAMETER :: RoutineName = 'FAST_CreateCheckpoint_T' CHARACTER(1024) :: FileName ! Name of the (output) checkpoint file CHARACTER(1024) :: DLLFileName ! Name of the (output) checkpoint file ! init error status ErrStat = ErrID_None ErrMsg = "" ! Get the arrays of data to be stored in the output file CALL FAST_PackTurbineType( ReKiBuf, DbKiBuf, IntKiBuf, Turbine, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) if (ErrStat >= AbortErrLev ) then call cleanup() RETURN end if ArraySizes = 0 IF ( ALLOCATED(ReKiBuf) ) ArraySizes(1) = SIZE(ReKiBuf) IF ( ALLOCATED(DbKiBuf) ) ArraySizes(2) = SIZE(DbKiBuf) IF ( ALLOCATED(IntKiBuf) ) ArraySizes(3) = SIZE(IntKiBuf) FileName = TRIM(CheckpointRoot)//'.chkp' DLLFileName = TRIM(CheckpointRoot)//'.dll.chkp' unOut=-1 IF (PRESENT(Unit)) unOut = Unit IF ( unOut < 0 ) THEN CALL GetNewUnit( unOut, ErrStat2, ErrMsg2 ) CALL OpenBOutFile ( unOut, FileName, ErrStat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) if (ErrStat >= AbortErrLev ) then call cleanup() IF (.NOT. PRESENT(Unit)) THEN CLOSE(unOut) unOut = -1 END IF RETURN end if ! checkpoint file header: WRITE (unOut, IOSTAT=ErrStat2) INT(ReKi ,B4Ki) ! let's make sure we've got the correct number of bytes for reals on restart. WRITE (unOut, IOSTAT=ErrStat2) INT(DbKi ,B4Ki) ! let's make sure we've got the correct number of bytes for doubles on restart. WRITE (unOut, IOSTAT=ErrStat2) INT(IntKi ,B4Ki) ! let's make sure we've got the correct number of bytes for integers on restart. WRITE (unOut, IOSTAT=ErrStat2) AbortErrLev WRITE (unOut, IOSTAT=ErrStat2) NumTurbines ! Number of turbines WRITE (unOut, IOSTAT=ErrStat2) t_initial ! initial time WRITE (unOut, IOSTAT=ErrStat2) n_t_global ! current time step END IF ! data from current turbine at time step: WRITE (unOut, IOSTAT=ErrStat2) ArraySizes ! Number of reals, doubles, and integers written to file WRITE (unOut, IOSTAT=ErrStat2) ReKiBuf ! Packed reals WRITE (unOut, IOSTAT=ErrStat2) DbKiBuf ! Packed doubles WRITE (unOut, IOSTAT=ErrStat2) IntKiBuf ! Packed integers IF ( ALLOCATED(ReKiBuf) ) DEALLOCATE(ReKiBuf) IF ( ALLOCATED(DbKiBuf) ) DEALLOCATE(DbKiBuf) IF ( ALLOCATED(IntKiBuf) ) DEALLOCATE(IntKiBuf) !CALL FAST_CreateCheckpoint(t_initial, n_t_global, Turbine%p_FAST, Turbine%y_FAST, Turbine%m_FAST, & ! Turbine%ED, Turbine%SrvD, Turbine%AD, Turbine%IfW, & ! Turbine%HD, Turbine%SD, Turbine%MAP, Turbine%FEAM, Turbine%MD, & ! Turbine%IceF, Turbine%IceD, Turbine%MeshMapData, ErrStat, ErrMsg ) IF (Turbine%TurbID == NumTurbines .OR. .NOT. PRESENT(Unit)) THEN CLOSE(unOut) unOut = -1 END IF IF (PRESENT(Unit)) Unit = unOut ! A hack to pack Bladed-style DLL data IF (Turbine%SrvD%p%UseBladedInterface) THEN if (Turbine%SrvD%m%dll_data%avrSWAP( 1) > 0 ) then ! store value to be overwritten old_avrSwap1 = Turbine%SrvD%m%dll_data%avrSWAP( 1) FileName = Turbine%SrvD%m%dll_data%DLL_InFile ! overwrite values: Turbine%SrvD%m%dll_data%DLL_InFile = DLLFileName Turbine%SrvD%m%dll_data%avrSWAP(50) = REAL( LEN_TRIM(DLLFileName) ) +1 ! No. of characters in the "INFILE" argument (-) (we add one for the C NULL CHARACTER) Turbine%SrvD%m%dll_data%avrSWAP( 1) = GH_DISCON_STATUS_CHECKPOINT Turbine%SrvD%m%dll_data%SimStatus = Turbine%SrvD%m%dll_data%avrSWAP( 1) CALL CallBladedDLL(Turbine%SrvD%Input(1), Turbine%SrvD%p, Turbine%SrvD%m%dll_data, ErrStat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) ! put values back: Turbine%SrvD%m%dll_data%DLL_InFile = FileName Turbine%SrvD%m%dll_data%avrSWAP(50) = REAL( LEN_TRIM(FileName) ) +1 ! No. of characters in the "INFILE" argument (-) (we add one for the C NULL CHARACTER) Turbine%SrvD%m%dll_data%avrSWAP( 1) = old_avrSwap1 Turbine%SrvD%m%dll_data%SimStatus = Turbine%SrvD%m%dll_data%avrSWAP( 1) end if END IF call cleanup() contains subroutine cleanup() IF ( ALLOCATED(ReKiBuf) ) DEALLOCATE(ReKiBuf) IF ( ALLOCATED(DbKiBuf) ) DEALLOCATE(DbKiBuf) IF ( ALLOCATED(IntKiBuf) ) DEALLOCATE(IntKiBuf) end subroutine cleanup END SUBROUTINE FAST_CreateCheckpoint_T !---------------------------------------------------------------------------------------------------------------------------------- !> Routine that calls FAST_RestoreFromCheckpoint_T for an array of Turbine data structures. SUBROUTINE FAST_RestoreFromCheckpoint_Tary(t_initial, n_t_global, Turbine, CheckpointRoot, ErrStat, ErrMsg ) REAL(DbKi), INTENT(IN ) :: t_initial !< initial time (for comparing with time from checkpoint file) INTEGER(IntKi), INTENT( OUT) :: n_t_global !< loop counter TYPE(FAST_TurbineType), INTENT( OUT) :: Turbine(:) !< all data for one instance of a turbine CHARACTER(*), INTENT(IN ) :: CheckpointRoot !< Rootname of checkpoint file INTEGER(IntKi), INTENT( OUT) :: ErrStat !< Error status of the operation CHARACTER(*), INTENT( OUT) :: ErrMsg !< Error message if ErrStat /= ErrID_None ! local variables REAL(DbKi) :: t_initial_out INTEGER(IntKi) :: NumTurbines_out INTEGER(IntKi) :: NumTurbines ! Number of turbines in this simulation INTEGER(IntKi) :: i_turb INTEGER :: Unit INTEGER(IntKi) :: ErrStat2 ! local error status CHARACTER(ErrMsgLen) :: ErrMsg2 ! local error message CHARACTER(*), PARAMETER :: RoutineName = 'FAST_RestoreFromCheckpoint_Tary' NumTurbines = SIZE(Turbine) ErrStat = ErrID_None ErrMsg = "" ! Init NWTC_Library, display copyright and version information: CALL FAST_ProgStart( FAST_Ver ) ! Restore data from checkpoint file Unit = -1 DO i_turb = 1,NumTurbines CALL FAST_RestoreFromCheckpoint_T(t_initial_out, n_t_global, NumTurbines_out, Turbine(i_turb), CheckpointRoot, ErrStat2, ErrMsg2, Unit ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) IF (t_initial_out /= t_initial) CALL SetErrStat(ErrID_Fatal, "invalid value of t_initial.", ErrStat, ErrMsg, RoutineName ) IF (NumTurbines_out /= NumTurbines) CALL SetErrStat(ErrID_Fatal, "invalid value of NumTurbines.", ErrStat, ErrMsg, RoutineName ) IF (ErrStat >= AbortErrLev) RETURN END DO CALL WrScr( ' Restarting simulation at '//TRIM(Num2LStr(n_t_global*Turbine(1)%p_FAST%DT))//' seconds.' ) END SUBROUTINE FAST_RestoreFromCheckpoint_Tary !---------------------------------------------------------------------------------------------------------------------------------- !> This routine is the inverse of FAST_CreateCheckpoint_T. It reads data from a checkpoint file and populates data structures for !! the turbine instance. SUBROUTINE FAST_RestoreFromCheckpoint_T(t_initial, n_t_global, NumTurbines, Turbine, CheckpointRoot, ErrStat, ErrMsg, Unit ) USE BladedInterface, ONLY: CallBladedDLL ! Hack for Bladed-style DLL USE BladedInterface, ONLY: GH_DISCON_STATUS_RESTARTING REAL(DbKi), INTENT(INOUT) :: t_initial !< initial time INTEGER(IntKi), INTENT(INOUT) :: n_t_global !< loop counter INTEGER(IntKi), INTENT(INOUT) :: NumTurbines !< Number of turbines in this simulation TYPE(FAST_TurbineType), INTENT(INOUT) :: Turbine !< all data for one instance of a turbine (bjj: note that is intent INOUT instead of OUT only because of a gfortran compiler memory issue) CHARACTER(*), INTENT(IN ) :: CheckpointRoot !< Rootname of checkpoint file INTEGER(IntKi), INTENT( OUT) :: ErrStat !< Error status of the operation CHARACTER(*), INTENT( OUT) :: ErrMsg !< Error message if ErrStat /= ErrID_None INTEGER(IntKi), OPTIONAL, INTENT(INOUT) :: Unit !< unit number for output file ! local variables: REAL(ReKi), ALLOCATABLE :: ReKiBuf(:) REAL(DbKi), ALLOCATABLE :: DbKiBuf(:) INTEGER(IntKi), ALLOCATABLE :: IntKiBuf(:) INTEGER(B4Ki) :: ArraySizes(3) INTEGER(IntKi) :: unIn ! unit number for input file INTEGER(IntKi) :: old_avrSwap1 ! previous value of avrSwap(1) !hack for Bladed DLL checkpoint/restore INTEGER(IntKi) :: ErrStat2 ! local error status CHARACTER(ErrMsgLen) :: ErrMsg2 ! local error message CHARACTER(*), PARAMETER :: RoutineName = 'FAST_RestoreFromCheckpoint_T' CHARACTER(1024) :: FileName ! Name of the (input) checkpoint file CHARACTER(1024) :: DLLFileName ! Name of the (input) checkpoint file ErrStat=ErrID_None ErrMsg="" FileName = TRIM(CheckpointRoot)//'.chkp' DLLFileName = TRIM(CheckpointRoot)//'.dll.chkp' ! FileName = TRIM(CheckpointRoot)//'.cp' unIn=-1 IF (PRESENT(Unit)) unIn = Unit IF ( unIn < 0 ) THEN CALL GetNewUnit( unIn, ErrStat2, ErrMsg2 ) CALL OpenBInpFile ( unIn, FileName, ErrStat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) IF (ErrStat >= AbortErrLev ) RETURN ! checkpoint file header: READ (unIn, IOSTAT=ErrStat2) ArraySizes ! let's make sure we've got the correct number of bytes for reals, doubles, and integers on restart. IF ( ArraySizes(1) /= ReKi ) CALL SetErrStat(ErrID_Fatal,"ReKi on restart is different than when checkpoint file was created.",ErrStat,ErrMsg,RoutineName) IF ( ArraySizes(2) /= DbKi ) CALL SetErrStat(ErrID_Fatal,"DbKi on restart is different than when checkpoint file was created.",ErrStat,ErrMsg,RoutineName) IF ( ArraySizes(3) /= IntKi ) CALL SetErrStat(ErrID_Fatal,"IntKi on restart is different than when checkpoint file was created.",ErrStat,ErrMsg,RoutineName) IF (ErrStat >= AbortErrLev) THEN CLOSE(unIn) unIn = -1 IF (PRESENT(Unit)) Unit = unIn RETURN END IF READ (unIn, IOSTAT=ErrStat2) AbortErrLev READ (unIn, IOSTAT=ErrStat2) NumTurbines ! Number of turbines READ (unIn, IOSTAT=ErrStat2) t_initial ! initial time READ (unIn, IOSTAT=ErrStat2) n_t_global ! current time step END IF ! in case the Turbine data structure isn't empty on entry of this routine: call FAST_DestroyTurbineType( Turbine, ErrStat2, ErrMsg2 ) ! data from current time step: READ (unIn, IOSTAT=ErrStat2) ArraySizes ! Number of reals, doubles, and integers written to file ALLOCATE(ReKiBuf( ArraySizes(1)), STAT=ErrStat2) IF (ErrStat2 /=0) CALL SetErrStat(ErrID_Fatal, "Could not allocate ReKiBuf", ErrStat, ErrMsg, RoutineName ) ALLOCATE(DbKiBuf( ArraySizes(2)), STAT=ErrStat2) IF (ErrStat2 /=0) CALL SetErrStat(ErrID_Fatal, "Could not allocate DbKiBuf", ErrStat, ErrMsg, RoutineName ) ALLOCATE(IntKiBuf(ArraySizes(3)), STAT=ErrStat2) IF (ErrStat2 /=0) CALL SetErrStat(ErrID_Fatal, "Could not allocate IntKiBuf", ErrStat, ErrMsg, RoutineName ) ! Read the packed arrays IF (ErrStat < AbortErrLev) THEN READ (unIn, IOSTAT=ErrStat2) ReKiBuf ! Packed reals IF (ErrStat2 /=0) CALL SetErrStat(ErrID_Fatal, "Could not read ReKiBuf", ErrStat, ErrMsg, RoutineName ) READ (unIn, IOSTAT=ErrStat2) DbKiBuf ! Packed doubles IF (ErrStat2 /=0) CALL SetErrStat(ErrID_Fatal, "Could not read DbKiBuf", ErrStat, ErrMsg, RoutineName ) READ (unIn, IOSTAT=ErrStat2) IntKiBuf ! Packed integers IF (ErrStat2 /=0) CALL SetErrStat(ErrID_Fatal, "Could not read IntKiBuf", ErrStat, ErrMsg, RoutineName ) END IF ! Put the arrays back in the data types IF (ErrStat < AbortErrLev) THEN CALL FAST_UnpackTurbineType( ReKiBuf, DbKiBuf, IntKiBuf, Turbine, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) END IF ! close file if necessary (do this after unpacking turbine data, so that TurbID is set) IF (Turbine%TurbID == NumTurbines .OR. .NOT. PRESENT(Unit)) THEN CLOSE(unIn) unIn = -1 END IF IF (PRESENT(Unit)) Unit = unIn IF ( ALLOCATED(ReKiBuf) ) DEALLOCATE(ReKiBuf) IF ( ALLOCATED(DbKiBuf) ) DEALLOCATE(DbKiBuf) IF ( ALLOCATED(IntKiBuf) ) DEALLOCATE(IntKiBuf) ! A sort-of hack to restore MAP DLL data (in particular Turbine%MAP%OtherSt%C_Obj%object) ! these must be the same variables that are used in MAP_Init because they get allocated in the DLL and ! destroyed in MAP_End (also, inside the DLL) IF (Turbine%p_FAST%CompMooring == Module_MAP) THEN CALL MAP_Restart( Turbine%MAP%Input(1), Turbine%MAP%p, Turbine%MAP%x(STATE_CURR), Turbine%MAP%xd(STATE_CURR), & Turbine%MAP%z(STATE_CURR), Turbine%MAP%OtherSt, Turbine%MAP%y, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) END IF ! A hack to restore Bladed-style DLL data if (Turbine%SrvD%p%UseBladedInterface) then if (Turbine%SrvD%m%dll_data%avrSWAP( 1) > 0 ) then ! this isn't allocated if UseBladedInterface is FALSE ! store value to be overwritten old_avrSwap1 = Turbine%SrvD%m%dll_data%avrSWAP( 1) FileName = Turbine%SrvD%m%dll_data%DLL_InFile ! overwrite values before calling DLL: Turbine%SrvD%m%dll_data%DLL_InFile = DLLFileName Turbine%SrvD%m%dll_data%avrSWAP(50) = REAL( LEN_TRIM(DLLFileName) ) +1 ! No. of characters in the "INFILE" argument (-) (we add one for the C NULL CHARACTER) Turbine%SrvD%m%dll_data%avrSWAP( 1) = GH_DISCON_STATUS_RESTARTING Turbine%SrvD%m%dll_data%SimStatus = Turbine%SrvD%m%dll_data%avrSWAP( 1) CALL CallBladedDLL(Turbine%SrvD%Input(1), Turbine%SrvD%p, Turbine%SrvD%m%dll_data, ErrStat2, ErrMsg2) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) ! put values back: Turbine%SrvD%m%dll_data%DLL_InFile = FileName Turbine%SrvD%m%dll_data%avrSWAP(50) = REAL( LEN_TRIM(FileName) ) +1 ! No. of characters in the "INFILE" argument (-) (we add one for the C NULL CHARACTER) Turbine%SrvD%m%dll_data%avrSWAP( 1) = old_avrSwap1 Turbine%SrvD%m%dll_data%SimStatus = Turbine%SrvD%m%dll_data%avrSWAP( 1) end if end if ! deal with sibling meshes here: ! (ignoring for now; they are not going to be siblings on restart) ! deal with files that were open: IF (Turbine%p_FAST%WrTxtOutFile) THEN CALL OpenFunkFileAppend ( Turbine%y_FAST%UnOu, TRIM(Turbine%p_FAST%OutFileRoot)//'.out', ErrStat2, ErrMsg2) IF ( ErrStat2 >= AbortErrLev ) RETURN CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL WrFileNR ( Turbine%y_FAST%UnOu, '#Restarting here') WRITE(Turbine%y_FAST%UnOu, '()') END IF ! (ignoring for now; will have fort.x files if any were open [though I printed a warning about not outputting binary files earlier]) END SUBROUTINE FAST_RestoreFromCheckpoint_T !---------------------------------------------------------------------------------------------------------------------------------- !---------------------------------------------------------------------------------------------------------------------------------- !> Routine that calls FAST_RestoreForVTKModeShape_T for an array of Turbine data structures. SUBROUTINE FAST_RestoreForVTKModeShape_Tary(t_initial, Turbine, InputFileName, ErrStat, ErrMsg ) REAL(DbKi), INTENT(IN ) :: t_initial !< initial time (for comparing with time from checkpoint file) TYPE(FAST_TurbineType), INTENT( OUT) :: Turbine(:) !< all data for one instance of a turbine CHARACTER(*), INTENT(IN ) :: InputFileName !< Name of the input file INTEGER(IntKi), INTENT( OUT) :: ErrStat !< Error status of the operation CHARACTER(*), INTENT( OUT) :: ErrMsg !< Error message if ErrStat /= ErrID_None ! local variables INTEGER(IntKi) :: i_turb INTEGER(IntKi) :: n_t_global !< loop counter INTEGER(IntKi) :: NumTurbines ! Number of turbines in this simulation INTEGER(IntKi) :: ErrStat2 ! local error status CHARACTER(ErrMsgLen) :: ErrMsg2 ! local error message CHARACTER(*), PARAMETER :: RoutineName = 'FAST_RestoreForVTKModeShape_Tary' ErrStat = ErrID_None ErrMsg = "" NumTurbines = SIZE(Turbine) if (NumTurbines /=1) then call SetErrStat(ErrID_Fatal, "Mode-shape visualization is not available for multiple turbines.", ErrStat, ErrMsg, RoutineName) return end if CALL ReadModeShapeFile( Turbine(1)%p_FAST, trim(InputFileName), ErrStat2, ErrMsg2, checkpointOnly=.true. ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) if (ErrStat >= AbortErrLev) return CALL FAST_RestoreFromCheckpoint_Tary( t_initial, n_t_global, Turbine, trim(Turbine(1)%p_FAST%VTK_modes%CheckpointRoot), ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) DO i_turb = 1,NumTurbines if (.not. allocated(Turbine(i_turb)%m_FAST%Lin%LinTimes)) then call SetErrStat(ErrID_Fatal, "Mode-shape visualization requires a checkpoint file from a simulation with linearization analysis, but NLinTimes is 0.", ErrStat, ErrMsg, RoutineName) return end if CALL FAST_RestoreForVTKModeShape_T(t_initial, Turbine(i_turb)%p_FAST, Turbine(i_turb)%y_FAST, Turbine(i_turb)%m_FAST, & Turbine(i_turb)%ED, Turbine(i_turb)%BD, Turbine(i_turb)%SrvD, Turbine(i_turb)%AD14, Turbine(i_turb)%AD, Turbine(i_turb)%IfW, Turbine(i_turb)%OpFM, & Turbine(i_turb)%HD, Turbine(i_turb)%SD, Turbine(i_turb)%ExtPtfm, Turbine(i_turb)%MAP, Turbine(i_turb)%FEAM, Turbine(i_turb)%MD, Turbine(i_turb)%Orca, & Turbine(i_turb)%IceF, Turbine(i_turb)%IceD, Turbine(i_turb)%MeshMapData, trim(InputFileName), ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) END DO END SUBROUTINE FAST_RestoreForVTKModeShape_Tary !---------------------------------------------------------------------------------------------------------------------------------- !> This routine calculates the motions generated by mode shapes and outputs VTK data for it SUBROUTINE FAST_RestoreForVTKModeShape_T(t_initial, p_FAST, y_FAST, m_FAST, ED, BD, SrvD, AD14, AD, IfW, OpFM, HD, SD, ExtPtfm, & MAPp, FEAM, MD, Orca, IceF, IceD, MeshMapData, InputFileName, ErrStat, ErrMsg ) REAL(DbKi), INTENT(IN ) :: t_initial !< initial time TYPE(FAST_ParameterType), INTENT(INOUT) :: p_FAST !< Parameters for the glue code TYPE(FAST_OutputFileType),INTENT(INOUT) :: y_FAST !< Output variables for the glue code TYPE(FAST_MiscVarType), INTENT(INOUT) :: m_FAST !< Miscellaneous variables TYPE(ElastoDyn_Data), INTENT(INOUT) :: ED !< ElastoDyn data TYPE(BeamDyn_Data), INTENT(INOUT) :: BD !< BeamDyn data TYPE(ServoDyn_Data), INTENT(INOUT) :: SrvD !< ServoDyn data TYPE(AeroDyn14_Data), INTENT(INOUT) :: AD14 !< AeroDyn14 data TYPE(AeroDyn_Data), INTENT(INOUT) :: AD !< AeroDyn data TYPE(InflowWind_Data), INTENT(INOUT) :: IfW !< InflowWind data TYPE(OpenFOAM_Data), INTENT(INOUT) :: OpFM !< OpenFOAM data TYPE(HydroDyn_Data), INTENT(INOUT) :: HD !< HydroDyn data TYPE(SubDyn_Data), INTENT(INOUT) :: SD !< SubDyn data TYPE(ExtPtfm_Data), INTENT(INOUT) :: ExtPtfm !< ExtPtfm_MCKF data TYPE(MAP_Data), INTENT(INOUT) :: MAPp !< MAP data TYPE(FEAMooring_Data), INTENT(INOUT) :: FEAM !< FEAMooring data TYPE(MoorDyn_Data), INTENT(INOUT) :: MD !< Data for the MoorDyn module TYPE(OrcaFlex_Data), INTENT(INOUT) :: Orca !< OrcaFlex interface data TYPE(IceFloe_Data), INTENT(INOUT) :: IceF !< IceFloe data TYPE(IceDyn_Data), INTENT(INOUT) :: IceD !< All the IceDyn data used in time-step loop TYPE(FAST_ModuleMapType), INTENT(INOUT) :: MeshMapData !< Data for mapping between modules CHARACTER(*), INTENT(IN ) :: InputFileName !< Name of the input file INTEGER(IntKi), INTENT( OUT) :: ErrStat !< Error status of the operation CHARACTER(*), INTENT( OUT) :: ErrMsg !< Error message if ErrStat /= ErrID_None ! local variables REAL(DbKi) :: dt ! time REAL(DbKi) :: tprime ! time INTEGER(IntKi) :: nt INTEGER(IntKi) :: iLinTime ! generic loop counters INTEGER(IntKi) :: it ! generic loop counters INTEGER(IntKi) :: iMode ! generic loop counters INTEGER(IntKi) :: ModeNo ! mode number INTEGER(IntKi) :: NLinTimes INTEGER(IntKi) :: ErrStat2 CHARACTER(ErrMsgLen) :: ErrMsg2 CHARACTER(*), PARAMETER :: RoutineName = 'FAST_RestoreForVTKModeShape_T' CHARACTER(1024) :: VTK_RootName ErrStat = ErrID_None ErrMsg = "" CALL ReadModeShapeFile( p_FAST, trim(InputFileName), ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) if (ErrStat >= AbortErrLev) return call ReadModeShapeMatlabFile( p_FAST, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) if (ErrStat >= AbortErrLev ) return y_FAST%WriteThisStep = .true. y_FAST%UnSum = -1 NLinTimes = min( p_FAST%VTK_modes%VTKNLinTimes, size(p_FAST%VTK_modes%x_eig_magnitude,2), p_FAST%NLinTimes ) VTK_RootName = p_FAST%VTK_OutFileRoot select case (p_FAST%VTK_modes%VTKLinTim) case (1) do iMode = 1,p_FAST%VTK_modes%VTKLinModes ModeNo = p_FAST%VTK_modes%VTKModes(iMode) call GetTimeConstants(p_FAST%VTK_modes%DampedFreq_Hz(ModeNo), p_FAST%VTK_fps, nt, dt, p_FAST%VTK_tWidth ) if (nt > 500) cycle p_FAST%VTK_OutFileRoot = trim(VTK_RootName)//'.Mode'//trim(num2lstr(ModeNo)) y_FAST%VTK_count = 1 ! we are skipping the reference meshes by starting at 1 do iLinTime = 1,NLinTimes tprime = m_FAST%Lin%LinTimes(iLinTime) - m_FAST%Lin%LinTimes(1) if (p_FAST%DT_UJac < p_FAST%TMax) then m_FAST%calcJacobian = .true. m_FAST%NextJacCalcTime = m_FAST%Lin%LinTimes(iLinTime) end if call SetOperatingPoint(iLinTime, p_FAST, y_FAST, m_FAST, ED, BD, SrvD, AD, IfW, OpFM, HD, SD, ExtPtfm, & MAPp, FEAM, MD, Orca, IceF, IceD, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) ! set perturbation of states based on x_eig magnitude and phase call PerturbOP(tprime, iLinTime, ModeNo, p_FAST, y_FAST, ED, BD, SrvD, AD, IfW, OpFM, HD, SD, ExtPtfm, MAPp, FEAM, MD, Orca, & IceF, IceD, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) IF (ErrStat >= AbortErrLev) RETURN CALL CalcOutputs_And_SolveForInputs( -1, m_FAST%Lin%LinTimes(iLinTime), STATE_CURR, m_FAST%calcJacobian, m_FAST%NextJacCalcTime, & p_FAST, m_FAST, .true., ED, BD, SrvD, AD14, AD, IfW, OpFM, HD, SD, ExtPtfm, MAPp, FEAM, MD, Orca, IceF, IceD, MeshMapData, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) IF (ErrStat >= AbortErrLev) RETURN call WriteVTK(m_FAST%Lin%LinTimes(iLinTime), p_FAST, y_FAST, MeshMapData, ED, BD, AD, IfW, OpFM, HD, SD, ExtPtfm, SrvD, MAPp, FEAM, MD, Orca, IceF, IceD) end do ! iLinTime end do ! iMode case (2) do iMode = 1,p_FAST%VTK_modes%VTKLinModes ModeNo = p_FAST%VTK_modes%VTKModes(iMode) call GetTimeConstants(p_FAST%VTK_modes%DampedFreq_Hz(ModeNo), p_FAST%VTK_fps, nt, dt, p_FAST%VTK_tWidth ) if (nt > 500) cycle do iLinTime = 1,NLinTimes p_FAST%VTK_OutFileRoot = trim(VTK_RootName)//'.Mode'//trim(num2lstr(ModeNo))//'.LinTime'//trim(num2lstr(iLinTime)) y_FAST%VTK_count = 1 ! we are skipping the reference meshes by starting at 1 if (p_FAST%DT_UJac < p_FAST%TMax) then m_FAST%calcJacobian = .true. m_FAST%NextJacCalcTime = m_FAST%Lin%LinTimes(iLinTime) end if do it = 1,nt tprime = (it-1)*dt call SetOperatingPoint(iLinTime, p_FAST, y_FAST, m_FAST, ED, BD, SrvD, AD, IfW, OpFM, HD, SD, ExtPtfm, & MAPp, FEAM, MD, Orca, IceF, IceD, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) ! set perturbation of states based on x_eig magnitude and phase call PerturbOP(tprime, iLinTime, ModeNo, p_FAST, y_FAST, ED, BD, SrvD, AD, IfW, OpFM, HD, SD, ExtPtfm, MAPp, FEAM, MD, Orca, & IceF, IceD, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) IF (ErrStat >= AbortErrLev) RETURN CALL CalcOutputs_And_SolveForInputs( -1, m_FAST%Lin%LinTimes(iLinTime), STATE_CURR, m_FAST%calcJacobian, m_FAST%NextJacCalcTime, & p_FAST, m_FAST, .true., ED, BD, SrvD, AD14, AD, IfW, OpFM, HD, SD, ExtPtfm, MAPp, FEAM, MD, Orca, IceF, IceD, MeshMapData, ErrStat2, ErrMsg2 ) CALL SetErrStat(ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) IF (ErrStat >= AbortErrLev) RETURN call WriteVTK(m_FAST%Lin%LinTimes(iLinTime)+tprime, p_FAST, y_FAST, MeshMapData, ED, BD, AD, IfW, OpFM, HD, SD, ExtPtfm, SrvD, MAPp, FEAM, MD, Orca, IceF, IceD) end do end do ! iLinTime end do ! iMode end select END SUBROUTINE FAST_RestoreForVTKModeShape_T !---------------------------------------------------------------------------------------------------------------------------------- SUBROUTINE GetTimeConstants(DampedFreq_Hz, VTK_fps, nt, dt, VTK_tWidth ) REAL(R8Ki), INTENT(IN ) :: DampedFreq_Hz REAL(DbKi), INTENT(IN ) :: VTK_fps INTEGER(IntKi), INTENT( OUT) :: nt !< number of steps REAL(DbKi), INTENT( OUT) :: dt !< time step INTEGER(IntKi), INTENT( OUT) :: VTK_tWidth REAL(DbKi) :: cycle_time ! time for one cycle of mode INTEGER(IntKi) :: NCycles INTEGER(IntKi), PARAMETER :: MinFrames = 5 if (DampedFreq_Hz <= 0.0_DbKi) then nt = huge(nt) dt = epsilon(dt) VTK_tWidth = 1 return end if nt = 1 NCycles = 0 do while (nt<MinFrames) NCycles = NCycles + 1 cycle_time = NCycles * 1.0_DbKi / DampedFreq_Hz nt = NINT( max(1.0_DbKi, VTK_fps) * cycle_time ) end do dt = cycle_time / nt VTK_tWidth = CEILING( log10( real(nt) ) ) + 1 END SUBROUTINE GetTimeConstants !---------------------------------------------------------------------------------------------------------------------------------- SUBROUTINE ReadModeShapeMatlabFile(p_FAST, ErrStat, ErrMsg) TYPE(FAST_ParameterType), INTENT(INOUT) :: p_FAST !< Parameters for the glue code INTEGER(IntKi), INTENT( OUT) :: ErrStat !< Error status of the operation CHARACTER(*), INTENT( OUT) :: ErrMsg !< Error message if ErrStat /= ErrID_None ! local variables INTEGER(IntKi) :: ErrStat2 CHARACTER(ErrMsgLen) :: ErrMsg2 CHARACTER(*), PARAMETER :: RoutineName = 'ReadModeShapeMatlabFile' INTEGER(4) :: FileType INTEGER(4) :: nModes INTEGER(4) :: nStates INTEGER(4) :: NLinTimes INTEGER(IntKi) :: iMode INTEGER(IntKi) :: UnIn ErrStat = ErrID_None ErrMsg = "" ! Open data file. CALL GetNewUnit( UnIn, ErrStat2, ErrMsg2 ) CALL OpenBInpFile ( UnIn, trim(p_FAST%VTK_modes%MatlabFileName), ErrStat2, ErrMsg2 ) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) IF (ErrStat >= AbortErrLev) RETURN ! Process the requested data records of this file. CALL WrScr ( NewLine//' =======================================================' ) CALL WrScr ( ' Reading in data from file "'//TRIM( p_FAST%VTK_modes%MatlabFileName )//'".'//NewLine ) ! Read some of the header information. READ (UnIn, IOSTAT=ErrStat2) FileType ! placeholder for future file format changes IF ( ErrStat2 /= 0 ) THEN CALL SetErrStat ( ErrID_Fatal, 'Fatal error reading FileType from file "'//TRIM( p_FAST%VTK_modes%MatlabFileName )//'".', ErrStat, ErrMsg, RoutineName ) RETURN ENDIF READ (UnIn, IOSTAT=ErrStat2) nModes ! number of modes in the file IF ( ErrStat2 /= 0 ) THEN CALL SetErrStat ( ErrID_Fatal, 'Fatal error reading nModes from file "'//TRIM( p_FAST%VTK_modes%MatlabFileName )//'".', ErrStat, ErrMsg, RoutineName ) RETURN ENDIF READ (UnIn, IOSTAT=ErrStat2) nStates ! number of states in the file IF ( ErrStat2 /= 0 ) THEN CALL SetErrStat ( ErrID_Fatal, 'Fatal error reading nStates from file "'//TRIM( p_FAST%VTK_modes%MatlabFileName )//'".', ErrStat, ErrMsg, RoutineName ) RETURN ENDIF READ (UnIn, IOSTAT=ErrStat2) NLinTimes ! number of linearization times / azimuths in the file IF ( ErrStat2 /= 0 ) THEN CALL SetErrStat ( ErrID_Fatal, 'Fatal error reading NLinTimes from file "'//TRIM( p_FAST%VTK_modes%MatlabFileName )//'".', ErrStat, ErrMsg, RoutineName ) RETURN ENDIF ALLOCATE( p_FAST%VTK_Modes%NaturalFreq_Hz(nModes), & p_FAST%VTK_Modes%DampingRatio( nModes), & p_FAST%VTK_Modes%DampedFreq_Hz( nModes), STAT=ErrStat2 ) IF ( ErrStat2 /= 0 ) THEN CALL SetErrStat ( ErrID_Fatal, 'Error allocating arrays to read from file.', ErrStat, ErrMsg, RoutineName ) RETURN ENDIF READ(UnIn, IOSTAT=ErrStat2) p_FAST%VTK_Modes%NaturalFreq_Hz ! read entire array IF ( ErrStat2 /= 0 ) THEN CALL SetErrStat ( ErrID_Fatal, 'Fatal error reading NaturalFreq_Hz array from file "'//TRIM( p_FAST%VTK_modes%MatlabFileName )//'".', ErrStat, ErrMsg, RoutineName ) RETURN ENDIF READ(UnIn, IOSTAT=ErrStat2) p_FAST%VTK_Modes%DampingRatio ! read entire array IF ( ErrStat2 /= 0 ) THEN CALL SetErrStat ( ErrID_Fatal, 'Fatal error reading DampingRatio array from file "'//TRIM( p_FAST%VTK_modes%MatlabFileName )//'".', ErrStat, ErrMsg, RoutineName ) RETURN ENDIF READ(UnIn, IOSTAT=ErrStat2) p_FAST%VTK_Modes%DampedFreq_Hz ! read entire array IF ( ErrStat2 /= 0 ) THEN CALL SetErrStat ( ErrID_Fatal, 'Fatal error reading DampedFreq_Hz array from file "'//TRIM( p_FAST%VTK_modes%MatlabFileName )//'".', ErrStat, ErrMsg, RoutineName ) RETURN ENDIF if (nModes < p_FAST%VTK_Modes%VTKLinModes) CALL SetErrStat(ErrID_Severe,'Number of modes requested exceeds the number of modes in the linearization analysis file "'//TRIM( p_FAST%VTK_modes%MatlabFileName )//'".', ErrStat, ErrMsg, RoutineName) if (NLinTimes /= p_FAST%NLinTimes) CALL SetErrStat(ErrID_Severe,'Number of times linearization was performed is not the same as the number of linearization times in the linearization analysis file "'//TRIM( p_FAST%VTK_modes%MatlabFileName )//'".', ErrStat, ErrMsg, RoutineName) !Let's read only the number of modes we need to use nModes = min( nModes, p_FAST%VTK_Modes%VTKLinModes ) ALLOCATE( p_FAST%VTK_Modes%x_eig_magnitude(nStates, NLinTimes, nModes), & p_FAST%VTK_Modes%x_eig_phase( nStates, NLinTimes, nModes), STAT=ErrStat2 ) IF ( ErrStat2 /= 0 ) THEN CALL SetErrStat ( ErrID_Fatal, 'Error allocating arrays to read from file.', ErrStat, ErrMsg, RoutineName ) RETURN ENDIF do iMode = 1,nModes READ(UnIn, IOSTAT=ErrStat2) p_FAST%VTK_Modes%x_eig_magnitude(:,:,iMode) ! read data for one mode IF ( ErrStat2 /= 0 ) THEN CALL SetErrStat ( ErrID_Fatal, 'Fatal error reading x_eig_magnitude from file "'//TRIM( p_FAST%VTK_modes%MatlabFileName )//'".', ErrStat, ErrMsg, RoutineName ) RETURN ENDIF READ(UnIn, IOSTAT=ErrStat2) p_FAST%VTK_Modes%x_eig_phase(:,:,iMode) ! read data for one mode IF ( ErrStat2 /= 0 ) THEN CALL SetErrStat ( ErrID_Fatal, 'Fatal error reading x_eig_phase from file "'//TRIM( p_FAST%VTK_modes%MatlabFileName )//'".', ErrStat, ErrMsg, RoutineName ) RETURN ENDIF end do END SUBROUTINE ReadModeShapeMatlabFile !---------------------------------------------------------------------------------------------------------------------------------- SUBROUTINE ReadModeShapeFile(p_FAST, InputFile, ErrStat, ErrMsg, checkpointOnly) TYPE(FAST_ParameterType), INTENT(INOUT) :: p_FAST !< Parameters for the glue code CHARACTER(*), INTENT(IN ) :: InputFile !< Name of the text input file to read INTEGER(IntKi), INTENT( OUT) :: ErrStat !< Error status of the operation CHARACTER(*), INTENT( OUT) :: ErrMsg !< Error message if ErrStat /= ErrID_None LOGICAL, OPTIONAL, INTENT(IN ) :: checkpointOnly !< Whether to return after reading checkpoint file name ! local variables INTEGER(IntKi) :: ErrStat2 CHARACTER(ErrMsgLen) :: ErrMsg2 CHARACTER(*), PARAMETER :: RoutineName = 'ReadModeShapeFile' CHARACTER(1024) :: PriPath ! Path name of the primary file INTEGER(IntKi) :: i INTEGER(IntKi) :: UnIn INTEGER(IntKi) :: UnEc LOGICAL :: VTKLinTimes1 ErrStat = ErrID_None ErrMsg = "" UnEc = -1 CALL GetPath( InputFile, PriPath ) ! Input files will be relative to the path where the primary input file is located. ! Open data file. CALL GetNewUnit( UnIn, ErrStat2, ErrMsg2 ) CALL OpenFInpFile ( UnIn, InputFile, ErrStat2, ErrMsg2 ) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) IF (ErrStat >= AbortErrLev) RETURN CALL ReadCom( UnIn, InputFile, 'File header: (line 1)', ErrStat2, ErrMsg2, UnEc ) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL ReadCom( UnIn, InputFile, 'File header: (line 2)', ErrStat2, ErrMsg2, UnEc ) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) !----------- FILE NAMES ---------------------------------------------------- CALL ReadCom( UnIn, InputFile, 'Section Header: File Names', ErrStat2, ErrMsg2, UnEc ) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL ReadVar( UnIn, InputFile, p_FAST%VTK_modes%CheckpointRoot, 'CheckpointRoot', 'Name of the checkpoint file written by FAST when linearization data was produced', ErrStat2, ErrMsg2, UnEc ) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) IF ( PathIsRelative( p_FAST%VTK_modes%CheckpointRoot ) ) p_FAST%VTK_modes%CheckpointRoot = TRIM(PriPath)//TRIM(p_FAST%VTK_modes%CheckpointRoot) if (present(checkpointOnly)) then if (checkpointOnly) then call cleanup() return end if end if CALL ReadVar( UnIn, InputFile, p_FAST%VTK_modes%MatlabFileName, 'MatlabFileName', 'Name of the file with eigenvectors written by Matlab', ErrStat2, ErrMsg2, UnEc ) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) IF ( ErrStat >= AbortErrLev ) THEN CALL Cleanup() RETURN END IF IF ( PathIsRelative( p_FAST%VTK_modes%MatlabFileName ) ) p_FAST%VTK_modes%MatlabFileName = TRIM(PriPath)//TRIM(p_FAST%VTK_modes%MatlabFileName) !----------- VISUALIZATION OPTIONS ------------------------------------------ CALL ReadCom( UnIn, InputFile, 'Section Header: Visualization Options', ErrStat2, ErrMsg2, UnEc ) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL ReadVar( UnIn, InputFile, p_FAST%VTK_modes%VTKLinModes, 'VTKLinModes', 'Number of modes to visualize', ErrStat2, ErrMsg2, UnEc ) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) if (p_FAST%VTK_modes%VTKLinModes <= 0) CALL SetErrStat( ErrID_Fatal, "VTKLinModes must be a positive number.", ErrStat, ErrMsg, RoutineName ) if (ErrStat >= AbortErrLev) then CALL Cleanup() RETURN end if call AllocAry( p_FAST%VTK_modes%VTKModes, p_FAST%VTK_modes%VTKLinModes, 'VTKModes', ErrStat2, ErrMsg2) call SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) if ( ErrStat >= AbortErrLev ) then call Cleanup() return end if p_FAST%VTK_modes%VTKModes = -1 CALL ReadAry( UnIn, InputFile, p_FAST%VTK_modes%VTKModes, p_FAST%VTK_modes%VTKLinModes, 'VTKModes', 'List of modes to visualize', ErrStat2, ErrMsg2, UnEc ) ! note that we don't check the ErrStat here; if the user entered fewer than p_FAST%VTK_modes%VTKLinModes values, we will use the ! last entry to fill in remaining values. !Check 1st value, we need at least one good value from user or throw error IF (p_FAST%VTK_modes%VTKModes(1) < 0 ) THEN call SetErrStat( ErrID_Fatal, "VTKModes must contain positive numbers.", ErrStat, ErrMsg, RoutineName ) CALL CleanUp() RETURN ELSE DO i = 2, p_FAST%VTK_modes%VTKLinModes IF ( p_FAST%VTK_modes%VTKModes(i) < 0 ) THEN p_FAST%VTK_modes%VTKModes(i)=p_FAST%VTK_modes%VTKModes(i-1) + 1 ENDIF ENDDO ENDIF CALL ReadVar( UnIn, InputFile, p_FAST%VTK_modes%VTKLinScale, 'VTKLinScale', 'Mode shape visualization scaling factor', ErrStat2, ErrMsg2, UnEc ) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL ReadVar( UnIn, InputFile, p_FAST%VTK_modes%VTKLinTim, 'VTKLinTim', 'Switch to make one animation for all LinTimes together (1) or separate animations for each LinTimes(2)', ErrStat2, ErrMsg2, UnEc ) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL ReadVar( UnIn, InputFile, VTKLinTimes1, 'VTKLinTimes1', 'If VTKLinTim=2, visualize modes at LinTimes(1) only?', ErrStat2, ErrMsg2, UnEc ) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) CALL ReadVar( UnIn, InputFile, p_FAST%VTK_modes%VTKLinPhase, 'VTKLinPhase', 'Phase when making one animation for all LinTimes together (used only when VTKLinTim=1)', ErrStat2, ErrMsg2, UnEc ) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) ! overwrite these based on inputs: if (p_FAST%VTK_modes%VTKLinTim == 2) then p_FAST%VTK_modes%VTKLinPhase = 0 ! "Phase when making one animation for all LinTimes together (used only when VTKLinTim=1)" - if (VTKLinTimes1) then p_FAST%VTK_modes%VTKNLinTimes = 1 else p_FAST%VTK_modes%VTKNLinTimes = p_FAST%NLinTimes end if else p_FAST%VTK_modes%VTKNLinTimes = p_FAST%NLinTimes end if contains SUBROUTINE Cleanup() IF (UnIn > 0) CLOSE(UnIn) END SUBROUTINE Cleanup END SUBROUTINE ReadModeShapeFile !---------------------------------------------------------------------------------------------------------------------------------- END MODULE FAST_Subs !----------------------------------------------------------------------------------------------------------------------------------
\section{Molecular orbitals} If the semi-empirical method is used to calculate electronic coupling elements, molecular orbitals of all molecules must be supplied. They can be generated using \gaussian program. The \gaussian input file for \dcvt is shown in listing~\ref{list:zindo_orbitals}. Provided with this input, \gaussian will generate \texttt{fort.7} file which contains the molecular orbitals of a \dcvt. This file can be renamed to \texttt{\dcvt.orb}. Note that the order of the atoms in the input file and the order of coefficients should always match. Therefore, the coordinate part of the input file must be supplied together with the orbitals. We will assume the coordinates, in the format \texttt{atom\_type: x y z}, is saved to the \texttt{\dcvt.xyz} file. \attention{Izindo requires the specification of orbitals for hole and electron transport in \xmlcsg. They are the HOMO and LUMO respectively and can be retrieved from the \texttt{log} file from which the \texttt{\dcvt.orb} file is generated. The number of \texttt{alpha electrons} is the HOMO, the LUMO is HOMO+1 } \lstinputlisting[ label=list:zindo_orbitals, basicstyle=\ttfamily\footnotesize, morekeywords={chk,mem,punch,int,S,C,S,N,H}, showstringspaces=false, keepspaces=true, caption={\small \gaussian input file \texttt{get\_orbitals.com} used for generating molecular orbitals. The first line contains the name of the check file, the second the requested RAM. % \texttt{int=zindos} requests the method ZINDO, \texttt{punch=mo} states that the molecular orbitals ought to be written to the \texttt{fort.7} file, \texttt{nosymm} forbids use of symmetry and is necessary to ensure correct position of orbitals with respect to the provided coordinates. The two integer numbers correspond to the charge and multiplicity of the system: $0\, 1$ corresponds to a neutral system with a multiplicity of one. They are followed by the types and coordinates of all atoms in the molecule. }]% {./input/get_orbitals.com} %
module ClimatePlots using Dates using Reexport @reexport using ClimateBase using PyCall using PyPlot using Statistics const basemap = PyNULL() const mpl = PyNULL() const cmocean = PyNULL() # const scipy = PyNULL() function __init__() copy!(mpl, pyimport_conda("matplotlib", "matplotlib", "conda-forge")) copy!(basemap, pyimport_conda("mpl_toolkits.basemap", "basemap", "conda-forge")) copy!(cmocean, pyimport_conda("cmocean", "cmocean", "conda-forge")) # copy!(scipy, pyimport_conda("scipy.interpolate", "scipy")) end include("mapping.jl") export plot, mapclimgrid, hist end # module
lemma locally_injective_linear_image: fixes f :: "'a::euclidean_space \<Rightarrow> 'b::euclidean_space" assumes f: "linear f" "inj f" and iff: "\<And>S. P (f ` S) \<longleftrightarrow> Q S" shows "locally P (f ` S) \<longleftrightarrow> locally Q S"
(** printing |-# %\vdash_{\#}% #&vdash;<sub>&#35;</sub># *) (** printing |-## %\vdash_{\#\#}% #&vdash;<sub>&#35&#35</sub># *) (** printing |-##v %\vdash_{\#\#v}% #&vdash;<sub>&#35&#35v</sub># *) (** printing |-! %\vdash_!% #&vdash;<sub>!</sub># *) (** remove printing ~ *) (** * Precise Typing (Elimination Typing II and III) *) (** This module reasons about - properties of precise typing ⊢!! and ⊢!!! (only defined for paths) - about well-formedness of environments which is defined through precise typing - about equivalent types (path replacement with well-typed paths) *) Set Implicit Arguments. Require Import Sequences. Require Import Coq.Program.Equality List. Require Import Definitions Binding RecordAndInertTypes Replacement. Require Export PreciseFlow. Reserved Notation "G '⊢!!' p ':' T" (at level 40, p at level 59). Reserved Notation "G '⊢!!!' p ':' T" (at level 40, p at level 59). (** ** II-level Precise Typing *) Inductive precise_typing2: ctx -> path -> typ -> Prop := | pt2: forall G p T U, G ⊢! p : T ⪼ U -> G ⊢!! p: U | pt2_sngl_trans : forall G p q a U, G ⊢!! p : {{ q }} -> G ⊢!! q•a : U -> G ⊢!! p•a : {{ q•a }} where "G '⊢!!' p ':' T" := (precise_typing2 G p T). (** ** III-level Precise Typing *) Inductive precise_typing3: ctx -> path -> typ -> Prop := | pt3: forall G p T, G ⊢!! p : T -> G ⊢!!! p: T | pt3_sngl_trans : forall G p q T, G ⊢!! p : {{ q }} -> G ⊢!!! q : T -> G ⊢!!! p : T where "G '⊢!!!' p ':' T" := (precise_typing3 G p T). Hint Constructors precise_typing2 precise_typing3. (** *** Properties of ⊢!! and ⊢!!!. Relationships between ⊢!, ⊢!!, and ⊢!!! *) Lemma precise_to_general2: forall G p T, G ⊢!! p: T -> G ⊢ trm_path p : T. Proof. introv Hp. induction Hp; eauto using precise_to_general. Qed. Lemma precise_to_general3: forall G p T, G ⊢!!! p: T -> G ⊢ trm_path p : T. Proof. introv Hp. induction Hp; eauto using precise_to_general2. Qed. Lemma pt2_and_destruct1: forall G p T U, G ⊢!! p: T ∧ U -> G ⊢!! p: T. Proof. introv Hp. dependent induction Hp; eauto. Qed. Lemma pt2_and_destruct2: forall G p T U, G ⊢!! p: T ∧ U -> G ⊢!! p: U. Proof. introv Hp. dependent induction Hp; eauto. Qed. Lemma pt3_and_destruct1: forall G p T U, G ⊢!!! p: T ∧ U -> G ⊢!!! p: T. Proof. introv Hp. dependent induction Hp; eauto. constructor. apply* pt2_and_destruct1. Qed. Lemma pt3_and_destruct2: forall G p T U, G ⊢!!! p: T ∧ U -> G ⊢!!! p: U. Proof. introv Hp. dependent induction Hp; eauto. constructor. apply* pt2_and_destruct2. Qed. Lemma pt2_inertsngl : forall G p T, inert G -> G ⊢!! p: T -> inert_sngl T \/ record_type T. Proof. introv Hi Pf. induction Pf. - apply* pf_inertsngl. - left. right. eexists. eauto. Qed. Lemma pt3_inertsngl : forall G p T, inert G -> G ⊢!!! p: T -> inert_sngl T \/ record_type T. Proof. introv Hi Pf. induction Pf; eauto; apply* pt2_inertsngl. Qed. Lemma pt2_psel: forall G p q A, inert G -> G ⊢!! p : q ↓ A -> False. Proof. introv Hi Hp. dependent induction Hp; eauto. apply* pf_psel. Qed. Lemma pt3_psel: forall G p q A, inert G -> G ⊢!!! p : q ↓ A -> False. Proof. introv Hi Hp. dependent induction Hp; eauto. apply* pt2_psel. Qed. Lemma pt3_trans: forall G p q a U, G ⊢!! p : {{ q }}-> G ⊢!!! q•a : U -> G ⊢!!! p•a : U. Proof. introv Hp Hq. gen p. dependent induction Hq; introv Hp; eauto. Qed. Lemma pt3_trans2: forall G p q a U, G ⊢!!! p : {{ q }}-> G ⊢!!! q•a : U -> G ⊢!!! p•a : U. Proof. introv Hp Hq. gen a U. dependent induction Hp; introv Hq. - apply* pt3_trans. - specialize (IHHp _ eq_refl _ _ Hq). apply* pt3_trans. Qed. Lemma pt3_field_elim: forall G p a T, G ⊢!!! p : typ_rcd { a ⦂ T } -> G ⊢!!! p•a : T. Proof. introv Hp. dependent induction Hp. - dependent induction H; eauto. - specialize (IHHp _ _ eq_refl). gen p. dependent induction IHHp; introv Hpq; eauto. Qed. Lemma path_elim_prec: forall G p q a T, inert G -> G ⊢!!! p: {{ q }}-> G ⊢!!! q•a : T -> G ⊢!!! p•a : {{ q•a }}. Proof. introv Hi Hp Hq. gen a T. dependent induction Hp; introv Hq. - inversion* Hq. - specialize (IHHp _ Hi eq_refl _ _ Hq). apply* pt3_trans. Qed. Lemma pf_pt2: forall G p T U V, inert G -> G ⊢! p: T ⪼ U -> G ⊢!! p: V -> inert_sngl V -> T = V. Proof. introv Hi Hp1 Hp2 His. gen T U. induction Hp2; introv Hp1. - lets Heq: (pf_T_unique Hi Hp1 H). subst. destruct His. * destruct H0. apply* pf_forall_T. apply* pf_bnd_T. * inversions H0. destruct_all. apply* pf_sngl_T. - destruct (pf_path_sel _ _ Hi Hp1) as [V Hp]. assert (inert_sngl {{ q }}) as His'. { right. eexists. auto. } specialize (IHHp2_1 Hi His' _ _ Hp). inversion IHHp2_1. Qed. Lemma pf_pt2_sngl: forall G p T U q, inert G -> G ⊢! p: T ⪼ U -> G ⊢!! p: {{ q }}-> T = {{ q }}. Proof. introv Hi Hp1 Hp2. apply* pf_pt2. right. eexists. auto. Qed. Lemma field_elim_q0: forall G p q a T, inert G -> G ⊢! p: {{ q }}⪼ {{ q }}-> G ⊢!! p•a : T -> exists U, G ⊢!! q•a: U. Proof. introv Hi Hp Hpa. gen q. dependent induction Hpa; introv Hp; eauto. - dependent induction H; try simpl_dot; eauto. lets Heq: (pf_T_unique Hi Hp H). subst. apply pf_sngl_U in H. inversion H. - clear IHHpa1 IHHpa2. simpl_dot. lets Heq: (pf_pt2_sngl Hi Hp Hpa1). inversion* Heq. Qed. Lemma field_elim_q0': forall G p q a T T', inert G -> G ⊢!! p: {{ q }}-> G ⊢! p•a : T ⪼ T' -> exists U, G ⊢!! q•a: U. Proof. introv Hi Hp Hpa. gen q. dependent induction Hpa; introv Hp; try simpl_dot; eauto. lets Hp2: (pf_pt2_sngl Hi Hpa Hp). subst. apply pf_sngl_U in Hpa. inversion Hpa. Qed. Lemma pf_pt2_sngl_invert G p q a T U : inert G -> G ⊢!! p: {{ q }}-> G ⊢! p•a : T ⪼ U -> False. Proof. intros Hi Hp Hpf. assert (exists V S, G ⊢! p: V ⪼ S) as [V [S Hpvs]]. { dependent induction Hpf; try simpl_dot; eauto. } lets ->: (pf_pt2_sngl Hi Hpvs Hp). clear Hp. dependent induction Hpf; try simpl_dot; eauto. lets Heq: (pf_T_unique Hi Hpvs Hpf). subst. apply pf_sngl_U in Hpf as[=]. Qed. Lemma pt2_sngl_exists: forall G p q T, inert G -> G ⊢!! p: {{ q }}-> G ⊢!! p: T -> exists q', T = {{ q' }}. Proof. introv Hi Hp Ht. gen T. dependent induction Hp; introv Ht; eauto. - lets ->: (pf_sngl_T Hi H). dependent induction Ht; eauto. lets Heq: (pf_T_unique Hi H H0). subst. eauto using pf_sngl_U. - dependent induction Ht; eauto. lets Contra: (pf_pt2_sngl_invert _ Hi Hp1 H). inversion Contra. Qed. Lemma pt2_sngl_unique: forall G p q1 q2, inert G -> G ⊢!! p: {{ q1 }} -> G ⊢!! p: {{ q2 }} -> q1 = q2. Proof. introv Hi Hp. gen q2. dependent induction Hp; introv Ht; eauto. - lets ->: (pf_sngl_T Hi H). dependent induction Ht; eauto. * lets Heq: (pf_T_unique Hi H H0). subst. apply pf_sngl_U in H0 as [=]. auto. * lets Contra: (pf_pt2_sngl_invert _ Hi Ht1 H). inversion Contra. - specialize (IHHp1 _ Hi eq_refl). gen q U. dependent induction Ht; introv Hpq IH1; introv Hqa IH2. * lets Contra: (pf_pt2_sngl_invert _ Hi Hpq H). inversion Contra. * simpl_dot. f_equal. eauto. Qed. Lemma pt2_sngl_unique' G p q T : inert G -> G ⊢!! p: {{ q }}-> G ⊢!! p: T -> T = {{ q }}. Proof. introv Hi Hp Hpt. destruct (pt2_sngl_exists Hi Hp Hpt) as [q' ->]. f_equal. eauto using pt2_sngl_unique. Qed. Lemma field_elim_q: forall G p q a T, inert G -> G ⊢!! p: {{ q }}-> G ⊢!! p•a : T -> exists U, G ⊢!! q•a: U. Proof. introv Hi Hp Hpa. gen a T. dependent induction Hp; introv Hpa. - lets Heq: (pf_sngl_T Hi H). subst. apply* field_elim_q0. - clear IHHp1 IHHp2. gen q0 U. dependent induction Hpa; introv Hp; introv Hq0. * apply* field_elim_q0'. * unfold sel_fields in x. destruct p0, p. inversions x. lets Hxbs: (pt2_sngl_trans _ Hp Hq0). assert (inert_sngl {{ q }}) as His. { right. eexists. eauto. } simpl in *. lets Hu: (pt2_sngl_unique Hi Hpa1 Hxbs). inversions Hu. eauto. Qed. Lemma field_elim_q2: forall G p q a T, inert G -> G ⊢!!! p: {{ q }}-> G ⊢!! p•a : T -> exists U, G ⊢!!! q•a: U. Proof. introv Hi Hp Hpa. gen a T. dependent induction Hp; introv Hpa. - destruct* (field_elim_q _ Hi H Hpa). - specialize (IHHp _ Hi eq_refl). destruct (field_elim_q _ Hi H Hpa) as [V Hqa]. apply* IHHp. Qed. Lemma field_elim_q3: forall G p q a T, inert G -> G ⊢!!! p: {{ q }}-> G ⊢!!! p•a : T -> exists U, G ⊢!!! q•a: U. Proof. introv Hi Hp Hpa. gen q. dependent induction Hpa; introv Hp. - gen a T. dependent induction Hp; introv Hpa; destruct* (field_elim_q _ Hi H Hpa). - clear IHHpa Hpa T. gen a q. dependent induction Hp; introv Hpa. * destruct* (field_elim_q _ Hi H Hpa). * lets Hp': (pt3_sngl_trans H Hp). apply* field_elim_q2. Qed. Lemma pt2_field_elim_p: forall G p q a U, inert G -> G ⊢!! p: {{ q }}-> G ⊢!! p • a : U -> G ⊢!! p • a : {{ q•a }}. Proof. introv Hi Hpq Hpa. destruct (field_elim_q _ Hi Hpq Hpa) as [T Hqa]. apply* pt2_sngl_trans. Qed. Lemma pt3_field_elim_p: forall G p q a U, inert G -> G ⊢!!! p: {{ q }}-> G ⊢!!! p • a : U -> G ⊢!!! p • a : {{ q•a }}. Proof. introv Hi Hpq Hpa. destruct (field_elim_q3 _ Hi Hpq Hpa) as [T Hqa]. apply* path_elim_prec. Qed. Lemma pt2_backtrack : forall G p a T, G ⊢!! p • a : T -> exists U, G ⊢!! p : U. Proof. introv Hp. dependent induction Hp; eauto. - dependent induction H; try simpl_dot; eauto. - simpl_dot. eauto. Qed. Lemma pt3_backtrack : forall G p a T, G ⊢!!! p • a : T -> exists U, G ⊢!!! p : U. Proof. introv Hp. dependent induction Hp; apply pt2_backtrack in H; destruct_all; eauto. Qed. Lemma pt3_sngl_trans3: forall G p q T, G ⊢!!! p: {{ q }}-> G ⊢!!! q: T -> G ⊢!!! p : T. Proof. introv Hp Hq. gen T. dependent induction Hp; introv Hq; eauto. Qed. Lemma pt2_field_trans: forall G p q bs T, inert G -> G ⊢!! p : {{ q }}-> G ⊢!! q••bs : T -> G ⊢!! p••bs : {{ q••bs }}. Proof. Proof. introv Hi Hp Hq. gen T q. induction bs; introv Hp Hq; unfolds sel_fields; destruct q, p; simpls; auto. rewrite proj_rewrite in *. destruct (pt2_backtrack _ _ Hq) as [U Hb]. specialize (IHbs _ _ Hp Hb). rewrite proj_rewrite. apply* pt2_sngl_trans. Qed. Lemma pt3_field_trans: forall G p q bs T, inert G -> G ⊢!!! p : {{ q }}-> G ⊢!!! q••bs : T -> G ⊢!!! p••bs : {{ q••bs }}. Proof. introv Hi Hp Hq. gen T q. induction bs; introv Hp Hq; unfolds sel_fields; destruct q, p; simpls; auto. rewrite proj_rewrite in *. destruct (pt3_backtrack _ _ Hq) as [U Hb]. specialize (IHbs _ _ Hp Hb). rewrite proj_rewrite. apply* path_elim_prec. Qed. Lemma pt3_field_trans': forall G p q bs T, inert G -> G ⊢!!! p : {{ q }}-> G ⊢!!! q••bs : T -> G ⊢!!! p••bs : T. Proof. introv Hi Hp1 Hp2. gen p q T. induction bs; introv Hp1; introv Hp2; unfolds sel_fields; destruct q, p; simpls. - apply* pt3_sngl_trans3. - rewrite proj_rewrite in *. destruct (pt3_backtrack _ _ Hp2) as [S Hb]. lets Hh: (pt3_field_trans _ Hi Hp1 Hb). apply* pt3_sngl_trans3. apply* path_elim_prec. Qed. Lemma pt2_weaken_one G p T x U : ok (G & x ~ U) -> G ⊢!! p : T -> G & x ~ U ⊢!! p : T. Proof. intros Hx Hp. induction Hp. - econstructor. rewrite <- concat_empty_r in Hx. apply* pf_weaken_one. do 2 eapply ok_concat_inv_l; eauto. - eapply pt2_sngl_trans; eauto. Qed. Lemma pt2_weaken G p T G' : ok (G & G') -> G ⊢!! p : T -> G & G' ⊢!! p : T. Proof. intros Hok Hp. induction G' using env_ind. - rewrite* concat_empty_r. - rewrite concat_assoc in *. apply* pt2_weaken_one. Qed. Lemma pt3_weaken_one G p T x U : ok (G & x ~ U) -> G ⊢!!! p : T -> G & x ~ U ⊢!!! p : T. Proof. intros Hx Hp. induction Hp. - econstructor. rewrite <- concat_empty_r in Hx. apply* pt2_weaken_one. - eapply pt3_sngl_trans; eauto. apply* pt2_weaken_one. Qed. Lemma pt3_weaken G G' p T : ok (G & G') -> G ⊢!!! p: T -> G & G' ⊢!!! p: T. Proof. intros Hok Hp. induction G' using env_ind. - rewrite* concat_empty_r. - rewrite concat_assoc in *. apply* pt3_weaken_one. Qed. Lemma pf_strengthen_full G p T U : inert G -> G ⊢! p : T ⪼ U -> exists G1 G2 x bs V, G = G1 & x ~ V & G2 /\ p = p_sel (avar_f x) bs /\ G1 & x ~ V ⊢! p : T ⪼ U. Proof. intros Hi Hp. pose proof (typed_paths_named (precise_to_general Hp)) as [x [bs ->]]. induction G as [|G1 y V] using env_ind. - apply precise_to_general in Hp. false* typing_empty_false. - destruct (classicT (y = x)) as [-> | Hn]. + repeat eexists; eauto. rewrite* concat_empty_r. + apply pf_strengthen in Hp; auto. specialize (IHG (inert_prefix Hi) Hp) as [G1' [G2' [z [cs [W [-> [[= -> ->] Hp']]]]]]]. repeat eexists; eauto. rewrite concat_assoc. eauto. Qed. Lemma pt2_destruct_env G p T : inert G -> G ⊢!! p : T -> exists G1 G2 x bs V, G = G1 & x ~ V & G2 /\ p = p_sel (avar_f x) bs. Proof. intros Hi Hp. induction Hp. - apply pf_strengthen_full in H; auto. destruct_all; repeat eexists; eauto. - specialize (IHHp1 Hi). specialize (IHHp2 Hi). destruct_all. simpl_dot. repeat eexists. Qed. Lemma pt2_var_sngl G x p : inert G -> G ⊢!! pvar x : {{ p }}-> False. Proof. intros Hi Hp. dependent induction Hp; try simpl_dot. pose proof (pf_sngl_T Hi H) as ->. apply (pf_binds Hi) in H. apply (binds_inert H) in Hi. inversion Hi. Qed. Lemma pt2_to_pf G p T : G ⊢!! p : T -> (inert_typ T \/ record_type T) -> exists U, G ⊢! p : U ⪼ T. Proof. intros Hp [Hin | Hr]. - inversions Hin; inversions Hp; eauto. - inversions Hr. inversions H; inversions Hp; eauto. Qed. Lemma pt3_trans_trans: forall G p q bs T, inert G -> G ⊢!!! p : {{ q }}-> G ⊢!!! p••bs : T -> G ⊢!!! p••bs : {{ q••bs }}. Proof. introv Hi Hp Hpbs. gen p q T. induction bs; introv Hp; introv Hpbs; unfolds sel_fields; destruct p, q; simpls; auto. repeat rewrite proj_rewrite in *. apply* pt3_field_elim_p. specialize (IHbs _ _ Hp). apply pt3_backtrack in Hpbs. destruct_all. eauto. Qed. Lemma pt2_bnd : forall G p T, inert G -> G ⊢!! p: μ T -> G ⊢!! p: open_typ_p p T. Proof. introv Hi Hp. dependent induction Hp; eauto. Qed. Lemma pt2_exists: forall G p T, G ⊢!!! p: T -> exists U, G ⊢!! p: U. Proof. induction 1; eauto. Qed. Lemma pt3_bnd : forall G p T, inert G -> G ⊢!!! p: μ T -> G ⊢!!! p: open_typ_p p T \/ (exists q U, G ⊢!!! p: {{ q }}/\ G ⊢!! q : U /\ G ⊢!!! p: open_typ_p q T). Proof. introv Hi Hp. dependent induction Hp. - left. constructor. apply* pt2_bnd. - specialize (IHHp _ Hi eq_refl). destruct IHHp as [Hq | [r [U [Hr1 [Hq Hr2]]]]]; right. + apply pt2_exists in Hp as [? ?]. repeat eexists; eauto. + exists r. repeat eexists; eauto. Qed. Lemma pf_pt2_trans_inv_mult : forall G p q bs T, inert G -> G ⊢! p: {{ q }}⪼ {{ q }}-> G ⊢!! p •• bs : T -> T = {{ q••bs }}. Proof. introv Hi Hp Hpbs. gen T. induction bs; introv Hpbs. - repeat rewrite field_sel_nil in *. apply pt2 in Hp. apply eq_sym. apply eq_sym. eauto using pt2_sngl_unique'. - rewrite proj_rewrite' in *. destruct (pt2_backtrack _ _ Hpbs) as [U Hb]. apply pt2 in Hp. specialize (IHbs _ Hb). subst. destruct (field_elim_q _ Hi Hb Hpbs) as [U Hf]. lets Hp2: (pt2_sngl_trans _ Hb Hf). eauto using pt2_sngl_unique'. Qed. Lemma pf_pt3_trans_inv_mult : forall G p q T, inert G -> G ⊢!! p: {{ q }}-> G ⊢!!! p : T -> inert_typ T \/ record_type T -> G ⊢!!! q : T. Proof. introv Hi Hpq Hp Hr. gen q. induction Hp; introv Hpq. - constructor. assert (inert_sngl {{ q }}) as His. { right. eexists. eauto. } lets ->: (pt2_sngl_unique' Hi Hpq H). destruct Hr. inversion His. inversion H1. inversion H0. inversion H0. inversion H1. - specialize (IHHp Hi Hr). assert (inert_sngl {{ q }}) as His1. { right. eexists. eauto. } assert (inert_sngl {{ q0 }}) as His2. { right. eexists. eauto. } lets Heq: (pt2_sngl_unique' Hi Hpq H). inversions Heq. eauto. Qed. Lemma pf_pt3_trans_inv_mult' : forall G p q T bs, inert G -> G ⊢! p: {{ q }}⪼ {{ q }}-> G ⊢!!! p •• bs : T -> inert_typ T \/ record_type T -> G ⊢!!! q •• bs : T. Proof. introv Hi Hp Hpbs Hr. assert (exists U, G ⊢!! p •• bs : U) as [U Hu] by apply* pt2_exists. apply* pf_pt3_trans_inv_mult. lets Hpf: (pf_pt2_trans_inv_mult _ Hi Hp Hu). subst*. Qed. Lemma pf_pt3_unique : forall G p S A T U, inert G -> G ⊢! p: S ⪼ typ_rcd {A >: T <: T} -> G ⊢!!! p: typ_rcd {A >: U <: U} -> T = U. Proof. introv Hi Hp1 Hp3. dependent induction Hp3. - apply pt2 in Hp1. dependent induction H. dependent induction Hp1. lets Hu: (pf_T_unique Hi H0 H). subst. destruct (pf_bnd_T2 Hi H0) as [V Heq]. subst. apply* pf_dec_typ_unique. - clear IHHp3. apply pt2 in Hp1. assert (inert_sngl {{ q }}) as His. { right. eexists. eauto. } lets Hu: (pt2_sngl_unique' Hi H Hp1). inversion Hu. Qed. Lemma pt23_invert : forall G p q T, inert G -> G ⊢!! p : T -> G ⊢!!! p : {{ q }}-> exists q', {{ q' }} = T /\ (q = q' \/ G ⊢!!! q' : {{ q }}). Proof. introv Hi Hp Hpq. gen T. dependent induction Hpq; introv Hp. - exists q. split*. apply eq_sym. apply* pt2_sngl_unique'. - lets Hu: (pt2_sngl_unique' Hi H Hp). subst*. Qed. Lemma pt3_invert : forall G p q T, inert G -> G ⊢!!! p : T -> G ⊢!!! p : {{ q }}-> G ⊢!!! q: T \/ exists q', {{ q' }} = T /\ (q = q' \/ G ⊢!!! q' : {{ q }}). Proof. introv Hi Hp Hpq. gen q. dependent induction Hp; introv Hpq. - right. apply* pt23_invert. - destruct (pt23_invert Hi H Hpq) as [q' [Heq [Heq' | Hq']]]; inversions Heq; eauto. Qed. Lemma pt3_var_sngl G x p : inert G -> G ⊢!!! pvar x : {{ p }}-> False. Proof. intros Hi Hp. dependent induction Hp; false* pt2_var_sngl. Qed. Lemma pf_inert_pt2_sngl_false G p q T U : inert G -> G ⊢! p : T ⪼ U -> G ⊢!! p : {{ q }}-> inert_typ T -> False. Proof. intros Hi Hp Hq Hin. gen q. dependent induction Hp; eauto; introv Hpq. - false* pt3_var_sngl. - lets Hp': (pf_fld Hp). pose proof (pf_pt2_sngl Hi Hp' Hpq) as ->. inversion Hin. Qed. Lemma pf_inert_pt3_sngl_false G p q T U : inert G -> G ⊢! p : T ⪼ U -> G ⊢!!! p : {{ q }}-> inert_typ T -> False. Proof. intros Hi Hp Hq Hin. gen T U. dependent induction Hq; introv Hin; introv Hp; apply* pf_inert_pt2_sngl_false. Qed. Lemma pt3_inert_pt2_sngl_invert G p q T : inert G -> G ⊢!!! p : T -> G ⊢!! p : {{ q }}-> inert_typ T -> G ⊢!!! q : T. Proof. intros Hi Hp Hpq Hin. gen q. induction Hp; introv Hpq. - pose proof (pt2_sngl_unique' Hi Hpq H) as ->. inversion Hin. - pose proof (pt2_sngl_unique Hi H Hpq) as ->. eauto. Qed. Lemma pt3_inert_sngl_invert G p q T : inert G -> G ⊢!!! p : T -> G ⊢!!! p : {{ q }}-> inert_typ T -> G ⊢!!! q : T. Proof. introv Hi Hp Hpq. gen T. dependent induction Hpq; introv Hp Hin; [.. | apply* IHHpq]; eapply (pt3_inert_pt2_sngl_invert Hi Hp); eauto. Qed. Lemma pt2_dec_typ_tight: forall G p A S U, inert G -> G ⊢!! p: typ_rcd {A >: S <: U} -> S = U. Proof. introv Hi Hp. dependent induction Hp; eauto. apply* pf_dec_typ_tight. Qed. Lemma pt3_dec_typ_tight: forall G p A S U, inert G -> G ⊢!!! p: typ_rcd {A >: S <: U} -> S = U. Proof. introv Hi Hp. dependent induction Hp; eauto. apply* pt2_dec_typ_tight. Qed. Lemma last_path G p T U : inert G -> G ⊢!!! p : ∀(T) U -> G ⊢!! p : ∀(T) U \/ exists q, G ⊢!!! p: {{ q }} /\ G ⊢!! q : ∀(T) U. Proof. intros Hi Hp. dependent induction Hp; eauto. specialize (IHHp _ _ Hi eq_refl) as [Hq | [r [Hq Hr]]]; eauto. Qed. Lemma pt2_qbs_typed G p q T bs V: inert G -> G ⊢! p : {{ q }} ⪼ {{ q }} -> G ⊢!! q : T -> G ⊢!! p••bs : V -> exists U, G ⊢!! q •• bs : U. Proof. intros Hi Hp Hq Hpbs. pose proof (pf_pt2_trans_inv_mult _ Hi Hp Hpbs) as ->. gen T. dependent induction Hpbs. - pose proof (pf_sngl_flds_elim _ Hi Hp H) as ->. rewrite* field_sel_nil. - destruct p0 as [p0x p0bs]. destruct p as [px pbs]. destruct q as [qx qbs]. destruct q0 as [q0x q0bs]. inversions x0. inversions x. simpl in IHHpbs2, IHHpbs1. destruct bs as [|b bs]. + rewrite app_nil_l in *. subst. eauto. + rewrite <- app_comm_cons in *. inversions H1. inversions H2. eauto. Qed. (** ** Wellformed paths and environments *) Inductive wf : ctx -> Prop := | wfe_empty : wf empty | wfe_push G x T : wf G -> x # G -> (forall bs q, G & x ~ T ⊢! p_sel (avar_f x) bs : {{ q }}⪼ {{ q }}-> exists U, G & x ~ T ⊢!! q : U) -> wf (G & x ~ T). Hint Constructors wf. Lemma wf_prefix_one G x T : wf (G & x ~ T) -> wf G. Proof. intros Hwf. dependent induction Hwf. - false* empty_push_inv. - apply eq_push_inv in x as [-> [-> ->]]. destruct G as [|G x U] using env_ind; auto. Qed. Lemma wf_prefix G G' : wf (G & G') -> wf G. Proof. intros Hwf. gen G. induction G' using env_ind; introv Hwf. - rewrite concat_empty_r in Hwf; auto. - rewrite concat_assoc in *. apply IHG'. apply* wf_prefix_one. Qed. Hint Resolve wf_prefix wf_prefix_one. (** ** Strengthening and Typing of Singleton Types *) (** Strengthening is the opposite of weakening: removing elements of the typing environment. The strengthening lemmas state that in a well-formed environment [Γ, x: T], precise typing of a path [y.bs] is preserved in the strengthened environment [Γ] if [x ≠ y]. *) Lemma pf_strengthen_one_helper G y bs T x q : inert (G & x ~ T) -> wf G -> G & x ~ T ⊢! p_sel (avar_f y) bs : {{ q }}⪼ {{ q }}-> x <> y -> exists U, G ⊢!! q : U. Proof. intros Hi Hwf. gen y bs q x T. dependent induction Hwf; introv Hi Hy Hn. - rewrite concat_empty_l in *. apply precise_to_general in Hy. apply typing_implies_bound in Hy as [S Hb]. apply binds_single_inv in Hb as [-> _]. false*. - apply pf_strengthen in Hy; auto. destruct (classicT (x = y)) as [-> | Hn']; eauto. specialize (IHHwf _ _ _ _ _ (inert_prefix Hi) Hy Hn') as [S Hq]. eexists. apply* pt2_weaken. apply inert_ok. apply inert_prefix in Hi; auto. Qed. Lemma pt2_strengthen_one_helper G y bs T x q : inert (G & x ~ T) -> wf G -> G & x ~ T ⊢!! p_sel (avar_f y) bs : {{ q }}-> x <> y -> G ⊢!! p_sel (avar_f y) bs : {{ q }}/\ exists S, G ⊢!! q : S. Proof. intros Hi Hwf Ht Hn. dependent induction Ht. - split. econstructor. apply* pf_strengthen. apply* pf_strengthen_one_helper. pose proof (pf_sngl_T Hi H) as ->. apply H. - simpl_dot. specialize (IHHt1 _ _ _ _ _ _ Hi Hwf JMeq_refl eq_refl eq_refl Hn) as [IHy [S IHq]]. pose proof (typed_paths_named (precise_to_general2 Ht2)) as [qx [qbs Heq]]. simpl_dot. simpl in IHHt2. assert (x0 <> qx) as Hn'. { pose proof (typing_implies_bound (precise_to_general2 IHq)) as [W Hb]. apply inert_ok in Hi. intros ->. apply ok_push_inv in Hi as [_ Hq]. eapply binds_fresh_inv; eauto. } rewrite proj_rewrite in *. pose proof (pt2_inertsngl Hi Ht2) as [[Hin | [q ->]] | Hr]. + pose proof (pt2_to_pf Ht2 (or_introl Hin)) as [? Hpr]. apply pf_strengthen in Hpr; auto; split*. + specialize (IHHt2 _ _ _ _ _ _ Hi Hwf JMeq_refl eq_refl eq_refl Hn') as [IHqx [W IHq']]. split. * rewrite proj_rewrite in *. eauto. * simpl. eexists; eauto. + pose proof (pt2_to_pf Ht2 (or_intror Hr)) as [? Hpr]. apply pf_strengthen in Hpr; auto; split*. Qed. Lemma pt2_strengthen_one G y bs T x U : inert (G & x ~ T) -> wf G -> G & x ~ T ⊢!! p_sel (avar_f y) bs : U -> x <> y -> G ⊢!! p_sel (avar_f y) bs : U. Proof. intros Hi Hwf Ht Hn. pose proof (pt2_inertsngl Hi Ht) as [[Hin | [q ->]] | Hr]. - pose proof (pt2_to_pf Ht (or_introl Hin)) as [? Hpr]. apply pf_strengthen in Hpr; eauto. - apply* pt2_strengthen_one_helper. - pose proof (pt2_to_pf Ht (or_intror Hr)) as [? Hpr]. apply pf_strengthen in Hpr; eauto. Qed. (** *** Typing of paths that form singleton types *) (** The following lemmas state that if a path has a precise type [q.type] in a well-formed environment, then [q] is typeable. *) Lemma sngl_typed G p q : inert G -> wf G -> G ⊢! p: {{ q }}⪼ {{ q }}-> exists T, G ⊢!! q: T. Proof. intros Hi Hwf Hp. gen p q. induction Hwf; introv Hpq. - apply precise_to_general in Hpq. false* typing_empty_false. - pose proof (typed_paths_named (precise_to_general Hpq)) as [px [pbs ->]]. destruct (classicT (x = px)) as [-> | Hn]; eauto. pose proof (pf_strengthen_one_helper Hi Hwf Hpq Hn) as [U Hq]. eexists. apply* pt2_weaken. Qed. Lemma sngl_typed2 : forall G p q, inert G -> wf G -> G ⊢!! p: {{ q }}-> exists T, G ⊢!! q: T. Proof. introv Hi Hwf Hpq. dependent induction Hpq; eauto. pose proof (pf_sngl_T Hi H) as ->. apply* sngl_typed. Qed. Lemma sngl_typed3 : forall G p q, inert G -> wf G -> G ⊢!!! p: {{ q }}-> exists T, G ⊢!!! q: T. Proof. introv Hi Hwf Hp. dependent induction Hp; eauto. destruct* (sngl_typed2 Hi Hwf H). Qed. Lemma pt2_fld_strengthen G p a T U G' : inert (G & G') -> wf G -> G ⊢!! p : T -> G & G' ⊢!! p • a : U -> G ⊢!! p • a : U. Proof. intros Hi Hwf Hp Hpa. gen T. dependent induction Hpa; introv Hp. - pose proof (pf_strengthen_full Hi H) as [G1 [G2 [px [pbs [V [HeqG [Heqp Hp1]]]]]]]. simpl_dot. pose proof (pt2_destruct_env (inert_prefix Hi) Hp) as [G1' [G2' [px' [pbs' [V' [-> [= -> ->]]]]]]]. rewrite <- concat_assoc in *. apply env_ok_inv' in HeqG as [-> [-> <-]]. + rewrite concat_assoc in *. apply* pt2_weaken. apply* inert_ok. apply* inert_prefix. + apply* inert_ok. - simpl_dot. destruct f0. + pose proof (typed_paths_named (precise_to_general2 Hpa1)) as [px [pbs [= -> <-]]]. false* pt2_var_sngl. + rewrite proj_rewrite in *. pose proof (pt2_backtrack _ _ Hp) as [W Hpb]. specialize (IHHpa1 _ _ _ _ Hi Hwf JMeq_refl eq_refl _ Hpb). specialize (IHHpa2 _ _ _ _ Hi Hwf JMeq_refl eq_refl). pose proof (sngl_typed2 (inert_prefix Hi) Hwf IHHpa1) as [X Hq]. eauto. Qed. Lemma pt2_strengthen G G1 G2 bs T x U : G = G1 & x ~ T & G2 -> inert G -> wf G -> G ⊢!! p_sel (avar_f x) bs : U -> G1 & x ~ T ⊢!! p_sel (avar_f x) bs : U. Proof. intros -> Hi Hwf Hp. induction G2 using env_ind. - rewrite concat_empty_r in *. auto. - destruct (classicT (x0 = x)) as [-> | Hn]. + apply inert_ok in Hi. apply ok_middle_inv_r in Hi. simpl_dom. apply notin_union in Hi as [Contra _]. false* notin_same. + rewrite concat_assoc in *. eapply pt2_strengthen_one in Hp; auto. specialize (IHG2 (inert_prefix Hi) (wf_prefix Hwf) Hp). eauto. apply* wf_prefix. Qed. Lemma pt3_strengthen_one G bs T x y U : inert (G & x ~ T) -> wf (G & x ~ T) -> G & x ~ T ⊢!!! p_sel (avar_f y) bs : U -> y <> x -> G ⊢!!! p_sel (avar_f y) bs : U. Proof. intros Hi Hwf Hp Hn. dependent induction Hp. - constructor. apply* pt2_strengthen_one. - pose proof (sngl_typed2 Hi Hwf H) as [U Ht%precise_to_general2]. apply typed_paths_named in Ht as [qx [qbs ->]]. destruct (classicT (qx = x)) as [-> | Hn']. + clear IHHp. apply pt2_strengthen_one in H; eauto. apply (sngl_typed2 (inert_prefix Hi)) in H as [S Ht]; eauto. apply (pt2_destruct_env (inert_prefix Hi)) in Ht as [G1 [G2 [px [pbs [V [-> [= -> ->]]]]]]]. apply inert_ok in Hi. rewrite <- concat_assoc in Hi. apply ok_middle_inv_r in Hi. simpl_dom. apply notin_union in Hi as [Contra _]. false* notin_same. + apply pt2_strengthen_one in H; eauto. Qed. Lemma pt3_strengthen G G1 G2 bs T x U : G = G1 & x ~ T & G2 -> inert G -> wf G -> G ⊢!!! p_sel (avar_f x) bs : U -> G1 & x ~ T ⊢!!! p_sel (avar_f x) bs : U. Proof. intros -> Hi Hwf Hp. induction G2 using env_ind. - rewrite concat_empty_r in *. auto. - destruct (classicT (x0 = x)) as [-> | Hn]. + apply inert_ok in Hi. apply ok_middle_inv_r in Hi. simpl_dom. apply notin_union in Hi as [Contra _]. false* notin_same. + rewrite concat_assoc in *. apply pt3_strengthen_one in Hp; auto. specialize (IHG2 (inert_prefix Hi) (wf_prefix Hwf) Hp). eauto. Qed. Lemma pt2_strengthen_full G p T : inert G -> wf G -> G ⊢!! p : T -> exists G1 G2 x bs V, G = G1 & x ~ V & G2 /\ p = p_sel (avar_f x) bs /\ G1 & x ~ V ⊢!! p : T. Proof. intros Hi Hwf Hp. pose proof (pt2_destruct_env Hi Hp) as [G1 [G2 [x [bs [V [-> ->]]]]]]. repeat eexists. apply* pt2_strengthen. Qed. Lemma pt2_strengthen_from_pf G G' p bs T T' U : inert (G & G') -> wf (G & G') -> G ⊢! p: T ⪼ T' -> G & G' ⊢!! p••bs : U -> G ⊢!! p••bs : U. Proof. intros Hi Hwf Hp1 Hp2. gen U. induction bs; introv Hp2. - rewrite field_sel_nil in *. apply pt2_strengthen_full in Hp2 as [G1 [G2 [px [pbs [V [Heq [-> Ht]]]]]]]; auto. pose proof (pt2_destruct_env (inert_prefix Hi) (pt2 Hp1)) as [G1' [G2' [px' [pbs' [V' [-> [= -> ->]]]]]]]. rewrite <- concat_assoc in *. pose proof (inert_ok Hi) as Hok. apply env_ok_inv' in Heq as [-> [-> <-]]; rewrite concat_assoc in *; auto. apply* pt2_weaken. - rewrite proj_rewrite' in *. pose proof (pt2_backtrack _ _ Hp2) as [V Hb]. specialize (IHbs _ Hb). pose proof (pt2_fld_strengthen _ Hi (wf_prefix Hwf) IHbs Hp2). eauto. Qed. Lemma pt3_strengthen_full G p T : inert G -> wf G -> G ⊢!!! p : T -> exists G1 G2 x bs V, G = G1 & x ~ V & G2 /\ p = p_sel (avar_f x) bs /\ G1 & x ~ V ⊢!!! p : T. Proof. intros Hi Hwf Hp. induction Hp. - pose proof (pt2_destruct_env Hi H) as [G1 [G2 [x [bs [V [-> ->]]]]]]. repeat eexists. constructor. apply* pt2_strengthen. - specialize (IHHp Hi Hwf) as [G1 [G2 [x [bs [V [-> [-> Hp3]]]]]]]. pose proof (pt2_strengthen_full Hi Hwf H) as [G1' [G2' [y [cs [W3 [Heq [-> Hp2]]]]]]]. do 5 eexists. split. apply Heq. split*. assert (inert (G1' & y ~ W3)) as Hi' by (rewrite Heq in Hi; apply* inert_prefix). assert (wf (G1' & y ~ W3)) as Hwf'. { rewrite Heq in Hwf. eapply wf_prefix. eauto. } pose proof (sngl_typed2 Hi' Hwf' Hp2) as [U Hx]. apply (pt2_strengthen_full Hi') in Hx as [G1'' [G2'' [z [ds [X [HeqG [[= <- <-] Hx]]]]]]]. rewrite HeqG in Heq. do 2 rewrite <- concat_assoc in Heq. rewrite concat_assoc in Heq. apply env_ok_inv in Heq as [-> [-> ->]]. apply pt2_weaken with (G':=G2'') in Hx. rewrite <- HeqG in Hx. eapply pt3_sngl_trans. apply Hp2. rewrite HeqG. apply* pt3_weaken. rewrite concat_assoc in Hi. apply inert_ok. apply* inert_prefix. rewrite concat_assoc in Hi. apply inert_ok. apply* inert_prefix. rewrite Heq in Hi. apply* inert_ok. auto. Qed. Lemma pt3_fld_strengthen G p a T U G' : inert (G & G') -> wf (G & G') -> G ⊢!!! p : T -> G & G' ⊢!!! p • a : U -> G ⊢!!! p • a : U. Proof. intros Hi Hwf Hp Hpa. pose proof (pt3_strengthen_full Hi Hwf Hpa) as [G1 [G2 [px [pbs [V [HeqG [Heqp Hp1]]]]]]]. simpl_dot. pose proof (pt3_strengthen_full (inert_prefix Hi) (wf_prefix Hwf) Hp) as [G1' [G2' [px' [pbs' [V' [-> [[= <- <-] HHH]]]]]]]. rewrite <- concat_assoc in *. apply env_ok_inv' in HeqG as [-> [-> <-]]; auto. rewrite concat_assoc in *. apply* pt3_weaken. apply inert_ok. apply* inert_prefix. Qed. Lemma pf_strengthen_from_pt3 G G' p T U V : inert (G & G') -> wf (G & G') -> G ⊢!!! p: T -> G & G' ⊢! p : U ⪼ V -> G ⊢! p : U ⪼ V. Proof. intros Hi Hwf Hp3 Hpf. apply (pf_strengthen_full Hi) in Hpf as [G1 [G2 [px [pbs [W [Heq [-> Hpf]]]]]]]. apply (pt3_strengthen_full (inert_prefix Hi)) in Hp3 as [G1' [G2' [? [? [? [-> [[= <- <-] Hp3]]]]]]]. rewrite <- concat_assoc in Heq. apply env_ok_inv in Heq as [-> [-> <-]]. apply* pf_weaken. apply inert_ok. apply* inert_prefix. rewrite concat_assoc in Heq. rewrite Heq in Hi. auto. apply* wf_prefix. Qed. (** ** Replacement Composition *) (** The [typed_repl_comp_qp] relation for equivalent types under a given environment states that for two types [T] and [U], [T[q/p]=U], where [p] and [q] are typed the environment. *) Definition typed_repl_comp_qp G T1 T2 := exists p q U, G ⊢! p: {{ q }} ⪼ {{ q }} /\ G ⊢!! q : U /\ repl_typ q p T1 T2. (** Reflexivte, transitive closure of [typed_repl_comp_qp]. [repl_composition_qp] allows us to express that types are equivalent as a result of multiple replacements *) Definition repl_composition_qp G := star (typed_repl_comp_qp G). Notation "G '⊢' T '⟿' U" := (repl_composition_qp G U T) (at level 40, T at level 59). Inductive typed_path_repl_comp_qp: ctx -> path -> path -> Prop := | tpr_path: forall G p q U bs, G ⊢! p: {{ q }} ⪼ {{ q }} -> G ⊢!! q : U -> typed_path_repl_comp_qp G (q •• bs) (p •• bs). Definition repl_composition_qp_p G := star (typed_path_repl_comp_qp G). Notation "G '⊢' p '⟿'' q" := (repl_composition_qp_p G q p) (at level 40, p at level 59). (** In a well-formed environment, there is a precise-typing relation between equivalent singleton paths *) Lemma repl_comp_to_prec': forall G G' p q T, inert (G & G') -> wf (G & G') -> G ⊢ {{ p }} ⟿ {{ q }} -> G & G' ⊢!!! p: T -> p = q \/ G ⊢!!! p: {{ q }}. Proof. introv Hi Hwf Hr Hp. gen T. dependent induction Hr; introv Hp; eauto. assert (exists r, b = {{ r }}) as [r Heq]. { inversion H as [? [? [? [? [? Hr']]]]]. inversion* Hr'. } subst. specialize (IHHr _ _ Hi Hwf eq_refl eq_refl). destruct (IHHr _ Hp). subst. - destruct H as [p1 [p2 [S [H1 [Hq H2]]]]]. right. inversions H2. destruct (pt2_exists Hp) as [U Hu]. apply (pt2_strengthen_from_pf _ Hi Hwf H1) in Hu. lets Hpf: (pf_pt2_trans_inv_mult _ (inert_prefix Hi) H1 Hu). subst*. - specialize (IHHr _ Hp). destruct H as [p1 [p2 [S [H1 [Hq H2]]]]]. destruct (repl_prefixes_sngl H2) as [bs [He1 He2]]. subst. destruct IHHr as [Heq | IH]. * subst. right. lets Hs: (sngl_typed3 (inert_prefix Hi) (wf_prefix Hwf) (pt3 (pt2 H1))). destruct Hs. apply* pt3_trans_trans. apply* inert_prefix. * right*. apply* pt3_sngl_trans3. lets Hs: (sngl_typed3 (inert_prefix Hi) (wf_prefix Hwf) IH). destruct Hs. apply* pt3_trans_trans. apply* inert_prefix. Qed. (** The following lemmas reasoning about further properties of equivalent types. *) Lemma repl_comp_sngl_inv1 : forall G T p, G ⊢ {{ p }} ⟿ T -> exists q, T = {{ q }}. Proof. introv Hr. dependent induction Hr; eauto. specialize (IHHr _ eq_refl). destruct_all. subst. inversions H. destruct_all. invert_repl. eexists. auto. Qed. Lemma repl_comp_sngl_inv2 : forall G T p, G ⊢ T ⟿ {{ p }}-> exists q, T = {{ q }}. Proof. introv Hr. dependent induction Hr; eauto. inversions H. destruct_all. invert_repl. specialize (IHHr _ eq_refl). destruct_all. eexists. eauto. Qed. Lemma repl_comp_bnd_inv1 G T U : G ⊢ μ U ⟿ T -> exists S, T = μ S. Proof. introv Hr. dependent induction Hr; eauto. specialize (IHHr _ eq_refl). destruct_all. subst. inversions H. destruct_all. invert_repl. eexists; eauto. Qed. Lemma repl_comp_bnd_inv2 G T U : G ⊢ T ⟿ μ U -> exists S, T = μ S. Proof. introv Hr. dependent induction Hr; eauto. inversions H. destruct_all. invert_repl. specialize (IHHr _ eq_refl). destruct_all. eexists. eauto. Qed. Lemma repl_comp_bnd': forall G T T', G ⊢ μ T ⟿ μ T' -> G ⊢ T ⟿ T'. Proof. introv Hr. dependent induction Hr. - apply star_refl. - destruct H as [?[?[?[?[? Hr']]]]]. assert (exists V, b = μ V) as [V ->]. { invert_repl. eauto. } apply star_trans with (b:=V). apply star_one. econstructor. repeat eexists. apply H. inversion* H0. invert_repl. eauto. apply* IHHr. Qed. Lemma repl_comp_trm_rcd G a T S : G ⊢ typ_rcd { a ⦂ T } ⟿ S -> exists T', S = typ_rcd { a ⦂ T' } /\ G ⊢ T ⟿ T'. Proof. intros Hr. dependent induction Hr. - repeat eexists; apply star_refl. - destruct H as [p[q[U[Hp[Hq Hr']]]]]. specialize (IHHr _ _ eq_refl) as [T' [-> Hrr]]. invert_repl. eexists; split; eauto. apply star_trans with (b:=T'); auto. apply star_one. econstructor; repeat eexists; eauto. Qed. Lemma repl_comp_trm_rcd' G a T S : G ⊢ S ⟿ typ_rcd { a ⦂ T } -> exists T', S = typ_rcd { a ⦂ T' } /\ G ⊢ T' ⟿ T . Proof. intros Hr. dependent induction Hr. - repeat eexists; apply star_refl. - destruct H as [p[q[U[Hp[Hq Hr']]]]]. invert_repl. specialize (IHHr _ _ eq_refl) as [T' [-> Hrr]]. eexists; split; eauto. apply star_trans with (b:=T2); auto. apply star_one. econstructor; repeat eexists; eauto. Qed. Lemma repl_comp_typ_and1 G T U S : G ⊢ S ⟿ T ∧ U -> exists T' U', S = T' ∧ U' /\ G ⊢ T' ⟿ T /\ G ⊢ U' ⟿ U. Proof. intros Hr. dependent induction Hr. - repeat eexists; apply star_refl. - destruct H as [p[q[V[Hp[Hq Hr']]]]]. invert_repl; specialize (IHHr _ _ eq_refl) as [T' [U' [-> [Hr1 Hr2]]]]; repeat eexists; eauto; apply star_trans with (b:=T2); auto; apply star_one; econstructor; repeat eexists; eauto. Qed. Lemma repl_comp_typ_and2 G T U S : G ⊢ T ∧ U ⟿ S -> exists T' U', S = T' ∧ U' /\ G ⊢ T ⟿ T' /\ G ⊢ U ⟿ U'. Proof. intros Hr. dependent induction Hr. - repeat eexists; apply star_refl. - destruct H as [p[q[V[Hp[Hq Hr']]]]]. specialize (IHHr _ _ eq_refl) as [T' [U' [-> [Hr1 Hr2]]]]; invert_repl; repeat eexists; eauto; [ apply star_trans with (b:=T') | apply star_trans with (b:=U') ]; auto; apply star_one; econstructor; repeat eexists; eauto. Qed. Lemma repl_comp_record_has2 G T U U' a : G ⊢ T ⟿ U -> record_has U { a ⦂ U' } -> exists T', record_has T { a ⦂ T' } /\ G ⊢ T' ⟿ U'. Proof. intros Hrc Hr. gen T. dependent induction Hr; introv Hrc. - apply repl_comp_trm_rcd' in Hrc as [T' [-> Hr]]. eauto. - apply repl_comp_typ_and1 in Hrc as [T' [U'' [-> [Hrc1 Hrc2]]]]. specialize (IHHr _ _ eq_refl _ Hrc1) as [V [Hr' Hrc]]. eexists. split. apply rh_andl. eauto. auto. - apply repl_comp_typ_and1 in Hrc as [T' [U'' [-> [Hrc1 Hrc2]]]]. specialize (IHHr _ _ eq_refl _ Hrc2) as [V [Hr' Hrc]]. eexists. split. apply rh_andr. eauto. auto. Qed. Lemma repl_comp_record_has1 G T U T' a : G ⊢ T ⟿ U -> record_has T { a ⦂ T' } -> exists U', record_has U { a ⦂ U' } /\ G ⊢ T' ⟿ U'. Proof. intros Hrc Hr. gen U. dependent induction Hr; introv Hrc. - apply repl_comp_trm_rcd in Hrc as [T'' [-> Hr]]. eauto. - apply repl_comp_typ_and2 in Hrc as [T'' [U'' [-> [Hrc1 Hrc2]]]]. specialize (IHHr _ _ eq_refl _ Hrc1) as [V [Hr' Hrc]]. eexists. split. apply rh_andl. eauto. auto. - apply repl_comp_typ_and2 in Hrc as [T'' [U'' [-> [Hrc1 Hrc2]]]]. specialize (IHHr _ _ eq_refl _ Hrc2) as [V [Hr' Hrc]]. eexists. split. apply rh_andr. eauto. auto. Qed. Lemma repl_composition_open G T U p : inert G -> G ⊢ T ⟿ U -> G ⊢ open_typ_p p T ⟿ open_typ_p p U. Proof. intros Hi Hrc. dependent induction Hrc. - apply star_refl. - eapply star_trans with (b:=open_typ_p p b); auto. destruct H as [q [r [V [Hp [Hq Hr]]]]]. apply star_one. econstructor. repeat eexists. apply Hp. eauto. apply* repl_open. apply precise_to_general2 in Hq. apply* typed_paths_named. apply precise_to_general in Hp. apply* typed_paths_named. Qed. Lemma repl_composition_weaken_one G x T U V : ok G -> x # G -> G ⊢ T ⟿ U -> G & x ~ V ⊢ T ⟿ U. Proof. intros Hok Hn Hr. gen x V. dependent induction Hr; intros. - constructor. - destruct H as [r [? [? [Hrq [? Hr']]]]]. eapply star_trans. apply star_one. econstructor. repeat eexists. apply* pf_weaken. apply* pt2_weaken. apply Hr'. apply* IHHr. Qed. Lemma repl_composition_weaken G G' T U : ok (G & G') -> G ⊢ T ⟿ U -> G & G' ⊢ T ⟿ U. Proof. intros Hok Hr. induction G' using env_ind. - rewrite* concat_empty_r. - rewrite concat_assoc in *. apply ok_push_inv in Hok as [? ?]. eapply repl_composition_weaken_one; eauto. Qed. Notation "G '⊩' T '⟿' U '⬳' V" := (G ⊢ T ⟿ U /\ G ⊢ V ⟿ U) (at level 40, T at level 59). Notation "G '⊩' p '⟿'' q '⬳' r" := (G ⊢ p ⟿' q /\ G ⊢ r ⟿' q) (at level 40, p at level 59). Lemma repl_comp_trans_open G S W T p : inert G -> G ⊩ S ⟿ W ⬳ T -> G ⊩ open_typ_p p S ⟿ open_typ_p p W ⬳ open_typ_p p T. Proof. split; apply* repl_composition_open. Qed. Lemma repl_comp_trans_record_has G T S U V a : G ⊩ T ⟿ S ⬳ U -> record_has U {a ⦂ V} -> exists V' S', record_has T {a ⦂ V'} /\ G ⊩ V' ⟿ S' ⬳ V. Proof. intros [Hc1 Hc2] Hr. pose proof (repl_comp_record_has1 Hc2 Hr) as [V1 [Hr1 Hc1']]. pose proof (repl_comp_record_has2 Hc1 Hr1) as [V2 [Hr2 Hc2']]. repeat eexists; eauto. Qed. Lemma field_typing_comp1: forall G r q a U, inert G -> G ⊢ q ⟿' r -> G ⊢!!! q•a : U -> exists T, G ⊢!!! r•a : T. Proof. introv Hi Hr Hq. gen a U. dependent induction Hr; introv Hq; eauto. destruct (IHHr _ _ Hq) as [T Hba]. destruct (pt3_backtrack _ _ Hba) as [U' Hb]. inversions H. apply* field_elim_q3. eapply pt3_trans_trans; eauto. Qed. Lemma field_typing_comp2: forall G r q a U, inert G -> G ⊢ r ⟿' q -> G ⊢!!! q•a : U -> exists T, G ⊢!!! r•a : T. Proof. introv Hi Hr Hq. gen a U. dependent induction Hr; introv Ha; eauto. apply IHHr with (U:=U). destruct (pt3_backtrack _ _ Ha) as [U' Hqbs]. inversions H. eapply pt3_trans2; eauto. eapply pt3_field_trans; eauto. Qed. Lemma repl_composition_fld_elim: forall G p q a T, inert G -> G ⊢ p ⟿' q -> G ⊢!!! p • a : T -> G ⊢ p•a ⟿' q•a. Proof. introv Hi Hr. gen T. dependent induction Hr; introv Ha. - apply star_refl. - destruct (field_typing_comp1 _ Hi Hr Ha) as [T1 Tb]. apply pt2_exists in Tb. destruct Tb as [U Tb]. inversions H. apply star_trans with (b:=(p •• bs)•a). * apply star_one. repeat rewrite <- proj_rewrite'. econstructor; eauto. * eapply IHHr. eauto. Qed.
{-# LANGUAGE FlexibleContexts, ConstraintKinds, DataKinds #-} import GHC.TypeLits import Numeric.LinearAlgebra.Static import qualified Numeric.LinearAlgebra as LA import System.Environment import Text.Printf (printf) -- TODO: Learn about statically typed matrices. -- TODO: Figure out how to avoid converting b/t lists and matrices. -- (Will basically require slicing and mapping over rows/colmns). -- -- Solution: extractRows and extractCols after the predictions line. -- Could get rid of the toColumns entry as well and separately extract. -- (Not really worth the time.) -- Create design matrix for polynomial powers. -- (or, just use Vector Double. But we want to keep generality.) -- expand :: (Element t, Field t, Num (Vector t)) => Vector t -> Int -> Matrix t expand :: (KnownNat n, KnownNat d) => R n -> L n d expand x deg = fromColumns $ map (x^) [0..deg] regress :: (Element t, Field t, Num (Vector t)) => Vector t -> Vector t -> Int -> Vector t regress x y deg = (expand x deg) <\> y -- ^ efficient pseudoinverse evalPoly :: (Element t, Field t, Product t, Num (Vector t)) => Vector t -> Vector t -> Vector t evalPoly coeff x = expand x (dim coeff - 1) <> coeff -- sumVector :: (Element t, Field t) => Vector t -> t squareDiff :: Vector Double -> Vector Double -> Vector Double squareDiff x y = mapVector (flip (^) 2) (x - y) sumVector :: Vector Double -> Double sumVector x = x <.> ones where ones = konst 1 (dim x) sumSquareDiff x y = sumVector $ squareDiff x y -- NB: This requires concrete types due to subroutines called: -- readFile :: FilePath -> IO String -- readMatrix :: String -> Matrix Double readData :: String -> IO [Vector Double] readData filename = fmap (toColumns . readMatrix) $ readFile filename maxDeg = 5 main = do args <- getArgs if null args then putStrLn "Usage: polyreg datafile" else do [x,y] <- readData "polyreg_data.txt" let models = map (regress x y) [1..maxDeg] predictions = map (flip evalPoly x) models residuals = map (squareDiff y) predictions predsview = fromColumns $ [x, y] ++ predictions residsview = fromColumns $ [x, y] ++ residuals totalerrs = map sumVector residuals putFormat = putStrLn . format " " (printf "%.2f") putStrLn "Modeling predictions" putFormat predsview putStrLn "Modeling residuals" putFormat residsview putStrLn "Total errors" putFormat $ fromRows [fromList totalerrs]
section \<open> Enumeration Extras \<close> theory Enum_extra imports "HOL-Library.Cardinality" begin subsection \<open> First Index Function \<close> text \<open> The following function extracts the index of the first occurrence of an element in a list, assuming it is indeed an element. \<close> fun first_ind :: "'a list \<Rightarrow> 'a \<Rightarrow> nat \<Rightarrow> nat" where "first_ind [] y i = undefined" | "first_ind (x # xs) y i = (if (x = y) then i else first_ind xs y (Suc i))" lemma first_ind_length: "x \<in> set(xs) \<Longrightarrow> first_ind xs x i < length(xs) + i" by (induct xs arbitrary: i, auto, metis add_Suc_right) lemma nth_first_ind: "\<lbrakk> distinct xs; x \<in> set(xs) \<rbrakk> \<Longrightarrow> xs ! (first_ind xs x i - i) = x" apply (induct xs arbitrary: i) apply (auto) apply (metis One_nat_def add.right_neutral add_Suc_right add_diff_cancel_left' diff_diff_left empty_iff first_ind.simps(2) list.set(1) nat.simps(3) neq_Nil_conv nth_Cons' zero_diff) done lemma first_ind_nth: "\<lbrakk> distinct xs; i < length xs \<rbrakk> \<Longrightarrow> first_ind xs (xs ! i) j = i + j" apply (induct xs arbitrary: i j) apply (auto) apply (metis less_Suc_eq_le nth_equal_first_eq) using less_Suc_eq_0_disj apply auto done subsection \<open> Enumeration Indices \<close> syntax "_ENUM" :: "type \<Rightarrow> logic" ("ENUM'(_')") translations "ENUM('a)" => "CONST Enum.enum :: ('a::enum) list" text \<open> Extract a unique natural number associated with an enumerated value by using its index in the characteristic list \<^term>\<open>ENUM('a)\<close>. \<close> definition enum_ind :: "'a::enum \<Rightarrow> nat" where "enum_ind (x :: 'a::enum) = first_ind ENUM('a) x 0" lemma length_enum_CARD: "length ENUM('a) = CARD('a)" by (simp add: UNIV_enum distinct_card enum_distinct) lemma CARD_length_enum: "CARD('a) = length ENUM('a)" by (simp add: length_enum_CARD) lemma enum_ind_less_CARD [simp]: "enum_ind (x :: 'a::enum) < CARD('a)" using first_ind_length[of x, OF in_enum, of 0] by (simp add: enum_ind_def CARD_length_enum) lemma enum_nth_ind [simp]: "Enum.enum ! (enum_ind x) = x" using nth_first_ind[of Enum.enum x 0, OF enum_distinct in_enum] by (simp add: enum_ind_def) lemma enum_distinct_conv_nth: assumes "i < CARD('a)" "j < CARD('a)" "ENUM('a) ! i = ENUM('a) ! j" shows "i = j" proof - have "(\<forall>i<length ENUM('a). \<forall>j<length ENUM('a). i \<noteq> j \<longrightarrow> ENUM('a) ! i \<noteq> ENUM('a) ! j)" using distinct_conv_nth[of "ENUM('a)", THEN sym] by (simp add: enum_distinct) with assms show ?thesis by (auto simp add: CARD_length_enum) qed lemma enum_ind_nth [simp]: assumes "i < CARD('a::enum)" shows "enum_ind (ENUM('a) ! i) = i" using assms first_ind_nth[of "ENUM('a)" i 0, OF enum_distinct] by (simp add: enum_ind_def CARD_length_enum) lemma enum_ind_spec: "enum_ind (x :: 'a::enum) = (THE i. i < CARD('a) \<and> Enum.enum ! i = x)" proof (rule sym, rule the_equality, safe) show "enum_ind x < CARD('a)" by (simp add: enum_ind_less_CARD[of x]) show "enum_class.enum ! enum_ind x = x" by simp show "\<And>i. i < CARD('a) \<Longrightarrow> x = ENUM('a) ! i \<Longrightarrow> i = enum_ind (ENUM('a) ! i)" by (simp add: enum_ind_nth) qed lemma enum_ind_inj: "inj (enum_ind :: 'a::enum \<Rightarrow> nat)" by (rule inj_on_inverseI[of _ "\<lambda> i. ENUM('a) ! i"], simp) lemma enum_ind_neq [simp]: "x \<noteq> y \<Longrightarrow> enum_ind x \<noteq> enum_ind y" by (simp add: enum_ind_inj inj_eq) end
Require Import floyd.base. Require Import floyd.assert_lemmas. Require Import floyd.client_lemmas. Require Import floyd.nested_field_lemmas. Require Import floyd.type_induction. Require Import floyd.reptype_lemmas. Require Import floyd.aggregate_type. Require Import floyd.sublist. Section PROJ_REPTYPE. Context {cs: compspecs}. Definition proj_gfield_reptype (t: type) (gf: gfield) (v: reptype t): reptype (gfield_type t gf) := match t, gf return (REPTYPE t -> reptype (gfield_type t gf)) with | Tarray t0 hi a, ArraySubsc i => fun v => Znth i v (default_val _) | Tstruct id _, StructField i => fun v => proj_struct i (co_members (get_co id)) v (default_val _) | Tunion id _, UnionField i => fun v => proj_union i (co_members (get_co id)) v (default_val _) | _, _ => fun _ => default_val _ end (unfold_reptype v). Fixpoint proj_reptype (t: type) (gfs: list gfield) (v: reptype t) : reptype (nested_field_type t gfs) := let res := match gfs as gfs' return reptype (match gfs' with | nil => t | gf :: gfs0 => gfield_type (nested_field_type t gfs0) gf end) with | nil => v | gf :: gfs0 => proj_gfield_reptype _ gf (proj_reptype t gfs0 v) end in eq_rect_r reptype res (nested_field_type_ind t gfs). End PROJ_REPTYPE.
= Sentence spacing =
function p = PlotHVLines(positions,direction,varargin) %PlotHVLines - Plot vertical (resp. horizontal) lines at listed x (resp. y). % % USAGE % % p = PlotHVLines(positions,direction,options) % % positions list of abscissae/ordinates % direction optional direction: 'h' or 'v' (default = 'v') % <options> options for function <a href="matlab:help plot">plot</a> % % Copyright (C) 2008-2012 by Michaël Zugaro % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 3 of the License, or % (at your option) any later version. if nargin < 1, error('Incorrect number of parameters (type ''help <a href="matlab:help PlotHVLines">PlotHVLines</a>'' for details).'); end if nargin < 2, direction = 'v'; else direction = lower(direction); end if min(size(positions)) > 2, error('List of abscissae/ordinates is not a vector (type ''help <a href="matlab:help PlotHVLines">PlotHVLines</a>'' for details).'); else positions = positions(:); end if ~isstring_FMAT(direction,'h','v'), varargin = {direction,varargin{:}}; direction = 'v'; end hold on; if strcmp(direction,'v'), yLim = ylim; for i = 1:size(positions,1), plot([positions(i,1) positions(i,1)],yLim,varargin{:}); end else xLim = xlim; for i = 1:size(positions,1), plot(xLim,[positions(i,1) positions(i,1)],varargin{:}); end end
If you’re looking for a paid apprenticeship, have graduated, and are looking to work full time in digital, events, promotions, shopper or operations, the Gateway to Greatness (GtoG) program is for you! This person will work under operation supporting multiple account teams helping with financial reporting, client services and research. This role will give people the opportunity to have the broadest view of the agency. They will come away understanding financial processes, client management and our approach to generating insights and creating strategies. At the end of this apprenticeship this person will have gained experience in multiple areas of the agency and be able to decide what area they would like to pursue.
lemma eventually_at_to_0: "eventually P (at a) \<longleftrightarrow> eventually (\<lambda>x. P (x + a)) (at 0)" for a :: "'a::real_normed_vector"
(* Nuevo constructor inteligente. *) Definition br (p m: N) (p1 p2: patriciaTree) : patriciaTree := match p1, p2 with | empty, _ => p2 | _, empty => p1 | _, _ => trie p m p1 p2 end.
module Sane where import Data.Fin as F -- -- open import Data.Empty open import Data.Unit -- open import Data.Unit.Core open import Data.Nat using (ℕ ; zero ; suc ; _+_ ; _>_ ) open import Data.Sum using (inj₁ ; inj₂ ) -- open import Data.Product renaming (map to _×→_) open import Data.Vec open import Function using ( id ) renaming (_∘_ to _○_) open import Relation.Binary.PropositionalEquality using ( _≡_ ; refl ; sym ; cong ; module ≡-Reasoning ) open ≡-Reasoning -- start re-splitting things up, as this is getting out of hand open import FT -- Finite Types open import VecHelpers open import NatSimple open import Eval -- not sure where else to put this [Z][A] hetType : {A B : Set} → (a : A) → A ≡ B → B hetType a refl = a -- construct a combinator which represents the swapping of the i-th and -- (i+1)-th 'bit' of a finite type. -- Best to think of this as an 'elementary permutation', in the same way -- we have 'elementary matrices' (which turn out to be permutations when they -- are unitary). swapi : {n : ℕ} → F.Fin n → (fromℕ (suc n)) ⇛ (fromℕ (suc n)) swapi {zero} () swapi {suc n} F.zero = assocl₊⇛ ◎ swap₊⇛ ⊕ id⇛ ◎ assocr₊⇛ swapi {suc n} (F.suc i) = id⇛ ⊕ swapi {n} i -- swapUpTo i permutes the combinator left by one up to i -- if possible values are X a b c Y d e, swapUpTo 3's possible outputs -- are a b c X Y d e swapUpTo : {n : ℕ} → F.Fin n → (fromℕ (suc n)) ⇛ (fromℕ (suc n)) swapUpTo F.zero = id⇛ swapUpTo (F.suc i) = (id⇛ ⊕ swapUpTo i) ◎ swapi F.zero -- swapDownFrom i permutes the combinator right by one up to i (the reverse -- of swapUpTo) swapDownFrom : {n : ℕ} → F.Fin n → (fromℕ (suc n)) ⇛ (fromℕ (suc n)) swapDownFrom F.zero = id⇛ swapDownFrom (F.suc i) = swapi F.zero ◎ (id⇛ ⊕ swapDownFrom i) -- TODO: verify that this is actually correct -- Idea: To swap n < m with each other, swap n, n + 1, ... , m - 1, m, then -- go back down, so that m and n are swapped and everything else is in the -- same spot -- makeSingleComb {combinator size} (arrayElement) (arrayIndex), -- gives a combinator which 'does' that, assuming i<j, else id⇛ makeSingleComb : {n : ℕ} → F.Fin n → F.Fin n → (fromℕ n) ⇛ (fromℕ n) makeSingleComb F.zero F.zero = id⇛ makeSingleComb F.zero (F.suc i) = id⇛ makeSingleComb (F.suc j) F.zero = swapDownFrom j ◎ swapi j ◎ swapUpTo j makeSingleComb (F.suc j) (F.suc i) = id⇛ ⊕ makeSingleComb j i -- swapm i returns a combinator that swaps 0 and i swapm : {n : ℕ} → F.Fin n → (fromℕ n) ⇛ (fromℕ n) swapm F.zero = id⇛ swapm (F.suc i) = swapUpTo i ◎ swapi i ◎ swapDownFrom i -- Correctness: after putting together i indices, the partial combinator c' is -- represented by the vector [1, 2, ... , n - (i +1)] ++ (last i v) -- -- Might want to bake in the correctness proof here---have the output be a -- combinator c, a vector v, and a proof that vecRep c v, then we just prove -- that the vector at the end is just the vector from the beginning -- -- Or just put them together and prove that they're related by vecRep with -- foldrWorks and that the end vector is the input vector; this is probably simpler -- (and is the approach currently reflected in the code below) -- swapInd i j returns a vector v′ where v′[i] = j, v′[j] = i, and v′[k] = k -- where k != j and k != i zeroIfEq : {n n′ : ℕ} → F.Fin n → F.Fin n → F.Fin (suc n′) → F.Fin (suc n′) zeroIfEq F.zero F.zero ret = F.zero zeroIfEq F.zero (F.suc j) ret = ret zeroIfEq (F.suc i) F.zero ret = ret zeroIfEq (F.suc i) (F.suc j) ret = zeroIfEq i j ret swapIndFn : {n : ℕ} → F.Fin n → F.Fin n → (F.Fin n → F.Fin n) swapIndFn F.zero j F.zero = j swapIndFn (F.suc i) F.zero F.zero = F.suc i swapIndFn (F.suc i) (F.suc j) F.zero = F.zero swapIndFn F.zero F.zero (F.suc x) = F.suc x swapIndFn {suc zero} F.zero (F.suc ()) (F.suc x) swapIndFn {suc (suc n)} F.zero (F.suc j) (F.suc x) = zeroIfEq j x (F.suc x) swapIndFn (F.suc i) F.zero (F.suc x) = zeroIfEq i x (F.suc x) swapIndFn (F.suc i) (F.suc j) (F.suc x) = F.suc (swapIndFn i j x) swapInd : {n : ℕ} → F.Fin n → F.Fin n → Vec (F.Fin n) n swapInd i j = tabulate (swapIndFn i j) swapIndVec : {n : ℕ} → F.Fin n → F.Fin n → Vec (F.Fin n) n → Vec (F.Fin n) n swapIndVec i j v = tabulate (λ k → v !! swapIndFn i j k) -- useful abbreviations 2+ : ℕ → ℕ 2+ n = suc (suc n) 3+ : ℕ → ℕ 3+ n = suc (2+ n) F2+ : {n : ℕ} → F.Fin n → F.Fin (2+ n) F2+ i = F.suc (F.suc i) F3+ : {n : ℕ} → F.Fin n → F.Fin (3+ n) F3+ i = F.suc (F2+ i) swap01 : {n : ℕ} → Vec (F.Fin (2+ n)) (2+ n) swap01 = F.suc F.zero ∷ F.zero ∷ tabulate F2+ swapIndIdAfterOne : {n : ℕ} → (i : F.Fin n) → (F2+ i) ≡ swapIndFn F.zero (F.suc F.zero) (F2+ i) swapIndIdAfterOne i = refl -- yesss finally it just works! swapIndSucDist : {n : ℕ} → (i j x : F.Fin n) → (F.suc (swapIndFn i j x)) ≡ (swapIndFn (F.suc i) (F.suc j) (F.suc x)) swapIndSucDist i j x = refl -- more useful abbreviations F1+swap : {n : ℕ} → (i : F.Fin n) → Vec (F.Fin (2+ n)) (suc n) F1+swap i = vmap F.suc (swapInd (F.inject₁ i) (F.suc i)) swapIndFn+ : {n : ℕ} → (i : F.Fin n) → F.Fin (suc n) → F.Fin (suc n) swapIndFn+ i = swapIndFn (F.inject₁ i) (F.suc i) swapInd++ : {n : ℕ} → (i : F.Fin n) → Vec (F.Fin (2+ n)) (2+ n) swapInd++ i = swapInd (F.inject₁ (F.suc i)) (F2+ i) swap≡ind₁ : {n : ℕ} → (i : F.Fin n) → F.zero ∷ F1+swap i ≡ swapInd++ i swap≡ind₁ {n} i = begin F.zero ∷ F1+swap i ≡⟨ cong (_∷_ F.zero) (begin F1+swap i ≡⟨ mapTab F.suc (swapIndFn+ i) ⟩ tabulate (F.suc ○ swapIndFn+ i) ≡⟨ tabf∼g _ _ (swapIndSucDist (F.inject₁ i) (F.suc i)) ⟩ (tabulate (swapIndFn+ (F.suc i) ○ F.suc) ∎)) ⟩ swapInd++ i ∎ -- vecRep c v relates a combinator c over normal types to the output -- vector it results in. This works only over a subset of combinators -- used in decompilation. data vecRep : {n : ℕ} → (fromℕ n) ⇛ (fromℕ n) → Vec (F.Fin n) n → Set where vr-id : {n : ℕ} → vecRep (id⇛ {fromℕ n}) (upTo n) vr-swap : {n : ℕ} → vecRep {suc (suc n)} (swapi {suc n} F.zero) swap01 vr-comp : {n : ℕ} {c₁ c₂ : (fromℕ n) ⇛ (fromℕ n)} {v₁ v₂ : Vec (F.Fin n) n} → vecRep c₁ v₁ → vecRep c₂ v₂ → vecRep (c₁ ◎ c₂) (v₁ ∘̬ v₂) vr-plus : {n : ℕ} → {c : (fromℕ n) ⇛ (fromℕ n)} → {v : Vec (F.Fin n) n} → vecRep {n} c v → vecRep {suc n} (id⇛ ⊕ c) (F.zero ∷ (vmap F.suc v)) -- Record for keeping a combinator, a vector, and a proof that they compute -- the same function. record Compiled (n : ℕ) : Set where constructor _►_⟨_⟩ field comb : (fromℕ n) ⇛ (fromℕ n) vec : Vec (F.Fin n) n proof : vecRep comb vec -- TODO: there might be a better vector to put in the vecRep here -- we'll need to see what's most amenable to proving swapUpToWorks swapiWorks : {n : ℕ} → (i : F.Fin n) → vecRep (swapi i) (swapInd (F.inject₁ i) (F.suc i)) swapiWorks {zero} () swapiWorks {suc n} F.zero = vr-swap swapiWorks {suc n} (F.suc i) = hetType (vr-plus (swapiWorks i)) (cong (vecRep (id⇛ ⊕ swapi i)) (swap≡ind₁ i)) -- permutations on vectors for specifying swapUpTo/DownFrom data _<F_ : {n : ℕ} → F.Fin n → F.Fin n → Set where zero-leq : {n : ℕ} → {i : F.Fin n} → F.zero <F (F.suc i) suc-leq : {n : ℕ} → {i j : F.Fin n} → i <F j → (F.suc i) <F (F.suc j) <suc : {n : ℕ} → (i j : F.Fin n) → (F.suc i) <F (F.suc j) → i <F j <suc i j (suc-leq p) = p dec<F : {n : ℕ} → (i j : F.Fin n) → Dec (i <F j) dec<F F.zero F.zero = no (λ ()) dec<F F.zero (F.suc j) = yes zero-leq dec<F (F.suc i) F.zero = no (λ ()) dec<F (F.suc i) (F.suc j) with dec<F i j dec<F (F.suc i) (F.suc j) | yes x = yes (suc-leq x) dec<F (F.suc i) (F.suc j) | no x = no (λ p → x (<suc i j p)) -- swap args of F.inject+ inj+ : {m n : ℕ} → F.Fin m → F.Fin (n + m) inj+ {m} {n} i = hetType (F.inject+ n i) (cong F.Fin (+-comm m n)) -- the library definition of + on Fin isn't what we want here, ugh _+F_ : {m n : ℕ} → F.Fin (suc m) → F.Fin n → F.Fin (m + n) _+F_ {m} {zero} F.zero () _+F_ {m} {suc n} F.zero j = inj+ {suc n} {m} j _+F_ {zero} {n} (F.suc ()) _ _+F_ {suc m} {n} (F.suc i) j = F.suc (i +F j) data _h≡_ {A : Set} : {B : Set} → A → B → Set₁ where hrefl : (x : A) → _h≡_ {A} {A} x x hetTypeIsID : {A B : Set} → (x : A) → (p : A ≡ B) → (hetType x p) h≡ x hetTypeIsID x refl = hrefl x -- Permute the first i elements of v to the right one (and i^th down to 0) -- Should correspond with swapDownFrom -- permuteRight : {n : ℕ} → (i : F.Fin n) → Vec (F.Fin n) n → Vec (F.Fin n) n -- permuteRight i v = tabulate (permRightFn v i) permuteRight : {n : ℕ} → (i : F.Fin n) → Vec (F.Fin n) n permuteRight {zero} () permuteRight {suc n} F.zero = upTo _ permuteRight {suc zero} (F.suc ()) permuteRight {suc (suc n)} (F.suc i) = F.suc (head (permuteRight i)) ∷ F.zero ∷ vmap F.suc (tail (permuteRight i)) -- redundant helper permRightID : {n : ℕ} → F.Fin n → Vec (F.Fin n) n permRightID i = permuteRight i -- The opposite of permuteRight; should correspond with swapUpTo pl′ : {m : ℕ} {A : Set} → F.Fin m → Vec A m → A → Vec A (suc m) pl′ {m = zero} () _ _ pl′ {m = suc m} F.zero (x ∷ xs) first = x ∷ first ∷ xs pl′ (F.suc i) (x ∷ xs) first = x ∷ (pl′ i xs first) permuteLeft : {n : ℕ} {A : Set} → (i : F.Fin n) → Vec A n → Vec A n permuteLeft {zero} () _ permuteLeft {suc n} F.zero v = v permuteLeft {suc zero} (F.suc ()) _ permuteLeft {suc (suc n)} (F.suc i) (a ∷ b ∷ rest) = pl′ i (b ∷ rest) a permLeftID : {n : ℕ} → F.Fin n → Vec (F.Fin n) n permLeftID i = permuteLeft i (upTo _) permLeftId₀ : {n : ℕ} → (upTo (suc n)) ≡ permuteLeft F.zero (upTo (suc n)) permLeftId₀ {n} = refl permLeftIdPasti : {n : ℕ} → (v : Vec (F.Fin (2+ n)) (2+ n)) → (i : F.Fin n) → permuteLeft (F.suc F.zero) v !! (F2+ i) ≡ v !! F2+ i permLeftIdPasti (x ∷ x₁ ∷ x₂ ∷ v) F.zero = refl permLeftIdPasti (x ∷ x₁ ∷ x₂ ∷ v) (F.suc i) = refl -- it should actually be possible to recur on this! -- and as an added bonus, it should actually be true! [Z] plCorr : {m n : ℕ} (v : Vec (F.Fin m) n) (i : F.Fin n) → vmap F.suc (pl′ i (vmap F.suc v) F.zero) ∘̬′ swap01 ≡ pl′ i (vmap F.suc (vmap F.suc v)) F.zero plCorr [] () plCorr (x ∷ v) F.zero = begin vmap F.suc (pl′ F.zero (vmap F.suc (x ∷ v)) F.zero) ∘̬′ swap01 ≡⟨ refl ⟩ (F.suc (F.suc x) ∷ F.suc F.zero ∷ vmap F.suc (vmap F.suc v)) ∘̬′ swap01 ≡⟨ refl ⟩ ((tabulate (F.suc ○ F.suc)) !! x) ∷ (F.suc F.zero ∷ vmap F.suc (vmap F.suc v)) ∘̬′ swap01 ≡⟨ cong (λ x → x ∷ (F.suc F.zero ∷ vmap F.suc (vmap F.suc v)) ∘̬′ swap01) (lookupTab x) ⟩ (F.suc (F.suc x)) ∷ ((F.suc F.zero ∷ vmap F.suc (vmap F.suc v)) ∘̬′ swap01) ≡⟨ refl ⟩ (F.suc (F.suc x)) ∷ F.zero ∷ ((vmap F.suc (vmap F.suc v)) ∘̬′ swap01) ≡⟨ cong (λ q → F.suc (F.suc x) ∷ F.zero ∷ q) (map2+id v) ⟩ F.suc (F.suc x) ∷ F.zero ∷ vmap F.suc (vmap F.suc v) ≡⟨ refl ⟩ pl′ F.zero (vmap F.suc (vmap F.suc (x ∷ v))) F.zero ∎ plCorr (x ∷ v) (F.suc i) = begin vmap F.suc (pl′ (F.suc i) (vmap F.suc (x ∷ v)) F.zero) ∘̬′ swap01 ≡⟨ refl ⟩ (tabulate (F.suc ○ F.suc) !! x) ∷ ((vmap F.suc (pl′ i (vmap F.suc v) F.zero)) ∘̬′ swap01) ≡⟨ cong (λ q → q ∷ ((vmap F.suc (pl′ i (vmap F.suc v) F.zero)) ∘̬′ swap01)) (lookupTab x) ⟩ F.suc (F.suc x) ∷ ((vmap F.suc (pl′ i (vmap F.suc v) F.zero)) ∘̬′ swap01) ≡⟨ cong (_∷_ (F.suc (F.suc x))) (plCorr v i) ⟩ F.suc (F.suc x) ∷ pl′ i (vmap F.suc (vmap F.suc v)) F.zero ≡⟨ refl ⟩ pl′ (F.suc i) (vmap F.suc (vmap F.suc (x ∷ v))) F.zero ∎ fzero : F.Fin 7 fzero = F.zero fone : F.Fin 7 fone = F.suc F.zero ftwo : F.Fin 7 ftwo = F.suc (F.suc F.zero) fthree : F.Fin 7 fthree = F.suc (F.suc (F.suc F.zero)) ffour : F.Fin 7 ffour = F.suc (F.suc (F.suc (F.suc F.zero))) ffive : F.Fin 7 ffive = F.suc (F.suc (F.suc (F.suc (F.suc F.zero)))) fsix : F.Fin 7 fsix = F.suc (F.suc (F.suc (F.suc (F.suc (F.suc F.zero))))) -- gzero : F.Fin 6 gzero = F.zero gone : F.Fin 6 gone = F.suc F.zero gtwo : F.Fin 6 gtwo = F.suc (F.suc F.zero) gthree : F.Fin 6 gthree = F.suc (F.suc (F.suc F.zero)) gfour : F.Fin 6 gfour = F.suc (F.suc (F.suc (F.suc F.zero))) gfive : F.Fin 6 gfive = F.suc (F.suc (F.suc (F.suc (F.suc F.zero)))) -- i=3 -- n=5 test1 : Vec (F.Fin 7) 7 test1 = permuteLeft ffour (fzero ∷ fone ∷ ftwo ∷ fthree ∷ ffour ∷ ffive ∷ fsix ∷ []) {-- test1 = (0 1) (1 2) (2 3) (3 4) (4 0) (5 5) (6 6) --} test2 : Vec (F.Fin 6) 6 test2 = permuteLeft gthree (gzero ∷ gone ∷ gtwo ∷ gthree ∷ gfour ∷ gfive ∷ []) {-- test2 = (0 1) (1 2) (2 3) (3 0) (4 4) (5 5) vmap F.suc test2 = (0 2) (1 3) (2 4) (3 1) (4 5) (5 6) F.zero ∷ vmap F.suc test2 = (0 0) (1 2) (2 3) (3 4) (4 1) (5 5) (6 6) swap01 = (0 1) (1 0) (2 2) (3 3) (4 4) (5 5) (6 6) (F.zero ∷ vmap F.suc test2) ∘̬ swap01 = (0 1) (1 2) (2 3) (3 4) (4 0) (5 5) (6 6) test1 = (0 1) (1 2) (2 3) (3 4) (4 0) (5 5) (6 6) --} -- glue lemma between plCorr and swapUpToWorks to deal with the difference between -- the result type of swapUpToWorks and the result type of the VecRep combinators -- We need this glue here to get from swapUpToWorks (which has two calls to permuteLeft) -- to plCorr (which has two calls to pl′), since permuteLeft is a wrapper around pl′. -- Once we've removed the wrapper, we can eat the delicious candy^W^W^W^Wactually do -- induction; hopefully the type of plCorr is general enough for this but not too general -- to, er, be true. [Z] sucWorks : {n : ℕ} → (i : F.Fin n) → (F.zero ∷ vmap F.suc (permuteLeft (F.inject₁ i) (upTo (suc n)))) ∘̬ swap01 ≡ pl′ {suc n} (F.inject₁ i) (tail (upTo (suc (suc n)))) F.zero sucWorks {suc n} F.zero = begin (F.zero ∷ vmap F.suc (permuteLeft F.zero (upTo (suc (suc n))))) ∘̬ swap01 ≡⟨ cong (λ x → (F.zero ∷ vmap F.suc x) ∘̬ swap01) (sym (permLeftId₀)) ⟩ (F.zero ∷ vmap F.suc (upTo (suc (suc n)))) ∘̬ swap01 ≡⟨ cong (λ x → (F.zero ∷ x) ∘̬ swap01) ((mapTab F.suc id)) ⟩ upTo (suc (suc (suc n))) ∘̬ swap01 ≡⟨ ∘̬simpleid swap01 ⟩ swap01 ≡⟨ refl ⟩ pl′ F.zero (tail (upTo (suc (suc (suc n))))) F.zero ∎ sucWorks {suc zero} (F.suc ()) sucWorks {suc (suc n)} (F.suc i) = begin (F.zero ∷ vmap F.suc (permuteLeft (F.inject₁ (F.suc i)) (upTo (suc (suc (suc n)))))) ∘̬ swap01 ≡⟨ ∘̬≡∘̬′ (F.zero ∷ vmap F.suc (permuteLeft (F.inject₁ (F.suc i)) (upTo (suc (suc (suc n)))))) swap01 ⟩ (F.zero ∷ vmap F.suc (permuteLeft (F.inject₁ (F.suc i)) (upTo (suc (suc (suc n)))))) ∘̬′ swap01 ≡⟨ refl ⟩ (F.zero ∷ vmap F.suc (pl′ (F.inject₁ i) (tail (upTo (suc (suc (suc n))))) F.zero)) ∘̬′ swap01 ≡⟨ refl ⟩ (F.suc F.zero) ∷ ((vmap F.suc (pl′ (F.inject₁ i) (tabulate F.suc) F.zero)) ∘̬′ swap01) ≡⟨ cong (λ q → F.suc F.zero ∷ vmap F.suc (pl′ (F.inject₁ i) q F.zero) ∘̬′ swap01) (sym (mapTab F.suc id)) ⟩ (F.suc F.zero) ∷ ((vmap F.suc (pl′ (F.inject₁ i) (vmap F.suc (tabulate id)) F.zero)) ∘̬′ swap01) ≡⟨ cong (_∷_ (F.suc F.zero)) (plCorr (tabulate id) (F.inject₁ i)) ⟩ (F.suc F.zero) ∷ (pl′ (F.inject₁ i) (vmap F.suc (vmap F.suc (tabulate id))) F.zero) ≡⟨ cong (λ q → F.suc F.zero ∷ pl′ (F.inject₁ i) (vmap F.suc q) F.zero) (mapTab F.suc id) ⟩ (F.suc F.zero) ∷ pl′ (F.inject₁ i) (vmap F.suc (tail (upTo (suc (suc (suc n)))))) F.zero ≡⟨ cong (λ x → (F.suc F.zero) ∷ pl′ (F.inject₁ i) x F.zero) (sym (upToTail (suc (suc n)))) ⟩ F.suc F.zero ∷ pl′ (F.inject₁ i) (tail (tail (upTo (suc (suc (suc (suc n))))))) F.zero ≡⟨ refl ⟩ pl′ (F.inject₁ (F.suc i)) (tail (upTo (suc (suc (suc (suc n)))))) F.zero ∎ -- NB: I added the F.inject₁ in calls to permuteLeft/Right to get it to work -- with swapUpTo/DownFrom; I'm not sure that this is correct? It might -- be a sign that the type of the swap functions is too specific, instead. -- (though now it looks like it will at least make the type of shuffle a bit nicer) [Z] swapUpToWorks : {n : ℕ} → (i : F.Fin n) → vecRep (swapUpTo i) (permuteLeft (F.inject₁ i) (upTo (suc n))) swapUpToWorks F.zero = vr-id swapUpToWorks (F.suc i) = hetType (vr-comp (vr-plus (swapUpToWorks i)) vr-swap) (cong (vecRep (swapUpTo (F.suc i))) (sucWorks i)) sdfWorks : {n : ℕ} → (i : F.Fin (suc n)) → swap01 ∘̬ (F.zero ∷ vmap F.suc (permuteRight i)) ≡ permuteRight (F.suc i) sdfWorks i = begin swap01 ∘̬ (F.zero ∷ vmap F.suc (permuteRight i)) ≡⟨ ∘̬≡∘̬′ swap01 (F.zero ∷ vmap F.suc (permuteRight i)) ⟩ swap01 ∘̬′ (F.zero ∷ vmap F.suc (permuteRight i)) ≡⟨ refl ⟩ (vmap F.suc (permuteRight i) !! F.zero) ∷ F.zero ∷ (tabulate (F.suc ○ F.suc) ∘̬′ (F.zero ∷ vmap F.suc (permuteRight i))) ≡⟨ cong (λ q → q ∷ F.zero ∷ tabulate (F.suc ○ F.suc) ∘̬′ (F.zero ∷ vmap F.suc (permuteRight i))) (head!!0 (vmap F.suc (permuteRight i))) ⟩ (head (vmap F.suc (permuteRight i))) ∷ F.zero ∷ (tabulate (F.suc ○ F.suc) ∘̬′ (F.zero ∷ vmap F.suc (permuteRight i))) ≡⟨ cong (λ q → q ∷ F.zero ∷ tabulate (F.suc ○ F.suc) ∘̬′ (F.zero ∷ vmap F.suc (permuteRight i))) (headmap (permuteRight i)) ⟩ (F.suc (head (permuteRight i))) ∷ F.zero ∷ (tabulate (F.suc ○ F.suc) ∘̬′ (F.zero ∷ vmap F.suc (permuteRight i))) ≡⟨ cong (λ q → F.suc (head (permuteRight i)) ∷ F.zero ∷ q) (sym (∘̬≡∘̬′ (tabulate (F.suc ○ F.suc)) (F.zero ∷ vmap F.suc (permuteRight i)))) ⟩ (F.suc (head (permuteRight i))) ∷ F.zero ∷ (tabulate (F.suc ○ F.suc) ∘̬ (F.zero ∷ vmap F.suc (permuteRight i))) ≡⟨ cong (λ q → F.suc (head (permuteRight i)) ∷ F.zero ∷ q) (2suc∘̬2tail (F.zero ∷ vmap F.suc (permuteRight i))) ⟩ (F.suc (head (permuteRight i))) ∷ F.zero ∷ (tail (vmap F.suc (permuteRight i))) ≡⟨ cong (λ q → F.suc (head (permuteRight i)) ∷ F.zero ∷ q) (tailmap (permuteRight i)) ⟩ (F.suc (head (permuteRight i))) ∷ F.zero ∷ (vmap F.suc (tail (permuteRight i))) ≡⟨ refl ⟩ permuteRight (F.suc i) ∎ swapDownFromWorks : {n : ℕ} → (i : F.Fin n) → vecRep (swapDownFrom i) (permuteRight (F.inject₁ i)) swapDownFromWorks F.zero = vr-id swapDownFromWorks (F.suc i) = hetType (vr-comp vr-swap (vr-plus (swapDownFromWorks i))) (cong (vecRep (swapDownFrom (F.suc i))) (sdfWorks (F.inject₁ i))) _◎∘̬_ : {n : ℕ} → Compiled n → Compiled n → Compiled n (c₁ ► v₁ ⟨ p₁ ⟩) ◎∘̬ (c₂ ► v₂ ⟨ p₂ ⟩) = ((c₁ ◎ c₂) ► v₁ ∘̬ v₂ ⟨ vr-comp p₁ p₂ ⟩ ) vecToComb : {n : ℕ} → Vec (F.Fin n) n → (fromℕ n) ⇛ (fromℕ n) vecToComb {n} vec = foldr (λ i → fromℕ n ⇛ fromℕ n) _◎_ id⇛ (map (λ i → makeSingleComb (vec !! i) i) (upTo n)) finToVal : {n : ℕ} → F.Fin n → ⟦ fromℕ n ⟧ finToVal F.zero = inj₁ tt finToVal (F.suc n) = inj₂ (finToVal n) valToFin : {n : ℕ} → ⟦ fromℕ n ⟧ → F.Fin n valToFin {zero} () valToFin {suc n} (inj₁ tt) = F.zero valToFin {suc n} (inj₂ v) = F.suc (valToFin v) finToValToFin : {n : ℕ} → (v : ⟦ fromℕ n ⟧) → finToVal (valToFin v) ≡ v finToValToFin {zero} () finToValToFin {suc n} (inj₁ tt) = refl -- (inj₁ tt) finToValToFin {suc n} (inj₂ v) = cong inj₂ (finToValToFin v) valToFinToVal : {n : ℕ} → (i : F.Fin n) → valToFin (finToVal i) ≡ i valToFinToVal F.zero = refl -- F.zero valToFinToVal (F.suc i) = cong F.suc (valToFinToVal i) combToVec : {n : ℕ} → (fromℕ n) ⇛ (fromℕ n) → Vec (F.Fin n) n combToVec c = tabulate (valToFin ○ (evalComb c) ○ finToVal) twoF4 : F.Fin four twoF4 = F.suc (F.suc F.zero) fourF5 : F.Fin five fourF5 = F.suc (F.suc F.zero) swapUpToTest : Vec (F.Fin five) five swapUpToTest = combToVec (swapUpTo twoF4) pltest : (n : ℕ) → (i : F.Fin n) → Vec (F.Fin n) n pltest n i = permuteLeft i (upTo n) prtest : Vec (F.Fin five) five prtest = permuteRight fourF5 -- (F.suc (F.suc (F.suc (F.suc F.zero)))) sdftest : Vec (F.Fin five) five sdftest = combToVec (swapDownFrom twoF4) sucomptest : {n : ℕ} → (i : F.Fin n) → Vec (F.Fin (suc (suc n))) (suc (suc n)) sucomptest {n} i = (F.zero ∷ vmap F.suc (permuteLeft (F.inject₁ i) (upTo (suc n)))) ∘̬ (F.suc F.zero ∷ F.zero ∷ vmap (F.suc ○ F.suc) (upTo n)) sit : Vec (F.Fin five) five sit = combToVec (swapi (F.suc (F.suc F.zero))) mntest : Vec (F.Fin five) five mntest = combToVec (makeSingleComb (F.suc (F.suc (F.suc F.zero))) F.zero) evalVec : {n : ℕ} → Vec (F.Fin n) n → F.Fin n → ⟦ fromℕ n ⟧ evalVec vec i = finToVal (lookup i vec) permLeftTest : F.Fin four permLeftTest = valToFin (evalVec (permLeftID (F.suc (F.suc F.zero))) (F.zero)) lookupToEvalVec : {n : ℕ} → (i : F.Fin n) → (v : Vec (F.Fin n) n) → lookup i v ≡ valToFin (evalVec v i) lookupToEvalVec i v = sym (valToFinToVal (lookup i v) ) -- Might want to take a ⟦ fromℕ n ⟧ instead of a Fin n as the second -- argument here? combToVecWorks : {n : ℕ} → (c : (fromℕ n) ⇛ (fromℕ n)) → (i : F.Fin n) → (evalComb c (finToVal i)) ≡ evalVec (combToVec c) i combToVecWorks c i = (sym (finToValToFin _)) ∘ (cong finToVal (sym (lookupTab i))) -- This lemma is the hammer that will let us use vecRep to (hopefully) simply -- prove some lemmas about the helper functions used in vecToComb, then apply -- vecRepWorks at the end to make sure they all "do the right thing" vecRepWorks : {n : ℕ} → {c : (fromℕ n) ⇛ (fromℕ n)} → {v : Vec (F.Fin n) n} → vecRep c v → (i : F.Fin n) → (evalVec v i) ≡ (evalComb c (finToVal i)) vecRepWorks vr-id i = cong finToVal (lookupTab i) vecRepWorks vr-swap F.zero = refl -- (inj₂ (inj₁ tt)) vecRepWorks vr-swap (F.suc F.zero) = refl -- (inj₁ tt) vecRepWorks {suc (suc n)} vr-swap (F.suc (F.suc i)) = cong finToVal (lookupTab i) vecRepWorks (vr-comp {n} {c₁} {c₂} {v₁} {v₂} vr vr₁) i = begin finToVal (lookup i (tabulate (λ j → lookup (lookup j v₁) v₂))) ≡⟨ cong finToVal (lookup∘tabulate i (λ j → lookup (lookup j v₁) v₂)) ⟩ finToVal (lookup (lookup i v₁) v₂) ≡⟨ cong (λ x → finToVal (lookup x v₂)) (lookupToEvalVec i v₁) ⟩ finToVal (lookup (valToFin (evalVec v₁ i)) v₂) ≡⟨ cong (λ x → finToVal (lookup (valToFin x) v₂)) (vecRepWorks vr i) ⟩ finToVal (lookup (valToFin (evalComb c₁ (finToVal i))) v₂) ≡⟨ cong finToVal (lookupToEvalVec (valToFin (evalComb c₁ (finToVal i))) v₂) ⟩ finToVal (valToFin (evalVec v₂ (valToFin (evalComb c₁ (finToVal i))))) ≡⟨ finToValToFin (evalVec v₂ (valToFin (evalComb c₁ (finToVal i)))) ⟩ evalVec v₂ (valToFin (evalComb c₁ (finToVal i))) ≡⟨ vecRepWorks vr₁ (valToFin (evalComb c₁ (finToVal i))) ⟩ evalComb c₂ (finToVal (valToFin (evalComb c₁ (finToVal i)))) ≡⟨ cong (evalComb c₂) (finToValToFin (evalComb c₁ (finToVal i))) ⟩ evalComb (c₁ ◎ c₂) (finToVal i) ∎ vecRepWorks {suc n} (vr-plus vr) F.zero = refl -- (inj₁ tt) vecRepWorks (vr-plus {c = c} {v = v} vr) (F.suc i) = begin evalVec (F.zero ∷ vmap F.suc v) (F.suc i) ≡⟨ cong finToVal (map!! F.suc v i) ⟩ inj₂ (finToVal (v !! i)) ≡⟨ cong inj₂ (vecRepWorks vr i) ⟩ (evalComb (id⇛ ⊕ c) (finToVal (F.suc i)) ∎) record Permut (n : ℕ) : Set where constructor per field vec : Vec (F.Fin n) n uniq : ∀ {i j : F.Fin n} → (vec !! i) ≡ (vec !! j) → i ≡ j -- this should also take a proof that i>0. pred′ : {n : ℕ} (i : F.Fin (suc (suc n))) → F.Fin (suc n) pred′ F.zero = F.zero pred′ (F.suc i) = i record NormComb (n : ℕ) : Set where constructor ⟪_,_⟫ field v : Vec (F.Fin n) n -- We can't actually have it be the stronger condition and still be -- able to properly recur on it as in vtc′. p : ∀ (i : F.Fin n) (j : F.Fin′ i) → (v !! (F.inject j) ≡ i) → (v !! i ≡ (F.inject j)) predToSuc : {n : ℕ} (i : F.Fin (suc n)) (j : F.Fin′ i) (x : F.Fin (suc (suc n))) (v : Vec (F.Fin (suc (suc n))) (suc n)) → vmap pred′ v !! F.inject j ≡ i → (∀ (i : F.Fin (suc (suc n))) (j : F.Fin′ i) → ((x ∷ v) !! (F.inject j) ≡ i) → ((x ∷ v) !! i ≡ (F.inject j))) → (x ∷ v) !! F.inject (F.suc j) ≡ F.suc i predToSuc i j x v p p₁ = begin (x ∷ v) !! F.inject (F.suc j) ≡⟨ refl ⟩ v !! F.inject j ≡⟨ {!refl!} ⟩ F.suc i ∎ nctail : {n : ℕ} → NormComb (suc n) → NormComb n nctail {zero} ⟪ x ∷ [] , p ⟫ = ⟪ [] , (λ ()) ⟫ nctail {suc n} ⟪ x ∷ v , p ⟫ = ⟪ vmap pred′ v , {!!} ⟫ vtc′ : {n : ℕ} (v : Vec (F.Fin n) n) → (fromℕ n) ⇛ (fromℕ n) vtc′ {zero} [] = id⇛ vtc′ {suc zero} (x ∷ []) = id⇛ -- can only swap with itself vtc′ {suc (suc n)} (F.zero ∷ v) = id⇛ ⊕ (vtc′ (vmap pred′ v)) vtc′ {suc (suc n)} ((F.suc i) ∷ v) = (id⇛ ⊕ (vtc′ (vmap pred′ v))) ◎ (swapm (F.suc i)) testvtc : {n : ℕ} → Vec (F.Fin n) n → Vec (F.Fin n) n testvtc v = combToVec (vtc′ v) testvtc0 : {n : ℕ} → Vec (F.Fin n) n → Vec (F.Fin n) n testvtc0 v = combToVec (vecToComb v) pl2 : Vec (F.Fin 5) 5 pl2 = permuteLeft (F.suc (F.suc F.zero)) (upTo 5) pr2 : Vec (F.Fin 5) 5 pr2 = permuteRight (F.suc (F.suc F.zero)) pred∘suc : {n : ℕ} (x : F.Fin (suc (suc n))) → ((F.toℕ x) > zero) → F.suc (pred′ x) ≡ x pred∘suc F.zero () pred∘suc (F.suc _) _ = refl -- Assumptions we need so far: -- - If the first element of a vec is zero, no other element is zero -- (to prove that "vmap F.suc (vmap pred′ v) == v") -- - Probably something for the last case, too magic1 : {n : ℕ} (v : Vec (F.Fin n) n) → vecRep (vtc′ v) v magic1 {zero} [] = vr-id magic1 {suc zero} (F.zero ∷ []) = vr-id magic1 {suc zero} (F.suc () ∷ []) -- this will need something reminiscent of LeftCancellation? magic1 {suc (suc n)} (F.zero ∷ v) = hetType (vr-plus (magic1 {suc n} (vmap pred′ v))) (cong (λ x → vecRep (id⇛ ⊕ vtc′ (vmap pred′ v)) (F.zero ∷ x)) ((vmap∘vmap F.suc pred′ v) ∘ (vmap∘id {!!}) )) -- swap and recurse? magic1 {suc (suc n)} (F.suc x ∷ v) = {!!} -- [JC] flip the conclusion around, as 'evalVec v i' is trivial. Makes -- equational reasoning easier vecToCombWorks : {n : ℕ} → (v : Vec (F.Fin n) n) → (i : F.Fin n) → (evalComb (vtc′ v) (finToVal i)) ≡ (evalVec v i) vecToCombWorks v i = sym (vecRepWorks (magic1 v) i) ------------------------------------------------------------------ -- Goal: lemma1 : {n : ℕ} (v : Vec (F.Fin n) n) → (i : F.Fin n) → (evalVec v i) ≡ (evalComb (vtc′ v) (finToVal i)) lemma1 v i = sym (vecToCombWorks v i) lemma2 : {n : ℕ} (c : (fromℕ n) ⇛ (fromℕ n)) → (i : F.Fin n) → (evalComb c (finToVal i)) ≡ evalVec (combToVec c) i lemma2 c i = combToVecWorks c i ----------------------------------------------------------------
module google using ..ProtoBuf import ..ProtoBuf: meta module protobuf using ..ProtoBuf import ..ProtoBuf: meta include("empty_pb.jl") include("any_pb.jl") include("timestamp_pb.jl") include("duration_pb.jl") include("wrappers_pb.jl") include("source_context_pb.jl") include("type_pb.jl") include("field_mask_pb.jl") include("api_pb.jl") include("struct_pb.jl") end end
{-# LANGUAGE DataKinds #-} {-# LANGUAGE ExplicitForAll #-} {-# LANGUAGE ScopedTypeVariables #-} module Elescore.Integration.DB ( runDBSource ) where import ClassyPrelude hiding (for, forM, head) import Data.DateTime (toSqlString) import Data.Map (elems) import Network.HTTP.Client (Manager) import Pipes import Pipes.Concurrent import qualified Pipes.Prelude as P import Prelude (head) import Database.SimpleEventStore import Elescore.IdTypes import Elescore.Integration.Common.Monitoring import Elescore.Integration.Common.Types import Elescore.Integration.Common.Utils import Elescore.Integration.DB.Client import Elescore.Integration.DB.Mapping import Elescore.Integration.DB.Monitoring import Elescore.Integration.DB.Types import Statistics.IQR runDBSource :: MonadIO m => Store -> ApiKey -> Host -> Manager -> m (Source 'DB) runDBSource store key host mgr = do disP <- disruptions store fP <- facilities store oEvs <- liftIO (readStream store) let oState = replayMkSeed dbObjectMonitor . fmap evPayload $ oEvs oIds = keys oState oP = objects store oEvs (output, input) <- liftIO (spawn unbounded) (out1, in1) <- liftIO (spawn unbounded) (out2, in2) <- liftIO (spawn unbounded) (out3, in3) <- liftIO (spawn unbounded) liftIO $ do void . forkIO . runEffect $ apiP 10 fetchDisruptedFacilities >-> disP >-> toOutput out1 void . forkIO . runEffect $ apiP 3600 (fetchFacilities Nothing) >-> fP >-> toOutput (output <> out2) void . forkIO . runEffect $ fromInput input >-> P.map evPayload >-> stationFilterP oIds >-> fetchStationP 5 >-> oP >-> toOutput out3 return Source { disruptionEvents = in1 , facilityEvents = in2 , objectEvents = in3 } where stationFilterP :: MonadIO m => [ObjectId] -> Pipe (FacilityEvent 'DB) ObjectId m () stationFilterP = go where go s = do ev <- await case ev of FacilityAssignedToObject _ oid -> unless (oid `elem` s) (yield oid >> go (oid : s)) _ -> return () go s fetchStationP :: Int -> Pipe ObjectId Station IO () fetchStationP delay = forever $ do oid <- fromObjectId <$> await a <- liftIO $ runReaderT (fetchStation oid) (key, mgr, host) either print yield a waitSeconds delay apiP :: Int -> API a -> Producer a IO () apiP delay action = forever $ do a <- liftIO $ runReaderT action (key, mgr, host) either print yield a waitSeconds delay disruptions :: MonadIO m => Store -> m (Pipe [Facility] (PersistedEvent (DisruptionEvent 'DB)) IO ()) disruptions store = do disEvs <- liftIO (readStream store) return $ P.map (fmap mkMDisruption) >-> monitorP dbDisruptionMonitor (replayMkSeed dbDisruptionMonitor . fmap evPayload $ disEvs) >-> eventStoreP store >-> eachBefore (chunkBy (toSqlString . evOccurredOn) disEvs) >-> disruptedApiFilter >-> P.concat >-> filterUnknown facilities :: MonadIO m => Store -> m (Pipe [Facility] (PersistedEvent (FacilityEvent 'DB)) IO ()) facilities store = do fEvs <- liftIO (readStream store) return $ P.map (fmap mkMFacility) >-> monitorP dbFacilityMonitor (replayMkSeed dbFacilityMonitor . fmap evPayload $ fEvs) >-> eventStoreP store >-> P.concat >-> eachBefore fEvs objects :: Store -> [PersistedEvent (ObjectEvent 'DB)] -> Pipe Station (PersistedEvent (ObjectEvent 'DB)) IO () objects store oEvs = P.map mkMObject >-> monitorSP dbObjectMonitor (replayMkSeed dbObjectMonitor . fmap evPayload $ oEvs) >-> eventStoreP store >-> P.concat >-> eachBefore oEvs -- | Filters out FaSta API unknown facility states filterUnknown :: Pipe (PersistedEvent (DisruptionEvent a)) (PersistedEvent (DisruptionEvent a)) IO () filterUnknown = for cat $ \ev -> case evPayload ev of FacilityDisrupted _ r -> unless (unknownReason r) (yield ev) DisruptionReasonUpdated _ r -> unless (unknownReason r) (yield ev) _ -> yield ev where unknownReason :: Reason -> Bool unknownReason MonitoringNotAvailable = True unknownReason MonitoringDisrupted = True unknownReason _ = False type Disruptions = MonitorState FacilityId MDisruption disruptedApiFilter :: MonadIO m => Pipe [PersistedEvent (DisruptionEvent 'DB)] [PersistedEvent (DisruptionEvent 'DB)] m () disruptedApiFilter = do firstEvents <- await let initialState = deriveState mempty firstEvents initialSample = singletonSample . fromIntegral . length $ initialState go initialState initialSample Nothing where go :: MonadIO m => Disruptions -> Sample -> Maybe (Disruptions, [PersistedEvent (DisruptionEvent 'DB)]) -> Pipe [PersistedEvent (DisruptionEvent 'DB)] [PersistedEvent (DisruptionEvent 'DB)] m () go previousState sample Nothing = do nextEvents <- await let nextState = deriveState previousState nextEvents numberOfDisruptions = fromIntegral (length nextState) if isResidual numberOfDisruptions sample then do liftIO (putStrLn $ (pack . toSqlString . evOccurredOn $ head nextEvents) <> " Residual detected: " <> tshow (length previousState) <> " -> " <> tshow numberOfDisruptions) go previousState sample (Just (nextState, nextEvents)) else yield nextEvents >> go nextState (addSample numberOfDisruptions sample) Nothing go lastKnownGoodState sample (Just (previousState, accumulatedEvents)) = do nextEvents <- await let nextState = deriveState previousState nextEvents numberOfDisruptions = fromIntegral (length nextState) if isResidual numberOfDisruptions sample then go lastKnownGoodState sample (Just (nextState, accumulatedEvents ++ nextEvents)) else do putStrLn $ (pack . toSqlString . evOccurredOn $ head nextEvents) <> " Back to normal: " <> tshow (length lastKnownGoodState) <> " -> " <> tshow numberOfDisruptions yield (compensateApiDisruption lastKnownGoodState nextState (accumulatedEvents ++ nextEvents)) go nextState (addSample numberOfDisruptions sample) Nothing addSample :: Double -> Sample -> Sample addSample a = restrictSampleSize 1000 . insertSample' a deriveState = foldl' (flip applyEvent) applyEvent :: PersistedEvent (DisruptionEvent 'DB) -> Disruptions -> Disruptions applyEvent = apply dbDisruptionMonitor . evPayload -- | from all happened events, take the latest one that was supposed to be happening compensateApiDisruption :: Disruptions -> Disruptions -> [PersistedEvent (DisruptionEvent 'DB)] -> [PersistedEvent (DisruptionEvent 'DB)] compensateApiDisruption d1 d2 evs = let (_, events) = calculateChanges dbDisruptionMonitor d1 (elems d2) reversedEvents = reverse evs in foldl' (\acc ev -> acc ++ maybe mempty pure (find ((==) ev . evPayload) reversedEvents)) [] events chunkBy :: Eq b => (a -> b) -> [a] -> [[a]] chunkBy _ [] = [] chunkBy f (x:xs) = let (_, as, res) = foldl' doChunk (f x, [x], []) xs in reverse (reverse as : res) where doChunk (b, as, ass) a = if f a == b then (b, a : as, ass) else (f a, [a], reverse as : ass)
A function $f$ is linear if and only if it satisfies the two conditions: $f(x + y) = f(x) + f(y)$ $f(cx) = cf(x)$