Datasets:
AI4M
/

text
stringlengths
0
3.34M
## ensureDir(dest) = mkpath(dirname(dest)) export ensureDir ## pathExtract(path::AbstractString)::RegexMatch = match(r"(.*/)?(([^/]*?)(?:\.([^.]+))?)$", path) export pathExtract fileNameNoExt(path::AbstractString) = pathExtract(path)[3] export fileNameNoExt ##
function glat(hlat) c------convert geographic latitude to geocentric latitude------------- c hlat (input) = geographic latitude in radians (north positive) c glat (output)= geocentric latitude in radians (north positive) c--------------------------------------------------------------------- data halfpi /1.570796/ if(halfpi - abs(hlat).ge.0.05) then glat = atan(0.993277*sin(hlat)/cos(hlat)) else c------special formula near pole glat = hlat/0.993277 - sign(0.010632, hlat) end if return end
function [ t, rank ] = ksubset_colex_successor ( k, n, t, rank ) %*****************************************************************************80 % %% KSUBSET_COLEX_SUCCESSOR computes the K subset colex successor. % % Discussion: % % In the original code, there is a last element with no successor. % % Licensing: % % This code is distributed under the GNU LGPL license. % % Modified: % % 24 January 2011 % % Author: % % John Burkardt % % Reference: % % Donald Kreher, Douglas Simpson, % Combinatorial Algorithms, % CRC Press, 1998, % ISBN: 0-8493-3988-X, % LC: QA164.K73. % % Parameters: % % Input, integer K, the number of elements each K subset must % have. 1 <= K <= N. % % Input, integer N, the number of elements in the master set. % N must be positive. % % Input/output, integer T(K), describes a K subset. T(I) is the % I-th element. The elements must be listed in DESCENDING order. % On input, T describes a K subset. % On output, T describes the next K subset in the ordering. % If the input T was the last in the ordering, then the output T % will be the first. % % Input/output, integer RANK, the rank. % If RANK = -1 on input, then the routine understands that this is % the first call, and that the user wishes the routine to supply % the first element in the ordering, which has RANK = 0. % In general, the input value of RANK is increased by 1 for output, % unless the very last element of the ordering was input, in which % case the output value of RANK is 0. % % % Return the first element. % if ( rank == -1 ) for i = 1 : k t(i) = k + 1 - i; end rank = 0; return end % % Check. % ierror = ksubset_colex_check ( k, n, t ); if ( ierror ~= 0 ) fprintf ( 1, '\n' ); fprintf ( 1, 'KSUBSET_COLEX_SUCCESSOR - Fatal error!\n' ); fprintf ( 1, ' The input array is illegal.\n' ); fprintf ( 1, ' IERROR = %d\n', ierror ); error ( 'KSUBSET_COLEX_SUCCESSOR - Fatal error!' ); end for i = k - 1 : -1 : 1 if ( t(k+1-i) + 1 < t(k-i) ) t(k+1-i) = t(k+1-i) + 1; rank = rank + 1; return end end if ( t(1) < n ) t(1) = t(1) + 1; for i = 1 : k - 1 t(k+1-i) = i; end rank = rank + 1; return end % % The last K subset was input. % Return the first one. % for i = 1 : k t(i) = k + 1 - i; end rank = 0; return end
From RecordUpdate Require Import RecordSet. Import RecordSetNotations. From Perennial.algebra Require Import liftable auth_map. From Perennial.Helpers Require Import Transitions. From Perennial.program_proof Require Import disk_prelude. From Goose.github_com.mit_pdos.go_nfsd Require Import simple. From Perennial.program_proof Require Import obj.obj_proof marshal_proof addr_proof crash_lockmap_proof addr.addr_proof buf.buf_proof. From Perennial.program_proof Require Import jrnl.sep_jrnl_proof. From Perennial.program_proof Require Import disk_prelude. From Perennial.program_proof Require Import disk_lib. From Perennial.Helpers Require Import NamedProps Map List range_set. From Perennial.program_logic Require Import spec_assert. From Perennial.goose_lang.lib Require Import slice.typed_slice into_val. From Perennial.program_proof Require Import simple.spec simple.invariant simple.common simple.iread. Section heap. Context `{!heapGS Σ}. Context `{!simpleG Σ}. Implicit Types (stk:stuckness) (E: coPset). Variable P : SimpleNFS.State -> iProp Σ. Context `{Ptimeless : !forall σ, Timeless (P σ)}. Opaque nfstypes.GETATTR3res. Opaque slice_val. Theorem wp_Inode__MkFattr ip inum len blk : {{{ is_inode_mem ip inum len blk }}} Inode__MkFattr #ip {{{ fattr3, RET fattr3; is_inode_mem ip inum len blk ∗ ⌜ getField_f nfstypes.Fattr3 "Size" fattr3 = #len ⌝ ∗ ⌜ getField_f nfstypes.Fattr3 "Fileid" fattr3 = #inum ⌝ ∗ ⌜ val_ty fattr3 (struct.t nfstypes.Fattr3) ⌝ }}}. Proof. iIntros (Φ) "Hmem HΦ". wp_call. iNamed "Hmem". wp_loadField. wp_loadField. wp_loadField. wp_pures. iApply "HΦ". iModIntro. iSplit. { iFrame. } iPureIntro; simpl. by eauto 50. Qed. Theorem wp_rootFattr : {{{ True }}} rootFattr #() {{{ fattr3, RET fattr3; ⌜ getField_f nfstypes.Fattr3 "Size" fattr3 = #0 ⌝ ∗ ⌜ val_ty fattr3 (struct.t nfstypes.Fattr3) ⌝ }}}. Proof. iIntros (Φ) "_ HΦ". wp_call. iApply "HΦ". eauto 50. Qed. Lemma nfstypes_getattr3res_merge reply s ok : ( reply ↦[nfstypes.GETATTR3res :: "Status"] s ∗ reply ↦[nfstypes.GETATTR3res :: "Resok"] ok ) -∗ reply ↦[struct.t nfstypes.GETATTR3res]{1} (s, (ok, #())). Proof. iIntros "(Status & Resok)". iApply struct_fields_split. iFrame. done. Qed. Theorem wp_NFSPROC3_GETATTR γ (nfs : loc) (fh : u64) (fhslice : Slice.t) (Q : SimpleNFS.res SimpleNFS.fattr -> iProp Σ) dinit : {{{ is_fs P γ nfs dinit ∗ is_fh fhslice fh ∗ ∀ σ σ' r E, ⌜relation.denote (SimpleNFS.full_getattr fh) σ σ' r⌝ -∗ ( P σ ={E}=∗ P σ' ∗ Q r ) }}} Nfs__NFSPROC3_GETATTR #nfs (struct.mk_f nfstypes.GETATTR3args [ "Object" ::= struct.mk_f nfstypes.Nfs_fh3 [ "Data" ::= slice_val fhslice ] ])%V {{{ v, RET v; ( ∃ (sz : u64) resok fattr3, ⌜ getField_f nfstypes.GETATTR3res "Status" v = #(U32 0) ⌝ ∗ ⌜ getField_f nfstypes.GETATTR3res "Resok" v = resok ⌝ ∗ ⌜ getField_f nfstypes.GETATTR3resok "Obj_attributes" resok = fattr3 ⌝ ∗ ⌜ getField_f nfstypes.Fattr3 "Size" fattr3 = #sz ⌝ ∗ Q (SimpleNFS.OK (SimpleNFS.Build_fattr sz)) ) ∨ ( ∃ (stat : Z), ⌜ getField_f nfstypes.GETATTR3res "Status" v = #(U32 stat) ⌝ ∗ ⌜ stat ≠ 0 ⌝ ∗ Q SimpleNFS.Err ) }}}. Proof using Ptimeless. iIntros (Φ) "(Hfs & #Hfh & Hfupd) HΦ". iNamed "Hfs". wp_call. wp_apply wp_ref_of_zero; first by auto. iIntros (reply) "Hreply". wp_apply util_proof.wp_DPrintf. wp_loadField. wp_apply (wp_Op__Begin with "[$Histxn $Htxnsys]"). iIntros (γtxn buftx) "Hjrnl". wp_apply (wp_fh2ino with "Hfh"). wp_pures. wp_if_destruct. { wp_apply (wp_storeField_struct with "Hreply"); first by auto. iIntros "Hreply". (* Simulate to get Q *) iApply fupd_wp. iInv "Hsrc" as ">Hopen" "Hclose". iNamed "Hopen". iDestruct ("Hfupd" with "[] HP") as "Hfupd". { iPureIntro. rewrite /SimpleNFS.full_getattr. case_decide as cond; try congruence. econstructor. { econstructor. eauto. } simpl. monad_simpl. } iMod "Hfupd" as "[HP HQ]". iMod ("Hclose" with "[Hsrcheap HP]"). { iModIntro. iExists _. iFrame "∗%#". } iModIntro. wp_apply wp_rootFattr. iIntros (fattr3) "(%Hlen & %Hfattr3)". iDestruct (struct_fields_split with "Hreply") as "Hreply". iNamed "Hreply". wp_apply (wp_struct_fieldRef_mapsto with "Resok"); first done. iIntros (fl) "[%Hfl Resok]". wp_apply (wp_storeField_struct with "Resok"). { eauto. } iIntros "Resok". rewrite Hfl; clear Hfl fl. wp_apply (wp_LoadAt with "[Status Resok]"). { iModIntro. iApply nfstypes_getattr3res_merge. iFrame. } iIntros "Hreply". iApply "HΦ". iLeft. iExists _, _, _. iSplit; first done. iSplit; first done. iSplit; first done. iSplit; first done. iFrame. } wp_apply (wp_validInum). iIntros (valid) "%Hvalid". wp_if_destruct. { wp_apply (wp_storeField_struct with "Hreply"); first by auto. iIntros "Hreply". (* Simulate to get Q *) iApply fupd_wp. iInv "Hsrc" as ">Hopen" "Hclose". iNamed "Hopen". iDestruct ("Hfupd" with "[] HP") as "Hfupd". { iPureIntro. rewrite /SimpleNFS.full_getattr. case_decide as cond; try congruence. simpl. monad_simpl. simpl. destruct (src !! fh) eqn:He. { exfalso. assert (fh ∈ dom src) as Hin. { apply elem_of_dom. rewrite He. eauto. } rewrite Hdom in Hin. apply Hvalid in Hin. congruence. } rewrite He. econstructor. eauto. } iMod "Hfupd" as "[HP HQ]". iMod ("Hclose" with "[Hsrcheap HP]"). { iModIntro. iExists _. iFrame "∗%#". } iModIntro. wp_load. iApply "HΦ". iRight. iExists _. iFrame "HQ". iPureIntro. Transparent nfstypes.GETATTR3res. simpl. intuition eauto. Opaque nfstypes.GETATTR3res. lia. } wp_loadField. wp_apply (wp_LockMap__Acquire with "[$Hislm]"); first by intuition eauto. iIntros "Hcrashlocked". wp_pures. wp_bind (NFSPROC3_GETATTR_internal _ _ _ _). iApply (wpc_wp _ _ _ _ True). iApply (use_CrashLocked _ with "Hcrashlocked"); first by eauto. iSplit. { done. } iIntros "Hstable". iApply ncfupd_wpc; iSplit. { iMod (is_inode_stable_crash with "Htxncrash Hstable") as "Hcrash". iModIntro. iSplit; try (iIntros "? !>"); done. } iNamed "Hstable". iMod (lift_liftable_into_txn with "Hjrnl Hinode_disk") as "[Hinode_disk Hjrnl]". { solve_ndisj. } { solve_ndisj. } { solve_ndisj. } iNamed "Hinode_disk". iNamed "Hjrnl". iModIntro. iApply wpc_cfupd. iCache with "Hinode_state Hjrnl_durable". { crash_case. iDestruct (is_jrnl_durable_to_old_pred with "Hjrnl_durable") as "[Hold _]". iMod (is_inode_crash_prev with "Htxncrash [$Hinode_state $Hold]") as "H". iModIntro. iSplit; try (iIntros "? !>"); done. } wpc_call. wpc_bind (NFSPROC3_GETATTR_wp _ _ _ _). wpc_frame. wp_call. wp_apply (wp_ReadInode with "[$Hjrnl_mem $Hinode_enc]"); first by intuition eauto. iIntros (ip) "(Hjrnl_mem & Hinode_enc & Hinode_mem)". wp_apply (wp_Inode__MkFattr with "Hinode_mem"). iIntros (fattr3) "(Hinode_mem & % & % & %)". iDestruct (struct_fields_split with "Hreply") as "Hreply". iNamed "Hreply". wp_apply (wp_struct_fieldRef_mapsto with "Resok"); first done. iIntros (fl) "[%Hfl Resok]". wp_apply (wp_storeField_struct with "Resok"). { eauto. } iIntros "Resok". rewrite Hfl; clear Hfl fl. wp_pures. iModIntro. iNamed 1. wpc_pures. iDestruct (is_jrnl_mem_durable with "Hjrnl_mem Hjrnl_durable") as "Hjrnl". wpc_apply (wpc_Op__CommitWait with "[$Hjrnl $Htxncrash Hinode_enc Hinode_data]"). 5: { (* XXX is there a clean version of this? *) generalize (jrnl_maps_to γtxn). intros. iAccu. } all: try solve_ndisj. { typeclasses eauto. } iSplit. { iIntros "[[H _]|[H0 H1]]"; iModIntro; iSplit; try done; iIntros "? !>". { iApply is_inode_crash_next. iFrame. } { iApply is_inode_crash_next. iFrame "Hinode_state". iRight. iFrame. } } iModIntro. iIntros (ok) "Hcommit". destruct ok; subst. - (* Simulate to get Q *) iApply fupd_wpc. iInv "Hsrc" as ">Hopen" "Hclose". iNamed "Hopen". iDestruct (map_valid with "Hsrcheap Hinode_state") as "%Hsrc_fh". iDestruct (big_sepM_lookup with "Hnooverflow") as %Hnooverflow; eauto. iDestruct ("Hfupd" with "[] HP") as "Hfupd". { iPureIntro. rewrite /SimpleNFS.full_getattr. case_decide as cond; try congruence. simpl. monad_simpl. rewrite /= Hsrc_fh /=. eapply relation.bind_runs with (x:=false). { econstructor. auto. } simpl. monad_simpl. } iMod "Hfupd" as "[HP HQ]". iMod ("Hclose" with "[Hsrcheap HP]"). { iModIntro. iExists _. iFrame "∗%#". } iModIntro. wpc_frame "Hinode_state Hcommit". { iMod (is_inode_crash_prev_own with "Htxncrash [$Hinode_state $Hcommit]") as "H". iModIntro. iSplit; try (iIntros "? !>"); done. } wp_storeField. iModIntro. iNamed 1. iSplitR "Hinode_state Hcommit". 2: { iExists _; iFrame. iExists _; iFrame. } iIntros "Hcrashlocked". iSplit. { done. } wp_loadField. wp_apply (wp_LockMap__Release with "Hcrashlocked"). wp_apply (wp_LoadAt with "[Status Resok]"). { iModIntro. iApply nfstypes_getattr3res_merge. iFrame. } iIntros "Hreply". simpl. iApply "HΦ". iLeft. iExists _, _, _. Transparent nfstypes.GETATTR3res. iSplit; first done. iSplit; first done. iSplit; first done. iSplit; first done. iFrame. - (* Simulate to get Q *) iApply fupd_wpc. iInv "Hsrc" as ">Hopen" "Hclose". iNamed "Hopen". iDestruct (map_valid with "Hsrcheap Hinode_state") as "%Hsrc_fh". iDestruct ("Hfupd" with "[] HP") as "Hfupd". { iPureIntro. rewrite /SimpleNFS.full_getattr. case_decide as cond; try congruence. simpl. monad_simpl. simpl. rewrite Hsrc_fh. simpl. eapply relation.bind_runs with (x:=true). { econstructor. auto. } econstructor. auto. } iMod "Hfupd" as "[HP HQ]". iMod ("Hclose" with "[Hsrcheap HP]"). { iModIntro. iExists _. iFrame "∗%#". } iModIntro. iDestruct "Hcommit" as "[Hcommit _]". wpc_frame "Hinode_state Hcommit". { iMod (is_inode_crash_prev_own with "Htxncrash [$Hinode_state $Hcommit]") as "H". iModIntro. iSplit; try (iIntros "? !>"); done. } wp_storeField. iModIntro. iNamed 1. iSplitR "Hinode_state Hcommit". 2: { iExists _; iFrame. } iIntros "Hcrashlocked". iSplit. { done. } wp_loadField. wp_apply (wp_LockMap__Release with "Hcrashlocked"). wp_apply (wp_LoadAt with "[Status Resok]"). { iModIntro. iApply nfstypes_getattr3res_merge. iFrame. } iIntros "Hreply". iApply "HΦ". iRight. iExists _. iFrame "HQ". iPureIntro. simpl. intuition eauto. lia. Unshelve. all: eauto. Qed. End heap.
def one (α : Type u) [OfNat α (nat_lit 1)] : α := 1 abbrev HasOne (α : Type u) := OfNat α (nat_lit 1) def one' (α : Type u) [HasOne α] : α := 1 example : HasOne Nat := inferInstance
lemma fract_poly_eq_0_iff [simp]: "fract_poly p = 0 \<longleftrightarrow> p = 0"
[GOAL] R : Type u_1 inst✝ : CommRing R n : ℕ v0 : R v : Fin n → R ⊢ vandermonde (Fin.cons v0 v) = Fin.cons (fun j => v0 ^ ↑j) fun i => Fin.cons 1 fun j => v i * vandermonde v i j [PROOFSTEP] ext i j [GOAL] case a.h R : Type u_1 inst✝ : CommRing R n : ℕ v0 : R v : Fin n → R i j : Fin (n + 1) ⊢ vandermonde (Fin.cons v0 v) i j = Fin.cons (fun j => v0 ^ ↑j) (fun i => Fin.cons 1 fun j => v i * vandermonde v i j) i j [PROOFSTEP] refine' Fin.cases (by simp) (fun i => _) i [GOAL] R : Type u_1 inst✝ : CommRing R n : ℕ v0 : R v : Fin n → R i j : Fin (n + 1) ⊢ vandermonde (Fin.cons v0 v) 0 j = Fin.cons (fun j => v0 ^ ↑j) (fun i => Fin.cons 1 fun j => v i * vandermonde v i j) 0 j [PROOFSTEP] simp [GOAL] case a.h R : Type u_1 inst✝ : CommRing R n : ℕ v0 : R v : Fin n → R i✝ j : Fin (n + 1) i : Fin n ⊢ vandermonde (Fin.cons v0 v) (Fin.succ i) j = Fin.cons (fun j => v0 ^ ↑j) (fun i => Fin.cons 1 fun j => v i * vandermonde v i j) (Fin.succ i) j [PROOFSTEP] refine' Fin.cases (by simp) (fun j => _) j [GOAL] R : Type u_1 inst✝ : CommRing R n : ℕ v0 : R v : Fin n → R i✝ j : Fin (n + 1) i : Fin n ⊢ vandermonde (Fin.cons v0 v) (Fin.succ i) 0 = Fin.cons (fun j => v0 ^ ↑j) (fun i => Fin.cons 1 fun j => v i * vandermonde v i j) (Fin.succ i) 0 [PROOFSTEP] simp [GOAL] case a.h R : Type u_1 inst✝ : CommRing R n : ℕ v0 : R v : Fin n → R i✝ j✝ : Fin (n + 1) i j : Fin n ⊢ vandermonde (Fin.cons v0 v) (Fin.succ i) (Fin.succ j) = Fin.cons (fun j => v0 ^ ↑j) (fun i => Fin.cons 1 fun j => v i * vandermonde v i j) (Fin.succ i) (Fin.succ j) [PROOFSTEP] simp [pow_succ] [GOAL] R : Type u_1 inst✝ : CommRing R n : ℕ v : Fin (Nat.succ n) → R ⊢ vandermonde v = Fin.cons (fun j => v 0 ^ ↑j) fun i => Fin.cons 1 fun j => v (Fin.succ i) * vandermonde (Fin.tail v) i j [PROOFSTEP] conv_lhs => rw [← Fin.cons_self_tail v, vandermonde_cons] [GOAL] R : Type u_1 inst✝ : CommRing R n : ℕ v : Fin (Nat.succ n) → R | vandermonde v [PROOFSTEP] rw [← Fin.cons_self_tail v, vandermonde_cons] [GOAL] R : Type u_1 inst✝ : CommRing R n : ℕ v : Fin (Nat.succ n) → R | vandermonde v [PROOFSTEP] rw [← Fin.cons_self_tail v, vandermonde_cons] [GOAL] R : Type u_1 inst✝ : CommRing R n : ℕ v : Fin (Nat.succ n) → R | vandermonde v [PROOFSTEP] rw [← Fin.cons_self_tail v, vandermonde_cons] [GOAL] R : Type u_1 inst✝ : CommRing R n : ℕ v w : Fin n → R i j : Fin n ⊢ (vandermonde v * (vandermonde w)ᵀ) i j = ∑ k : Fin n, (v i * w j) ^ ↑k [PROOFSTEP] simp only [vandermonde_apply, Matrix.mul_apply, Matrix.transpose_apply, mul_pow] [GOAL] R : Type u_1 inst✝ : CommRing R n : ℕ v : Fin n → R i j : Fin n ⊢ ((vandermonde v)ᵀ * vandermonde v) i j = ∑ k : Fin n, v k ^ (↑i + ↑j) [PROOFSTEP] simp only [vandermonde_apply, Matrix.mul_apply, Matrix.transpose_apply, pow_add] [GOAL] R : Type u_1 inst✝ : CommRing R n : ℕ v : Fin n → R ⊢ det (vandermonde v) = ∏ i : Fin n, ∏ j in Ioi i, (v j - v i) [PROOFSTEP] unfold vandermonde [GOAL] R : Type u_1 inst✝ : CommRing R n : ℕ v : Fin n → R ⊢ (det fun i j => v i ^ ↑j) = ∏ i : Fin n, ∏ j in Ioi i, (v j - v i) [PROOFSTEP] induction' n with n ih [GOAL] case zero R : Type u_1 inst✝ : CommRing R n : ℕ v✝ : Fin n → R v : Fin Nat.zero → R ⊢ (det fun i j => v i ^ ↑j) = ∏ i : Fin Nat.zero, ∏ j in Ioi i, (v j - v i) [PROOFSTEP] exact det_eq_one_of_card_eq_zero (Fintype.card_fin 0) [GOAL] case succ R : Type u_1 inst✝ : CommRing R n✝ : ℕ v✝ : Fin n✝ → R n : ℕ ih : ∀ (v : Fin n → R), (det fun i j => v i ^ ↑j) = ∏ i : Fin n, ∏ j in Ioi i, (v j - v i) v : Fin (Nat.succ n) → R ⊢ (det fun i j => v i ^ ↑j) = ∏ i : Fin (Nat.succ n), ∏ j in Ioi i, (v j - v i) [PROOFSTEP] calc det (of fun i j : Fin n.succ => v i ^ (j : ℕ)) = det (of fun i j : Fin n.succ => Matrix.vecCons (v 0 ^ (j : ℕ)) (fun i => v (Fin.succ i) ^ (j : ℕ) - v 0 ^ (j : ℕ)) i) := det_eq_of_forall_row_eq_smul_add_const (Matrix.vecCons 0 1) 0 (Fin.cons_zero _ _) ?_ _ = det (of fun i j : Fin n => Matrix.vecCons (v 0 ^ (j.succ : ℕ)) (fun i : Fin n => v (Fin.succ i) ^ (j.succ : ℕ) - v 0 ^ (j.succ : ℕ)) (Fin.succAbove 0 i)) := by simp_rw [det_succ_column_zero, Fin.sum_univ_succ, of_apply, Matrix.cons_val_zero, submatrix, of_apply, Matrix.cons_val_succ, Fin.val_zero, pow_zero, one_mul, sub_self, mul_zero, zero_mul, Finset.sum_const_zero, add_zero] _ = det (of fun i j : Fin n => (v (Fin.succ i) - v 0) * ∑ k in Finset.range (j + 1 : ℕ), v i.succ ^ k * v 0 ^ (j - k : ℕ) : Matrix _ _ R) := by congr ext i j rw [Fin.succAbove_zero, Matrix.cons_val_succ, Fin.val_succ, mul_comm] exact (geom_sum₂_mul (v i.succ) (v 0) (j + 1 : ℕ)).symm _ = (Finset.prod Finset.univ (fun i => v (Fin.succ i) - v 0)) * det fun i j : Fin n => ∑ k in Finset.range (j + 1 : ℕ), v i.succ ^ k * v 0 ^ (j - k : ℕ) := (det_mul_column (fun i => v (Fin.succ i) - v 0) _) _ = (Finset.prod Finset.univ (fun i => v (Fin.succ i) - v 0)) * det fun i j : Fin n => v (Fin.succ i) ^ (j : ℕ) := (congr_arg _ ?_) _ = ∏ i : Fin n.succ, Finset.prod (Ioi i) (fun j => v j - v i) := by simp_rw [Fin.prod_univ_succ, Fin.prod_Ioi_zero, Fin.prod_Ioi_succ] have h := ih (v ∘ Fin.succ) unfold Function.comp at h rw [h] [GOAL] R : Type u_1 inst✝ : CommRing R n✝ : ℕ v✝ : Fin n✝ → R n : ℕ ih : ∀ (v : Fin n → R), (det fun i j => v i ^ ↑j) = ∏ i : Fin n, ∏ j in Ioi i, (v j - v i) v : Fin (Nat.succ n) → R ⊢ det (↑of fun i j => vecCons (v 0 ^ ↑j) (fun i => v (Fin.succ i) ^ ↑j - v 0 ^ ↑j) i) = det (↑of fun i j => vecCons (v 0 ^ ↑(Fin.succ j)) (fun i => v (Fin.succ i) ^ ↑(Fin.succ j) - v 0 ^ ↑(Fin.succ j)) (Fin.succAbove 0 i)) [PROOFSTEP] simp_rw [det_succ_column_zero, Fin.sum_univ_succ, of_apply, Matrix.cons_val_zero, submatrix, of_apply, Matrix.cons_val_succ, Fin.val_zero, pow_zero, one_mul, sub_self, mul_zero, zero_mul, Finset.sum_const_zero, add_zero] [GOAL] R : Type u_1 inst✝ : CommRing R n✝ : ℕ v✝ : Fin n✝ → R n : ℕ ih : ∀ (v : Fin n → R), (det fun i j => v i ^ ↑j) = ∏ i : Fin n, ∏ j in Ioi i, (v j - v i) v : Fin (Nat.succ n) → R ⊢ det (↑of fun i j => vecCons (v 0 ^ ↑(Fin.succ j)) (fun i => v (Fin.succ i) ^ ↑(Fin.succ j) - v 0 ^ ↑(Fin.succ j)) (Fin.succAbove 0 i)) = det (↑of fun i j => (v (Fin.succ i) - v 0) * ∑ k in range (↑j + 1), v (Fin.succ i) ^ k * v 0 ^ (↑j - k)) [PROOFSTEP] congr [GOAL] case e_M.h.e_6.h R : Type u_1 inst✝ : CommRing R n✝ : ℕ v✝ : Fin n✝ → R n : ℕ ih : ∀ (v : Fin n → R), (det fun i j => v i ^ ↑j) = ∏ i : Fin n, ∏ j in Ioi i, (v j - v i) v : Fin (Nat.succ n) → R ⊢ (fun i j => vecCons (v 0 ^ ↑(Fin.succ j)) (fun i => v (Fin.succ i) ^ ↑(Fin.succ j) - v 0 ^ ↑(Fin.succ j)) (Fin.succAbove 0 i)) = fun i j => (v (Fin.succ i) - v 0) * ∑ k in range (↑j + 1), v (Fin.succ i) ^ k * v 0 ^ (↑j - k) [PROOFSTEP] ext i j [GOAL] case e_M.h.e_6.h.h.h R : Type u_1 inst✝ : CommRing R n✝ : ℕ v✝ : Fin n✝ → R n : ℕ ih : ∀ (v : Fin n → R), (det fun i j => v i ^ ↑j) = ∏ i : Fin n, ∏ j in Ioi i, (v j - v i) v : Fin (Nat.succ n) → R i j : Fin n ⊢ vecCons (v 0 ^ ↑(Fin.succ j)) (fun i => v (Fin.succ i) ^ ↑(Fin.succ j) - v 0 ^ ↑(Fin.succ j)) (Fin.succAbove 0 i) = (v (Fin.succ i) - v 0) * ∑ k in range (↑j + 1), v (Fin.succ i) ^ k * v 0 ^ (↑j - k) [PROOFSTEP] rw [Fin.succAbove_zero, Matrix.cons_val_succ, Fin.val_succ, mul_comm] [GOAL] case e_M.h.e_6.h.h.h R : Type u_1 inst✝ : CommRing R n✝ : ℕ v✝ : Fin n✝ → R n : ℕ ih : ∀ (v : Fin n → R), (det fun i j => v i ^ ↑j) = ∏ i : Fin n, ∏ j in Ioi i, (v j - v i) v : Fin (Nat.succ n) → R i j : Fin n ⊢ v (Fin.succ i) ^ (↑j + 1) - v 0 ^ (↑j + 1) = (∑ k in range (↑j + 1), v (Fin.succ i) ^ k * v 0 ^ (↑j - k)) * (v (Fin.succ i) - v 0) [PROOFSTEP] exact (geom_sum₂_mul (v i.succ) (v 0) (j + 1 : ℕ)).symm [GOAL] R : Type u_1 inst✝ : CommRing R n✝ : ℕ v✝ : Fin n✝ → R n : ℕ ih : ∀ (v : Fin n → R), (det fun i j => v i ^ ↑j) = ∏ i : Fin n, ∏ j in Ioi i, (v j - v i) v : Fin (Nat.succ n) → R ⊢ ((∏ i : Fin n, (v (Fin.succ i) - v 0)) * det fun i j => v (Fin.succ i) ^ ↑j) = ∏ i : Fin (Nat.succ n), ∏ j in Ioi i, (v j - v i) [PROOFSTEP] simp_rw [Fin.prod_univ_succ, Fin.prod_Ioi_zero, Fin.prod_Ioi_succ] [GOAL] R : Type u_1 inst✝ : CommRing R n✝ : ℕ v✝ : Fin n✝ → R n : ℕ ih : ∀ (v : Fin n → R), (det fun i j => v i ^ ↑j) = ∏ i : Fin n, ∏ j in Ioi i, (v j - v i) v : Fin (Nat.succ n) → R ⊢ ((∏ i : Fin n, (v (Fin.succ i) - v 0)) * det fun i j => v (Fin.succ i) ^ ↑j) = (∏ j : Fin n, (v (Fin.succ j) - v 0)) * ∏ x : Fin n, ∏ j in Ioi x, (v (Fin.succ j) - v (Fin.succ x)) [PROOFSTEP] have h := ih (v ∘ Fin.succ) [GOAL] R : Type u_1 inst✝ : CommRing R n✝ : ℕ v✝ : Fin n✝ → R n : ℕ ih : ∀ (v : Fin n → R), (det fun i j => v i ^ ↑j) = ∏ i : Fin n, ∏ j in Ioi i, (v j - v i) v : Fin (Nat.succ n) → R h : (det fun i j => (v ∘ Fin.succ) i ^ ↑j) = ∏ i : Fin n, ∏ j in Ioi i, ((v ∘ Fin.succ) j - (v ∘ Fin.succ) i) ⊢ ((∏ i : Fin n, (v (Fin.succ i) - v 0)) * det fun i j => v (Fin.succ i) ^ ↑j) = (∏ j : Fin n, (v (Fin.succ j) - v 0)) * ∏ x : Fin n, ∏ j in Ioi x, (v (Fin.succ j) - v (Fin.succ x)) [PROOFSTEP] unfold Function.comp at h [GOAL] R : Type u_1 inst✝ : CommRing R n✝ : ℕ v✝ : Fin n✝ → R n : ℕ ih : ∀ (v : Fin n → R), (det fun i j => v i ^ ↑j) = ∏ i : Fin n, ∏ j in Ioi i, (v j - v i) v : Fin (Nat.succ n) → R h : (det fun i j => v (Fin.succ i) ^ ↑j) = ∏ i : Fin n, ∏ j in Ioi i, (v (Fin.succ j) - v (Fin.succ i)) ⊢ ((∏ i : Fin n, (v (Fin.succ i) - v 0)) * det fun i j => v (Fin.succ i) ^ ↑j) = (∏ j : Fin n, (v (Fin.succ j) - v 0)) * ∏ x : Fin n, ∏ j in Ioi x, (v (Fin.succ j) - v (Fin.succ x)) [PROOFSTEP] rw [h] [GOAL] case succ.calc_1 R : Type u_1 inst✝ : CommRing R n✝ : ℕ v✝ : Fin n✝ → R n : ℕ ih : ∀ (v : Fin n → R), (det fun i j => v i ^ ↑j) = ∏ i : Fin n, ∏ j in Ioi i, (v j - v i) v : Fin (Nat.succ n) → R ⊢ ∀ (i j : Fin (Nat.succ n)), ↑of (fun i j => v i ^ ↑j) i j = ↑of (fun i j => vecCons (v 0 ^ ↑j) (fun i => v (Fin.succ i) ^ ↑j - v 0 ^ ↑j) i) i j + vecCons 0 1 i * ↑of (fun i j => vecCons (v 0 ^ ↑j) (fun i => v (Fin.succ i) ^ ↑j - v 0 ^ ↑j) i) 0 j [PROOFSTEP] intro i j [GOAL] case succ.calc_1 R : Type u_1 inst✝ : CommRing R n✝ : ℕ v✝ : Fin n✝ → R n : ℕ ih : ∀ (v : Fin n → R), (det fun i j => v i ^ ↑j) = ∏ i : Fin n, ∏ j in Ioi i, (v j - v i) v : Fin (Nat.succ n) → R i j : Fin (Nat.succ n) ⊢ ↑of (fun i j => v i ^ ↑j) i j = ↑of (fun i j => vecCons (v 0 ^ ↑j) (fun i => v (Fin.succ i) ^ ↑j - v 0 ^ ↑j) i) i j + vecCons 0 1 i * ↑of (fun i j => vecCons (v 0 ^ ↑j) (fun i => v (Fin.succ i) ^ ↑j - v 0 ^ ↑j) i) 0 j [PROOFSTEP] simp_rw [of_apply] [GOAL] case succ.calc_1 R : Type u_1 inst✝ : CommRing R n✝ : ℕ v✝ : Fin n✝ → R n : ℕ ih : ∀ (v : Fin n → R), (det fun i j => v i ^ ↑j) = ∏ i : Fin n, ∏ j in Ioi i, (v j - v i) v : Fin (Nat.succ n) → R i j : Fin (Nat.succ n) ⊢ v i ^ ↑j = vecCons (v 0 ^ ↑j) (fun i => v (Fin.succ i) ^ ↑j - v 0 ^ ↑j) i + vecCons 0 1 i * vecCons (v 0 ^ ↑j) (fun i => v (Fin.succ i) ^ ↑j - v 0 ^ ↑j) 0 [PROOFSTEP] rw [Matrix.cons_val_zero] [GOAL] case succ.calc_1 R : Type u_1 inst✝ : CommRing R n✝ : ℕ v✝ : Fin n✝ → R n : ℕ ih : ∀ (v : Fin n → R), (det fun i j => v i ^ ↑j) = ∏ i : Fin n, ∏ j in Ioi i, (v j - v i) v : Fin (Nat.succ n) → R i j : Fin (Nat.succ n) ⊢ v i ^ ↑j = vecCons (v 0 ^ ↑j) (fun i => v (Fin.succ i) ^ ↑j - v 0 ^ ↑j) i + vecCons 0 1 i * v 0 ^ ↑j [PROOFSTEP] refine' Fin.cases _ (fun i => _) i [GOAL] case succ.calc_1.refine'_1 R : Type u_1 inst✝ : CommRing R n✝ : ℕ v✝ : Fin n✝ → R n : ℕ ih : ∀ (v : Fin n → R), (det fun i j => v i ^ ↑j) = ∏ i : Fin n, ∏ j in Ioi i, (v j - v i) v : Fin (Nat.succ n) → R i j : Fin (Nat.succ n) ⊢ v 0 ^ ↑j = vecCons (v 0 ^ ↑j) (fun i => v (Fin.succ i) ^ ↑j - v 0 ^ ↑j) 0 + vecCons 0 1 0 * v 0 ^ ↑j [PROOFSTEP] simp [GOAL] case succ.calc_1.refine'_2 R : Type u_1 inst✝ : CommRing R n✝ : ℕ v✝ : Fin n✝ → R n : ℕ ih : ∀ (v : Fin n → R), (det fun i j => v i ^ ↑j) = ∏ i : Fin n, ∏ j in Ioi i, (v j - v i) v : Fin (Nat.succ n) → R i✝ j : Fin (Nat.succ n) i : Fin n ⊢ v (Fin.succ i) ^ ↑j = vecCons (v 0 ^ ↑j) (fun i => v (Fin.succ i) ^ ↑j - v 0 ^ ↑j) (Fin.succ i) + vecCons 0 1 (Fin.succ i) * v 0 ^ ↑j [PROOFSTEP] rw [Matrix.cons_val_succ, Matrix.cons_val_succ, Pi.one_apply] [GOAL] case succ.calc_1.refine'_2 R : Type u_1 inst✝ : CommRing R n✝ : ℕ v✝ : Fin n✝ → R n : ℕ ih : ∀ (v : Fin n → R), (det fun i j => v i ^ ↑j) = ∏ i : Fin n, ∏ j in Ioi i, (v j - v i) v : Fin (Nat.succ n) → R i✝ j : Fin (Nat.succ n) i : Fin n ⊢ v (Fin.succ i) ^ ↑j = v (Fin.succ i) ^ ↑j - v 0 ^ ↑j + 1 * v 0 ^ ↑j [PROOFSTEP] ring [GOAL] case succ.calc_2 R : Type u_1 inst✝ : CommRing R n✝ : ℕ v✝ : Fin n✝ → R n : ℕ ih : ∀ (v : Fin n → R), (det fun i j => v i ^ ↑j) = ∏ i : Fin n, ∏ j in Ioi i, (v j - v i) v : Fin (Nat.succ n) → R ⊢ (det fun i j => ∑ k in range (↑j + 1), v (Fin.succ i) ^ k * v 0 ^ (↑j - k)) = det fun i j => v (Fin.succ i) ^ ↑j [PROOFSTEP] cases n [GOAL] case succ.calc_2.zero R : Type u_1 inst✝ : CommRing R n : ℕ v✝ : Fin n → R ih : ∀ (v : Fin Nat.zero → R), (det fun i j => v i ^ ↑j) = ∏ i : Fin Nat.zero, ∏ j in Ioi i, (v j - v i) v : Fin (Nat.succ Nat.zero) → R ⊢ (det fun i j => ∑ k in range (↑j + 1), v (Fin.succ i) ^ k * v 0 ^ (↑j - k)) = det fun i j => v (Fin.succ i) ^ ↑j [PROOFSTEP] rw [det_eq_one_of_card_eq_zero (Fintype.card_fin 0), det_eq_one_of_card_eq_zero (Fintype.card_fin 0)] [GOAL] case succ.calc_2.succ R : Type u_1 inst✝ : CommRing R n : ℕ v✝ : Fin n → R n✝ : ℕ ih : ∀ (v : Fin (Nat.succ n✝) → R), (det fun i j => v i ^ ↑j) = ∏ i : Fin (Nat.succ n✝), ∏ j in Ioi i, (v j - v i) v : Fin (Nat.succ (Nat.succ n✝)) → R ⊢ (det fun i j => ∑ k in range (↑j + 1), v (Fin.succ i) ^ k * v 0 ^ (↑j - k)) = det fun i j => v (Fin.succ i) ^ ↑j [PROOFSTEP] apply det_eq_of_forall_col_eq_smul_add_pred fun _ => v 0 [GOAL] case succ.calc_2.succ.A_zero R : Type u_1 inst✝ : CommRing R n : ℕ v✝ : Fin n → R n✝ : ℕ ih : ∀ (v : Fin (Nat.succ n✝) → R), (det fun i j => v i ^ ↑j) = ∏ i : Fin (Nat.succ n✝), ∏ j in Ioi i, (v j - v i) v : Fin (Nat.succ (Nat.succ n✝)) → R ⊢ ∀ (i : Fin (n✝ + 1)), ∑ k in range (↑0 + 1), v (Fin.succ i) ^ k * v 0 ^ (↑0 - k) = v (Fin.succ i) ^ ↑0 [PROOFSTEP] intro j [GOAL] case succ.calc_2.succ.A_zero R : Type u_1 inst✝ : CommRing R n : ℕ v✝ : Fin n → R n✝ : ℕ ih : ∀ (v : Fin (Nat.succ n✝) → R), (det fun i j => v i ^ ↑j) = ∏ i : Fin (Nat.succ n✝), ∏ j in Ioi i, (v j - v i) v : Fin (Nat.succ (Nat.succ n✝)) → R j : Fin (n✝ + 1) ⊢ ∑ k in range (↑0 + 1), v (Fin.succ j) ^ k * v 0 ^ (↑0 - k) = v (Fin.succ j) ^ ↑0 [PROOFSTEP] simp [GOAL] case succ.calc_2.succ.A_succ R : Type u_1 inst✝ : CommRing R n : ℕ v✝ : Fin n → R n✝ : ℕ ih : ∀ (v : Fin (Nat.succ n✝) → R), (det fun i j => v i ^ ↑j) = ∏ i : Fin (Nat.succ n✝), ∏ j in Ioi i, (v j - v i) v : Fin (Nat.succ (Nat.succ n✝)) → R ⊢ ∀ (i : Fin (n✝ + 1)) (j : Fin n✝), ∑ k in range (↑(Fin.succ j) + 1), v (Fin.succ i) ^ k * v 0 ^ (↑(Fin.succ j) - k) = v (Fin.succ i) ^ ↑(Fin.succ j) + v 0 * ∑ k in range (↑(Fin.castSucc j) + 1), v (Fin.succ i) ^ k * v 0 ^ (↑(Fin.castSucc j) - k) [PROOFSTEP] intro i j [GOAL] case succ.calc_2.succ.A_succ R : Type u_1 inst✝ : CommRing R n : ℕ v✝ : Fin n → R n✝ : ℕ ih : ∀ (v : Fin (Nat.succ n✝) → R), (det fun i j => v i ^ ↑j) = ∏ i : Fin (Nat.succ n✝), ∏ j in Ioi i, (v j - v i) v : Fin (Nat.succ (Nat.succ n✝)) → R i : Fin (n✝ + 1) j : Fin n✝ ⊢ ∑ k in range (↑(Fin.succ j) + 1), v (Fin.succ i) ^ k * v 0 ^ (↑(Fin.succ j) - k) = v (Fin.succ i) ^ ↑(Fin.succ j) + v 0 * ∑ k in range (↑(Fin.castSucc j) + 1), v (Fin.succ i) ^ k * v 0 ^ (↑(Fin.castSucc j) - k) [PROOFSTEP] simp only [smul_eq_mul, Pi.add_apply, Fin.val_succ, Fin.coe_castSucc, Pi.smul_apply] [GOAL] case succ.calc_2.succ.A_succ R : Type u_1 inst✝ : CommRing R n : ℕ v✝ : Fin n → R n✝ : ℕ ih : ∀ (v : Fin (Nat.succ n✝) → R), (det fun i j => v i ^ ↑j) = ∏ i : Fin (Nat.succ n✝), ∏ j in Ioi i, (v j - v i) v : Fin (Nat.succ (Nat.succ n✝)) → R i : Fin (n✝ + 1) j : Fin n✝ ⊢ ∑ x in range (↑j + 1 + 1), v (Fin.succ i) ^ x * v 0 ^ (↑j + 1 - x) = v (Fin.succ i) ^ (↑j + 1) + v 0 * ∑ x in range (↑j + 1), v (Fin.succ i) ^ x * v 0 ^ (↑j - x) [PROOFSTEP] rw [Finset.sum_range_succ, add_comm, tsub_self, pow_zero, mul_one, Finset.mul_sum] [GOAL] case succ.calc_2.succ.A_succ R : Type u_1 inst✝ : CommRing R n : ℕ v✝ : Fin n → R n✝ : ℕ ih : ∀ (v : Fin (Nat.succ n✝) → R), (det fun i j => v i ^ ↑j) = ∏ i : Fin (Nat.succ n✝), ∏ j in Ioi i, (v j - v i) v : Fin (Nat.succ (Nat.succ n✝)) → R i : Fin (n✝ + 1) j : Fin n✝ ⊢ v (Fin.succ i) ^ (↑j + 1) + ∑ x in range (↑j + 1), v (Fin.succ i) ^ x * v 0 ^ (↑j + 1 - x) = v (Fin.succ i) ^ (↑j + 1) + ∑ x in range (↑j + 1), v 0 * (v (Fin.succ i) ^ x * v 0 ^ (↑j - x)) [PROOFSTEP] congr 1 [GOAL] case succ.calc_2.succ.A_succ.e_a R : Type u_1 inst✝ : CommRing R n : ℕ v✝ : Fin n → R n✝ : ℕ ih : ∀ (v : Fin (Nat.succ n✝) → R), (det fun i j => v i ^ ↑j) = ∏ i : Fin (Nat.succ n✝), ∏ j in Ioi i, (v j - v i) v : Fin (Nat.succ (Nat.succ n✝)) → R i : Fin (n✝ + 1) j : Fin n✝ ⊢ ∑ x in range (↑j + 1), v (Fin.succ i) ^ x * v 0 ^ (↑j + 1 - x) = ∑ x in range (↑j + 1), v 0 * (v (Fin.succ i) ^ x * v 0 ^ (↑j - x)) [PROOFSTEP] refine' Finset.sum_congr rfl fun i' hi' => _ [GOAL] case succ.calc_2.succ.A_succ.e_a R : Type u_1 inst✝ : CommRing R n : ℕ v✝ : Fin n → R n✝ : ℕ ih : ∀ (v : Fin (Nat.succ n✝) → R), (det fun i j => v i ^ ↑j) = ∏ i : Fin (Nat.succ n✝), ∏ j in Ioi i, (v j - v i) v : Fin (Nat.succ (Nat.succ n✝)) → R i : Fin (n✝ + 1) j : Fin n✝ i' : ℕ hi' : i' ∈ range (↑j + 1) ⊢ v (Fin.succ i) ^ i' * v 0 ^ (↑j + 1 - i') = v 0 * (v (Fin.succ i) ^ i' * v 0 ^ (↑j - i')) [PROOFSTEP] rw [mul_left_comm (v 0), Nat.succ_sub, pow_succ] [GOAL] case succ.calc_2.succ.A_succ.e_a R : Type u_1 inst✝ : CommRing R n : ℕ v✝ : Fin n → R n✝ : ℕ ih : ∀ (v : Fin (Nat.succ n✝) → R), (det fun i j => v i ^ ↑j) = ∏ i : Fin (Nat.succ n✝), ∏ j in Ioi i, (v j - v i) v : Fin (Nat.succ (Nat.succ n✝)) → R i : Fin (n✝ + 1) j : Fin n✝ i' : ℕ hi' : i' ∈ range (↑j + 1) ⊢ i' ≤ ↑j [PROOFSTEP] exact Nat.lt_succ_iff.mp (Finset.mem_range.mp hi') [GOAL] R : Type u_1 inst✝¹ : CommRing R inst✝ : IsDomain R n : ℕ v : Fin n → R ⊢ det (vandermonde v) = 0 ↔ ∃ i j, v i = v j ∧ i ≠ j [PROOFSTEP] constructor [GOAL] case mp R : Type u_1 inst✝¹ : CommRing R inst✝ : IsDomain R n : ℕ v : Fin n → R ⊢ det (vandermonde v) = 0 → ∃ i j, v i = v j ∧ i ≠ j [PROOFSTEP] simp only [det_vandermonde v, Finset.prod_eq_zero_iff, sub_eq_zero, forall_exists_index] [GOAL] case mp R : Type u_1 inst✝¹ : CommRing R inst✝ : IsDomain R n : ℕ v : Fin n → R ⊢ ∀ (x : Fin n), (x ∈ univ ∧ ∃ a, a ∈ Ioi x ∧ v a = v x) → ∃ i j, v i = v j ∧ i ≠ j [PROOFSTEP] rintro i ⟨_, j, h₁, h₂⟩ [GOAL] case mp.intro.intro.intro R : Type u_1 inst✝¹ : CommRing R inst✝ : IsDomain R n : ℕ v : Fin n → R i : Fin n left✝ : i ∈ univ j : Fin n h₁ : j ∈ Ioi i h₂ : v j = v i ⊢ ∃ i j, v i = v j ∧ i ≠ j [PROOFSTEP] exact ⟨j, i, h₂, (mem_Ioi.mp h₁).ne'⟩ [GOAL] case mpr R : Type u_1 inst✝¹ : CommRing R inst✝ : IsDomain R n : ℕ v : Fin n → R ⊢ (∃ i j, v i = v j ∧ i ≠ j) → det (vandermonde v) = 0 [PROOFSTEP] simp only [Ne.def, forall_exists_index, and_imp] [GOAL] case mpr R : Type u_1 inst✝¹ : CommRing R inst✝ : IsDomain R n : ℕ v : Fin n → R ⊢ ∀ (x x_1 : Fin n), v x = v x_1 → ¬x = x_1 → det (vandermonde v) = 0 [PROOFSTEP] refine' fun i j h₁ h₂ => Matrix.det_zero_of_row_eq h₂ (funext fun k => _) [GOAL] case mpr R : Type u_1 inst✝¹ : CommRing R inst✝ : IsDomain R n : ℕ v : Fin n → R i j : Fin n h₁ : v i = v j h₂ : ¬i = j k : Fin n ⊢ vandermonde v i k = vandermonde v j k [PROOFSTEP] rw [vandermonde_apply, vandermonde_apply, h₁] [GOAL] R : Type u_1 inst✝¹ : CommRing R inst✝ : IsDomain R n : ℕ v : Fin n → R ⊢ det (vandermonde v) ≠ 0 ↔ Function.Injective v [PROOFSTEP] unfold Function.Injective [GOAL] R : Type u_1 inst✝¹ : CommRing R inst✝ : IsDomain R n : ℕ v : Fin n → R ⊢ det (vandermonde v) ≠ 0 ↔ ∀ ⦃a₁ a₂ : Fin n⦄, v a₁ = v a₂ → a₁ = a₂ [PROOFSTEP] simp only [det_vandermonde_eq_zero_iff, Ne.def, not_exists, not_and, Classical.not_not] [GOAL] R✝ : Type u_1 inst✝² : CommRing R✝ R : Type u_2 inst✝¹ : CommRing R inst✝ : IsDomain R n : ℕ f v : Fin n → R hf : Function.Injective f hfv : ∀ (j : Fin n), ∑ i : Fin n, v i * f j ^ ↑i = 0 ⊢ v = 0 [PROOFSTEP] apply eq_zero_of_forall_index_sum_pow_mul_eq_zero hf [GOAL] R✝ : Type u_1 inst✝² : CommRing R✝ R : Type u_2 inst✝¹ : CommRing R inst✝ : IsDomain R n : ℕ f v : Fin n → R hf : Function.Injective f hfv : ∀ (j : Fin n), ∑ i : Fin n, v i * f j ^ ↑i = 0 ⊢ ∀ (j : Fin n), ∑ i : Fin n, f j ^ ↑i * v i = 0 [PROOFSTEP] simp_rw [mul_comm] [GOAL] R✝ : Type u_1 inst✝² : CommRing R✝ R : Type u_2 inst✝¹ : CommRing R inst✝ : IsDomain R n : ℕ f v : Fin n → R hf : Function.Injective f hfv : ∀ (j : Fin n), ∑ i : Fin n, v i * f j ^ ↑i = 0 ⊢ ∀ (j : Fin n), ∑ x : Fin n, v x * f j ^ ↑x = 0 [PROOFSTEP] exact hfv
library(ggplot2) visualize_as_histogram <- function(corpus) { melted <- melt_and_group_columns(corpus) manifest <- corpus$manifest min <- get_property_value(manifest, "min") max <- get_property_value(manifest, "max") bin_size <- get_property_value(manifest, "bin-size") plot <- ggplot(melted, aes(x = value, col = variable, fill = variable)) + ( if(!is.null(min) && !is.null(max) && !is.null(bin_size)) geom_histogram(aes(y = stat(count / sum(count))), breaks = seq(min, max, by = bin_size), position="dodge", show.legend=!manifest['disable-legend'][[1]]) else if(!is.null(bin_size)) geom_histogram(binwidth = bin_size, position="dodge", show.legend=!manifest['disable-legend'][[1]]) else geom_histogram(position="dodge", show.legend=!manifest['disable-legend'][[1]]) ) + # geom_density(alpha=.7, show.legend=FALSE) + xlab(manifest['labels'][[1]]['x-axis']) + ylab(manifest['labels'][[1]]['y-axis']) + ggtitle( # eval(parse(text="expression(atop(bold('ok'),atop('ok')))")) eval(parse(text=paste('expression( atop( bold( ', manifest['labels'][[1]]['title'], ' ), atop( ', manifest['labels'][[1]]['subtitle'], ' ) ) )', sep=''))) ) + theme( # axis.text.x = element_text(angle=-45, hjust=0, vjust=1), plot.title = element_text(size = 14, colour = "black", vjust = -1, hjust=0.5) ) # scale_colour_discrete("Continents") # + # guides( # color = guide_legend( # override.aes = list(fill = NA) # ), # linetype = guide_legend( # override.aes = list(fill = NA) # ) # ) + # theme( # legend.key = element_rect(fill = "white") # ) + # guides(fill="none") + # delete entries from legend which correspond to the bars fill color # scale_fill_discrete(name="Experimental\nCondition") custom_legend_properties = get_property_value(manifest, 'legend') if (!is.null(custom_legend_properties)) { # plot + scale_fill_discrete(name = "New Legend Title", fill = FALSE) custom_legend_title = get_property_value(custom_legend_properties, 'title') if (!is.null(custom_legend_title)) { plot + guides(fill = guide_legend(title=custom_legend_title)) + guides(col = "none") } } return(plot) }
### A Pluto.jl notebook ### # v0.12.18 using Markdown using InteractiveUtils # ╔═╡ ad4957b2-5292-11eb-1f64-c96793eb50a3 using DrWatson # ╔═╡ b993ce0a-52a4-11eb-325d-9762114e31e8 using BenchmarkTools, DynamicalSystems, Neighborhood, Entropies, DataFrames, CSV # ╔═╡ bbc53e10-53f9-11eb-1166-17295832370f using Plots # ╔═╡ 3660b24a-52a5-11eb-06a7-5b4bf9b5f359 md"# Setup" # ╔═╡ 02804130-5295-11eb-2076-9dd3d942b26c @quickactivate "FractalDimension" # ╔═╡ f08543ee-52a4-11eb-1928-89a52d10ffdf md"Import all needed functions for benchmarks from packages and by direct definition." # ╔═╡ 00c03bce-52a5-11eb-1fa0-19ffb17b23dd function _correlationsum_new(tree, X, ε, w, qf) theiler = Neighborhood.Theiler(w) searchtype = Neighborhood.WithinRange(maximum(ε)) N = length(X) Cq = similar(ε, Float64) @inbounds for i in 1:N idxs = Neighborhood.isearch(tree, X[i], searchtype, theiler(i)) isempty(idxs) && continue dist = [Neighborhood.evaluate(tree.metric, X[i], X[j]) for j in idxs] sort!(dist) for k in 1:length(ε)-1 j = searchsortedfirst(dist, ε[k]) Cq[k] += qf(j-1) end Cq[end] += qf(length(dist)) end return Cq ./ (N*qf(N-w-1)) end # ╔═╡ fa4e2bfc-52a4-11eb-088f-9bd8377cc691 function correlationsum_new(X, ε; q = 2, metric = Euclidean(), w = 0) ntype = WithinRange(maximum(ε)) tree = KDTree(X) qf = q == 2 ? identity : x -> float(x)^(q-1) _correlationsum_new(tree, X, ε, w, qf) end # ╔═╡ 07c6fc50-52a5-11eb-37d6-e546a66a5c28 # Define a function to access data sets. """ sample_data(data, N_sample) Sample `N_sample` unique random points out of `data`. """ function sample_data(data, N_sample) N_data = length(data) possible_indices = 1:N_data indices = unique(rand(possible_indices, 2N_sample))[1:N_sample] data[indices] |> Dataset end # ╔═╡ 3f6eb602-52a5-11eb-1735-f9d1f28fbcd8 md"# Single Benchmark Functions ## Classic Correlation" # ╔═╡ 11e7cb6a-52a5-11eb-16de-cd668a8473ff function benchmark_correlation(data) bm = @benchmark begin ε0 = min_pairwise_distance($data)[2] ε1 = minimum(maxima($data) - minima($data)) εs = 10 .^ range(log10(ε0), log10(ε1), length = 12) [correlationsum($data, ε) for ε in εs] end minimum(bm.times) end # ╔═╡ 5a1a167a-52a5-11eb-11a9-958f6cefa7b3 md"## New Correlation" # ╔═╡ 162b224e-52a5-11eb-0351-955a17fd1524 function benchmark_new_correlation(data) bm = @benchmark begin ε0 = min_pairwise_distance($data)[2] ε1 = minimum(maxima($data) - minima($data)) εs = 10 .^ range(log10(ε0), log10(ε1), length = 12) correlationsum_new($data, εs) end minimum(bm.times) end # ╔═╡ 68a515f2-52a5-11eb-29ec-310b27c74895 md"## Boxed Correlation" # ╔═╡ 1a849636-52a5-11eb-11fe-61afc4a4b453 function benchmark_boxed_correlation(data::Dataset{D,T}, prismdim = D) where {D,T} bm = @benchmark begin ε0 = min_pairwise_distance($data)[2] ε1 = estimate_r0_buenoorovio($data, $prismdim) εs = 10 .^ range(log10(ε0), log10(ε1), length = 12) boxed_correlationsum($data, εs, ε1, M = $prismdim) end minimum(bm.times) end # ╔═╡ 7da26766-52a5-11eb-2318-593d397abb4c md"## Moltenos Generalized Entropy" # ╔═╡ 1f5dbdb8-52a5-11eb-3814-33ca2ad86123 function benchmark_molteno(data) bm = @benchmark molteno_boxing($data) minimum(bm.times) end # ╔═╡ 8a690dba-52a5-11eb-0703-932f4a1ab648 md"## Standard Generalized Entropy" # ╔═╡ 2384e768-52a5-11eb-38cb-15b49cb5fdcb function benchmark_genentropy(data) bm = @benchmark begin ε0 = min_pairwise_distance($data)[2] ε1 = minimum(maxima($data) - minima($data)) εs = 10 .^ range(log10(ε0), log10(ε1), length = 12) [Entropies.genentropy($data, ε) for ε in εs] end minimum(bm.times) end # ╔═╡ 9663d82a-52a5-11eb-3fe8-3f753118ab60 md"# Actual Experiments ## Benchmark of Size The values are spread logarithmically" # ╔═╡ 289e88c6-52a5-11eb-113a-b78dd25b0154 """ benchmark_N( lower_number, upper_number, number_of_numbers; base = 10, feedback = false ) Benchmarks `number_of_numbers` values in the interval `base^lower_number`, `base^higher_number`. These values are distributed logarithmically. If `feedback` is `true` there is a text feedback. """ function benchmark_N( lower_number, upper_number, number_of_numbers; base = 10, feedback = false ) result = DataFrame(N = Int[], Model = [], Method = [], Time = []) numbers = floor.(Int, base .^ range(lower_number, upper_number, length = number_of_numbers)) # Define Systems. henon_sys = Systems.henon(rand(2)) lorenz_sys = Systems.lorenz(randn(3)) N_traj = 5 * floor(base ^ upper_number) # Integrate trajectories. henon = trajectory(henon_sys, N_traj, Ttr = 100) lorenz = trajectory(lorenz_sys, N_traj * 0.1, dt = 0.1, Ttr = 10) trajectories = [(:henon, henon), (:lorenz, lorenz)] for (name, traj) in trajectories feedback && println("Now using the $name system.") for N in numbers feedback && println("Currently calculating with $N random data points.") data = sample_data(traj, N) feedback && println("Benchmarking the classic correlation…") push!( result, (N, name, "Correlation",benchmark_correlation(data)) ) feedback && println("Benchmarking the new correlation…") push!( result, (N, name, "New Correlation", benchmark_new_correlation(data)) ) feedback && println("Benchmarking the boxed correlation…") push!( result, (N, name, "Boxed Correlation", benchmark_boxed_correlation(data)) ) feedback && println("Benchmarking the generalized entropy with factor 2 boxing…") push!( result, (N, name, "Molteno", benchmark_molteno(data)) ) feedback && println("Benchmarking the generalized entropy with standard boxing…") push!( result, (N, name, "Generalized Dimension", benchmark_genentropy(data)) ) end end wsave( datadir( "benchmark", savename( "benchmark_number", Dict( :lowerN => lower_number, :upperN => upper_number, :NofN => number_of_numbers, :base => base, ), "csv", ), ), result, ) result end # ╔═╡ 0ab12ebc-52a6-11eb-300d-1f864d2fcdf3 md"## Benchmark of dimension" # ╔═╡ 2f2d2cec-52a5-11eb-0748-0dc568cf81aa """ benchmark_dimension( lower_dimension::Int = 4, upper_dimension::Int = 16, distance_dimension::Int = 1; N_sample = 10000, feedback = false, ) Benchmarks different correlation algorithms for dimensions with distance `distance_dimension` between `lower_dimension` and `upper_dimension`. These algorithms are compared for different distance_dimensions. If `feedback` is `true` a status is printed after each benchmark step. """ function benchmark_dimension( lower_dimension::Int = 4, upper_dimension::Int = 16, distance_dimension::Int = 1; N_sample = 10000, feedback = false, ) result = DataFrame(Dimension = Int[], Method = [], Time = []) dimensions = lower_dimension:distance_dimension:upper_dimension for dimension in dimensions feedback && println("The current dimension is $dimension.") # The current trajectroy is longer than the data sample taken from the trajectory. traj = trajectory( Systems.lorenz96(dimension, rand(dimension), F = 8.0), N_sample, Ttr = 100, dt = 0.1, ) # Only 10000 unique data points are sampled from the 100000 trajectory points data = sample_data(traj, N_sample) # Benchmark the classic correlation. feedback && println("Now benchmarking the classic correlation…") push!( result, (dimension, "Classic Correlation", benchmark_correlation(data)), ) # Benchmark the new correlation that uses KDTrees. feedback && println("Now benchmarking the new correlation…") push!( result, (dimension, "New Correlation", benchmark_new_correlation(data)), ) # Benchmark the Boxed Correlation without accessing the prism property. feedback && println("Now benchmarking the boxed correlation…") push!( result, (dimension, "Boxed Correlation", benchmark_boxed_correlation(data)), ) feedback && println("Now benchmarking the prism correlation…") # Benchmark the Prism Correlation with Prism Dimension by Theiler. embedding_dim = 0.75log2(N_sample) < dimension ? (0.5log2(N_sample) |> ceil |> Int) : dimension push!( result, (dimension, "Prism Correlation", benchmark_boxed_correlation(data, embedding_dim)), ) feedback && println("Now benchmarking the generalized entropy by Molteno…") # Benchmark the generalized entropy method by Molteno. push!( result, (dimension, "Molteno", benchmark_molteno(data)) ) feedback && println("Now benchmarking the classic generalized entropy…") # Benchmark the classic generalized entropy. push!( result, (dimension, "Generalized Entropy", benchmark_genentropy(data)) ) end wsave( datadir( "benchmark", savename( "benchmark_dim", Dict( :N => N_sample, :lowerdim => lower_dimension, :upperdim => upper_dimension, :ddim => distance_dimension, ), "csv", ), ), result, ) result end # ╔═╡ fa38cdc0-52c0-11eb-08ba-e3b2e399dc2f data = trajectory(Systems.henon(0.1rand(2)), 1000000, Ttr = 10) # ╔═╡ fa33702a-52c0-11eb-250b-9d7a7a7506ad benchmark_correlation(sample_data(data, 1000)) # ╔═╡ 2a048274-52c1-11eb-339c-6b10fb972d11 benchmark_new_correlation(sample_data(data, 1000)) # ╔═╡ 33866012-52c1-11eb-329c-eff5928eb12e benchmark_boxed_correlation(sample_data(data, 1000)) # ╔═╡ 40b6a85a-52c1-11eb-080a-272e1642425d benchmark_molteno(sample_data(data, 1000)) # ╔═╡ 4c2583a0-52c1-11eb-35ec-49b3c59c471f benchmark_genentropy(sample_data(data, 1000)) # ╔═╡ 5c2b6d64-52c1-11eb-14e5-bd81d666bb81 benchmark_boxed_correlation(sample_data(data, 1000), 1) # ╔═╡ 0124b0f2-53f9-11eb-3ebb-f182fd11a129 md"# Tests" # ╔═╡ 64d806be-53f9-11eb-2ca9-1d2ece3404bd sdata = sample_data(data, 10000) # ╔═╡ e7bf3d5c-5414-11eb-0556-452471c2b65b q = 1.99 # ╔═╡ bd059f48-5414-11eb-08c2-794f627f15ee # ╔═╡ bba5b5d8-5415-11eb-35b1-c3e070d1e09d md"# Results ## `boxed_correlationsum` vs `correlationsum` It seems like they behave the same for a given ε. Say `henon` is a dataset with a trajectory of the henon map." # ╔═╡ c6d939e8-5415-11eb-0c37-c73be604f29c henon = trajectory(Systems.henon(0.1rand(2)), 10000, Ttr = 22) # ╔═╡ 0d016116-5416-11eb-3ab5-a534b0d1453a md"Then we can choose the εs by selecting the upper border `r0` using `estimate_r0_buenoorovio` and the lower border `ε_min` via `min_pairwise_distance` and spread them logarithmically on that interval." # ╔═╡ 6f5e0968-5416-11eb-0fcb-572aaa902574 r0 = estimate_r0_buenoorovio(henon) # ╔═╡ a0f41bf2-5416-11eb-2da6-cb4b485084c5 ε_min = min_pairwise_distance(henon)[2] # ╔═╡ a2ca2444-5416-11eb-0a40-1f65148b816e εs = 10 .^ range(log10(ε_min), log10(r0), length = 15) # ╔═╡ 0798e090-53f9-11eb-377a-fdf6c2ade4d1 bcs = boxed_correlationsum(sdata, εs, q = q) # ╔═╡ 88515afc-5415-11eb-273c-83e703c7392d cs = correlationsum(sdata, εs, q = q) # ╔═╡ 9fc5c036-5415-11eb-1d0e-5377b9d92943 bcs ≈ cs # ╔═╡ be07006c-53f9-11eb-0141-4f9afae62d4b plot(εs .|> log10, bcs .|> log10) # ╔═╡ e89063f6-53fa-11eb-2671-5bacb746b401 linear_region(εs .|> log10, bcs .|> log10)[2]*1/(q-1) # ╔═╡ efe5247c-5416-11eb-235e-6d7ce045b31e md"Now the two correlation sums can be calculated." # ╔═╡ fc2bd50a-5416-11eb-38f5-97335565a8eb correlation_2 = correlationsum(henon, εs) # ╔═╡ 067a4be0-5417-11eb-2774-915824fb7987 boxed_correlation_2 = boxed_correlationsum(henon, εs) # ╔═╡ cbcac542-5416-11eb-3b99-791d68ce0745 md"Comparing these two directly works." # ╔═╡ 1b3d11c0-5417-11eb-0856-b5aa0be46b0b correlation_2 == boxed_correlation_2 # ╔═╡ 3842c2ec-5417-11eb-0030-83c97d87e157 md"The algorithm differs for `q≠2` so we need to compare this case as well." # ╔═╡ 4d1e7eea-5417-11eb-1021-d50ee8615148 correlation_q = correlationsum(henon, εs, q = 3.3) # ╔═╡ 61abb6b6-5417-11eb-32a7-f74a2549ef42 boxed_correlation_q = boxed_correlationsum(henon, εs, q = 3.3) # ╔═╡ 70a0118a-5417-11eb-12cf-016cdbccb50d correlation_q == boxed_correlation_q # ╔═╡ 81510afc-5417-11eb-3111-6dfc809e8f6b md"This does not come unexpected. The sums are only expected to be approximately equal, since the precision of the types plays a role." # ╔═╡ c8c092ea-5417-11eb-2175-b3a1c62f1454 correlation_q ≈ boxed_correlation_q # ╔═╡ 8f48f42e-5419-11eb-1865-c19b60d19b02 begin import ChaosTools: boxed_correlationdim function boxed_correlationdim(data, εs, r0 = maximum(εs); q = 2, M = size(data, 2)) @assert M ≤ size(data,2) "Prism dimension has to be lower or equal than " * "data dimension." if isinf(q) dd = boxed_correlationsum(data, εs, r0; q = 3, M = M) return 1 / (3 - 1) * linear_region(log.(εs), log.(maximum.(dd)), tol = 0.1)[2] else dd = boxed_correlationsum(data, εs, r0; q = q, M = M) return 1 / (q - 1) * linear_region(log.(εs), log.(dd), tol = 0.1)[2] end end end # ╔═╡ 420e26b2-5418-11eb-0477-5fd4284ff1d0 boxed_correlationdim(henon, q = 3) # ╔═╡ e3627ac8-5417-11eb-1cf7-e13f24c1b62f md"## q-order correlation literature I was not able to find any paper using the explicit q-order correlationsum, yet its definition seems sensible and the plots I retrieve show linear scaling regions for different `q`." # ╔═╡ d0e25b7c-5424-11eb-04dd-396f8e034b86 begin ϵ_min = min_pairwise_distance(henon)[2] ϵ_max = maximum(maxima(henon)-minima(henon)) ϵs = 10 .^ range(log10(ϵ_min), log10(ϵ_max), length = 20) plot() for q in 1.5:0.5:6 corsum = correlationsum(henon, ϵs, q = q) (p1, p2), dim = linear_region(log10.(ϵs), log10.(corsum)) dim = 1/(q-1)*dim plot!( log10.(ϵs), log10.(corsum), label = "q = $q, Δ = $(round(dim, digits = 3))", ) end plot!( legend = :bottomright, xlims = log10.((ϵs[1], ϵs[20])), xguide = "\$ \\log(\\epsilon) \$", yguide = "\$ C_q \$", ) end # ╔═╡ Cell order: # ╟─3660b24a-52a5-11eb-06a7-5b4bf9b5f359 # ╠═ad4957b2-5292-11eb-1f64-c96793eb50a3 # ╠═02804130-5295-11eb-2076-9dd3d942b26c # ╟─f08543ee-52a4-11eb-1928-89a52d10ffdf # ╠═b993ce0a-52a4-11eb-325d-9762114e31e8 # ╠═fa4e2bfc-52a4-11eb-088f-9bd8377cc691 # ╠═00c03bce-52a5-11eb-1fa0-19ffb17b23dd # ╠═07c6fc50-52a5-11eb-37d6-e546a66a5c28 # ╟─3f6eb602-52a5-11eb-1735-f9d1f28fbcd8 # ╠═11e7cb6a-52a5-11eb-16de-cd668a8473ff # ╟─5a1a167a-52a5-11eb-11a9-958f6cefa7b3 # ╠═162b224e-52a5-11eb-0351-955a17fd1524 # ╟─68a515f2-52a5-11eb-29ec-310b27c74895 # ╠═1a849636-52a5-11eb-11fe-61afc4a4b453 # ╟─7da26766-52a5-11eb-2318-593d397abb4c # ╠═1f5dbdb8-52a5-11eb-3814-33ca2ad86123 # ╟─8a690dba-52a5-11eb-0703-932f4a1ab648 # ╠═2384e768-52a5-11eb-38cb-15b49cb5fdcb # ╟─9663d82a-52a5-11eb-3fe8-3f753118ab60 # ╠═289e88c6-52a5-11eb-113a-b78dd25b0154 # ╟─0ab12ebc-52a6-11eb-300d-1f864d2fcdf3 # ╠═2f2d2cec-52a5-11eb-0748-0dc568cf81aa # ╠═fa38cdc0-52c0-11eb-08ba-e3b2e399dc2f # ╠═fa33702a-52c0-11eb-250b-9d7a7a7506ad # ╠═2a048274-52c1-11eb-339c-6b10fb972d11 # ╠═33866012-52c1-11eb-329c-eff5928eb12e # ╠═40b6a85a-52c1-11eb-080a-272e1642425d # ╠═4c2583a0-52c1-11eb-35ec-49b3c59c471f # ╠═5c2b6d64-52c1-11eb-14e5-bd81d666bb81 # ╟─0124b0f2-53f9-11eb-3ebb-f182fd11a129 # ╠═64d806be-53f9-11eb-2ca9-1d2ece3404bd # ╠═e7bf3d5c-5414-11eb-0556-452471c2b65b # ╠═0798e090-53f9-11eb-377a-fdf6c2ade4d1 # ╠═88515afc-5415-11eb-273c-83e703c7392d # ╠═9fc5c036-5415-11eb-1d0e-5377b9d92943 # ╠═bbc53e10-53f9-11eb-1166-17295832370f # ╠═be07006c-53f9-11eb-0141-4f9afae62d4b # ╠═e89063f6-53fa-11eb-2671-5bacb746b401 # ╠═bd059f48-5414-11eb-08c2-794f627f15ee # ╟─bba5b5d8-5415-11eb-35b1-c3e070d1e09d # ╠═c6d939e8-5415-11eb-0c37-c73be604f29c # ╟─0d016116-5416-11eb-3ab5-a534b0d1453a # ╠═6f5e0968-5416-11eb-0fcb-572aaa902574 # ╠═a0f41bf2-5416-11eb-2da6-cb4b485084c5 # ╠═a2ca2444-5416-11eb-0a40-1f65148b816e # ╟─efe5247c-5416-11eb-235e-6d7ce045b31e # ╠═fc2bd50a-5416-11eb-38f5-97335565a8eb # ╠═067a4be0-5417-11eb-2774-915824fb7987 # ╟─cbcac542-5416-11eb-3b99-791d68ce0745 # ╠═1b3d11c0-5417-11eb-0856-b5aa0be46b0b # ╟─3842c2ec-5417-11eb-0030-83c97d87e157 # ╠═4d1e7eea-5417-11eb-1021-d50ee8615148 # ╠═61abb6b6-5417-11eb-32a7-f74a2549ef42 # ╠═70a0118a-5417-11eb-12cf-016cdbccb50d # ╟─81510afc-5417-11eb-3111-6dfc809e8f6b # ╠═c8c092ea-5417-11eb-2175-b3a1c62f1454 # ╠═8f48f42e-5419-11eb-1865-c19b60d19b02 # ╠═420e26b2-5418-11eb-0477-5fd4284ff1d0 # ╟─e3627ac8-5417-11eb-1cf7-e13f24c1b62f # ╟─d0e25b7c-5424-11eb-04dd-396f8e034b86
let sys = DenseSystem(test_params...), beta = 12.34, basis_size = 10, P = 256, trotter = Trotter(sys, beta, basis_size, P) @test isapprox(trotter.Z, 7.78099507e-3) @test isapprox(trotter.E, 3.92839066e-1) @test isapprox(trotter.Cv, -5.05361185e-1) end
lemma biholomorphic_to_disc: assumes "connected S" and S: "S \<noteq> {}" "S \<noteq> UNIV" and prev: "\<And>f. \<lbrakk>f holomorphic_on S; \<forall>z \<in> S. f z \<noteq> 0\<rbrakk> \<Longrightarrow> \<exists>g. g holomorphic_on S \<and> (\<forall>z \<in> S. f z = (g z)\<^sup>2)" shows "\<exists>f g. f holomorphic_on S \<and> g holomorphic_on ball 0 1 \<and> (\<forall>z \<in> S. f z \<in> ball 0 1 \<and> g(f z) = z) \<and> (\<forall>z \<in> ball 0 1. g z \<in> S \<and> f(g z) = z)"
lemma bounded_UN [intro]: "finite A \<Longrightarrow> \<forall>x\<in>A. bounded (B x) \<Longrightarrow> bounded (\<Union>x\<in>A. B x)"
module DPairQuoteProblem import Language.Reflection %default total extract : Type -> Elab Unit extract ty = logTerm "debug.elab" 0 "type" !(quote ty) %macro extract' : Type -> Elab Unit extract' = extract -- logTerm "debug.elab" 0 "type" !(quote ty) %language ElabReflection ----------------------------- --- One-parameter example --- ----------------------------- namespace OneParameter data Y : Nat -> Type where Y0 : Y 0 Y1 : Y 1 %runElab logMsg "debug.elab" 0 "----------------------" namespace NonInlined X : Type X = (n : Nat ** Y n) %runElab extract X v : Unit v = %runElab extract X u : Unit u = extract' X %runElab logMsg "debug.elab" 0 "----------------------" namespace Inlined -- When there are not so many stuff inside the dpair, all is okay being inlined %runElab extract (n : Nat ** Y n) v : Unit v = %runElab extract (n : Nat ** Y n) u : Unit u = extract' (n : Nat ** Y n) ----------------------------- --- Two-parameter example --- ----------------------------- namespace TwoParameters data Y : Nat -> Type -> Type where Y0 : Y 0 Int Y1 : Y 1 Nat %runElab logMsg "debug.elab" 0 "----------------------" namespace NotInlined -- The following two elaboration runnings log the same result: X : Type X = (n : Nat ** x : Type ** Y n x) %runElab extract X v : Unit v = %runElab extract X u : Unit u = extract' X %runElab logMsg "debug.elab" 0 "----------------------" namespace Inlined -- The following two elaboration runnings log different results, -- but we expect them to be the same as above. %runElab extract (n : Nat ** x : Type ** Y n x) v : Unit v = %runElab extract (n : Nat ** x : Type ** Y n x) u : Unit u = extract' (n : Nat ** x : Type ** Y n x)
[GOAL] α β : SemilatSupCat e : α.X ≃o β.X ⊢ { toSupHom := { toFun := ↑e, map_sup' := (_ : ∀ (a b : α.X), ↑e (a ⊔ b) = ↑e a ⊔ ↑e b) }, map_bot' := (_ : ↑e ⊥ = ⊥) } ≫ { toSupHom := { toFun := ↑(OrderIso.symm e), map_sup' := (_ : ∀ (a b : β.X), ↑(OrderIso.symm e) (a ⊔ b) = ↑(OrderIso.symm e) a ⊔ ↑(OrderIso.symm e) b) }, map_bot' := (_ : ↑(OrderIso.symm e) ⊥ = ⊥) } = 𝟙 α [PROOFSTEP] ext [GOAL] case w α β : SemilatSupCat e : α.X ≃o β.X x✝ : (forget SemilatSupCat).obj α ⊢ ↑({ toSupHom := { toFun := ↑e, map_sup' := (_ : ∀ (a b : α.X), ↑e (a ⊔ b) = ↑e a ⊔ ↑e b) }, map_bot' := (_ : ↑e ⊥ = ⊥) } ≫ { toSupHom := { toFun := ↑(OrderIso.symm e), map_sup' := (_ : ∀ (a b : β.X), ↑(OrderIso.symm e) (a ⊔ b) = ↑(OrderIso.symm e) a ⊔ ↑(OrderIso.symm e) b) }, map_bot' := (_ : ↑(OrderIso.symm e) ⊥ = ⊥) }) x✝ = ↑(𝟙 α) x✝ [PROOFSTEP] exact e.symm_apply_apply _ [GOAL] α β : SemilatSupCat e : α.X ≃o β.X ⊢ { toSupHom := { toFun := ↑(OrderIso.symm e), map_sup' := (_ : ∀ (a b : β.X), ↑(OrderIso.symm e) (a ⊔ b) = ↑(OrderIso.symm e) a ⊔ ↑(OrderIso.symm e) b) }, map_bot' := (_ : ↑(OrderIso.symm e) ⊥ = ⊥) } ≫ { toSupHom := { toFun := ↑e, map_sup' := (_ : ∀ (a b : α.X), ↑e (a ⊔ b) = ↑e a ⊔ ↑e b) }, map_bot' := (_ : ↑e ⊥ = ⊥) } = 𝟙 β [PROOFSTEP] ext [GOAL] case w α β : SemilatSupCat e : α.X ≃o β.X x✝ : (forget SemilatSupCat).obj β ⊢ ↑({ toSupHom := { toFun := ↑(OrderIso.symm e), map_sup' := (_ : ∀ (a b : β.X), ↑(OrderIso.symm e) (a ⊔ b) = ↑(OrderIso.symm e) a ⊔ ↑(OrderIso.symm e) b) }, map_bot' := (_ : ↑(OrderIso.symm e) ⊥ = ⊥) } ≫ { toSupHom := { toFun := ↑e, map_sup' := (_ : ∀ (a b : α.X), ↑e (a ⊔ b) = ↑e a ⊔ ↑e b) }, map_bot' := (_ : ↑e ⊥ = ⊥) }) x✝ = ↑(𝟙 β) x✝ [PROOFSTEP] exact e.apply_symm_apply _ [GOAL] α β : SemilatInfCat e : α.X ≃o β.X ⊢ { toInfHom := { toFun := ↑e, map_inf' := (_ : ∀ (a b : α.X), ↑e (a ⊓ b) = ↑e a ⊓ ↑e b) }, map_top' := (_ : ↑e ⊤ = ⊤) } ≫ { toInfHom := { toFun := ↑(OrderIso.symm e), map_inf' := (_ : ∀ (a b : β.X), ↑(OrderIso.symm e) (a ⊓ b) = ↑(OrderIso.symm e) a ⊓ ↑(OrderIso.symm e) b) }, map_top' := (_ : ↑(OrderIso.symm e) ⊤ = ⊤) } = 𝟙 α [PROOFSTEP] ext [GOAL] case w α β : SemilatInfCat e : α.X ≃o β.X x✝ : (forget SemilatInfCat).obj α ⊢ ↑({ toInfHom := { toFun := ↑e, map_inf' := (_ : ∀ (a b : α.X), ↑e (a ⊓ b) = ↑e a ⊓ ↑e b) }, map_top' := (_ : ↑e ⊤ = ⊤) } ≫ { toInfHom := { toFun := ↑(OrderIso.symm e), map_inf' := (_ : ∀ (a b : β.X), ↑(OrderIso.symm e) (a ⊓ b) = ↑(OrderIso.symm e) a ⊓ ↑(OrderIso.symm e) b) }, map_top' := (_ : ↑(OrderIso.symm e) ⊤ = ⊤) }) x✝ = ↑(𝟙 α) x✝ [PROOFSTEP] exact e.symm_apply_apply _ [GOAL] α β : SemilatInfCat e : α.X ≃o β.X ⊢ { toInfHom := { toFun := ↑(OrderIso.symm e), map_inf' := (_ : ∀ (a b : β.X), ↑(OrderIso.symm e) (a ⊓ b) = ↑(OrderIso.symm e) a ⊓ ↑(OrderIso.symm e) b) }, map_top' := (_ : ↑(OrderIso.symm e) ⊤ = ⊤) } ≫ { toInfHom := { toFun := ↑e, map_inf' := (_ : ∀ (a b : α.X), ↑e (a ⊓ b) = ↑e a ⊓ ↑e b) }, map_top' := (_ : ↑e ⊤ = ⊤) } = 𝟙 β [PROOFSTEP] ext [GOAL] case w α β : SemilatInfCat e : α.X ≃o β.X x✝ : (forget SemilatInfCat).obj β ⊢ ↑({ toInfHom := { toFun := ↑(OrderIso.symm e), map_inf' := (_ : ∀ (a b : β.X), ↑(OrderIso.symm e) (a ⊓ b) = ↑(OrderIso.symm e) a ⊓ ↑(OrderIso.symm e) b) }, map_top' := (_ : ↑(OrderIso.symm e) ⊤ = ⊤) } ≫ { toInfHom := { toFun := ↑e, map_inf' := (_ : ∀ (a b : α.X), ↑e (a ⊓ b) = ↑e a ⊓ ↑e b) }, map_top' := (_ : ↑e ⊤ = ⊤) }) x✝ = ↑(𝟙 β) x✝ [PROOFSTEP] exact e.apply_symm_apply _
1 Malaysia has historically been the meeting place of vastly different cultures, religions, and people. People from all over the world have come to settle in Malaysia, each having brought something new to the country. Some, of course, took things away from Malaysia. 2 Early Malaysian history begins with the migration of Chinese people onto the Malaysian peninsula about 10,000 years ago. For thousands of years, the people of Malaysia lived somewhat isolated from the rest of the world. In 1 AD, two unrelated events would dramatically change Malaysia and begin bringing people from all over the world to Malaysia's shores. 3 At the time, India was getting gold and other metals from the Roman Empire and China. Around 1 AD, the Chinese Huns cut off the land route between India and China and the Roman emperor Vespasian ended shipments of gold to India. Desperate to resume the importation of gold and other metals, India sent huge ships with hundreds of men to Southeast Asia--including Malaysia--to find other sources. But when the Indians arrived on the Malay Peninsula, they didn't find gold--they found tin. While not as valuable as gold, tin provided plenty of wealth to the new Indian settlers.
module SimpleFFI.Spec mutual public export data DartType = IntType | BoolType | StringType | DoubleType | VoidType | NamedType String | FunctionType (List DartType) DartType | ListType DartType public export data Field = Var String DartType | Final String DartType public export data Parameter = P String DartType | N String DartType public export data Function = Fun String (List Parameter) DartType public export data Member = FieldMember Field | Method Function | Static Function | Constructor String (List Parameter) | Extends String | Const String DartType public export record Class where constructor MkClass name : String members : List Member public export data Declaration = ClassDecl Class | EnumDecl String (List String) public export record Lib where constructor MkLib name : String package : String public export record LibDef where constructor MkLibDef lib : Lib declarations : List Declaration public export record Module where constructor MkModule name : String libs : List LibDef export FromString DartType where fromString = NamedType export string : DartType string = StringType export double : DartType double = DoubleType export int : DartType int = IntType export bool : DartType bool = BoolType export void : DartType void = VoidType export function : List DartType -> DartType -> DartType function = FunctionType export listOf : DartType -> DartType listOf = ListType export var : DartType -> String -> Member var ty n = FieldMember $ Var n ty export final : DartType -> String -> Member final ty n = FieldMember $ Final n ty export positional : DartType -> String -> Parameter positional ty n = P n ty export defConst : DartType -> String -> Member defConst ty n = Const n ty export named : DartType -> String -> Parameter named ty n = N n ty export defConstructor : String -> List Parameter -> Member defConstructor = Constructor export defIO : String -> List Parameter -> DartType -> Member defIO n ps ret = Method $ Fun n ps ret export defStatic : String -> List Parameter -> DartType -> Member defStatic n ps ret = Static $ Fun n ps ret export defClass : String -> List Member -> Declaration defClass n ms = ClassDecl (MkClass n ms) export defEnum : String -> List String -> Declaration defEnum = EnumDecl export defLib : Lib -> List Declaration -> LibDef defLib = MkLibDef export defModule : String -> List LibDef -> Module defModule = MkModule export extends : String -> Member extends = Extends
"I’ve been privileged to work with Colette for over 3 years, observing first-hand the positive connection she creates with all parties involved in disharmony. Her communication skills help clarify the problems, assisting participants in moving forward towards a better understanding of each other. Her expertise in supporting parties in conflict to work towards a sensible solution demonstrates her understanding of the nature and needs of conflict resolution. Her background in grief counseling makes her particularly adept in working with hurting people." “The significant success of Abbotsford Restorative Justice, positively impacting the lives of many young offenders and their victims, is a testimony to your hard work and inspired leadership. "Colette is a highly skilled mediator, who has a natural ability to connect with people and guide them through conflict. She shows her clients compassion, empathy, and understanding."
using SymbolicRegression using Test using Random begin X = 2 .* randn(MersenneTwister(0), Float32, 2, 1000) y = 3 * cos.(X[2, :]) + X[1, :] .^ 2 .- 2 options = SymbolicRegression.Options(; binary_operators=(+, *, /, -), unary_operators=(cos,), crossoverProbability=0.0, # required for recording, as not set up to track crossovers. max_evals=10000, deterministic=true, seed=0, verbosity=0, progress=false, ) all_outputs = [] for i in 1:2 local hall_of_fame = EquationSearch( X, y; niterations=5, options=options, multithreading=false, numprocs=0 ) local dominating = calculate_pareto_frontier(X, y, hall_of_fame, options) push!(all_outputs, dominating[end].tree) end @test string(all_outputs[1]) == string(all_outputs[2]) end
-- Mathematical induction is the process of, by simple rules, -- we achieve a generalization (the opposite of deduction). -- Inductive data types follows the same principles, they -- have a base case and a inductive case. inductive ℕ : Type where | z : ℕ -- Here "z" (zero) is the base case | s : ℕ → ℕ -- And "s" (sucessor) is the inductive case theorem seven : ℕ := ℕ.s (ℕ.s (ℕ.s (ℕ.s (ℕ.s (ℕ.s (ℕ.s ℕ.z)))))) -- Some cool definitions to make it easier to work with this new -- data type def fromDefaultNat : Nat → ℕ | 0 => ℕ.z | n+1 => ℕ.s (fromDefaultNat n) def toDefaultNat : ℕ → Nat | ℕ.z => 0 | ℕ.s n => Nat.succ (toDefaultNat n) instance : OfNat ℕ n where ofNat := fromDefaultNat n instance : Repr ℕ where reprPrec x _ := repr (toDefaultNat x) -- Operations are defined recursively like that def add : ℕ → ℕ → ℕ | ℕ.z, m => m | ℕ.s n, m => ℕ.s (add n m) def add' : ℕ → ℕ → ℕ | m, ℕ.z => m | m, ℕ.s n => ℕ.s (add' m n) def mult : ℕ → ℕ → ℕ | ℕ.z, m => ℕ.z | ℕ.s ℕ.z, m => m | ℕ.s n, m => add m (mult n m) -- Like subtraction but trim at zero def monus : ℕ → ℕ → ℕ | ℕ.z, m => ℕ.z | m, ℕ.z => m | ℕ.s m, ℕ.s n => monus m n infixl:65 " + " => add infixl:66 " * " => mult instance : HSub ℕ ℕ ℕ where hSub := monus example : 3 * 3 + 5 - 4 = 10 := rfl -- Binary natural numbers inductive 𝔹 : Type where | nob : 𝔹 | zero : 𝔹 → 𝔹 | one : 𝔹 → 𝔹 deriving Repr def Bin.inc : 𝔹 → 𝔹 | 𝔹.nob => 𝔹.one 𝔹.nob | 𝔹.zero n => 𝔹.one n | 𝔹.one n => 𝔹.zero (inc n) def Bin.toNat : 𝔹 → ℕ | 𝔹.nob => ℕ.z | 𝔹.zero n => toNat n * 2 | 𝔹.one n => toNat n * 2 + 1 def Nat.toBin : ℕ → 𝔹 | ℕ.z => 𝔹.nob | ℕ.s n => Bin.inc (toBin n) instance : OfNat 𝔹 n where ofNat := Nat.toBin (fromDefaultNat n) -- Proofs theorem Nt.Add.sucAssoc : ∀ (m n : ℕ), ℕ.s m + n = ℕ.s (m + n) | ℕ.z, n => rfl | ℕ.s m, n => congrArg ℕ.s (sucAssoc m n) theorem Nt.Add.sucShift : ∀ (m n : ℕ), ℕ.s m + n = m + ℕ.s n | ℕ.z, n => rfl | ℕ.s m, n => Eq.trans (Nt.Add.sucAssoc (ℕ.s m) n) (congrArg ℕ.s (sucShift m n)) theorem Nt.Add.assoc : ∀ (m n p : ℕ), (m + n) + p = m + (n + p) | ℕ.z , n, p => rfl | ℕ.s m, n, p => by rw [Nt.Add.sucAssoc] apply congrArg ℕ.s (assoc m n p) theorem Nt.Add.rightId : ∀ (m : ℕ), m + 0 = m | ℕ.z => rfl | ℕ.s n => congrArg ℕ.s (rightId n) theorem Nt.Add.comm : ∀ (m n : ℕ), m + n = n + m | 0, n => Eq.symm (Nt.Add.rightId n) | ℕ.s m, n => by rw [Nt.Add.sucAssoc m n, comm m n, ← Nt.Add.sucShift n m] rfl theorem Nt.Mul.leftId : ∀ (m : ℕ), ℕ.s 0 * m = m | 0 => rfl | ℕ.s m => rfl theorem Nt.Mul.leftNeutral : ∀ (m : ℕ), 0 * m = 0 | 0 => rfl | ℕ.s m => rfl theorem Nt.Mul.sucLeft : ∀ (m n : ℕ), ℕ.s m * n = n + (m * n) | 0, n => by apply (Eq.symm (Nt.Add.rightId n)) | ℕ.s m, n => by rfl theorem Nt.Mul.sucRight : ∀ (m n : ℕ), m * ℕ.s n = (m * n) + m | 0, n => by simp; rfl | ℕ.s m, n => by rw [Nt.Mul.sucLeft m, Nt.Mul.sucLeft, sucRight m n, Nt.Add.assoc, Nt.Add.sucShift, ←Nt.Add.sucAssoc, Nt.Add.sucShift]; theorem Nt.Mul.distribAdd : ∀ (m n p : ℕ), (m + n) * p = m * p + n * p | 0 , n, p => by rfl | ℕ.s m, n, p => by rw [Nt.Add.sucAssoc] simp [Nt.Mul.sucLeft] rw [distribAdd m n p, Nt.Add.assoc] theorem Nt.Mul.rightNeutral : ∀ (m : ℕ), m * 0 = 0 | 0 => rfl | ℕ.s m => by rw[Nt.Mul.sucLeft, rightNeutral m]; rfl theorem Nt.Mul.rightId : ∀ (m : ℕ), m * ℕ.s 0 = m | 0 => rfl | ℕ.s m => by rw[Nt.Mul.sucLeft, rightId m]; rfl theorem Nt.Mul.comm : ∀ (m n : ℕ), m * n = n * m | 0 , n => Eq.symm (Nt.Mul.rightNeutral n) | ℕ.s m, n => by rw [Nt.Mul.sucRight, Nt.Mul.sucLeft, Nt.Add.comm, comm m n] termination_by Nt.Mul.comm m _ => sizeOf m -- Binary theorem Bin.incEqNatSuc : ∀ (b : 𝔹), Bin.toNat (Bin.inc b) = ℕ.s (Bin.toNat b) | 𝔹.nob => rfl | 𝔹.zero n => by simp [Bin.toNat]; rw [Nt.Add.comm]; rfl | 𝔹.one n => by simp [Bin.toNat] rw [Nt.Add.comm, incEqNatSuc n, Nt.Mul.sucLeft] rfl termination_by Bin.incEqNatSuc t => sizeOf t theorem Bin.eqNat : ∀ (n : ℕ), Bin.toNat (Nat.toBin n) = n | 0 => rfl | ℕ.s n => by simp [Nat.toBin]; rw [Bin.incEqNatSuc, eqNat n]; termination_by Bin.eqNat t => sizeOf t
lemma (in linorder_topology) compact_attains_inf: assumes "compact S" "S \<noteq> {}" shows "\<exists>s\<in>S. \<forall>t\<in>S. s \<le> t"
import FrankWolfe import LinearAlgebra import Random using Test n = Int(1e3) k = 10000 s = rand(1:100) @info "Seed: $s" Random.seed!(s) xpi = rand(n); total = sum(xpi); const xp = xpi ./ total; f(x) = LinearAlgebra.norm(x - xp)^2 function grad!(storage, x) @. storage = 2 * (x - xp) return nothing end lmo = FrankWolfe.UnitSimplexOracle(1.0) x0 = FrankWolfe.compute_extreme_point(lmo, rand(n)) @time xblas, _ = FrankWolfe.frank_wolfe( f, grad!, lmo, x0, max_iteration=k, line_search=FrankWolfe.Shortstep(), L=2, emphasis=FrankWolfe.blas, verbose=false, trajectory=false, momentum=0.9, ) @time xmem, _ = FrankWolfe.frank_wolfe( f, grad!, lmo, x0, max_iteration=k, line_search=FrankWolfe.Shortstep(), L=2, emphasis=FrankWolfe.memory, verbose=true, trajectory=true, momentum=0.9, ) @test f(xblas) ≈ f(xmem)
[STATEMENT] lemma trancl_code [code]: "trancl A = (if finite A then ntrancl (card A - 1) A else Code.abort (STR ''trancl: infinite set'') (\<lambda>_. trancl A))" [PROOF STATE] proof (prove) goal (1 subgoal): 1. A\<^sup>+ = (if finite A then ntrancl (card A - 1) A else Code.abort STR ''trancl: infinite set'' (\<lambda>_. A\<^sup>+)) [PROOF STEP] by (simp add: finite_trancl_ntranl)
------------------------------------------------------------------------ -- Precedence-correct expressions ------------------------------------------------------------------------ module Mixfix.Expr where open import Data.Vec using (Vec) open import Data.List using (List; []; _∷_) open import Data.List.Membership.Propositional using (_∈_) open import Data.List.Relation.Unary.Any using (here; there) open import Data.Product using (∃; _,_) open import Mixfix.Fixity open import Mixfix.Operator ------------------------------------------------------------------------ -- An abstract definition of precedence graphs -- The interface of precedence graphs. record PrecedenceGraphInterface : Set₁ where field -- Precedence graphs. PrecedenceGraph : Set -- Precedence levels. Precedence : PrecedenceGraph → Set -- The operators of the given precedence. ops : (g : PrecedenceGraph) → Precedence g → (fix : Fixity) → List (∃ (Operator fix)) -- The immediate successors of the precedence level. ↑ : (g : PrecedenceGraph) → Precedence g → List (Precedence g) -- All precedence levels in the graph. anyPrecedence : (g : PrecedenceGraph) → List (Precedence g) -- When a precedence graph is given the following module may be -- convenient to avoid having to write "g" all the time. module PrecedenceGraph (i : PrecedenceGraphInterface) (g : PrecedenceGraphInterface.PrecedenceGraph i) where PrecedenceGraph : Set PrecedenceGraph = PrecedenceGraphInterface.PrecedenceGraph i Precedence : Set Precedence = PrecedenceGraphInterface.Precedence i g ops : Precedence → (fix : Fixity) → List (∃ (Operator fix)) ops = PrecedenceGraphInterface.ops i g ↑ : Precedence → List Precedence ↑ = PrecedenceGraphInterface.↑ i g anyPrecedence : List Precedence anyPrecedence = PrecedenceGraphInterface.anyPrecedence i g ------------------------------------------------------------------------ -- Precedence-correct operator applications -- Parameterised on a precedence graph. module PrecedenceCorrect (i : PrecedenceGraphInterface) (g : PrecedenceGraphInterface.PrecedenceGraph i) where open PrecedenceGraph i g public mutual infixl 4 _⟨_⟩ˡ_ infixr 4 _⟨_⟩ʳ_ infix 4 _⟨_⟩_ _⟨_⟫ ⟪_⟩_ _∙_ -- Expr ps contains expressions where the outermost operator has -- one of the precedences in ps. data Expr (ps : List Precedence) : Set where _∙_ : ∀ {p assoc} (p∈ps : p ∈ ps) (e : ExprIn p assoc) → Expr ps -- ExprIn p assoc contains expressions where the outermost -- operator has precedence p (is /in/ precedence level p) and the -- associativity assoc. data ExprIn (p : Precedence) : Associativity → Set where ⟪_⟫ : (op : Inner (ops p closed )) → ExprIn p non _⟨_⟫ : (l : Outer p left) (op : Inner (ops p postfx )) → ExprIn p left ⟪_⟩_ : (op : Inner (ops p prefx )) (r : Outer p right) → ExprIn p right _⟨_⟩_ : (l : Expr (↑ p) ) (op : Inner (ops p (infx non ))) (r : Expr (↑ p) ) → ExprIn p non _⟨_⟩ˡ_ : (l : Outer p left) (op : Inner (ops p (infx left ))) (r : Expr (↑ p) ) → ExprIn p left _⟨_⟩ʳ_ : (l : Expr (↑ p) ) (op : Inner (ops p (infx right))) (r : Outer p right) → ExprIn p right -- Outer p fix contains expressions where the head operator either -- ⑴ has precedence p and associativity assoc or -- ⑵ binds strictly tighter than p. data Outer (p : Precedence) (assoc : Associativity) : Set where similar : (e : ExprIn p assoc) → Outer p assoc tighter : (e : Expr (↑ p)) → Outer p assoc -- Inner ops contains the internal parts (operator plus -- internal arguments) of operator applications. The operators -- have to be members of ops. data Inner {fix} (ops : List (∃ (Operator fix))) : Set where _∙_ : ∀ {arity op} (op∈ops : (arity , op) ∈ ops) (args : Vec (Expr anyPrecedence) arity) → Inner ops -- "Weakening". weakenE : ∀ {p ps} → Expr ps → Expr (p ∷ ps) weakenE (p∈ps ∙ e) = there p∈ps ∙ e weakenI : ∀ {fix ops} {op : ∃ (Operator fix)} → Inner ops → Inner (op ∷ ops) weakenI (op∈ops ∙ args) = there op∈ops ∙ args
% \section{Mutual Information} \newpage \chapter{Conclusion} We have seen that information must be measured from the transformed data, and not from the data itself. This approach has been used in fact for several years in the domain of image compression. Indeed, modern image compression methods consist firstly of applying a transformation (cosine transform for JPEG, wavelet transform, etc.) to the image, and then coding the coefficients obtained. A good transform for image compression is obviously an orthogonal transform because there is no redundancy, and the number of pixels is the same as in the original image. The exact number of bits necessary to code the coefficients is given by the Shannon entropy. For signal restoration, the problem is not to reduce the number of bits in the representation of the data, and we prefer to use a non-orthogonal wavelet transform, which avoids artifacts in reconstruction due to undersampling. We could have used the Shannon entropy to measure the information at a given scale, and derive the bins of the histogram from the standard deviation of the noise, but for several reasons we thought it better to directly introduce noise probability into our information measure. Firstly, we have seen that this leads, for Gaussian noise, to a very physical relation between the information and the wavelet coefficients: information is proportional to the energy of the wavelet coefficients normalized by the standard deviation of the noise. Secondly, it works even in the case of images with few photons/events (the histograms in this case present a bias). We have seen that the equations are easy to manipulate. Finally, experiments have confirmed that this approach gives good results. We have seen also that our new information measure leads naturally to a new method for signal restoration. We are now experimenting with this method, and working on generalizations to other classes of noise. \clearpage \newpage
# -*- coding: utf-8 -*- #!/usr/bin/python # # Authors Yann Bayle # E-mails [email protected] # License MIT # Created 16/08/2017 # Updated 20/10/2017 # Version 1.0.0 # """ Description of dl4m.py ====================== Parse dl4m.bib to create a simple and readable ReadMe.md table. ..todo:: sort bib add Fig for tasks, wordcloud, dataaugmentation bibtexparser accentuation handling in authors.md list error handling report on nb item per ENTRYTYPE generate .tsv from .bib wordcloud titles, abstract, articles valid bib field https://www.openoffice.org/bibliographic/bibtex-defs.html """ import numpy as np import matplotlib.pyplot as plt import bibtexparser from bibtexparser.bwriter import BibTexWriter def write_bib(bib_database, filen="dl4m.bib"): """Description of write_bib Write the items stored in bib_database into filen """ writer = BibTexWriter() writer.indent = ' ' writer.order_entries_by = ('noneyear', "author") with open(filen, "w", encoding="utf-8") as bibfile: bibfile.write(writer.write(bib_database)) def read_bib(filen="dl4m.bib"): """Description of read_bib Parse a bib file and load it into memory in a python format """ with open(filen, "r", encoding="utf-8") as bibtex_file: bibtex_str = bibtex_file.read() bib_database = bibtexparser.loads(bibtex_str) return bib_database def load_bib(filen="dl4m.bib"): """Description of load_bib Load and return the items stored in filen """ bib = read_bib(filen) write_bib(bib, filen) bib = read_bib(filen) return bib.entries def articles_per_year(bib): """Description of main Display the number of articles published per year input: file name storing articles details """ years = [] for entry in bib: year = int(entry['year']) years.append(year) plt.xlabel('Years') plt.ylabel('Number of Deep Learning articles\n related to Music Information Retrieval') year_bins = np.arange(min(years), max(years) + 2.0, 1.0) plt.hist(years, bins=year_bins, color="#401153", align="left") axe = plt.gca() axe.spines['right'].set_color('none') axe.spines['top'].set_color('none') axe.xaxis.set_ticks_position('bottom') axe.yaxis.set_ticks_position('left') fig_fn = "fig/articles_per_year.png" plt.savefig(fig_fn, dpi=200) print("Fig. with number of articles per year saved in", fig_fn) def get_reproducibility(bib): """Description of get_reproducibility Generate insights on reproducibility """ cpt = 0 for entry in bib: if "code" in entry: if entry["code"][:2] != "No": cpt += 1 print(str(cpt) + " articles provide their source code.") return cpt def get_nb_articles(bib): """Description of get_nb_articles Count the number of articles in the database """ print("There are", len(bib), "articles referenced.") return len(bib) def get_authors(bib): """Description of get_authors Print in authors.md the alphabetical list of authors """ authors = [] for entry in bib: for author in entry['author'].split(" and "): authors.append(author) authors = sorted(set(authors)) nb_authors = len(authors) print("There are", nb_authors, "researchers working on DL4M.") authors_fn = "authors.md" with open(authors_fn, "w", encoding="utf-8") as filep: filep.write("# List of authors\n\n") for author in authors: filep.write("- " + author + "\n") print("List of authors written in", authors_fn) return nb_authors def generate_list_articles(bib): """Description of generate_list_articles From the bib file generates a ReadMe-styled table like: | [Name of the article](Link to the .pdf) | Code's link if available | """ articles = "" for entry in bib: if "title" in entry: if "link" in entry: articles += "| [" + entry["title"] + "](" + entry["link"] + ") | " else: articles += "| " + entry["title"] + " | " if "code" in entry: if "No" in entry["code"]: articles += "No " else: if "github" in entry["code"]: articles += "[GitHub" else: articles += "[Website" articles += "](" + entry["code"] + ") " else: articles += "No " articles += "|\n" return articles def generate_summary_table(bib): """Description of generate_summary_table Parse dl4m.bib to create a simple and readable ReadMe.md table. """ nb_articles = get_nb_articles(bib) nb_repro = get_reproducibility(bib) percent_repro = str(int(nb_repro * 100. / nb_articles)) nb_articles = str(nb_articles) nb_repro = str(nb_repro) nb_authors = str(get_authors(bib) - 1) nb_tasks = str(get_field(bib, "task")) nb_datasets = str(get_field(bib, "dataset")) nb_archi = str(get_field(bib, "architecture")) nb_framework = str(get_field(bib, "framework")) articles = generate_list_articles(bib) readme_fn = "README.md" readme = "" pasted_articles = False with open(readme_fn, "r", encoding="utf-8") as filep: for line in filep: if "| " in line[:2] and line[2] != " ": if not pasted_articles: readme += articles pasted_articles = True elif "papers referenced" in line: readme += "- " + nb_articles + " papers referenced. " readme += "See the details in [dl4m.bib](dl4m.bib).\n" elif "other researchers" in line: readme += "- If you are applying DL to music, there are [" readme += nb_authors + " other researchers](authors.md) " readme += "in your field.\n" elif "tasks investigated" in line: readme += "- " + nb_tasks + " tasks investigated. " readme += "See the list of [tasks](tasks.md).\n" elif "datasets used" in line: readme += "- " + nb_datasets + " datasets used. " readme += "See the list of [datasets](datasets.md).\n" elif "architectures used" in line: readme += "- " + nb_archi + " architectures used. " readme += "See the list of [architectures](architectures.md).\n" elif "frameworks used" in line: readme += "- " + nb_framework + " frameworks used. " readme += "See the list of [frameworks](frameworks.md).\n" elif "- Only" in line: readme += "- Only " + nb_repro + " articles (" + percent_repro readme += "%) provide their source code.\n" else: readme += line with open(readme_fn, "w", encoding="utf-8") as filep: filep.write(readme) print("New ReadMe generated") def validate_field(field_name): """Description of validate_field Assert the validity of the field's name """ fields = ["task", "dataset", "architecture", "author", "dataaugmentation", "link", "title", "year", "journal", "code", "ENTRYTYPE", "framework"] error_str = "Invalid field provided: " + field_name + ". " error_str += "Valid fields: " + '[%s]' % ', '.join(map(str, fields)) assert field_name in fields, error_str def make_autopct(values): """Wrapper for the custom values to display in the pie chart slices """ def my_autopct(pct): """Define custom value to print in pie chart """ total = sum(values) val = int(round(pct*total/100.0)) return '{p:.1f}% ({v:d})'.format(p=pct, v=val) return my_autopct def pie_chart(items, field_name, max_nb_slice=8): """Description of pie_chart Display a pie_chart from the items given in input """ # plt.figure(figsize=(14, 10)) sizes = [] labels = sorted(set(items)) for label in labels: sizes.append(items.count(label)) labels = np.array(labels) sizes = np.array(sizes) if len(sizes) > max_nb_slice: new_labels = [] new_sizes = [] for _ in range(0, max_nb_slice): index = np.where(sizes == max(sizes))[0] if len(index) == len(labels): break new_labels.append(labels[index][0]) new_sizes.append(sizes[index][0]) labels = np.delete(labels, index) sizes = np.delete(sizes, index) new_labels.append(str(len(labels)) + " others") new_sizes.append(sum(sizes)) labels = np.array(new_labels) sizes = np.array(new_sizes) colors = ["gold", "yellowgreen", "lightcoral", "lightskyblue", "red", "green", "bisque", "lightgrey", "#555555"] tmp_labels = [] for label in labels: if "[" in label: label = label[1:].split("]")[0] tmp_labels.append(label) labels = np.array(tmp_labels) # h = plt.pie(sizes, labels=labels, colors=colors, shadow=False, plt.pie(sizes, labels=labels, colors=colors, shadow=False, startangle=90, autopct=make_autopct(sizes)) # Display the legend # leg = plt.legend(h[0], labels, bbox_to_anchor=(0.08, 0.4)) # leg.draw_frame(False) plt.axis('equal') fig_fn = "fig/pie_chart_" + field_name + ".png" plt.savefig(fig_fn, dpi=200) plt.close() print("Fig. with number of articles per year saved in", fig_fn) def get_field(bib, field_name): """Description of get_field Generate insights on the field_name in the bib file """ validate_field(field_name) nb_article_missing = 0 fields = [] for entry in bib: if field_name in entry: cur_fields = entry[field_name].split(" & ") for field in cur_fields: fields.append(field) else: nb_article_missing += 1 print(str(nb_article_missing) + " entries are missing the " + field_name + " field.") nb_fields = len(set(fields)) print(str(nb_fields) + " unique " + field_name + ".") field_fn = field_name + "s.md" with open(field_fn, "w", encoding="utf-8") as filep: filep.write("# List of " + field_name + "s\n\n") filep.write("Please refer to the list of useful acronyms used in deep ") filep.write("learning and music: [acronyms.md](acronyms.md).\n\n") for field in sorted(set(fields)): filep.write("- " + field + "\n") print("List of " + field_name + "s written in", field_fn) pie_chart(fields, field_name) return nb_fields def create_table(bib, outfilen="dl4m.tsv"): """Description of create_table Generate human-readable table in .tsv form. """ print("Generating the human-readable table as .tsv") # Gather all existing field in bib fields = [] for entry in bib: for key in entry: fields.append(key) print("Available fields:") print(set(fields)) fields = ["year", "ENTRYTYPE", "title", "author", "link", "code", "task", "reproducible", "dataset", "framework", "architecture", "dropout", "batch", "epochs", "dataaugmentation", "input", "dimension", "activation", "loss", "learningrate", "optimizer", "gpu"] print("Fields taken in order (in this order):") print(fields) separator = "\t" str2write = "" for field in fields: str2write += field.title() + separator str2write += "\n" for entry in bib: for field in fields: if field in entry: str2write += entry[field] str2write += separator str2write += "\n" with open(outfilen, "w", encoding="UTF-8") as filep: filep.write(str2write) def where_published(bib): """Display insights on where the articles have been published """ journals = [] conf = [] for entry in bib: if "article" in entry["ENTRYTYPE"]: journals.append(entry["journal"]) elif "inproceedings" in entry["ENTRYTYPE"]: conf.append(entry["booktitle"]) journals = sorted(set(journals)) conf = sorted(set(conf)) with open("publication_type.md", "w") as filep: filep.write("# List of publications type\n\n### Journals:\n\n- ") filep.write("\n- ".join(journals)) filep.write("\n\n### Conferences:\n\n- ") filep.write("\n- ".join(conf)) filep.write("\n") def main(filen="dl4m.bib"): """Description of main Main entry point input: file name storing articles details """ bib = load_bib(filen) generate_summary_table(bib) articles_per_year(bib) create_table(bib) where_published(bib) if __name__ == "__main__": main("dl4m.bib")
Formal statement is: lemma poly_cutoff_0 [simp]: "poly_cutoff n 0 = 0" Informal statement is: The polynomial $p_n(x)$ is zero at $x = 0$.
import algebra.big_operators.intervals algebra.big_operators.order algebra.big_operators.ring /-! # IMO 2021 A5 -/ namespace IMOSL namespace IMO2021A5 open finset variables {F : Type*} [linear_ordered_field F] private lemma bound1 {a : ℕ → F} (h : ∀ n : ℕ, 0 < a n) {n : ℕ} (h0 : (range n.succ).sum a ≤ 1) : a n / (1 - a n) * ((range n).sum a) ^ 2 ≤ (((range n.succ).sum a) ^ 3 - ((range n).sum a) ^ 3) / 3 := begin rcases nat.eq_zero_or_pos n with rfl | h1, rw [sum_range_zero, sum_range_one, zero_pow two_pos, mul_zero, zero_pow three_pos, sub_zero], exact div_nonneg (pow_nonneg (le_of_lt (h 0)) 3) zero_le_three, rw [sum_range_succ, add_comm] at h0 ⊢, have h2 : 0 ≤ (range n).sum a := sum_nonneg (λ i _, le_of_lt (h i)), replace h := h n, generalizes [hx : a n = x, hy : (range n).sum a = y], rw ← hx at h0 h; rw ← hy at h0 h2, clear h1 hx hy a n, suffices : x / (1 - x) * y ^ 2 ≤ x ^ 2 * y + x * y ^ 2, { apply le_trans this, rw ← sub_nonneg; ring_nf, exact mul_nonneg (div_nonneg zero_le_one zero_le_three) (pow_nonneg (le_of_lt h) 3) }, rw [← le_sub_iff_add_le', le_iff_eq_or_lt] at h0, rcases h0 with rfl | h0, { rw le_iff_eq_or_lt at h2, rcases h2 with h2 | h2, rw [← h2, sq, mul_zero, mul_zero, ← add_mul, mul_zero], rw [sq, ← mul_assoc, div_mul_cancel x (ne_of_gt h2), sq, mul_assoc, ← mul_add, ← add_mul, add_sub_cancel'_right, one_mul] }, { have h1 := ne_of_gt (lt_of_le_of_lt h2 h0), rw [div_eq_mul_inv, mul_right_comm, ← sub_le_iff_le_add, ← mul_sub_one, inv_eq_one_div, div_sub_one h1, sub_sub_cancel, ← mul_div_assoc, mul_right_comm, ← sq, sq y, ← mul_assoc, mul_div_assoc, ← sub_nonpos, ← mul_sub_one, div_sub_one h1], refine mul_nonpos_of_nonneg_of_nonpos (mul_nonneg _ h2) (div_nonpos_of_nonpos_of_nonneg _ _), exacts [sq_nonneg x, le_of_lt (by rwa sub_neg), le_trans h2 (le_of_lt h0)] } end /-- Final solution -/ theorem final_solution {a : ℕ → F} (h : ∀ n : ℕ, 0 < a n) {n : ℕ} (h0 : (range n).sum a ≤ 1) : (range n).sum (λ k, a k / (1 - a k) * ((range k).sum a) ^ 2) < 1 / 3 := begin rcases nat.eq_zero_or_pos n with rfl | h1, rw [sum_range_zero, one_div, inv_pos]; exact three_pos, refine lt_of_lt_of_le (sum_lt_sum (λ i h2, bound1 h _) _) _, { rw [mem_range, ← nat.succ_le_iff] at h2, refine le_trans _ h0, rw [← sum_range_add_sum_Ico a h2, le_add_iff_nonneg_right], exact sum_nonneg (λ i _, (le_of_lt (h i))) }, { use 0; split, rwa mem_range, rw [sum_range_zero, zero_pow two_pos, mul_zero, zero_pow three_pos, sub_zero, sum_range_one], exact div_pos (pow_pos (h 0) 3) three_pos }, { rw [← sum_div, sum_range_sub (λ i, (range i).sum a ^ 3)], simp only [sub_zero, sum_range_zero, zero_pow three_pos], exact div_le_div_of_le zero_le_three (pow_le_one 3 (sum_nonneg (λ i _, le_of_lt (h i))) h0) } end end IMO2021A5 end IMOSL
module CH09 %default total data Elem : a -> List a -> Type where InCons : Elem value (value :: xs) InList : (prf : Elem value xs) -> Elem value (x :: xs) elemNotInNil : Elem value [] -> Void elemNotInNil _ impossible elemNotInTail : (notInTail : Elem y xs -> Void) -> (notInCons : (x = y) -> Void) -> Elem y (x :: xs) -> Void elemNotInTail _ notInCons InCons = notInCons Refl elemNotInTail notInTail notInCons (InList prf) = notInTail prf isElem : DecEq a => (value : a) -> (xs : List a) -> Dec (Elem value xs) isElem _ [] = No elemNotInNil isElem y (x :: xs) = case decEq x y of Yes Refl => Yes InCons No notInCons => case isElem y xs of Yes prf => Yes (InList prf) No notInTail => No (elemNotInTail notInTail notInCons) data Last : List a -> a -> Type where LastOne : Last [value] value LastCons : (prf : Last xs value) -> Last (x :: xs) value notInLast : (contra : (x = y) -> Void) -> Last [x] y -> Void notInLast contra LastOne = contra Refl notInNil : Last [] value -> Void notInNil _ impossible notInTail : (notNil : (xs = []) -> Void) -> (notInList : Last xs y -> Void) -> Last (x :: xs) y -> Void notInTail notNil _ LastOne = notNil Refl notInTail _ notInList (LastCons prf) = notInList prf isLast : DecEq a => (xs : List a) -> (value : a) -> Dec (Last xs value) isLast [] _ = No notInNil isLast (x :: xs) y = case decEq xs [] of Yes Refl => case decEq x y of Yes Refl => Yes LastOne No notEq => No (notInLast notEq) No notNil => case isLast xs y of Yes prf => Yes (LastCons prf) No notLast => No (notInTail notNil notLast)
# All arrangements of 4 elements in 1 .. 4 Arrangements([1 .. 4], 4); # All permutations of 1 .. 4 PermutationsList([1 .. 4]);
import .Preloaded theorem limit_unique {X : Type*} [metric_space X] {s : ℕ → X} (x₀ x₁ : X) (h₀ : s ⟶ x₀) (h₁ : s ⟶ x₁) : x₀ = x₁ := begin unfold converges_to at *, apply eq_of_forall_dist_le, intros ε hεp, specialize h₀ (ε/3) (by linarith), cases h₀ with N₀ hN₀, specialize h₁ (ε/3) (by linarith), cases h₁ with N₁ hN₁, set N := max N₀ N₁ with hN, specialize hN₀ N (le_max_left _ _), specialize hN₁ N (le_max_right _ _), transitivity, apply dist_triangle_right _ _ (s N), linarith, end
section \<open>Computing the Gcd via the subresultant PRS\<close> text \<open>This theory now formalizes how the subresultant PRS can be used to calculate the gcd of two polynomials. Moreover, it proves the connection between resultants and gcd, namely that the resultant is 0 iff the degree of the gcd is non-zero.\<close> theory Subresultant_Gcd imports Subresultant Polynomial_Factorization.Missing_Polynomial_Factorial begin subsection \<open>Algorithm\<close> locale div_exp_sound_gcd = div_exp_sound div_exp for div_exp :: "'a :: {semiring_gcd_mult_normalize,factorial_ring_gcd} \<Rightarrow> 'a \<Rightarrow> nat \<Rightarrow> 'a" begin definition gcd_impl_primitive where [code del]: "gcd_impl_primitive G1 G2 = normalize (primitive_part (fst (subresultant_prs G1 G2)))" definition gcd_impl_main where [code del]: "gcd_impl_main G1 G2 = (if G1 = 0 then 0 else if G2 = 0 then normalize G1 else smult (gcd (content G1) (content G2)) (gcd_impl_primitive (primitive_part G1) (primitive_part G2)))" definition gcd_impl where "gcd_impl f g = (if length (coeffs f) \<ge> length (coeffs g) then gcd_impl_main f g else gcd_impl_main g f)" subsection \<open>Soundness Proof for @{term "gcd_impl = gcd"}\<close> end locale subresultant_prs_gcd = subresultant_prs_locale2 F n \<delta> f k \<beta> G1 G2 for F :: "nat \<Rightarrow> 'a :: {factorial_ring_gcd,semiring_gcd_mult_normalize} fract poly" and n :: "nat \<Rightarrow> nat" and \<delta> :: "nat \<Rightarrow> nat" and f :: "nat \<Rightarrow> 'a fract" and k :: nat and \<beta> :: "nat \<Rightarrow> 'a fract" and G1 G2 :: "'a poly" begin text \<open>The subresultant PRS computes the gcd up to a scalar multiple.\<close> context fixes div_exp :: "'a \<Rightarrow> 'a \<Rightarrow> nat \<Rightarrow> 'a" assumes div_exp_sound: "div_exp_sound div_exp" begin interpretation div_exp_sound_gcd div_exp using div_exp_sound by (rule div_exp_sound_gcd.intro) lemma subresultant_prs_gcd: assumes "subresultant_prs G1 G2 = (Gk, hk)" shows "\<exists> a b. a \<noteq> 0 \<and> b \<noteq> 0 \<and> smult a (gcd G1 G2) = smult b (normalize Gk)" proof - from subresultant_prs[OF div_exp_sound assms] have Fk: "F k = ffp Gk" and "\<forall> i. \<exists> H. i \<noteq> 0 \<longrightarrow> F i = ffp H" and "\<forall> i. \<exists> b. 3 \<le> i \<longrightarrow> i \<le> Suc k \<longrightarrow> \<beta> i = ff b" by auto from choice[OF this(2)] choice[OF this(3)] obtain H beta where FH: "\<And> i. i \<noteq> 0 \<Longrightarrow> F i = ffp (H i)" and beta: "\<And> i. 3 \<le> i \<Longrightarrow> i \<le> Suc k \<Longrightarrow> \<beta> i = ff (beta i)" by auto from Fk FH[OF k0] FH[of 1] FH[of 2] FH[of "Suc k"] F0[of "Suc k"] F1 F2 have border: "H k = Gk" "H 1 = G1" "H 2 = G2" "H (Suc k) = 0" by auto have "i \<noteq> 0 \<Longrightarrow> i \<le> k \<Longrightarrow> \<exists> a b. a \<noteq> 0 \<and> b \<noteq> 0 \<and> smult a (gcd G1 G2) = smult b (gcd (H i) (H (Suc i)))" for i proof (induct i rule: less_induct) case (less i) from less(3) have ik: "i \<le> k" . from less(2) have "i = 1 \<or> i \<ge> 2" by auto thus ?case proof assume "i = 1" thus ?thesis unfolding border[symmetric] by (intro exI[of _ 1], auto simp: numeral_2_eq_2) next assume i2: "i \<ge> 2" with ik have "i - 1 < i" "i - 1 \<noteq> 0" and imk: "i - 1 \<le> k" by auto from less(1)[OF this] i2 obtain a b where a: "a \<noteq> 0" and b: "b \<noteq> 0" and IH: "smult a (gcd G1 G2) = smult b (gcd (H (i - 1)) (H i))" by auto define M where "M = pseudo_mod (H (i - 1)) (H i)" define c where "c = \<beta> (Suc i)" have M: "pseudo_mod (F (i - 1)) (F i) = ffp M" unfolding to_fract_hom.pseudo_mod_hom[symmetric] M_def using i2 FH by auto have c: "c \<noteq> 0" using \<beta>0 unfolding c_def . from i2 ik have 3: "Suc i \<ge> 3" "Suc i \<le> Suc k" by auto from pmod[OF 3] have pm: "smult c (F (Suc i)) = pseudo_mod (F (i - 1)) (F i)" unfolding c_def by simp from beta[OF 3, folded c_def] obtain d where cd: "c = ff d" by auto with c have d: "d \<noteq> 0" by auto from pm[unfolded cd M] FH[of "Suc i"] have "ffp (smult d (H (Suc i))) = ffp M" by auto hence pm: "smult d (H (Suc i)) = M" by (rule map_poly_hom.injectivity) from ik F0[of i] i2 FH[of i] have Hi0: "H i \<noteq> 0" by auto from pseudo_mod[OF this, of "H (i - 1)", folded M_def] obtain c Q where c: "c \<noteq> 0" and "smult c (H (i - 1)) = H i * Q + M" by auto from this[folded pm] have "smult c (H (i - 1)) = Q * H i + smult d (H (Suc i))" by simp from gcd_add_mult[of "H i" Q "smult d (H (Suc i))", folded this] have "gcd (H i) (smult c (H (i - 1))) = gcd (H i) (smult d (H (Suc i)))" . with gcd_smult_ex[OF c, of "H (i - 1)" "H i"] obtain e where e: "e \<noteq> 0" and "gcd (H i) (smult d (H (Suc i))) = smult e (gcd (H i) (H (i - 1)))" unfolding gcd.commute[of "H i"] by auto with gcd_smult_ex[OF d, of "H (Suc i)" "H i"] obtain c where c: "c \<noteq> 0" and "smult c (gcd (H i) (H (Suc i))) = smult e (gcd (H (i - 1)) (H i))" unfolding gcd.commute[of "H i"] by auto from arg_cong[OF this(2), of "smult b"] arg_cong[OF IH, of "smult e"] have "smult (e * a) (gcd G1 G2) = smult (b * c) (gcd (H i) (H (Suc i)))" unfolding smult_smult by (simp add: ac_simps) moreover have "e * a \<noteq> 0" "b * c \<noteq> 0" using a b c e by auto ultimately show ?thesis by blast qed qed from this[OF k0 le_refl, unfolded border] obtain a b where "a \<noteq> 0" "b \<noteq> 0" and "smult a (gcd G1 G2) = smult b (normalize Gk)" by auto thus ?thesis by auto qed lemma gcd_impl_primitive: assumes "primitive_part G1 = G1" and "primitive_part G2 = G2" shows "gcd_impl_primitive G1 G2 = gcd G1 G2" proof - let ?pp = primitive_part let ?c = "content" let ?n = normalize from F2 F0[of 2] k2 have G2: "G2 \<noteq> 0" by auto obtain Gk hk where sub: "subresultant_prs G1 G2 = (Gk, hk)" by force have impl: "gcd_impl_primitive G1 G2 = ?n (?pp Gk)" unfolding gcd_impl_primitive_def sub by auto from subresultant_prs_gcd[OF sub] obtain a b where a: "a \<noteq> 0" and b: "b \<noteq> 0" and id: "smult a (gcd G1 G2) = smult b (?n Gk)" by auto define c where "c = unit_factor (gcd G1 G2)" define d where "d = smult (unit_factor a) c" from G2 have c: "is_unit c" unfolding c_def by auto from arg_cong[OF id, of ?pp, unfolded primitive_part_smult primitive_part_gcd assms primitive_part_normalize c_def[symmetric]] have id: "d * gcd G1 G2 = smult (unit_factor b) (?n (?pp Gk))" unfolding d_def by simp have d: "is_unit d" unfolding d_def using c a by (simp add: is_unit_smult_iff) from is_unitE[OF d] obtain e where e: "is_unit e" and de: "d * e = 1" by metis define a where "a = smult (unit_factor b) e" from arg_cong[OF id, of "\<lambda> x. e * x"] have "(d * e) * gcd G1 G2 = a * (?n (?pp Gk))" by (simp add: ac_simps a_def) hence id: "gcd G1 G2 = a * (?n (?pp Gk))" using de by simp have a: "is_unit a" unfolding a_def using b e by (simp add: is_unit_smult_iff) define b where "b = unit_factor (?pp Gk)" have "Gk \<noteq> 0" using subresultant_prs[OF div_exp_sound sub] F0[OF k0] by auto hence b: "is_unit b" unfolding b_def by auto from is_unitE[OF b] obtain c where c: "is_unit c" and bc: "b * c = 1" by metis obtain d where d: "is_unit d" and dac: "d = a * c" using c a by auto have "gcd G1 G2 = d * (b * ?n (?pp Gk))" unfolding id dac using bc by (simp add: ac_simps) also have "b * ?n (?pp Gk) = ?pp Gk" unfolding b_def by simp finally have "gcd G1 G2 = d * ?pp Gk" by simp from arg_cong[OF this, of ?n] have "gcd G1 G2 = ?n (d * ?pp Gk)" by simp also have "\<dots> = ?n (?pp Gk)" using d unfolding normalize_mult by (simp add: is_unit_normalize) finally show ?thesis unfolding impl .. qed end end context div_exp_sound_gcd begin lemma gcd_impl_main: assumes len: "length (coeffs G1) \<ge> length (coeffs G2)" shows "gcd_impl_main G1 G2 = gcd G1 G2" proof (cases "G1 = 0") case G1: False show ?thesis proof (cases "G2 = 0") case G2: False let ?pp = "primitive_part" from G2 have G2: "?pp G2 \<noteq> 0" and id: "(G2 = 0) = False" by auto from len have len: "length (coeffs (?pp G1)) \<ge> length (coeffs (?pp G2))" by simp from enter_subresultant_prs[OF len G2] obtain F n d f k b where "subresultant_prs_locale2 F n d f k b (?pp G1) (?pp G2)" by auto interpret subresultant_prs_locale2 F n d f k b "?pp G1" "?pp G2" by fact interpret subresultant_prs_gcd F n d f k b "?pp G1" "?pp G2" .. show ?thesis unfolding gcd_impl_main_def gcd_poly_decompose[of G1] id if_False using G1 by (subst gcd_impl_primitive, auto intro: div_exp_sound_axioms) next case True thus ?thesis unfolding gcd_impl_main_def by simp qed next case True with len have "G2 = 0" by auto thus ?thesis using True unfolding gcd_impl_main_def by simp qed text \<open>The implementation also reveals an important connection between resultant and gcd.\<close> lemma resultant_0_gcd: "resultant (f :: 'a poly) g = 0 \<longleftrightarrow> degree (gcd f g) \<noteq> 0" proof - { fix f g :: "'a poly" assume len: "length (coeffs f) \<ge> length (coeffs g)" { assume g: "g \<noteq> 0" with len have f: "f \<noteq> 0" by auto let ?f = "primitive_part f" let ?g = "primitive_part g" let ?c = "content" from len have len: "length (coeffs ?f) \<ge> length (coeffs ?g)" by simp obtain Gk hk where sub: "subresultant_prs ?f ?g = (Gk,hk)" by force have cf: "?c f \<noteq> 0" and cg: "?c g \<noteq> 0" using f g by auto { from g have "?g \<noteq> 0" by auto from enter_subresultant_prs[OF len this] obtain F n d f k b where "subresultant_prs_locale2 F n d f k b ?f ?g" by auto interpret subresultant_prs_locale2 F n d f k b ?f ?g by fact from subresultant_prs[OF div_exp_sound_axioms sub] have "h k = ff hk" by auto with h0[OF le_refl] have "hk \<noteq> 0" by auto } note hk0 = this have "resultant f g = 0 \<longleftrightarrow> resultant (smult (?c f) ?f) (smult (?c g) ?g) = 0" by simp also have "\<dots> \<longleftrightarrow> resultant ?f ?g = 0" unfolding resultant_smult_left[OF cf] resultant_smult_right[OF cg] using cf cg by auto also have "\<dots> \<longleftrightarrow> resultant_impl_main ?f ?g = 0" unfolding resultant_impl[symmetric] resultant_impl_def resultant_impl_main_def using len by auto also have "\<dots> \<longleftrightarrow> (degree Gk \<noteq> 0)" unfolding resultant_impl_main_def sub split using g hk0 by auto also have "degree Gk = degree (gcd_impl_primitive ?f ?g)" unfolding gcd_impl_primitive_def sub by simp also have "\<dots> = degree (gcd_impl_main f g)" unfolding gcd_impl_main_def using f g by auto also have "\<dots> = degree (gcd f g)" unfolding gcd_impl[symmetric] gcd_impl_def using len by auto finally have "(resultant f g = 0) = (degree (gcd f g) \<noteq> 0)" . } moreover { assume g: "g = 0" and f: "degree f \<noteq> 0" have "(resultant f g = 0) = (degree (gcd f g) \<noteq> 0)" unfolding g using f by auto } moreover { assume g: "g = 0" and f: "degree f = 0" have "(resultant f g = 0) = (degree (gcd f g) \<noteq> 0)" unfolding g using f by (auto simp: resultant_def sylvester_mat_def sylvester_mat_sub_def) } ultimately have "(resultant f g = 0) = (degree (gcd f g) \<noteq> 0)" by blast } note main = this show ?thesis proof (cases "length (coeffs f) \<ge> length (coeffs g)") case True from main[OF True] show ?thesis . next case False hence "length (coeffs g) \<ge> length (coeffs f)" by auto from main[OF this] show ?thesis unfolding gcd.commute[of g f] resultant_swap[of g f] by (simp split: if_splits) qed qed subsection \<open>Code Equations\<close> definition "gcd_impl_rec = subresultant_prs_main_impl fst" definition "gcd_impl_start = subresultant_prs_impl fst" lemma gcd_impl_rec_code: "gcd_impl_rec Gi_1 Gi ni_1 d1_1 hi_2 = ( let pmod = pseudo_mod Gi_1 Gi in if pmod = 0 then Gi else let ni = degree Gi; d1 = ni_1 - ni; gi_1 = lead_coeff Gi_1; hi_1 = (if d1_1 = 1 then gi_1 else div_exp gi_1 hi_2 d1_1); divisor = if d1 = 1 then gi_1 * hi_1 else if even d1 then - gi_1 * hi_1 ^ d1 else gi_1 * hi_1 ^ d1; Gi_p1 = sdiv_poly pmod divisor in gcd_impl_rec Gi Gi_p1 ni d1 hi_1)" unfolding gcd_impl_rec_def subresultant_prs_main_impl.simps[of _ Gi_1] split Let_def unfolding gcd_impl_rec_def[symmetric] by (rule if_cong, auto) lemma gcd_impl_start_code: "gcd_impl_start G1 G2 = (let pmod = pseudo_mod G1 G2 in if pmod = 0 then G2 else let n2 = degree G2; n1 = degree G1; d1 = n1 - n2; G3 = if even d1 then - pmod else pmod; pmod = pseudo_mod G2 G3 in if pmod = 0 then G3 else let g2 = lead_coeff G2; n3 = degree G3; h2 = (if d1 = 1 then g2 else g2 ^ d1); d2 = n2 - n3; divisor = (if d2 = 1 then g2 * h2 else if even d2 then - g2 * h2 ^ d2 else g2 * h2 ^ d2); G4 = sdiv_poly pmod divisor in gcd_impl_rec G3 G4 n3 d2 h2)" proof - obtain d1 where d1: "degree G1 - degree G2 = d1" by auto have id1: "(if even d1 then - pmod else pmod) = (-1)^ (d1 + 1) * (pmod :: 'a poly)" for pmod by simp show ?thesis unfolding gcd_impl_start_def subresultant_prs_impl_def gcd_impl_rec_def[symmetric] Let_def split unfolding d1 unfolding id1 by (rule if_cong, auto) qed lemma gcd_impl_main_code: "gcd_impl_main G1 G2 = (if G1 = 0 then 0 else if G2 = 0 then normalize G1 else let c1 = content G1; c2 = content G2; p1 = map_poly (\<lambda> x. x div c1) G1; p2 = map_poly (\<lambda> x. x div c2) G2 in smult (gcd c1 c2) (normalize (primitive_part (gcd_impl_start p1 p2))))" unfolding gcd_impl_main_def Let_def primitive_part_def gcd_impl_start_def gcd_impl_primitive_def subresultant_prs_impl by simp lemmas gcd_code_lemmas = gcd_impl_main_code gcd_impl_start_code gcd_impl_rec_code gcd_impl_def corollary gcd_via_subresultant: "gcd = gcd_impl" by simp end global_interpretation div_exp_Lazard_gcd: div_exp_sound_gcd "dichotomous_Lazard :: 'a :: {semiring_gcd_mult_normalize,factorial_ring_gcd} \<Rightarrow> _" defines gcd_impl_Lazard = div_exp_Lazard_gcd.gcd_impl and gcd_impl_main_Lazard = div_exp_Lazard_gcd.gcd_impl_main and gcd_impl_start_Lazard = div_exp_Lazard_gcd.gcd_impl_start and gcd_impl_rec_Lazard = div_exp_Lazard_gcd.gcd_impl_rec by (simp add: Subresultant.dichotomous_Lazard div_exp_sound_gcd_def) declare div_exp_Lazard_gcd.gcd_code_lemmas[code] lemmas resultant_0_gcd = div_exp_Lazard_gcd.resultant_0_gcd thm div_exp_Lazard_gcd.gcd_via_subresultant text \<open>Note that we did not activate @{thm div_exp_Lazard_gcd.gcd_via_subresultant} as code-equation, since according to our experiments, the subresultant-gcd algorithm is not always more efficient than the currently active equation. In particular, on @{typ "int poly"} @{const gcd_impl_Lazard} performs worse, but on multi-variate polynomials, e.g., @{typ "int poly poly poly"}, @{const gcd_impl_Lazard} is preferable.\<close> end
Furniture — This furniture, is one of the 19 designs published under the gallery: Home Interior Wall Color Contrast. In the next page, we have the home interior wall colors inspiring well home interior wall colors of worthy interior luxury [ ... ]. While in the previous page, we have the home interior wall colors photo of fine painting the house ideas interior interior home minimalist [ ... ].
module Mod_plcd_Notdef use typre use Mod_plcd_Material use Mod_Listen implicit none private public Notdef type, extends(PLCDMaterial) :: Notdef contains procedure :: SpecificCreateElementData => SpecificCreateElementData procedure :: ComputeStressTensor => CSLinElas procedure :: ComputeTangentTensor => CTLinElas procedure :: SpecificReadData => LE_SpecificReadData procedure :: SpecificScatterData => LE_SpecificScatterData end type contains subroutine CSLinElas(a,S) class(Notdef):: a real(rp) :: S(:) call runend('Notdef material cannot compute stresses') end subroutine subroutine CTLinElas(a,T) class(Notdef):: a real(rp) :: T(:,:) call runend('Notdef material cannot compute tangent matrix') end subroutine subroutine LE_SpecificReadData(a,Listener) class(Notdef) :: a type(ListenFile) :: Listener end subroutine subroutine LE_SpecificScatterData(a) class(Notdef) :: a end subroutine subroutine SpecificCreateElementData(a,pgaus,ElementData) implicit none class(NotDef), target :: a integer(ip) :: pgaus class(ElementMaterialData), pointer :: ElementData call runend('Notdef material cannot create gausspointdata') end subroutine end module
using RecipesBase @recipe function f(R::T) where {T<:PLMClusteringResult} χ = isinf(R.ϵ) ? 2.0 : R.ϵ for (i,idxs) in enumerate(R.clusters) addlabel = true for c in idxs @series begin label --> (addlabel ? "MC$i" : "") linecolor --> i models(R)[c], χ end addlabel = false end end if length(size(R.complex)) > 0 D = hcat(map(mean, models(R))...)' R.complex, D end end
-------------------------------------------------------------------------------- {-# OPTIONS_GHC -fno-warn-orphans #-} -------------------------------------------------------------------------------- {-# LANGUAGE AllowAmbiguousTypes #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE CPP #-} {-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE ForeignFunctionInterface #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE MagicHash #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeFamilyDependencies #-} {-# LANGUAGE TypeInType #-} {-# LANGUAGE UnboxedTuples #-} {-# LANGUAGE UndecidableInstances #-} -------------------------------------------------------------------------------- -- | Internal module to Eigen. -- Here we define all foreign function calls, -- and some typeclasses integral to the public and private interfaces -- of the library. module Eigen.Internal where -- FIXME: Explicit export list -------------------------------------------------------------------------------- --import Control.Monad (when) import Data.Binary (Binary(put,get)) import Data.Binary.Get (getByteString, getWord32be) import Data.Binary.Put (putByteString, putWord32be) import Data.Bits (xor) import Data.Complex (Complex((:+))) import Data.Kind (Type) import Data.Proxy (Proxy(Proxy)) --import Foreign.C.String (CString, peekCString) import Foreign.C.Types (CInt(CInt), CFloat(CFloat), CDouble(CDouble), CChar) import Foreign.ForeignPtr (ForeignPtr, castForeignPtr, withForeignPtr) import Foreign.Ptr (Ptr, castPtr, plusPtr) import Foreign.Storable (Storable(sizeOf, alignment, poke, peek, peekByteOff, peekElemOff, pokeByteOff, pokeElemOff)) import GHC.TypeLits (natVal, KnownNat, Nat) import System.IO.Unsafe (unsafeDupablePerformIO) import qualified Data.Vector.Storable as VS import qualified Data.ByteString as BS import qualified Data.ByteString.Internal as BSI -------------------------------------------------------------------------------- -- | Like 'Proxy', but specialised to 'Nat'. data Row (r :: Nat) = Row -- | Like 'Proxy', but specialised to 'Nat'. data Col (c :: Nat) = Col -- | Used internally. Given a 'KnownNat' constraint, turn the type-level 'Nat' into an 'Int'. natToInt :: forall n. KnownNat n => Int {-# INLINE natToInt #-} natToInt = fromIntegral (natVal @n Proxy) -------------------------------------------------------------------------------- -- | Cast to and from a C-FFI type -- 'Cast' is a closed typeclass with an associated injective type family. -- It is closed in the sense that we provide only four types -- with instances for it; and intend for eigen to only be used -- with those four types. The injectivity of the type family is -- then useful for avoiding MPTCs. 'Cast' has two functions; 'toC' -- and 'fromC', where 'toC' goes from a Haskell type to its associated -- C type for internal use, with the C FFI, and 'fromC' goes from the -- associated C type to the Haskell type. class Cast (a :: Type) where type family C a = (result :: Type) | result -> a toC :: a -> C a fromC :: C a -> a instance Cast Int where type C Int = CInt toC = CInt . fromIntegral {-# INLINE toC #-} fromC (CInt x) = fromIntegral x {-# INLINE fromC #-} instance Cast Float where type C Float = CFloat toC = CFloat {-# INLINE toC #-} fromC (CFloat x) = x {-# INLINE fromC #-} instance Cast Double where type C Double = CDouble toC = CDouble {-# INLINE toC #-} fromC (CDouble x) = x {-# INLINE fromC #-} instance Cast a => Cast (Complex a) where type C (Complex a) = CComplex (C a) toC (a :+ b) = CComplex (toC a) (toC b) {-# INLINE toC #-} fromC (CComplex a b) = (fromC a) :+ (fromC b) {-# INLINE fromC #-} -- | WARNING! 'toC' is lossy for any Int greater than (maxBound :: Int32)! instance Cast a => Cast (Int, Int, a) where type C (Int, Int, a) = CTriplet a {-# INLINE toC #-} toC (x, y, z) = CTriplet (toC x) (toC y) (toC z) {-# INLINE fromC #-} fromC (CTriplet x y z) = (fromC x, fromC y, fromC z) -------------------------------------------------------------------------------- -- | Complex number for FFI with the same memory layout as std::complex\<T\> data CComplex a = CComplex !a !a deriving (Show) instance Storable a => Storable (CComplex a) where sizeOf _ = sizeOf (undefined :: a) * 2 alignment _ = alignment (undefined :: a) poke p (CComplex x y) = do pokeElemOff (castPtr p) 0 x pokeElemOff (castPtr p) 1 y peek p = CComplex <$> peekElemOff (castPtr p) 0 <*> peekElemOff (castPtr p) 1 -------------------------------------------------------------------------------- -- | FIXME: Doc data CTriplet a where CTriplet :: Cast a => !CInt -> !CInt -> !(C a) -> CTriplet a deriving instance (Show a, Show (C a)) => Show (CTriplet a) instance (Storable a, Elem a) => Storable (CTriplet a) where sizeOf _ = sizeOf (undefined :: a) + sizeOf (undefined :: CInt) * 2 alignment _ = alignment (undefined :: CInt) poke p (CTriplet row col val) = do pokeElemOff (castPtr p) 0 row pokeElemOff (castPtr p) 1 col pokeByteOff p (sizeOf (undefined :: CInt) * 2) val peek p = CTriplet <$> peekElemOff (castPtr p) 0 <*> peekElemOff (castPtr p) 1 <*> peekByteOff p (sizeOf (undefined :: CInt) * 2) -------------------------------------------------------------------------------- -- | `Elem` is a closed typeclass that encompasses the properties -- eigen expects its values to possess, and simplifies the external -- API quite a bit. class (Num a, Cast a, Storable a, Storable (C a), Code (C a)) => Elem a instance Elem Float instance Elem Double instance Elem (Complex Float) instance Elem (Complex Double) -------------------------------------------------------------------------------- -- | Encode a C Type as a CInt -- -- Hack used in FFI wrapper functions when constructing FFI calls class Code a where; code :: a -> CInt instance Code CFloat where; code _ = 0 instance Code CDouble where; code _ = 1 instance Code (CComplex CFloat) where; code _ = 2 instance Code (CComplex CDouble) where; code _ = 3 -- | Hack used in constructing FFI calls. newtype MagicCode = MagicCode CInt deriving Eq instance Binary MagicCode where put (MagicCode _code) = putWord32be $ fromIntegral _code get = MagicCode . fromIntegral <$> getWord32be -- | Hack used in constructing FFI calls. magicCode :: Code a => a -> MagicCode magicCode x = MagicCode (code x `xor` 0x45696730) -------------------------------------------------------------------------------- -- | Machine size of a 'CInt'. intSize :: Int intSize = sizeOf (undefined :: CInt) -- | FIXME: Doc encodeInt :: CInt -> BS.ByteString encodeInt x = BSI.unsafeCreate (sizeOf x) $ (`poke` x) . castPtr -- | FIXME: Doc decodeInt :: BS.ByteString -> CInt decodeInt (BSI.PS fp fo fs) | fs == sizeOf x = x | otherwise = error "decodeInt: wrong buffer size" where x = performIO $ withForeignPtr fp $ peek . (`plusPtr` fo) -------------------------------------------------------------------------------- -- | 'Binary' instance for 'Data.Vector.Storable.Mutable.Vector' instance Storable a => Binary (VS.Vector a) where put vs = put (BS.length bs) >> putByteString bs where (fp,fs) = VS.unsafeToForeignPtr0 vs es = sizeOf (VS.head vs) bs = BSI.fromForeignPtr (castForeignPtr fp) 0 (fs * es) get = get >>= getByteString >>= \bs -> let (fp,fo,fs) = BSI.toForeignPtr bs es = sizeOf (VS.head vs) -- `plusForeignPtr` is used qualified here to just remind a reader -- that it is defined internally within eigen vs = VS.unsafeFromForeignPtr0 (Eigen.Internal.plusForeignPtr fp fo) (fs `div` es) in return vs -------------------------------------------------------------------------------- -- | FIXME: Doc data CSparseMatrix a -- | FIXME: Doc type CSparseMatrixPtr a = Ptr (CSparseMatrix a) -- | FIXME: Doc data CSolver a -- | FIXME: Doc type CSolverPtr a = Ptr (CSolver a) -- {-# INLINE unholyPerformIO #-} -- unholyPerformIO :: IO a -> a -- unholyPerformIO (IO m) = case m realWorld# of (# _, r #) -> r -- | FIXME: replace with unholyPerformIO (?) performIO :: IO a -> a performIO = unsafeDupablePerformIO -- | FIXME: Doc plusForeignPtr :: ForeignPtr a -> Int -> ForeignPtr b plusForeignPtr fp fo = castForeignPtr fp1 where vs :: VS.Vector CChar vs = VS.unsafeFromForeignPtr (castForeignPtr fp) fo 0 (fp1, _) = VS.unsafeToForeignPtr0 vs --------------------------------------------------------------------------------
(** * paterson: Equivalence of two flowchart schemes, due to Paterson cf. "Mathematical theory of computation", Manna, 1974 cf. "Kleene algebra with tests and program schematology", A. Angus and D. Kozen, 2001 *) From RelationAlgebra Require Import kat normalisation rewriting move kat_tac comparisons rel. Set Implicit Arguments. (** * Memory model *) (** we need only five memory locations: the [y_i] are temporary variables and [io] is used for input and output *) Inductive loc := y1 | y2 | y3 | y4 | io. Record state := { v1: nat; v2: nat; v3: nat; v4: nat; vio: nat }. (** getting the content of a memory cell *) Definition get x := match x with y1 => v1 | y2 => v2 | y3 => v3 | y4 => v4 | io => vio end. (** setting the content of a memory cell *) Definition set x n m := match x with | y1 => {| v1:=n; v2:=v2 m; v3:=v3 m; v4:=v4 m; vio:=vio m |} | y2 => {| v1:=v1 m; v2:=n; v3:=v3 m; v4:=v4 m; vio:=vio m |} | y3 => {| v1:=v1 m; v2:=v2 m; v3:=n; v4:=v4 m; vio:=vio m |} | y4 => {| v1:=v1 m; v2:=v2 m; v3:=v3 m; v4:=n; vio:=vio m |} | io => {| v1:=v1 m; v2:=v2 m; v3:=v3 m; v4:=v4 m; vio:=n |} end. (** basic properties of [get] and [set] *) Lemma get_set x v m: get x (set x v m) = v. Proof. now destruct x. Qed. Lemma get_set' x y v m: x<>y -> get x (set y v m) = get x m. Proof. destruct y; destruct x; simpl; trivial; congruence. Qed. Lemma set_set x v v' m: set x v (set x v' m) = set x v m. Proof. now destruct x. Qed. Lemma set_set' x y v v' m: x<>y -> set x v (set y v' m) = set y v' (set x v m). Proof. destruct y; destruct x; simpl; trivial; congruence. Qed. (** comparing locations *) Definition eqb x y := match x,y with | y1,y1 | y2,y2 | y3,y3 | y4,y4 | io,io => true | _,_ => false end. Lemma eqb_spec: forall x y, reflect (x=y) (eqb x y). Proof. destruct x; destruct y; simpl; try constructor; congruence. Qed. Lemma eqb_false x y: x<>y -> eqb x y = false. Proof. case eqb_spec; congruence. Qed. Lemma neqb_spec x y: negb (eqb x y) <-> x<>y. Proof. case eqb_spec; intuition; congruence. Qed. (** * Arithmetic and Boolean expressions *) Section s. (** we assume arbitrary functions to interpret symbols [f], [g], and [p] *) Variable ff: nat -> nat. Variable gg: nat -> nat -> nat. Variable pp: nat -> bool. (** we use a single inductive to represent Arithmetic and Boolean expressions: this allows us to share code about evaluation, free variables and so on, through polymorphism *) Inductive expr: Set -> Set := | e_var: loc -> expr nat | O: expr nat | f': expr nat -> expr nat | g': expr nat -> expr nat -> expr nat | p': expr nat -> expr bool | e_cap: expr bool -> expr bool -> expr bool | e_cup: expr bool -> expr bool -> expr bool | e_neg: expr bool -> expr bool | e_bot: expr bool | e_top: expr bool. Coercion e_var: loc >-> expr. (** ** evaluation of expressions *) Fixpoint eval A (e: expr A) (m: state): A := match e with | e_var x => get x m | O => 0%nat | f' e => ff (eval e m) | g' e f => gg (eval e m) (eval f m) | p' e => pp (eval e m) | e_cap e f => eval e m &&& eval f m | e_cup e f => eval e m ||| eval f m | e_neg e => negb (eval e m) | e_bot => false | e_top => true end. (** ** Free variables *) Fixpoint free y A (e: expr A): bool := match e with | e_var x => negb (eqb x y) | f' e | p' e | e_neg e => free y e | g' e f | e_cap e f | e_cup e f => free y e &&& free y f | _ => true end. (** ** Substitution *) Fixpoint subst x v A (f: expr A): expr A := match f with | e_var y => if eqb x y then v else e_var y | O => O | f' e => f' (subst x v e) | p' e => p' (subst x v e) | g' e f => g' (subst x v e) (subst x v f) | e_cup e f => e_cup (subst x v e) (subst x v f) | e_cap e f => e_cap (subst x v e) (subst x v f) | e_neg e => e_neg (subst x v e) | e_bot => e_bot | e_top => e_top end. Lemma subst_free x v A (e: expr A): free x e -> subst x v e = e. Proof. induction e; simpl; trivial. rewrite neqb_spec. case eqb_spec; congruence. intro. now rewrite IHe. rewrite landb_spec. intros [? ?]. now rewrite IHe1, IHe2. intro. now rewrite IHe. rewrite landb_spec. intros [? ?]. now rewrite IHe1, IHe2. rewrite landb_spec. intros [? ?]. now rewrite IHe1, IHe2. intro. now rewrite IHe. Qed. Lemma free_subst x e A (f: expr A): free x e -> free x (subst x e f). Proof. intro. induction f; simpl; rewrite ?IHf1; auto. case eqb_spec; trivial. simpl. rewrite neqb_spec. congruence. Qed. (** * Programs *) (** We just use KAT expressions, since any gflowchat scheme can be encoded as such an expression *) Inductive prog := | p_tst(t: expr bool) | p_aff(x: loc)(e: expr nat) | p_str(p: prog) | p_dot(p q: prog) | p_pls(p q: prog). (** * Bigstep semantics *) (** updating the memory, according to the assignment [x<-e] *) Definition update x e m := set x (eval e m) m. (** relational counterpart of this function *) Notation upd x e := (frel (update x e)). (** Bigstep semantics, as a fixpoint *) Fixpoint bstep (p: prog): hrel state state := match p with | p_tst p => [eval p: dset state] | p_aff x e => upd x e | p_str p => (bstep p)^* | p_dot p q => bstep p ⋅ bstep q | p_pls p q => bstep p + bstep q end. (** auxiliary lemma relating the evaluation of expressions, the assignments to the memory, and subsitution of expressions *) Lemma eval_update x v A (e: expr A) m: eval e (update x v m) = eval (subst x v e) m. Proof. induction e; simpl; try congruence. unfold update. case eqb_spec. intros <-. apply get_set. intro. apply get_set'. congruence. now rewrite IHe1, IHe2. now rewrite IHe1, IHe2. Qed. (** Now we make the set of programs a Kleene algebra with tests: we declare canonical structures for Boolean expressions (tests), programs (Kleene elements), and the natural injection of the former into the latter *) Canonical Structure expr_lattice_ops: lattice.ops := {| car := expr bool; leq := fun x y => eval x ≦ eval y; weq := fun x y => eval x ≡ eval y; cup := e_cup; cap := e_cap; bot := e_bot; top := e_top; neg := e_neg |}. Canonical Structure prog_lattice_ops: lattice.ops := {| car := prog; leq := fun x y => bstep x ≦ bstep y; weq := fun x y => bstep x ≡ bstep y; cup := p_pls; cap := assert_false p_pls; bot := p_tst e_bot; top := assert_false (p_tst e_bot); neg := assert_false id |}. Canonical Structure prog_monoid_ops: monoid.ops := {| ob := unit; mor n m := prog_lattice_ops; dot n m p := p_dot; one n := p_tst e_top; itr n := (fun x => p_dot x (p_str x)); str n := p_str; cnv n m := assert_false id; ldv n m p := assert_false (fun _ => id); rdv n m p := assert_false (fun _ => id) |}. Canonical Structure prog_kat_ops: kat.ops := {| kar := prog_monoid_ops; tst n := expr_lattice_ops; inj n := p_tst |}. Notation prog' := (prog_kat_ops tt tt). Notation test := (@tst prog_kat_ops tt). (** proving that the laws of KAT are satisfied is almost trivial, since the model faithfully embeds in the relational model *) Instance expr_lattice_laws: lattice.laws BL expr_lattice_ops. Proof. apply laws_of_injective_morphism with (@eval bool: expr bool -> dset state); trivial. split; simpl; tauto. Qed. Instance prog_monoid_laws: monoid.laws BKA prog_monoid_ops. Proof. apply laws_of_faithful_functor with (fun _ => state) (fun _ _: unit => bstep); trivial. split; simpl; try discriminate; try tauto. 2: firstorder. split; simpl; try discriminate; try tauto. firstorder auto with bool. Qed. Instance prog_lattice_laws: lattice.laws BKA prog_lattice_ops := lattice_laws tt tt. Instance prog_kat_laws: kat.laws prog_kat_ops. Proof. constructor; simpl; eauto with typeclass_instances. 2: tauto. split; try discriminate; try (simpl; tauto). intros x y H. apply inj_leq. intro m. apply H. intros x y H. apply inj_weq. intro m. apply H. intros _ x y. apply (inj_cup (X:=hrel_kat_ops)). intros _ x y. apply (inj_cap (X:=hrel_kat_ops)). Qed. (** ** variables read by a program *) (** [dont_read y p] holds if [p] never reads [y] *) Fixpoint dont_read y (p: prog'): bool := match p with | p_str p => dont_read y p | p_dot p q | p_pls p q => dont_read y p &&& dont_read y q | p_aff x e => free y e | p_tst t => free y t end. (** ** Additional notation *) Infix " ;" := (dot _ _ _) (left associativity, at level 40): ra_terms. Definition aff x e: prog' := p_aff x e. Notation "x <- e" := (aff x e) (at level 30). Notation del y := (y<-O). (** * Laws of schematic KAT *) Arguments hrel_monoid_ops : simpl never. Arguments hrel_lattice_ops : simpl never. (** (the numbering corresponds to Angus and Kozen's paper) *) Lemma eq_6 (x y: loc) (s t: expr nat): negb (eqb x y) &&& free y s -> x<-s;y<-t ≡ y<-subst x s t; x<-s. Proof. rewrite landb_spec, neqb_spec. intros [D H]. cbn. rewrite 2frel_comp. apply frel_weq. intro m. unfold update at 1 2 3. rewrite set_set' by congruence. f_equal. now rewrite eval_update, subst_free. unfold update. now rewrite <-eval_update. Qed. Lemma eq_7 (x y: loc) (s t: expr nat): negb (eqb x y) &&& free x s -> x<-s;y<-t ≡ x<-s;y<-subst x s t. Proof. rewrite landb_spec, neqb_spec. intros [D H]. cbn. rewrite 2frel_comp. apply frel_weq. intro m. unfold update at 1 3. f_equal. rewrite 2eval_update. symmetry. rewrite subst_free. reflexivity. now apply free_subst. Qed. Lemma eq_8 (x: loc) (s t: expr nat): x<-s;x<-t ≡ x<-subst x s t. Proof. cbn. rewrite frel_comp. apply frel_weq. intro m. unfold update. rewrite set_set. f_equal. apply eval_update. Qed. Lemma eq_9 (x: loc) (t: expr nat) (phi: test): [subst x t phi: test];x<-t ≡ x<-t;[phi]. Proof. Transparent hrel_lattice_ops. intros m m'. split. Opaque hrel_lattice_ops. intros [m0 [<- H] ->]. eexists. reflexivity. split; trivial. now rewrite eval_update. intros [m0 -> [<- H]]. eexists. 2: reflexivity. split; trivial. now rewrite <-eval_update. Qed. Lemma eq_6' (x y: loc) (s t: expr nat): free x t &&& negb (eqb x y) &&& free y s -> x<-s;y<-t ≡ y<-t; x<-s. Proof. rewrite landb_spec. intros [? ?]. now rewrite eq_6, subst_free. Qed. Lemma eq_9' (x: loc) (t: expr nat) (phi: test): free x phi -> [phi];x<-t ≡ x<-t;[phi]. Proof. intro. now rewrite <-eq_9, subst_free. Qed. Transparent hrel_lattice_ops. Arguments hrel_lattice_ops : simpl never. Lemma same_value (f: state -> state) (p: prog') (a b: test): bstep p ≡ frel f -> (forall m, eval a (f m) = eval b (f m)) -> p;[a ⊓ !b ⊔ !a ⊓ b] ≦ 0. Proof. intros Hp H. cbn. rewrite Hp. intros m m' [? -> [<- E]]. exfalso. rewrite lorb_spec, 2landb_spec, 2negb_spec, H in E. intuition congruence. Qed. (** * Garbage-collecting assignments to unread variables *) (** (i.e., Lemma 4.5 in Angus and Kozen's paper) *) Fixpoint gc y (p: prog'): prog' := match p with | p_str p => (gc y p)^* | p_tst _ => p | p_aff x e => if eqb x y then 1 else x<-e | p_dot p q => gc y p ; gc y q | p_pls p q => gc y p + gc y q end. Arguments prog_monoid_ops : simpl never. Arguments prog_lattice_ops : simpl never. Arguments prog_kat_ops : simpl never. Lemma gc_correct y p: dont_read y p -> gc y p; del y ≡ p; del y. Proof. intro H. transitivity (del y; gc y p). induction p; cbn. now apply eq_9'. case eqb_spec. ra. intro. apply eq_6'. now rewrite eqb_false. symmetry. apply str_move. symmetry. now auto. apply landb_spec in H as [? ?]. mrewrite IHp2. 2: assumption. now mrewrite IHp1. apply landb_spec in H as [? ?]. ra_normalise. now apply cup_weq; auto. symmetry. induction p; cbn. now apply eq_9'. case eqb_spec. intros <-. rewrite eq_8. ra. intro D. apply eq_6'. now rewrite eqb_false. symmetry. apply str_move. symmetry. now auto. apply landb_spec in H as [? ?]. mrewrite IHp2. 2: assumption. now mrewrite IHp1. apply landb_spec in H as [? ?]. ra_normalise. now apply cup_weq; auto. Qed. Ltac solve_rmov ::= first [ eassumption | symmetry; eassumption | eapply rmov_x_dot | apply rmov_x_pls | apply rmov_x_str | apply rmov_x_itr | apply rmov_x_cap | apply rmov_x_cup | apply rmov_x_neg | apply rmov_inj | apply rmov_x_1 | apply rmov_x_0 ]; match goal with |- ?x ≡ ?y => solve_rmov end. (** * Paterson's equivalence *) Theorem Paterson: let a1 := p' y1: test in let a2 := p' y2: test in let a3 := p' y3: test in let a4 := p' y4: test in let clr := del y1; del y2; del y3; del y4 in let x1 := y1<-io in let s1 := y1<-f' io in let s2 := y2<-f' io in let z1 := io<-y1; clr in let z2 := io<-y2; clr in let p11 := y1<-f' y1 in let p13 := y1<-f' y3 in let p22 := y2<-f' y2 in let p41 := y4<-f' y1 in let q222 := y2<-g' y2 y2 in let q214 := y2<-g' y1 y4 in let q211 := y2<-g' y1 y1 in let q311 := y3<-g' y1 y1 in let r11 := y1<-f' (f' y1) in let r12 := y1<-f' (f' y2) in let r13 := y1<-f' (f' y3) in let r22 := y2<-f' (f' y2) in let rhs := s2;[a2];q222;([!a2];r22;[a2];q222)^*;[a2];z2 in x1;p41;p11;q214;q311;([!a1];p11;q214;q311)^*;[a1];p13; (([!a4]+[a4];([!a2];p22)^*;[a2 ⊓ !a3];p41;p11);q214;q311;([!a1];p11;q214;q311)^*;[a1];p13)^*; [a4];([!a2];p22)^*;[a2 ⊓ a3];z2 ≡ rhs. Proof. intros. (** simple commutation hypotheses, to be exploited by [hkat] *) assert (a1p22: [a1];p22 ≡ p22;[a1]) by now apply eq_9'. assert (a1q214: [a1];q214 ≡ q214;[a1]) by now apply eq_9'. assert (a1q211: [a1];q211 ≡ q211;[a1]) by now apply eq_9'. assert (a1q311: [a1];q311 ≡ q311;[a1]) by now apply eq_9'. assert (a2p13: [a2];p13 ≡ p13;[a2]) by now apply eq_9'. assert (a2r12: [a2];r12 ≡ r12;[a2]) by now apply eq_9'. assert (a2r13: [a2];r13 ≡ r13;[a2]) by now apply eq_9'. assert (a3p13: [a3];p13 ≡ p13;[a3]) by now apply eq_9'. assert (a3p22: [a3];p22 ≡ p22;[a3]) by now apply eq_9'. assert (a3r12: [a3];r12 ≡ r12;[a3]) by now apply eq_9'. assert (a3r13: [a3];r13 ≡ r13;[a3]) by now apply eq_9'. assert (a4p13: [a4];p13 ≡ p13;[a4]) by now apply eq_9'. assert (a4p11: [a4];p11 ≡ p11;[a4]) by now apply eq_9'. assert (a4p22: [a4];p22 ≡ p22;[a4]) by now apply eq_9'. assert (a4q214: [a4];q214 ≡ q214;[a4]) by now apply eq_9'. assert (a4q211: [a4];q211 ≡ q211;[a4]) by now apply eq_9'. assert (a4q311: [a4];q311 ≡ q311;[a4]) by now apply eq_9'. assert (p41p11: p41;p11;[a1 ⊓ !a4 ⊔ !a1 ⊓ a4] ≦ 0). eapply same_value. apply frel_comp. reflexivity. assert (q211q311: q211;q311;[a2 ⊓ !a3 ⊔ !a2 ⊓ a3] ≦ 0). eapply same_value. apply frel_comp. reflexivity. assert (r12p22: r12;p22;p22;[a1 ⊓ !a2 ⊔ !a1 ⊓ a2] ≦ 0). eapply same_value. simpl bstep. rewrite 2frel_comp. reflexivity. reflexivity. (** this one cannot be used by [hkat], it's used by [rmov1] *) assert (p13p22: p13;p22 ≡ p22;p13) by now apply eq_6'. (** here starts the proof; the numbers in the comments refer to the equation numbers in Angus and Kozen's paper proof *) (** (19) *) transitivity ( x1;p41;p11;q214;q311; ([!a1 ⊓ !a4];p11;q214;q311 + [!a1 ⊓ a4];p11;q214;q311 + [ a1 ⊓ !a4];p13;[!a4];q214;q311 + [a1 ⊓ a4];p13;([!a2];p22)^*;[a2 ⊓ !a3];p41;p11;q214;q311)^*; [a1];p13;([!a2];p22)^*;[a2 ⊓ a3 ⊓ a4];z2). clear -a4p13 a4p22. hkat. do 2 rmov1 p13. (** (23+) *) transitivity ( x1;p41;p11;q214;q311; ([!a1 ⊓ !a4];p11;q214;q311 + [!a1 ⊓ a4];p11;q214;q311 + [ a1 ⊓ !a4];p13;[!a4];q214;q311 + [a1 ⊓ a4];p13;([!a2];p22)^*;[a2 ⊓ !a3];p41;p11;q214;q311)^*; ([!a2];p22)^*;[a1 ⊓ a2 ⊓ a3 ⊓ a4];(p13;z2)). clear -a1p22; hkat. setoid_replace (p13;z2) with z2 by (unfold z2, clr; mrewrite <-(gc_correct y1); [ simpl gc; kat | reflexivity ]). (** (24) *) transitivity (x1;p41;p11;q214;q311; ([a1 ⊓ a4];p13;([!a2];p22)^*;[a2 ⊓ !a3];p41;p11;q214;q311)^*; ([!a2];p22)^*;[a1 ⊓ a2 ⊓ a3 ⊓ a4];z2). clear -p41p11 a1p22 a1q214 a1q311 a4p11 a4p13 a4p22 a4q214 a4q311; hkat. (** big simplification w.r.t the paper proof here... *) (** (27) *) assert (p41p11q214: p41;p11;q214 ≡ p41;p11;q211). change (upd y4 (f' y1) ; upd y1 (f' y1) ; upd y2 (g' y1 y4) ≡ upd y4 (f' y1) ; upd y1 (f' y1) ; upd y2 (g' y1 y1)). now rewrite 3frel_comp. do 2 mrewrite p41p11q214. clear p41p11q214. (** (29) *) transitivity (x1;(p41;(p11;q211;q311;[a1];p13;([!a2];p22)^*;[a2 ⊓ !a3]))^*; p41;p11;q211;q311;([!a2];p22)^*;[a1 ⊓ a2 ⊓ a3];z2). clear -p41p11 a1p22 a1q211 a1q311 a4p22 a4q211 a4q311; hkat. (** (31) *) transitivity (x1;(p11;q211;q311;[a1];p13;([!a2];p22)^*;[a2 ⊓ !a3])^*; p11;q211;q311;([!a2];p22)^*;[a1 ⊓ a2 ⊓ a3];z2). unfold z2, clr. mrewrite <-(gc_correct y4). 2: reflexivity. simpl gc. kat. (** (32) *) rmov1 p13. transitivity ((x1;p11);(q211;q311;([!a2];p22)^*;[a1 ⊓ a2 ⊓ !a3];(p13;p11))^*; q211;q311;([!a2];p22)^*;[a1 ⊓ a2 ⊓ a3];z2). clear -a1p22 a2p13 a3p13; hkat. (** big simplification w.r.t the paper proof here... *) (** (33) *) setoid_replace (x1;p11) with s1 by apply eq_8. setoid_replace (p13;p11) with r13 by apply eq_8. (** (34) *) transitivity (s1;(q211;q311;(([!a2];p22)^*;([a1];r13));[a2 ⊓ !a3])^*; q211;q311;([!a2];p22)^*;[a1 ⊓ a2 ⊓ a3];z2). clear -a2r13 a3r13; hkat. setoid_replace (([!a2];p22)^*;([a1];r13)) with ([a1];r13;([!a2];p22)^*) by (assert (r13;p22 ≡ p22;r13) by (now apply eq_6'); rmov1 r13; clear -a1p22; hkat). transitivity (s1;([a1];(q211;q311;r13);([!a2];p22)^*;[a2 ⊓ !a3])^*; q211;q311;([!a2];p22)^*;[a1 ⊓ a2 ⊓ a3];z2). clear -a1q311 a1q211; hkat. (** (35) *) setoid_replace (q211;q311;r13) with (q211;q311;r12). 2: change (upd y2 (g' y1 y1) ; upd y3 (g' y1 y1) ; upd y1 (f' (f' y3)) ≡ upd y2 (g' y1 y1) ; upd y3 (g' y1 y1) ; upd y1 (f' (f' y2))); now rewrite 3frel_comp. (** (36) *) transitivity (s1;([a1];(q211;q311);[!a2];r12;([!a2];p22)^*;[a2])^*; (q211;q311);[a2];([!a2];p22)^*;[a1 ⊓ a2];z2). clear -a3p22 a3r12 q211q311. hkat. (** (37) *) transitivity (s1;([a1];q211;[!a2];r12;([!a2];p22)^*;[a2])^*; q211;[a2];([!a2];p22)^*;[a1 ⊓ a2];z2). unfold z2, clr. mrewrite <-(gc_correct y3). 2: reflexivity. simpl gc. kat. (** (38) *) transitivity (s1;[a1];q211;([!a2];r12;[a1];p22;[a2];q211 + [!a2];r12;[a1];p22;[!a2];(p22;q211))^*;[a2];z2). clear -a1p22 a1q211 a2r12 r12p22 a1p22. hkat. (** big simplification w.r.t the paper proof here... *) (** (43) *) assert (p22q211: p22;q211 ≡ q211) by apply eq_8. rewrite p22q211. transitivity (s1;[a1];q211;([!a2];r12;[a1];(p22;q211))^*;[a2];z2). kat. rewrite p22q211. clear p22q211. (** (44) *) unfold s1, a1, q211, r12, a2. rewrite <-eq_9. mrewrite eq_7. 2: reflexivity. mrewrite <-eq_9. mrewrite (eq_7 y1 y2 (f' (f' y2))). 2: reflexivity. unfold z2, clr. mrewrite <-(gc_correct y1). 2: reflexivity. unfold rhs, z2, clr, s2, a2. rewrite <-eq_9. unfold q222. mrewrite eq_7. 2: reflexivity. unfold r22. mrewrite <-eq_9. do 2 mrewrite eq_8. simpl gc. kat. (** (47) *) Qed. End s.
[STATEMENT] lemma boolfun_cases_helper: "g=(\<lambda>x. False) | g=(\<lambda>x. x) | g=(\<lambda>x. True) | g= (\<lambda>x. \<not>x)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. g = (\<lambda>x. False) \<or> g = (\<lambda>x. x) \<or> g = (\<lambda>x. True) \<or> g = Not [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. g = (\<lambda>x. False) \<or> g = (\<lambda>x. x) \<or> g = (\<lambda>x. True) \<or> g = Not [PROOF STEP] { [PROOF STATE] proof (state) goal (1 subgoal): 1. g = (\<lambda>x. False) \<or> g = (\<lambda>x. x) \<or> g = (\<lambda>x. True) \<or> g = Not [PROOF STEP] assume "g False" "g True" [PROOF STATE] proof (state) this: g False g True goal (1 subgoal): 1. g = (\<lambda>x. False) \<or> g = (\<lambda>x. x) \<or> g = (\<lambda>x. True) \<or> g = Not [PROOF STEP] hence "g = (\<lambda>x. True)" [PROOF STATE] proof (prove) using this: g False g True goal (1 subgoal): 1. g = (\<lambda>x. True) [PROOF STEP] by (rule_tac ext, case_tac x, auto) [PROOF STATE] proof (state) this: g = (\<lambda>x. True) goal (1 subgoal): 1. g = (\<lambda>x. False) \<or> g = (\<lambda>x. x) \<or> g = (\<lambda>x. True) \<or> g = Not [PROOF STEP] } [PROOF STATE] proof (state) this: \<lbrakk>g False; g True\<rbrakk> \<Longrightarrow> g = (\<lambda>x. True) goal (1 subgoal): 1. g = (\<lambda>x. False) \<or> g = (\<lambda>x. x) \<or> g = (\<lambda>x. True) \<or> g = Not [PROOF STEP] moreover [PROOF STATE] proof (state) this: \<lbrakk>g False; g True\<rbrakk> \<Longrightarrow> g = (\<lambda>x. True) goal (1 subgoal): 1. g = (\<lambda>x. False) \<or> g = (\<lambda>x. x) \<or> g = (\<lambda>x. True) \<or> g = Not [PROOF STEP] { [PROOF STATE] proof (state) this: \<lbrakk>g False; g True\<rbrakk> \<Longrightarrow> g = (\<lambda>x. True) goal (1 subgoal): 1. g = (\<lambda>x. False) \<or> g = (\<lambda>x. x) \<or> g = (\<lambda>x. True) \<or> g = Not [PROOF STEP] assume "g False" "\<not>g True" [PROOF STATE] proof (state) this: g False \<not> g True goal (1 subgoal): 1. g = (\<lambda>x. False) \<or> g = (\<lambda>x. x) \<or> g = (\<lambda>x. True) \<or> g = Not [PROOF STEP] hence "g = (\<lambda>x. \<not>x)" [PROOF STATE] proof (prove) using this: g False \<not> g True goal (1 subgoal): 1. g = Not [PROOF STEP] by (rule_tac ext, case_tac x, auto) [PROOF STATE] proof (state) this: g = Not goal (1 subgoal): 1. g = (\<lambda>x. False) \<or> g = (\<lambda>x. x) \<or> g = (\<lambda>x. True) \<or> g = Not [PROOF STEP] } [PROOF STATE] proof (state) this: \<lbrakk>g False; \<not> g True\<rbrakk> \<Longrightarrow> g = Not goal (1 subgoal): 1. g = (\<lambda>x. False) \<or> g = (\<lambda>x. x) \<or> g = (\<lambda>x. True) \<or> g = Not [PROOF STEP] moreover [PROOF STATE] proof (state) this: \<lbrakk>g False; \<not> g True\<rbrakk> \<Longrightarrow> g = Not goal (1 subgoal): 1. g = (\<lambda>x. False) \<or> g = (\<lambda>x. x) \<or> g = (\<lambda>x. True) \<or> g = Not [PROOF STEP] { [PROOF STATE] proof (state) this: \<lbrakk>g False; \<not> g True\<rbrakk> \<Longrightarrow> g = Not goal (1 subgoal): 1. g = (\<lambda>x. False) \<or> g = (\<lambda>x. x) \<or> g = (\<lambda>x. True) \<or> g = Not [PROOF STEP] assume "\<not>g False" "g True" [PROOF STATE] proof (state) this: \<not> g False g True goal (1 subgoal): 1. g = (\<lambda>x. False) \<or> g = (\<lambda>x. x) \<or> g = (\<lambda>x. True) \<or> g = Not [PROOF STEP] hence "g = (\<lambda>x. x)" [PROOF STATE] proof (prove) using this: \<not> g False g True goal (1 subgoal): 1. g = (\<lambda>x. x) [PROOF STEP] by (rule_tac ext, case_tac x, auto) [PROOF STATE] proof (state) this: g = (\<lambda>x. x) goal (1 subgoal): 1. g = (\<lambda>x. False) \<or> g = (\<lambda>x. x) \<or> g = (\<lambda>x. True) \<or> g = Not [PROOF STEP] } [PROOF STATE] proof (state) this: \<lbrakk>\<not> g False; g True\<rbrakk> \<Longrightarrow> g = (\<lambda>x. x) goal (1 subgoal): 1. g = (\<lambda>x. False) \<or> g = (\<lambda>x. x) \<or> g = (\<lambda>x. True) \<or> g = Not [PROOF STEP] moreover [PROOF STATE] proof (state) this: \<lbrakk>\<not> g False; g True\<rbrakk> \<Longrightarrow> g = (\<lambda>x. x) goal (1 subgoal): 1. g = (\<lambda>x. False) \<or> g = (\<lambda>x. x) \<or> g = (\<lambda>x. True) \<or> g = Not [PROOF STEP] { [PROOF STATE] proof (state) this: \<lbrakk>\<not> g False; g True\<rbrakk> \<Longrightarrow> g = (\<lambda>x. x) goal (1 subgoal): 1. g = (\<lambda>x. False) \<or> g = (\<lambda>x. x) \<or> g = (\<lambda>x. True) \<or> g = Not [PROOF STEP] assume "\<not>g False" "\<not>g True" [PROOF STATE] proof (state) this: \<not> g False \<not> g True goal (1 subgoal): 1. g = (\<lambda>x. False) \<or> g = (\<lambda>x. x) \<or> g = (\<lambda>x. True) \<or> g = Not [PROOF STEP] hence "g = (\<lambda>x. False)" [PROOF STATE] proof (prove) using this: \<not> g False \<not> g True goal (1 subgoal): 1. g = (\<lambda>x. False) [PROOF STEP] by (rule_tac ext, case_tac x, auto) [PROOF STATE] proof (state) this: g = (\<lambda>x. False) goal (1 subgoal): 1. g = (\<lambda>x. False) \<or> g = (\<lambda>x. x) \<or> g = (\<lambda>x. True) \<or> g = Not [PROOF STEP] } [PROOF STATE] proof (state) this: \<lbrakk>\<not> g False; \<not> g True\<rbrakk> \<Longrightarrow> g = (\<lambda>x. False) goal (1 subgoal): 1. g = (\<lambda>x. False) \<or> g = (\<lambda>x. x) \<or> g = (\<lambda>x. True) \<or> g = Not [PROOF STEP] ultimately [PROOF STATE] proof (chain) picking this: \<lbrakk>g False; g True\<rbrakk> \<Longrightarrow> g = (\<lambda>x. True) \<lbrakk>g False; \<not> g True\<rbrakk> \<Longrightarrow> g = Not \<lbrakk>\<not> g False; g True\<rbrakk> \<Longrightarrow> g = (\<lambda>x. x) \<lbrakk>\<not> g False; \<not> g True\<rbrakk> \<Longrightarrow> g = (\<lambda>x. False) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: \<lbrakk>g False; g True\<rbrakk> \<Longrightarrow> g = (\<lambda>x. True) \<lbrakk>g False; \<not> g True\<rbrakk> \<Longrightarrow> g = Not \<lbrakk>\<not> g False; g True\<rbrakk> \<Longrightarrow> g = (\<lambda>x. x) \<lbrakk>\<not> g False; \<not> g True\<rbrakk> \<Longrightarrow> g = (\<lambda>x. False) goal (1 subgoal): 1. g = (\<lambda>x. False) \<or> g = (\<lambda>x. x) \<or> g = (\<lambda>x. True) \<or> g = Not [PROOF STEP] by fast [PROOF STATE] proof (state) this: g = (\<lambda>x. False) \<or> g = (\<lambda>x. x) \<or> g = (\<lambda>x. True) \<or> g = Not goal: No subgoals! [PROOF STEP] qed
#cut values from CompareToManual.printComparisonsCSV() to make input file file <- "recallValues.txt" x <- t(read.csv(file)) x <- x[,] max <- max(x) h<-hist(x) hist(x, breaks = 20, main="Recall per experiment", xlab="Recall", ylab="Experiment Frequency") png("RecallHistogram.png", width=800, height = 800) hist(x, breaks = 20, main="Recall per experiment", xlab="Recall", ylab="Experiment Frequency") dev.off()
[STATEMENT] lemma det_state_cover_d_reachable[elim] : assumes "is_det_state_cover M V" and "v \<in> V" obtains q where "d_reaches M (initial M) v q" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<And>q. d_reaches M (initial M) v q \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by (metis (no_types, opaque_lifting) assms(1) assms(2) image_iff is_det_state_cover.simps is_det_state_cover_ass.elims(2))
```python import numpy as np from scipy.fftpack import dct, idct import matplotlib import seaborn as sns import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from music21 import converter matplotlib.style.use('styles.mplstyle') from helpers import cm2inch, title ``` ## Complex roots of unity ```python def omega(N, n): return np.exp(n * 2*np.pi*(0+1j) / N) ``` ```python N = 5 roots = np.array([ omega(N, k) for k in range(N)]) plt.figure(figsize=cm2inch(8.2, 7)) circle = plt.Circle((0,0), 1, ec='.7', fc='w', ls='--', lw=.5) plt.gca().add_artist(circle) for k, r in enumerate(roots): x, y = np.real(r), np.imag(r) plt.plot([0, x], [0, y], 'k--', lw=.5, alpha=.3) plt.plot(x, y, 'o', c='C3', ms=5) plt.annotate(f'$\omega_{N}^{k} = e^\\frac{{{k} \cdot 2\pi i}}{{{N}}}$', xy=(x,y), xytext=(10,0), textcoords='offset points') plt.axis('equal'); plt.xlim(-1.4, 1.4) plt.ylim(-1.4, 1.4) plt.ylabel('imaginary part') plt.xlabel('real part') title(f'Complex {N}-th roots of unity') plt.tight_layout() plt.savefig('../figures/suppl-S3/fig-roots-of-unity.pdf') ``` ## Cosine eigenvectors ```python def show_eigenvector(N, n): colors = ['.5'] + [f'C{i}' for i in range(9)] cos = lambda xs: np.cos(xs * np.pi * n / N) xs = np.arange(0, N) plt.plot(xs, cos(xs), '.-', lw=.5, c=colors[n]) xs = np.array([N-1, N]) plt.plot(xs, cos(xs), '.:', c=colors[n], lw=.5) plt.axhline(0, ls='--', c='.75', zorder=-1, lw=.5) plt.figure(figsize=cm2inch(8.2, 3.5)) show_eigenvector(10, 2) ``` ```python fig = plt.figure(figsize=cm2inch(8.2, 6), tight_layout=True) max_n = 5 gs = gridspec.GridSpec(max_n, 2) for n in range(max_n): fig.add_subplot(gs[n, 0]) show_eigenvector(10, n) plt.ylim(-1.1, 1.1) plt.ylabel(f'$\mathbf{{v}}_{n}$') if n < max_n-1: plt.xticks([]) if n == 0: title('$N = 10$') if n == max_n - 1: plt.xlabel('time step') for n in range(max_n): fig.add_subplot(gs[n, 1]) show_eigenvector(30, n) plt.yticks([]) plt.ylim(-1.1, 1.1) if n < max_n-1: plt.xticks([]) if n == 0: title('$N = 30$') if n == max_n - 1: plt.xlabel('time step') plt.tight_layout(pad=0) plt.savefig('../figures/suppl-S3/fig-cosines.pdf') ``` ## Autoregressive process AR(1) We look at the (unnormalized) autocovariance matrix \begin{align} [\Psi(\rho)]_{ij} := \rho^{|j-i|} \end{align} from Ahmed et al (1974). These are Toeplitz matrices ```python def get_psi(N, rho): psi = np.eye(N) for i, j in zip(*np.triu_indices(N)): psi[i, j] = rho**(j-i) psi[j, i] = rho**(j-i) return psi # get_psi(5, .99) ``` ```python fig = plt.figure(figsize=cm2inch(8.2, 6)) gs = gridspec.GridSpec(3, 2) def show_col(col, rho, N=200): ax1 = fig.add_subplot(gs[:2, col]) psi = get_psi(N, rho) plt.imshow(psi) title(f'Covariance $\\rho = {rho}$') ax1 = fig.add_subplot(gs[2, col]) lam, V = np.linalg.eig(psi) top_lambdas = lam.argsort()[::-1][1:4] plt.plot(V[:, top_lambdas]) title('Eigenvectors') # show_col(0, .1) # show_col(1, .5) show_col(0, .95) show_col(1, .999) plt.tight_layout() plt.savefig('../figures/suppl-S3/fig-ar1.pdf') ``` ```python ```
# This file is part of RStan # Copyright (C) 2012, 2013, 2014, 2015, 2016, 2017 Trustees of Columbia University # Copyright (C) 1995-2012 The R Core Team # Some parts Copyright (C) 1999 Dr. Jens Oehlschlaegel-Akiyoshi # # RStan 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. # # RStan is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. pairs.stanfit <- function(x, labels = NULL, panel = NULL, ..., lower.panel = NULL, upper.panel = NULL, diag.panel = NULL, text.panel = NULL, label.pos = 0.5 + 1 / 3, cex.labels = NULL, font.labels = 1, row1attop = TRUE, gap = 1, log = "", pars = NULL, condition = "accept_stat__", include = TRUE) { gsp <- get_sampler_params(x, inc_warmup = FALSE) if (is.null(pars)) { pars <- dimnames(x)[[3]] arr <- round(rstan::extract(x, pars = pars, permuted = FALSE), digits = 12) if ("energy__" %in% colnames(gsp[[1]])) { dims <- dim(arr) dims[3] <- dims[3] + 1L nms <- dimnames(arr) nms$parameters <- c(nms$parameters, "energy__") E <- sapply(gsp, FUN = function(y) y[, "energy__"]) arr <- array(c(c(arr), c(E)), dim = dims, dimnames = nms) } } else if (!include) { incl_energy <- !any(pars == "energy__") pars <- setdiff(x@sim$pars_oi, pars) arr <- round(rstan::extract(x, pars = pars, permuted = FALSE), digits = 12) if (incl_energy && "energy__" %in% colnames(gsp[[1]])) { dims <- dim(arr) dims[3] <- dims[3] + 1L nms <- dimnames(arr) nms$parameters <- c(nms$parameters, "energy__") E <- sapply(gsp, FUN = function(y) y[, "energy__"]) arr <- array(c(c(arr), c(E)), dim = dims, dimnames = nms) } } else { arr <- round(rstan::extract(x, pars = pars, permuted = FALSE), digits = 12) } sims <- nrow(arr) chains <- ncol(arr) varying <- apply(arr, 3, FUN = function(y) length(unique(c(y))) > 1) if (any(!varying)) { message( "the following parameters were dropped because they are constant\n", paste(names(varying)[!varying], collapse = " ") ) arr <- arr[, , varying, drop = FALSE] } dupes <- duplicated(arr, MARGIN = 3) if (any(dupes)) { message( "the following parameters were dropped because they are duplicative\n", paste(dimnames(arr)[[3]][dupes], collapse = " ") ) arr <- arr[, , !dupes, drop = FALSE] } divergent__ <- matrix(c(sapply(gsp, FUN = function(y) y[, "divergent__"])), nrow = sims * chains, ncol = dim(arr)[3] ) max_td <- x@stan_args[[1]]$control if (is.null(max_td)) { max_td <- 10 } else { max_td <- max_td$max_treedepth if (is.null(max_td)) max_td <- 10 } hit <- matrix(c(sapply(gsp, FUN = function(y) y[, "treedepth__"] >= max_td)), nrow = sims * chains, ncol = dim(arr)[3] ) if (is.list(condition)) { if (length(condition) != 2) stop("if a list, 'condition' must be of length 2") arr <- arr[, c(condition[[1]], condition[[2]]), , drop = FALSE] k <- length(condition[[1]]) mark <- c(rep(TRUE, sims * k), rep(FALSE, sims * length(condition[[2]]))) } else if (is.logical(condition)) { stopifnot(length(condition) == (sims * chains)) mark <- !condition } else if (is.character(condition)) { condition <- match.arg(condition, several.ok = FALSE, choices = c( "accept_stat__", "stepsize__", "treedepth__", "n_leapfrog__", "divergent__", "energy__", "lp__" ) ) if (condition == "lp__") { mark <- simplify2array(get_logposterior(x, inc_warmup = FALSE)) } else { mark <- sapply(gsp, FUN = function(y) y[, condition]) } if (condition == "divergent__") { mark <- as.logical(mark) } else { mark <- c(mark) >= median(mark) } if (length(unique(mark)) == 1) { stop(paste(condition, "is constant so it cannot be used as a condition")) } } else if (!is.null(condition)) { if (all(condition == as.integer(condition))) { arr <- arr[, condition, , drop = FALSE] k <- ncol(arr) %/% 2 mark <- c(rep(FALSE, sims * k), rep(TRUE, sims * (chains - k))) } else if (condition > 0 && condition < 1) { mark <- rep(1:sims > (condition * sims), times = chains) } else { stop("'condition' must be an integer (vector) or a number between 0 and 1 exclusive") } } else { k <- ncol(arr) %/% 2 mark <- c(rep(FALSE, sims * k), rep(TRUE, sims * (chains - k))) } x <- apply(arr, MARGIN = "parameters", FUN = function(y) y) nc <- ncol(x) if (isTRUE(log)) { xl <- apply(x >= 0, 2, FUN = all) if ("lp__" %in% names(xl)) xl["lp__"] <- FALSE } else if (is.numeric(log)) { xl <- log } else { xl <- grepl("x", log) } if (is.numeric(xl) || any(xl)) { x[, xl] <- log(x[, xl]) colnames(x)[xl] <- paste("log", colnames(x)[xl], sep = "-") } if (is.null(lower.panel)) { if (!is.null(panel)) { lower.panel <- panel } else { lower.panel <- function(x, y, ...) { dots <- list(...) dots$x <- x[!mark] dots$y <- y[!mark] if (is.null(mc$nrpoints) && !identical(condition, "divergent__")) { dots$nrpoints <- Inf dots$col <- ifelse(divergent__[!mark] == 1, "red", ifelse(hit[!mark] == 1, "yellow", NA_character_) ) } dots$add <- TRUE do.call(smoothScatter, args = dots) } } } if (is.null(upper.panel)) { if (!is.null(panel)) { upper.panel <- panel } else { upper.panel <- function(x, y, ...) { dots <- list(...) dots$x <- x[mark] dots$y <- y[mark] if (is.null(mc$nrpoints) && !identical(condition, "divergent__")) { dots$nrpoints <- Inf dots$col <- ifelse(divergent__[mark] == 1, "red", ifelse(hit[mark] == 1, "yellow", NA_character_) ) } dots$add <- TRUE do.call(smoothScatter, args = dots) } } } if (is.null(diag.panel)) { diag.panel <- function(x, ...) { usr <- par("usr") on.exit(par(usr)) par(usr = c(usr[1:2], 0, 1.5)) h <- hist(x, plot = FALSE) breaks <- h$breaks y <- h$counts y <- y / max(y) nB <- length(breaks) rect(breaks[-nB], 0, breaks[-1], y, col = "cyan", ...) } } if (is.null(panel)) panel <- points if (is.null(text.panel)) { textPanel <- function(x = 0.5, y = 0.5, txt, cex, font) { text(x, y, txt, cex = cex, font = font) } } else { textPanel <- text.panel } if (is.null(labels)) labels <- colnames(x) mc <- match.call(expand.dots = TRUE) mc[1] <- call("pairs") mc$x <- x mc$labels <- labels mc$panel <- panel mc$lower.panel <- lower.panel mc$upper.panel <- upper.panel mc$diag.panel <- diag.panel mc$text.panel <- textPanel mc$log <- "" mc$condition <- NULL mc$pars <- NULL mc$include <- NULL eval(mc) }
Require Import CertifiedExtraction.Extraction.Core CertifiedExtraction.Extraction.Basics. (* Lemma CompileBinop: *) (* forall {av} name var1 var2 (val1 val2: W) ext op tenv, *) (* name ∉ ext -> *) (* NotInTelescope name tenv -> *) (* StringMap.MapsTo var1 (SCA av val1) ext -> *) (* StringMap.MapsTo var2 (SCA av val2) ext -> *) (* forall env, *) (* {{ tenv }} *) (* Assign name (Binop op (Var var1) (Var var2)) *) (* {{ [[name ->> (SCA _ (eval_binop (inl op) val1 val2)) as _]]::tenv }} ∪ {{ ext }} // env. *) (* Proof. *) (* SameValues_Facade_t. *) (* Qed. *) Definition WrapOpInExpr op := match op with | inl o => Binop o | inr t => TestE t end. Lemma CompileBinopOrTest: forall {av} name var1 var2 (val1 val2: W) ext op (tenv: Telescope av), name ∉ ext -> NotInTelescope name tenv -> StringMap.MapsTo var1 (wrap val1) ext -> StringMap.MapsTo var2 (wrap val2) ext -> forall env, {{ tenv }} Assign name (WrapOpInExpr op (Var var1) (Var var2)) {{ [[`name ->> (eval_binop op val1 val2) as _]]::tenv }} ∪ {{ ext }} // env. Proof. destruct op; SameValues_Facade_t. Qed. (* Lemma CompileBinopB_util: *) (* forall {T} k1 k2 k3 {v1 v2 v3} (fmap: StringMap.t T), *) (* k1 <> k2 -> k2 <> k3 -> k1 <> k3 -> *) (* StringMap.Equal ([`k3 |> v3] ::[`k2 |> v2]::[`k1 |> v1]::fmap) *) (* ([`k1 |> v1] ::[`k2 |> v2]::[`k3 |> v3]::fmap). *) (* Proof. *) (* unfold StringMap.Equal; intros; *) (* destruct (StringMap.E.eq_dec y k1); *) (* destruct (StringMap.E.eq_dec y k2); *) (* destruct (StringMap.E.eq_dec y k3); *) (* SameValues_Facade_t. *) (* Qed. *) (* Lemma CompileBinopB_util2: *) (* forall {av : Type} (var1 var2 var3 : StringMap.key) *) (* (val1 val2 val3 : _) (ext : StringMap.t (Value av)), *) (* var1 <> var2 -> *) (* var2 <> var3 -> *) (* var1 <> var3 -> *) (* var1 ∉ ext -> *) (* var2 ∉ ext -> *) (* var3 ∉ ext -> *) (* [`var1 |> val1] *) (* ::[`var2 |> val2] *) (* ::[`var3 |> val3]::ext *) (* ≲ [[`var1 ->> val1 as _]] *) (* ::[[`var2 ->> val2 as _]] *) (* ::[[`var3 ->> val3 as _]]::Nil ∪ ext. *) (* Proof. *) (* intros. *) (* repeat apply Cons_PopExt; try decide_not_in. *) (* rewrite CompileBinopB_util by assumption. *) (* apply SameValues_Nil_always. *) (* Qed. *) (* Lemma CompileBinop_with_dealloc_USELESS: *) (* forall {av} name var1 var2 (val1 val2: W) env ext op p1 p2 p3, *) (* name ∉ ext -> *) (* var1 ∉ ext -> *) (* var2 ∉ ext -> *) (* var1 <> var2 -> *) (* var1 <> name -> *) (* var2 <> name -> *) (* {{ Nil }} *) (* p1 *) (* {{ [[`var1 ->> SCA _ val1 as _]]::Nil }} ∪ {{ ext }} // env -> *) (* {{ [[`var1 ->> SCA _ val1 as _]]::Nil }} *) (* p2 *) (* {{ [[`var1 ->> SCA _ val1 as _]]::[[`var2 ->> SCA _ val2 as _]]::Nil }} ∪ {{ ext }} // env -> *) (* {{ [[`var1 ->> SCA _ val1 as _]]::[[`var2 ->> SCA _ val2 as _]]::[[`name ->> (SCA av (eval_binop (inl op) val1 val2)) as _]]::Nil }} *) (* p3 *) (* {{ [[ret (SCA _ val1) as _]]::[[ret (SCA _ val2) as _]]::[[`name ->> (SCA av (eval_binop (inl op) val1 val2)) as _]]::Nil }} ∪ {{ ext }} // env -> *) (* {{ Nil }} *) (* (Seq p1 (Seq p2 (Seq (Assign name (Binop op (Var var1) (Var var2))) p3))) *) (* {{ [[`name ->> (SCA av (eval_binop (inl op) val1 val2)) as _]]::Nil }} ∪ {{ ext }} // env. *) (* Proof. *) (* Time SameValues_Facade_t; *) (* *) (* assert ([`name |> SCA av (IL.evalBinop op val1 val2)]::st'0 *) (* ≲ [[`var1 ->> SCA av val1 as _]] *) (* ::[[`var2 ->> SCA av val2 as _]] *) (* ::[[`name ->> SCA av (eval_binop (inl op) val1 val2) as _]]::Nil *) (* ∪ ext) by (repeat apply Cons_PopExt; *) (* try decide_not_in; *) (* simpl; *) (* SameValues_Facade_t); *) (* *) (* SameValues_Facade_t. *) (* Qed. *) (* Lemma CompileBinop_left: *) (* forall {av} name var1 var2 (val1 val2: W) env ext op p2, *) (* name ∉ ext -> *) (* StringMap.MapsTo var1 (SCA av val1) ext -> *) (* var2 ∉ ext -> *) (* var1 <> var2 -> *) (* var2 <> name -> *) (* {{ Nil }} *) (* p2 *) (* {{ [[`var2 ->> SCA _ val2 as _]]::Nil }} ∪ {{ ext }} // env -> *) (* {{ Nil }} *) (* (Seq p2 (Assign name (Binop op (Var var1) (Var var2)))) *) (* {{ [[`name ->> (SCA av (eval_binop (inl op) val1 val2)) as _]]::Nil }} ∪ {{ ext }} // env. *) (* Proof. *) (* Time SameValues_Facade_t. *) (* *) (* rewrite (add_redundant_cancel H0) in H19; SameValues_Facade_t. *) (* apply Cons_PopExt; [ SameValues_Facade_t | ]. *) (* *) (* cut (st' ≲ Nil ∪ ext); *) (* repeat match goal with *) (* | _ => reflexivity *) (* | _ => solve [simpl; SameValues_Facade_t] *) (* | _ => apply WeakEq_pop_SCA; [decide_not_in|] *) (* | [ H: WeakEq ?a ?st |- ?st ≲ _ ∪ _ ] => rewrite <- H *) (* | _ => progress simpl *) (* end. *) (* Qed. *) Lemma CompileBinopOrTest_left: forall {av} name var1 var2 (val1 val2: W) env ext op p2 (tenv: Telescope av), name ∉ ext -> NotInTelescope name tenv -> StringMap.MapsTo var1 (wrap val1) ext -> var2 ∉ ext -> var1 <> var2 -> var2 <> name -> {{ tenv }} p2 {{ [[`var2 ->> val2 as _]]::tenv }} ∪ {{ ext }} // env -> {{ tenv }} (Seq p2 (Assign name (WrapOpInExpr op (Var var1) (Var var2)))) {{ [[`name ->> (eval_binop op val1 val2) as _]]::tenv }} ∪ {{ ext }} // env. Proof. repeat hoare. destruct op; SameValues_Facade_t. Qed. (* Lemma CompileBinop_right: *) (* forall {av} name var1 var2 (val1 val2: W) env ext op p2, *) (* name ∉ ext -> *) (* var1 ∉ ext -> *) (* StringMap.MapsTo var2 (SCA av val2) ext -> *) (* var1 <> var2 -> *) (* var1 <> name -> *) (* {{ Nil }} *) (* p2 *) (* {{ [[`var1 ->> SCA _ val1 as _]]::Nil }} ∪ {{ ext }} // env -> *) (* {{ Nil }} *) (* (Seq p2 (Assign name (Binop op (Var var1) (Var var2)))) *) (* {{ [[`name ->> (SCA av (eval_binop (inl op) val1 val2)) as _]]::Nil }} ∪ {{ ext }} // env. *) (* Proof. *) (* Time SameValues_Facade_t. *) (* *) (* rewrite (add_redundant_cancel H1) in H19; SameValues_Facade_t. *) (* apply Cons_PopExt; [ SameValues_Facade_t | ]. *) (* *) (* cut (st' ≲ Nil ∪ ext); *) (* repeat match goal with *) (* | _ => reflexivity *) (* | _ => solve [simpl; SameValues_Facade_t] *) (* | _ => apply WeakEq_pop_SCA; [decide_not_in|] *) (* | [ H: WeakEq ?a ?st |- ?st ≲ _ ∪ _ ] => rewrite <- H *) (* | _ => progress simpl *) (* end. *) (* Qed. *) Lemma CompileBinopOrTest_right: forall {av} name var1 var2 (val1 val2: W) env ext op p2 (tenv: Telescope av), name ∉ ext -> NotInTelescope name tenv -> StringMap.MapsTo var2 (wrap val2) ext -> var1 ∉ ext -> var1 <> var2 -> var1 <> name -> {{ tenv }} p2 {{ [[`var1 ->> val1 as _]]::tenv }} ∪ {{ ext }} // env -> {{ tenv }} (Seq p2 (Assign name (WrapOpInExpr op (Var var1) (Var var2)))) {{ [[`name ->> (eval_binop op val1 val2) as _]]::tenv }} ∪ {{ ext }} // env. Proof. repeat hoare. destruct op; SameValues_Facade_t. Qed. (* Lemma CompileBinop_full: *) (* forall {av} name var1 var2 (val1 val2: W) env ext op p1 p2, *) (* name ∉ ext -> *) (* var1 ∉ ext -> *) (* var2 ∉ ext -> *) (* var1 <> var2 -> *) (* var1 <> name -> *) (* var2 <> name -> *) (* {{ Nil }} *) (* p1 *) (* {{ [[`var1 ->> SCA _ val1 as _]]::Nil }} ∪ {{ ext }} // env -> *) (* {{ [[`var1 ->> SCA _ val1 as _]]::Nil }} *) (* p2 *) (* {{ [[`var1 ->> SCA _ val1 as _]]::[[`var2 ->> SCA _ val2 as _]]::Nil }} ∪ {{ ext }} // env -> *) (* {{ Nil }} *) (* (Seq p1 (Seq p2 (Assign name (Binop op (Var var1) (Var var2))))) *) (* {{ [[`name ->> (SCA av (eval_binop (inl op) val1 val2)) as _]]::Nil }} ∪ {{ ext }} // env. *) (* Proof. *) (* Time SameValues_Facade_t. *) (* apply Cons_PopExt; [ SameValues_Facade_t | ]. *) (* *) (* cut (st'0 ≲ Nil ∪ ext); *) (* repeat match goal with *) (* | _ => reflexivity *) (* | _ => solve [simpl; SameValues_Facade_t] *) (* | _ => apply WeakEq_pop_SCA; [decide_not_in|] *) (* | [ H: WeakEq ?a ?st |- ?st ≲ _ ∪ _ ] => rewrite <- H *) (* | _ => progress simpl *) (* end. *) (* Qed. *) Opaque Word.natToWord. Lemma CompileBinopOrTest_full: forall {av} name var1 var2 (val1 val2: W) env ext op p1 p2 (tenv: Telescope av), name ∉ ext -> NotInTelescope name tenv -> var1 ∉ ext -> var2 ∉ ext -> var1 <> var2 -> var1 <> name -> var2 <> name -> {{ tenv }} p1 {{ [[`var1 ->> val1 as _]]::tenv }} ∪ {{ ext }} // env -> {{ [[`var1 ->> val1 as _]]::tenv }} p2 {{ [[`var1 ->> val1 as _]]::[[`var2 ->> val2 as _]]::tenv }} ∪ {{ ext }} // env -> {{ tenv }} (Seq p1 (Seq p2 (Assign name ((match op with inl o => Binop o | inr o => TestE o end) (Var var1) (Var var2))))) {{ [[`name ->> (eval_binop op val1 val2) as _]]::tenv }} ∪ {{ ext }} // env. Proof. repeat hoare. destruct op; SameValues_Facade_t. apply (SameValues_Pop_Both (H := FacadeWrapper_SCA)); eauto 2. apply SameValues_not_In_Telescope_not_in_Ext_remove; eauto 2. eapply SameValues_forget_Ext. 2:eapply SameValues_forget_Ext; try eassumption. eauto with SameValues_db. eauto with SameValues_db. apply (SameValues_Pop_Both (H := FacadeWrapper_SCA)); eauto 2. apply SameValues_not_In_Telescope_not_in_Ext_remove; eauto 2. eapply SameValues_forget_Ext. 2:eapply SameValues_forget_Ext; try eassumption. eauto with SameValues_db. eauto with SameValues_db. Qed. (* NOTE why doesn't eauto suffice here? *) Lemma CompileBinopOrTest_right_inPlace: forall {av} op name var2 (val1 val2: W) env ext (tenv: Telescope av), name ∉ ext -> NotInTelescope name tenv -> StringMap.MapsTo var2 (wrap val2) ext -> {{ [[`name ->> val1 as _]]::tenv }} (Assign name (WrapOpInExpr op (Var name) (Var var2))) {{ [[`name ->> (eval_binop op val1 val2) as _]]::tenv }} ∪ {{ ext }} // env. Proof. destruct op; SameValues_Facade_t. Qed. Lemma CompileBinopOrTest_right_inPlace_tel: forall {av} op vret varg (val1 val2: W) env ext (tenv: Telescope av), PreconditionSet tenv ext [[[vret; varg]]] -> {{ [[`vret ->> val1 as _]]::[[`varg ->> val2 as _]]::tenv }} Assign vret (WrapOpInExpr op (Var vret) (Var varg)) {{ [[`vret ->> (eval_binop op val1 val2) as _]]::tenv }} ∪ {{ ext }} // env. Proof. repeat hoare. move_to_front varg. apply CompileDeallocW_discretely; try compile_do_side_conditions. apply ProgOk_Chomp_Some; try compile_do_side_conditions. intros; apply CompileBinopOrTest_right_inPlace; try compile_do_side_conditions. Qed. Lemma CompileBinopOrTest_right_inPlace_tel_generalized: forall {av} op vret varg (val1 val2: W) env ext (tenv tenv': Telescope av) pCoda, PreconditionSet tenv ext [[[vret; varg]]] -> {{ [[`vret ->> (eval_binop op val1 val2) as _]]::[[`varg ->> val2 as _]]::tenv }} pCoda {{ [[`vret ->> (eval_binop op val1 val2) as _]]::tenv' }} ∪ {{ ext }} // env -> {{ [[`vret ->> val1 as _]]::[[`varg ->> val2 as _]]::tenv }} (Seq (Assign vret (WrapOpInExpr op (Var vret) (Var varg))) pCoda) {{ [[`vret ->> (eval_binop op val1 val2) as _]]::tenv' }} ∪ {{ ext }} // env. Proof. repeat hoare. move_to_front varg. apply ProgOk_Chomp_Some; try compile_do_side_conditions. intros; apply CompileBinopOrTest_right_inPlace; try compile_do_side_conditions. Qed.
lemma at_bot_le_at_infinity: "at_bot \<le> (at_infinity :: real filter)"
module Math %include C "eps.h" %link C "eps.o" machineEps : Double -> Double machineEps x = unsafePerformIO $ foreign FFI_C "machine_eps" (Double -> IO Double) x
(*<*) theory ex2_4 imports Main begin (*>*) text {* Boolean functions (in finitely many variables) can be represented by so-called {\it binary decision diagrams} (BDDs), which are given by the following data type: *} datatype bdd = Leaf bool | Branch bdd bdd primrec eval :: "(nat \<Rightarrow> bool) \<Rightarrow> nat \<Rightarrow> bdd \<Rightarrow> bool" where "eval f i (Leaf b) = b" |"eval f i (Branch x y) = (if (f i) then (eval f (Suc i) y) else ( eval f (Suc i ) x))" text {* that evaluates a BDD under a given variable assignment, beginning at a variable with a given index. *} text {* {\bf Exercise 2:} Define two functions *} primrec bdd_unop :: "(bool \<Rightarrow> bool) \<Rightarrow> bdd \<Rightarrow> bdd" where "bdd_unop f (Leaf x) = Leaf (f x)" | "bdd_unop f (Branch b1 b2) = Branch (bdd_unop f b1) (bdd_unop f b2)" primrec bdd_binop :: "(bool \<Rightarrow> bool \<Rightarrow> bool) \<Rightarrow> bdd \<Rightarrow> bdd \<Rightarrow> bdd" where "bdd_binop f (Leaf x) b = bdd_unop (f x) b" | "bdd_binop f (Branch b1 b2) b = (case b of Leaf x \<Rightarrow> Branch (bdd_binop f b1 (Leaf x)) (bdd_binop f b2 (Leaf x)) | Branch b1' b2' \<Rightarrow> Branch (bdd_binop f b1 b1') (bdd_binop f b2 b2'))" text {* for the application of unary and binary operators to BDDs, and prove their correctness. *} theorem bdd_unop_correct: "\<forall>i. eval e i (bdd_unop f b) = f (eval e i b)" apply (induct b) apply auto done theorem bdd_binop_correct: "\<forall>i b2. eval e i (bdd_binop f b1 b2) = f (eval e i b1) (eval e i b2)" apply (induct b1 ) apply (auto simp add :bdd_unop_correct) apply (case_tac b2) apply auto apply (case_tac b2) apply auto apply (case_tac b2) apply auto apply (case_tac b2) apply auto done text {* Now use @{term "bdd_unop"} and @{term "bdd_binop"} to define *} fun bdd_and :: "bdd \<Rightarrow> bdd \<Rightarrow> bdd" where "bdd_and x y = (bdd_binop (\<lambda> x y. x\<and>y) x y)" fun bdd_or :: "bdd \<Rightarrow> bdd \<Rightarrow> bdd"where "bdd_or x y = (bdd_binop (\<lambda> x y. x\<or>y) x y)" fun bdd_not :: "bdd \<Rightarrow> bdd"where "bdd_not x = (bdd_unop (\<lambda> x . (\<not>x)) x )" fun bdd_xor :: "bdd \<Rightarrow> bdd \<Rightarrow> bdd"where "bdd_xor x y = (bdd_or (bdd_and (bdd_not x) y) (bdd_and x (bdd_not y)))" text {* and show correctness. *} theorem bdd_and_correct: "eval e i (bdd_and b1 b2) = (eval e i b1 \<and> eval e i b2)" apply (auto simp add: bdd_binop_correct) done theorem bdd_or_correct: "eval e i (bdd_or b1 b2) = (eval e i b1 \<or> eval e i b2)" apply (auto simp add: bdd_binop_correct) done theorem bdd_not_correct: "eval e i (bdd_not b) = (\<not>(eval e i b))" apply (auto simp add: bdd_unop_correct) done text {* Finally, define a function *} text {* to create a BDD that evaluates to @{term "True"} if and only if the variable with the given index evaluates to @{term "True"}. Again prove a suitable correctness theorem. {\bf Hint:} If a lemma cannot be proven by induction because in the inductive step a different value is used for a (non-induction) variable than in the induction hypothesis, it may be necessary to strengthen the lemma by universal quantification over that variable (cf.\ Section 3.2 in the Tutorial on Isabelle/HOL). *} text_raw {* \begin{minipage}[t]{0.45\textwidth} *} text{* {\bf Example:} instead of *} lemma "P (b::bdd) x" apply (induct b) (*<*) oops (*>*) text_raw {* \end{minipage} *} text_raw {* \begin{minipage}[t]{0.45\textwidth} *} text {* Strengthening: *} lemma "\<forall>x. P (b::bdd) x" apply (induct b) (*<*) oops (*>*) text_raw {* \end{minipage} \\[0.5cm]*} primrec bdd_var :: "nat \<Rightarrow> bdd" where "bdd_var 0 = Branch (Leaf False) (Leaf True)" | "bdd_var (Suc i) = Branch (bdd_var i) (bdd_var i)" theorem bdd_var_correct: "\<forall>j. eval e j (bdd_var i) = e (i+j)" apply (induct i) apply auto done text {* {\bf Exercise 3:} Recall the following data type of propositional formulae (cf.\ the exercise on ``Representation of Propositional Formulae by Polynomials'') *} datatype form = T | Var nat | And form form | Xor form form text {* together with the evaluation function @{text "evalf"}: *} definition xor :: "bool \<Rightarrow> bool \<Rightarrow> bool" where "xor x y \<equiv> (x \<and> \<not> y) \<or> (\<not> x \<and> y)" primrec evalf :: "(nat \<Rightarrow> bool) \<Rightarrow> form \<Rightarrow> bool" where "evalf e T = True" | "evalf e (Var i) = e i" | "evalf e (And f1 f2) = (evalf e f1 \<and> evalf e f2)" | "evalf e (Xor f1 f2) = xor (evalf e f1) (evalf e f2)" text {* Define a function *} primrec mk_bdd :: "form \<Rightarrow> bdd" where "mk_bdd T = (Leaf True)" |"mk_bdd (Var i) = (bdd_var i)" |"mk_bdd (And f1 f2) = bdd_and (mk_bdd f1) (mk_bdd f2)" |"mk_bdd(Xor f1 f2) = bdd_xor (mk_bdd f1) (mk_bdd f2)" text {* that transforms a propositional formula of type @{typ "form"} into a BDD. Prove the correctness theorem *} theorem mk_bdd_correct: "eval e 0 (mk_bdd f) = evalf e f" apply (induct f) apply (auto simp add: bdd_var_correct bdd_and_correct bdd_or_correct bdd_not_correct xor_def) oops (*<*) end (*>*)
import category_theory.limits.shapes.pullbacks /-! Thanks to Markus Himmel for suggesting this question. -/ open category_theory open category_theory.limits /-! Let C be a category, X and Y be objects and f : X ⟶ Y be a morphism. Show that f is an epimorphism if and only if the diagram X --f--→ Y | | f 𝟙 | | ↓ ↓ Y --𝟙--→ Y is a pushout. -/ variables {C : Type*} [category C] def pushout_of_epi {X Y : C} (f : X ⟶ Y) [epi f] : is_colimit (pushout_cocone.mk (𝟙 Y) (𝟙 Y) rfl : pushout_cocone f f) := -- Hint: you can start a proof with `fapply pushout_cocone.is_colimit.mk` -- to save a little bit of work over just building a `is_colimit` structure directly. -- sorry begin fapply pushout_cocone.is_colimit.mk, { intro s, apply s.ι.app walking_span.left, }, { tidy, }, { tidy, apply (cancel_epi f).1, have fst := s.ι.naturality walking_span.hom.fst, simp at fst, rw fst, have snd := s.ι.naturality walking_span.hom.snd, simp at snd, rw snd, }, { tidy, } end -- sorry theorem epi_of_pushout {X Y : C} (f : X ⟶ Y) (is_colim : is_colimit (pushout_cocone.mk (𝟙 Y) (𝟙 Y) rfl : pushout_cocone f f)) : epi f := -- Hint: You can use `pushout_cocone.mk` to conveniently construct a cocone over a cospan. -- Hint: use `is_colim.desc` to construct the map from a colimit cocone to any other cocone. -- Hint: use `is_colim.fac` to show that this map gives a factorisation of the cocone maps through the colimit cocone. -- Hint: if `simp` won't correctly simplify `𝟙 X ≫ f`, try `dsimp, simp`. -- sorry { left_cancellation := λ Z g h hf, begin let a := pushout_cocone.mk _ _ hf, have hg : is_colim.desc a = g, { convert is_colim.fac a walking_span.left, simp, dsimp, simp, }, have hh : is_colim.desc a = h, { convert is_colim.fac a walking_span.right, simp, dsimp, simp, }, rw [←hg, ←hh], end } -- sorry /-! There are some further hints in `hints/category_theory/exercise6/` -/
function affineTransformationMatrix = get_affine_matrix(this) % Transforms geometry parameters into affine 4x4 matrix (T*R*Z*S) % with T = Translation, R = Rotation, Z = Zooming (Scaling with Resolution) % S = Shearing % i.e. performing operations in the order from right to left, in particular % rotation before translation % % Y = MrImageGeometry() % Y.get_affine_matrix(inputs) % % This is a method of class MrImageGeometry. % % IN % % OUT % % EXAMPLE % get_affine_matrix % % See also MrImageGeometry tapas_uniqc_spm_matrix % Author: Saskia Klein & Lars Kasper % Created: 2014-07-15 % Copyright (C) 2014 Institute for Biomedical Engineering % University of Zurich and ETH Zurich % % This file is part of the TAPAS UniQC Toolbox, which is released % under the terms of the GNU General Public Licence (GPL), version 3. % You can redistribute it and/or modify it under the terms of the GPL % (either version 3 or, at your option, any later version). % For further details, see the file COPYING or % <http://www.gnu.org/licenses/>. P(1:3) = this.offcenter_mm; P(4:6) = this.rotation_deg*pi/180; P(7:9) = this.resolution_mm; P(10:12) = this.shear; affineTransformationMatrix = tapas_uniqc_spm_matrix(P);
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleContexts #-} {-| Module : Grenade.Layers.Reshape Description : Multipurpose reshaping layer Copyright : (c) Huw Campbell, 2016-2017 License : BSD2 Stability : experimental -} module Grenade.Layers.Reshape ( Reshape (..) ) where import Data.Serialize import Data.Singletons.TypeLits import GHC.TypeLits import Control.DeepSeq (NFData (..)) import GHC.Generics (Generic) import Numeric.LinearAlgebra.Static import Numeric.LinearAlgebra.Data as LA ( flatten ) import Grenade.Core -- | Reshape Layer -- -- The Reshape layer can flatten any 2D or 3D image to 1D vector with the -- same number of activations, as well as cast up from 1D to a 2D or 3D -- shape. -- -- Can also be used to turn a 3D image with only one channel into a 2D image -- or vice versa. data Reshape = Reshape deriving (Show,Generic,NFData) instance UpdateLayer Reshape where type Gradient Reshape = () runUpdate _ _ _ = Reshape instance RandomLayer Reshape where createRandomWith _ _ = return Reshape instance (KnownNat a, KnownNat x, KnownNat y, a ~ (x * y)) => Layer Reshape ('D2 x y) ('D1 a) where type Tape Reshape ('D2 x y) ('D1 a) = () runForwards _ (S2D y) = ((), fromJust' . fromStorable . flatten . extract $ y) runBackwards _ _ (S1D y) = ((), fromJust' . fromStorable . extract $ y) instance (KnownNat a, KnownNat x, KnownNat y, KnownNat (x * z), KnownNat z, a ~ (x * y * z)) => Layer Reshape ('D3 x y z) ('D1 a) where type Tape Reshape ('D3 x y z) ('D1 a) = () runForwards _ (S3D y) = ((), fromJust' . fromStorable . flatten . extract $ y) runBackwards _ _ (S1D y) = ((), fromJust' . fromStorable . extract $ y) instance (KnownNat y, KnownNat x, KnownNat z, z ~ 1) => Layer Reshape ('D3 x y z) ('D2 x y) where type Tape Reshape ('D3 x y z) ('D2 x y) = () runForwards _ (S3D y) = ((), S2D y) runBackwards _ _ (S2D y) = ((), S3D y) instance (KnownNat y, KnownNat x, KnownNat z, z ~ 1) => Layer Reshape ('D2 x y) ('D3 x y z) where type Tape Reshape ('D2 x y) ('D3 x y z) = () runForwards _ (S2D y) = ((), S3D y) runBackwards _ _ (S3D y) = ((), S2D y) instance (KnownNat a, KnownNat x, KnownNat y, a ~ (x * y)) => Layer Reshape ('D1 a) ('D2 x y) where type Tape Reshape ('D1 a) ('D2 x y) = () runForwards _ (S1D y) = ((), fromJust' . fromStorable . extract $ y) runBackwards _ _ (S2D y) = ((), fromJust' . fromStorable . flatten . extract $ y) instance (KnownNat a, KnownNat x, KnownNat y, KnownNat (x * z), KnownNat z, a ~ (x * y * z)) => Layer Reshape ('D1 a) ('D3 x y z) where type Tape Reshape ('D1 a) ('D3 x y z) = () runForwards _ (S1D y) = ((), fromJust' . fromStorable . extract $ y) runBackwards _ _ (S3D y) = ((), fromJust' . fromStorable . flatten . extract $ y) instance Serialize Reshape where put _ = return () get = return Reshape fromJust' :: Maybe x -> x fromJust' (Just x) = x fromJust' Nothing = error $ "Reshape error: data shape couldn't be converted." -------------------- GNum instances -------------------- instance GNum Reshape where _ |* Reshape = Reshape _ |+ Reshape = Reshape gFromRational _ = Reshape
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE FlexibleContexts #-} module Statistics.BBVI.Gradient ( gradientScore , gradientReparam , DistInvariant(..) , Samples ) where import qualified Data.Vector as V import Statistics.BBVI.Propagator ( DistCell(..) , Gradient , Memory , dist ) import Statistics.BBVI.Class type Samples = V.Vector -- | invariant data for a variational distribution cell data DistInvariant a = DistInvariant { weight :: !Double -- ^ total occurences of z in log -- likelihood , prior :: !a -- ^ prior on latent variable , rhoF :: !(Gradient -> DistCell a -> (Memory, V.Vector Double)) -- ^ calculates change in memory, -- and stepsize } -- | internal helper function for building gradient propagators gradient :: (DistUtil a) => (DistCell a -> Double -> c -> Double -> V.Vector Double) -> DistInvariant a -> DistCell a -> (Double, V.Vector Double, Samples c) -> DistCell a3 gradient f (DistInvariant {..}) no (nFactors, like, samples) = U memory' (V.zipWith (*) rho' gr) where summed = V.foldl' (V.zipWith (+)) (V.replicate (nParams (dist no)) 0.0) $ V.zipWith (f no nFactors) samples like gr = fmap (/ (fromIntegral $ V.length samples)) summed (memory', rho') = rhoF gr no -- | helper function for transforming log joint to score gradient -- propagator gradientScore :: Dist a c => DistInvariant a -> DistCell a -- ^ current variational distribution -> (Double, V.Vector Double, Samples c) -- ^ n factors in log -- joint calculation, log joint calculation on each sample of \(z\), -- samples -> DistCell a -- ^ update to variational distribution gradientScore gp@(DistInvariant {..}) = gradient f gp where f (Node _time _memory d) nFactors s l = fmap (* (l + nFactors / weight * (logProb prior s - logProb d s))) (paramGradOfLogQ d s) f (U _ _) _ _ _ = error "called gradient update on update cell" -- | helper function for transforming log joint to reparameterization -- gradient propagator gradientReparam :: (Differentiable a Double) => DistInvariant a -> DistCell a -- ^ current variational distribution -> (Double, V.Vector Double, Samples Double) -- ^ n factors in log joint calculation, gradient of joint wrt \(z\) -- for each sample, un-transformed samples -> DistCell a -- ^ update to variational distribution gradientReparam gp@(DistInvariant {..}) = gradient f gp where f (Node _time _memory d) nFactors s g = fmap (* ( g + nFactors / weight * ( sampleGradOfLogQ prior (transform d s) - sampleGradOfLogQ d (transform d s) ) ) ) (gradTransform d s) f (U _ _) _ _ _ = err err :: a err = error "called gradient update on update cell"
# Vierachsroboter implizit # Initialisierung restart: kin_constraints_exist := true: # Für Speicherung ; with(StringTools): # Für Zeitausgabe with(LinearAlgebra): with(codegen): with(CodeGeneration): codegen_act := true: codegen_opt := 1: # Geringerer Optimierungsgrad. Sonst zu lange. codegen_debug := 0: # Zur Code-Generierung auch für Nicht-Inert-Ausdrücke ; read "../helper/proc_MatlabExport": read "../transformation/proc_rotx": read "../transformation/proc_roty": read "../transformation/proc_rotz": read "../transformation/proc_trotz": read "../transformation/proc_transl": read "../helper/proc_convert_s_t": read "../helper/proc_convert_t_s": read "../robot_codegen_constraints/proc_subs_kintmp_exp": read "../helper/proc_intersect_circle": with(RealDomain): # Schränkt alle Funktionen auf den reellen Bereich ein. Muss nach Definition von MatlabExport kommen. Sonst geht dieses nicht. ; read "../robot_codegen_definitions/robot_env_IC": read sprintf("../codeexport/%s/tmp/tree_floatb_definitions", robot_name_OL): # Ergebnisse der Kinematik laden read sprintf("../codeexport/%s/tmp/kinematics_floatb_%s_rotmat_maple.m", robot_name_OL, base_method_name); read "../robot_codegen_definitions/robot_env_IC": Trf := Trf: Trf_c := Trf_c: Trf ; # VGK Gelb 2-7-11-14-6 # Schleife (1-6)-(6-14) T_1_14 := combine( Matrix(Trf(1..4,1..4, 6)) . Matrix(Trf(1..4,1..4,14))): # Schleife (1-2)-(2-7)-(7-11) T_1_11:= combine( Matrix(Trf(1..4,1..4, 2)) . Matrix(Trf(1..4,1..4,7)) . Matrix(Trf(1..4,1..4,11))): h1t := T_1_14(1..3,4) - T_1_11(1..3,4); #tmp := Transpose( Matrix(T_1_14(1..3,1..3)) ) . Matrix(T_1_11(1..3,1..3)); nur anzeigen lassen für h1r ; #combine(tmp);# nur anzeigen lassen für h1r ; h1r := -(-qJ6(t)+qJ2(t)+qJ7(t)+phi711+qJ11(t))+Pi/2: # VGK PINK 2-3-12-15-9-8-2 # Schleife (2-3)-(3-12) T_2_12 := combine(Matrix(Trf(1..4,1..4, 3)) . Matrix(Trf(1..4,1..4,12))): # Schleife (2-8)-(8-9)-(9-15) T_2_15:= combine(Matrix(Trf(1..4,1..4, 8)) . Matrix(Trf(1..4,1..4,9)).Matrix(Trf(1..4,1..4, 15))): h2t := T_2_12(1..3,4) - T_2_15(1..3,4): tmp := Transpose( Matrix(T_2_12(1..3,1..3)) ) . Matrix(T_2_15(1..3,1..3)); # nur anzeigen lassen für h1r ; combine(tmp); # nur anzeigen lassen für h1r ; h2r:=(qJ3(t)+phi312+qJ12(t)-qJ8(t)-qJ9(t))+3*Pi/2: # VGK GRÜN 2-3-4-13-16-10-7-2 # Schleife (2-3)-(3-4)-(4-13) T_2_13 := combine( Matrix(Trf(1..4,1..4, 3)) . Matrix(Trf(1..4,1..4,4)) . Matrix(Trf(1..4,1..4,13))): # Schleife (2-7)-(7-10)-(10-16) T_2_16:= combine( Matrix(Trf(1..4,1..4, 7)) . Matrix(Trf(1..4,1..4,10)).Matrix(Trf(1..4,1..4,16)) ): h3t := T_2_13(1..3,4) - T_2_16(1..3,4): #tmp := Transpose( Matrix(T_2_13(1..3,1..3)) ) . Matrix(T_2_16(1..3,1..3)); nur anzeigen lassen für h2r ; #combine(tmp); nur anzeigen lassen für h3r ; h3r:=-(qJ3(t)+qJ4(t)+phi413+qJ13(t)-qJ7(t)+phi710-qJ10(t))+5*Pi/2: # Zusammenstellen aller Zwangsbedingungen implconstr_t := <h1t([1, 3],1);h2t([1, 2],1);h3t([1, 2],1); h1r; h2r; h3r>; # TODO: In h1r, h2r, h3r muss das richtige drinstehen. implconstr_s := convert_t_s(implconstr_t): # Exportiere Code für folgende Skripte kin_constraints_exist:=true: save implconstr_t, implconstr_s, kin_constraints_exist, sprintf("../codeexport/%s/tmp/kinematic_constraints_implicit_maple.m", robot_name): # Exportieren des vollständigen Ausdruckes if codegen_act then MatlabExport(implconstr_s, sprintf("../codeexport/%s/tmp/kinconstr_impl_matlab.m", robot_name), 2): end if: # Liste mit abhängigen konstanten Kinematikparametern erstellen (wichtig für Matlab-Funktionsgenerierung) read "../helper/proc_list_constant_expressions"; kc_symbols := Matrix(list_constant_expressions( implconstr_s )): save kc_symbols, sprintf("../codeexport/%s/tmp/kinematic_implicit_constraints_symbols_list_maple", robot_name): MatlabExport(Transpose(kc_symbols), sprintf("../codeexport/%s/tmp/kinematic_implicit_constraints_symbols_list_matlab.m", robot_name), 2):
module prep_density_pp_sub implicit none private public :: calc_density_pp contains subroutine calc_density_pp(lg,mg,system,info,pp,fg,poisson,rho) use salmon_global,only : nelem, kion, yn_ffte use communication, only: comm_summation use structures use sym_rho_sub, only: sym_rho implicit none type(s_rgrid) ,intent(in) :: lg,mg type(s_dft_system) ,intent(in) :: system type(s_parallel_info) ,intent(in) :: info type(s_pp_info) ,intent(in) :: pp type(s_reciprocal_grid),intent(in) :: fg type(s_poisson) :: poisson type(s_scalar) :: rho(:) ! integer :: ia,i,ik,ix,iy,iz,kx,ky,kz,iiy,iiz,nspin real(8) :: g(3),gd,s,g2sq,const,sb,x complex(8) :: tmp_exp complex(8) :: vtmp1(mg%is(1):mg%ie(1),mg%is(2):mg%ie(2),mg%is(3):mg%ie(3)) complex(8) :: vtmp2(mg%is(1):mg%ie(1),mg%is(2):mg%ie(2),mg%is(3):mg%ie(3)) complex(8),allocatable :: zrhoG(:,:,:,:) complex(8),parameter :: zero=(0.0d0,0.0d0) allocate( zrhoG(mg%is(1):mg%ie(1),mg%is(2):mg%ie(2),mg%is(3):mg%ie(3),nelem) ) zrhoG=zero const = 1.0d0/system%det_A !!$omp parallel !!$omp do private(ik,ix,iy,iz,g,g2sq,s,r1,dr,i,vloc_av) collapse(3) do ik=1,nelem do iz=mg%is(3),mg%ie(3) do iy=mg%is(2),mg%ie(2) do ix=mg%is(1),mg%ie(1) g(1) = fg%vec_G(1,ix,iy,iz) g(2) = fg%vec_G(2,ix,iy,iz) g(3) = fg%vec_G(3,ix,iy,iz) g2sq = sqrt(g(1)**2+g(2)**2+g(3)**2) if ( g2sq == 0.0d0 ) then zrhoG(ix,iy,iz,ik) = pp%zps(ik)*const cycle end if s=0.0d0 do i = 1, pp%mr(ik)-1 x = g2sq*pp%rad(i,ik) ! --- Spherical Bessel (l=0) --- if ( x < 1.d-1 ) then sb=-(1.d0/39916800.d0*x**10-1.d0/362880.d0*x**8 & +1.d0/5040.d0*x**6-1.d0/120.d0*x**4+1.d0/6.d0*x**2-1.d0) else sb=sin(x)/x end if ! --- s = s + pp%rho_pp_tbl(i,ik)*sb*(pp%rad(i+1,ik)-pp%rad(i,ik)) end do zrhoG(ix,iy,iz,ik) = s*const end do !ix end do !iy end do !iz end do !ik !!$omp end do !!$omp end parallel vtmp1=zero !!$omp parallel do collapse(2) private(ix,iy,iz,g,ia,ik,gd,tmp_exp) do iz=mg%is(3),mg%ie(3) do iy=mg%is(2),mg%ie(2) do ix=mg%is(1),mg%ie(1) g(1) = fg%vec_G(1,ix,iy,iz) g(2) = fg%vec_G(2,ix,iy,iz) g(3) = fg%vec_G(3,ix,iy,iz) do ia=info%ia_s,info%ia_e ik=kion(ia) gd = g(1)*system%Rion(1,ia) + g(2)*system%Rion(2,ia) + g(3)*system%Rion(3,ia) tmp_exp = cmplx( cos(gd), -sin(gd) ) vtmp1(ix,iy,iz) = vtmp1(ix,iy,iz) + zrhoG(ix,iy,iz,ik)*tmp_exp end do end do end do end do !!$omp end parallel do call comm_summation( vtmp1, vtmp2, size(vtmp2), info%icomm_ko ) if ( yn_ffte == 'n' ) then !$omp parallel workshare poisson%ff1x = zero poisson%ff1y = zero poisson%ff1z = zero !$omp end parallel workshare !$omp parallel do private(kz,ky,kx) do kz = mg%is(3),mg%ie(3) do ky = mg%is(2),mg%ie(2) do kx = mg%is(1),mg%ie(1) poisson%ff1z(kx,ky,kz) = vtmp2(kx,ky,kz) end do end do end do call comm_summation(poisson%ff1z,poisson%ff2z,mg%num(1)*mg%num(2)*lg%num(3),info%icomm_z) !$omp parallel do private(iz,ky,kx) do iz = mg%is(3),mg%ie(3) do ky = mg%is(2),mg%ie(2) do kx = mg%is(1),mg%ie(1) poisson%ff1y(kx,ky,iz) = sum(fg%egz(:,iz)*poisson%ff2z(kx,ky,:)) end do end do end do call comm_summation(poisson%ff1y,poisson%ff2y,mg%num(1)*lg%num(2)*mg%num(3),info%icomm_y) !$omp parallel do private(iz,iy,kx) do iz = mg%is(3),mg%ie(3) do iy = mg%is(2),mg%ie(2) do kx = mg%is(1),mg%ie(1) poisson%ff1x(kx,iy,iz)=sum(fg%egy(:,iy)*poisson%ff2y(kx,:,iz)) end do end do end do call comm_summation(poisson%ff1x,poisson%ff2x,lg%num(1)*mg%num(2)*mg%num(3),info%icomm_x) !$omp parallel do private(iz,iy,ix) collapse(2) do iz = mg%is(3),mg%ie(3) do iy = mg%is(2),mg%ie(2) do ix = mg%is(1),mg%ie(1) rho(1)%f(ix,iy,iz) = sum(fg%egx(:,ix)*poisson%ff2x(:,iy,iz)) end do end do end do else ! yn_ffte==.true. poisson%b_ffte=zero !$omp parallel do private(iz,iy,ix,iiz,iiy) collapse(2) do iz = 1,mg%num(3) do iy = 1,mg%num(2) do ix = mg%is(1),mg%ie(1) iiz=iz+mg%is(3)-1 iiy=iy+mg%is(2)-1 poisson%b_ffte(ix,iy,iz) = vtmp2(ix,iiy,iiz) end do end do end do call comm_summation(poisson%b_ffte,poisson%a_ffte,size(poisson%a_ffte),info%icomm_x) call PZFFT3DV_MOD(poisson%a_ffte,poisson%b_ffte,lg%num(1),lg%num(2),lg%num(3), & info%isize_y,info%isize_z,1, & info%icomm_y,info%icomm_z) !$omp parallel do private(iz,iy,iiz,iiy) collapse(2) do iz=1,mg%num(3) do iy=1,mg%num(2) iiz=iz+mg%is(3)-1 iiy=iy+mg%is(2)-1 rho(1)%f(mg%is(1):mg%ie(1),iiy,iiz) = poisson%b_ffte(mg%is(1):mg%ie(1),iy,iz)*system%ngrid end do end do end if call sym_rho( rho(1)%f(:,:,:) ) nspin = size(rho) if ( nspin == 2 ) then rho(1)%f(:,:,:) = 0.5d0*rho(1)%f(:,:,:) rho(2)%f(:,:,:) = rho(1)%f(:,:,:) end if !write(*,*) "sum(rho)=",sum(rho(1)%f)*system%hvol !rewind 200 !do ix = mg%is(1),mg%ie(1) ! write(200,*) (ix-1)*system%hgs(1), rho(1)%f(ix,1,1) !end do !stop return end subroutine calc_density_pp end module prep_density_pp_sub
using ImageContainers using Test using Base64, FileIO function writebuf(c::ImageContainer, mime::AbstractString) buf = IOBuffer() show(buf, MIME(mime), c) take!(buf) end @testset "ImageContainers.jl" begin data = rand(UInt8, 4) b64data = base64encode(data) @test ImageContainer{:a, Int}(3).content == 3 for (fmt, mime) in ImageContainers.plainmimes c = storeimage(fmt, data) @test c.content == data @test writebuf(c, mime) == data end for fmt in (:gif, :bmp) c = storeimage(fmt, data) @test c.content == data @test String(writebuf(c, "text/html")) == "<img src=\"data:image/$fmt;base64,$b64data\" />" end for fmt in (:mp4, :webm) for mime in ("text/html", "application/prs.juno.plotpane+html") c = storeimage(fmt, data) @test c.content == data @test String(writebuf(c, mime)) == "<video controls autoplay loop " * "src=\"data:video/$fmt;base64,$b64data\" />" end end begin # Julia image c = storeimage(:jlc, data) buf = IOBuffer() save(format"BMP", buf, data) out1 = writebuf(c, "image/bmp") # Juno @test out1 == take!(buf) out2 = writebuf(c, "text/html") # Jupyter @test String(out2) == "<img src=\"data:image/bmp;base64,$(base64encode(out1))\" />" end end
||| Copyright 2016 Google Inc. ||| ||| 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. ||| ||| This module defines a generalized algebraic data type, `MessageDescriptor`, ||| which is the strongly typed equivalent of the `Descriptor` protocol buffer. ||| Because types are first class values in Idris, we can construct a function ||| `interpMessage` that maps a `MessageDescriptor` to the *type* of structure ||| that the message describes. The ability to treat types as first class ||| values, and to create generic functions allows us to do in Idris code much ||| of what is done with generated code for protocol buffer implementations in ||| other languages. ||| ||| We try to follow the naming conventions for protocol buffer descriptors ||| found in [descriptor.proto](https://developers.google.com/protocol-buffers/docs/reference/cpp/google.protobuf.descriptor.pb) with the exception that we use the name ||| `MessageDescriptor` instead of `Descriptor`. module Protobuf.Core import public Data.Fin import public Data.Vect %default total %access public export ||| A `Label` is an annotation on a field that describes what kind of data type ||| the field represents. data Label : Type where ||| `Optional` fields are represented as a `Maybe` type. Optional : Label ||| `Required` fields are represented as a single value. Required : Label ||| `Repeated` fields are represented as a `List`. Repeated : Label ||| A descriptor for a single value in an enum. record EnumValueDescriptor where constructor MkEnumValueDescriptor name : String number : Int ||| A descriptor for an enum. ||| ||| k is the size of the enum ||| values is the possible values of the enum. Note that enum values have a ||| numeric value that is possibly different from the index of the value in ||| `values`, e.g. `values` could be `[MkEnumValueDescriptor "five" 5]`. record EnumDescriptor where constructor MkEnumDescriptor name : String values : Vect k EnumValueDescriptor mutual ||| A descriptor that describes the type of a protocol buffer message. This ||| describes the type of a protocol buffer message, which is a list of ||| fields. record MessageDescriptor where constructor MkMessageDescriptor name : String fields : Vect k FieldDescriptor ||| A descriptor that describes the type of a protocol buffer field. E.g. ||| `MkFieldDescriptor Optional PBDouble "temperature"` describes an ||| optional field whose name is "temperature" of type PBDouble, which is ||| interpreted Idris as a `Maybe double`. ||| ||| label determines whether the field is optional, required or repeated. ||| ty is the type of a single value in the field. ||| name is the field's name, used in the text format. record FieldDescriptor where constructor MkFieldDescriptor label : Label ty : FieldValueDescriptor name : String number : Int ||| This does not correspond to anything in `descriptor.proto`, but is a ||| necessary definition here. It describes the type of the value of a ||| protocol buffer required field, i.e. a single value. This may be a ||| message, an enum or a primitive value. data FieldValueDescriptor : Type where PBDouble : FieldValueDescriptor PBFloat : FieldValueDescriptor PBInt32 : FieldValueDescriptor PBInt64 : FieldValueDescriptor PBUInt32 : FieldValueDescriptor PBUInt64 : FieldValueDescriptor PBSInt32 : FieldValueDescriptor PBSInt64 : FieldValueDescriptor PBFixed32 : FieldValueDescriptor PBFixed64 : FieldValueDescriptor PBSFixed32 : FieldValueDescriptor PBSFixed64 : FieldValueDescriptor PBBool : FieldValueDescriptor PBString : FieldValueDescriptor PBBytes : FieldValueDescriptor ||| A value which is itself a message. PBMessage : MessageDescriptor -> FieldValueDescriptor PBEnum : EnumDescriptor -> FieldValueDescriptor interpEnum : EnumDescriptor -> Type interpEnum (MkEnumDescriptor {k=k} _ _) = Fin k -- NOTE: we implement Interp* as inductive types rather than as functions, -- because these allow us to implement type classes such as Eq and Show. -- -- E.g. if we had a function interpMessage : MessageDescriptor -> Type -- it would not be possible to define a typeclass implementation -- -- implementation Eq (interpMessage d) where ... -- -- but it is possible to define -- -- implementation Eq (InterpMessage d) where ... -- -- Type classes also operate differently with respect to unfolding, though -- that didn't pose any problems while working with functions. mutual ||| Takes a message descriptor and returns the type that that message ||| descriptor describes. This is implemented with the algebraic data type ||| `InterpMessage`. data InterpMessage : MessageDescriptor -> Type where MkMessage : InterpFields fields -> InterpMessage (MkMessageDescriptor name fields) ||| `InterpMessage` the algebraic data type used to implement `interpMessage`. ||| `InterpMessage fs` is a heterogeneous vector where where the type of each ||| element is `interpField` applied to the corresponding element in `fs`. ||| While it is possible to construct this type using `Data.HVect`, I haven't ||| found a way to satisfy the totality checker when using this approach. data InterpFields : (Vect k FieldDescriptor) -> Type where Nil : InterpFields Nil (::) : (interpField f) -> (InterpFields m) -> InterpFields (f :: m) ||| Takes a field descriptor and returns the type that that field descriptor ||| describes. This is a single value, a `Maybe` or a `List` depending on ||| the field's label. interpField : FieldDescriptor -> Type interpField (MkFieldDescriptor Optional value _ _) = Maybe (interpFieldValue value) interpField (MkFieldDescriptor Required value _ _) = interpFieldValue value interpField (MkFieldDescriptor Repeated value _ _) = List (interpFieldValue value) ||| Interprets a single field value, i.e. the value described by a required ||| field. For primitive types this is a corresponding Idris primitive type. ||| For messages this is `interpMessage` for that message. For enum's it is ||| `Fin k` where `k` is the number of values in the enum. interpFieldValue : FieldValueDescriptor -> Type interpFieldValue PBDouble = Double interpFieldValue PBFloat = Double interpFieldValue PBInt32 = Integer interpFieldValue PBInt64 = Integer interpFieldValue PBUInt32 = Integer interpFieldValue PBUInt64 = Integer interpFieldValue PBSInt32 = Integer interpFieldValue PBSInt64 = Integer interpFieldValue PBFixed32 = Integer interpFieldValue PBFixed64 = Integer interpFieldValue PBSFixed32 = Integer interpFieldValue PBSFixed64 = Integer interpFieldValue PBBool = Bool interpFieldValue PBString = String interpFieldValue PBBytes = String interpFieldValue (PBMessage m) = InterpMessage m interpFieldValue (PBEnum e) = interpEnum e
% This subroutine selcts the Ni closest earthquakes % around a userdefined point % report_this_filefun(mfilename('fullpath')); new = a; ni = input('Please input number of events ni:') %ni = 100 axes(h6) [xa0,ya0] = ginput(1); l = sqrt(((a.Longitude-xa0)*cos(pi/180*ya0)*111).^2 + ((a.Latitude-ya0)*111).^2) ; [s,is] = sort(l); new = a(is(:,1),:) ; plos1 = plot(new(1:ni,1),new(1:ni,2),'xw','EraseMode','back'); %plos1 = plot(new(1:ni,1),new(1:ni,2),'xw') figure_w_normalized_uicontrolunits(2) clf h3 = gcf; newt = new(1:ni,:); [st,ist] = sort(newt); newt2 = newt(ist(:,3),:); newt2(:,9) = newt2.Date + newt2.Date.Month/12 + newt2.Date.Day/365; [st,ist] = sort(newt2); newt3 = newt2(ist(:,9),:); %figure_w_normalized_uicontrolunits(3) %clf %plode = plot(newt3(:,9),-newt3(:,8),'o') %axis([81 92.6 -20 0]) %grid %xlabel('Time') %ylabel('Depth in km') timeplot
import numpy as np import re import tokenize import awkward0 import awkward as ak import logging from io import StringIO from typing import List logger = logging.getLogger(__name__) __all__ = ["get_branches", "evaluate"] constants = {"nan": np.nan, "inf": np.inf, "pi": np.pi, "e": np.e, } def get_branches(cut: str, valid: List[str]) -> List[str]: """ Get branches relevant to the cut. """ branches = [] string = StringIO(cut).readline tokens = tokenize.generate_tokens(string) current_branch = [] for toknum, tokval, _, _, _ in tokens: if toknum == tokenize.NAME: if ".".join(current_branch + [tokval]) in valid: current_branch.append(tokval) continue if tokval == ".": continue if current_branch: branches.append(".".join(current_branch)) current_branch = [] return branches def deconstruct_jaggedness(array, counts): if not isinstance(array, (awkward0.array.base.AwkwardArrayWithContent, ak.highlevel.Array)): return array, counts if isinstance(array, ak.highlevel.Array): counts.insert(0, array.layout.compact_offsets64) array = ak.flatten(array) return deconstruct_jaggedness(array.layout.content, counts) else: array = array.compact() counts.insert(0, array.counts) return deconstruct_jaggedness(array.content, counts) def reconstruct_jaggedness(array, counts): # array = ak.unflatten(array, lengths, axis=1) for count in counts: array = awkward0.JaggedArray.fromcounts(count, array) return array class TreeToDictAdaptor(): """ Make an uproot tree look like a dict for numexpr """ def __init__(self, tree, alias_dict, needed_variables): self.tree = tree self.aliases = alias_dict self.vars, self.counts = self.broadcast_variables(needed_variables) def broadcast_variables(self, variables): arrays = {} most_jagged = (-1, None) for var in variables: if var in constants: continue array = self.get_raw(var) contents, counts = deconstruct_jaggedness(array, counts=[]) arrays[var] = (contents, counts, array) if len(counts) > most_jagged[0]: most_jagged = (len(counts), var) most_jagged = most_jagged[1] broadcast_to = arrays[most_jagged][1] broadcast_vars = {most_jagged: arrays[most_jagged]} for var, (contents, counts, raw) in arrays.items(): if var == most_jagged: continue # Check broadcastable for left, right in zip(broadcast_to, counts): if not np.array_equal(left, right): raise ValueError("Unable to broadcast all values") for copies in broadcast_to[len(counts):]: contents = np.repeat(contents, copies) broadcast_vars[var] = (contents, broadcast_to, raw) return broadcast_vars, broadcast_to def __getitem__(self, item): if item in constants: return constants[item] result = self.vars[item][0] return result def get_raw(self, item): if item in constants: return constants[item] full_item = self.aliases.get(item, item) array = self.tree.array(full_item) return array def __contains__(self, item): return item in self.vars def __iter__(self): for i in self.vars: yield i def apply_jaggedness(self, array): if self.counts is None: return array result = reconstruct_jaggedness(array, self.counts) return result attribute_re = re.compile(r"([a-zA-Z]\w*)\s*(\.\s*(\w+))+") def preprocess_expression(expression): alias_dict = {} replace_dict = {} for match in attribute_re.finditer(expression): original = match.group(0) alias = original.replace('.', '__DOT__') alias_dict[alias] = original replace_dict[original] = alias clean_expr = attribute_re.sub(lambda x: replace_dict[x.group(0)], expression) return clean_expr, alias_dict def evaluate(tree, expression): cleaned_expression, _ = preprocess_expression(expression) return tree.evaluate(cleaned_expression, global_dict=constants)
{-# OPTIONS --without-K --show-implicit #-} module WithoutK10 where data Unit : Set where unit : Unit data D {A : Set} (f : Unit → A) : A → Set where d : ∀ {x} → D f x Foo : ∀ {A} {x : A} → D (let f = λ { unit → x } in f) x → Set₁ Foo d = Set
using VisualCircuits, Compose width, height = 7.5, 4 nand1 = Gate(5, 1, :NAND) nand2 = Gate(5, 3, :NAND) nand3 = Gate(3, nand1[:in1][2], :NAND, [:in1, :in2, :in3]) nand4 = Gate(3, nand2[:in2][2], :NAND, [:in1, :in2, :in3]) circuit = begin compose( # Range of coordinate system context(units=UnitBox(0, 0, width, height)), # Gates render(nand1), render(nand2), render(nand3), render(nand4), # Connect to edges (point, x_value) connect(nand1[:out], width-1), connect(nand2[:out], width-1), connect(nand3[:in1], 1), connect(nand4[:in3], 1), connect((1.5, 2), 1), # Connect Gates connect(nand1[:in1], nand3[:out]), connect(nand2[:in2], nand4[:out]), # crossing lines connect( nand1[:in2], (4, nand1[:in2][2]), (4, 1.75), (6, 2.25), (6, nand2[:out][2]), nand2[:out] ), connect( nand2[:in1], (4, nand2[:in1][2]), (4, 2.25), (6, 1.75), (6, nand1[:out][2]), nand1[:out] ), # Clock line connect( nand3[:in2], (1.5, nand3[:in2][2]), (1.5, nand4[:in2][2]), nand4[:in2] ), # looping lines connect(nand3[:in3], (2, nand3[:in3][2]), (2, 1.5), (4, 1.5)), connect(nand4[:in1], (2, nand4[:in1][2]), (2, 2.5), (4, 2.5)), # connections/dots dots( (6, nand1[:out][2]), (6, nand2[:out][2]), (1.5, 2), (4, 1.5), (4, 2.5) ), # render text render( (0.5, nand3[:in1][2], "J"), (0.5, nand4[:in3][2], "K"), (0.5, 2, "C"), (width-0.5, nand1[:out][2], "Q"), (width-0.5, nand2[:out][2], "~Q") ), # compose options stroke("black"), linewidth(2mm) ) end # draw(PDF("JK_FlipFlop.pdf", autosize(width, height)...), circuit) draw(SVG("JK_FlipFlop.svg", autosize(width, height)...), circuit)
library(shiny) about.thisapp <- HTML(" <p> This <a href='http://www.rstudio.com/products/shiny/'>shiny</a> app uses <a href='https://github.com/wrathematics/hackR'>the hackR package</a>, where you can also find the <a href='https://github.com/wrathematics/hackR/tree/master/inst/hackR'>source</a> for this shiny app. </p> <p> This app is inspired by crappy movies like Hackers, where people call themselves things like ne0BuRn. With this app, you're one step closer to hacking the gibson. </p> ") type_print <- c("lower", "upper", "unchanged", "random", "alternating") shinyUI( fluidPage( titlePanel("2 l33t 4 u"), fluidRow( sidebarPanel( tags$textarea(id="inputbox", rows=2, cols=40, "Put the text in here that you want to l33tify."), br(), sliderInput("leetness", "Leetness", 0, 1, 0.4, step=0.05, ticks=TRUE), selectizeInput("case.type", "Casing Options", type_print, "alternating"), radioButtons("sub.type", "Substitution Type", c("simple", "complex"), "simple", inline=TRUE), checkboxInput("include.unicode", "Include Unicode?", value=FALSE), actionButton("button_leetify", "Leetify"), actionButton("button_random", "Random") ), mainPanel( tabsetPanel( tabPanel("Leet Handle", htmlOutput("text")), tabPanel("About This App", helpText(about.thisapp)) ) ) )) )
{-# LANGUAGE BangPatterns #-} module Lib where import Graphics.UI.GLUT import Control.Monad import Data.Int import Data.Complex import System.Exit ( exitWith, ExitCode(ExitSuccess) ) import qualified Data.Map as Map start = 5 iterations = 7 maxIterations = 30 x // y = fromIntegral x / fromIntegral y -- Divides [a] into [[a], [a], ...] with each sublist of length n, -- except the last sublist which has length <= n. chunkify n [] = [] chunkify n xs = let (xs', rest) = splitAt n xs in xs' : chunkify n rest -- Converts a coordinate in screen space to a vertex. pix2vert (Size w h) (x, y) = Vertex2 ((3 // w * fromIntegral x) - 2.0) ((2 // h * fromIntegral y) - 1.0) -- List of all of the vertices that represent screen pixels. vertices :: IO [Vertex2 GLfloat] vertices = get windowSize >>= (\x -> return $ vertices' x) vertices' (Size w h) = [pix2vert (Size w h) (x, y) | x <- [0..w-1], y <- [0..h-1]] -- Gets the color for a number of iterations. color3 r g b = Color3 r g b getcolor :: Int -> Color3 Float getcolor numberOfIterations | inMandelbrotSet = color3 0 0 0 | otherwise = color3 (escapeNumber*0.5) (escapeNumber * 0.5) escapeNumber where escapeNumber = numberOfIterations // iterations inMandelbrotSet = numberOfIterations == iterations -- Returns the number of iterations <= the maximum iterations of the -- Mandelbrot set at the given vertex. mandel numberOfIterations (Vertex2 r i) = length . takeWhile (\z -> magnitude z <= 2) . take numberOfIterations $ iterate (\z -> z^2 + (r :+ i)) 0 mandel' numberOfIterations (Vertex2 r i) = length . takeWhile (\z -> magnitude z <= 2) . take numberOfIterations $ iterate (\z -> z^2 + (r :+ i)) 0 mandelMap :: (RealFloat a1, Fractional a2) => Vertex2 a1 -> Map.Map Int (Color3 a2) mandelMap (Vertex2 r i) = Map.fromList iterList where mandelNumbers = iterate (\z -> z^2 + (r :+ i)) 0 escapeVelocity numIter = length . takeWhile (\z -> magnitude z <= 2) . take numIter $ mandelNumbers --iterList = makeMap (\iter -> getColor (escapeVelocity iter) iter) [1..maxIterations] iterList = makeMap (\iter -> getColor (escapeVelocity iter) iter) [start..iterations] getColor escapedAt totalNumIters | inMandelbrotSet = color3 0 0 0 | otherwise = color3 (escapeNumber*0.5) (escapeNumber * 0.5) escapeNumber where escapeNumber = escapedAt // totalNumIters inMandelbrotSet = escapedAt == totalNumIters colorPoint :: RealFloat a => Int -> Vertex2 a -> Color3 Float colorPoint numIterations = getcolor . (mandel numIterations) -- plots one point. -- drawVert v = do -- color . getcolor $ mandel v -- vertex v drawVert' (point, color_) = do color color_ vertex point -- draws all the vertices in slices (to update the display while drawing). -- display' chunks = do -- mapM_ render chunks -- displayCallback $= display -- where render points = do -- renderPrimitive Points (mapM_ drawVert points) -- flush getColor :: (Map.Map (Vertex2 GLfloat) (Map.Map Int (Color3 Double))) -> Int -> Vertex2 GLfloat -> Color3 Double getColor pointMap numIter vertex = case Map.lookup vertex pointMap of Just colorMap -> case Map.lookup numIter colorMap of Just r -> r Nothing -> Color3 0 0 0 Nothing -> Color3 0 0 0 drawAll :: Int -> Map.Map (Vertex2 GLfloat) (Map.Map Int (Color3 Double)) -> [Vertex2 GLfloat] -> IO() drawAll count pointMap points = do render displayCallback $= (display (count + 1) pointMap) where render = do renderPrimitive Points (mapM_ drawVert' toDraw) flush toDraw :: [(Vertex2 GLfloat, Color3 Double)] toDraw = makeMap (getColor pointMap count) points -- draws the whole fractal display :: Int -> Map.Map (Vertex2 GLfloat) (Map.Map Int (Color3 Double)) -> IO () display 200 _ = do exitWith ExitSuccess display num pointMap = do clear [ ColorBuffer ] -- displayCallback $= (vertices >>= display' . chunkify 256) displayCallback $= (vertices >>= (drawAll num pointMap)) get currentWindow >>= postRedisplay keyboard :: KeyboardMouseCallback keyboard (Char keyPressed) Down _ _ = case keyPressed of ' ' -> postRedisplay Nothing '\27' -> exitWith ExitSuccess _ -> return () keyboard _ _ _ _ = return () mandelMain = do getArgsAndInitialize initialDisplayMode $= [ SingleBuffered, RGBMode] initialWindowSize $= Size 1200 1024 initialWindowPosition $= Position 100 100 createWindow "Mandelbrot" --fullScreen -- renderString Roman "Test" clearColor $= Color4 0 0 0 0 matrixMode $= Projection loadIdentity ortho (-2) 1 (-1) 1 (-1) 1 keyboardMouseCallback $= Just keyboard points <- vertices putStrLn "PreLoading.." let !preload = Map.fromList $ makeMap mandelMap points putStrLn "Loaded" displayCallback $= (display start preload) mainLoop makeMap :: (a -> b) -> [a] -> [(a, b)] makeMap fn lst = zip lst (map fn lst)
Formal statement is: lemma eucl_rel_poly: "eucl_rel_poly x y (x div y, x mod y)" Informal statement is: The Euclidean algorithm can be used to compute the quotient and remainder of a division.
module Examples where open import Data.List hiding (reverse) open import Data.List.All open import Data.Nat open import Typing open import Syntax ex1 : Expr [] TUnit ex1 = letbind [] (new [] (delay send!)) (letpair (left []) (here []) (letbind (rght (left [])) (fork (wait (here []))) (close (there UUnit (here []))))) ex1dual : Expr [] TUnit ex1dual = letbind [] (new [] (delay send!)) (letpair (left []) (here []) (letbind (left (rght [])) (fork (close (here []))) (wait (there UUnit (here []))))) -- sending and receiving ex2 : Expr [] TUnit ex2 = letbind [] (new [] (delay (Typing.send TInt (delay send!)))) (letpair (left []) (here []) (letbind (left (rght [])) (fork (letbind (rght []) (nat [] 42) (letbind (left (left [])) (Expr.send (rght (left [])) (here []) (here [])) (letbind (left []) (close (here [])) (var (here [])))))) (letbind (rght (left [])) (Expr.recv (here [])) (letpair (left (rght [])) (here []) (letbind (left (left (rght []))) (wait (here (UInt ∷ []))) (var (here (UUnit ∷ [])))))))) -- higher order sending and receiving ex3 : Expr [] TUnit ex3 = letbind [] (new [] (delay (Typing.send (TChan send!) (delay send!)))) (letbind (rght []) (new [] (delay send!)) (letpair (left (rght [])) (here []) (letpair (rght (rght (left []))) (here []) (letbind (left (rght (left (left [])))) (fork (letbind (left (left (rght []))) (Expr.send (left (rght [])) (here []) (here [])) (letbind (left (rght [])) (close (here [])) (wait (there UUnit (here [])))))) (letbind (left (left [])) (Expr.recv (there UUnit (here []))) (letpair (left []) (here []) (letbind (left (rght [])) (wait (here [])) (letbind (left (left [])) (close (there UUnit (here []))) (var (here [])))))))))) -- branching ex4 : Expr [] TUnit ex4 = letbind [] (new [] (delay (sintern (delay send!) (delay send?)))) (letpair (left []) (here []) (letbind (left (rght [])) (fork (letbind (left []) (select Left (here [])) (close (here [])))) (branch (left (left [])) (there UUnit (here [])) (wait (here [])) (close (here []))))) -- simple lambda: (λx.x)() ex5 : Expr [] TUnit ex5 = letbind [] (llambda [] [] (var (here []))) (letbind (rght []) (unit []) (app (rght (left [])) (here []) (here []))) -- lambda app: (λfx.fx) (λx.x)() ex6 : Expr [] TUnit ex6 = letbind [] (llambda [] [] (llambda (left []) [] (app (rght (left [])) (here []) (here [])))) (letbind (rght []) (llambda [] [] (var (here []))) (letbind (rght (rght [])) (unit []) (letbind (rght (left (left []))) (app (rght (left [])) (here []) (here [])) (app (left (rght [])) (here []) (here [])))))
module LongestNonRepeatingSubstring Set : Type -> Type Set = List contains : Eq a => a -> Set a -> Bool contains x [] = False contains x (y :: ys) = (x == y) || contains x ys add : a -> Set a -> Set a add x xs = x :: xs emptySet : {0 a : Type} -> Set a emptySet = [] longestHelp : {0 a : Type} -> Eq a => Set a -> Int -> Int -> List a -> Int longestHelp seen count soFar [] = max soFar count longestHelp seen count soFar (x :: xs) = if contains x seen then longestHelp (emptySet {a}) 0 (max soFar count) (x :: xs) else longestHelp (add x seen) (count + 1) soFar xs longest : Eq a => List a -> Int longest = longestHelp (emptySet {a}) 0 0 test1 : longest (unpack "abcabcbb") = 3 test1 = Refl test2 : longest (unpack "bbbbb") = 1 test2 = Refl test3 : longest (unpack "pwwkew") = 3 test3 = Refl test4 : longest (unpack "") = 0 test4 = Refl
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: S.P. van der Linden """ from hall_interface import HallInterface import socket import json from time import sleep import numpy as np import sys def send_altaz(sock: socket, alt: float, az: float): """ Send an altaz pair to the connected server through the socket""" ob = {'alt': round(alt), 'az': round(az)} sock.send(bytes(json.dumps(ob), 'utf-8')) def convert_azimuth(az_in: float): """Convert azimuth sensor readout to actual calibrated azimuth Args: az_in (float): Input azimuth, 0<=az_in<360 Returns: float: calibrated azimuth, 0<=az<360 """ # TODO: calibrate this return az_in def convert_altitude(alt_in: float): """Convert altitude sensor readout to actual calibrated altitude Args: az_in (float): Input altitude, 0<=alt_in<360 Returns: float: calibrated altitude, 0<=alt<=90 """ # TODO: calibrate this return np.interp(alt_in, np.array([131.5, 216.5]), np.array([0., 90.])) def main(): sensor_azi = HallInterface(0, 0) sensor_alt = HallInterface(0, 1) sensor_azi.enable() sensor_alt.enable() sleep(30) # Wait for screen to start # Create the client socket s = None # Connect to the server via port 7272, with 50 tries counter = 1 while True: if s: s.close() s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: print("Trying to connect") s.connect(('192.168.178.68', 7272)) except (OSError, ConnectionRefusedError) as e: # We got an error, print out what, then sleep and try again print("Connection failed (attempt {}): {}".format(counter, e)) sleep(5) counter = counter + 1 continue with s: print('Connected, starting normal operation.') while True: try: azimuth = convert_azimuth(sensor_azi.get_angle()) altitude = convert_altitude(sensor_alt.get_angle()) #print(int(altitude), int(azimuth)) send_altaz(s, altitude, azimuth) sleep(0.1) except KeyboardInterrupt: print('Quitting...') sys.exit(1) sensor_azi.finish() sensor_alt.finish() if __name__ == "__main__": main()
{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-} {-# OPTIONS_GHC -fno-warn-missing-signatures #-} {-# OPTIONS_GHC -fno-warn-incomplete-patterns #-} {-# LANGUAGE CPP #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeOperators #-} module Test.Grenade.Layers.Mul where import System.Random.MWC import Data.Proxy import GHC.TypeLits import Grenade.Core import Grenade.Layers.Mul import qualified Numeric.LinearAlgebra as LA import Numeric.LinearAlgebra.Static (L, R) import qualified Numeric.LinearAlgebra.Static as H import Hedgehog import qualified Hedgehog.Range as Range import Test.Hedgehog.Compat import Test.Hedgehog.Hmatrix import Data.Either import Data.Serialize prop_mul_scalar_one_does_nothing = property $ do height :: Int <- forAll $ choose 2 100 width :: Int <- forAll $ choose 2 100 channels :: Int <- forAll $ choose 2 100 case (someNatVal (fromIntegral height), someNatVal (fromIntegral width), someNatVal (fromIntegral channels)) of (Just (SomeNat (Proxy :: Proxy h)), Just (SomeNat (Proxy :: Proxy w)), Just (SomeNat (Proxy :: Proxy c))) -> do input :: S ('D3 h w c) <- forAll genOfShape let layer = initMul :: Mul 1 1 1 S3D out = snd $ runForwards layer input :: S ('D3 h w c) S3D inp' = input :: S ('D3 h w c) H.extract inp' === H.extract out prop_mul_random_scalar_as_expected = property $ do height :: Int <- forAll $ choose 2 100 width :: Int <- forAll $ choose 2 100 channels :: Int <- forAll $ choose 2 100 scalar :: R 1 <- forAll randomVector let scale = H.extract scalar LA.! 0 case (someNatVal (fromIntegral height), someNatVal (fromIntegral width), someNatVal (fromIntegral channels)) of (Just (SomeNat (Proxy :: Proxy h)), Just (SomeNat (Proxy :: Proxy w)), Just (SomeNat (Proxy :: Proxy c))) -> do input :: S ('D3 h w c) <- forAll genOfShape let layer = Mul scalar :: Mul 1 1 1 S3D out = snd $ runForwards layer input :: S ('D3 h w c) inp' = (\(S3D x) -> H.dmmap (* scale) x) input :: L (h * c) w H.extract inp' === H.extract out prop_mul_has_show = withTests 1 $ property $ do gen <- evalIO create mul :: Mul 1 1 1 <- evalIO $ createRandomWith UniformInit gen show mul `seq` success prop_mul_can_update = withTests 1 $ property $ do gen <- evalIO create mul :: Mul 1 1 1 <- evalIO $ createRandomWith UniformInit gen runUpdate defSGD mul () `seq` success runUpdate defAdam mul () `seq` success prop_mul_can_be_used_with_batch = withTests 1 $ property $ do reduceGradient @(Mul 1 1 1) [()] `seq` success prop_mul_can_be_serialized = withTests 1 $ property $ do s <- forAll $ genRealNum $ Range.constant 1 10 let mul :: Mul 1 1 1 = Mul (H.fromList [s]) bs = encode mul dec = decode bs :: Either String (Mul 1 1 1) assert $ isRight dec let Right mul' = dec (Mul scalarMat) = mul (Mul scalarMat') = mul' (H.extract scalarMat) === (H.extract scalarMat') prop_mul_fails_serialize_with_incorrect_size = withTests 1 $ property $ do s <- forAll $ genRealNum $ Range.constant 1 10 let mul :: Mul 1 1 1 = Mul (H.fromList [s]) let bs = encode mul let dec = decode bs :: Either String (Mul 1 2 1) assert $ isLeft dec tests :: IO Bool tests = checkParallel $$(discover)
using DataFrames, CSV, Statistics, StatsBase df = CSV.read("./preprocessing/input/land-sustainable.csv") vars = CSV.read("./preprocessing/input/land-sustainable-attributes.csv") # remove last row df = df[.!ismissing.(df.Scenario),:] # remove region col select!(df, Not(:Region)) df = stack(df, 5:size(df)[2]) rename!(df, [:year, :value, :model, :scenario, :variable, :unit]) df[occursin.("N2O", df.variable), :value] /= 1000 df[occursin.("CO2", df.variable), :value] /= 1000 df[occursin.("Sequestration", df.variable), :value] /= 1000 df[occursin.("N2O", df.variable), :unit] = "Mt N₂O/yr" df[occursin.("CO2", df.variable), :unit] = "Gt CO₂/yr" df[occursin.("Sequestration", df.variable), :unit] = "Gt CO₂/yr" df[occursin.("CH4", df.variable), :unit] = "Mt CH₄/yr" df = unstack(df, :year, :value) df[occursin.("Def", df.scenario), :scenario] = "default" df[occursin.("Sust", df.scenario), :scenario] = "sustainable" # sort!(df, [order(:variable, rev=true), order(:scenario)]) df = join(vars,df,on = :variable, kind= :outer) CSV.write("./src/assets/data/land-sustainable.csv", df)
Require Import VST.msl.Axioms. Require Import VST.concurrency.sepcomp. Import SepComp. Require Import VST.concurrency.pos. Require Import VST.concurrency.stack. Require Import VST.concurrency.cast. From mathcomp.ssreflect Require Import ssreflect ssrbool ssrnat ssrfun eqtype seq fintype finfun. Set Implicit Arguments. (*NOTE: because of redefinition of [val], these imports must appear after Ssreflect eqtype.*) Require Import compcert.common.AST. (*for typ*) Require Import compcert.common.Values. (*for val*) Require Import compcert.common.Globalenvs. Require Import compcert.common.Memory. Require Import compcert.lib.Integers. Require Import ZArith. (** * Language-Independent Linking Semantics *) (** This file gives the operational semantics of multi-language linking. *) (** ** The following are the key types: *) (** [Modsem.t]: The semantics of a single translation unit, written in a particular programming language and w/ a particular global environment. *) (** [Core.t]: Runtime states corresponding to dynamic invocations of [Modsem.t]s, initialized from a [Modsem] module to handle a particular external function call made by another [Core]. *) (** [CallStack.t]: Stacks of [Core.t]s satisfying a few well-formedness properties. *) (** [Linker.t]: The type of linker corestates. Linker states contain: - [stack]: The stack of cores maintained at runtime. - [fn_tbl]: A table mapping external function id's to module id's. *) (** Linked states are parameterized by: - [N : nat]: The number of modules in the program. - [cores : 'I_N -> Modsem.t]: A function from module id's ('I_N, or integers in the range [0..N-1]) to module semantics. *) (** ** Semantics *) (** [LinkerSem]: A module defining the actual linking semantics. In later parts of the file, the [LinkerSem] semantics is shown to be both a [CoopCoreSem] and an [EffectSem] (cf. core_semantics.v, effect_semantics.v). *) (** [Modsem.t]: Semantics of translation units *) Module Modsem. Record t := mk { F : Type ; V : Type ; ge : Genv.t F V ; C : Type ; sem : @EffectSem (Genv.t F V) C }. End Modsem. (** [Cores] are runtime execution units. *) Module Core. Section core. Variable N : pos. Variable cores : 'I_N -> Modsem.t. Import Modsem. (** ** [Core.t] *) (** The type [Core.t] gives runtime states of dynamic module invocations. - [i : 'I_N]: A natural between [0..n-1] that maps this core back to the translation unit numbered [i] from which it was invoked. - [c : (cores i).(C)]: Runtime states of module [i]. - [sg : signature]: Type signature of the function that this core was spawned to handle. *) Record t := mk { i : 'I_N ; c :> (cores i).(C) ; sg : signature }. Definition upd (core : t) (new : (cores core.(i)).(C)) := {| i := core.(i) ; c := new ; sg:= core.(sg) |}. End core. End Core. Arguments Core.t {N} cores. Arguments Core.i {N cores} !t /. Arguments Core.c {N cores} !t /. Arguments Core.sg {N cores} !t /. Arguments Core.upd {N cores} !core _ /. (* Linking semantics invariants: *) (* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ *) (* 1) All cores except the topmost one are at_external. *) (* 2) The call stack always contains at least one core. *) Section coreDefs. Import Modsem. Variable N : pos. Variable cores : 'I_N -> Modsem.t. Definition atExternal (c: Core.t cores) := let: (Core.mk i c sg) := c in let: F := (cores i).(F) in let: V := (cores i).(V) in let: C := (cores i).(C) in let: effSem := (cores i).(sem) in if at_external effSem c is Some (ef, args) then true else false. Definition wf_callStack (stk : Stack.t (Core.t cores)) := [&& all atExternal (STACK.pop stk) & size stk > 0]. End coreDefs. Arguments atExternal {N} cores c. (** Call stacks are [stack]s satisfying the [wf_callStack] invariant. *) Module CallStack. Section callStack. Context {N : pos} (cores : 'I_N -> Modsem.t). Record t : Type := mk { callStack :> Stack.t (Core.t cores) ; _ : wf_callStack callStack }. Program Definition singl (core: Core.t cores) := mk [:: core] _. Section callStackDefs. Context (stack : t). Definition callStackSize := size stack.(callStack). Lemma callStack_wf : wf_callStack stack. Proof. by case: stack. Qed. Lemma callStack_ext : all (atExternal cores) (STACK.pop stack). Proof. by move: callStack_wf; move/andP=> [H1 H2]. Qed. Lemma callStack_size : callStackSize > 0. Proof. by move: callStack_wf; move/andP=> [H1 H2]. Qed. Lemma callStack_nonempty : STACK.nonempty stack. Proof. by case: stack=> //; case. Qed. End callStackDefs. End callStack. End CallStack. (** ** [Linker.t] *) (** The first two parameters of this record are static configuration data: - [N] is the number of modules in the program. - [cores] is a function from module id's (['I_n], or integers in the range [0..n-1]) to genvs and core semantics, with existentially quantified core type [C]. *) (** Fields: - [fn_tbl] maps external function id's to module id's - [stack] is used to maintain a stack of cores, at runtime. *) Module Linker. Section linker. Variable N : pos. Variable cores : 'I_N -> Modsem.t. Record t := mkLinker { fn_tbl : ident -> option 'I_N ; stack :> CallStack.t cores }. End linker. End Linker. Import Linker. Notation linker := Linker.t. Section linkerDefs. Context {N : pos} (my_cores : 'I_N -> Modsem.t) (l : linker N my_cores). Import CallStack. (*for coercion [callStack]*) Definition updStack (newStack : CallStack.t my_cores) := {| fn_tbl := l.(fn_tbl) ; stack := newStack |}. (** [inContext]: The top core on the call stack has a return context *) Definition inContext (l0 : linker N my_cores) := callStackSize l0.(stack) > 1. (** [updCore]: Replace the top core on the call stack with [newCore] *) Program Definition updCore (newCore: Core.t my_cores) := updStack (CallStack.mk (STACK.push (STACK.pop l.(stack)) newCore) _). Next Obligation. apply/andP; split=>/=; last by []; by apply: callStack_ext. Qed. Lemma updCore_inj newCore newCore' : updCore newCore = updCore newCore' -> newCore=newCore'. Proof. by case. Qed. Lemma updCore_inj_upd c c1 c2 : updCore (Core.upd c c1) = updCore (Core.upd c c2) -> c1=c2. Proof. case=> H1; move: (EqdepFacts.eq_sigT_snd H1); move=> <-. by rewrite -Eqdep.Eq_rect_eq.eq_rect_eq. Qed. (** [pushCore]: Push a new core onto the call stack. *) (** Succeeds only if all cores are currently at_external. *) Lemma stack_push_wf newCore : all (atExternal my_cores) l.(stack).(callStack) -> wf_callStack (SeqStack.updStack (newCore :: l.(stack).(callStack))). Proof. by rewrite/wf_callStack=> H; apply/andP; split. Qed. Definition pushCore (newCore: Core.t my_cores) (pf : all (atExternal my_cores) l.(stack).(callStack)) := updStack (CallStack.mk (STACK.push l.(stack) newCore) (stack_push_wf _ pf)). (** [popCore]: Pop the top core on the call stack. *) (** Succeeds only if the top core is running in a return context. *) Lemma inContext_wf (stk : Stack.t (Core.t my_cores)) : size stk > 1 -> wf_callStack stk -> wf_callStack (STACK.pop stk). Proof. rewrite/wf_callStack=> H1; move/andP=> [H2 H3]; apply/andP; split. - by apply: STACK.all_pop. - by move: H1 H2 H3; case: stk. Qed. Program Definition popCore : option (linker N my_cores) := (match inContext l as pf return (pf = inContext l -> option (linker N my_cores)) with | true => fun pf => Some (updStack (CallStack.mk (STACK.pop l.(stack)) (inContext_wf _ _ _))) | false => fun pf => None end) Logic.eq_refl. Next Obligation. by apply: callStack_wf. Qed. Definition peekCore := STACK.head l.(stack) (callStack_nonempty l.(stack)). Definition emptyStack := if l.(stack).(callStack) is [::] then true else false. Import Modsem. (* We take the RC initial core here because we want to make sure the args *) (* are properly stashed in the [c] tuple. *) Definition initCore (sg: signature) (ix: 'I_N) (v: val) (args: list val) : option (Core.t my_cores):= if @initial_core _ _ _ (my_cores ix).(sem) (my_cores ix).(Modsem.ge) v args is Some c then Some (Core.mk _ my_cores ix c sg) else None. End linkerDefs. Notation ge_ty := (Genv.t unit unit). Arguments updStack {N} {my_cores} !_ _ /. Arguments updCore {N} {my_cores} !_ _ /. Arguments pushCore {N} {my_cores} !l _ _ /. Arguments peekCore {N} {my_cores} !l /. Arguments emptyStack {N} {my_cores} !l /. Lemma popCoreI N my_cores l l' pf : inContext l -> l' = updStack l (CallStack.mk (STACK.pop (CallStack.callStack l)) pf) -> @popCore N my_cores l = Some l'. Proof. rewrite /popCore. move: (popCore_obligation_1 l); move: (popCore_obligation_2 l). case: (inContext l)=> pf1 pf2 // _ ->. f_equal=> //. f_equal=> //. f_equal=> //. by apply: proof_irr. Qed. Lemma popCoreE N my_cores l l' : @popCore N my_cores l = Some l' -> exists pf, [/\ inContext l & l' = updStack l (CallStack.mk (STACK.pop (CallStack.callStack l)) pf)]. Proof. rewrite /popCore. move: (popCore_obligation_1 l); move: (popCore_obligation_2 l). case: (inContext l)=> pf1 pf2 //; case=> <-. have pf: wf_callStack (STACK.pop (CallStack.callStack l)). { case: (andP (pf1 erefl))=> A B; apply/andP; split=> //. by apply: SeqStack.all_pop. by move: (pf2 erefl); clear pf1 pf2 A B; case: l=> /= ?; case; elim. } exists pf; split=> //. by f_equal; f_equal; apply: proof_irr. Qed. (** ** Linking Interaction Semantics *) Module LinkerSem. Section linkerSem. Variable N : pos. (* Number of translation units *) Variable my_cores : 'I_N -> Modsem.t. Variable my_fn_tbl: ident -> option 'I_N. (* [handle id l args] looks up function id [id] in function table *) (* [l.fn_tbl], producing an optional module index [ix : 'I_N]. The index *) (* is used to construct a new core to handle the call to function *) (* [id]. The new core is pushed onto the call stack. *) Section handle. Variables (sg: signature) (id: ident) (l: linker N my_cores) (args: list val). Import CallStack. Definition handle := (match all (atExternal my_cores) l.(stack).(callStack) as pf return (all (atExternal my_cores) l.(stack).(callStack) = pf -> option (linker N my_cores)) with | true => fun pf => if l.(fn_tbl) id is Some ix then if Genv.find_symbol (my_cores ix).(Modsem.ge) id is Some bf then if initCore my_cores sg ix (Vptr bf Int.zero) args is Some c then Some (pushCore l c pf) else None else None else None | false => fun _ => None end) erefl. End handle. Section handle_lems. Import CallStack. Lemma handleP sg id l args l' : handle sg id l args = Some l' <-> (exists (pf : all (atExternal my_cores) l.(stack).(callStack)) ix bf c, [/\ l.(fn_tbl) id = Some ix , Genv.find_symbol (my_cores ix).(Modsem.ge) id = Some bf , initCore my_cores sg ix (Vptr bf Int.zero) args = Some c & l' = pushCore l c pf]). Proof. rewrite/handle. rewrite /pushCore. generalize (stack_push_wf l). pattern (all (atExternal my_cores) (CallStack.callStack (stack l))) at 1 2 3 4 5 6 7 8. case f: (all _ _); move=> pf. case g: (fn_tbl l id)=> [ix|]. case fnd: (Genv.find_symbol _ _)=> [bf|]. case h: (initCore _ _ _)=> [c|]. split=> H. exists (erefl true),ix,bf,c; split=> //; first by case: H=> <-. case: H=> pf0 []ix0 []bf0 []c0 []; case=> <-. rewrite fnd; case=> <-; rewrite h; case=> <- ->. by repeat f_equal; apply: proof_irr. split=> //; case=> pf0 []ix0 []bf0 []c0 []. by case=> <-; rewrite fnd; case=> <-; rewrite h. split=> //; case=> pf0 []ix0 []bf0 []c0 []. by case=> <-; rewrite fnd; discriminate. split=> //. by case=> pf0 []ix0 []bf0 []c0 []; discriminate. split=> //. by case=> pf0 []ix0 []bf0 []c0 []; discriminate. Qed. End handle_lems. Definition main_sig := mksignature nil (Some Tint). Definition initial_core (ge: ge_ty) (v: val) (args: list val) : option (linker N my_cores) := if v is Vptr bf ofs then if Int.eq ofs Int.zero then if Genv.invert_symbol ge bf is Some id then if my_fn_tbl id is Some ix then if initCore my_cores (main_sig cc_default) ix (Vptr bf Int.zero) args is Some c then Some (mkLinker my_fn_tbl (CallStack.singl c)) else None else None else None else None else None. (* Functions suffixed w/ 0 always operate on the running core on the (top *) (* of the) call stack. *) Definition at_external0 (l: linker N my_cores) := let: c := peekCore l in let: ix := c.(Core.i) in let: sem := (my_cores ix).(Modsem.sem) in let: F := (my_cores ix).(Modsem.F) in let: V := (my_cores ix).(Modsem.V) in @at_external (Genv.t F V) _ _ sem (Core.c c). Arguments at_external0 !l. Require Import VST.sepcomp.val_casted. (*for val_has_type_func*) Definition halted0 (l: linker N my_cores) := let: c := peekCore l in let: ix := c.(Core.i) in let: sg := c.(Core.sg) in let: sem := (my_cores ix).(Modsem.sem) in let: F := (my_cores ix).(Modsem.F) in let: V := (my_cores ix).(Modsem.V) in if @halted (Genv.t F V) _ _ sem (Core.c c) is Some v then if val_casted.val_has_type_func v (proj_sig_res sg) then Some v else None else None. Arguments halted0 !l. (* [corestep0] lifts a corestep of the runing core to a corestep of the *) (* whole program semantics. *) (* Note: we call the RC version of corestep here. *) Definition corestep0 (l: linker N my_cores) (m: Mem.mem) (l': linker N my_cores) (m': Mem.mem) := let: c := peekCore l in let: ix := c.(Core.i) in let: sem := (my_cores ix).(Modsem.sem) in let: F := (my_cores ix).(Modsem.F) in let: V := (my_cores ix).(Modsem.V) in let: ge := (my_cores ix).(Modsem.ge) in exists c', @corestep (Genv.t F V) _ _ sem ge (Core.c c) m c' m' /\ l' = updCore l (Core.upd c c'). Arguments corestep0 !l m l' m'. Parameter FIXME_id_of_string : String.string -> ident. Definition fun_id (ef: external_function) : option ident := if ef is (EF_external id sig) then Some (FIXME_id_of_string id) else None. (* The linker is [at_external] whenever the top core is [at_external] and *) (* the [id] of the called external function isn't handleable by any *) (* compilation unit. *) Definition at_external (l: linker N my_cores) := if at_external0 l is Some (ef, args) then if fun_id ef is Some id then if fn_tbl l id is None then Some (ef, args) else None else None else at_external0 l. (* We call the RC version of after_external here to ensure that the *) (* return value [mv] of the external call is properly stashed in the *) (* state tuple [c]. *) Definition after_external (mv: option val) (l: linker N my_cores) := let: c := peekCore l in let: ix := c.(Core.i) in let: sem := (my_cores ix).(Modsem.sem) in let: F := (my_cores ix).(Modsem.F) in let: V := (my_cores ix).(Modsem.V) in let: ge := (my_cores ix).(Modsem.ge) in if @after_external (Genv.t F V) _ _ sem mv (Core.c c) is Some c' then Some (updCore l (Core.upd c c')) else None. (** The linker is [halted] when the last core on the call stack is halted. *) Definition halted (l: linker N my_cores) := if ~~inContext l then if halted0 l is Some rv then Some rv else None else None. (** Return type of topmost core *) Definition retType0 (l: linker N my_cores) : option typ := let: c := peekCore l in let: sg := c.(Core.sg) in sig_res sg. (** ** Corestep relation of linking semantics *) Definition corestep (l: linker N my_cores) (m: Mem.mem) (l': linker N my_cores) (m': Mem.mem) := (** 1- The running core takes a step, or *) corestep0 l m l' m' \/ (** 2- We're in a function call context. In this case, the running core is either *) (m=m' /\ ~corestep0 l m l' m' /\ (** 3- at_external, in which case we push a core onto the stack to handle the external function call (or this is not possible because no module handles the external function id, in which case the entire linker is at_external) *) if at_external0 l is Some (ef, args) then if fun_id ef is Some id then if handle (ef_sig ef) id l args is Some l'' then l'=l'' else False else False else (** 4- or halted, in which case we pop the halted core from the call stack and inject its return value into the caller's corestate. *) if inContext l then if halted0 l is Some rv then if popCore l is Some l0 then if after_external (Some rv) l0 is Some l'' then l'=l'' else False else False else False else False). (** An inductive characterization of [corestep] above, proved equivalent below. *) Inductive Corestep : linker N my_cores -> mem -> linker N my_cores -> mem -> Prop := | Corestep_step : forall l m c' m', let: c := peekCore l in let: c_ix := Core.i c in let: c_ge := Modsem.ge (my_cores c_ix) in let: c_sem := Modsem.sem (my_cores c_ix) in semantics.corestep c_sem c_ge (Core.c c) m c' m' -> Corestep l m (updCore l (Core.upd (peekCore l) c')) m' | Corestep_call : forall (l : linker N my_cores) m ef args id bf d_ix d (pf : all (atExternal my_cores) (CallStack.callStack l)), let: c := peekCore l in let: c_ix := Core.i c in let: c_ge := Modsem.ge (my_cores c_ix) in let: c_sem := Modsem.sem (my_cores c_ix) in semantics.at_external c_sem (Core.c c) = Some (ef,args) -> fun_id ef = Some id -> fn_tbl l id = Some d_ix -> Genv.find_symbol (my_cores d_ix).(Modsem.ge) id = Some bf -> let: d_ge := Modsem.ge (my_cores d_ix) in let: d_sem := Modsem.sem (my_cores d_ix) in semantics.initial_core d_sem d_ge (Vptr bf Int.zero) args = Some d -> Corestep l m (pushCore l (Core.mk _ _ _ d (ef_sig ef)) pf) m | Corestep_return : forall (l : linker N my_cores) l'' m rv d', 1 < CallStack.callStackSize (stack l) -> let: c := peekCore l in let: c_ix := Core.i c in let: c_sg := Core.sg c in let: c_ge := Modsem.ge (my_cores c_ix) in let: c_sem := Modsem.sem (my_cores c_ix) in popCore l = Some l'' -> let: d := peekCore l'' in let: d_ix := Core.i d in let: d_ge := Modsem.ge (my_cores d_ix) in let: d_sem := Modsem.sem (my_cores d_ix) in semantics.halted c_sem (Core.c c) = Some rv -> val_has_type_func rv (proj_sig_res c_sg)=true -> semantics.after_external d_sem (Some rv) (Core.c d) = Some d' -> Corestep l m (updCore l'' (Core.upd d d')) m. Lemma CorestepE l m l' m' : Corestep l m l' m' -> corestep l m l' m'. Proof. inversion 1; subst; rename H0 into A; rename H into B. by left; exists c'; split. right; split=> //. split=> //. rewrite /corestep0=> [][]c' []step. by rewrite (corestep_not_at_external _ _ _ _ _ _ step) in A. rewrite /inContext /at_external0 A H1. case e: (handle _ _ _)=> //[l'|]. move: e; case/handleP=> pf' []ix' []bf' []c []C G D ->. move: D; rewrite /initCore. rewrite H2 in C; case: C=> eq; subst ix'. rewrite G in H3; case: H3=> ->. by rewrite H4; case=> <-; f_equal; apply: proof_irr. move: e; rewrite/handle /pushCore. generalize (stack_push_wf l). pattern (all (atExternal my_cores) (CallStack.callStack (stack l))) at 1 2 3 4 5 6. case f: (all _ _)=> pf'. rewrite H2 H3 /initCore H4; discriminate. by rewrite pf in f. right; split=> //. split=> //. rewrite /corestep0=> [][]c' []step. by rewrite (corestep_not_halted _ _ _ _ _ _ step) in H2. have at_ext: semantics.at_external (Modsem.sem (my_cores (Core.i (peekCore l)))) (Core.c (peekCore l)) = None. { case: (at_external_halted_excl (Modsem.sem (my_cores (Core.i (peekCore l)))) (Core.c (peekCore l)))=> //. by rewrite H2. } rewrite /inContext A /at_external0 H1 at_ext. by rewrite /halted0 H2 /after_external H3 H4. Qed. Lemma CorestepI l m l' m' : corestep l m l' m' -> Corestep l m l' m'. Proof. case. case=> c []step ->. by apply: Corestep_step. case=> <-. case=> nstep. case atext: (at_external0 _)=> [[ef args]|//]. case funid: (fun_id ef)=> [id|//]. case hdl: (handle (ef_sig ef) id l args)=> [l''|//] ->. move: hdl; case/handleP=> pf []ix []bf []c []fntbl genv init ->. move: init; rewrite /initCore. case init: (semantics.initial_core _ _ _ _)=> [c'|//]; case=> <-. by apply: (@Corestep_call _ _ ef args id bf). case inCtx: (inContext _)=> //. case hlt: (halted0 _)=> [rv|//]. case pop: (popCore _)=> [c|//]. case aft: (after_external _ _)=> [l''|//] ->. move: aft; rewrite /after_external. case aft: (semantics.after_external _ _ _)=> [c''|//]. rewrite /halted0 in hlt; move: hlt. case hlt: (semantics.halted _ _)=> //. case oval: (val_has_type_func _ _)=> //; case=> Heq. subst. case=> <-. by apply: (@Corestep_return _ _ _ rv c''). Qed. (** Prove that the two representations above coincide. *) Lemma CorestepP l m l' m' : corestep l m l' m' <-> Corestep l m l' m'. Proof. by split; [apply: CorestepI | apply: CorestepE]. Qed. Lemma corestep_not_at_external0 m c m' c' : corestep0 c m c' m' -> at_external0 c = None. Proof. by move=>[]newCore []H1 H2; apply corestep_not_at_external in H1. Qed. Lemma at_external_halted_excl0 c : at_external0 c = None \/ halted0 c = None. Proof. case: (at_external_halted_excl (Modsem.sem (my_cores (Core.i (peekCore c)))) (Core.c (peekCore c))). by rewrite /at_external0=> ->; left. by rewrite /halted0=> ->; right. Qed. Lemma corestep_not_halted0 m c m' c' : corestep0 c m c' m' -> halted c = None. Proof. move=> []newCore []H1 H2; rewrite/halted. case Hcx: (~~ inContext _)=>//; case Hht: (halted0 _)=>//. move: Hht; rewrite/halted0; apply corestep_not_halted in H1. by move: H1=> /= ->. Qed. Lemma corestep_not_halted0' m c m' c' : corestep0 c m c' m' -> halted0 c = None. Proof. move=> []newCore []H1 H2; rewrite/halted. case Hht: (halted0 _)=>//. by move: Hht; rewrite/halted0; apply corestep_not_halted in H1; rewrite /= H1. Qed. Lemma corestep_not_at_external (ge : ge_ty) m c m' c' : corestep c m c' m' -> at_external c = None. Proof. rewrite/corestep/at_external. move=> [H|[_ [_ H]]]; first by move: H; move/corestep_not_at_external0=> /= ->. move: H; case Heq: (at_external0 c)=>[[ef args]|//]. move: Heq; case: (at_external_halted_excl0 c)=> [H|H]; first by rewrite H. move=> H2; case: (fun_id ef)=>// id; case hdl: (handle _ _ _)=> [a|]. by move: hdl; case/handleP=> ? []? []? []? []->. by []. Qed. Lemma at_external0_not_halted c x : at_external0 c = Some x -> halted c = None. Proof. case: (at_external_halted_excl0 c); rewrite/at_external0/halted. by case Heq: (peekCore c)=>//[a] ->. move=> H; case Heq: (peekCore c)=>//[a]. by case Hcx: (~~ inContext _)=>//; rewrite H. Qed. Lemma corestep_not_halted (ge : ge_ty) m c m' c' : corestep c m c' m' -> halted c = None. Proof. rewrite/corestep. move=> [H|[_ [_ H]]]; first by move: H; move/corestep_not_halted0. move: H; case Hat: (at_external0 _)=> [x|//]. by rewrite (at_external0_not_halted _ Hat). by rewrite /halted; case Hcx: (inContext _). Qed. Lemma at_external_halted_excl c : at_external c = None \/ halted c = None. Proof. rewrite/at_external/halted; case Hat: (at_external0 c)=>//; first by right; apply: (at_external0_not_halted _ Hat). by left. Qed. Notation cast'' pf x := (cast (Modsem.C \o my_cores) (sym_eq pf) x). Lemma after_externalE rv c c' : after_external rv c = Some c' -> exists fn_tbl hd hd' tl pf pf' (eq_pf : Core.i hd = Core.i hd') (sig_pf : Core.sg hd = Core.sg hd'), [/\ c = mkLinker fn_tbl (CallStack.mk [:: hd & tl] pf) , c' = mkLinker fn_tbl (CallStack.mk [:: hd' & tl] pf') & semantics.after_external (Modsem.sem (my_cores (Core.i hd))) rv (Core.c hd) = Some (cast'' eq_pf (Core.c hd'))]. Proof. case: c=> fntbl; case; case=> // hd stk pf aft; exists fntbl,hd. move: aft; rewrite /after_external /=. case e: (semantics.after_external _ _ _)=> // [hd']; case=> <-. exists (Core.mk N my_cores (Core.i hd) hd' (Core.sg hd)),stk,pf,pf. rewrite /=; exists refl_equal; exists refl_equal; split=> //; f_equal; f_equal. by apply: proof_irr. Qed. (** Construct the interaction semantics of linking. *) Definition coresem : CoreSemantics ge_ty (linker N my_cores) Mem.mem := Build_CoreSemantics ge_ty (linker N my_cores) Mem.mem initial_core at_external after_external halted (fun _ : ge_ty => corestep) corestep_not_at_external corestep_not_halted at_external_halted_excl. (** The linking semantics function \mathcal{L} is deterministic: \mathcal{L}(M1,...,Mn) is deterministic as long as M1, ..., Mn are. *) Lemma linking_det (dets : forall ix : 'I_N, semantics_lemmas.corestep_fun (Modsem.sem (my_cores ix))) : semantics_lemmas.corestep_fun coresem. Proof. move=> ge m c m' c' m'' c''. move/CorestepP=> H1; move/CorestepP=> H2. inversion H2; subst. { inversion H1; subst; first by case: (dets _ _ _ _ _ _ _ _ H H0)=> -> ->. by apply semantics.corestep_not_at_external in H; rewrite H in H0. by apply semantics.corestep_not_halted in H; rewrite H in H4. } { inversion H1; subst. by apply semantics.corestep_not_at_external in H6; rewrite H6 in H. split; auto. f_equal. { assert (ef0 = ef) by congruence; subst. assert (id0 = id) by congruence; subst. assert (d_ix0 = d_ix) by congruence; subst. assert (d0 = d) by congruence; subst. reflexivity. } apply proof_irr. case: (semantics.at_external_halted_excl (Modsem.sem (my_cores (Core.i (peekCore c')))) (Core.c (peekCore c'))). by rewrite H. by rewrite H8. } { inversion H1; subst. by apply semantics.corestep_not_halted in H6; rewrite H6 in H3. case: (semantics.at_external_halted_excl (Modsem.sem (my_cores (Core.i (peekCore c')))) (Core.c (peekCore c'))). by rewrite H6. by rewrite H3. rewrite H8 in H3; case: H3=> eq1; subst. rewrite H0 in H7; case: H7=> eq2; subst. by rewrite H5 in H10; case: H10=> <-. } Qed. End linkerSem. End LinkerSem. (** ** Linking Effect Semantics *) Section effingLinker. Variable N : pos. Variable my_cores : 'I_N -> Modsem.t. Variable my_fun_tbl : ident -> option 'I_N. Import Linker. Definition effstep0 U (l: linker N my_cores) m (l': linker N my_cores) m' := let: c := peekCore l in let: ix := c.(Core.i) in let: sem := (my_cores ix).(Modsem.sem) in let: F := (my_cores ix).(Modsem.F) in let: V := (my_cores ix).(Modsem.V) in let: ge := (my_cores ix).(Modsem.ge) in exists c', @effstep (Genv.t F V) _ sem ge U (Core.c c) m c' m' /\ l' = updCore l (Core.upd c c'). Lemma effstep0_unchanged U l m l' m' : effstep0 U l m l' m' -> Mem.unchanged_on (fun b ofs => U b ofs = false) m m'. Proof. rewrite/effstep0; case=> ? [STEP]. by move: {STEP}(effax1 _ _ _ _ _ _ _ STEP)=> [STEP]UNCH H2. Qed. Lemma effstep0_corestep0 U l m l' m' : effstep0 U l m l' m' -> LinkerSem.corestep0 l m l' m'. Proof. rewrite/effstep0/LinkerSem.corestep0; case=> c' [STEP]. move: {STEP}(effax1 _ _ _ _ _ _ _ STEP)=> [STEP]UNCH H2. by exists c'; split. Qed. Lemma effstep0_forward U l m l' m' : effstep0 U l m l' m' -> mem_forward m m'. Proof. move/effstep0_corestep0; rewrite/LinkerSem.corestep0. move=> []c' []STEP H1. apply semantics_lemmas.corestep_fwd in STEP. auto. Qed. Lemma effstep0_mem U l m l' m' : effstep0 U l m l' m' -> mem_step m m'. Proof. move/effstep0_corestep0; rewrite/LinkerSem.corestep0. move=> []c' []STEP H1. apply corestep_mem in STEP. auto. Qed. Lemma effstep0_rdonly U l m l' m' : effstep0 U l m l' m' -> forall b, Mem.valid_block m b -> readonly m b m'. Proof. move/effstep0_corestep0. rewrite/LinkerSem.corestep0. by move=> []c' []STEP H1 b VB; intros; eapply semantics_lemmas.corestep_rdonly; eauto. Qed. Definition inner_effstep (ge: ge_ty) (l: linker N my_cores) m (l': linker N my_cores) m' := [/\ LinkerSem.corestep l m l' m' & LinkerSem.corestep0 l m l' m' -> exists U, effstep0 U l m l' m']. Definition effstep (ge: ge_ty) V (l: linker N my_cores) m (l': linker N my_cores) m' := [/\ LinkerSem.corestep l m l' m' , LinkerSem.corestep0 l m l' m' -> effstep0 V l m l' m' & ~LinkerSem.corestep0 l m l' m' -> forall b ofs, ~~ V b ofs]. Section csem. Notation mycsem := (LinkerSem.coresem N my_cores my_fun_tbl). Program Definition csem : CoreSemantics ge_ty (linker N my_cores) Mem.mem := Build_CoreSemantics _ _ _ (initial_core mycsem) (at_external mycsem) (after_external mycsem) (halted mycsem) inner_effstep _ _ _. Next Obligation. move: H; rewrite/inner_effstep=> [[H1] H2]. by apply: (LinkerSem.corestep_not_at_external ge H1). Qed. Next Obligation. move: H; rewrite/inner_effstep=> [[H1] H2]. by apply: (LinkerSem.corestep_not_halted ge H1). Qed. Next Obligation. by apply: (LinkerSem.at_external_halted_excl). Qed. End csem. Lemma linking_det (dets : forall ix : 'I_N, semantics_lemmas.corestep_fun (Modsem.sem (my_cores ix))) : semantics_lemmas.corestep_fun csem. Proof. move=> m m' m'' ge c c' c''; rewrite /= /inner_effstep => [][]H1 _ []H2 _. case: (@LinkerSem.linking_det N my_cores my_fun_tbl dets _ _ _ _ _ _ _ H1 H2). by refine ge. by move=> -> ->. Qed. Program Definition coopsem := Build_MemSem _ _ csem _. Next Obligation. move: CS; case; move=>[H1|[<- [H0 H1]]]. by move/(_ H1)=>{H1} [U EFF]; apply: (effstep0_mem EFF). by move=> ?; apply: semantics_lemmas.mem_step_refl. Qed. Program Definition effsem := Build_EffectSem _ _ coopsem effstep _ _ _. Next Obligation. move: H=>[H1]H2; split. by split=> //; move=> H3; move: {H2 H3}(H2 H3)=> STEP; exists M. case: H1=> [H1|[<- [H0 H1]]]=> //. by move: (H2 H1)=> H3; apply: (effstep0_unchanged H3). apply Mem.unchanged_on_refl. Qed. Next Obligation. move: H; rewrite/inner_effstep=> [[[H1|[<- [H0 H1]]]]] H2=> //. move: (H2 H1)=> {H2}[U H3]; exists U; split=> //. by left; apply: (effstep0_corestep0 H3). by exists [fun _ _ => false]; split=> //; right. Qed. Next Obligation. move: H; rewrite/effstep=> [][]; case. move=> H; move/(_ H); rewrite/effstep0. by move=> []? []H2 _ _; apply: (effstep_perm _ _ _ _ _ _ _ H2 _ _ H0). by move=> []_ []nstep _ _; move/(_ nstep b z); rewrite H0. Qed. End effingLinker.
import classes.context_free.basics.definition import utilities.list_utils /-- Pumping lemma for context-free languages. -/ lemma CF_pumping {T : Type} {L : language T} (cf : is_CF L) : ∃ n : ℕ, ∀ w ∈ L, list.length w ≥ n → ( ∃ u v x y z : list T, (w = u ++ v ++ x ++ y ++ z) ∧ (v ++ y).length > 0 ∧ (v ++ x ++ y).length ≤ n ∧ (∀ i : ℕ, u ++ v ^ i ++ x ++ y ^ i ++ z ∈ L) ) := sorry
/* Copyright [2021] [IBM Corporation] 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. */ #ifndef __MM_PLUGIN_ITF_H__ #define __MM_PLUGIN_ITF_H__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-variable" #pragma GCC diagnostic ignored "-Wunused-parameter" #pragma GCC diagnostic ignored "-Wunused-function" #define PUBLIC __attribute__((__visibility__("default"))) #if defined(__cplusplus) #pragma GCC diagnostic ignored "-Weffc++" #include <common/byte_span.h> #include <gsl/span> #include <functional> #endif #include <stdlib.h> #include <assert.h> #if defined(__cplusplus) extern "C" { #endif typedef int status_t; typedef void * mm_plugin_heap_t; typedef void (*request_memory_callback_t)(void * param, size_t alignment, size_t size_hint, void * addr_hint); typedef void (*release_memory_callback_t)(void * param, void * addr, size_t size); /** * Initialize mm library * * @return S_OK, E_FAIL */ status_t mm_plugin_init(); /** * Create a heap instance * * @param params Constructor parameters (e.g., JSON) * @param root_ptr Root point for persistent heaps * @param out_heap Heap context * * @return S_OK, E_FAIL */ status_t mm_plugin_create(const char * params, void * root_ptr, mm_plugin_heap_t * out_heap); /** * Delete a heap instance * * @param heap Heap context to destroy * * @return S_OK, E_INVAL, E_FAIL */ status_t mm_plugin_destroy(mm_plugin_heap_t heap); /** * Add (slab) region of memory to fuel the allocator. The passthru * allocator does not need this as it takes directly from the OS. * * @param heap Heap context * @param region_base Pointer to beginning of region * @param region_size Region length in bytes * * @return E_NOT_IMPL, S_OK, E_FAIL, E_INVAL */ status_t mm_plugin_add_managed_region(mm_plugin_heap_t heap, void * region_base, size_t region_size); /** * Query memory regions being used by the allocator * * @param heap Heap context * @param region_id Index counting from 0 * @param [out] Base address of region * @param [out] Size of region in bytes * * @return S_MORE (continue to next region id), S_OK (done), E_INVAL */ status_t mm_plugin_query_managed_region(mm_plugin_heap_t heap, unsigned region_id, void** out_region_base, size_t* out_region_size); /** * Register callback the allocator can use to request more memory * * @param heap Heap context * @param callback Call back function pointer * @param param Optional parameter which will be pass to callback function * * @return E_NOT_IMPL, S_OK */ status_t mm_plugin_register_callback_request_memory(mm_plugin_heap_t heap, request_memory_callback_t callback, void * param); /** * Allocate a region of memory without alignment or hint * * @param heap Heap context * @param Length in bytes * @param [out] Pointer to allocated region * * @return S_OK or E_FAIL */ status_t mm_plugin_allocate(mm_plugin_heap_t heap, size_t n, void ** out_ptr); /** * Allocation region of memory that is aligned * * @param heap Heap context * @param n Size of region in bytes * @param alignment Alignment in bytes * @param out_ptr Address if [in] nullptr, [out] pointer to allocated region * * @return S_OK, E_FAIL, E_INVAL (depending on implementation) */ status_t mm_plugin_aligned_allocate(mm_plugin_heap_t heap, size_t n, size_t alignment, void ** out_ptr); /** * Special case for EASTL * * @param heap Heap context * @param n Size of region in bytes * @param alignment Alignment in bytes * @param offset Offset from start of region to location within region which satisfies alignment * @param out_ptr Address if [in] nullptr, [out] pointer to allocated region * * @return */ status_t mm_plugin_aligned_allocate_offset(mm_plugin_heap_t heap, size_t n, size_t alignment, size_t offset, void ** out_ptr); /** * Free a previously allocated region of memory with length known * * @param heap Heap context * @param ptr Address of [in] pointer to previously allocated region, [out] nullptr * @param size Length of region in bytes * * @return S_OK or E_INVAL; */ status_t mm_plugin_deallocate(mm_plugin_heap_t heap, void ** ptr, size_t size); /** * Free previously allocated region without known length * * @param heap Heap context * @param ptr Address of [in] pointer to previously allocated region, [out] nullptr * * @return S_OK */ status_t mm_plugin_deallocate_without_size(mm_plugin_heap_t heap, void ** ptr); /** * Allocate region and zero memory * * @param heap Heap context * @param size Size of region in bytes * @param ptr [out] Pointer to allocated region * * @return S_OK */ status_t mm_plugin_callocate(mm_plugin_heap_t heap, size_t n, void ** out_ptr); /* The POSIX realloc() function changes the size of the memory block pointed to by ptr to size bytes. The contents will be unchanged in the range from the start of the region up to the minimum of the old and new sizes. If the new size is larger than the old size, the added memory will not be initialized. If ptr is NULL, then the call is equivalent to malloc(size), for all values of size; if size is equal to zero, and ptr is not NULL, then the call is equivalent to free(ptr). Unless ptr is NULL, it must have been returned by an earlier call to malloc(), calloc(), or realloc(). If the area pointed to was moved, a free(ptr) is done. */ /** * Resize an existing allocation * * @param heap Heap context * @param in_out_ptr Address of pointer to [in] existing allocated region, [out] new reallocated region or null if unable to reallocate * @param size New size in bytes * * * @return S_OK */ status_t mm_plugin_reallocate(mm_plugin_heap_t heap, void ** in_out_ptr, size_t size); /** * Get the number of usable bytes in block pointed to by ptr. The * allocator *may* not have this information and should then return * E_NOT_IMPL. Returned size may be larger than requested allocation * * @param heap Heap context * @param ptr Pointer to block base * @param out_ptr [out] Number of bytes in allocated block * * @return S_OK, E_NOT_IMPL */ status_t mm_plugin_usable_size(mm_plugin_heap_t heap, void * ptr, size_t * out_size); /** * Inject an allocation back into the allocator (reconstituing) * * @param heap Heap context * @param ptr Pointer to region of memory to mark allocated * @param size Size of region in bytes * * @return S_OK, E_NOT_IMPL */ status_t mm_plugin_inject_allocation(mm_plugin_heap_t heap, void * ptr, size_t size); /** * Report bytes remaining * * @param bytes_remaining Bytes remaining for allocation * * @return S_OK, E_NOT_IMPL */ status_t mm_plugin_bytes_remaining(mm_plugin_heap_t heap, size_t *bytes_remaining); /** * Get debugging information * * @param heap Heap context */ void mm_plugin_debug(mm_plugin_heap_t heap); /** * Check for crash consistency libccpm behavior) * * @return non-zero iff the root_ptr parameter of mm_plugin_create is interpreted as a struct ccpm_params *. */ int mm_plugin_is_crash_consistent(mm_plugin_heap_t heap); /** * Check for inject_allocation capability * * @return non-zero iff mm_plugin_inject_allocation is implemented */ int mm_plugin_can_inject_allocation(mm_plugin_heap_t heap); /** * Function pointer table for all methods * */ typedef struct tag_mm_plugin_function_table_t { status_t (*mm_plugin_init)(); status_t (*mm_plugin_create)(const char * params, void * root_ptr , mm_plugin_heap_t * out_heap); status_t (*mm_plugin_destroy)(mm_plugin_heap_t heap); status_t (*mm_plugin_add_managed_region)(mm_plugin_heap_t heap, void * region_base, size_t region_size); status_t (*mm_plugin_query_managed_region)(mm_plugin_heap_t heap, unsigned region_id, void** out_region_base, size_t* out_region_size); status_t (*mm_plugin_register_callback_request_memory)(mm_plugin_heap_t heap, request_memory_callback_t callback, void * param); status_t (*mm_plugin_allocate)(mm_plugin_heap_t heap, size_t n, void ** out_ptr); status_t (*mm_plugin_aligned_allocate)(mm_plugin_heap_t heap, size_t n, size_t alignment, void ** out_ptr); status_t (*mm_plugin_aligned_allocate_offset)(mm_plugin_heap_t heap, size_t n, size_t alignment, size_t offset, void ** out_ptr); status_t (*mm_plugin_deallocate)(mm_plugin_heap_t heap, void ** ptr, size_t size); status_t (*mm_plugin_deallocate_without_size)(mm_plugin_heap_t heap, void ** ptr); status_t (*mm_plugin_callocate)(mm_plugin_heap_t heap, size_t n, void ** out_ptr); status_t (*mm_plugin_reallocate)(mm_plugin_heap_t heap, void ** in_out_ptr, size_t size); status_t (*mm_plugin_usable_size)(mm_plugin_heap_t heap, void * ptr, size_t * out_size); status_t (*mm_plugin_bytes_remaining)(mm_plugin_heap_t heap, size_t * bytes_remaining); void (*mm_plugin_debug)(mm_plugin_heap_t heap); status_t (*mm_plugin_inject_allocation)(mm_plugin_heap_t heap, void * ptr, size_t size); int (*mm_plugin_is_crash_consistent)(mm_plugin_heap_t heap); int (*mm_plugin_can_inject_allocation)(mm_plugin_heap_t heap); } mm_plugin_function_table_t; #if defined(__cplusplus) } #endif #if defined(__cplusplus) #include <dlfcn.h> #include <string> #include <stdio.h> #include <stdexcept> #define LOAD_SYMBOL(X) _ft.X = reinterpret_cast<decltype(_ft.X)>(dlsym(_module, # X)); assert(_ft.X) /** * C++ wrapper on C-based plugin API * */ class MM_plugin_wrapper { public: MM_plugin_wrapper(const std::string& plugin_path, const std::string& config = "", void * root_ptr = nullptr) { assert(plugin_path.empty() == false); _module = dlopen(plugin_path.c_str(), RTLD_NOW | RTLD_NODELETE); // RTLD_DEEPBIND | if(_module == nullptr) { char err[1024]; sprintf(err, "%s\n", dlerror()); throw std::invalid_argument(err); } LOAD_SYMBOL(mm_plugin_init); LOAD_SYMBOL(mm_plugin_create); LOAD_SYMBOL(mm_plugin_add_managed_region); LOAD_SYMBOL(mm_plugin_query_managed_region); LOAD_SYMBOL(mm_plugin_register_callback_request_memory); LOAD_SYMBOL(mm_plugin_allocate); LOAD_SYMBOL(mm_plugin_aligned_allocate); LOAD_SYMBOL(mm_plugin_aligned_allocate_offset); LOAD_SYMBOL(mm_plugin_deallocate); LOAD_SYMBOL(mm_plugin_deallocate_without_size); LOAD_SYMBOL(mm_plugin_callocate); LOAD_SYMBOL(mm_plugin_reallocate); LOAD_SYMBOL(mm_plugin_usable_size); LOAD_SYMBOL(mm_plugin_debug); LOAD_SYMBOL(mm_plugin_destroy); LOAD_SYMBOL(mm_plugin_inject_allocation); LOAD_SYMBOL(mm_plugin_bytes_remaining); LOAD_SYMBOL(mm_plugin_is_crash_consistent); LOAD_SYMBOL(mm_plugin_can_inject_allocation); // dlclose(_module); /* create heap instance */ _ft.mm_plugin_create(config.c_str(), root_ptr, &_heap); } MM_plugin_wrapper(const MM_plugin_wrapper &) = delete; MM_plugin_wrapper(MM_plugin_wrapper && other) noexcept : _module(std::move(other._module)) , _ft(std::move(other._ft)) , _heap(std::move(other._heap)) { other._heap = nullptr; } virtual ~MM_plugin_wrapper() noexcept { if ( _heap ) { _ft.mm_plugin_destroy(_heap); } } /* forwarding in liners */ inline status_t init() noexcept { return _ft.mm_plugin_init(); } inline status_t add_managed_region(void * region_base, size_t region_size) noexcept { return _ft.mm_plugin_add_managed_region(_heap, region_base, region_size); } inline status_t query_managed_region(unsigned region_id, void** out_region_base, size_t* out_region_size) noexcept { return _ft.mm_plugin_query_managed_region(_heap, region_id, out_region_base, out_region_size); } inline status_t register_callback_request_memory(request_memory_callback_t callback, void * param) noexcept { return _ft.mm_plugin_register_callback_request_memory(_heap, callback, param); } inline status_t allocate(size_t n, void ** out_ptr) noexcept { return _ft.mm_plugin_allocate(_heap, n, out_ptr); } inline status_t aligned_allocate(size_t n, size_t alignment, void ** out_ptr) noexcept { return _ft.mm_plugin_aligned_allocate(_heap, n, alignment, out_ptr); } inline status_t aligned_allocate_offset(size_t n, size_t alignment, size_t offset, void ** out_ptr) noexcept { return _ft.mm_plugin_aligned_allocate_offset(_heap, n, alignment, offset, out_ptr); } inline status_t deallocate(void ** ptr, size_t size) noexcept { return _ft.mm_plugin_deallocate(_heap, ptr, size); } inline status_t deallocate_without_size(void ** ptr) noexcept { return _ft.mm_plugin_deallocate_without_size(_heap, ptr); } inline status_t callocate(size_t n, void ** out_ptr) noexcept { return _ft.mm_plugin_callocate(_heap, n, out_ptr); } inline status_t reallocate(void ** in_out_ptr, size_t size) noexcept { return _ft.mm_plugin_reallocate(_heap, in_out_ptr, size); } inline status_t usable_size(void * ptr, size_t * out_size) noexcept { return _ft.mm_plugin_usable_size(_heap, ptr, out_size); } inline status_t bytes_remaining(size_t *bytes_remaining) const noexcept { return _ft.mm_plugin_bytes_remaining(_heap, bytes_remaining); } inline void debug(mm_plugin_heap_t heap) noexcept { return _ft.mm_plugin_debug(_heap); } inline status_t inject_allocation(void * ptr, size_t size) noexcept { return _ft.mm_plugin_inject_allocation(_heap, ptr, size); } inline int is_crash_consistent() noexcept { return _ft.mm_plugin_is_crash_consistent(_heap); } inline int can_inject_allocation() noexcept { return _ft.mm_plugin_can_inject_allocation(_heap); } private: void * _module; mm_plugin_function_table_t _ft; #if 0 /* intention, but we avoid appealing to moveable_ptr */ common::moveable_ptr<void> _heap; #else void * _heap; #endif }; #include <limits> #include <new> /** * Standard C++ allocator wrapper * */ template <class T> class MM_plugin_cxx_allocator { public: using value_type = T; using pointer = value_type*; using const_pointer = typename std::pointer_traits<pointer>::template rebind<value_type const>; using void_pointer = typename std::pointer_traits<pointer>::template rebind<void>; using const_void_pointer = typename std::pointer_traits<pointer>::template rebind<const void>; using difference_type = typename std::pointer_traits<pointer>::difference_type; using size_type = std::make_unsigned_t<difference_type>; template <class U> struct rebind {typedef MM_plugin_cxx_allocator<U> other;}; MM_plugin_cxx_allocator(MM_plugin_wrapper& wrapper) noexcept : _wrapper(wrapper) { } template <class U> MM_plugin_cxx_allocator(MM_plugin_cxx_allocator<U> const& a_) noexcept : _wrapper(a_._wrapper) {} pointer allocate(std::size_t n) { pointer p = nullptr; auto status = _wrapper.allocate(n*sizeof(value_type), reinterpret_cast<void**>(&p)); if(status != 0) throw std::bad_alloc(); return p; } void deallocate(pointer p, std::size_t n) noexcept { _wrapper.deallocate(reinterpret_cast<void**>(&p), n); } pointer allocate(std::size_t n, const_void_pointer) { return allocate(n); } template <class U, class ...Args> void construct(U* p, Args&& ...args) { ::new(p) U(std::forward<Args>(args)...); } template <class U> void destroy(U* p) noexcept { p->~U(); } std::size_t max_size() const noexcept { return std::numeric_limits<size_type>::max(); } MM_plugin_cxx_allocator select_on_container_copy_construction() const { return *this; } using propagate_on_container_copy_assignment = std::false_type; using propagate_on_container_move_assignment = std::false_type; using propagate_on_container_swap = std::false_type; using is_always_equal = std::is_empty<MM_plugin_cxx_allocator>; MM_plugin_wrapper& _wrapper; }; template <class T, class U> bool operator==(MM_plugin_cxx_allocator<T> const&, MM_plugin_cxx_allocator<U> const&) noexcept { return true; } template <class T, class U> bool operator!=(MM_plugin_cxx_allocator<T> const& x, MM_plugin_cxx_allocator<U> const& y) noexcept { return !(x == y); } #undef LOAD_SYMBOL #endif #pragma GCC diagnostic pop #endif // __MM_PLUGIN_ITF_H__
lemma degree_reflect_poly_le: "degree (reflect_poly p) \<le> degree p"
-- Andreas, 2017-12-13, issue #2867 -- Parentheses needed when giving module argument module _ where module M (A : Set) where id : A → A id x = x test : (F : Set → Set) (A : Set) (x : F A) → F A test F A = λ x → x where open M {!F A!} -- Give this -- Expected: M (F A)
open import FRP.LTL.Time using ( Time ; _≤_ ; _<_ ) module FRP.LTL.RSet.Core where -- Reactive types RSet : Set₁ RSet = Time → Set ⟨_⟩ : Set → RSet ⟨ A ⟩ t = A ⟦_⟧ : RSet → Set ⟦ A ⟧ = ∀ {t} → (A t) -- Reactive sets over an interval _[_,_] : RSet → Time → Time → Set A [ s , u ] = ∀ {t} → s ≤ t → t ≤ u → A t _[_,_⟩ : RSet → Time → Time → Set A [ s , u ⟩ = ∀ {t} → s ≤ t → t < u → A t
import cv2 import numpy as np # capturing video through webcam cap = cv2.VideoCapture(0) while (1): _, img = cap.read() hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) or_lower = np.array([22, 60, 200], np.uint8) or_upper = np.array([60, 255, 255], np.uint8) orange = cv2.inRange(hsv, or_lower, or_upper) kernal = np.ones((5, 5), "uint8") orange = cv2.dilate(orange, kernal) res = cv2.bitwise_and(img, img, mask=orange) (_, contours, hierarchy) = cv2.findContours(orange, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) for pic, contour in enumerate(contours): area = cv2.contourArea(contour) if (area > 300): x, y, w, h = cv2.boundingRect(contour) # print(x,y,w,h) img = cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 255), 2) cv2.putText(img, "Yellow", (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 255)) cv2.imshow("CV Test", img) if cv2.waitKey(10) & 0xFF == ord('q'): cap.release() cv2.destroyAllWindows() break
import time import picamera import numpy as np import scipy.misc #vw, vh = (640, 480) vw, vh = (1920, 1440) fps = 60 output = np.empty((vh * vw + (int(vh/2) * int(vw/2) * 2)), dtype=np.uint8) with picamera.PiCamera(resolution=(vw,vh), framerate=fps) as camera: time.sleep(1) print(time.time()) camera.capture('output.jpg', use_video_port=False) #scipy.misc.imsave(filename, output) #print(filename, time.time()) print(time.time())
State Before: α : Type u β : α → Type v inst✝ : FinEnum α ⊢ List.Nodup (toList α) State After: α : Type u β : α → Type v inst✝ : FinEnum α ⊢ List.Nodup (List.map (↑Equiv.symm) (List.finRange (card α))) Tactic: simp [toList] State Before: α : Type u β : α → Type v inst✝ : FinEnum α ⊢ List.Nodup (List.map (↑Equiv.symm) (List.finRange (card α))) State After: no goals Tactic: apply List.Nodup.map <;> [apply Equiv.injective; apply List.nodup_finRange]
But here there is no light ,
(* Author: Alexander Maletzky *) section \<open>Multivariate Polynomials with Power-Products Represented by Polynomial Mappings\<close> theory MPoly_PM imports Quasi_PM_Power_Products begin text \<open>Many notions introduced in this theory for type @{typ "('x \<Rightarrow>\<^sub>0 'a) \<Rightarrow>\<^sub>0 'b"} closely resemble those introduced in @{theory Polynomials.MPoly_Type} for type @{typ "'a mpoly"}.\<close> lemma monomial_single_power: "(monomial c (Poly_Mapping.single x k)) ^ n = monomial (c ^ n) (Poly_Mapping.single x (k * n))" proof - have eq: "(\<Sum>i = 0..<n. Poly_Mapping.single x k) = Poly_Mapping.single x (k * n)" by (induct n, simp_all add: add.commute single_add) show ?thesis by (simp add: punit.monomial_power eq) qed lemma monomial_power_map_scale: "(monomial c t) ^ n = monomial (c ^ n) (n \<cdot> t)" proof - have "(\<Sum>i = 0..<n. t) = (\<Sum>i = 0..<n. 1) \<cdot> t" by (simp only: map_scale_sum_distrib_right map_scale_one_left) thus ?thesis by (simp add: punit.monomial_power) qed lemma times_canc_left: assumes "h * p = h * q" and "h \<noteq> (0::('x::linorder \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 'a::ring_no_zero_divisors)" shows "p = q" proof (rule ccontr) assume "p \<noteq> q" hence "p - q \<noteq> 0" by simp with assms(2) have "h * (p - q) \<noteq> 0" by simp hence "h * p \<noteq> h * q" by (simp add: algebra_simps) thus False using assms(1) .. qed lemma times_canc_right: assumes "p * h = q * h" and "h \<noteq> (0::('x::linorder \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 'a::ring_no_zero_divisors)" shows "p = q" proof (rule ccontr) assume "p \<noteq> q" hence "p - q \<noteq> 0" by simp hence "(p - q) * h \<noteq> 0" using assms(2) by simp hence "p * h \<noteq> q * h" by (simp add: algebra_simps) thus False using assms(1) .. qed subsection \<open>Degree\<close> lemma plus_minus_assoc_pm_nat_1: "s + t - u = (s - (u - t)) + (t - (u::_ \<Rightarrow>\<^sub>0 nat))" by (rule poly_mapping_eqI, simp add: lookup_add lookup_minus) lemma plus_minus_assoc_pm_nat_2: "s + (t - u) = (s + (except (u - t) (- keys s))) + t - (u::_ \<Rightarrow>\<^sub>0 nat)" proof (rule poly_mapping_eqI) fix x show "lookup (s + (t - u)) x = lookup (s + except (u - t) (- keys s) + t - u) x" proof (cases "x \<in> keys s") case True thus ?thesis by (simp add: plus_minus_assoc_pm_nat_1 lookup_add lookup_minus lookup_except) next case False hence "lookup s x = 0" by (simp add: in_keys_iff) with False show ?thesis by (simp add: lookup_add lookup_minus lookup_except) qed qed lemma deg_pm_sum: "deg_pm (sum t A) = (\<Sum>a\<in>A. deg_pm (t a))" by (induct A rule: infinite_finite_induct) (auto simp: deg_pm_plus) lemma deg_pm_mono: "s adds t \<Longrightarrow> deg_pm s \<le> deg_pm (t::_ \<Rightarrow>\<^sub>0 _::add_linorder_min)" by (metis addsE deg_pm_plus le_iff_add) lemma adds_deg_pm_antisym: "s adds t \<Longrightarrow> deg_pm t \<le> deg_pm (s::_ \<Rightarrow>\<^sub>0 _::add_linorder_min) \<Longrightarrow> s = t" by (metis (no_types, lifting) add.right_neutral add.right_neutral add_left_cancel addsE deg_pm_eq_0_iff deg_pm_mono deg_pm_plus dual_order.antisym) lemma deg_pm_minus: assumes "s adds (t::_ \<Rightarrow>\<^sub>0 _::comm_monoid_add)" shows "deg_pm (t - s) = deg_pm t - deg_pm s" proof - from assms have "(t - s) + s = t" by (rule adds_minus) hence "deg_pm t = deg_pm ((t - s) + s)" by simp also have "\<dots> = deg_pm (t - s) + deg_pm s" by (simp only: deg_pm_plus) finally show ?thesis by simp qed lemma adds_group [simp]: "s adds (t::'a \<Rightarrow>\<^sub>0 'b::ab_group_add)" proof (rule addsI) show "t = s + (t - s)" by simp qed lemmas deg_pm_minus_group = deg_pm_minus[OF adds_group] lemma deg_pm_minus_le: "deg_pm (t - s) \<le> deg_pm (t::_ \<Rightarrow>\<^sub>0 nat)" proof - have "keys (t - s) \<subseteq> keys t" by (rule, simp add: lookup_minus in_keys_iff) hence "deg_pm (t - s) = (\<Sum>x\<in>keys t. lookup (t - s) x)" using finite_keys by (rule deg_pm_superset) also have "\<dots> \<le> (\<Sum>x\<in>keys t. lookup t x)" by (rule sum_mono) (simp add: lookup_minus) also have "\<dots> = deg_pm t" by (rule sym, rule deg_pm_superset, fact subset_refl, fact finite_keys) finally show ?thesis . qed lemma minus_id_iff: "t - s = t \<longleftrightarrow> keys t \<inter> keys (s::_ \<Rightarrow>\<^sub>0 nat) = {}" proof assume "t - s = t" { fix x assume "x \<in> keys t" and "x \<in> keys s" hence "0 < lookup t x" and "0 < lookup s x" by (simp_all add: in_keys_iff) hence "lookup (t - s) x \<noteq> lookup t x" by (simp add: lookup_minus) with \<open>t - s = t\<close> have False by simp } thus "keys t \<inter> keys s = {}" by blast next assume *: "keys t \<inter> keys s = {}" show "t - s = t" proof (rule poly_mapping_eqI) fix x have "lookup t x - lookup s x = lookup t x" proof (cases "x \<in> keys t") case True with * have "x \<notin> keys s" by blast thus ?thesis by (simp add: in_keys_iff) next case False thus ?thesis by (simp add: in_keys_iff) qed thus "lookup (t - s) x = lookup t x" by (simp only: lookup_minus) qed qed lemma deg_pm_minus_id_iff: "deg_pm (t - s) = deg_pm t \<longleftrightarrow> keys t \<inter> keys (s::_ \<Rightarrow>\<^sub>0 nat) = {}" proof assume eq: "deg_pm (t - s) = deg_pm t" { fix x assume "x \<in> keys t" and "x \<in> keys s" hence "0 < lookup t x" and "0 < lookup s x" by (simp_all add: in_keys_iff) hence *: "lookup (t - s) x < lookup t x" by (simp add: lookup_minus) have "keys (t - s) \<subseteq> keys t" by (rule, simp add: lookup_minus in_keys_iff) hence "deg_pm (t - s) = (\<Sum>x\<in>keys t. lookup (t - s) x)" using finite_keys by (rule deg_pm_superset) also from finite_keys have "\<dots> < (\<Sum>x\<in>keys t. lookup t x)" proof (rule sum_strict_mono_ex1) show "\<forall>x\<in>keys t. lookup (t - s) x \<le> lookup t x" by (simp add: lookup_minus) next from \<open>x \<in> keys t\<close> * show "\<exists>x\<in>keys t. lookup (t - s) x < lookup t x" .. qed also have "\<dots> = deg_pm t" by (rule sym, rule deg_pm_superset, fact subset_refl, fact finite_keys) finally have False by (simp add: eq) } thus "keys t \<inter> keys s = {}" by blast next assume "keys t \<inter> keys s = {}" hence "t - s = t" by (simp only: minus_id_iff) thus "deg_pm (t - s) = deg_pm t" by (simp only:) qed definition poly_deg :: "(('x \<Rightarrow>\<^sub>0 'a::add_linorder) \<Rightarrow>\<^sub>0 'b::zero) \<Rightarrow> 'a" where "poly_deg p = (if keys p = {} then 0 else Max (deg_pm ` keys p))" definition maxdeg :: "(('x \<Rightarrow>\<^sub>0 'a::add_linorder) \<Rightarrow>\<^sub>0 'b::zero) set \<Rightarrow> 'a" where "maxdeg A = Max (poly_deg ` A)" definition mindeg :: "(('x \<Rightarrow>\<^sub>0 'a::add_linorder) \<Rightarrow>\<^sub>0 'b::zero) set \<Rightarrow> 'a" where "mindeg A = Min (poly_deg ` A)" lemma poly_deg_monomial: "poly_deg (monomial c t) = (if c = 0 then 0 else deg_pm t)" by (simp add: poly_deg_def) lemma poly_deg_monomial_zero [simp]: "poly_deg (monomial c 0) = 0" by (simp add: poly_deg_monomial) lemma poly_deg_zero [simp]: "poly_deg 0 = 0" by (simp only: single_zero[of 0, symmetric] poly_deg_monomial_zero) lemma poly_deg_one [simp]: "poly_deg 1 = 0" by (simp only: single_one[symmetric] poly_deg_monomial_zero) lemma poly_degE: assumes "p \<noteq> 0" obtains t where "t \<in> keys p" and "poly_deg p = deg_pm t" proof - from assms have "poly_deg p = Max (deg_pm ` keys p)" by (simp add: poly_deg_def) also have "\<dots> \<in> deg_pm ` keys p" proof (rule Max_in) from assms show "deg_pm ` keys p \<noteq> {}" by simp qed simp finally obtain t where "t \<in> keys p" and "poly_deg p = deg_pm t" .. thus ?thesis .. qed lemma poly_deg_max_keys: "t \<in> keys p \<Longrightarrow> deg_pm t \<le> poly_deg p" using finite_keys by (auto simp: poly_deg_def) lemma poly_deg_leI: "(\<And>t. t \<in> keys p \<Longrightarrow> deg_pm t \<le> (d::'a::add_linorder_min)) \<Longrightarrow> poly_deg p \<le> d" using finite_keys by (auto simp: poly_deg_def) lemma poly_deg_lessI: "p \<noteq> 0 \<Longrightarrow> (\<And>t. t \<in> keys p \<Longrightarrow> deg_pm t < (d::'a::add_linorder_min)) \<Longrightarrow> poly_deg p < d" using finite_keys by (auto simp: poly_deg_def) lemma poly_deg_zero_imp_monomial: assumes "poly_deg p = (0::'a::add_linorder_min)" shows "monomial (lookup p 0) 0 = p" proof (rule keys_subset_singleton_imp_monomial, rule) fix t assume "t \<in> keys p" have "t = 0" proof (rule ccontr) assume "t \<noteq> 0" hence "deg_pm t \<noteq> 0" by simp hence "0 < deg_pm t" using not_gr_zero by blast also from \<open>t \<in> keys p\<close> have "... \<le> poly_deg p" by (rule poly_deg_max_keys) finally have "poly_deg p \<noteq> 0" by simp from this assms show False .. qed thus "t \<in> {0}" by simp qed lemma poly_deg_plus_le: "poly_deg (p + q) \<le> max (poly_deg p) (poly_deg (q::(_ \<Rightarrow>\<^sub>0 'a::add_linorder_min) \<Rightarrow>\<^sub>0 _))" proof (rule poly_deg_leI) fix t assume "t \<in> keys (p + q)" also have "... \<subseteq> keys p \<union> keys q" by (fact Poly_Mapping.keys_add) finally show "deg_pm t \<le> max (poly_deg p) (poly_deg q)" proof assume "t \<in> keys p" hence "deg_pm t \<le> poly_deg p" by (rule poly_deg_max_keys) thus ?thesis by (simp add: le_max_iff_disj) next assume "t \<in> keys q" hence "deg_pm t \<le> poly_deg q" by (rule poly_deg_max_keys) thus ?thesis by (simp add: le_max_iff_disj) qed qed lemma poly_deg_uminus [simp]: "poly_deg (-p) = poly_deg p" by (simp add: poly_deg_def keys_uminus) lemma poly_deg_minus_le: "poly_deg (p - q) \<le> max (poly_deg p) (poly_deg (q::(_ \<Rightarrow>\<^sub>0 'a::add_linorder_min) \<Rightarrow>\<^sub>0 _))" proof (rule poly_deg_leI) fix t assume "t \<in> keys (p - q)" also have "... \<subseteq> keys p \<union> keys q" by (fact keys_minus) finally show "deg_pm t \<le> max (poly_deg p) (poly_deg q)" proof assume "t \<in> keys p" hence "deg_pm t \<le> poly_deg p" by (rule poly_deg_max_keys) thus ?thesis by (simp add: le_max_iff_disj) next assume "t \<in> keys q" hence "deg_pm t \<le> poly_deg q" by (rule poly_deg_max_keys) thus ?thesis by (simp add: le_max_iff_disj) qed qed lemma poly_deg_times_le: "poly_deg (p * q) \<le> poly_deg p + poly_deg (q::(_ \<Rightarrow>\<^sub>0 'a::add_linorder_min) \<Rightarrow>\<^sub>0 _)" proof (rule poly_deg_leI) fix t assume "t \<in> keys (p * q)" then obtain u v where "u \<in> keys p" and "v \<in> keys q" and "t = u + v" by (rule in_keys_timesE) from \<open>u \<in> keys p\<close> have "deg_pm u \<le> poly_deg p" by (rule poly_deg_max_keys) moreover from \<open>v \<in> keys q\<close> have "deg_pm v \<le> poly_deg q" by (rule poly_deg_max_keys) ultimately show "deg_pm t \<le> poly_deg p + poly_deg q" by (simp add: \<open>t = u + v\<close> deg_pm_plus add_mono) qed lemma poly_deg_times: assumes "p \<noteq> 0" and "q \<noteq> (0::('x::linorder \<Rightarrow>\<^sub>0 'a::add_linorder_min) \<Rightarrow>\<^sub>0 'b::semiring_no_zero_divisors)" shows "poly_deg (p * q) = poly_deg p + poly_deg q" using poly_deg_times_le proof (rule antisym) let ?A = "\<lambda>f. {u. deg_pm u < poly_deg f}" define p1 where "p1 = except p (?A p)" define p2 where "p2 = except p (- ?A p)" define q1 where "q1 = except q (?A q)" define q2 where "q2 = except q (- ?A q)" have deg_p1: "deg_pm t = poly_deg p" if "t \<in> keys p1" for t proof - from that have "t \<in> keys p" and "poly_deg p \<le> deg_pm t" by (simp_all add: p1_def keys_except not_less) from this(1) have "deg_pm t \<le> poly_deg p" by (rule poly_deg_max_keys) thus ?thesis using \<open>poly_deg p \<le> deg_pm t\<close> by (rule antisym) qed have deg_p2: "t \<in> keys p2 \<Longrightarrow> deg_pm t < poly_deg p" for t by (simp add: p2_def keys_except) have deg_q1: "deg_pm t = poly_deg q" if "t \<in> keys q1" for t proof - from that have "t \<in> keys q" and "poly_deg q \<le> deg_pm t" by (simp_all add: q1_def keys_except not_less) from this(1) have "deg_pm t \<le> poly_deg q" by (rule poly_deg_max_keys) thus ?thesis using \<open>poly_deg q \<le> deg_pm t\<close> by (rule antisym) qed have deg_q2: "t \<in> keys q2 \<Longrightarrow> deg_pm t < poly_deg q" for t by (simp add: q2_def keys_except) have p: "p = p1 + p2" unfolding p1_def p2_def by (fact except_decomp) have "p1 \<noteq> 0" proof - from assms(1) obtain t where "t \<in> keys p" and "poly_deg p = deg_pm t" by (rule poly_degE) hence "t \<in> keys p1" by (simp add: p1_def keys_except) thus ?thesis by auto qed have q: "q = q1 + q2" unfolding q1_def q2_def by (fact except_decomp) have "q1 \<noteq> 0" proof - from assms(2) obtain t where "t \<in> keys q" and "poly_deg q = deg_pm t" by (rule poly_degE) hence "t \<in> keys q1" by (simp add: q1_def keys_except) thus ?thesis by auto qed with \<open>p1 \<noteq> 0\<close> have "p1 * q1 \<noteq> 0" by simp hence "keys (p1 * q1) \<noteq> {}" by simp then obtain u where "u \<in> keys (p1 * q1)" by blast then obtain s t where "s \<in> keys p1" and "t \<in> keys q1" and u: "u = s + t" by (rule in_keys_timesE) from \<open>s \<in> keys p1\<close> have "deg_pm s = poly_deg p" by (rule deg_p1) moreover from \<open>t \<in> keys q1\<close> have "deg_pm t = poly_deg q" by (rule deg_q1) ultimately have eq: "poly_deg p + poly_deg q = deg_pm u" by (simp only: u deg_pm_plus) also have "\<dots> \<le> poly_deg (p * q)" proof (rule poly_deg_max_keys) have "u \<notin> keys (p1 * q2 + p2 * q)" proof assume "u \<in> keys (p1 * q2 + p2 * q)" also have "\<dots> \<subseteq> keys (p1 * q2) \<union> keys (p2 * q)" by (rule Poly_Mapping.keys_add) finally have "deg_pm u < poly_deg p + poly_deg q" proof assume "u \<in> keys (p1 * q2)" then obtain s' t' where "s' \<in> keys p1" and "t' \<in> keys q2" and u: "u = s' + t'" by (rule in_keys_timesE) from \<open>s' \<in> keys p1\<close> have "deg_pm s' = poly_deg p" by (rule deg_p1) moreover from \<open>t' \<in> keys q2\<close> have "deg_pm t' < poly_deg q" by (rule deg_q2) ultimately show ?thesis by (simp add: u deg_pm_plus) next assume "u \<in> keys (p2 * q)" then obtain s' t' where "s' \<in> keys p2" and "t' \<in> keys q" and u: "u = s' + t'" by (rule in_keys_timesE) from \<open>s' \<in> keys p2\<close> have "deg_pm s' < poly_deg p" by (rule deg_p2) moreover from \<open>t' \<in> keys q\<close> have "deg_pm t' \<le> poly_deg q" by (rule poly_deg_max_keys) ultimately show ?thesis by (simp add: u deg_pm_plus add_less_le_mono) qed thus False by (simp only: eq) qed with \<open>u \<in> keys (p1 * q1)\<close> have "u \<in> keys (p1 * q1 + (p1 * q2 + p2 * q))" by (rule in_keys_plusI1) thus "u \<in> keys (p * q)" by (simp only: p q algebra_simps) qed finally show "poly_deg p + poly_deg q \<le> poly_deg (p * q)" . qed corollary poly_deg_monom_mult_le: "poly_deg (punit.monom_mult c (t::_ \<Rightarrow>\<^sub>0 'a::add_linorder_min) p) \<le> deg_pm t + poly_deg p" proof - have "poly_deg (punit.monom_mult c t p) \<le> poly_deg (monomial c t) + poly_deg p" by (simp only: times_monomial_left[symmetric] poly_deg_times_le) also have "... \<le> deg_pm t + poly_deg p" by (simp add: poly_deg_monomial) finally show ?thesis . qed lemma poly_deg_monom_mult: assumes "c \<noteq> 0" and "p \<noteq> (0::(_ \<Rightarrow>\<^sub>0 'a::add_linorder_min) \<Rightarrow>\<^sub>0 'b::semiring_no_zero_divisors)" shows "poly_deg (punit.monom_mult c t p) = deg_pm t + poly_deg p" proof (rule order.antisym, fact poly_deg_monom_mult_le) from assms(2) obtain s where "s \<in> keys p" and "poly_deg p = deg_pm s" by (rule poly_degE) have "deg_pm t + poly_deg p = deg_pm (t + s)" by (simp add: \<open>poly_deg p = deg_pm s\<close> deg_pm_plus) also have "... \<le> poly_deg (punit.monom_mult c t p)" proof (rule poly_deg_max_keys) from \<open>s \<in> keys p\<close> show "t + s \<in> keys (punit.monom_mult c t p)" unfolding punit.keys_monom_mult[OF assms(1)] by fastforce qed finally show "deg_pm t + poly_deg p \<le> poly_deg (punit.monom_mult c t p)" . qed lemma poly_deg_map_scale: "poly_deg (c \<cdot> p) = (if c = (0::_::semiring_no_zero_divisors) then 0 else poly_deg p)" by (simp add: poly_deg_def keys_map_scale) lemma poly_deg_sum_le: "((poly_deg (sum f A))::'a::add_linorder_min) \<le> Max (poly_deg ` f ` A)" proof (cases "finite A") case True thus ?thesis proof (induct A) case empty show ?case by simp next case (insert a A) show ?case proof (cases "A = {}") case True thus ?thesis by simp next case False have "poly_deg (sum f (insert a A)) \<le> max (poly_deg (f a)) (poly_deg (sum f A))" by (simp only: comm_monoid_add_class.sum.insert[OF insert(1) insert(2)] poly_deg_plus_le) also have "... \<le> max (poly_deg (f a)) (Max (poly_deg ` f ` A))" using insert(3) max.mono by blast also have "... = (Max (poly_deg ` f ` (insert a A)))" using False by (simp add: insert(1)) finally show ?thesis . qed qed next case False thus ?thesis by simp qed lemma poly_deg_prod_le: "((poly_deg (prod f A))::'a::add_linorder_min) \<le> (\<Sum>a\<in>A. poly_deg (f a))" proof (cases "finite A") case True thus ?thesis proof (induct A) case empty show ?case by simp next case (insert a A) have "poly_deg (prod f (insert a A)) \<le> (poly_deg (f a)) + (poly_deg (prod f A))" by (simp only: comm_monoid_mult_class.prod.insert[OF insert(1) insert(2)] poly_deg_times_le) also have "... \<le> (poly_deg (f a)) + (\<Sum>a\<in>A. poly_deg (f a))" using insert(3) add_le_cancel_left by blast also have "... = (\<Sum>a\<in>insert a A. poly_deg (f a))" by (simp add: insert(1) insert(2)) finally show ?case . qed next case False thus ?thesis by simp qed lemma maxdeg_max: assumes "finite A" and "p \<in> A" shows "poly_deg p \<le> maxdeg A" unfolding maxdeg_def using assms by auto lemma mindeg_min: assumes "finite A" and "p \<in> A" shows "mindeg A \<le> poly_deg p" unfolding mindeg_def using assms by auto subsection \<open>Indeterminates\<close> definition indets :: "(('x \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 'b::zero) \<Rightarrow> 'x set" where "indets p = \<Union> (keys ` keys p)" definition PPs :: "'x set \<Rightarrow> ('x \<Rightarrow>\<^sub>0 nat) set" (".[(_)]") where "PPs X = {t. keys t \<subseteq> X}" definition Polys :: "'x set \<Rightarrow> (('x \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 'b::zero) set" ("P[(_)]") where "Polys X = {p. keys p \<subseteq> .[X]}" subsubsection \<open>@{const indets}\<close> lemma in_indetsI: assumes "x \<in> keys t" and "t \<in> keys p" shows "x \<in> indets p" using assms by (auto simp add: indets_def) lemma keys_subset_indets: "t \<in> keys p \<Longrightarrow> keys t \<subseteq> indets p" by (auto dest: in_indetsI) lemma indets_empty_imp_monomial: assumes "indets p = {}" shows "monomial (lookup p 0) 0 = p" proof (rule keys_subset_singleton_imp_monomial, rule) fix t assume "t \<in> keys p" have "t = 0" proof (rule ccontr) assume "t \<noteq> 0" hence "keys t \<noteq> {}" by simp then obtain x where "x \<in> keys t" by blast from this \<open>t \<in> keys p\<close> have "x \<in> indets p" by (rule in_indetsI) with assms show False by simp qed thus "t \<in> {0}" by simp qed lemma finite_indets: "finite (indets p)" by (simp only: indets_def, rule finite_UN_I, (rule finite_keys)+) lemma indets_zero [simp]: "indets 0 = {}" by (simp add: indets_def) lemma indets_one [simp]: "indets 1 = {}" by (simp add: indets_def) lemma indets_monomial_single_subset: "indets (monomial c (Poly_Mapping.single v k)) \<subseteq> {v}" proof fix x assume "x \<in> indets (monomial c (Poly_Mapping.single v k))" then have "x = v" unfolding indets_def by (metis UN_E lookup_eq_zero_in_keys_contradict lookup_single_not_eq) thus "x \<in> {v}" by simp qed lemma indets_monomial_single: assumes "c \<noteq> 0" and "k \<noteq> 0" shows "indets (monomial c (Poly_Mapping.single v k)) = {v}" proof (rule, fact indets_monomial_single_subset, simp) from assms show "v \<in> indets (monomial c (monomial k v))" by (simp add: indets_def) qed lemma indets_monomial: assumes "c \<noteq> 0" shows "indets (monomial c t) = keys t" proof (rule antisym; rule subsetI) fix x assume "x \<in> indets (monomial c t)" then have "lookup t x \<noteq> 0" unfolding indets_def by (metis UN_E lookup_eq_zero_in_keys_contradict lookup_single_not_eq) thus "x \<in> keys t" by (meson lookup_not_eq_zero_eq_in_keys) next fix x assume "x \<in> keys t" then have "lookup t x \<noteq> 0" by (meson lookup_not_eq_zero_eq_in_keys) thus "x \<in> indets (monomial c t)" unfolding indets_def using assms by (metis UN_iff lookup_not_eq_zero_eq_in_keys lookup_single_eq) qed lemma indets_monomial_subset: "indets (monomial c t) \<subseteq> keys t" by (cases "c = 0", simp_all add: indets_def) lemma indets_monomial_zero [simp]: "indets (monomial c 0) = {}" by (simp add: indets_def) lemma indets_plus_subset: "indets (p + q) \<subseteq> indets p \<union> indets q" proof fix x assume "x \<in> indets (p + q)" then obtain t where "x \<in> keys t" and "t \<in> keys (p + q)" by (metis UN_E indets_def) hence "t \<in> keys p \<union> keys q" by (metis Poly_Mapping.keys_add subsetCE) thus "x \<in> indets p \<union> indets q" using indets_def \<open>x \<in> keys t\<close> by fastforce qed lemma indets_uminus [simp]: "indets (-p) = indets p" by (simp add: indets_def keys_uminus) lemma indets_minus_subset: "indets (p - q) \<subseteq> indets p \<union> indets q" proof fix x assume "x \<in> indets (p - q)" then obtain t where "x \<in> keys t" and "t \<in> keys (p - q)" by (metis UN_E indets_def) hence "t \<in> keys p \<union> keys q" by (metis keys_minus subsetCE) thus "x \<in> indets p \<union> indets q" using indets_def \<open>x \<in> keys t\<close> by fastforce qed lemma indets_times_subset: "indets (p * q) \<subseteq> indets p \<union> indets (q::(_ \<Rightarrow>\<^sub>0 _::cancel_comm_monoid_add) \<Rightarrow>\<^sub>0 _)" proof fix x assume "x \<in> indets (p * q)" then obtain t where "t \<in> keys (p * q)" and "x \<in> keys t" unfolding indets_def by blast from this(1) obtain u v where "u \<in> keys p" "v \<in> keys q" and "t = u + v" by (rule in_keys_timesE) hence "x \<in> keys u \<union> keys v" by (metis \<open>x \<in> keys t\<close> Poly_Mapping.keys_add subsetCE) thus "x \<in> indets p \<union> indets q" unfolding indets_def using \<open>u \<in> keys p\<close> \<open>v \<in> keys q\<close> by blast qed corollary indets_monom_mult_subset: "indets (punit.monom_mult c t p) \<subseteq> keys t \<union> indets p" proof - have "indets (punit.monom_mult c t p) \<subseteq> indets (monomial c t) \<union> indets p" by (simp only: times_monomial_left[symmetric] indets_times_subset) also have "... \<subseteq> keys t \<union> indets p" using indets_monomial_subset[of t c] by blast finally show ?thesis . qed lemma indets_monom_mult: assumes "c \<noteq> 0" and "p \<noteq> (0::('x \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 'b::semiring_no_zero_divisors)" shows "indets (punit.monom_mult c t p) = keys t \<union> indets p" proof (rule, fact indets_monom_mult_subset, rule) fix x assume "x \<in> keys t \<union> indets p" thus "x \<in> indets (punit.monom_mult c t p)" proof assume "x \<in> keys t" from assms(2) have "keys p \<noteq> {}" by simp then obtain s where "s \<in> keys p" by blast hence "t + s \<in> (+) t ` keys p" by fastforce also from assms(1) have "... = keys (punit.monom_mult c t p)" by (simp add: punit.keys_monom_mult) finally have "t + s \<in> keys (punit.monom_mult c t p)" . show ?thesis proof (rule in_indetsI) from \<open>x \<in> keys t\<close> show "x \<in> keys (t + s)" by (simp add: keys_plus_ninv_comm_monoid_add) qed fact next assume "x \<in> indets p" then obtain s where "s \<in> keys p" and "x \<in> keys s" by (rule in_indetsE) from this(1) have "t + s \<in> (+) t ` keys p" by fastforce also from assms(1) have "... = keys (punit.monom_mult c t p)" by (simp add: punit.keys_monom_mult) finally have "t + s \<in> keys (punit.monom_mult c t p)" . show ?thesis proof (rule in_indetsI) from \<open>x \<in> keys s\<close> show "x \<in> keys (t + s)" by (simp add: keys_plus_ninv_comm_monoid_add) qed fact qed qed lemma indets_sum_subset: "indets (sum f A) \<subseteq> (\<Union>a\<in>A. indets (f a))" proof (cases "finite A") case True thus ?thesis proof (induct A) case empty show ?case by simp next case (insert a A) have "indets (sum f (insert a A)) \<subseteq> indets (f a) \<union> indets (sum f A)" by (simp only: comm_monoid_add_class.sum.insert[OF insert(1) insert(2)] indets_plus_subset) also have "... \<subseteq> indets (f a) \<union> (\<Union>a\<in>A. indets (f a))" using insert(3) by blast also have "... = (\<Union>a\<in>insert a A. indets (f a))" by simp finally show ?case . qed next case False thus ?thesis by simp qed lemma indets_prod_subset: "indets (prod (f::_ \<Rightarrow> ((_ \<Rightarrow>\<^sub>0 _::cancel_comm_monoid_add) \<Rightarrow>\<^sub>0 _)) A) \<subseteq> (\<Union>a\<in>A. indets (f a))" proof (cases "finite A") case True thus ?thesis proof (induct A) case empty show ?case by simp next case (insert a A) have "indets (prod f (insert a A)) \<subseteq> indets (f a) \<union> indets (prod f A)" by (simp only: comm_monoid_mult_class.prod.insert[OF insert(1) insert(2)] indets_times_subset) also have "... \<subseteq> indets (f a) \<union> (\<Union>a\<in>A. indets (f a))" using insert(3) by blast also have "... = (\<Union>a\<in>insert a A. indets (f a))" by simp finally show ?case . qed next case False thus ?thesis by simp qed lemma indets_power_subset: "indets (p ^ n) \<subseteq> indets (p::('x \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 'b::comm_semiring_1)" proof - have "p ^ n = (\<Prod>i=0..<n. p)" by simp also have "indets ... \<subseteq> (\<Union>i\<in>{0..<n}. indets p)" by (fact indets_prod_subset) also have "... \<subseteq> indets p" by simp finally show ?thesis . qed lemma indets_empty_iff_poly_deg_zero: "indets p = {} \<longleftrightarrow> poly_deg p = 0" proof assume "indets p = {}" hence "monomial (lookup p 0) 0 = p" by (rule indets_empty_imp_monomial) moreover have "poly_deg (monomial (lookup p 0) 0) = 0" by simp ultimately show "poly_deg p = 0" by metis next assume "poly_deg p = 0" hence "monomial (lookup p 0) 0 = p" by (rule poly_deg_zero_imp_monomial) moreover have "indets (monomial (lookup p 0) 0) = {}" by simp ultimately show "indets p = {}" by metis qed subsubsection \<open>@{const PPs}\<close> lemma PPsI: "keys t \<subseteq> X \<Longrightarrow> t \<in> .[X]" by (simp add: PPs_def) lemma PPsD: "t \<in> .[X] \<Longrightarrow> keys t \<subseteq> X" by (simp add: PPs_def) lemma PPs_empty [simp]: ".[{}] = {0}" by (simp add: PPs_def) lemma PPs_UNIV [simp]: ".[UNIV] = UNIV" by (simp add: PPs_def) lemma PPs_singleton: ".[{x}] = range (Poly_Mapping.single x)" proof (rule set_eqI) fix t show "t \<in> .[{x}] \<longleftrightarrow> t \<in> range (Poly_Mapping.single x)" proof assume "t \<in> .[{x}]" hence "keys t \<subseteq> {x}" by (rule PPsD) hence "Poly_Mapping.single x (lookup t x) = t" by (rule keys_subset_singleton_imp_monomial) from this[symmetric] UNIV_I show "t \<in> range (Poly_Mapping.single x)" .. next assume "t \<in> range (Poly_Mapping.single x)" then obtain e where "t = Poly_Mapping.single x e" .. thus "t \<in> .[{x}]" by (simp add: PPs_def) qed qed lemma zero_in_PPs: "0 \<in> .[X]" by (simp add: PPs_def) lemma PPs_mono: "X \<subseteq> Y \<Longrightarrow> .[X] \<subseteq> .[Y]" by (auto simp: PPs_def) lemma PPs_closed_single: assumes "x \<in> X" shows "Poly_Mapping.single x e \<in> .[X]" proof (rule PPsI) have "keys (Poly_Mapping.single x e) \<subseteq> {x}" by simp also from assms have "... \<subseteq> X" by simp finally show "keys (Poly_Mapping.single x e) \<subseteq> X" . qed lemma PPs_closed_plus: assumes "s \<in> .[X]" and "t \<in> .[X]" shows "s + t \<in> .[X]" proof - have "keys (s + t) \<subseteq> keys s \<union> keys t" by (fact Poly_Mapping.keys_add) also from assms have "... \<subseteq> X" by (simp add: PPs_def) finally show ?thesis by (rule PPsI) qed lemma PPs_closed_minus: assumes "s \<in> .[X]" shows "s - t \<in> .[X]" proof - have "keys (s - t) \<subseteq> keys s" by (metis lookup_minus lookup_not_eq_zero_eq_in_keys subsetI zero_diff) also from assms have "... \<subseteq> X" by (rule PPsD) finally show ?thesis by (rule PPsI) qed lemma PPs_closed_adds: assumes "s \<in> .[X]" and "t adds s" shows "t \<in> .[X]" proof - from assms(2) have "s - (s - t) = t" by (metis add_minus_2 adds_minus) moreover from assms(1) have "s - (s - t) \<in> .[X]" by (rule PPs_closed_minus) ultimately show ?thesis by simp qed lemma PPs_closed_lcs: assumes "s \<in> .[X]" and "t \<in> .[X]" shows "lcs s t \<in> .[X]" proof - from assms have "s + t \<in> .[X]" by (rule PPs_closed_plus) hence "(s + t) - gcs s t \<in> .[X]" by (rule PPs_closed_minus) thus ?thesis by (simp add: gcs_plus_lcs[of s t, symmetric]) qed lemma PPs_closed_except': "t \<in> .[X] \<Longrightarrow> except t Y \<in> .[X - Y]" by (auto simp: keys_except PPs_def) lemma PPs_closed_except: "t \<in> .[X] \<Longrightarrow> except t Y \<in> .[X]" by (auto simp: keys_except PPs_def) lemma PPs_UnI: assumes "tx \<in> .[X]" and "ty \<in> .[Y]" and "t = tx + ty" shows "t \<in> .[X \<union> Y]" proof - from assms(1) have "tx \<in> .[X \<union> Y]" by rule (simp add: PPs_mono) moreover from assms(2) have "ty \<in> .[X \<union> Y]" by rule (simp add: PPs_mono) ultimately show ?thesis unfolding assms(3) by (rule PPs_closed_plus) qed lemma PPs_UnE: assumes "t \<in> .[X \<union> Y]" obtains tx ty where "tx \<in> .[X]" and "ty \<in> .[Y]" and "t = tx + ty" proof - from assms have "keys t \<subseteq> X \<union> Y" by (rule PPsD) define tx where "tx = except t (- X)" have "keys tx \<subseteq> X" by (simp add: tx_def keys_except) hence "tx \<in> .[X]" by (simp add: PPs_def) have "tx adds t" by (simp add: tx_def adds_poly_mappingI le_fun_def lookup_except) from adds_minus[OF this] have "t = tx + (t - tx)" by (simp only: ac_simps) have "t - tx \<in> .[Y]" proof (rule PPsI, rule) fix x assume "x \<in> keys (t - tx)" also have "... \<subseteq> keys t \<union> keys tx" by (rule keys_minus) also from \<open>keys t \<subseteq> X \<union> Y\<close> \<open>keys tx \<subseteq> X\<close> have "... \<subseteq> X \<union> Y" by blast finally show "x \<in> Y" proof assume "x \<in> X" hence "x \<notin> keys (t - tx)" by (simp add: tx_def lookup_except lookup_minus in_keys_iff) thus ?thesis using \<open>x \<in> keys (t - tx)\<close> .. qed qed with \<open>tx \<in> .[X]\<close> show ?thesis using \<open>t = tx + (t - tx)\<close> .. qed lemma PPs_Un: ".[X \<union> Y] = (\<Union>t\<in>.[X]. (+) t ` .[Y])" (is "?A = ?B") proof (rule set_eqI) fix t show "t \<in> ?A \<longleftrightarrow> t \<in> ?B" proof assume "t \<in> ?A" then obtain tx ty where "tx \<in> .[X]" and "ty \<in> .[Y]" and "t = tx + ty" by (rule PPs_UnE) from this(2) have "t \<in> (+) tx ` .[Y]" unfolding \<open>t = tx + ty\<close> by (rule imageI) with \<open>tx \<in> .[X]\<close> show "t \<in> ?B" .. next assume "t \<in> ?B" then obtain tx where "tx \<in> .[X]" and "t \<in> (+) tx ` .[Y]" .. from this(2) obtain ty where "ty \<in> .[Y]" and "t = tx + ty" .. with \<open>tx \<in> .[X]\<close> show "t \<in> ?A" by (rule PPs_UnI) qed qed corollary PPs_insert: ".[insert x X] = (\<Union>e. (+) (Poly_Mapping.single x e) ` .[X])" proof - have ".[insert x X] = .[{x} \<union> X]" by simp also have "... = (\<Union>t\<in>.[{x}]. (+) t ` .[X])" by (fact PPs_Un) also have "... = (\<Union>e. (+) (Poly_Mapping.single x e) ` .[X])" by (simp add: PPs_singleton) finally show ?thesis . qed corollary PPs_insertI: assumes "tx \<in> .[X]" and "t = Poly_Mapping.single x e + tx" shows "t \<in> .[insert x X]" proof - from assms(1) have "t \<in> (+) (Poly_Mapping.single x e) ` .[X]" unfolding assms(2) by (rule imageI) with UNIV_I show ?thesis unfolding PPs_insert by (rule UN_I) qed corollary PPs_insertE: assumes "t \<in> .[insert x X]" obtains e tx where "tx \<in> .[X]" and "t = Poly_Mapping.single x e + tx" proof - from assms obtain e where "t \<in> (+) (Poly_Mapping.single x e) ` .[X]" unfolding PPs_insert .. then obtain tx where "tx \<in> .[X]" and "t = Poly_Mapping.single x e + tx" .. thus ?thesis .. qed lemma PPs_Int: ".[X \<inter> Y] = .[X] \<inter> .[Y]" by (auto simp: PPs_def) lemma PPs_INT: ".[\<Inter> X] = \<Inter> (PPs ` X)" by (auto simp: PPs_def) subsubsection \<open>@{const Polys}\<close> lemma Polys_alt: "P[X] = {p. indets p \<subseteq> X}" by (auto simp: Polys_def PPs_def indets_def) lemma PolysI: "keys p \<subseteq> .[X] \<Longrightarrow> p \<in> P[X]" by (simp add: Polys_def) lemma PolysI_alt: "indets p \<subseteq> X \<Longrightarrow> p \<in> P[X]" by (simp add: Polys_alt) lemma PolysD: assumes "p \<in> P[X]" shows "keys p \<subseteq> .[X]" and "indets p \<subseteq> X" using assms by (simp add: Polys_def, simp add: Polys_alt) lemma Polys_empty: "P[{}] = ((range (Poly_Mapping.single 0))::(('x \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 'b::zero) set)" proof (rule set_eqI) fix p :: "('x \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 'b::zero" show "p \<in> P[{}] \<longleftrightarrow> p \<in> range (Poly_Mapping.single 0)" proof assume "p \<in> P[{}]" hence "keys p \<subseteq> .[{}]" by (rule PolysD) also have "... = {0}" by simp finally have "keys p \<subseteq> {0}" . hence "Poly_Mapping.single 0 (lookup p 0) = p" by (rule keys_subset_singleton_imp_monomial) from this[symmetric] UNIV_I show "p \<in> range (Poly_Mapping.single 0)" .. next assume "p \<in> range (Poly_Mapping.single 0)" then obtain c where "p = monomial c 0" .. thus "p \<in> P[{}]" by (simp add: Polys_def) qed qed lemma Polys_UNIV [simp]: "P[UNIV] = UNIV" by (simp add: Polys_def) lemma zero_in_Polys: "0 \<in> P[X]" by (simp add: Polys_def) lemma one_in_Polys: "1 \<in> P[X]" by (simp add: Polys_def zero_in_PPs) lemma Polys_mono: "X \<subseteq> Y \<Longrightarrow> P[X] \<subseteq> P[Y]" by (auto simp: Polys_alt) lemma Polys_closed_monomial: "t \<in> .[X] \<Longrightarrow> monomial c t \<in> P[X]" using indets_monomial_subset[where c=c and t=t] by (auto simp: Polys_alt PPs_def) lemma Polys_closed_plus: "p \<in> P[X] \<Longrightarrow> q \<in> P[X] \<Longrightarrow> p + q \<in> P[X]" using indets_plus_subset[of p q] by (auto simp: Polys_alt PPs_def) lemma Polys_closed_uminus: "p \<in> P[X] \<Longrightarrow> -p \<in> P[X]" by (simp add: Polys_def keys_uminus) lemma Polys_closed_minus: "p \<in> P[X] \<Longrightarrow> q \<in> P[X] \<Longrightarrow> p - q \<in> P[X]" using indets_minus_subset[of p q] by (auto simp: Polys_alt PPs_def) lemma Polys_closed_monom_mult: "t \<in> .[X] \<Longrightarrow> p \<in> P[X] \<Longrightarrow> punit.monom_mult c t p \<in> P[X]" using indets_monom_mult_subset[of c t p] by (auto simp: Polys_alt PPs_def) corollary Polys_closed_map_scale: "p \<in> P[X] \<Longrightarrow> (c::_::semiring_0) \<cdot> p \<in> P[X]" unfolding punit.map_scale_eq_monom_mult using zero_in_PPs by (rule Polys_closed_monom_mult) lemma Polys_closed_times: "p \<in> P[X] \<Longrightarrow> q \<in> P[X] \<Longrightarrow> p * q \<in> P[X]" using indets_times_subset[of p q] by (auto simp: Polys_alt PPs_def) lemma Polys_closed_power: "p \<in> P[X] \<Longrightarrow> p ^ m \<in> P[X]" by (induct m) (auto intro: one_in_Polys Polys_closed_times) lemma Polys_closed_sum: "(\<And>a. a \<in> A \<Longrightarrow> f a \<in> P[X]) \<Longrightarrow> sum f A \<in> P[X]" by (induct A rule: infinite_finite_induct) (auto intro: zero_in_Polys Polys_closed_plus) lemma Polys_closed_prod: "(\<And>a. a \<in> A \<Longrightarrow> f a \<in> P[X]) \<Longrightarrow> prod f A \<in> P[X]" by (induct A rule: infinite_finite_induct) (auto intro: one_in_Polys Polys_closed_times) lemma Polys_closed_except: "p \<in> P[X] \<Longrightarrow> except p T \<in> P[X]" by (auto intro!: PolysI simp: keys_except dest!: PolysD(1)) lemma times_in_PolysD: assumes "p * q \<in> P[X]" and "p \<in> P[X]" and "p \<noteq> (0::('x::linorder \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 'a::semiring_no_zero_divisors)" shows "q \<in> P[X]" proof - define qX where "qX = except q (- .[X])" define qY where "qY = except q .[X]" have q: "q = qX + qY" by (simp only: qX_def qY_def add.commute flip: except_decomp) have "qX \<in> P[X]" by (rule PolysI) (simp add: qX_def keys_except) with assms(2) have "p * qX \<in> P[X]" by (rule Polys_closed_times) show ?thesis proof (cases "qY = 0") case True with \<open>qX \<in> P[X]\<close> show ?thesis by (simp add: q) next case False with assms(3) have "p * qY \<noteq> 0" by simp hence "keys (p * qY) \<noteq> {}" by simp then obtain t where "t \<in> keys (p * qY)" by blast then obtain t1 t2 where "t2 \<in> keys qY" and t: "t = t1 + t2" by (rule in_keys_timesE) have "t \<notin> .[X]" unfolding t proof assume "t1 + t2 \<in> .[X]" hence "t1 + t2 - t1 \<in> .[X]" by (rule PPs_closed_minus) hence "t2 \<in> .[X]" by simp with \<open>t2 \<in> keys qY\<close> show False by (simp add: qY_def keys_except) qed have "t \<notin> keys (p * qX)" proof assume "t \<in> keys (p * qX)" also from \<open>p * qX \<in> P[X]\<close> have "\<dots> \<subseteq> .[X]" by (rule PolysD) finally have "t \<in> .[X]" . with \<open>t \<notin> .[X]\<close> show False .. qed with \<open>t \<in> keys (p * qY)\<close> have "t \<in> keys (p * qX + p * qY)" by (rule in_keys_plusI2) also have "\<dots> = keys (p * q)" by (simp only: q algebra_simps) finally have "p * q \<notin> P[X]" using \<open>t \<notin> .[X]\<close> by (auto simp: Polys_def) thus ?thesis using assms(1) .. qed qed lemma poly_mapping_plus_induct_Polys [consumes 1, case_names 0 plus]: assumes "p \<in> P[X]" and "P 0" and "\<And>p c t. t \<in> .[X] \<Longrightarrow> p \<in> P[X] \<Longrightarrow> c \<noteq> 0 \<Longrightarrow> t \<notin> keys p \<Longrightarrow> P p \<Longrightarrow> P (monomial c t + p)" shows "P p" using assms(1) proof (induct p rule: poly_mapping_plus_induct) case 1 show ?case by (fact assms(2)) next case step: (2 p c t) from step.hyps(1) have 1: "keys (monomial c t) = {t}" by simp also from step.hyps(2) have "\<dots> \<inter> keys p = {}" by simp finally have "keys (monomial c t + p) = keys (monomial c t) \<union> keys p" by (rule keys_add[symmetric]) hence "keys (monomial c t + p) = insert t (keys p)" by (simp only: 1 flip: insert_is_Un) moreover from step.prems(1) have "keys (monomial c t + p) \<subseteq> .[X]" by (rule PolysD) ultimately have "t \<in> .[X]" and "keys p \<subseteq> .[X]" by blast+ from this(2) have "p \<in> P[X]" by (rule PolysI) hence "P p" by (rule step.hyps) with \<open>t \<in> .[X]\<close> \<open>p \<in> P[X]\<close> step.hyps(1, 2) show ?case by (rule assms(3)) qed lemma Polys_Int: "P[X \<inter> Y] = P[X] \<inter> P[Y]" by (auto simp: Polys_def PPs_Int) lemma Polys_INT: "P[\<Inter> X] = \<Inter> (Polys ` X)" by (auto simp: Polys_def PPs_INT) subsection \<open>Substitution Homomorphism\<close> text \<open>The substitution homomorphism defined here is more general than @{const insertion}, since it replaces indeterminates by @{emph \<open>polynomials\<close>} rather than coefficients, and therefore constructs new polynomials.\<close> definition subst_pp :: "('x \<Rightarrow> (('y \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 'a)) \<Rightarrow> ('x \<Rightarrow>\<^sub>0 nat) \<Rightarrow> (('y \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 'a::comm_semiring_1)" where "subst_pp f t = (\<Prod>x\<in>keys t. (f x) ^ (lookup t x))" definition poly_subst :: "('x \<Rightarrow> (('y \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 'a)) \<Rightarrow> (('x \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 'a) \<Rightarrow> (('y \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 'a::comm_semiring_1)" where "poly_subst f p = (\<Sum>t\<in>keys p. punit.monom_mult (lookup p t) 0 (subst_pp f t))" lemma subst_pp_alt: "subst_pp f t = (\<Prod>x. (f x) ^ (lookup t x))" proof - from finite_keys have "subst_pp f t = (\<Prod>x. if x \<in> keys t then (f x) ^ (lookup t x) else 1)" unfolding subst_pp_def by (rule Prod_any.conditionalize) also have "... = (\<Prod>x. (f x) ^ (lookup t x))" by (rule Prod_any.cong) (simp add: in_keys_iff) finally show ?thesis . qed lemma subst_pp_zero [simp]: "subst_pp f 0 = 1" by (simp add: subst_pp_def) lemma subst_pp_trivial_not_zero: assumes "t \<noteq> 0" shows "subst_pp (\<lambda>_. 0) t = (0::(_ \<Rightarrow>\<^sub>0 'b::comm_semiring_1))" unfolding subst_pp_def using finite_keys proof (rule prod_zero) from assms have "keys t \<noteq> {}" by simp then obtain x where "x \<in> keys t" by blast thus "\<exists>x\<in>keys t. 0 ^ lookup t x = (0::(_ \<Rightarrow>\<^sub>0 'b))" proof from \<open>x \<in> keys t\<close> have "0 < lookup t x" by (simp add: in_keys_iff) thus "0 ^ lookup t x = (0::(_ \<Rightarrow>\<^sub>0 'b))" by (rule Power.semiring_1_class.zero_power) qed qed lemma subst_pp_single: "subst_pp f (Poly_Mapping.single x e) = (f x) ^ e" by (simp add: subst_pp_def) corollary subst_pp_trivial: "subst_pp (\<lambda>_. 0) t = (if t = 0 then 1 else 0)" by (simp split: if_split add: subst_pp_trivial_not_zero) corollary finite_power_lookup_not_one: "finite {x. f x ^ (lookup t x) \<noteq> 1}" by (rule finite_subset, fact power_lookup_not_one_subset_keys, fact finite_keys) lemma subst_pp_plus: "subst_pp f (s + t) = subst_pp f s * subst_pp f t" by (simp add: subst_pp_alt lookup_add power_add, rule Prod_any.distrib, (fact finite_power_lookup_not_one)+) lemma subst_pp_id: assumes "\<And>x. x \<in> keys t \<Longrightarrow> f x = monomial 1 (Poly_Mapping.single x 1)" shows "subst_pp f t = monomial 1 t" proof - have "subst_pp f t = (\<Prod>x\<in>keys t. monomial 1 (Poly_Mapping.single x (lookup t x)))" proof (simp only: subst_pp_def, rule prod.cong, fact refl) fix x assume "x \<in> keys t" thus "f x ^ lookup t x = monomial 1 (Poly_Mapping.single x (lookup t x))" by (simp add: assms monomial_single_power) qed also have "... = monomial 1 t" by (simp add: punit.monomial_prod_sum[symmetric] poly_mapping_sum_monomials) finally show ?thesis . qed lemma in_indets_subst_ppE: assumes "x \<in> indets (subst_pp f t)" obtains y where "y \<in> keys t" and "x \<in> indets (f y)" proof - note assms also have "indets (subst_pp f t) \<subseteq> (\<Union>y\<in>keys t. indets ((f y) ^ (lookup t y)))" unfolding subst_pp_def by (rule indets_prod_subset) finally obtain y where "y \<in> keys t" and "x \<in> indets ((f y) ^ (lookup t y))" .. note this(2) also have "indets ((f y) ^ (lookup t y)) \<subseteq> indets (f y)" by (rule indets_power_subset) finally have "x \<in> indets (f y)" . with \<open>y \<in> keys t\<close> show ?thesis .. qed lemma subst_pp_by_monomials: assumes "\<And>y. y \<in> keys t \<Longrightarrow> f y = monomial (c y) (s y)" shows "subst_pp f t = monomial (\<Prod>y\<in>keys t. (c y) ^ lookup t y) (\<Sum>y\<in>keys t. lookup t y \<cdot> s y)" by (simp add: subst_pp_def assms monomial_power_map_scale punit.monomial_prod_sum) lemma poly_deg_subst_pp_eq_zeroI: assumes "\<And>x. x \<in> keys t \<Longrightarrow> poly_deg (f x) = 0" shows "poly_deg (subst_pp f t) = 0" proof - have "poly_deg (subst_pp f t) \<le> (\<Sum>x\<in>keys t. poly_deg ((f x) ^ (lookup t x)))" unfolding subst_pp_def by (fact poly_deg_prod_le) also have "... = 0" proof (rule sum.neutral, rule) fix x assume "x \<in> keys t" hence "poly_deg (f x) = 0" by (rule assms) have "f x ^ lookup t x = (\<Prod>i=0..<lookup t x. f x)" by simp also have "poly_deg ... \<le> (\<Sum>i=0..<lookup t x. poly_deg (f x))" by (rule poly_deg_prod_le) also have "... = 0" by (simp add: \<open>poly_deg (f x) = 0\<close>) finally show "poly_deg (f x ^ lookup t x) = 0" by simp qed finally show ?thesis by simp qed lemma poly_deg_subst_pp_le: assumes "\<And>x. x \<in> keys t \<Longrightarrow> poly_deg (f x) \<le> 1" shows "poly_deg (subst_pp f t) \<le> deg_pm t" proof - have "poly_deg (subst_pp f t) \<le> (\<Sum>x\<in>keys t. poly_deg ((f x) ^ (lookup t x)))" unfolding subst_pp_def by (fact poly_deg_prod_le) also have "... \<le> (\<Sum>x\<in>keys t. lookup t x)" proof (rule sum_mono) fix x assume "x \<in> keys t" hence "poly_deg (f x) \<le> 1" by (rule assms) have "f x ^ lookup t x = (\<Prod>i=0..<lookup t x. f x)" by simp also have "poly_deg ... \<le> (\<Sum>i=0..<lookup t x. poly_deg (f x))" by (rule poly_deg_prod_le) also from \<open>poly_deg (f x) \<le> 1\<close> have "... \<le> (\<Sum>i=0..<lookup t x. 1)" by (rule sum_mono) finally show "poly_deg (f x ^ lookup t x) \<le> lookup t x" by simp qed also have "... = deg_pm t" by (rule deg_pm_superset[symmetric], fact subset_refl, fact finite_keys) finally show ?thesis by simp qed lemma poly_subst_alt: "poly_subst f p = (\<Sum>t. punit.monom_mult (lookup p t) 0 (subst_pp f t))" proof - from finite_keys have "poly_subst f p = (\<Sum>t. if t \<in> keys p then punit.monom_mult (lookup p t) 0 (subst_pp f t) else 0)" unfolding poly_subst_def by (rule Sum_any.conditionalize) also have "\<dots> = (\<Sum>t. punit.monom_mult (lookup p t) 0 (subst_pp f t))" by (rule Sum_any.cong) (simp add: in_keys_iff) finally show ?thesis . qed lemma poly_subst_trivial [simp]: "poly_subst (\<lambda>_. 0) p = monomial (lookup p 0) 0" by (simp add: poly_subst_def subst_pp_trivial if_distrib in_keys_iff cong: if_cong) (metis mult.right_neutral times_monomial_left) lemma poly_subst_zero [simp]: "poly_subst f 0 = 0" by (simp add: poly_subst_def) lemma monom_mult_lookup_not_zero_subset_keys: "{t. punit.monom_mult (lookup p t) 0 (subst_pp f t) \<noteq> 0} \<subseteq> keys p" proof (rule, simp) fix t assume "punit.monom_mult (lookup p t) 0 (subst_pp f t) \<noteq> 0" thus "t \<in> keys p" unfolding in_keys_iff by (metis punit.monom_mult_zero_left) qed corollary finite_monom_mult_lookup_not_zero: "finite {t. punit.monom_mult (lookup p t) 0 (subst_pp f t) \<noteq> 0}" by (rule finite_subset, fact monom_mult_lookup_not_zero_subset_keys, fact finite_keys) lemma poly_subst_plus: "poly_subst f (p + q) = poly_subst f p + poly_subst f q" by (simp add: poly_subst_alt lookup_add punit.monom_mult_dist_left, rule Sum_any.distrib, (fact finite_monom_mult_lookup_not_zero)+) lemma poly_subst_uminus: "poly_subst f (-p) = - poly_subst f (p::('x \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 'b::comm_ring_1)" by (simp add: poly_subst_def keys_uminus punit.monom_mult_uminus_left sum_negf) lemma poly_subst_minus: "poly_subst f (p - q) = poly_subst f p - poly_subst f (q::('x \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 'b::comm_ring_1)" proof - have "poly_subst f (p + (-q)) = poly_subst f p + poly_subst f (-q)" by (fact poly_subst_plus) thus ?thesis by (simp add: poly_subst_uminus) qed lemma poly_subst_monomial: "poly_subst f (monomial c t) = punit.monom_mult c 0 (subst_pp f t)" by (simp add: poly_subst_def lookup_single) corollary poly_subst_one [simp]: "poly_subst f 1 = 1" by (simp add: single_one[symmetric] poly_subst_monomial punit.monom_mult_monomial del: single_one) lemma poly_subst_times: "poly_subst f (p * q) = poly_subst f p * poly_subst f q" proof - have bij: "bij (\<lambda>(l, n, m). (m, l, n))" by (auto intro!: bijI injI simp add: image_def) let ?P = "keys p" let ?Q = "keys q" let ?PQ = "{s + t | s t. lookup p s \<noteq> 0 \<and> lookup q t \<noteq> 0}" have fin_PQ: "finite ?PQ" by (rule finite_not_eq_zero_sumI, simp_all) have fin_1: "finite {l. lookup p l * (\<Sum>qa. lookup q qa when t = l + qa) \<noteq> 0}" for t proof (rule finite_subset) show "{l. lookup p l * (\<Sum>qa. lookup q qa when t = l + qa) \<noteq> 0} \<subseteq> keys p" by (rule, auto simp: in_keys_iff) qed (fact finite_keys) have fin_2: "finite {v. (lookup q v when t = u + v) \<noteq> 0}" for t u proof (rule finite_subset) show "{v. (lookup q v when t = u + v) \<noteq> 0} \<subseteq> keys q" by (rule, auto simp: in_keys_iff) qed (fact finite_keys) have fin_3: "finite {v. (lookup p u * lookup q v when t = u + v) \<noteq> 0}" for t u proof (rule finite_subset) show "{v. (lookup p u * lookup q v when t = u + v) \<noteq> 0} \<subseteq> keys q" by (rule, auto simp add: in_keys_iff simp del: lookup_not_eq_zero_eq_in_keys) qed (fact finite_keys) have "(\<Sum>t. punit.monom_mult (lookup (p * q) t) 0 (subst_pp f t)) = (\<Sum>t. \<Sum>u. punit.monom_mult (lookup p u * (\<Sum>v. lookup q v when t = u + v)) 0 (subst_pp f t))" by (simp add: times_poly_mapping.rep_eq prod_fun_def punit.monom_mult_Sum_any_left[OF fin_1]) also have "\<dots> = (\<Sum>t. \<Sum>u. \<Sum>v. (punit.monom_mult (lookup p u * lookup q v) 0 (subst_pp f t)) when t = u + v)" by (simp add: Sum_any_right_distrib[OF fin_2] punit.monom_mult_Sum_any_left[OF fin_3] mult_when punit.when_monom_mult) also have "\<dots> = (\<Sum>t. (\<Sum>(u, v). (punit.monom_mult (lookup p u * lookup q v) 0 (subst_pp f t)) when t = u + v))" by (subst (2) Sum_any.cartesian_product [of "?P \<times> ?Q"]) (auto simp: in_keys_iff) also have "\<dots> = (\<Sum>(t, u, v). punit.monom_mult (lookup p u * lookup q v) 0 (subst_pp f t) when t = u + v)" apply (subst Sum_any.cartesian_product [of "?PQ \<times> (?P \<times> ?Q)"]) apply (auto simp: fin_PQ in_keys_iff) apply (metis monomial_0I mult_not_zero times_monomial_left) done also have "\<dots> = (\<Sum>(u, v, t). punit.monom_mult (lookup p u * lookup q v) 0 (subst_pp f t) when t = u + v)" using bij by (rule Sum_any.reindex_cong [of "\<lambda>(u, v, t). (t, u, v)"]) (simp add: fun_eq_iff) also have "\<dots> = (\<Sum>(u, v). \<Sum>t. punit.monom_mult (lookup p u * lookup q v) 0 (subst_pp f t) when t = u + v)" apply (subst Sum_any.cartesian_product2 [of "(?P \<times> ?Q) \<times> ?PQ"]) apply (auto simp: fin_PQ in_keys_iff) apply (metis monomial_0I mult_not_zero times_monomial_left) done also have "\<dots> = (\<Sum>(u, v). punit.monom_mult (lookup p u * lookup q v) 0 (subst_pp f u * subst_pp f v))" by (simp add: subst_pp_plus) also have "\<dots> = (\<Sum>u. \<Sum>v. punit.monom_mult (lookup p u * lookup q v) 0 (subst_pp f u * subst_pp f v))" by (subst Sum_any.cartesian_product [of "?P \<times> ?Q"]) (auto simp: in_keys_iff) also have "\<dots> = (\<Sum>u. \<Sum>v. (punit.monom_mult (lookup p u) 0 (subst_pp f u)) * (punit.monom_mult (lookup q v) 0 (subst_pp f v)))" by (simp add: times_monomial_left[symmetric] ac_simps mult_single) also have "\<dots> = (\<Sum>t. punit.monom_mult (lookup p t) 0 (subst_pp f t)) * (\<Sum>t. punit.monom_mult (lookup q t) 0 (subst_pp f t))" by (rule Sum_any_product [symmetric], (fact finite_monom_mult_lookup_not_zero)+) finally show ?thesis by (simp add: poly_subst_alt) qed corollary poly_subst_monom_mult: "poly_subst f (punit.monom_mult c t p) = punit.monom_mult c 0 (subst_pp f t * poly_subst f p)" by (simp only: times_monomial_left[symmetric] poly_subst_times poly_subst_monomial mult.assoc) corollary poly_subst_monom_mult': "poly_subst f (punit.monom_mult c t p) = (punit.monom_mult c 0 (subst_pp f t)) * poly_subst f p" by (simp only: times_monomial_left[symmetric] poly_subst_times poly_subst_monomial) lemma poly_subst_sum: "poly_subst f (sum p A) = (\<Sum>a\<in>A. poly_subst f (p a))" by (rule fun_sum_commute, simp_all add: poly_subst_plus) lemma poly_subst_prod: "poly_subst f (prod p A) = (\<Prod>a\<in>A. poly_subst f (p a))" by (rule fun_prod_commute, simp_all add: poly_subst_times) lemma poly_subst_power: "poly_subst f (p ^ n) = (poly_subst f p) ^ n" by (induct n, simp_all add: poly_subst_times) lemma poly_subst_subst_pp: "poly_subst f (subst_pp g t) = subst_pp (\<lambda>x. poly_subst f (g x)) t" by (simp only: subst_pp_def poly_subst_prod poly_subst_power) lemma poly_subst_poly_subst: "poly_subst f (poly_subst g p) = poly_subst (\<lambda>x. poly_subst f (g x)) p" proof - have "poly_subst f (poly_subst g p) = poly_subst f (\<Sum>t\<in>keys p. punit.monom_mult (lookup p t) 0 (subst_pp g t))" by (simp only: poly_subst_def) also have "\<dots> = (\<Sum>t\<in>keys p. punit.monom_mult (lookup p t) 0 (subst_pp (\<lambda>x. poly_subst f (g x)) t))" by (simp add: poly_subst_sum poly_subst_monom_mult poly_subst_subst_pp) also have "\<dots> = poly_subst (\<lambda>x. poly_subst f (g x)) p" by (simp only: poly_subst_def) finally show ?thesis . qed lemma poly_subst_id: assumes "\<And>x. x \<in> indets p \<Longrightarrow> f x = monomial 1 (Poly_Mapping.single x 1)" shows "poly_subst f p = p" proof - have "poly_subst f p = (\<Sum>t\<in>keys p. monomial (lookup p t) t)" proof (simp only: poly_subst_def, rule sum.cong, fact refl) fix t assume "t \<in> keys p" have eq: "subst_pp f t = monomial 1 t" by (rule subst_pp_id, rule assms, erule in_indetsI, fact \<open>t \<in> keys p\<close>) show "punit.monom_mult (lookup p t) 0 (subst_pp f t) = monomial (lookup p t) t" by (simp add: eq punit.monom_mult_monomial) qed also have "... = p" by (simp only: poly_mapping_sum_monomials) finally show ?thesis . qed lemma in_keys_poly_substE: assumes "t \<in> keys (poly_subst f p)" obtains s where "s \<in> keys p" and "t \<in> keys (subst_pp f s)" proof - note assms also have "keys (poly_subst f p) \<subseteq> (\<Union>t\<in>keys p. keys (punit.monom_mult (lookup p t) 0 (subst_pp f t)))" unfolding poly_subst_def by (rule keys_sum_subset) finally obtain s where "s \<in> keys p" and "t \<in> keys (punit.monom_mult (lookup p s) 0 (subst_pp f s))" .. note this(2) also have "\<dots> \<subseteq> (+) 0 ` keys (subst_pp f s)" by (rule punit.keys_monom_mult_subset[simplified]) also have "\<dots> = keys (subst_pp f s)" by simp finally have "t \<in> keys (subst_pp f s)" . with \<open>s \<in> keys p\<close> show ?thesis .. qed lemma in_indets_poly_substE: assumes "x \<in> indets (poly_subst f p)" obtains y where "y \<in> indets p" and "x \<in> indets (f y)" proof - note assms also have "indets (poly_subst f p) \<subseteq> (\<Union>t\<in>keys p. indets (punit.monom_mult (lookup p t) 0 (subst_pp f t)))" unfolding poly_subst_def by (rule indets_sum_subset) finally obtain t where "t \<in> keys p" and "x \<in> indets (punit.monom_mult (lookup p t) 0 (subst_pp f t))" .. note this(2) also have "indets (punit.monom_mult (lookup p t) 0 (subst_pp f t)) \<subseteq> keys (0::('a \<Rightarrow>\<^sub>0 nat)) \<union> indets (subst_pp f t)" by (rule indets_monom_mult_subset) also have "... = indets (subst_pp f t)" by simp finally obtain y where "y \<in> keys t" and "x \<in> indets (f y)" by (rule in_indets_subst_ppE) from this(1) \<open>t \<in> keys p\<close> have "y \<in> indets p" by (rule in_indetsI) from this \<open>x \<in> indets (f y)\<close> show ?thesis .. qed lemma poly_deg_poly_subst_eq_zeroI: assumes "\<And>x. x \<in> indets p \<Longrightarrow> poly_deg (f x) = 0" shows "poly_deg (poly_subst (f::_ \<Rightarrow> (('y \<Rightarrow>\<^sub>0 _) \<Rightarrow>\<^sub>0 _)) (p::('x \<Rightarrow>\<^sub>0 _) \<Rightarrow>\<^sub>0 'b::comm_semiring_1)) = 0" proof (cases "p = 0") case True thus ?thesis by simp next case False have "poly_deg (poly_subst f p) \<le> Max (poly_deg ` (\<lambda>t. punit.monom_mult (lookup p t) 0 (subst_pp f t)) ` keys p)" unfolding poly_subst_def by (fact poly_deg_sum_le) also have "... \<le> 0" proof (rule Max.boundedI) show "finite (poly_deg ` (\<lambda>t. punit.monom_mult (lookup p t) 0 (subst_pp f t)) ` keys p)" by (simp add: finite_image_iff) next from False show "poly_deg ` (\<lambda>t. punit.monom_mult (lookup p t) 0 (subst_pp f t)) ` keys p \<noteq> {}" by simp next fix d assume "d \<in> poly_deg ` (\<lambda>t. punit.monom_mult (lookup p t) 0 (subst_pp f t)) ` keys p" then obtain t where "t \<in> keys p" and d: "d = poly_deg (punit.monom_mult (lookup p t) 0 (subst_pp f t))" by fastforce have "d \<le> deg_pm (0::'y \<Rightarrow>\<^sub>0 nat) + poly_deg (subst_pp f t)" unfolding d by (fact poly_deg_monom_mult_le) also have "... = poly_deg (subst_pp f t)" by simp also have "... = 0" by (rule poly_deg_subst_pp_eq_zeroI, rule assms, erule in_indetsI, fact) finally show "d \<le> 0" . qed finally show ?thesis by simp qed lemma poly_deg_poly_subst_le: assumes "\<And>x. x \<in> indets p \<Longrightarrow> poly_deg (f x) \<le> 1" shows "poly_deg (poly_subst (f::_ \<Rightarrow> (('y \<Rightarrow>\<^sub>0 _) \<Rightarrow>\<^sub>0 _)) (p::('x \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 'b::comm_semiring_1)) \<le> poly_deg p" proof (cases "p = 0") case True thus ?thesis by simp next case False have "poly_deg (poly_subst f p) \<le> Max (poly_deg ` (\<lambda>t. punit.monom_mult (lookup p t) 0 (subst_pp f t)) ` keys p)" unfolding poly_subst_def by (fact poly_deg_sum_le) also have "... \<le> poly_deg p" proof (rule Max.boundedI) show "finite (poly_deg ` (\<lambda>t. punit.monom_mult (lookup p t) 0 (subst_pp f t)) ` keys p)" by (simp add: finite_image_iff) next from False show "poly_deg ` (\<lambda>t. punit.monom_mult (lookup p t) 0 (subst_pp f t)) ` keys p \<noteq> {}" by simp next fix d assume "d \<in> poly_deg ` (\<lambda>t. punit.monom_mult (lookup p t) 0 (subst_pp f t)) ` keys p" then obtain t where "t \<in> keys p" and d: "d = poly_deg (punit.monom_mult (lookup p t) 0 (subst_pp f t))" by fastforce have "d \<le> deg_pm (0::'y \<Rightarrow>\<^sub>0 nat) + poly_deg (subst_pp f t)" unfolding d by (fact poly_deg_monom_mult_le) also have "... = poly_deg (subst_pp f t)" by simp also have "... \<le> deg_pm t" by (rule poly_deg_subst_pp_le, rule assms, erule in_indetsI, fact) also from \<open>t \<in> keys p\<close> have "... \<le> poly_deg p" by (rule poly_deg_max_keys) finally show "d \<le> poly_deg p" . qed finally show ?thesis by simp qed lemma subst_pp_cong: "s = t \<Longrightarrow> (\<And>x. x \<in> keys t \<Longrightarrow> f x = g x) \<Longrightarrow> subst_pp f s = subst_pp g t" by (simp add: subst_pp_def) lemma poly_subst_cong: assumes "p = q" and "\<And>x. x \<in> indets q \<Longrightarrow> f x = g x" shows "poly_subst f p = poly_subst g q" proof (simp add: poly_subst_def assms(1), rule sum.cong) fix t assume "t \<in> keys q" { fix x assume "x \<in> keys t" with \<open>t \<in> keys q\<close> have "x \<in> indets q" by (auto simp: indets_def) hence "f x = g x" by (rule assms(2)) } thus "punit.monom_mult (lookup q t) 0 (subst_pp f t) = punit.monom_mult (lookup q t) 0 (subst_pp g t)" by (simp cong: subst_pp_cong) qed (fact refl) lemma Polys_homomorphismE: obtains h where "\<And>p q. h (p + q) = h p + h q" and "\<And>p q. h (p * q) = h p * h q" and "\<And>p::('x \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 'a::comm_ring_1. h (h p) = h p" and "range h = P[X]" proof - let ?f = "\<lambda>x. if x \<in> X then monomial (1::'a) (Poly_Mapping.single x 1) else 1" have 1: "poly_subst ?f p = p" if "p \<in> P[X]" for p proof (rule poly_subst_id) fix x assume "x \<in> indets p" also from that have "\<dots> \<subseteq> X" by (rule PolysD) finally show "?f x = monomial 1 (Poly_Mapping.single x 1)" by simp qed have 2: "poly_subst ?f p \<in> P[X]" for p proof (intro PolysI_alt subsetI) fix x assume "x \<in> indets (poly_subst ?f p)" then obtain y where "x \<in> indets (?f y)" by (rule in_indets_poly_substE) thus "x \<in> X" by (simp add: indets_monomial split: if_split_asm) qed from poly_subst_plus poly_subst_times show ?thesis proof fix p from 2 show "poly_subst ?f (poly_subst ?f p) = poly_subst ?f p" by (rule 1) next show "range (poly_subst ?f) = P[X]" proof (intro set_eqI iffI) fix p :: "_ \<Rightarrow>\<^sub>0 'a" assume "p \<in> P[X]" hence "p = poly_subst ?f p" by (simp only: 1) thus "p \<in> range (poly_subst ?f)" by (rule image_eqI) simp qed (auto intro: 2) qed qed lemma in_idealE_Polys_finite: assumes "finite B" and "B \<subseteq> P[X]" and "p \<in> P[X]" and "(p::('x \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 'a::comm_ring_1) \<in> ideal B" obtains q where "\<And>b. q b \<in> P[X]" and "p = (\<Sum>b\<in>B. q b * b)" proof - obtain h where "\<And>p q. h (p + q) = h p + h q" and "\<And>p q. h (p * q) = h p * h q" and "\<And>p::('x \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 'a. h (h p) = h p" and rng[symmetric]: "range h = P[X]" by (rule Polys_homomorphismE) blast from this(1-3) assms obtain q where "\<And>b. q b \<in> P[X]" and "p = (\<Sum>b\<in>B. q b * b)" unfolding rng by (rule in_idealE_homomorphism_finite) blast thus ?thesis .. qed corollary in_idealE_Polys: assumes "B \<subseteq> P[X]" and "p \<in> P[X]" and "p \<in> ideal B" obtains A q where "finite A" and "A \<subseteq> B" and "\<And>b. q b \<in> P[X]" and "p = (\<Sum>b\<in>A. q b * b)" proof - from assms(3) obtain A where "finite A" and "A \<subseteq> B" and "p \<in> ideal A" by (rule ideal.span_finite_subset) from this(2) assms(1) have "A \<subseteq> P[X]" by (rule subset_trans) with \<open>finite A\<close> obtain q where "\<And>b. q b \<in> P[X]" and "p = (\<Sum>b\<in>A. q b * b)" using assms(2) \<open>p \<in> ideal A\<close> by (rule in_idealE_Polys_finite) blast with \<open>finite A\<close> \<open>A \<subseteq> B\<close> show ?thesis .. qed lemma ideal_induct_Polys [consumes 3, case_names 0 plus]: assumes "F \<subseteq> P[X]" and "p \<in> P[X]" and "p \<in> ideal F" assumes "P 0" and "\<And>c q h. c \<in> P[X] \<Longrightarrow> q \<in> F \<Longrightarrow> P h \<Longrightarrow> h \<in> P[X] \<Longrightarrow> P (c * q + h)" shows "P (p::('x \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 'a::comm_ring_1)" proof - obtain h where "\<And>p q. h (p + q) = h p + h q" and "\<And>p q. h (p * q) = h p * h q" and "\<And>p::('x \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 'a. h (h p) = h p" and rng[symmetric]: "range h = P[X]" by (rule Polys_homomorphismE) blast from this(1-3) assms show ?thesis unfolding rng by (rule ideal_induct_homomorphism) blast qed lemma image_poly_subst_ideal_subset: "poly_subst g ` ideal F \<subseteq> ideal (poly_subst g ` F)" proof (intro subsetI, elim imageE) fix h f assume h: "h = poly_subst g f" assume "f \<in> ideal F" thus "h \<in> ideal (poly_subst g ` F)" unfolding h proof (induct f rule: ideal.span_induct_alt) case base show ?case by (simp add: ideal.span_zero) next case (step c f h) from step.hyps(1) have "poly_subst g f \<in> ideal (poly_subst g ` F)" by (intro ideal.span_base imageI) hence "poly_subst g c * poly_subst g f \<in> ideal (poly_subst g ` F)" by (rule ideal.span_scale) hence "poly_subst g c * poly_subst g f + poly_subst g h \<in> ideal (poly_subst g ` F)" using step.hyps(2) by (rule ideal.span_add) thus ?case by (simp only: poly_subst_plus poly_subst_times) qed qed subsection \<open>Evaluating Polynomials\<close> lemma lookup_times_zero: "lookup (p * q) 0 = lookup p 0 * lookup q (0::'a::{comm_powerprod,ninv_comm_monoid_add})" proof - have eq: "(\<Sum>v\<in>keys q. lookup q v when t + v = 0) = (lookup q 0 when t = 0)" for t proof - have "(\<Sum>v\<in>keys q. lookup q v when t + v = 0) = (\<Sum>v\<in>keys q \<inter> {0}. lookup q v when t + v = 0)" proof (intro sum.mono_neutral_right ballI) fix v assume "v \<in> keys q - keys q \<inter> {0}" hence "v \<noteq> 0" by blast hence "t + v \<noteq> 0" using plus_eq_zero_2 by blast thus "(lookup q v when t + v = 0) = 0" by simp qed simp_all also have "\<dots> = (lookup q 0 when t = 0)" by (cases "0 \<in> keys q") (simp_all add: in_keys_iff) finally show ?thesis . qed have "(\<Sum>t\<in>keys p. lookup p t * lookup q 0 when t = 0) = (\<Sum>t\<in>keys p \<inter> {0}. lookup p t * lookup q 0 when t = 0)" proof (intro sum.mono_neutral_right ballI) fix t assume "t \<in> keys p - keys p \<inter> {0}" hence "t \<noteq> 0" by blast thus "(lookup p t * lookup q 0 when t = 0) = 0" by simp qed simp_all also have "\<dots> = lookup p 0 * lookup q 0" by (cases "0 \<in> keys p") (simp_all add: in_keys_iff) finally show ?thesis by (simp add: lookup_times eq when_distrib) qed corollary lookup_prod_zero: "lookup (prod f I) 0 = (\<Prod>i\<in>I. lookup (f i) (0::_::{comm_powerprod,ninv_comm_monoid_add}))" by (induct I rule: infinite_finite_induct) (simp_all add: lookup_times_zero) corollary lookup_power_zero: "lookup (p ^ k) 0 = lookup p (0::_::{comm_powerprod,ninv_comm_monoid_add}) ^ k" by (induct k) (simp_all add: lookup_times_zero) definition poly_eval :: "('x \<Rightarrow> 'a) \<Rightarrow> (('x \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 'a) \<Rightarrow> 'a::comm_semiring_1" where "poly_eval a p = lookup (poly_subst (\<lambda>y. monomial (a y) (0::'x \<Rightarrow>\<^sub>0 nat)) p) 0" lemma poly_eval_alt: "poly_eval a p = (\<Sum>t\<in>keys p. lookup p t * (\<Prod>x\<in>keys t. a x ^ lookup t x))" by (simp add: poly_eval_def poly_subst_def lookup_sum lookup_times_zero subst_pp_def lookup_prod_zero lookup_power_zero flip: times_monomial_left) lemma poly_eval_monomial: "poly_eval a (monomial c t) = c * (\<Prod>x\<in>keys t. a x ^ lookup t x)" by (simp add: poly_eval_def poly_subst_monomial subst_pp_def punit.lookup_monom_mult lookup_prod_zero lookup_power_zero) lemma poly_eval_zero [simp]: "poly_eval a 0 = 0" by (simp only: poly_eval_def poly_subst_zero lookup_zero) lemma poly_eval_zero_left [simp]: "poly_eval 0 p = lookup p 0" by (simp add: poly_eval_def) lemma poly_eval_plus: "poly_eval a (p + q) = poly_eval a p + poly_eval a q" by (simp only: poly_eval_def poly_subst_plus lookup_add) lemma poly_eval_uminus [simp]: "poly_eval a (- p) = - poly_eval (a::_::comm_ring_1) p" by (simp only: poly_eval_def poly_subst_uminus lookup_uminus) lemma poly_eval_minus: "poly_eval a (p - q) = poly_eval a p - poly_eval (a::_::comm_ring_1) q" by (simp only: poly_eval_def poly_subst_minus lookup_minus) lemma poly_eval_one [simp]: "poly_eval a 1 = 1" by (simp add: poly_eval_def lookup_one) lemma poly_eval_times: "poly_eval a (p * q) = poly_eval a p * poly_eval a q" by (simp only: poly_eval_def poly_subst_times lookup_times_zero) lemma poly_eval_power: "poly_eval a (p ^ m) = poly_eval a p ^ m" by (induct m) (simp_all add: poly_eval_times) lemma poly_eval_sum: "poly_eval a (sum f I) = (\<Sum>i\<in>I. poly_eval a (f i))" by (induct I rule: infinite_finite_induct) (simp_all add: poly_eval_plus) lemma poly_eval_prod: "poly_eval a (prod f I) = (\<Prod>i\<in>I. poly_eval a (f i))" by (induct I rule: infinite_finite_induct) (simp_all add: poly_eval_times) lemma poly_eval_cong: "p = q \<Longrightarrow> (\<And>x. x \<in> indets q \<Longrightarrow> a x = b x) \<Longrightarrow> poly_eval a p = poly_eval b q" by (simp add: poly_eval_def cong: poly_subst_cong) lemma indets_poly_eval_subset: "indets (poly_eval a p) \<subseteq> \<Union> (indets ` a ` indets p) \<union> \<Union> (indets ` lookup p ` keys p)" proof (induct p rule: poly_mapping_plus_induct) case 1 show ?case by simp next case (2 p c t) have "keys (monomial c t + p) = keys (monomial c t) \<union> keys p" by (rule keys_plus_eqI) (simp add: 2(2)) with 2(1) have eq1: "keys (monomial c t + p) = insert t (keys p)" by simp hence eq2: "indets (monomial c t + p) = keys t \<union> indets p" by (simp add: indets_def) from 2(2) have eq3: "lookup (monomial c t + p) t = c" by (simp add: lookup_add in_keys_iff) have eq4: "lookup (monomial c t + p) s = lookup p s" if "s \<in> keys p" for s using that 2(2) by (auto simp: lookup_add lookup_single when_def) have "indets (poly_eval a (monomial c t + p)) = indets (c * (\<Prod>x\<in>keys t. a x ^ lookup t x) + poly_eval a p)" by (simp only: poly_eval_plus poly_eval_monomial) also have "\<dots> \<subseteq> indets (c * (\<Prod>x\<in>keys t. a x ^ lookup t x)) \<union> indets (poly_eval a p)" by (fact indets_plus_subset) also have "\<dots> \<subseteq> indets c \<union> (\<Union> (indets ` a ` keys t)) \<union> (\<Union> (indets ` a ` indets p) \<union> \<Union> (indets ` lookup p ` keys p))" proof (intro Un_mono 2(3)) have "indets (c * (\<Prod>x\<in>keys t. a x ^ lookup t x)) \<subseteq> indets c \<union> indets (\<Prod>x\<in>keys t. a x ^ lookup t x)" by (fact indets_times_subset) also have "indets (\<Prod>x\<in>keys t. a x ^ lookup t x) \<subseteq> (\<Union>x\<in>keys t. indets (a x ^ lookup t x))" by (fact indets_prod_subset) also have "\<dots> \<subseteq> (\<Union>x\<in>keys t. indets (a x))" by (intro UN_mono subset_refl indets_power_subset) also have "\<dots> = \<Union> (indets ` a ` keys t)" by simp finally show "indets (c * (\<Prod>x\<in>keys t. a x ^ lookup t x)) \<subseteq> indets c \<union> \<Union> (indets ` a ` keys t)" by blast qed also have "\<dots> = \<Union> (indets ` a ` indets (monomial c t + p)) \<union> \<Union> (indets ` lookup (monomial c t + p) ` keys (monomial c t + p))" by (simp add: eq1 eq2 eq3 eq4 Un_commute Un_assoc Un_left_commute) finally show ?case . qed lemma image_poly_eval_ideal: "poly_eval a ` ideal F = ideal (poly_eval a ` F)" proof (intro image_ideal_eq_surj poly_eval_plus poly_eval_times surjI) fix x show "poly_eval a (monomial x 0) = x" by (simp add: poly_eval_monomial) qed subsection \<open>Replacing Indeterminates\<close> definition map_indets where "map_indets f = poly_subst (\<lambda>x. monomial 1 (Poly_Mapping.single (f x) 1))" lemma shows map_indets_zero [simp]: "map_indets f 0 = 0" and map_indets_one [simp]: "map_indets f 1 = 1" and map_indets_uminus [simp]: "map_indets f (- r) = - map_indets f (r::_ \<Rightarrow>\<^sub>0 _::comm_ring_1)" and map_indets_plus: "map_indets f (p + q) = map_indets f p + map_indets f q" and map_indets_minus: "map_indets f (r - s) = map_indets f r - map_indets f s" and map_indets_times: "map_indets f (p * q) = map_indets f p * map_indets f q" and map_indets_power [simp]: "map_indets f (p ^ m) = map_indets f p ^ m" and map_indets_sum: "map_indets f (sum g A) = (\<Sum>a\<in>A. map_indets f (g a))" and map_indets_prod: "map_indets f (prod g A) = (\<Prod>a\<in>A. map_indets f (g a))" by (simp_all add: map_indets_def poly_subst_uminus poly_subst_plus poly_subst_minus poly_subst_times poly_subst_power poly_subst_sum poly_subst_prod) lemma map_indets_monomial: "map_indets f (monomial c t) = monomial c (\<Sum>x\<in>keys t. Poly_Mapping.single (f x) (lookup t x))" by (simp add: map_indets_def poly_subst_monomial subst_pp_def monomial_power_map_scale punit.monom_mult_monomial flip: punit.monomial_prod_sum) lemma map_indets_id: "(\<And>x. x \<in> indets p \<Longrightarrow> f x = x) \<Longrightarrow> map_indets f p = p" by (simp add: map_indets_def poly_subst_id) lemma map_indets_map_indets: "map_indets f (map_indets g p) = map_indets (f \<circ> g) p" by (simp add: map_indets_def poly_subst_poly_subst poly_subst_monomial subst_pp_single) lemma map_indets_cong: "p = q \<Longrightarrow> (\<And>x. x \<in> indets q \<Longrightarrow> f x = g x) \<Longrightarrow> map_indets f p = map_indets g q" unfolding map_indets_def by (simp cong: poly_subst_cong) lemma poly_subst_map_indets: "poly_subst f (map_indets g p) = poly_subst (f \<circ> g) p" by (simp add: map_indets_def poly_subst_poly_subst poly_subst_monomial subst_pp_single comp_def) lemma poly_eval_map_indets: "poly_eval a (map_indets g p) = poly_eval (a \<circ> g) p" by (simp add: poly_eval_def poly_subst_map_indets comp_def) (simp add: poly_subst_def lookup_sum lookup_times_zero subst_pp_def lookup_prod_zero lookup_power_zero flip: times_monomial_left) lemma map_indets_inverseE_Polys: assumes "inj_on f X" and "p \<in> P[X]" shows "map_indets (the_inv_into X f) (map_indets f p) = p" unfolding map_indets_map_indets proof (rule map_indets_id) fix x assume "x \<in> indets p" also from assms(2) have "\<dots> \<subseteq> X" by (rule PolysD) finally show "(the_inv_into X f \<circ> f) x = x" using assms(1) by (auto intro: the_inv_into_f_f) qed lemma map_indets_inverseE: assumes "inj f" obtains g where "g = the_inv f" and "g \<circ> f = id" and "map_indets g \<circ> map_indets f = id" proof - define g where "g = the_inv f" moreover from assms have eq: "g \<circ> f = id" by (auto intro!: ext the_inv_f_f simp: g_def) moreover have "map_indets g \<circ> map_indets f = id" by (rule ext) (simp add: map_indets_map_indets eq map_indets_id) ultimately show ?thesis .. qed lemma indets_map_indets_subset: "indets (map_indets f (p::_ \<Rightarrow>\<^sub>0 'a::comm_semiring_1)) \<subseteq> f ` indets p" proof fix x assume "x \<in> indets (map_indets f p)" then obtain y where "y \<in> indets p" and "x \<in> indets (monomial (1::'a) (Poly_Mapping.single (f y) 1))" unfolding map_indets_def by (rule in_indets_poly_substE) from this(2) have x: "x = f y" by (simp add: indets_monomial) from \<open>y \<in> indets p\<close> show "x \<in> f ` indets p" unfolding x by (rule imageI) qed corollary map_indets_in_Polys: "map_indets f p \<in> P[f ` indets p]" using indets_map_indets_subset by (rule PolysI_alt) lemma indets_map_indets: assumes "inj_on f (indets p)" shows "indets (map_indets f p) = f ` indets p" using indets_map_indets_subset proof (rule subset_antisym) let ?g = "the_inv_into (indets p) f" have "p = map_indets ?g (map_indets f p)" unfolding map_indets_map_indets by (rule sym, rule map_indets_id) (simp add: assms the_inv_into_f_f) also have "indets \<dots> \<subseteq> ?g ` indets (map_indets f p)" by (fact indets_map_indets_subset) finally have "f ` indets p \<subseteq> f ` ?g ` indets (map_indets f p)" by (rule image_mono) also have "\<dots> = (\<lambda>x. x) ` indets (map_indets f p)" unfolding image_image using refl proof (rule image_cong) fix x assume "x \<in> indets (map_indets f p)" with indets_map_indets_subset have "x \<in> f ` indets p" .. with assms show "f (?g x) = x" by (rule f_the_inv_into_f) qed finally show "f ` indets p \<subseteq> indets (map_indets f p)" by simp qed lemma image_map_indets_Polys: "map_indets f ` P[X] = (P[f ` X]::(_ \<Rightarrow>\<^sub>0 'a::comm_semiring_1) set)" proof (intro set_eqI iffI) fix p :: "_ \<Rightarrow>\<^sub>0 'a" assume "p \<in> map_indets f ` P[X]" then obtain q where "q \<in> P[X]" and "p = map_indets f q" .. note this(2) also have "map_indets f q \<in> P[f ` indets q]" by (fact map_indets_in_Polys) also from \<open>q \<in> _\<close> have "\<dots> \<subseteq> P[f ` X]" by (auto intro!: Polys_mono imageI dest: PolysD) finally show "p \<in> P[f ` X]" . next fix p :: "_ \<Rightarrow>\<^sub>0 'a" assume "p \<in> P[f ` X]" define g where "g = (\<lambda>y. SOME x. x \<in> X \<and> f x = y)" have "g y \<in> X \<and> f (g y) = y" if "y \<in> indets p" for y proof - note that also from \<open>p \<in> _\<close> have "indets p \<subseteq> f ` X" by (rule PolysD) finally obtain x where "x \<in> X" and "y = f x" .. hence "x \<in> X \<and> f x = y" by simp thus ?thesis unfolding g_def by (rule someI) qed hence 1: "g y \<in> X" and 2: "f (g y) = y" if "y \<in> indets p" for y using that by simp_all show "p \<in> map_indets f ` P[X]" proof show "p = map_indets f (map_indets g p)" by (rule sym) (simp add: map_indets_map_indets map_indets_id 2) next have "map_indets g p \<in> P[g ` indets p]" by (fact map_indets_in_Polys) also have "\<dots> \<subseteq> P[X]" by (auto intro!: Polys_mono 1) finally show "map_indets g p \<in> P[X]" . qed qed corollary range_map_indets: "range (map_indets f) = P[range f]" proof - have "range (map_indets f) = map_indets f ` P[UNIV]" by simp also have "\<dots> = P[range f]" by (simp only: image_map_indets_Polys) finally show ?thesis . qed lemma in_keys_map_indetsE: assumes "t \<in> keys (map_indets f (p::_ \<Rightarrow>\<^sub>0 'a::comm_semiring_1))" obtains s where "s \<in> keys p" and "t = (\<Sum>x\<in>keys s. Poly_Mapping.single (f x) (lookup s x))" proof - let ?f = "(\<lambda>x. monomial (1::'a) (Poly_Mapping.single (f x) 1))" from assms obtain s where "s \<in> keys p" and "t \<in> keys (subst_pp ?f s)" unfolding map_indets_def by (rule in_keys_poly_substE) note this(2) also have "\<dots> \<subseteq> {\<Sum>x\<in>keys s. Poly_Mapping.single (f x) (lookup s x)}" by (simp add: subst_pp_def monomial_power_map_scale flip: punit.monomial_prod_sum) finally have "t = (\<Sum>x\<in>keys s. Poly_Mapping.single (f x) (lookup s x))" by simp with \<open>s \<in> keys p\<close> show ?thesis .. qed lemma keys_map_indets_subset: "keys (map_indets f p) \<subseteq> (\<lambda>t. \<Sum>x\<in>keys t. Poly_Mapping.single (f x) (lookup t x)) ` keys p" by (auto elim: in_keys_map_indetsE) lemma keys_map_indets: assumes "inj_on f (indets p)" shows "keys (map_indets f p) = (\<lambda>t. \<Sum>x\<in>keys t. Poly_Mapping.single (f x) (lookup t x)) ` keys p" using keys_map_indets_subset proof (rule subset_antisym) let ?g = "the_inv_into (indets p) f" have "p = map_indets ?g (map_indets f p)" unfolding map_indets_map_indets by (rule sym, rule map_indets_id) (simp add: assms the_inv_into_f_f) also have "keys \<dots> \<subseteq> (\<lambda>t. \<Sum>x\<in>keys t. monomial (lookup t x) (?g x)) ` keys (map_indets f p)" by (rule keys_map_indets_subset) finally have "(\<lambda>t. \<Sum>x\<in>keys t. Poly_Mapping.single (f x) (lookup t x)) ` keys p \<subseteq> (\<lambda>t. \<Sum>x\<in>keys t. Poly_Mapping.single (f x) (lookup t x)) ` (\<lambda>t. \<Sum>x\<in>keys t. Poly_Mapping.single (?g x) (lookup t x)) ` keys (map_indets f p)" by (rule image_mono) also from refl have "\<dots> = (\<lambda>t. \<Sum>x. Poly_Mapping.single (f x) (lookup t x)) ` (\<lambda>t. \<Sum>x\<in>keys t. Poly_Mapping.single (?g x) (lookup t x)) ` keys (map_indets f p)" by (rule image_cong) (smt Sum_any.conditionalize Sum_any.cong finite_keys not_in_keys_iff_lookup_eq_zero single_zero) also have "\<dots> = (\<lambda>t. t) ` keys (map_indets f p)" unfolding image_image using refl proof (rule image_cong) fix t assume "t \<in> keys (map_indets f p)" have "(\<Sum>x. monomial (lookup (\<Sum>y\<in>keys t. Poly_Mapping.single (?g y) (lookup t y)) x) (f x)) = (\<Sum>x. \<Sum>y\<in>keys t. monomial (lookup t y when ?g y = x) (f x))" by (simp add: lookup_sum lookup_single monomial_sum) also have "\<dots> = (\<Sum>x\<in>indets p. \<Sum>y\<in>keys t. Poly_Mapping.single (f x) (lookup t y when ?g y = x))" proof (intro Sum_any.expand_superset finite_indets subsetI) fix x assume "x \<in> {a. (\<Sum>y\<in>keys t. Poly_Mapping.single (f a) (lookup t y when ?g y = a)) \<noteq> 0}" hence "(\<Sum>y\<in>keys t. Poly_Mapping.single (f x) (lookup t y when ?g y = x)) \<noteq> 0" by simp then obtain y where "y \<in> keys t" and *: "Poly_Mapping.single (f x) (lookup t y when ?g y = x) \<noteq> 0" by (rule sum.not_neutral_contains_not_neutral) from this(1) have "y \<in> indets (map_indets f p)" using \<open>t \<in> _\<close> by (rule in_indetsI) with indets_map_indets_subset have "y \<in> f ` indets p" .. from * have "x = ?g y" by (simp add: when_def split: if_split_asm) also from assms \<open>y \<in> f ` indets p\<close> subset_refl have "\<dots> \<in> indets p" by (rule the_inv_into_into) finally show "x \<in> indets p" . qed also have "\<dots> = (\<Sum>y\<in>keys t. \<Sum>x\<in>indets p. Poly_Mapping.single (f x) (lookup t y when ?g y = x))" by (fact sum.swap) also from refl have "\<dots> = (\<Sum>y\<in>keys t. Poly_Mapping.single y (lookup t y))" proof (rule sum.cong) fix x assume "x \<in> keys t" hence "x \<in> indets (map_indets f p)" using \<open>t \<in> _\<close> by (rule in_indetsI) with indets_map_indets_subset have "x \<in> f ` indets p" .. with assms have "?g x \<in> indets p" using subset_refl by (rule the_inv_into_into) hence "{?g x} \<subseteq> indets p" by simp with finite_indets have "(\<Sum>y\<in>indets p. Poly_Mapping.single (f y) (lookup t x when ?g x = y)) = (\<Sum>y\<in>{?g x}. Poly_Mapping.single (f y) (lookup t x when ?g x = y))" by (rule sum.mono_neutral_right) (simp add: monomial_0_iff when_def) also from assms \<open>x \<in> f ` indets p\<close> have "\<dots> = Poly_Mapping.single x (lookup t x)" by (simp add: f_the_inv_into_f) finally show "(\<Sum>y\<in>indets p. Poly_Mapping.single (f y) (lookup t x when ?g x = y)) = Poly_Mapping.single x (lookup t x)" . qed also have "\<dots> = t" by (fact poly_mapping_sum_monomials) finally show "(\<Sum>x. monomial (lookup (\<Sum>y\<in>keys t. Poly_Mapping.single (?g y) (lookup t y)) x) (f x)) = t" . qed also have "\<dots> = keys (map_indets f p)" by simp finally show "(\<lambda>t. \<Sum>x\<in>keys t. Poly_Mapping.single (f x) (lookup t x)) ` keys p \<subseteq> keys (map_indets f p)" . qed lemma poly_deg_map_indets: assumes "inj_on f (indets p)" shows "poly_deg (map_indets f p) = poly_deg p" proof - from assms have "deg_pm ` keys (map_indets f p) = deg_pm ` keys p" by (simp add: keys_map_indets image_image deg_pm_sum deg_pm_single flip: deg_pm_superset[OF subset_refl]) thus ?thesis by (auto simp: poly_deg_def) qed lemma map_indets_inj_on_PolysI: assumes "inj_on (f::'x \<Rightarrow> 'y) X" shows "inj_on ((map_indets f)::_ \<Rightarrow> _ \<Rightarrow>\<^sub>0 'a::comm_semiring_1) P[X]" proof (rule inj_onI) fix p q :: "_ \<Rightarrow>\<^sub>0 'a" assume "p \<in> P[X]" with assms have 1: "map_indets (the_inv_into X f) (map_indets f p) = p" (is "map_indets ?g _ = _") by (rule map_indets_inverseE_Polys) assume "q \<in> P[X]" with assms have "map_indets ?g (map_indets f q) = q" by (rule map_indets_inverseE_Polys) moreover assume "map_indets f p = map_indets f q" ultimately show "p = q" using 1 by (simp add: map_indets_map_indets) qed lemma map_indets_injI: assumes "inj f" shows "inj (map_indets f)" proof - from assms have "inj_on (map_indets f) P[UNIV]" by (rule map_indets_inj_on_PolysI) thus ?thesis by simp qed lemma image_map_indets_ideal: assumes "inj f" shows "map_indets f ` ideal F = ideal (map_indets f ` (F::(_ \<Rightarrow>\<^sub>0 'a::comm_ring_1) set)) \<inter> P[range f]" proof from map_indets_plus map_indets_times have "map_indets f ` ideal F \<subseteq> ideal (map_indets f ` F)" by (rule image_ideal_subset) moreover from subset_UNIV have "map_indets f ` ideal F \<subseteq> range (map_indets f)" by (rule image_mono) ultimately show "map_indets f ` ideal F \<subseteq> ideal (map_indets f ` F) \<inter> P[range f]" unfolding range_map_indets by blast next show "ideal (map_indets f ` F) \<inter> P[range f] \<subseteq> map_indets f ` ideal F" proof fix p assume "p \<in> ideal (map_indets f ` F) \<inter> P[range f]" hence "p \<in> ideal (map_indets f ` F)" and "p \<in> range (map_indets f)" by (simp_all add: range_map_indets) from this(1) obtain F0 q where "F0 \<subseteq> map_indets f ` F" and p: "p = (\<Sum>f'\<in>F0. q f' * f')" by (rule ideal.spanE) from this(1) obtain F' where "F' \<subseteq> F" and F0: "F0 = map_indets f ` F'" by (rule subset_imageE) from assms obtain g where "map_indets g \<circ> map_indets f = (id::_ \<Rightarrow> _ \<Rightarrow>\<^sub>0 'a)" by (rule map_indets_inverseE) hence eq: "map_indets g (map_indets f p') = p'" for p'::"_ \<Rightarrow>\<^sub>0 'a" by (simp add: pointfree_idE) from assms have "inj (map_indets f)" by (rule map_indets_injI) from this subset_UNIV have "inj_on (map_indets f) F'" by (rule inj_on_subset) from \<open>p \<in> range _\<close> obtain p' where "p = map_indets f p'" .. hence "p = map_indets f (map_indets g p)" by (simp add: eq) also from \<open>inj_on _ F'\<close> have "\<dots> = map_indets f (\<Sum>f'\<in>F'. map_indets g (q (map_indets f f')) * f')" by (simp add: p F0 sum.reindex map_indets_sum map_indets_times eq) finally have "p = map_indets f (\<Sum>f'\<in>F'. map_indets g (q (map_indets f f')) * f')" . moreover have "(\<Sum>f'\<in>F'. map_indets g (q (map_indets f f')) * f') \<in> ideal F" proof show "(\<Sum>f'\<in>F'. map_indets g (q (map_indets f f')) * f') \<in> ideal F'" by (rule ideal.sum_in_spanI) next from \<open>F' \<subseteq> F\<close> show "ideal F' \<subseteq> ideal F" by (rule ideal.span_mono) qed ultimately show "p \<in> map_indets f ` ideal F" by (rule image_eqI) qed qed subsection \<open>Homogeneity\<close> definition homogeneous :: "(('x \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 'a::zero) \<Rightarrow> bool" where "homogeneous p \<longleftrightarrow> (\<forall>s\<in>keys p. \<forall>t\<in>keys p. deg_pm s = deg_pm t)" definition hom_component :: "(('x \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 'a) \<Rightarrow> nat \<Rightarrow> (('x \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 'a::zero)" where "hom_component p n = except p {t. deg_pm t \<noteq> n}" definition hom_components :: "(('x \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 'a) \<Rightarrow> (('x \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 'a::zero) set" where "hom_components p = hom_component p ` deg_pm ` keys p" definition homogeneous_set :: "(('x \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 'a::zero) set \<Rightarrow> bool" where "homogeneous_set A \<longleftrightarrow> (\<forall>a\<in>A. \<forall>n. hom_component a n \<in> A)" lemma homogeneousI: "(\<And>s t. s \<in> keys p \<Longrightarrow> t \<in> keys p \<Longrightarrow> deg_pm s = deg_pm t) \<Longrightarrow> homogeneous p" unfolding homogeneous_def by blast lemma homogeneousD: "homogeneous p \<Longrightarrow> s \<in> keys p \<Longrightarrow> t \<in> keys p \<Longrightarrow> deg_pm s = deg_pm t" unfolding homogeneous_def by blast lemma homogeneousD_poly_deg: assumes "homogeneous p" and "t \<in> keys p" shows "deg_pm t = poly_deg p" proof (rule antisym) from assms(2) show "deg_pm t \<le> poly_deg p" by (rule poly_deg_max_keys) next show "poly_deg p \<le> deg_pm t" proof (rule poly_deg_leI) fix s assume "s \<in> keys p" with assms(1) have "deg_pm s = deg_pm t" using assms(2) by (rule homogeneousD) thus "deg_pm s \<le> deg_pm t" by simp qed qed lemma homogeneous_monomial [simp]: "homogeneous (monomial c t)" by (auto split: if_split_asm intro: homogeneousI) corollary homogeneous_zero [simp]: "homogeneous 0" and homogeneous_one [simp]: "homogeneous 1" by (simp_all only: homogeneous_monomial flip: single_zero[of 0] single_one) lemma homogeneous_uminus_iff [simp]: "homogeneous (- p) \<longleftrightarrow> homogeneous p" by (auto intro!: homogeneousI dest: homogeneousD simp: keys_uminus) lemma homogeneous_monom_mult: "homogeneous p \<Longrightarrow> homogeneous (punit.monom_mult c t p)" by (auto intro!: homogeneousI elim!: punit.keys_monom_multE simp: deg_pm_plus dest: homogeneousD) lemma homogeneous_monom_mult_rev: assumes "c \<noteq> (0::'a::semiring_no_zero_divisors)" and "homogeneous (punit.monom_mult c t p)" shows "homogeneous p" proof (rule homogeneousI) fix s s' assume "s \<in> keys p" hence 1: "t + s \<in> keys (punit.monom_mult c t p)" using assms(1) by (rule punit.keys_monom_multI[simplified]) assume "s' \<in> keys p" hence "t + s' \<in> keys (punit.monom_mult c t p)" using assms(1) by (rule punit.keys_monom_multI[simplified]) with assms(2) 1 have "deg_pm (t + s) = deg_pm (t + s')" by (rule homogeneousD) thus "deg_pm s = deg_pm s'" by (simp add: deg_pm_plus) qed lemma homogeneous_times: assumes "homogeneous p" and "homogeneous q" shows "homogeneous (p * q)" proof (rule homogeneousI) fix s t assume "s \<in> keys (p * q)" then obtain sp sq where sp: "sp \<in> keys p" and sq: "sq \<in> keys q" and s: "s = sp + sq" by (rule in_keys_timesE) assume "t \<in> keys (p * q)" then obtain tp tq where tp: "tp \<in> keys p" and tq: "tq \<in> keys q" and t: "t = tp + tq" by (rule in_keys_timesE) from assms(1) sp tp have "deg_pm sp = deg_pm tp" by (rule homogeneousD) moreover from assms(2) sq tq have "deg_pm sq = deg_pm tq" by (rule homogeneousD) ultimately show "deg_pm s = deg_pm t" by (simp only: s t deg_pm_plus) qed lemma lookup_hom_component: "lookup (hom_component p n) = (\<lambda>t. lookup p t when deg_pm t = n)" by (rule ext) (simp add: hom_component_def lookup_except) lemma keys_hom_component: "keys (hom_component p n) = {t. t \<in> keys p \<and> deg_pm t = n}" by (auto simp: hom_component_def keys_except) lemma keys_hom_componentD: assumes "t \<in> keys (hom_component p n)" shows "t \<in> keys p" and "deg_pm t = n" using assms by (simp_all add: keys_hom_component) lemma homogeneous_hom_component: "homogeneous (hom_component p n)" by (auto dest: keys_hom_componentD intro: homogeneousI) lemma hom_component_zero [simp]: "hom_component 0 = 0" by (rule ext) (simp add: hom_component_def) lemma hom_component_zero_iff: "hom_component p n = 0 \<longleftrightarrow> (\<forall>t\<in>keys p. deg_pm t \<noteq> n)" by (metis (mono_tags, lifting) empty_iff keys_eq_empty_iff keys_hom_component mem_Collect_eq subsetI subset_antisym) lemma hom_component_uminus [simp]: "hom_component (- p) = - hom_component p" by (intro ext poly_mapping_eqI) (simp add: hom_component_def lookup_except) lemma hom_component_plus: "hom_component (p + q) n = hom_component p n + hom_component q n" by (rule poly_mapping_eqI) (simp add: hom_component_def lookup_except lookup_add) lemma hom_component_minus: "hom_component (p - q) n = hom_component p n - hom_component q n" by (rule poly_mapping_eqI) (simp add: hom_component_def lookup_except lookup_minus) lemma hom_component_monom_mult: "punit.monom_mult c t (hom_component p n) = hom_component (punit.monom_mult c t p) (deg_pm t + n)" by (auto simp: hom_component_def lookup_except punit.lookup_monom_mult deg_pm_minus deg_pm_mono intro!: poly_mapping_eqI) lemma hom_component_inject: assumes "t \<in> keys p" and "hom_component p (deg_pm t) = hom_component p n" shows "deg_pm t = n" proof - from assms(1) have "t \<in> keys (hom_component p (deg_pm t))" by (simp add: keys_hom_component) hence "0 \<noteq> lookup (hom_component p (deg_pm t)) t" by (simp add: in_keys_iff) also have "lookup (hom_component p (deg_pm t)) t = lookup (hom_component p n) t" by (simp only: assms(2)) also have "\<dots> = (lookup p t when deg_pm t = n)" by (simp only: lookup_hom_component) finally show ?thesis by simp qed lemma hom_component_of_homogeneous: assumes "homogeneous p" shows "hom_component p n = (p when n = poly_deg p)" proof (cases "n = poly_deg p") case True have "hom_component p n = p" proof (rule poly_mapping_eqI) fix t show "lookup (hom_component p n) t = lookup p t" proof (cases "t \<in> keys p") case True with assms have "deg_pm t = n" unfolding \<open>n = poly_deg p\<close> by (rule homogeneousD_poly_deg) thus ?thesis by (simp add: lookup_hom_component) next case False moreover from this have "t \<notin> keys (hom_component p n)" by (simp add: keys_hom_component) ultimately show ?thesis by (simp add: in_keys_iff) qed qed with True show ?thesis by simp next case False have "hom_component p n = 0" unfolding hom_component_zero_iff proof (intro ballI notI) fix t assume "t \<in> keys p" with assms have "deg_pm t = poly_deg p" by (rule homogeneousD_poly_deg) moreover assume "deg_pm t = n" ultimately show False using False by simp qed with False show ?thesis by simp qed lemma hom_components_zero [simp]: "hom_components 0 = {}" by (simp add: hom_components_def) lemma hom_components_zero_iff [simp]: "hom_components p = {} \<longleftrightarrow> p = 0" by (simp add: hom_components_def) lemma hom_components_uminus: "hom_components (- p) = uminus ` hom_components p" by (simp add: hom_components_def keys_uminus image_image) lemma hom_componentsI: "q = hom_component p (deg_pm t) \<Longrightarrow> t \<in> keys p \<Longrightarrow> q \<in> hom_components p" unfolding hom_components_def by blast lemma hom_componentsE: assumes "q \<in> hom_components p" obtains t where "t \<in> keys p" and "q = hom_component p (deg_pm t)" using assms unfolding hom_components_def by blast lemma hom_components_of_homogeneous: assumes "homogeneous p" shows "hom_components p = (if p = 0 then {} else {p})" proof (split if_split, intro conjI impI) assume "p \<noteq> 0" have "deg_pm ` keys p = {poly_deg p}" proof (rule set_eqI) fix n have "n \<in> deg_pm ` keys p \<longleftrightarrow> n = poly_deg p" proof assume "n \<in> deg_pm ` keys p" then obtain t where "t \<in> keys p" and "n = deg_pm t" .. from assms this(1) have "deg_pm t = poly_deg p" by (rule homogeneousD_poly_deg) thus "n = poly_deg p" by (simp only: \<open>n = deg_pm t\<close>) next assume "n = poly_deg p" from \<open>p \<noteq> 0\<close> have "keys p \<noteq> {}" by simp then obtain t where "t \<in> keys p" by blast with assms have "deg_pm t = poly_deg p" by (rule homogeneousD_poly_deg) hence "n = deg_pm t" by (simp only: \<open>n = poly_deg p\<close>) with \<open>t \<in> keys p\<close> show "n \<in> deg_pm ` keys p" by (rule rev_image_eqI) qed thus "n \<in> deg_pm ` keys p \<longleftrightarrow> n \<in> {poly_deg p}" by simp qed with assms show "hom_components p = {p}" by (simp add: hom_components_def hom_component_of_homogeneous) qed simp lemma finite_hom_components: "finite (hom_components p)" unfolding hom_components_def using finite_keys by (intro finite_imageI) lemma hom_components_homogeneous: "q \<in> hom_components p \<Longrightarrow> homogeneous q" by (elim hom_componentsE) (simp only: homogeneous_hom_component) lemma hom_components_nonzero: "q \<in> hom_components p \<Longrightarrow> q \<noteq> 0" by (auto elim!: hom_componentsE simp: hom_component_zero_iff) lemma deg_pm_hom_components: assumes "q1 \<in> hom_components p" and "q2 \<in> hom_components p" and "t1 \<in> keys q1" and "t2 \<in> keys q2" shows "deg_pm t1 = deg_pm t2 \<longleftrightarrow> q1 = q2" proof - from assms(1) obtain s1 where "s1 \<in> keys p" and q1: "q1 = hom_component p (deg_pm s1)" by (rule hom_componentsE) from assms(3) have t1: "deg_pm t1 = deg_pm s1" unfolding q1 by (rule keys_hom_componentD) from assms(2) obtain s2 where "s2 \<in> keys p" and q2: "q2 = hom_component p (deg_pm s2)" by (rule hom_componentsE) from assms(4) have t2: "deg_pm t2 = deg_pm s2" unfolding q2 by (rule keys_hom_componentD) from \<open>s1 \<in> keys p\<close> show ?thesis by (auto simp: q1 q2 t1 t2 dest: hom_component_inject) qed lemma poly_deg_hom_components: assumes "q1 \<in> hom_components p" and "q2 \<in> hom_components p" shows "poly_deg q1 = poly_deg q2 \<longleftrightarrow> q1 = q2" proof - from assms(1) have "homogeneous q1" and "q1 \<noteq> 0" by (rule hom_components_homogeneous, rule hom_components_nonzero) from this(2) have "keys q1 \<noteq> {}" by simp then obtain t1 where "t1 \<in> keys q1" by blast with \<open>homogeneous q1\<close> have t1: "deg_pm t1 = poly_deg q1" by (rule homogeneousD_poly_deg) from assms(2) have "homogeneous q2" and "q2 \<noteq> 0" by (rule hom_components_homogeneous, rule hom_components_nonzero) from this(2) have "keys q2 \<noteq> {}" by simp then obtain t2 where "t2 \<in> keys q2" by blast with \<open>homogeneous q2\<close> have t2: "deg_pm t2 = poly_deg q2" by (rule homogeneousD_poly_deg) from assms \<open>t1 \<in> keys q1\<close> \<open>t2 \<in> keys q2\<close> have "deg_pm t1 = deg_pm t2 \<longleftrightarrow> q1 = q2" by (rule deg_pm_hom_components) thus ?thesis by (simp only: t1 t2) qed lemma hom_components_keys_disjoint: assumes "q1 \<in> hom_components p" and "q2 \<in> hom_components p" and "q1 \<noteq> q2" shows "keys q1 \<inter> keys q2 = {}" proof (rule ccontr) assume "keys q1 \<inter> keys q2 \<noteq> {}" then obtain t where "t \<in> keys q1" and "t \<in> keys q2" by blast with assms(1, 2) have "deg_pm t = deg_pm t \<longleftrightarrow> q1 = q2" by (rule deg_pm_hom_components) with assms(3) show False by simp qed lemma Keys_hom_components: "Keys (hom_components p) = keys p" by (auto simp: Keys_def hom_components_def keys_hom_component) lemma lookup_hom_components: "q \<in> hom_components p \<Longrightarrow> t \<in> keys q \<Longrightarrow> lookup q t = lookup p t" by (auto elim!: hom_componentsE simp: keys_hom_component lookup_hom_component) lemma poly_deg_hom_components_le: assumes "q \<in> hom_components p" shows "poly_deg q \<le> poly_deg p" proof (rule poly_deg_leI) fix t assume "t \<in> keys q" also from assms have "\<dots> \<subseteq> Keys (hom_components p)" by (rule keys_subset_Keys) also have "\<dots> = keys p" by (fact Keys_hom_components) finally show "deg_pm t \<le> poly_deg p" by (rule poly_deg_max_keys) qed lemma sum_hom_components: "\<Sum>(hom_components p) = p" proof (rule poly_mapping_eqI) fix t show "lookup (\<Sum>(hom_components p)) t = lookup p t" unfolding lookup_sum proof (cases "t \<in> keys p") case True also have "keys p = Keys (hom_components p)" by (simp only: Keys_hom_components) finally obtain q where q: "q \<in> hom_components p" and t: "t \<in> keys q" by (rule in_KeysE) from this(1) have "(\<Sum>q0\<in>hom_components p. lookup q0 t) = (\<Sum>q0\<in>insert q (hom_components p). lookup q0 t)" by (simp only: insert_absorb) also from finite_hom_components have "\<dots> = lookup q t + (\<Sum>q0\<in>hom_components p - {q}. lookup q0 t)" by (rule sum.insert_remove) also from q t have "\<dots> = lookup p t + (\<Sum>q0\<in>hom_components p - {q}. lookup q0 t)" by (simp only: lookup_hom_components) also have "(\<Sum>q0\<in>hom_components p - {q}. lookup q0 t) = 0" proof (intro sum.neutral ballI) fix q0 assume "q0 \<in> hom_components p - {q}" hence "q0 \<in> hom_components p" and "q \<noteq> q0" by blast+ with q have "keys q \<inter> keys q0 = {}" by (rule hom_components_keys_disjoint) with t have "t \<notin> keys q0" by blast thus "lookup q0 t = 0" by (simp add: in_keys_iff) qed finally show "(\<Sum>q\<in>hom_components p. lookup q t) = lookup p t" by simp next case False hence "t \<notin> Keys (hom_components p)" by (simp add: Keys_hom_components) hence "\<forall>q\<in>hom_components p. lookup q t = 0" by (simp add: Keys_def in_keys_iff) hence "(\<Sum>q\<in>hom_components p. lookup q t) = 0" by (rule sum.neutral) also from False have "\<dots> = lookup p t" by (simp add: in_keys_iff) finally show "(\<Sum>q\<in>hom_components p. lookup q t) = lookup p t" . qed qed lemma homogeneous_setI: "(\<And>a n. a \<in> A \<Longrightarrow> hom_component a n \<in> A) \<Longrightarrow> homogeneous_set A" by (simp add: homogeneous_set_def) lemma homogeneous_setD: "homogeneous_set A \<Longrightarrow> a \<in> A \<Longrightarrow> hom_component a n \<in> A" by (simp add: homogeneous_set_def) lemma homogeneous_set_Polys: "homogeneous_set (P[X]::(_ \<Rightarrow>\<^sub>0 'a::zero) set)" proof (intro homogeneous_setI PolysI subsetI) fix p::"_ \<Rightarrow>\<^sub>0 'a" and n t assume "p \<in> P[X]" assume "t \<in> keys (hom_component p n)" hence "t \<in> keys p" by (rule keys_hom_componentD) also from \<open>p \<in> P[X]\<close> have "\<dots> \<subseteq> .[X]" by (rule PolysD) finally show "t \<in> .[X]" . qed lemma homogeneous_set_IntI: "homogeneous_set A \<Longrightarrow> homogeneous_set B \<Longrightarrow> homogeneous_set (A \<inter> B)" by (simp add: homogeneous_set_def) lemma homogeneous_setD_hom_components: assumes "homogeneous_set A" and "a \<in> A" and "b \<in> hom_components a" shows "b \<in> A" proof - from assms(3) obtain t::"'a \<Rightarrow>\<^sub>0 nat" where "b = hom_component a (deg_pm t)" by (rule hom_componentsE) also from assms(1, 2) have "\<dots> \<in> A" by (rule homogeneous_setD) finally show ?thesis . qed lemma zero_in_homogeneous_set: assumes "homogeneous_set A" and "A \<noteq> {}" shows "0 \<in> A" proof - from assms(2) obtain a where "a \<in> A" by blast have "lookup a t = 0" if "deg_pm t = Suc (poly_deg a)" for t proof (rule ccontr) assume "lookup a t \<noteq> 0" hence "t \<in> keys a" by (simp add: in_keys_iff) hence "deg_pm t \<le> poly_deg a" by (rule poly_deg_max_keys) thus False by (simp add: that) qed hence "0 = hom_component a (Suc (poly_deg a))" by (intro poly_mapping_eqI) (simp add: lookup_hom_component when_def) also from assms(1) \<open>a \<in> A\<close> have "\<dots> \<in> A" by (rule homogeneous_setD) finally show ?thesis . qed lemma homogeneous_ideal: assumes "\<And>f. f \<in> F \<Longrightarrow> homogeneous f" and "p \<in> ideal F" shows "hom_component p n \<in> ideal F" proof - from assms(2) have "p \<in> punit.pmdl F" by simp thus ?thesis proof (induct p rule: punit.pmdl_induct) case module_0 show ?case by (simp add: ideal.span_zero) next case (module_plus a f c t) let ?f = "punit.monom_mult c t f" from module_plus.hyps(3) have "f \<in> punit.pmdl F" by (simp add: ideal.span_base) hence *: "?f \<in> punit.pmdl F" by (rule punit.pmdl_closed_monom_mult) from module_plus.hyps(3) have "homogeneous f" by (rule assms(1)) hence "homogeneous ?f" by (rule homogeneous_monom_mult) hence "hom_component ?f n = (?f when n = poly_deg ?f)" by (rule hom_component_of_homogeneous) also from * have "\<dots> \<in> ideal F" by (simp add: when_def ideal.span_zero) finally have "hom_component ?f n \<in> ideal F" . with module_plus.hyps(2) show ?case unfolding hom_component_plus by (rule ideal.span_add) qed qed corollary homogeneous_set_homogeneous_ideal: "(\<And>f. f \<in> F \<Longrightarrow> homogeneous f) \<Longrightarrow> homogeneous_set (ideal F)" by (auto intro: homogeneous_setI homogeneous_ideal) corollary homogeneous_ideal': assumes "\<And>f. f \<in> F \<Longrightarrow> homogeneous f" and "p \<in> ideal F" and "q \<in> hom_components p" shows "q \<in> ideal F" using _ assms(2, 3) proof (rule homogeneous_setD_hom_components) from assms(1) show "homogeneous_set (ideal F)" by (rule homogeneous_set_homogeneous_ideal) qed lemma homogeneous_idealE_homogeneous: assumes "\<And>f. f \<in> F \<Longrightarrow> homogeneous f" and "p \<in> ideal F" and "homogeneous p" obtains F' q where "finite F'" and "F' \<subseteq> F" and "p = (\<Sum>f\<in>F'. q f * f)" and "\<And>f. homogeneous (q f)" and "\<And>f. f \<in> F' \<Longrightarrow> poly_deg (q f * f) = poly_deg p" and "\<And>f. f \<notin> F' \<Longrightarrow> q f = 0" proof - from assms(2) obtain F'' q' where "finite F''" and "F'' \<subseteq> F" and p: "p = (\<Sum>f\<in>F''. q' f * f)" by (rule ideal.spanE) let ?A = "\<lambda>f. {h \<in> hom_components (q' f). poly_deg h + poly_deg f = poly_deg p}" let ?B = "\<lambda>f. {h \<in> hom_components (q' f). poly_deg h + poly_deg f \<noteq> poly_deg p}" define F' where "F' = {f \<in> F''. (\<Sum>(?A f)) * f \<noteq> 0}" define q where "q = (\<lambda>f. (\<Sum>(?A f)) when f \<in> F')" have "F' \<subseteq> F''" by (simp add: F'_def) hence "F' \<subseteq> F" using \<open>F'' \<subseteq> F\<close> by (rule subset_trans) have 1: "deg_pm t + poly_deg f = poly_deg p" if "f \<in> F'" and "t \<in> keys (q f)" for f t proof - from that have "t \<in> keys (\<Sum>(?A f))" by (simp add: q_def) also have "\<dots> \<subseteq> (\<Union>h\<in>?A f. keys h)" by (fact keys_sum_subset) finally obtain h where "h \<in> ?A f" and "t \<in> keys h" .. from this(1) have "h \<in> hom_components (q' f)" and eq: "poly_deg h + poly_deg f = poly_deg p" by simp_all from this(1) have "homogeneous h" by (rule hom_components_homogeneous) hence "deg_pm t = poly_deg h" using \<open>t \<in> keys h\<close> by (rule homogeneousD_poly_deg) thus ?thesis by (simp only: eq) qed have 2: "deg_pm t = poly_deg p" if "f \<in> F'" and "t \<in> keys (q f * f)" for f t proof - from that(1) \<open>F' \<subseteq> F\<close> have "f \<in> F" .. hence "homogeneous f" by (rule assms(1)) from that(2) obtain s1 s2 where "s1 \<in> keys (q f)" and "s2 \<in> keys f" and t: "t = s1 + s2" by (rule in_keys_timesE) from that(1) this(1) have "deg_pm s1 + poly_deg f = poly_deg p" by (rule 1) moreover from \<open>homogeneous f\<close> \<open>s2 \<in> keys f\<close> have "deg_pm s2 = poly_deg f" by (rule homogeneousD_poly_deg) ultimately show ?thesis by (simp add: t deg_pm_plus) qed from \<open>F' \<subseteq> F''\<close> \<open>finite F''\<close> have "finite F'" by (rule finite_subset) thus ?thesis using \<open>F' \<subseteq> F\<close> proof note p also from refl have "(\<Sum>f\<in>F''. q' f * f) = (\<Sum>f\<in>F''. (\<Sum>(?A f) * f) + (\<Sum>(?B f) * f))" proof (rule sum.cong) fix f assume "f \<in> F''" from sum_hom_components have "q' f = (\<Sum>(hom_components (q' f)))" by (rule sym) also have "\<dots> = (\<Sum>(?A f \<union> ?B f))" by (rule arg_cong[where f="sum (\<lambda>x. x)"]) blast also have "\<dots> = \<Sum>(?A f) + \<Sum>(?B f)" proof (rule sum.union_disjoint) have "?A f \<subseteq> hom_components (q' f)" by blast thus "finite (?A f)" using finite_hom_components by (rule finite_subset) next have "?B f \<subseteq> hom_components (q' f)" by blast thus "finite (?B f)" using finite_hom_components by (rule finite_subset) qed blast finally show "q' f * f = (\<Sum>(?A f) * f) + (\<Sum>(?B f) * f)" by (metis (no_types, lifting) distrib_right) qed also have "\<dots> = (\<Sum>f\<in>F''. \<Sum>(?A f) * f) + (\<Sum>f\<in>F''. \<Sum>(?B f) * f)" by (rule sum.distrib) also from \<open>finite F''\<close> \<open>F' \<subseteq> F''\<close> have "(\<Sum>f\<in>F''. \<Sum>(?A f) * f) = (\<Sum>f\<in>F'. q f * f)" proof (intro sum.mono_neutral_cong_right ballI) fix f assume "f \<in> F'' - F'" thus "\<Sum>(?A f) * f = 0" by (simp add: F'_def) next fix f assume "f \<in> F'" thus "\<Sum>(?A f) * f = q f * f" by (simp add: q_def) qed finally have p[symmetric]: "p = (\<Sum>f\<in>F'. q f * f) + (\<Sum>f\<in>F''. \<Sum>(?B f) * f)" . moreover have "keys (\<Sum>f\<in>F''. \<Sum>(?B f) * f) = {}" proof (rule, rule) fix t assume t_in: "t \<in> keys (\<Sum>f\<in>F''. \<Sum>(?B f) * f)" also have "\<dots> \<subseteq> (\<Union>f\<in>F''. keys (\<Sum>(?B f) * f))" by (fact keys_sum_subset) finally obtain f where "f \<in> F''" and "t \<in> keys (\<Sum>(?B f) * f)" .. from this(2) obtain s1 s2 where "s1 \<in> keys (\<Sum>(?B f))" and "s2 \<in> keys f" and t: "t = s1 + s2" by (rule in_keys_timesE) from \<open>f \<in> F''\<close> \<open>F'' \<subseteq> F\<close> have "f \<in> F" .. hence "homogeneous f" by (rule assms(1)) note \<open>s1 \<in> keys (\<Sum>(?B f))\<close> also have "keys (\<Sum>(?B f)) \<subseteq> (\<Union>h\<in>?B f. keys h)" by (fact keys_sum_subset) finally obtain h where "h \<in> ?B f" and "s1 \<in> keys h" .. from this(1) have "h \<in> hom_components (q' f)" and neq: "poly_deg h + poly_deg f \<noteq> poly_deg p" by simp_all from this(1) have "homogeneous h" by (rule hom_components_homogeneous) hence "deg_pm s1 = poly_deg h" using \<open>s1 \<in> keys h\<close> by (rule homogeneousD_poly_deg) moreover from \<open>homogeneous f\<close> \<open>s2 \<in> keys f\<close> have "deg_pm s2 = poly_deg f" by (rule homogeneousD_poly_deg) ultimately have "deg_pm t \<noteq> poly_deg p" using neq by (simp add: t deg_pm_plus) have "t \<notin> keys (\<Sum>f\<in>F'. q f * f)" proof assume "t \<in> keys (\<Sum>f\<in>F'. q f * f)" also have "\<dots> \<subseteq> (\<Union>f\<in>F'. keys (q f * f))" by (fact keys_sum_subset) finally obtain f where "f \<in> F'" and "t \<in> keys (q f * f)" .. hence "deg_pm t = poly_deg p" by (rule 2) with \<open>deg_pm t \<noteq> poly_deg p\<close> show False .. qed with t_in have "t \<in> keys ((\<Sum>f\<in>F'. q f * f) + (\<Sum>f\<in>F''. \<Sum>(?B f) * f))" by (rule in_keys_plusI2) hence "t \<in> keys p" by (simp only: p) with assms(3) have "deg_pm t = poly_deg p" by (rule homogeneousD_poly_deg) with \<open>deg_pm t \<noteq> poly_deg p\<close> show "t \<in> {}" .. qed (fact empty_subsetI) ultimately show "p = (\<Sum>f\<in>F'. q f * f)" by simp next fix f show "homogeneous (q f)" proof (cases "f \<in> F'") case True show ?thesis proof (rule homogeneousI) fix s t assume "s \<in> keys (q f)" with True have *: "deg_pm s + poly_deg f = poly_deg p" by (rule 1) assume "t \<in> keys (q f)" with True have "deg_pm t + poly_deg f = poly_deg p" by (rule 1) with * show "deg_pm s = deg_pm t" by simp qed next case False thus ?thesis by (simp add: q_def) qed assume "f \<in> F'" show "poly_deg (q f * f) = poly_deg p" proof (intro antisym) show "poly_deg (q f * f) \<le> poly_deg p" proof (rule poly_deg_leI) fix t assume "t \<in> keys (q f * f)" with \<open>f \<in> F'\<close> have "deg_pm t = poly_deg p" by (rule 2) thus "deg_pm t \<le> poly_deg p" by simp qed next from \<open>f \<in> F'\<close> have "q f * f \<noteq> 0" by (simp add: q_def F'_def) hence "keys (q f * f) \<noteq> {}" by simp then obtain t where "t \<in> keys (q f * f)" by blast with \<open>f \<in> F'\<close> have "deg_pm t = poly_deg p" by (rule 2) moreover from \<open>t \<in> keys (q f * f)\<close> have "deg_pm t \<le> poly_deg (q f * f)" by (rule poly_deg_max_keys) ultimately show "poly_deg p \<le> poly_deg (q f * f)" by simp qed qed (simp add: q_def) qed corollary homogeneous_idealE: assumes "\<And>f. f \<in> F \<Longrightarrow> homogeneous f" and "p \<in> ideal F" obtains F' q where "finite F'" and "F' \<subseteq> F" and "p = (\<Sum>f\<in>F'. q f * f)" and "\<And>f. poly_deg (q f * f) \<le> poly_deg p" and "\<And>f. f \<notin> F' \<Longrightarrow> q f = 0" proof (cases "p = 0") case True show ?thesis proof show "p = (\<Sum>f\<in>{}. (\<lambda>_. 0) f * f)" by (simp add: True) qed simp_all next case False define P where "P = (\<lambda>h qf. finite (fst qf) \<and> fst qf \<subseteq> F \<and> h = (\<Sum>f\<in>fst qf. snd qf f * f) \<and> (\<forall>f\<in>fst qf. poly_deg (snd qf f * f) = poly_deg h) \<and> (\<forall>f. f \<notin> fst qf \<longrightarrow> snd qf f = 0))" define q0 where "q0 = (\<lambda>h. SOME qf. P h qf)" have 1: "P h (q0 h)" if "h \<in> hom_components p" for h proof - note assms(1) moreover from assms that have "h \<in> ideal F" by (rule homogeneous_ideal') moreover from that have "homogeneous h" by (rule hom_components_homogeneous) ultimately obtain F' q where "finite F'" and "F' \<subseteq> F" and "h = (\<Sum>f\<in>F'. q f * f)" and "\<And>f. f \<in> F' \<Longrightarrow> poly_deg (q f * f) = poly_deg h" and "\<And>f. f \<notin> F' \<Longrightarrow> q f = 0" by (rule homogeneous_idealE_homogeneous) blast+ hence "P h (F', q)" by (simp add: P_def) thus ?thesis unfolding q0_def by (rule someI) qed define F' where "F' = (\<Union>h\<in>hom_components p. fst (q0 h))" define q where "q = (\<lambda>f. \<Sum>h\<in>hom_components p. snd (q0 h) f)" show ?thesis proof have "finite F' \<and> F' \<subseteq> F" unfolding F'_def UN_subset_iff finite_UN[OF finite_hom_components] proof (intro conjI ballI) fix h assume "h \<in> hom_components p" hence "P h (q0 h)" by (rule 1) thus "finite (fst (q0 h))" and "fst (q0 h) \<subseteq> F" by (simp_all only: P_def) qed thus "finite F'" and "F' \<subseteq> F" by simp_all from sum_hom_components have "p = (\<Sum>(hom_components p))" by (rule sym) also from refl have "\<dots> = (\<Sum>h\<in>hom_components p. \<Sum>f\<in>F'. snd (q0 h) f * f)" proof (rule sum.cong) fix h assume "h \<in> hom_components p" hence "P h (q0 h)" by (rule 1) hence "h = (\<Sum>f\<in>fst (q0 h). snd (q0 h) f * f)" and 2: "\<And>f. f \<notin> fst (q0 h) \<Longrightarrow> snd (q0 h) f = 0" by (simp_all add: P_def) note this(1) also from \<open>finite F'\<close> have "(\<Sum>f\<in>fst (q0 h). (snd (q0 h)) f * f) = (\<Sum>f\<in>F'. snd (q0 h) f * f)" proof (intro sum.mono_neutral_left ballI) show "fst (q0 h) \<subseteq> F'" unfolding F'_def using \<open>h \<in> hom_components p\<close> by blast next fix f assume "f \<in> F' - fst (q0 h)" hence "f \<notin> fst (q0 h)" by simp hence "snd (q0 h) f = 0" by (rule 2) thus "snd (q0 h) f * f = 0" by simp qed finally show "h = (\<Sum>f\<in>F'. snd (q0 h) f * f)" . qed also have "\<dots> = (\<Sum>f\<in>F'. \<Sum>h\<in>hom_components p. snd (q0 h) f * f)" by (rule sum.swap) also have "\<dots> = (\<Sum>f\<in>F'. q f * f)" by (simp only: q_def sum_distrib_right) finally show "p = (\<Sum>f\<in>F'. q f * f)" . fix f have "poly_deg (q f * f) = poly_deg (\<Sum>h\<in>hom_components p. snd (q0 h) f * f)" by (simp only: q_def sum_distrib_right) also have "\<dots> \<le> Max (poly_deg ` (\<lambda>h. snd (q0 h) f * f) ` hom_components p)" by (rule poly_deg_sum_le) also have "\<dots> = Max ((\<lambda>h. poly_deg (snd (q0 h) f * f)) ` hom_components p)" (is "_ = Max (?f ` _)") by (simp only: image_image) also have "\<dots> \<le> poly_deg p" proof (rule Max.boundedI) from finite_hom_components show "finite (?f ` hom_components p)" by (rule finite_imageI) next from False show "?f ` hom_components p \<noteq> {}" by simp next fix d assume "d \<in> ?f ` hom_components p" then obtain h where "h \<in> hom_components p" and d: "d = ?f h" .. from this(1) have "P h (q0 h)" by (rule 1) hence 2: "\<And>f. f \<in> fst (q0 h) \<Longrightarrow> poly_deg (snd (q0 h) f * f) = poly_deg h" and 3: "\<And>f. f \<notin> fst (q0 h) \<Longrightarrow> snd (q0 h) f = 0" by (simp_all add: P_def) show "d \<le> poly_deg p" proof (cases "f \<in> fst (q0 h)") case True hence "poly_deg (snd (q0 h) f * f) = poly_deg h" by (rule 2) hence "d = poly_deg h" by (simp only: d) also from \<open>h \<in> hom_components p\<close> have "\<dots> \<le> poly_deg p" by (rule poly_deg_hom_components_le) finally show ?thesis . next case False hence "snd (q0 h) f = 0" by (rule 3) thus ?thesis by (simp add: d) qed qed finally show "poly_deg (q f * f) \<le> poly_deg p" . assume "f \<notin> F'" show "q f = 0" unfolding q_def proof (intro sum.neutral ballI) fix h assume "h \<in> hom_components p" hence "P h (q0 h)" by (rule 1) hence 2: "\<And>f. f \<notin> fst (q0 h) \<Longrightarrow> snd (q0 h) f = 0" by (simp add: P_def) show "snd (q0 h) f = 0" proof (intro 2 notI) assume "f \<in> fst (q0 h)" hence "f \<in> F'" unfolding F'_def using \<open>h \<in> hom_components p\<close> by blast with \<open>f \<notin> F'\<close> show False .. qed qed qed qed corollary homogeneous_idealE_finite: assumes "finite F" and "\<And>f. f \<in> F \<Longrightarrow> homogeneous f" and "p \<in> ideal F" obtains q where "p = (\<Sum>f\<in>F. q f * f)" and "\<And>f. poly_deg (q f * f) \<le> poly_deg p" and "\<And>f. f \<notin> F \<Longrightarrow> q f = 0" proof - from assms(2, 3) obtain F' q where "F' \<subseteq> F" and p: "p = (\<Sum>f\<in>F'. q f * f)" and "\<And>f. poly_deg (q f * f) \<le> poly_deg p" and 1: "\<And>f. f \<notin> F' \<Longrightarrow> q f = 0" by (rule homogeneous_idealE) blast+ show ?thesis proof from assms(1) \<open>F' \<subseteq> F\<close> have "(\<Sum>f\<in>F'. q f * f) = (\<Sum>f\<in>F. q f * f)" proof (intro sum.mono_neutral_left ballI) fix f assume "f \<in> F - F'" hence "f \<notin> F'" by simp hence "q f = 0" by (rule 1) thus "q f * f = 0" by simp qed thus "p = (\<Sum>f\<in>F. q f * f)" by (simp only: p) next fix f show "poly_deg (q f * f) \<le> poly_deg p" by fact assume "f \<notin> F" with \<open>F' \<subseteq> F\<close> have "f \<notin> F'" by blast thus "q f = 0" by (rule 1) qed qed subsubsection \<open>Homogenization and Dehomogenization\<close> definition homogenize :: "'x \<Rightarrow> (('x \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 'a) \<Rightarrow> (('x \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 'a::semiring_1)" where "homogenize x p = (\<Sum>t\<in>keys p. monomial (lookup p t) (Poly_Mapping.single x (poly_deg p - deg_pm t) + t))" definition dehomo_subst :: "'x \<Rightarrow> 'x \<Rightarrow> (('x \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 'a::zero_neq_one)" where "dehomo_subst x = (\<lambda>y. if y = x then 1 else monomial 1 (Poly_Mapping.single y 1))" definition dehomogenize :: "'x \<Rightarrow> (('x \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 'a) \<Rightarrow> (('x \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 'a::comm_semiring_1)" where "dehomogenize x = poly_subst (dehomo_subst x)" lemma homogenize_zero [simp]: "homogenize x 0 = 0" by (simp add: homogenize_def) lemma homogenize_uminus [simp]: "homogenize x (- p) = - homogenize x (p::_ \<Rightarrow>\<^sub>0 'a::ring_1)" by (simp add: homogenize_def keys_uminus sum.reindex inj_on_def single_uminus sum_negf) lemma homogenize_monom_mult [simp]: "homogenize x (punit.monom_mult c t p) = punit.monom_mult c t (homogenize x p)" for c::"'a::{semiring_1,semiring_no_zero_divisors_cancel}" proof (cases "p = 0") case True thus ?thesis by simp next case False show ?thesis proof (cases "c = 0") case True thus ?thesis by simp next case False show ?thesis by (simp add: homogenize_def punit.keys_monom_mult \<open>p \<noteq> 0\<close> False sum.reindex punit.lookup_monom_mult punit.monom_mult_sum_right poly_deg_monom_mult punit.monom_mult_monomial ac_simps deg_pm_plus) qed qed lemma homogenize_alt: "homogenize x p = (\<Sum>q\<in>hom_components p. punit.monom_mult 1 (Poly_Mapping.single x (poly_deg p - poly_deg q)) q)" proof - have "homogenize x p = (\<Sum>t\<in>Keys (hom_components p). monomial (lookup p t) (Poly_Mapping.single x (poly_deg p - deg_pm t) + t))" by (simp only: homogenize_def Keys_hom_components) also have "\<dots> = (\<Sum>t\<in>(\<Union> (keys ` hom_components p)). monomial (lookup p t) (Poly_Mapping.single x (poly_deg p - deg_pm t) + t))" by (simp only: Keys_def) also have "\<dots> = (\<Sum>q\<in>hom_components p. (\<Sum>t\<in>keys q. monomial (lookup p t) (Poly_Mapping.single x (poly_deg p - deg_pm t) + t)))" by (auto intro!: sum.UNION_disjoint finite_hom_components finite_keys dest: hom_components_keys_disjoint) also have "\<dots> = (\<Sum>q\<in>hom_components p. punit.monom_mult 1 (Poly_Mapping.single x (poly_deg p - poly_deg q)) q)" using refl proof (rule sum.cong) fix q assume q: "q \<in> hom_components p" hence "homogeneous q" by (rule hom_components_homogeneous) have "(\<Sum>t\<in>keys q. monomial (lookup p t) (Poly_Mapping.single x (poly_deg p - deg_pm t) + t)) = (\<Sum>t\<in>keys q. punit.monom_mult 1 (Poly_Mapping.single x (poly_deg p - poly_deg q)) (monomial (lookup q t) t))" using refl proof (rule sum.cong) fix t assume "t \<in> keys q" with \<open>homogeneous q\<close> have "deg_pm t = poly_deg q" by (rule homogeneousD_poly_deg) moreover from q \<open>t \<in> keys q\<close> have "lookup q t = lookup p t" by (rule lookup_hom_components) ultimately show "monomial (lookup p t) (Poly_Mapping.single x (poly_deg p - deg_pm t) + t) = punit.monom_mult 1 (Poly_Mapping.single x (poly_deg p - poly_deg q)) (monomial (lookup q t) t)" by (simp add: punit.monom_mult_monomial) qed also have "\<dots> = punit.monom_mult 1 (Poly_Mapping.single x (poly_deg p - poly_deg q)) q" by (simp only: poly_mapping_sum_monomials flip: punit.monom_mult_sum_right) finally show "(\<Sum>t\<in>keys q. monomial (lookup p t) (Poly_Mapping.single x (poly_deg p - deg_pm t) + t)) = punit.monom_mult 1 (Poly_Mapping.single x (poly_deg p - poly_deg q)) q" . qed finally show ?thesis . qed lemma keys_homogenizeE: assumes "t \<in> keys (homogenize x p)" obtains t' where "t' \<in> keys p" and "t = Poly_Mapping.single x (poly_deg p - deg_pm t') + t'" proof - note assms also have "keys (homogenize x p) \<subseteq> (\<Union>t\<in>keys p. keys (monomial (lookup p t) (Poly_Mapping.single x (poly_deg p - deg_pm t) + t)))" unfolding homogenize_def by (rule keys_sum_subset) finally obtain t' where "t' \<in> keys p" and "t \<in> keys (monomial (lookup p t') (Poly_Mapping.single x (poly_deg p - deg_pm t') + t'))" .. from this(2) have "t = Poly_Mapping.single x (poly_deg p - deg_pm t') + t'" by (simp split: if_split_asm) with \<open>t' \<in> keys p\<close> show ?thesis .. qed lemma keys_homogenizeE_alt: assumes "t \<in> keys (homogenize x p)" obtains q t' where "q \<in> hom_components p" and "t' \<in> keys q" and "t = Poly_Mapping.single x (poly_deg p - poly_deg q) + t'" proof - note assms also have "keys (homogenize x p) \<subseteq> (\<Union>q\<in>hom_components p. keys (punit.monom_mult 1 (Poly_Mapping.single x (poly_deg p - poly_deg q)) q))" unfolding homogenize_alt by (rule keys_sum_subset) finally obtain q where q: "q \<in> hom_components p" and "t \<in> keys (punit.monom_mult 1 (Poly_Mapping.single x (poly_deg p - poly_deg q)) q)" .. note this(2) also have "\<dots> \<subseteq> (+) (Poly_Mapping.single x (poly_deg p - poly_deg q)) ` keys q" by (rule punit.keys_monom_mult_subset[simplified]) finally obtain t' where "t' \<in> keys q" and "t = Poly_Mapping.single x (poly_deg p - poly_deg q) + t'" .. with q show ?thesis .. qed lemma deg_pm_homogenize: assumes "t \<in> keys (homogenize x p)" shows "deg_pm t = poly_deg p" proof - from assms obtain q t' where q: "q \<in> hom_components p" and "t' \<in> keys q" and t: "t = Poly_Mapping.single x (poly_deg p - poly_deg q) + t'" by (rule keys_homogenizeE_alt) from q have "homogeneous q" by (rule hom_components_homogeneous) hence "deg_pm t' = poly_deg q" using \<open>t' \<in> keys q\<close> by (rule homogeneousD_poly_deg) moreover from q have "poly_deg q \<le> poly_deg p" by (rule poly_deg_hom_components_le) ultimately show ?thesis by (simp add: t deg_pm_plus deg_pm_single) qed corollary homogeneous_homogenize: "homogeneous (homogenize x p)" proof (rule homogeneousI) fix s t assume "s \<in> keys (homogenize x p)" hence *: "deg_pm s = poly_deg p" by (rule deg_pm_homogenize) assume "t \<in> keys (homogenize x p)" hence "deg_pm t = poly_deg p" by (rule deg_pm_homogenize) with * show "deg_pm s = deg_pm t" by simp qed corollary poly_deg_homogenize_le: "poly_deg (homogenize x p) \<le> poly_deg p" proof (rule poly_deg_leI) fix t assume "t \<in> keys (homogenize x p)" hence "deg_pm t = poly_deg p" by (rule deg_pm_homogenize) thus "deg_pm t \<le> poly_deg p" by simp qed lemma homogenize_id_iff [simp]: "homogenize x p = p \<longleftrightarrow> homogeneous p" proof assume "homogenize x p = p" moreover have "homogeneous (homogenize x p)" by (fact homogeneous_homogenize) ultimately show "homogeneous p" by simp next assume "homogeneous p" hence "hom_components p = (if p = 0 then {} else {p})" by (rule hom_components_of_homogeneous) thus "homogenize x p = p" by (simp add: homogenize_alt split: if_split_asm) qed lemma homogenize_homogenize [simp]: "homogenize x (homogenize x p) = homogenize x p" by (simp add: homogeneous_homogenize) lemma homogenize_monomial: "homogenize x (monomial c t) = monomial c t" by (simp only: homogenize_id_iff homogeneous_monomial) lemma indets_homogenize_subset: "indets (homogenize x p) \<subseteq> insert x (indets p)" proof fix y assume "y \<in> indets (homogenize x p)" then obtain t where "t \<in> keys (homogenize x p)" and "y \<in> keys t" by (rule in_indetsE) from this(1) obtain t' where "t' \<in> keys p" and t: "t = Poly_Mapping.single x (poly_deg p - deg_pm t') + t'" by (rule keys_homogenizeE) note \<open>y \<in> keys t\<close> also have "keys t \<subseteq> keys (Poly_Mapping.single x (poly_deg p - deg_pm t')) \<union> keys t'" unfolding t by (rule Poly_Mapping.keys_add) finally show "y \<in> insert x (indets p)" proof assume "y \<in> keys (Poly_Mapping.single x (poly_deg p - deg_pm t'))" thus ?thesis by (simp split: if_split_asm) next assume "y \<in> keys t'" hence "y \<in> indets p" using \<open>t' \<in> keys p\<close> by (rule in_indetsI) thus ?thesis by simp qed qed lemma homogenize_in_Polys: "p \<in> P[X] \<Longrightarrow> homogenize x p \<in> P[insert x X]" using indets_homogenize_subset[of x p] by (auto simp: Polys_alt) lemma lookup_homogenize: assumes "x \<notin> indets p" and "x \<notin> keys t" shows "lookup (homogenize x p) (Poly_Mapping.single x (poly_deg p - deg_pm t) + t) = lookup p t" proof - let ?p = "homogenize x p" let ?t = "Poly_Mapping.single x (poly_deg p - deg_pm t) + t" have eq: "(\<Sum>s\<in>keys p - {t}. lookup (monomial (lookup p s) (Poly_Mapping.single x (poly_deg p - deg_pm s) + s)) ?t) = 0" proof (intro sum.neutral ballI) fix s assume "s \<in> keys p - {t}" hence "s \<in> keys p" and "s \<noteq> t" by simp_all from this(1) have "keys s \<subseteq> indets p" by (simp add: in_indetsI subsetI) with assms(1) have "x \<notin> keys s" by blast have "?t \<noteq> Poly_Mapping.single x (poly_deg p - deg_pm s) + s" proof assume a: "?t = Poly_Mapping.single x (poly_deg p - deg_pm s) + s" hence "lookup ?t x = lookup (Poly_Mapping.single x (poly_deg p - deg_pm s) + s) x" by simp moreover from assms(2) have "lookup t x = 0" by (simp add: in_keys_iff) moreover from \<open>x \<notin> keys s\<close> have "lookup s x = 0" by (simp add: in_keys_iff) ultimately have "poly_deg p - deg_pm t = poly_deg p - deg_pm s" by (simp add: lookup_add) with a have "s = t" by simp with \<open>s \<noteq> t\<close> show False .. qed thus "lookup (monomial (lookup p s) (Poly_Mapping.single x (poly_deg p - deg_pm s) + s)) ?t = 0" by (simp add: lookup_single) qed show ?thesis proof (cases "t \<in> keys p") case True have "lookup ?p ?t = (\<Sum>s\<in>keys p. lookup (monomial (lookup p s) (Poly_Mapping.single x (poly_deg p - deg_pm s) + s)) ?t)" by (simp add: homogenize_def lookup_sum) also have "\<dots> = lookup (monomial (lookup p t) ?t) ?t + (\<Sum>s\<in>keys p - {t}. lookup (monomial (lookup p s) (Poly_Mapping.single x (poly_deg p - deg_pm s) + s)) ?t)" using finite_keys True by (rule sum.remove) also have "\<dots> = lookup p t" by (simp add: eq) finally show ?thesis . next case False hence 1: "keys p - {t} = keys p" by simp have "lookup ?p ?t = (\<Sum>s\<in>keys p - {t}. lookup (monomial (lookup p s) (Poly_Mapping.single x (poly_deg p - deg_pm s) + s)) ?t)" by (simp add: homogenize_def lookup_sum 1) also have "\<dots> = 0" by (simp only: eq) also from False have "\<dots> = lookup p t" by (simp add: in_keys_iff) finally show ?thesis . qed qed lemma keys_homogenizeI: assumes "x \<notin> indets p" and "t \<in> keys p" shows "Poly_Mapping.single x (poly_deg p - deg_pm t) + t \<in> keys (homogenize x p)" (is "?t \<in> keys ?p") proof - from assms(2) have "keys t \<subseteq> indets p" by (simp add: in_indetsI subsetI) with assms(1) have "x \<notin> keys t" by blast with assms(1) have "lookup ?p ?t = lookup p t" by (rule lookup_homogenize) also from assms(2) have "\<dots> \<noteq> 0" by (simp add: in_keys_iff) finally show ?thesis by (simp add: in_keys_iff) qed lemma keys_homogenize: "x \<notin> indets p \<Longrightarrow> keys (homogenize x p) = (\<lambda>t. Poly_Mapping.single x (poly_deg p - deg_pm t) + t) ` keys p" by (auto intro: keys_homogenizeI elim: keys_homogenizeE) lemma card_keys_homogenize: assumes "x \<notin> indets p" shows "card (keys (homogenize x p)) = card (keys p)" unfolding keys_homogenize[OF assms] proof (intro card_image inj_onI) fix s t assume "s \<in> keys p" and "t \<in> keys p" with assms have "x \<notin> keys s" and "x \<notin> keys t" by (auto dest: in_indetsI simp only:) let ?s = "Poly_Mapping.single x (poly_deg p - deg_pm s)" let ?t = "Poly_Mapping.single x (poly_deg p - deg_pm t)" assume "?s + s = ?t + t" hence "lookup (?s + s) x = lookup (?t + t) x" by simp with \<open>x \<notin> keys s\<close> \<open>x \<notin> keys t\<close> have "?s = ?t" by (simp add: lookup_add in_keys_iff) with \<open>?s + s = ?t + t\<close> show "s = t" by simp qed lemma poly_deg_homogenize: assumes "x \<notin> indets p" shows "poly_deg (homogenize x p) = poly_deg p" proof (cases "p = 0") case True thus ?thesis by simp next case False then obtain t where "t \<in> keys p" and 1: "poly_deg p = deg_pm t" by (rule poly_degE) from assms this(1) have "Poly_Mapping.single x (poly_deg p - deg_pm t) + t \<in> keys (homogenize x p)" by (rule keys_homogenizeI) hence "t \<in> keys (homogenize x p)" by (simp add: 1) hence "poly_deg p \<le> poly_deg (homogenize x p)" unfolding 1 by (rule poly_deg_max_keys) with poly_deg_homogenize_le show ?thesis by (rule antisym) qed lemma maxdeg_homogenize: assumes "x \<notin> \<Union> (indets ` F)" shows "maxdeg (homogenize x ` F) = maxdeg F" unfolding maxdeg_def image_image proof (rule arg_cong[where f=Max], rule set_eqI) fix d show "d \<in> (\<lambda>f. poly_deg (homogenize x f)) ` F \<longleftrightarrow> d \<in> poly_deg ` F" proof assume "d \<in> (\<lambda>f. poly_deg (homogenize x f)) ` F" then obtain f where "f \<in> F" and d: "d = poly_deg (homogenize x f)" .. from assms this(1) have "x \<notin> indets f" by blast hence "d = poly_deg f" by (simp add: d poly_deg_homogenize) with \<open>f \<in> F\<close> show "d \<in> poly_deg ` F" by (rule rev_image_eqI) next assume "d \<in> poly_deg ` F" then obtain f where "f \<in> F" and d: "d = poly_deg f" .. from assms this(1) have "x \<notin> indets f" by blast hence "d = poly_deg (homogenize x f)" by (simp add: d poly_deg_homogenize) with \<open>f \<in> F\<close> show "d \<in> (\<lambda>f. poly_deg (homogenize x f)) ` F" by (rule rev_image_eqI) qed qed lemma homogeneous_ideal_homogenize: assumes "\<And>f. f \<in> F \<Longrightarrow> homogeneous f" and "p \<in> ideal F" shows "homogenize x p \<in> ideal F" proof - have "homogenize x p = (\<Sum>q\<in>hom_components p. punit.monom_mult 1 (Poly_Mapping.single x (poly_deg p - poly_deg q)) q)" by (fact homogenize_alt) also have "\<dots> \<in> ideal F" proof (rule ideal.span_sum) fix q assume "q \<in> hom_components p" with assms have "q \<in> ideal F" by (rule homogeneous_ideal') thus "punit.monom_mult 1 (Poly_Mapping.single x (poly_deg p - poly_deg q)) q \<in> ideal F" by (rule punit.pmdl_closed_monom_mult[simplified]) qed finally show ?thesis . qed lemma subst_pp_dehomo_subst [simp]: "subst_pp (dehomo_subst x) t = monomial (1::'b::comm_semiring_1) (except t {x})" proof - have "subst_pp (dehomo_subst x) t = ((\<Prod>y\<in>keys t. dehomo_subst x y ^ lookup t y)::_ \<Rightarrow>\<^sub>0 'b)" by (fact subst_pp_def) also have "\<dots> = (\<Prod>y\<in>keys t - {y0. dehomo_subst x y0 ^ lookup t y0 = (1::_ \<Rightarrow>\<^sub>0 'b)}. dehomo_subst x y ^ lookup t y)" by (rule sym, rule prod.setdiff_irrelevant, fact finite_keys) also have "\<dots> = (\<Prod>y\<in>keys t - {x}. monomial 1 (Poly_Mapping.single y 1) ^ lookup t y)" proof (rule prod.cong) have "dehomo_subst x x ^ lookup t x = 1" by (simp add: dehomo_subst_def) moreover { fix y assume "y \<noteq> x" hence "dehomo_subst x y ^ lookup t y = monomial 1 (Poly_Mapping.single y (lookup t y))" by (simp add: dehomo_subst_def monomial_single_power) moreover assume "dehomo_subst x y ^ lookup t y = 1" ultimately have "Poly_Mapping.single y (lookup t y) = 0" by (smt single_one monomial_inj zero_neq_one) hence "lookup t y = 0" by (rule monomial_0D) moreover assume "y \<in> keys t" ultimately have False by (simp add: in_keys_iff) } ultimately show "keys t - {y0. dehomo_subst x y0 ^ lookup t y0 = 1} = keys t - {x}" by auto qed (simp add: dehomo_subst_def) also have "\<dots> = (\<Prod>y\<in>keys t - {x}. monomial 1 (Poly_Mapping.single y (lookup t y)))" by (simp add: monomial_single_power) also have "\<dots> = monomial 1 (\<Sum>y\<in>keys t - {x}. Poly_Mapping.single y (lookup t y))" by (simp flip: punit.monomial_prod_sum) also have "(\<Sum>y\<in>keys t - {x}. Poly_Mapping.single y (lookup t y)) = except t {x}" proof (rule poly_mapping_eqI, simp add: lookup_sum lookup_except lookup_single, rule) fix y assume "y \<noteq> x" show "(\<Sum>z\<in>keys t - {x}. lookup t z when z = y) = lookup t y" proof (cases "y \<in> keys t") case True have "finite (keys t - {x})" by simp moreover from True \<open>y \<noteq> x\<close> have "y \<in> keys t - {x}" by simp ultimately have "(\<Sum>z\<in>keys t - {x}. lookup t z when z = y) = (lookup t y when y = y) + (\<Sum>z\<in>keys t - {x} - {y}. lookup t z when z = y)" by (rule sum.remove) also have "(\<Sum>z\<in>keys t - {x} - {y}. lookup t z when z = y) = 0" by auto finally show ?thesis by simp next case False hence "(\<Sum>z\<in>keys t - {x}. lookup t z when z = y) = 0" by (auto simp: when_def) also from False have "\<dots> = lookup t y" by (simp add: in_keys_iff) finally show ?thesis . qed qed finally show ?thesis . qed lemma shows dehomogenize_zero [simp]: "dehomogenize x 0 = 0" and dehomogenize_one [simp]: "dehomogenize x 1 = 1" and dehomogenize_monomial: "dehomogenize x (monomial c t) = monomial c (except t {x})" and dehomogenize_plus: "dehomogenize x (p + q) = dehomogenize x p + dehomogenize x q" and dehomogenize_uminus: "dehomogenize x (- r) = - dehomogenize x (r::_ \<Rightarrow>\<^sub>0 _::comm_ring_1)" and dehomogenize_minus: "dehomogenize x (r - r') = dehomogenize x r - dehomogenize x r'" and dehomogenize_times: "dehomogenize x (p * q) = dehomogenize x p * dehomogenize x q" and dehomogenize_power: "dehomogenize x (p ^ n) = dehomogenize x p ^ n" and dehomogenize_sum: "dehomogenize x (sum f A) = (\<Sum>a\<in>A. dehomogenize x (f a))" and dehomogenize_prod: "dehomogenize x (prod f A) = (\<Prod>a\<in>A. dehomogenize x (f a))" by (simp_all add: dehomogenize_def poly_subst_monomial poly_subst_plus poly_subst_uminus poly_subst_minus poly_subst_times poly_subst_power poly_subst_sum poly_subst_prod punit.monom_mult_monomial) corollary dehomogenize_monom_mult: "dehomogenize x (punit.monom_mult c t p) = punit.monom_mult c (except t {x}) (dehomogenize x p)" by (simp only: times_monomial_left[symmetric] dehomogenize_times dehomogenize_monomial) lemma poly_deg_dehomogenize_le: "poly_deg (dehomogenize x p) \<le> poly_deg p" unfolding dehomogenize_def dehomo_subst_def by (rule poly_deg_poly_subst_le) (simp add: poly_deg_monomial deg_pm_single) lemma indets_dehomogenize: "indets (dehomogenize x p) \<subseteq> indets p - {x}" for p::"('x \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 'a::comm_semiring_1" proof fix y::'x assume "y \<in> indets (dehomogenize x p)" then obtain y' where "y' \<in> indets p" and "y \<in> indets ((dehomo_subst x y')::_ \<Rightarrow>\<^sub>0 'a)" unfolding dehomogenize_def by (rule in_indets_poly_substE) from this(2) have "y = y'" and "y' \<noteq> x" by (simp_all add: dehomo_subst_def indets_monomial split: if_split_asm) with \<open>y' \<in> indets p\<close> show "y \<in> indets p - {x}" by simp qed lemma dehomogenize_id_iff [simp]: "dehomogenize x p = p \<longleftrightarrow> x \<notin> indets p" proof assume eq: "dehomogenize x p = p" from indets_dehomogenize[of x p] show "x \<notin> indets p" by (auto simp: eq) next assume a: "x \<notin> indets p" show "dehomogenize x p = p" unfolding dehomogenize_def proof (rule poly_subst_id) fix y assume "y \<in> indets p" with a have "y \<noteq> x" by blast thus "dehomo_subst x y = monomial 1 (Poly_Mapping.single y 1)" by (simp add: dehomo_subst_def) qed qed lemma dehomogenize_dehomogenize [simp]: "dehomogenize x (dehomogenize x p) = dehomogenize x p" proof - from indets_dehomogenize[of x p] have "x \<notin> indets (dehomogenize x p)" by blast thus ?thesis by simp qed lemma dehomogenize_homogenize [simp]: "dehomogenize x (homogenize x p) = dehomogenize x p" proof - have "dehomogenize x (homogenize x p) = sum (dehomogenize x) (hom_components p)" by (simp add: homogenize_alt dehomogenize_sum dehomogenize_monom_mult except_single) also have "\<dots> = dehomogenize x p" by (simp only: sum_hom_components flip: dehomogenize_sum) finally show ?thesis . qed corollary dehomogenize_homogenize_id: "x \<notin> indets p \<Longrightarrow> dehomogenize x (homogenize x p) = p" by simp lemma range_dehomogenize: "range (dehomogenize x) = (P[- {x}] :: (_ \<Rightarrow>\<^sub>0 'a::comm_semiring_1) set)" proof (intro subset_antisym subsetI PolysI_alt range_eqI) fix p::"_ \<Rightarrow>\<^sub>0 'a" and y assume "p \<in> range (dehomogenize x)" then obtain q where p: "p = dehomogenize x q" .. assume "y \<in> indets p" hence "y \<in> indets (dehomogenize x q)" by (simp only: p) with indets_dehomogenize have "y \<in> indets q - {x}" .. thus "y \<in> - {x}" by simp next fix p::"_ \<Rightarrow>\<^sub>0 'a" assume "p \<in> P[- {x}]" hence "x \<notin> indets p" by (auto dest: PolysD) thus "p = dehomogenize x (homogenize x p)" by (rule dehomogenize_homogenize_id[symmetric]) qed lemma dehomogenize_alt: "dehomogenize x p = (\<Sum>t\<in>keys p. monomial (lookup p t) (except t {x}))" proof - have "dehomogenize x p = dehomogenize x (\<Sum>t\<in>keys p. monomial (lookup p t) t)" by (simp only: poly_mapping_sum_monomials) also have "\<dots> = (\<Sum>t\<in>keys p. monomial (lookup p t) (except t {x}))" by (simp only: dehomogenize_sum dehomogenize_monomial) finally show ?thesis . qed lemma keys_dehomogenizeE: assumes "t \<in> keys (dehomogenize x p)" obtains s where "s \<in> keys p" and "t = except s {x}" proof - note assms also have "keys (dehomogenize x p) \<subseteq> (\<Union>s\<in>keys p. keys (monomial (lookup p s) (except s {x})))" unfolding dehomogenize_alt by (rule keys_sum_subset) finally obtain s where "s \<in> keys p" and "t \<in> keys (monomial (lookup p s) (except s {x}))" .. from this(2) have "t = except s {x}" by (simp split: if_split_asm) with \<open>s \<in> keys p\<close> show ?thesis .. qed lemma except_inj_on_keys_homogeneous: assumes "homogeneous p" shows "inj_on (\<lambda>t. except t {x}) (keys p)" proof fix s t assume "s \<in> keys p" and "t \<in> keys p" from assms this(1) have "deg_pm s = poly_deg p" by (rule homogeneousD_poly_deg) moreover from assms \<open>t \<in> keys p\<close> have "deg_pm t = poly_deg p" by (rule homogeneousD_poly_deg) ultimately have "deg_pm (Poly_Mapping.single x (lookup s x) + except s {x}) = deg_pm (Poly_Mapping.single x (lookup t x) + except t {x})" by (simp only: flip: plus_except) moreover assume 1: "except s {x} = except t {x}" ultimately have 2: "lookup s x = lookup t x" by (simp only: deg_pm_plus deg_pm_single) show "s = t" proof (rule poly_mapping_eqI) fix y show "lookup s y = lookup t y" proof (cases "y = x") case True with 2 show ?thesis by simp next case False hence "lookup s y = lookup (except s {x}) y" and "lookup t y = lookup (except t {x}) y" by (simp_all add: lookup_except) with 1 show ?thesis by simp qed qed qed lemma lookup_dehomogenize: assumes "homogeneous p" and "t \<in> keys p" shows "lookup (dehomogenize x p) (except t {x}) = lookup p t" proof - let ?t = "except t {x}" have eq: "(\<Sum>s\<in>keys p - {t}. lookup (monomial (lookup p s) (except s {x})) ?t) = 0" proof (intro sum.neutral ballI) fix s assume "s \<in> keys p - {t}" hence "s \<in> keys p" and "s \<noteq> t" by simp_all have "?t \<noteq> except s {x}" proof from assms(1) have "inj_on (\<lambda>t. except t {x}) (keys p)" by (rule except_inj_on_keys_homogeneous) moreover assume "?t = except s {x}" ultimately have "t = s" using assms(2) \<open>s \<in> keys p\<close> by (rule inj_onD) with \<open>s \<noteq> t\<close> show False by simp qed thus "lookup (monomial (lookup p s) (except s {x})) ?t = 0" by (simp add: lookup_single) qed have "lookup (dehomogenize x p) ?t = (\<Sum>s\<in>keys p. lookup (monomial (lookup p s) (except s {x})) ?t)" by (simp only: dehomogenize_alt lookup_sum) also have "\<dots> = lookup (monomial (lookup p t) ?t) ?t + (\<Sum>s\<in>keys p - {t}. lookup (monomial (lookup p s) (except s {x})) ?t)" using finite_keys assms(2) by (rule sum.remove) also have "\<dots> = lookup p t" by (simp add: eq) finally show ?thesis . qed lemma keys_dehomogenizeI: assumes "homogeneous p" and "t \<in> keys p" shows "except t {x} \<in> keys (dehomogenize x p)" proof - from assms have "lookup (dehomogenize x p) (except t {x}) = lookup p t" by (rule lookup_dehomogenize) also from assms(2) have "\<dots> \<noteq> 0" by (simp add: in_keys_iff) finally show ?thesis by (simp add: in_keys_iff) qed lemma homogeneous_homogenize_dehomogenize: assumes "homogeneous p" obtains d where "d = poly_deg p - poly_deg (homogenize x (dehomogenize x p))" and "punit.monom_mult 1 (Poly_Mapping.single x d) (homogenize x (dehomogenize x p)) = p" proof (cases "p = 0") case True hence "0 = poly_deg p - poly_deg (homogenize x (dehomogenize x p))" and "punit.monom_mult 1 (Poly_Mapping.single x 0) (homogenize x (dehomogenize x p)) = p" by simp_all thus ?thesis .. next case False let ?q = "dehomogenize x p" let ?p = "homogenize x ?q" define d where "d = poly_deg p - poly_deg ?p" show ?thesis proof have "punit.monom_mult 1 (Poly_Mapping.single x d) ?p = (\<Sum>t\<in>keys ?q. monomial (lookup ?q t) (Poly_Mapping.single x (d + (poly_deg ?q - deg_pm t)) + t))" by (simp add: homogenize_def punit.monom_mult_sum_right punit.monom_mult_monomial flip: add.assoc single_add) also have "\<dots> = (\<Sum>t\<in>keys ?q. monomial (lookup ?q t) (Poly_Mapping.single x (poly_deg p - deg_pm t) + t))" using refl proof (rule sum.cong) fix t assume "t \<in> keys ?q" have "poly_deg ?p = poly_deg ?q" proof (rule poly_deg_homogenize) from indets_dehomogenize show "x \<notin> indets ?q" by fastforce qed hence d: "d = poly_deg p - poly_deg ?q" by (simp only: d_def) thm poly_deg_dehomogenize_le from \<open>t \<in> keys ?q\<close> have "d + (poly_deg ?q - deg_pm t) = (d + poly_deg ?q) - deg_pm t" by (intro add_diff_assoc poly_deg_max_keys) also have "d + poly_deg ?q = poly_deg p" by (simp add: d poly_deg_dehomogenize_le) finally show "monomial (lookup ?q t) (Poly_Mapping.single x (d + (poly_deg ?q - deg_pm t)) + t) = monomial (lookup ?q t) (Poly_Mapping.single x (poly_deg p - deg_pm t) + t)" by (simp only:) qed also have "\<dots> = (\<Sum>t\<in>(\<lambda>s. except s {x}) ` keys p. monomial (lookup ?q t) (Poly_Mapping.single x (poly_deg p - deg_pm t) + t))" proof (rule sum.mono_neutral_left) show "keys (dehomogenize x p) \<subseteq> (\<lambda>s. except s {x}) ` keys p" proof fix t assume "t \<in> keys (dehomogenize x p)" then obtain s where "s \<in> keys p" and "t = except s {x}" by (rule keys_dehomogenizeE) thus "t \<in> (\<lambda>s. except s {x}) ` keys p" by (rule rev_image_eqI) qed qed (simp_all add: in_keys_iff) also from assms have "\<dots> = (\<Sum>t\<in>keys p. monomial (lookup ?q (except t {x})) (Poly_Mapping.single x (poly_deg p - deg_pm (except t {x})) + except t {x}))" by (intro sum.reindex[unfolded comp_def] except_inj_on_keys_homogeneous) also from refl have "\<dots> = (\<Sum>t\<in>keys p. monomial (lookup p t) t)" proof (rule sum.cong) fix t assume "t \<in> keys p" with assms have "lookup ?q (except t {x}) = lookup p t" by (rule lookup_dehomogenize) moreover have "Poly_Mapping.single x (poly_deg p - deg_pm (except t {x})) + except t {x} = t" (is "?l = _") proof (rule poly_mapping_eqI) fix y show "lookup ?l y = lookup t y" proof (cases "y = x") case True from assms \<open>t \<in> keys p\<close> have "deg_pm t = poly_deg p" by (rule homogeneousD_poly_deg) also have "deg_pm t = deg_pm (Poly_Mapping.single x (lookup t x) + except t {x})" by (simp flip: plus_except) also have "\<dots> = lookup t x + deg_pm (except t {x})" by (simp only: deg_pm_plus deg_pm_single) finally have "poly_deg p - deg_pm (except t {x}) = lookup t x" by simp thus ?thesis by (simp add: True lookup_add lookup_except lookup_single) next case False thus ?thesis by (simp add: lookup_add lookup_except lookup_single) qed qed ultimately show "monomial (lookup ?q (except t {x})) (Poly_Mapping.single x (poly_deg p - deg_pm (except t {x})) + except t {x}) = monomial (lookup p t) t" by (simp only:) qed also have "\<dots> = p" by (fact poly_mapping_sum_monomials) finally show "punit.monom_mult 1 (Poly_Mapping.single x d) ?p = p" . qed (simp only: d_def) qed lemma dehomogenize_zeroD: assumes "dehomogenize x p = 0" and "homogeneous p" shows "p = 0" proof - from assms(2) obtain d where "punit.monom_mult 1 (Poly_Mapping.single x d) (homogenize x (dehomogenize x p)) = p" by (rule homogeneous_homogenize_dehomogenize) thus ?thesis by (simp add: assms(1)) qed lemma dehomogenize_ideal: "dehomogenize x ` ideal F = ideal (dehomogenize x ` F) \<inter> P[- {x}]" unfolding range_dehomogenize[symmetric] using dehomogenize_plus dehomogenize_times dehomogenize_dehomogenize by (rule image_ideal_eq_Int) corollary dehomogenize_ideal_subset: "dehomogenize x ` ideal F \<subseteq> ideal (dehomogenize x ` F)" by (simp add: dehomogenize_ideal) lemma ideal_dehomogenize: assumes "ideal G = ideal (homogenize x ` F)" and "F \<subseteq> P[UNIV - {x}]" shows "ideal (dehomogenize x ` G) = ideal F" proof - have eq: "dehomogenize x (homogenize x f) = f" if "f \<in> F" for f proof (rule dehomogenize_homogenize_id) from that assms(2) have "f \<in> P[UNIV - {x}]" .. thus "x \<notin> indets f" by (auto simp: Polys_alt) qed show ?thesis proof (intro Set.equalityI ideal.span_subset_spanI) show "dehomogenize x ` G \<subseteq> ideal F" proof fix q assume "q \<in> dehomogenize x ` G" then obtain g where "g \<in> G" and q: "q = dehomogenize x g" .. from this(1) have "g \<in> ideal G" by (rule ideal.span_base) also have "\<dots> = ideal (homogenize x ` F)" by fact finally have "q \<in> dehomogenize x ` ideal (homogenize x ` F)" using q by (rule rev_image_eqI) also have "\<dots> \<subseteq> ideal (dehomogenize x ` homogenize x ` F)" by (rule dehomogenize_ideal_subset) also have "dehomogenize x ` homogenize x ` F = F" by (auto simp: eq image_image simp del: dehomogenize_homogenize intro!: image_eqI) finally show "q \<in> ideal F" . qed next show "F \<subseteq> ideal (dehomogenize x ` G)" proof fix f assume "f \<in> F" hence "homogenize x f \<in> homogenize x ` F" by (rule imageI) also have "\<dots> \<subseteq> ideal (homogenize x ` F)" by (rule ideal.span_superset) also from assms(1) have "\<dots> = ideal G" by (rule sym) finally have "dehomogenize x (homogenize x f) \<in> dehomogenize x ` ideal G" by (rule imageI) with \<open>f \<in> F\<close> have "f \<in> dehomogenize x ` ideal G" by (simp only: eq) also have "\<dots> \<subseteq> ideal (dehomogenize x ` G)" by (rule dehomogenize_ideal_subset) finally show "f \<in> ideal (dehomogenize x ` G)" . qed qed qed subsection \<open>Embedding Polynomial Rings in Larger Polynomial Rings (With One Additional Indeterminate)\<close> text \<open>We define a homomorphism for embedding a polynomial ring in a larger polynomial ring, and its inverse. This is mainly needed for homogenizing wrt. a fresh indeterminate.\<close> definition extend_indets_subst :: "'x \<Rightarrow> ('x option \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 'a::comm_semiring_1" where "extend_indets_subst x = monomial 1 (Poly_Mapping.single (Some x) 1)" definition extend_indets :: "(('x \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 'a) \<Rightarrow> ('x option \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 'a::comm_semiring_1" where "extend_indets = poly_subst extend_indets_subst" definition restrict_indets_subst :: "'x option \<Rightarrow> 'x \<Rightarrow>\<^sub>0 nat" where "restrict_indets_subst x = (case x of Some y \<Rightarrow> Poly_Mapping.single y 1 | _ \<Rightarrow> 0)" definition restrict_indets :: "(('x option \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 'a) \<Rightarrow> ('x \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 'a::comm_semiring_1" where "restrict_indets = poly_subst (\<lambda>x. monomial 1 (restrict_indets_subst x))" definition restrict_indets_pp :: "('x option \<Rightarrow>\<^sub>0 nat) \<Rightarrow> ('x \<Rightarrow>\<^sub>0 nat)" where "restrict_indets_pp t = (\<Sum>x\<in>keys t. lookup t x \<cdot> restrict_indets_subst x)" lemma lookup_extend_indets_subst_aux: "lookup (\<Sum>y\<in>keys t. Poly_Mapping.single (Some y) (lookup t y)) = (\<lambda>x. case x of Some y \<Rightarrow> lookup t y | _ \<Rightarrow> 0)" proof - have "(\<Sum>x\<in>keys t. lookup t x when x = y) = lookup t y" for y proof (cases "y \<in> keys t") case True hence "(\<Sum>x\<in>keys t. lookup t x when x = y) = (\<Sum>x\<in>insert y (keys t). lookup t x when x = y)" by (simp only: insert_absorb) also have "\<dots> = lookup t y + (\<Sum>x\<in>keys t - {y}. lookup t x when x = y)" by (simp add: sum.insert_remove) also have "(\<Sum>x\<in>keys t - {y}. lookup t x when x = y) = 0" by (auto simp: when_def intro: sum.neutral) finally show ?thesis by simp next case False hence "(\<Sum>x\<in>keys t. lookup t x when x = y) = 0" by (auto simp: when_def intro: sum.neutral) with False show ?thesis by (simp add: in_keys_iff) qed thus ?thesis by (auto simp: lookup_sum lookup_single split: option.split) qed lemma keys_extend_indets_subst_aux: "keys (\<Sum>y\<in>keys t. Poly_Mapping.single (Some y) (lookup t y)) = Some ` keys t" by (auto simp: lookup_extend_indets_subst_aux simp flip: lookup_not_eq_zero_eq_in_keys split: option.splits) lemma subst_pp_extend_indets_subst: "subst_pp extend_indets_subst t = monomial 1 (\<Sum>y\<in>keys t. Poly_Mapping.single (Some y) (lookup t y))" proof - have "subst_pp extend_indets_subst t = monomial (\<Prod>y\<in>keys t. 1 ^ lookup t y) (\<Sum>y\<in>keys t. lookup t y \<cdot> Poly_Mapping.single (Some y) 1)" by (rule subst_pp_by_monomials) (simp only: extend_indets_subst_def) also have "\<dots> = monomial 1 (\<Sum>y\<in>keys t. Poly_Mapping.single (Some y) (lookup t y))" by simp finally show ?thesis . qed lemma keys_extend_indets: "keys (extend_indets p) = (\<lambda>t. \<Sum>y\<in>keys t. Poly_Mapping.single (Some y) (lookup t y)) ` keys p" proof - have "keys (extend_indets p) = (\<Union>t\<in>keys p. keys (punit.monom_mult (lookup p t) 0 (subst_pp extend_indets_subst t)))" unfolding extend_indets_def poly_subst_def using finite_keys proof (rule keys_sum) fix s t :: "'a \<Rightarrow>\<^sub>0 nat" assume "s \<noteq> t" then obtain x where "lookup s x \<noteq> lookup t x" by (meson poly_mapping_eqI) have "(\<Sum>y\<in>keys t. monomial (lookup t y) (Some y)) \<noteq> (\<Sum>y\<in>keys s. monomial (lookup s y) (Some y))" (is "?l \<noteq> ?r") proof assume "?l = ?r" hence "lookup ?l (Some x) = lookup ?r (Some x)" by (simp only:) hence "lookup s x = lookup t x" by (simp add: lookup_extend_indets_subst_aux) with \<open>lookup s x \<noteq> lookup t x\<close> show False .. qed thus "keys (punit.monom_mult (lookup p s) 0 (subst_pp extend_indets_subst s)) \<inter> keys (punit.monom_mult (lookup p t) 0 (subst_pp extend_indets_subst t)) = {}" by (simp add: subst_pp_extend_indets_subst punit.monom_mult_monomial) qed also have "\<dots> = (\<lambda>t. \<Sum>y\<in>keys t. monomial (lookup t y) (Some y)) ` keys p" by (auto simp: subst_pp_extend_indets_subst punit.monom_mult_monomial split: if_split_asm) finally show ?thesis . qed lemma indets_extend_indets: "indets (extend_indets p) = Some ` indets (p::_ \<Rightarrow>\<^sub>0 'a::comm_semiring_1)" proof (rule set_eqI) fix x show "x \<in> indets (extend_indets p) \<longleftrightarrow> x \<in> Some ` indets p" proof assume "x \<in> indets (extend_indets p)" then obtain y where "y \<in> indets p" and "x \<in> indets (monomial (1::'a) (Poly_Mapping.single (Some y) 1))" unfolding extend_indets_def extend_indets_subst_def by (rule in_indets_poly_substE) from this(2) indets_monomial_single_subset have "x \<in> {Some y}" .. hence "x = Some y" by simp with \<open>y \<in> indets p\<close> show "x \<in> Some ` indets p" by (rule rev_image_eqI) next assume "x \<in> Some ` indets p" then obtain y where "y \<in> indets p" and x: "x = Some y" .. from this(1) obtain t where "t \<in> keys p" and "y \<in> keys t" by (rule in_indetsE) from this(2) have "Some y \<in> keys (\<Sum>y\<in>keys t. Poly_Mapping.single (Some y) (lookup t y))" unfolding keys_extend_indets_subst_aux by (rule imageI) moreover have "(\<Sum>y\<in>keys t. Poly_Mapping.single (Some y) (lookup t y)) \<in> keys (extend_indets p)" unfolding keys_extend_indets using \<open>t \<in> keys p\<close> by (rule imageI) ultimately show "x \<in> indets (extend_indets p)" unfolding x by (rule in_indetsI) qed qed lemma poly_deg_extend_indets [simp]: "poly_deg (extend_indets p) = poly_deg p" proof - have eq: "deg_pm ((\<Sum>y\<in>keys t. Poly_Mapping.single (Some y) (lookup t y))) = deg_pm t" for t::"'a \<Rightarrow>\<^sub>0 nat" proof - have "deg_pm ((\<Sum>y\<in>keys t. Poly_Mapping.single (Some y) (lookup t y))) = (\<Sum>y\<in>keys t. lookup t y)" by (simp add: deg_pm_sum deg_pm_single) also from subset_refl finite_keys have "\<dots> = deg_pm t" by (rule deg_pm_superset[symmetric]) finally show ?thesis . qed show ?thesis proof (rule antisym) show "poly_deg (extend_indets p) \<le> poly_deg p" proof (rule poly_deg_leI) fix t assume "t \<in> keys (extend_indets p)" then obtain s where "s \<in> keys p" and "t = (\<Sum>y\<in>keys s. Poly_Mapping.single (Some y) (lookup s y))" unfolding keys_extend_indets .. from this(2) have "deg_pm t = deg_pm s" by (simp only: eq) also from \<open>s \<in> keys p\<close> have "\<dots> \<le> poly_deg p" by (rule poly_deg_max_keys) finally show "deg_pm t \<le> poly_deg p" . qed next show "poly_deg p \<le> poly_deg (extend_indets p)" proof (rule poly_deg_leI) fix t assume "t \<in> keys p" hence *: "(\<Sum>y\<in>keys t. Poly_Mapping.single (Some y) (lookup t y)) \<in> keys (extend_indets p)" unfolding keys_extend_indets by (rule imageI) have "deg_pm t = deg_pm (\<Sum>y\<in>keys t. Poly_Mapping.single (Some y) (lookup t y))" by (simp only: eq) also from * have "\<dots> \<le> poly_deg (extend_indets p)" by (rule poly_deg_max_keys) finally show "deg_pm t \<le> poly_deg (extend_indets p)" . qed qed qed lemma shows extend_indets_zero [simp]: "extend_indets 0 = 0" and extend_indets_one [simp]: "extend_indets 1 = 1" and extend_indets_monomial: "extend_indets (monomial c t) = punit.monom_mult c 0 (subst_pp extend_indets_subst t)" and extend_indets_plus: "extend_indets (p + q) = extend_indets p + extend_indets q" and extend_indets_uminus: "extend_indets (- r) = - extend_indets (r::_ \<Rightarrow>\<^sub>0 _::comm_ring_1)" and extend_indets_minus: "extend_indets (r - r') = extend_indets r - extend_indets r'" and extend_indets_times: "extend_indets (p * q) = extend_indets p * extend_indets q" and extend_indets_power: "extend_indets (p ^ n) = extend_indets p ^ n" and extend_indets_sum: "extend_indets (sum f A) = (\<Sum>a\<in>A. extend_indets (f a))" and extend_indets_prod: "extend_indets (prod f A) = (\<Prod>a\<in>A. extend_indets (f a))" by (simp_all add: extend_indets_def poly_subst_monomial poly_subst_plus poly_subst_uminus poly_subst_minus poly_subst_times poly_subst_power poly_subst_sum poly_subst_prod) lemma extend_indets_zero_iff [simp]: "extend_indets p = 0 \<longleftrightarrow> p = 0" by (metis (no_types, lifting) imageE imageI keys_extend_indets lookup_zero not_in_keys_iff_lookup_eq_zero poly_deg_extend_indets poly_deg_zero poly_deg_zero_imp_monomial) lemma extend_indets_inject: assumes "extend_indets p = extend_indets (q::_ \<Rightarrow>\<^sub>0 _::comm_ring_1)" shows "p = q" proof - from assms have "extend_indets (p - q) = 0" by (simp add: extend_indets_minus) thus ?thesis by simp qed corollary inj_extend_indets: "inj (extend_indets::_ \<Rightarrow> _ \<Rightarrow>\<^sub>0 _::comm_ring_1)" using extend_indets_inject by (intro injI) lemma poly_eval_extend_indets: "poly_eval a (extend_indets p) = poly_eval (a \<circ> Some) p" proof - have eq: "poly_eval a (extend_indets (monomial c t)) = poly_eval (\<lambda>x. a (Some x)) (monomial c t)" for c t by (simp add: extend_indets_monomial poly_eval_times poly_eval_monomial poly_eval_prod poly_eval_power subst_pp_def extend_indets_subst_def flip: times_monomial_left) show ?thesis by (induct p rule: poly_mapping_plus_induct) (simp_all add: extend_indets_plus poly_eval_plus eq) qed lemma lookup_restrict_indets_pp: "lookup (restrict_indets_pp t) = (\<lambda>x. lookup t (Some x))" proof - let ?f = "\<lambda>z x. lookup t x * lookup (case x of None \<Rightarrow> 0 | Some y \<Rightarrow> Poly_Mapping.single y 1) z" have "sum (?f z) (keys t) = lookup t (Some z)" for z proof (cases "Some z \<in> keys t") case True hence "sum (?f z) (keys t) = sum (?f z) (insert (Some z) (keys t))" by (simp only: insert_absorb) also have "\<dots> = lookup t (Some z) + sum (?f z) (keys t - {Some z})" by (simp add: sum.insert_remove) also have "sum (?f z) (keys t - {Some z}) = 0" by (auto simp: when_def lookup_single intro: sum.neutral split: option.splits) finally show ?thesis by simp next case False hence "sum (?f z) (keys t) = 0" by (auto simp: when_def lookup_single intro: sum.neutral split: option.splits) with False show ?thesis by (simp add: in_keys_iff) qed thus ?thesis by (auto simp: restrict_indets_pp_def restrict_indets_subst_def lookup_sum) qed lemma restrict_indets_pp_zero [simp]: "restrict_indets_pp 0 = 0" by (simp add: restrict_indets_pp_def) lemma restrict_indets_pp_plus: "restrict_indets_pp (s + t) = restrict_indets_pp s + restrict_indets_pp t" by (rule poly_mapping_eqI) (simp add: lookup_add lookup_restrict_indets_pp) lemma deg_pm_restrict_indets_pp: "deg_pm (restrict_indets_pp t) + lookup t None = deg_pm t" proof - have "deg_pm t = sum (lookup t) (insert None (keys t))" by (rule deg_pm_superset) auto also from finite_keys have "\<dots> = lookup t None + sum (lookup t) (keys t - {None})" by (rule sum.insert_remove) also have "sum (lookup t) (keys t - {None}) = (\<Sum>x\<in>keys t. lookup t x * deg_pm (restrict_indets_subst x))" by (intro sum.mono_neutral_cong_left) (auto simp: restrict_indets_subst_def deg_pm_single) also have "\<dots> = deg_pm (restrict_indets_pp t)" by (simp only: restrict_indets_pp_def deg_pm_sum deg_pm_map_scale) finally show ?thesis by simp qed lemma keys_restrict_indets_subset: "keys (restrict_indets p) \<subseteq> restrict_indets_pp ` keys p" proof fix t assume "t \<in> keys (restrict_indets p)" also have "\<dots> = keys (\<Sum>t\<in>keys p. monomial (lookup p t) (restrict_indets_pp t))" by (simp add: restrict_indets_def poly_subst_def subst_pp_restrict_indets_subst punit.monom_mult_monomial) also have "\<dots> \<subseteq> (\<Union>t\<in>keys p. keys (monomial (lookup p t) (restrict_indets_pp t)))" by (rule keys_sum_subset) also have "\<dots> = restrict_indets_pp ` keys p" by (auto split: if_split_asm) finally show "t \<in> restrict_indets_pp ` keys p" . qed lemma keys_restrict_indets: assumes "None \<notin> indets p" shows "keys (restrict_indets p) = restrict_indets_pp ` keys p" proof - have "keys (restrict_indets p) = keys (\<Sum>t\<in>keys p. monomial (lookup p t) (restrict_indets_pp t))" by (simp add: restrict_indets_def poly_subst_def subst_pp_restrict_indets_subst punit.monom_mult_monomial) also from finite_keys have "\<dots> = (\<Union>t\<in>keys p. keys (monomial (lookup p t) (restrict_indets_pp t)))" proof (rule keys_sum) fix s t assume "s \<in> keys p" hence "keys s \<subseteq> indets p" by (rule keys_subset_indets) with assms have "None \<notin> keys s" by blast assume "t \<in> keys p" hence "keys t \<subseteq> indets p" by (rule keys_subset_indets) with assms have "None \<notin> keys t" by blast assume "s \<noteq> t" then obtain x where neq: "lookup s x \<noteq> lookup t x" by (meson poly_mapping_eqI) have "x \<noteq> None" proof assume "x = None" with \<open>None \<notin> keys s\<close> and \<open>None \<notin> keys t\<close> have "x \<notin> keys s" and "x \<notin> keys t" by blast+ with neq show False by (simp add: in_keys_iff) qed then obtain y where x: "x = Some y" by blast have "restrict_indets_pp t \<noteq> restrict_indets_pp s" proof assume "restrict_indets_pp t = restrict_indets_pp s" hence "lookup (restrict_indets_pp t) y = lookup (restrict_indets_pp s) y" by (simp only:) hence "lookup s x = lookup t x" by (simp add: x lookup_restrict_indets_pp) with neq show False .. qed thus "keys (monomial (lookup p s) (restrict_indets_pp s)) \<inter> keys (monomial (lookup p t) (restrict_indets_pp t)) = {}" by (simp add: subst_pp_extend_indets_subst) qed also have "\<dots> = restrict_indets_pp ` keys p" by (auto split: if_split_asm) finally show ?thesis . qed lemma indets_restrict_indets_subset: "indets (restrict_indets p) \<subseteq> the ` (indets p - {None})" proof fix x assume "x \<in> indets (restrict_indets p)" then obtain t where "t \<in> keys (restrict_indets p)" and "x \<in> keys t" by (rule in_indetsE) from this(1) keys_restrict_indets_subset have "t \<in> restrict_indets_pp ` keys p" .. then obtain s where "s \<in> keys p" and "t = restrict_indets_pp s" .. from \<open>x \<in> keys t\<close> this(2) have "x \<in> the ` (keys s - {None})" by (simp only: keys_restrict_indets_pp) also from \<open>s \<in> keys p\<close> have "\<dots> \<subseteq> the ` (indets p - {None})" by (intro image_mono Diff_mono keys_subset_indets subset_refl) finally show "x \<in> the ` (indets p - {None})" . qed lemma poly_deg_restrict_indets_le: "poly_deg (restrict_indets p) \<le> poly_deg p" proof (rule poly_deg_leI) fix t assume "t \<in> keys (restrict_indets p)" hence "t \<in> restrict_indets_pp ` keys p" using keys_restrict_indets_subset .. then obtain s where "s \<in> keys p" and "t = restrict_indets_pp s" .. from this(2) have "deg_pm t + lookup s None = deg_pm s" by (simp only: deg_pm_restrict_indets_pp) also from \<open>s \<in> keys p\<close> have "\<dots> \<le> poly_deg p" by (rule poly_deg_max_keys) finally show "deg_pm t \<le> poly_deg p" by simp qed lemma shows restrict_indets_zero [simp]: "restrict_indets 0 = 0" and restrict_indets_one [simp]: "restrict_indets 1 = 1" and restrict_indets_monomial: "restrict_indets (monomial c t) = monomial c (restrict_indets_pp t)" and restrict_indets_plus: "restrict_indets (p + q) = restrict_indets p + restrict_indets q" and restrict_indets_uminus: "restrict_indets (- r) = - restrict_indets (r::_ \<Rightarrow>\<^sub>0 _::comm_ring_1)" and restrict_indets_minus: "restrict_indets (r - r') = restrict_indets r - restrict_indets r'" and restrict_indets_times: "restrict_indets (p * q) = restrict_indets p * restrict_indets q" and restrict_indets_power: "restrict_indets (p ^ n) = restrict_indets p ^ n" and restrict_indets_sum: "restrict_indets (sum f A) = (\<Sum>a\<in>A. restrict_indets (f a))" and restrict_indets_prod: "restrict_indets (prod f A) = (\<Prod>a\<in>A. restrict_indets (f a))" by (simp_all add: restrict_indets_def poly_subst_monomial poly_subst_plus poly_subst_uminus poly_subst_minus poly_subst_times poly_subst_power poly_subst_sum poly_subst_prod subst_pp_restrict_indets_subst punit.monom_mult_monomial) lemma restrict_extend_indets [simp]: "restrict_indets (extend_indets p) = p" unfolding extend_indets_def restrict_indets_def poly_subst_poly_subst by (rule poly_subst_id) (simp add: extend_indets_subst_def restrict_indets_subst_def poly_subst_monomial subst_pp_single) lemma extend_restrict_indets: assumes "None \<notin> indets p" shows "extend_indets (restrict_indets p) = p" unfolding extend_indets_def restrict_indets_def poly_subst_poly_subst proof (rule poly_subst_id) fix x assume "x \<in> indets p" with assms have "x \<noteq> None" by meson then obtain y where x: "x = Some y" by blast thus "poly_subst extend_indets_subst (monomial 1 (restrict_indets_subst x)) = monomial 1 (Poly_Mapping.single x 1)" by (simp add: extend_indets_subst_def restrict_indets_subst_def poly_subst_monomial subst_pp_single) qed lemma restrict_indets_dehomogenize [simp]: "restrict_indets (dehomogenize None p) = restrict_indets p" proof - have eq: "poly_subst (\<lambda>x. (monomial 1 (restrict_indets_subst x))) (dehomo_subst None y) = monomial 1 (restrict_indets_subst y)" for y::"'x option" by (auto simp: restrict_indets_subst_def dehomo_subst_def poly_subst_monomial subst_pp_single) show ?thesis by (simp only: dehomogenize_def restrict_indets_def poly_subst_poly_subst eq) qed corollary restrict_indets_comp_dehomogenize: "restrict_indets \<circ> dehomogenize None = restrict_indets" by (rule ext) (simp only: o_def restrict_indets_dehomogenize) corollary extend_restrict_indets_eq_dehomogenize: "extend_indets (restrict_indets p) = dehomogenize None p" proof - have "extend_indets (restrict_indets p) = extend_indets (restrict_indets (dehomogenize None p))" by simp also have "\<dots> = dehomogenize None p" proof (intro extend_restrict_indets notI) assume "None \<in> indets (dehomogenize None p)" hence "None \<in> indets p - {None}" using indets_dehomogenize .. thus False by simp qed finally show ?thesis . qed corollary extend_indets_comp_restrict_indets: "extend_indets \<circ> restrict_indets = dehomogenize None" by (rule ext) (simp only: o_def extend_restrict_indets_eq_dehomogenize) lemma restrict_homogenize_extend_indets [simp]: "restrict_indets (homogenize None (extend_indets p)) = p" proof - have "restrict_indets (homogenize None (extend_indets p)) = restrict_indets (dehomogenize None (homogenize None (extend_indets p)))" by (simp only: restrict_indets_dehomogenize) also have "\<dots> = restrict_indets (dehomogenize None (extend_indets p))" by (simp only: dehomogenize_homogenize) also have "\<dots> = p" by simp finally show ?thesis . qed lemma dehomogenize_extend_indets [simp]: "dehomogenize None (extend_indets p) = extend_indets p" by (simp add: indets_extend_indets) lemma restrict_indets_ideal: "restrict_indets ` ideal F = ideal (restrict_indets ` F)" using restrict_indets_plus restrict_indets_times proof (rule image_ideal_eq_surj) from restrict_extend_indets show "surj restrict_indets" by (rule surjI) qed lemma ideal_restrict_indets: "ideal G = ideal (homogenize None ` extend_indets ` F) \<Longrightarrow> ideal (restrict_indets ` G) = ideal F" by (simp flip: restrict_indets_ideal) (simp add: restrict_indets_ideal image_image) lemma extend_indets_ideal: "extend_indets ` ideal F = ideal (extend_indets ` F) \<inter> P[- {None}]" proof - have "extend_indets ` ideal F = extend_indets ` restrict_indets ` ideal (extend_indets ` F)" by (simp add: restrict_indets_ideal image_image) also have "\<dots> = ideal (extend_indets ` F) \<inter> P[- {None}]" by (simp add: extend_restrict_indets_eq_dehomogenize dehomogenize_ideal image_image) finally show ?thesis . qed corollary extend_indets_ideal_subset: "extend_indets ` ideal F \<subseteq> ideal (extend_indets ` F)" by (simp add: extend_indets_ideal) subsection \<open>Canonical Isomorphisms between \<open>P[X,Y]\<close> and \<open>P[X][Y]\<close>: \<open>focus\<close> and \<open>flatten\<close>\<close> definition focus :: "'x set \<Rightarrow> (('x \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 'a) \<Rightarrow> (('x \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 ('x \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 'a::comm_monoid_add)" where "focus X p = (\<Sum>t\<in>keys p. monomial (monomial (lookup p t) (except t X)) (except t (- X)))" definition flatten :: "('a \<Rightarrow>\<^sub>0 'a \<Rightarrow>\<^sub>0 'b) \<Rightarrow> ('a::comm_powerprod \<Rightarrow>\<^sub>0 'b::semiring_1)" where "flatten p = (\<Sum>t\<in>keys p. punit.monom_mult 1 t (lookup p t))" lemma focus_superset: assumes "finite A" and "keys p \<subseteq> A" shows "focus X p = (\<Sum>t\<in>A. monomial (monomial (lookup p t) (except t X)) (except t (- X)))" unfolding focus_def using assms by (rule sum.mono_neutral_left) (simp add: in_keys_iff) lemma keys_focus: "keys (focus X p) = (\<lambda>t. except t (- X)) ` keys p" proof have "keys (focus X p) \<subseteq> (\<Union>t\<in>keys p. keys (monomial (monomial (lookup p t) (except t X)) (except t (- X))))" unfolding focus_def by (rule keys_sum_subset) also have "\<dots> \<subseteq> (\<Union>t\<in>keys p. {except t (- X)})" by (intro UN_mono subset_refl) simp also have "\<dots> = (\<lambda>t. except t (- X)) ` keys p" by (rule UNION_singleton_eq_range) finally show "keys (focus X p) \<subseteq> (\<lambda>t. except t (- X)) ` keys p" . next { fix s assume "s \<in> keys p" have "lookup (focus X p) (except s (- X)) = (\<Sum>t\<in>keys p. monomial (lookup p t) (except t X) when except t (- X) = except s (- X))" (is "_ = ?p") by (simp only: focus_def lookup_sum lookup_single) also have "\<dots> \<noteq> 0" proof have "lookup ?p (except s X) = (\<Sum>t\<in>keys p. lookup p t when except t X = except s X \<and> except t (- X) = except s (- X))" by (simp add: lookup_sum lookup_single when_def if_distrib if_distribR) (metis (no_types, hide_lams) lookup_single_eq lookup_single_not_eq lookup_zero) also have "\<dots> = (\<Sum>t\<in>{s}. lookup p t)" proof (intro sum.mono_neutral_cong_right ballI) fix t assume "t \<in> keys p - {s}" hence "t \<noteq> s" by simp hence "except t X + except t (- X) \<noteq> except s X + except s (- X)" by (simp flip: except_decomp) thus "(lookup p t when except t X = except s X \<and> except t (- X) = except s (- X)) = 0" by (auto simp: when_def) next from \<open>s \<in> keys p\<close> show "{s} \<subseteq> keys p" by simp qed simp_all also from \<open>s \<in> keys p\<close> have "\<dots> \<noteq> 0" by (simp add: in_keys_iff) finally have "except s X \<in> keys ?p" by (simp add: in_keys_iff) moreover assume "?p = 0" ultimately show False by simp qed finally have "except s (- X) \<in> keys (focus X p)" by (simp add: in_keys_iff) } thus "(\<lambda>t. except t (- X)) ` keys p \<subseteq> keys (focus X p)" by blast qed lemma keys_coeffs_focus_subset: assumes "c \<in> range (lookup (focus X p))" shows "keys c \<subseteq> (\<lambda>t. except t X) ` keys p" proof - from assms obtain s where "c = lookup (focus X p) s" .. hence "keys c = keys (lookup (focus X p) s)" by (simp only:) also have "\<dots> \<subseteq> (\<Union>t\<in>keys p. keys (lookup (monomial (monomial (lookup p t) (except t X)) (except t (- X))) s))" unfolding focus_def lookup_sum by (rule keys_sum_subset) also from subset_refl have "\<dots> \<subseteq> (\<Union>t\<in>keys p. {except t X})" by (rule UN_mono) (simp add: lookup_single when_def) also have "\<dots> = (\<lambda>t. except t X) ` keys p" by (rule UNION_singleton_eq_range) finally show ?thesis . qed lemma focus_in_Polys': assumes "p \<in> P[Y]" shows "focus X p \<in> P[Y \<inter> X]" proof (intro PolysI subsetI) fix t assume "t \<in> keys (focus X p)" then obtain s where "s \<in> keys p" and t: "t = except s (- X)" unfolding keys_focus .. note this(1) also from assms have "keys p \<subseteq> .[Y]" by (rule PolysD) finally have "keys s \<subseteq> Y" by (rule PPsD) hence "keys t \<subseteq> Y \<inter> X" by (simp add: t keys_except le_infI1) thus "t \<in> .[Y \<inter> X]" by (rule PPsI) qed corollary focus_in_Polys: "focus X p \<in> P[X]" proof - have "p \<in> P[UNIV]" by simp hence "focus X p \<in> P[UNIV \<inter> X]" by (rule focus_in_Polys') thus ?thesis by simp qed lemma focus_coeffs_subset_Polys': assumes "p \<in> P[Y]" shows "range (lookup (focus X p)) \<subseteq> P[Y - X]" proof (intro subsetI PolysI) fix c t assume "c \<in> range (lookup (focus X p))" hence "keys c \<subseteq> (\<lambda>t. except t X) ` keys p" by (rule keys_coeffs_focus_subset) moreover assume "t \<in> keys c" ultimately have "t \<in> (\<lambda>t. except t X) ` keys p" .. then obtain s where "s \<in> keys p" and t: "t = except s X" .. note this(1) also from assms have "keys p \<subseteq> .[Y]" by (rule PolysD) finally have "keys s \<subseteq> Y" by (rule PPsD) hence "keys t \<subseteq> Y - X" by (simp add: t keys_except Diff_mono) thus "t \<in> .[Y - X]" by (rule PPsI) qed corollary focus_coeffs_subset_Polys: "range (lookup (focus X p)) \<subseteq> P[- X]" proof - have "p \<in> P[UNIV]" by simp hence "range (lookup (focus X p)) \<subseteq> P[UNIV - X]" by (rule focus_coeffs_subset_Polys') thus ?thesis by (simp only: Compl_eq_Diff_UNIV) qed corollary lookup_focus_in_Polys: "lookup (focus X p) t \<in> P[- X]" using focus_coeffs_subset_Polys by blast lemma focus_zero [simp]: "focus X 0 = 0" by (simp add: focus_def) lemma focus_eq_zero_iff [iff]: "focus X p = 0 \<longleftrightarrow> p = 0" by (simp only: keys_focus flip: keys_eq_empty_iff) simp lemma focus_one [simp]: "focus X 1 = 1" by (simp add: focus_def) lemma focus_monomial: "focus X (monomial c t) = monomial (monomial c (except t X)) (except t (- X))" by (simp add: focus_def) lemma focus_uminus [simp]: "focus X (- p) = - focus X p" by (simp add: focus_def keys_uminus single_uminus sum_negf) lemma focus_plus: "focus X (p + q) = focus X p + focus X q" proof - have "finite (keys p \<union> keys q)" by simp moreover have "keys (p + q) \<subseteq> keys p \<union> keys q" by (rule Poly_Mapping.keys_add) ultimately show ?thesis by (simp add: focus_superset[where A="keys p \<union> keys q"] lookup_add single_add sum.distrib) qed lemma focus_minus: "focus X (p - q) = focus X p - focus X (q::_ \<Rightarrow>\<^sub>0 _::ab_group_add)" by (simp only: diff_conv_add_uminus focus_plus focus_uminus) lemma focus_times: "focus X (p * q) = focus X p * focus X q" proof - have eq: "focus X (monomial c s * q) = focus X (monomial c s) * focus X q" for c s proof - have "focus X (monomial c s * q) = focus X (punit.monom_mult c s q)" by (simp only: times_monomial_left) also have "\<dots> = (\<Sum>t\<in>(+) s ` keys q. monomial (monomial (lookup (punit.monom_mult c s q) t) (except t X)) (except t (- X)))" by (rule focus_superset) (simp_all add: punit.keys_monom_mult_subset[simplified]) also have "\<dots> = (\<Sum>t\<in>keys q. ((\<lambda>t. monomial (monomial (lookup (punit.monom_mult c s q) t) (except t X)) (except t (- X))) \<circ> ((+) s)) t)" by (rule sum.reindex) simp also have "\<dots> = monomial (monomial c (except s X)) (except s (- X)) * (\<Sum>t\<in>keys q. monomial (monomial (lookup q t) (except t X)) (except t (- X)))" by (simp add: o_def punit.lookup_monom_mult except_plus times_monomial_monomial sum_distrib_left) also have "\<dots> = focus X (monomial c s) * focus X q" by (simp only: focus_monomial focus_def[where p=q]) finally show ?thesis . qed show ?thesis by (induct p rule: poly_mapping_plus_induct) (simp_all add: ring_distribs focus_plus eq) qed lemma focus_sum: "focus X (sum f I) = (\<Sum>i\<in>I. focus X (f i))" by (induct I rule: infinite_finite_induct) (simp_all add: focus_plus) lemma focus_prod: "focus X (prod f I) = (\<Prod>i\<in>I. focus X (f i))" by (induct I rule: infinite_finite_induct) (simp_all add: focus_times) lemma focus_power [simp]: "focus X (f ^ m) = focus X f ^ m" by (induct m) (simp_all add: focus_times) lemma focus_Polys: assumes "p \<in> P[X]" shows "focus X p = (\<Sum>t\<in>keys p. monomial (monomial (lookup p t) 0) t)" unfolding focus_def proof (rule sum.cong) fix t assume "t \<in> keys p" also from assms have "\<dots> \<subseteq> .[X]" by (rule PolysD) finally have "keys t \<subseteq> X" by (rule PPsD) hence "except t X = 0" and "except t (- X) = t" by (rule except_eq_zeroI, auto simp: except_id_iff) thus "monomial (monomial (lookup p t) (except t X)) (except t (- X)) = monomial (monomial (lookup p t) 0) t" by simp qed (fact refl) corollary lookup_focus_Polys: "p \<in> P[X] \<Longrightarrow> lookup (focus X p) t = monomial (lookup p t) 0" by (simp add: focus_Polys lookup_sum lookup_single when_def in_keys_iff) lemma focus_Polys_Compl: assumes "p \<in> P[- X]" shows "focus X p = monomial p 0" proof - have "focus X p = (\<Sum>t\<in>keys p. monomial (monomial (lookup p t) t) 0)" unfolding focus_def proof (rule sum.cong) fix t assume "t \<in> keys p" also from assms have "\<dots> \<subseteq> .[- X]" by (rule PolysD) finally have "keys t \<subseteq> - X" by (rule PPsD) hence "except t (- X) = 0" and "except t X = t" by (rule except_eq_zeroI, auto simp: except_id_iff) thus "monomial (monomial (lookup p t) (except t X)) (except t (- X)) = monomial (monomial (lookup p t) t) 0" by simp qed (fact refl) also have "\<dots> = monomial (\<Sum>t\<in>keys p. monomial (lookup p t) t) 0" by (simp only: monomial_sum) also have "\<dots> = monomial p 0" by (simp only: poly_mapping_sum_monomials) finally show ?thesis . qed corollary focus_empty [simp]: "focus {} p = monomial p 0" by (rule focus_Polys_Compl) simp lemma focus_Int: assumes "p \<in> P[Y]" shows "focus (X \<inter> Y) p = focus X p" unfolding focus_def using refl proof (rule sum.cong) fix t assume "t \<in> keys p" also from assms have "\<dots> \<subseteq> .[Y]" by (rule PolysD) finally have "keys t \<subseteq> Y" by (rule PPsD) hence "keys t \<subseteq> X \<union> Y" by blast hence "except t (X \<inter> Y) = except t X + except t Y" by (rule except_Int) also from \<open>keys t \<subseteq> Y\<close> have "except t Y = 0" by (rule except_eq_zeroI) finally have eq: "except t (X \<inter> Y) = except t X" by simp have "except t (- (X \<inter> Y)) = except (except t (- Y)) (- X)" by (simp add: except_except Un_commute) also from \<open>keys t \<subseteq> Y\<close> have "except t (- Y) = t" by (auto simp: except_id_iff) finally show "monomial (monomial (lookup p t) (except t (X \<inter> Y))) (except t (- (X \<inter> Y))) = monomial (monomial (lookup p t) (except t X)) (except t (- X))" by (simp only: eq) qed lemma range_focusD: assumes "p \<in> range (focus X)" shows "p \<in> P[X]" and "range (lookup p) \<subseteq> P[- X]" and "lookup p t \<in> P[- X]" using assms by (auto intro: focus_in_Polys lookup_focus_in_Polys) lemma range_focusI: assumes "p \<in> P[X]" and "lookup p ` keys (p::_ \<Rightarrow>\<^sub>0 _ \<Rightarrow>\<^sub>0 _::semiring_1) \<subseteq> P[- X]" shows "p \<in> range (focus X)" using assms proof (induct p rule: poly_mapping_plus_induct_Polys) case 0 show ?case by simp next case (plus p c t) from plus.hyps(3) have 1: "keys (monomial c t) = {t}" by simp also from plus.hyps(4) have "\<dots> \<inter> keys p = {}" by simp finally have "keys (monomial c t + p) = keys (monomial c t) \<union> keys p" by (rule keys_add[symmetric]) hence 2: "keys (monomial c t + p) = insert t (keys p)" by (simp only: 1 flip: insert_is_Un) from \<open>t \<in> .[X]\<close> have "keys t \<subseteq> X" by (rule PPsD) hence eq1: "except t X = 0" and eq2: "except t (- X) = t" by (rule except_eq_zeroI, auto simp: except_id_iff) from plus.hyps(3, 4) plus.prems have "c \<in> P[- X]" and "lookup p ` keys p \<subseteq> P[- X]" by (simp_all add: 2 lookup_add lookup_single in_keys_iff) (smt add.commute add.right_neutral image_cong plus.hyps(4) when_simps(2)) from this(2) have "p \<in> range (focus X)" by (rule plus.hyps) then obtain q where p: "p = focus X q" .. moreover from \<open>c \<in> P[- X]\<close> have "monomial c t = focus X (monomial 1 t * c)" by (simp add: focus_times focus_monomial eq1 eq2 focus_Polys_Compl times_monomial_monomial) ultimately have "monomial c t + p = focus X (monomial 1 t * c + q)" by (simp only: focus_plus) thus ?case by (rule range_eqI) qed lemma inj_focus: "inj ((focus X) :: (('x \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 'a::ab_group_add) \<Rightarrow> _)" proof (rule injI) fix p q :: "('x \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 'a" assume "focus X p = focus X q" hence "focus X (p - q) = 0" by (simp add: focus_minus) thus "p = q" by simp qed lemma flatten_superset: assumes "finite A" and "keys p \<subseteq> A" shows "flatten p = (\<Sum>t\<in>A. punit.monom_mult 1 t (lookup p t))" unfolding flatten_def using assms by (rule sum.mono_neutral_left) (simp add: in_keys_iff) lemma keys_flatten_subset: "keys (flatten p) \<subseteq> (\<Union>t\<in>keys p. (+) t ` keys (lookup p t))" proof - have "keys (flatten p) \<subseteq> (\<Union>t\<in>keys p. keys (punit.monom_mult 1 t (lookup p t)))" unfolding flatten_def by (rule keys_sum_subset) also from subset_refl have "\<dots> \<subseteq> (\<Union>t\<in>keys p. (+) t ` keys (lookup p t))" by (rule UN_mono) (rule punit.keys_monom_mult_subset[simplified]) finally show ?thesis . qed lemma flatten_in_Polys: assumes "p \<in> P[X]" and "lookup p ` keys p \<subseteq> P[Y]" shows "flatten p \<in> P[X \<union> Y]" proof (intro PolysI subsetI) fix t assume "t \<in> keys (flatten p)" also have "\<dots> \<subseteq> (\<Union>t\<in>keys p. (+) t ` keys (lookup p t))" by (rule keys_flatten_subset) finally obtain s where "s \<in> keys p" and "t \<in> (+) s ` keys (lookup p s)" .. from this(2) obtain s' where "s' \<in> keys (lookup p s)" and t: "t = s + s'" .. from assms(1) have "keys p \<subseteq> .[X]" by (rule PolysD) with \<open>s \<in> keys p\<close> have "s \<in> .[X]" .. also have "\<dots> \<subseteq> .[X \<union> Y]" by (rule PPs_mono) simp finally have 1: "s \<in> .[X \<union> Y]" . from \<open>s \<in> keys p\<close> have "lookup p s \<in> lookup p ` keys p" by (rule imageI) also have "\<dots> \<subseteq> P[Y]" by fact finally have "keys (lookup p s) \<subseteq> .[Y]" by (rule PolysD) with \<open>s' \<in> _\<close> have "s' \<in> .[Y]" .. also have "\<dots> \<subseteq> .[X \<union> Y]" by (rule PPs_mono) simp finally have "s' \<in> .[X \<union> Y]" . with 1 show "t \<in> .[X \<union> Y]" unfolding t by (rule PPs_closed_plus) qed lemma flatten_zero [simp]: "flatten 0 = 0" by (simp add: flatten_def) lemma flatten_one [simp]: "flatten 1 = 1" by (simp add: flatten_def) lemma flatten_monomial: "flatten (monomial c t) = punit.monom_mult 1 t c" by (simp add: flatten_def) lemma flatten_uminus [simp]: "flatten (- p) = - flatten (p::_ \<Rightarrow>\<^sub>0 _ \<Rightarrow>\<^sub>0 _::ring)" by (simp add: flatten_def keys_uminus punit.monom_mult_uminus_right sum_negf) lemma flatten_plus: "flatten (p + q) = flatten p + flatten q" proof - have "finite (keys p \<union> keys q)" by simp moreover have "keys (p + q) \<subseteq> keys p \<union> keys q" by (rule Poly_Mapping.keys_add) ultimately show ?thesis by (simp add: flatten_superset[where A="keys p \<union> keys q"] punit.monom_mult_dist_right lookup_add sum.distrib) qed lemma flatten_minus: "flatten (p - q) = flatten p - flatten (q::_ \<Rightarrow>\<^sub>0 _ \<Rightarrow>\<^sub>0 _::ring)" by (simp only: diff_conv_add_uminus flatten_plus flatten_uminus) lemma flatten_times: "flatten (p * q) = flatten p * flatten (q::_ \<Rightarrow>\<^sub>0 _ \<Rightarrow>\<^sub>0 'b::comm_semiring_1)" proof - have eq: "flatten (monomial c s * q) = flatten (monomial c s) * flatten q" for c s proof - have eq: "monomial 1 (t + s) = monomial 1 s * monomial (1::'b) t" for t by (simp add: times_monomial_monomial add.commute) have "flatten (monomial c s * q) = flatten (punit.monom_mult c s q)" by (simp only: times_monomial_left) also have "\<dots> = (\<Sum>t\<in>(+) s ` keys q. punit.monom_mult 1 t (lookup (punit.monom_mult c s q) t))" by (rule flatten_superset) (simp_all add: punit.keys_monom_mult_subset[simplified]) also have "\<dots> = (\<Sum>t\<in>keys q. ((\<lambda>t. punit.monom_mult 1 t (lookup (punit.monom_mult c s q) t)) \<circ> (+) s) t)" by (rule sum.reindex) simp thm times_monomial_left also have "\<dots> = punit.monom_mult 1 s c * (\<Sum>t\<in>keys q. punit.monom_mult 1 t (lookup q t))" by (simp add: o_def punit.lookup_monom_mult sum_distrib_left) (simp add: algebra_simps eq flip: times_monomial_left) also have "\<dots> = flatten (monomial c s) * flatten q" by (simp only: flatten_monomial flatten_def[where p=q]) finally show ?thesis . qed show ?thesis by (induct p rule: poly_mapping_plus_induct) (simp_all add: ring_distribs flatten_plus eq) qed lemma flatten_monom_mult: "flatten (punit.monom_mult c t p) = punit.monom_mult 1 t (c * flatten (p::_ \<Rightarrow>\<^sub>0 _ \<Rightarrow>\<^sub>0 'b::comm_semiring_1))" by (simp only: flatten_times flatten_monomial mult.assoc flip: times_monomial_left) lemma flatten_sum: "flatten (sum f I) = (\<Sum>i\<in>I. flatten (f i))" by (induct I rule: infinite_finite_induct) (simp_all add: flatten_plus) lemma flatten_prod: "flatten (prod f I) = (\<Prod>i\<in>I. flatten (f i :: _ \<Rightarrow>\<^sub>0 _::comm_semiring_1))" by (induct I rule: infinite_finite_induct) (simp_all add: flatten_times) lemma flatten_power [simp]: "flatten (f ^ m) = flatten (f:: _ \<Rightarrow>\<^sub>0 _::comm_semiring_1) ^ m" by (induct m) (simp_all add: flatten_times) lemma surj_flatten: "surj flatten" proof (rule surjI) fix p show "flatten (monomial p 0) = p" by (simp add: flatten_monomial) qed lemma flatten_focus [simp]: "flatten (focus X p) = p" by (induct p rule: poly_mapping_plus_induct) (simp_all add: focus_plus flatten_plus focus_monomial flatten_monomial punit.monom_mult_monomial add.commute flip: except_decomp) lemma focus_flatten: assumes "p \<in> P[X]" and "lookup p ` keys p \<subseteq> P[- X]" shows "focus X (flatten p) = p" proof - from assms have "p \<in> range (focus X)" by (rule range_focusI) then obtain q where "p = focus X q" .. thus ?thesis by simp qed lemma image_focus_ideal: "focus X ` ideal F = ideal (focus X ` F) \<inter> range (focus X)" proof from focus_plus focus_times have "focus X ` ideal F \<subseteq> ideal (focus X ` F)" by (rule image_ideal_subset) moreover from subset_UNIV have "focus X ` ideal F \<subseteq> range (focus X)" by (rule image_mono) ultimately show "focus X ` ideal F \<subseteq> ideal (focus X ` F) \<inter> range (focus X)" by blast next show "ideal (focus X ` F) \<inter> range (focus X) \<subseteq> focus X ` ideal F" proof fix p assume "p \<in> ideal (focus X ` F) \<inter> range (focus X)" hence "p \<in> ideal (focus X ` F)" and "p \<in> range (focus X)" by simp_all from this(1) obtain F0 q where "F0 \<subseteq> focus X ` F" and p: "p = (\<Sum>f'\<in>F0. q f' * f')" by (rule ideal.spanE) from this(1) obtain F' where "F' \<subseteq> F" and F0: "F0 = focus X ` F'" by (rule subset_imageE) from inj_focus subset_UNIV have "inj_on (focus X) F'" by (rule inj_on_subset) from \<open>p \<in> range _\<close> obtain p' where "p = focus X p'" .. hence "p = focus X (flatten p)" by simp also from \<open>inj_on _ F'\<close> have "\<dots> = focus X (\<Sum>f'\<in>F'. flatten (q (focus X f')) * f')" by (simp add: p F0 sum.reindex flatten_sum flatten_times) finally have "p = focus X (\<Sum>f'\<in>F'. flatten (q (focus X f')) * f')" . moreover have "(\<Sum>f'\<in>F'. flatten (q (focus X f')) * f') \<in> ideal F" proof show "(\<Sum>f'\<in>F'. flatten (q (focus X f')) * f') \<in> ideal F'" by (rule ideal.sum_in_spanI) next from \<open>F' \<subseteq> F\<close> show "ideal F' \<subseteq> ideal F" by (rule ideal.span_mono) qed ultimately show "p \<in> focus X ` ideal F" by (rule image_eqI) qed qed lemma image_flatten_ideal: "flatten ` ideal F = ideal (flatten ` F)" using flatten_plus flatten_times surj_flatten by (rule image_ideal_eq_surj) lemma poly_eval_focus: "poly_eval a (focus X p) = poly_subst (\<lambda>x. if x \<in> X then a x else monomial 1 (Poly_Mapping.single x 1)) p" proof - let ?b = "\<lambda>x. if x \<in> X then a x else monomial 1 (Poly_Mapping.single x 1)" have *: "lookup (punit.monom_mult (monomial (lookup p t) (except t X)) 0 (subst_pp (\<lambda>x. monomial (a x) 0) (except t (- X)))) 0 = punit.monom_mult (lookup p t) 0 (subst_pp ?b t)" for t proof - have 1: "subst_pp ?b (except t X) = monomial 1 (except t X)" by (rule subst_pp_id) (simp add: keys_except) from refl have 2: "subst_pp ?b (except t (- X)) = subst_pp a (except t (-X))" by (rule subst_pp_cong) (simp add: keys_except) have "lookup (punit.monom_mult (monomial (lookup p t) (except t X)) 0 (subst_pp (\<lambda>x. monomial (a x) 0) (except t (- X)))) 0 = punit.monom_mult (lookup p t) (except t X) (subst_pp a (except t (- X)))" by (simp add: lookup_times_zero subst_pp_def lookup_prod_zero lookup_power_zero flip: times_monomial_left) also have "\<dots> = punit.monom_mult (lookup p t) 0 (monomial 1 (except t X) * subst_pp a (except t (- X)))" by (simp add: times_monomial_monomial flip: times_monomial_left mult.assoc) also have "\<dots> = punit.monom_mult (lookup p t) 0 (subst_pp ?b (except t X + except t (- X)))" by (simp only: subst_pp_plus 1 2) also have "\<dots> = punit.monom_mult (lookup p t) 0 (subst_pp ?b t)" by (simp flip: except_decomp) finally show ?thesis . qed show ?thesis by (simp add: poly_eval_def focus_def poly_subst_sum lookup_sum poly_subst_monomial * flip: poly_subst_def) qed corollary poly_eval_poly_eval_focus: "poly_eval a (poly_eval b (focus X p)) = poly_eval (\<lambda>x::'x. if x \<in> X then poly_eval a (b x) else a x) p" proof - have eq: "monomial (lookup (poly_subst (\<lambda>y. monomial (a y) (0::'x \<Rightarrow>\<^sub>0 nat)) q) 0) 0 = poly_subst (\<lambda>y. monomial (a y) (0::'x \<Rightarrow>\<^sub>0 nat)) q" for q by (intro poly_deg_zero_imp_monomial poly_deg_poly_subst_eq_zeroI) simp show ?thesis unfolding poly_eval_focus by (simp add: poly_eval_def poly_subst_poly_subst if_distrib poly_subst_monomial subst_pp_single eq cong: if_cong) qed lemma indets_poly_eval_focus_subset: "indets (poly_eval a (focus X p)) \<subseteq> \<Union> (indets ` a ` X) \<union> (indets p - X)" proof fix x assume "x \<in> indets (poly_eval a (focus X p))" also have "\<dots> = indets (poly_subst (\<lambda>x. if x \<in> X then a x else monomial 1 (Poly_Mapping.single x 1)) p)" (is "_ = indets (poly_subst ?f _)") by (simp only: poly_eval_focus) finally obtain y where "y \<in> indets p" and "x \<in> indets (?f y)" by (rule in_indets_poly_substE) from this(2) have "(x \<notin> X \<and> x = y) \<or> (y \<in> X \<and> x \<in> indets (a y))" by (simp add: indets_monomial split: if_split_asm) thus "x \<in> \<Union> (indets ` a ` X) \<union> (indets p - X)" proof (elim disjE conjE) assume "x \<notin> X" and "x = y" with \<open>y \<in> indets p\<close> have "x \<in> indets p - X" by simp thus ?thesis .. next assume "y \<in> X" and "x \<in> indets (a y)" hence "x \<in> \<Union> (indets ` a ` X)" by blast thus ?thesis .. qed qed lemma lookup_poly_eval_focus: "lookup (poly_eval (\<lambda>x. monomial (a x) 0) (focus X p)) t = poly_eval a (lookup (focus (- X) p) t)" proof - let ?f = "\<lambda>x. if x \<in> X then monomial (a x) 0 else monomial 1 (Poly_Mapping.single x 1)" have eq: "subst_pp ?f s = monomial (\<Prod>x\<in>keys s \<inter> X. a x ^ lookup s x) (except s X)" for s proof - have "subst_pp ?f s = (\<Prod>x\<in>(keys s \<inter> X) \<union> (keys s - X). ?f x ^ lookup s x)" unfolding subst_pp_def by (rule prod.cong) blast+ also have "\<dots> = (\<Prod>x\<in>keys s \<inter> X. ?f x ^ lookup s x) * (\<Prod>x\<in>keys s - X. ?f x ^ lookup s x)" by (rule prod.union_disjoint) auto also have "\<dots> = monomial (\<Prod>x\<in>keys s \<inter> X. a x ^ lookup s x) (\<Sum>x\<in>keys s - X. Poly_Mapping.single x (lookup s x))" by (simp add: monomial_power_map_scale times_monomial_monomial flip: punit.monomial_prod_sum) also have "(\<Sum>x\<in>keys s - X. Poly_Mapping.single x (lookup s x)) = except s X" by (metis (mono_tags, lifting) DiffD2 keys_except lookup_except_eq_idI poly_mapping_sum_monomials sum.cong) finally show ?thesis . qed show ?thesis by (simp add: poly_eval_focus poly_subst_def lookup_sum eq flip: punit.map_scale_eq_monom_mult) (simp add: focus_def lookup_sum poly_eval_sum lookup_single when_distrib poly_eval_monomial keys_except lookup_except_when) qed lemma keys_poly_eval_focus_subset: "keys (poly_eval (\<lambda>x. monomial (a x) 0) (focus X p)) \<subseteq> (\<lambda>t. except t X) ` keys p" proof fix t assume "t \<in> keys (poly_eval (\<lambda>x. monomial (a x) 0) (focus X p))" hence "lookup (poly_eval (\<lambda>x. monomial (a x) 0) (focus X p)) t \<noteq> 0" by (simp add: in_keys_iff) hence "poly_eval a (lookup (focus (- X) p) t) \<noteq> 0" by (simp add: lookup_poly_eval_focus) hence "t \<in> keys (focus (- X) p)" by (auto simp flip: lookup_not_eq_zero_eq_in_keys) thus "t \<in> (\<lambda>t. except t X) ` keys p" by (simp add: keys_focus) qed lemma poly_eval_focus_in_Polys: assumes "p \<in> P[X]" shows "poly_eval (\<lambda>x. monomial (a x) 0) (focus Y p) \<in> P[X - Y]" proof (rule PolysI_alt) have "indets (poly_eval (\<lambda>x. monomial (a x) 0) (focus Y p)) \<subseteq> \<Union> (indets ` (\<lambda>x. monomial (a x) 0) ` Y) \<union> (indets p - Y)" by (fact indets_poly_eval_focus_subset) also have "\<dots> = indets p - Y" by simp also from assms have "\<dots> \<subseteq> X - Y" by (auto dest: PolysD) finally show "indets (poly_eval (\<lambda>x. monomial (a x) 0) (focus Y p)) \<subseteq> X - Y" . qed lemma image_poly_eval_focus_ideal: "poly_eval (\<lambda>x. monomial (a x) 0) ` focus X ` ideal F = ideal (poly_eval (\<lambda>x. monomial (a x) 0) ` focus X ` F) \<inter> (P[- X]::(('x \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 'a::comm_ring_1) set)" proof - let ?h = "\<lambda>f. poly_eval (\<lambda>x. monomial (a x) 0) (focus X f)" have h_id: "?h p = p" if "p \<in> P[- X]" for p proof - from that have "focus X p \<in> P[- X \<inter> X]" by (rule focus_in_Polys') also have "\<dots> = P[{}]" by simp finally obtain c where eq: "focus X p = monomial c 0" unfolding Polys_empty .. hence "flatten (focus X p) = flatten (monomial c 0)" by (rule arg_cong) hence "c = p" by (simp add: flatten_monomial) thus "?h p = p" by (simp add: eq poly_eval_monomial) qed have rng: "range ?h = P[- X]" proof (intro subset_antisym subsetI, elim rangeE) fix b f assume b: "b = ?h f" have "?h f \<in> P[UNIV - X]" by (rule poly_eval_focus_in_Polys) simp thus "b \<in> P[- X]" by (simp add: b Compl_eq_Diff_UNIV) next fix p :: "('x \<Rightarrow>\<^sub>0 nat) \<Rightarrow>\<^sub>0 'a" assume "p \<in> P[- X]" hence "?h p = p" by (rule h_id) hence "p = ?h p" by (rule sym) thus "p \<in> range ?h" by (rule range_eqI) qed have "poly_eval (\<lambda>x. monomial (a x) 0) ` focus X ` ideal F = ?h ` ideal F" by (fact image_image) also have "\<dots> = ideal (?h ` F) \<inter> range ?h" proof (rule image_ideal_eq_Int) fix p have "?h p \<in> range ?h" by (fact rangeI) also have "\<dots> = P[- X]" by fact finally show "?h (?h p) = ?h p" by (rule h_id) qed (simp_all only: focus_plus poly_eval_plus focus_times poly_eval_times) also have "\<dots> = ideal (poly_eval (\<lambda>x. monomial (a x) 0) ` focus X ` F) \<inter> P[- X]" by (simp only: image_image rng) finally show ?thesis . qed subsection \<open>Locale @{term pm_powerprod}\<close> lemma varnum_eq_zero_iff: "varnum X t = 0 \<longleftrightarrow> t \<in> .[X]" by (auto simp: varnum_def PPs_def) lemma dgrad_set_varnum: "dgrad_set (varnum X) 0 = .[X]" by (simp add: dgrad_set_def PPs_def varnum_eq_zero_iff) context ordered_powerprod begin abbreviation "lcf \<equiv> punit.lc" abbreviation "tcf \<equiv> punit.tc" abbreviation "lpp \<equiv> punit.lt" abbreviation "tpp \<equiv> punit.tt" end (* ordered_powerprod *) locale pm_powerprod = ordered_powerprod ord ord_strict for ord::"('x::{countable,linorder} \<Rightarrow>\<^sub>0 nat) \<Rightarrow> ('x \<Rightarrow>\<^sub>0 nat) \<Rightarrow> bool" (infixl "\<preceq>" 50) and ord_strict (infixl "\<prec>" 50) begin sublocale gd_powerprod .. lemma PPs_closed_lpp: assumes "p \<in> P[X]" shows "lpp p \<in> .[X]" proof (cases "p = 0") case True thus ?thesis by (simp add: zero_in_PPs) next case False hence "lpp p \<in> keys p" by (rule punit.lt_in_keys) also from assms have "\<dots> \<subseteq> .[X]" by (rule PolysD) finally show ?thesis . qed lemma PPs_closed_tpp: assumes "p \<in> P[X]" shows "tpp p \<in> .[X]" proof (cases "p = 0") case True thus ?thesis by (simp add: zero_in_PPs) next case False hence "tpp p \<in> keys p" by (rule punit.tt_in_keys) also from assms have "\<dots> \<subseteq> .[X]" by (rule PolysD) finally show ?thesis . qed corollary PPs_closed_image_lpp: "F \<subseteq> P[X] \<Longrightarrow> lpp ` F \<subseteq> .[X]" by (auto intro: PPs_closed_lpp) corollary PPs_closed_image_tpp: "F \<subseteq> P[X] \<Longrightarrow> tpp ` F \<subseteq> .[X]" by (auto intro: PPs_closed_tpp) lemma hom_component_lpp: assumes "p \<noteq> 0" shows "hom_component p (deg_pm (lpp p)) \<noteq> 0" (is "?p \<noteq> 0") and "lpp (hom_component p (deg_pm (lpp p))) = lpp p" proof - from assms have "lpp p \<in> keys p" by (rule punit.lt_in_keys) hence *: "lpp p \<in> keys ?p" by (simp add: keys_hom_component) thus "?p \<noteq> 0" by auto from * show "lpp ?p = lpp p" proof (rule punit.lt_eqI_keys) fix t assume "t \<in> keys ?p" hence "t \<in> keys p" by (simp add: keys_hom_component) thus "t \<preceq> lpp p" by (rule punit.lt_max_keys) qed qed definition is_hom_ord :: "'x \<Rightarrow> bool" where "is_hom_ord x \<longleftrightarrow> (\<forall>s t. deg_pm s = deg_pm t \<longrightarrow> (s \<preceq> t \<longleftrightarrow> except s {x} \<preceq> except t {x}))" lemma is_hom_ordD: "is_hom_ord x \<Longrightarrow> deg_pm s = deg_pm t \<Longrightarrow> s \<preceq> t \<longleftrightarrow> except s {x} \<preceq> except t {x}" by (simp add: is_hom_ord_def) lemma dgrad_p_set_varnum: "punit.dgrad_p_set (varnum X) 0 = P[X]" by (simp add: punit.dgrad_p_set_def dgrad_set_varnum Polys_def) end text \<open>We must create a copy of @{locale pm_powerprod} to avoid infinite chains of interpretations.\<close> instantiation option :: (linorder) linorder begin fun less_eq_option :: "'a option \<Rightarrow> 'a option \<Rightarrow> bool" where "less_eq_option None _ = True" | "less_eq_option (Some x) None = False" | "less_eq_option (Some x) (Some y) = (x \<le> y)" definition less_option :: "'a option \<Rightarrow> 'a option \<Rightarrow> bool" where "less_option x y \<longleftrightarrow> x \<le> y \<and> \<not> y \<le> x" instance proof fix x :: "'a option" show "x \<le> x" using less_eq_option.elims(3) by fastforce qed (auto simp: less_option_def elim!: less_eq_option.elims) end locale extended_ord_pm_powerprod = pm_powerprod begin definition extended_ord :: "('a option \<Rightarrow>\<^sub>0 nat) \<Rightarrow> ('a option \<Rightarrow>\<^sub>0 nat) \<Rightarrow> bool" where "extended_ord s t \<longleftrightarrow> (restrict_indets_pp s \<prec> restrict_indets_pp t \<or> (restrict_indets_pp s = restrict_indets_pp t \<and> lookup s None \<le> lookup t None))" definition extended_ord_strict :: "('a option \<Rightarrow>\<^sub>0 nat) \<Rightarrow> ('a option \<Rightarrow>\<^sub>0 nat) \<Rightarrow> bool" where "extended_ord_strict s t \<longleftrightarrow> (restrict_indets_pp s \<prec> restrict_indets_pp t \<or> (restrict_indets_pp s = restrict_indets_pp t \<and> lookup s None < lookup t None))" sublocale extended_ord: pm_powerprod extended_ord extended_ord_strict proof - have 1: "s = t" if "lookup s None = lookup t None" and "restrict_indets_pp s = restrict_indets_pp t" for s t :: "'a option \<Rightarrow>\<^sub>0 nat" proof (rule poly_mapping_eqI) fix y show "lookup s y = lookup t y" proof (cases y) case None with that(1) show ?thesis by simp next case y: (Some z) have "lookup s y = lookup (restrict_indets_pp s) z" by (simp only: lookup_restrict_indets_pp y) also have "\<dots> = lookup (restrict_indets_pp t) z" by (simp only: that(2)) also have "\<dots> = lookup t y" by (simp only: lookup_restrict_indets_pp y) finally show ?thesis . qed qed have 2: "0 \<prec> t" if "t \<noteq> 0" for t::"'a \<Rightarrow>\<^sub>0 nat" using that zero_min by (rule ordered_powerprod_lin.dual_order.not_eq_order_implies_strict) show "pm_powerprod extended_ord extended_ord_strict" by standard (auto simp: extended_ord_def extended_ord_strict_def restrict_indets_pp_plus lookup_add 1 dest: plus_monotone_strict 2) qed lemma extended_ord_is_hom_ord: "extended_ord.is_hom_ord None" by (auto simp add: extended_ord_def lookup_restrict_indets_pp lookup_except extended_ord.is_hom_ord_def simp flip: deg_pm_restrict_indets_pp) end end (* theory *)
K = 10 w = c(5,2,4,6) v = c(18,9,12,25) DataKnap<-data.frame(w,v) DataKnap$rows_idx <- row(DataKnap) DataKnap <- DataKnap[DataKnap$w < K,] DataKnap$VWRatio <- DataKnap$v/DataKnap$w DescOrder <- order(DataKnap$VWRatio, decreasing = TRUE) DataKnap <- DataKnap[DescOrder,] KnapSol <- list(value = 0) SumWeights <- 0 i <- 1 while (i<=nrow(DataKnap) & SumWeights + DataKnap$w[i]<=K){ SumWeights <- SumWeights + DataKnap$w[i] KnapSol$value <- KnapSol$value + DataKnap$v[i] KnapSol$elements[i] <- DataKnap$row[i] i <- i + 1 } print(KnapSol)
(** This file proves the basic laws of the HeapLang program logic by applying the Iris lifting lemmas. *) From iris.proofmode Require Import proofmode. From iris.bi.lib Require Import fractional. From transfinite.base_logic.lib Require Import mono_nat. From transfinite.base_logic.lib Require Export gen_heap gen_inv_heap. From melocoton.language Require Export weakestpre lifting. From melocoton.ml_lang Require Export lang_instantiation class_instances. From melocoton.ml_lang Require Import tactics notation. From iris.prelude Require Import options. From melocoton Require Import monotone. Class heapGpre_ML {SI:indexT} Σ := HeapGpre_ML { heapGpre_gen_heapGpre :> gen_heapPreG loc (option (list val)) Σ; }. Class heapG_ML `{SI: indexT} Σ := HeapG_ML { heapG_gen_heapG :> gen_heapG loc (option (list val)) Σ; }. Definition heapΣ_ML {SI: indexT} : gFunctors := #[gen_heapΣ loc (option (list val))]. Global Instance subG_heapGpre_ML `{SI: indexT} Σ : subG heapΣ_ML Σ → heapGpre_ML Σ. Proof. solve_inG. Qed. Local Notation state := (gmap loc (option (list val))). Global Program Instance heapG_langG_ML `{SI: indexT}`{heapG_ML Σ} : langG val ML_lang Σ := { state_interp σ := gen_heap_interp σ }. Notation "l ↦M{ dq } v" := (mapsto (L:=loc) (V:=option (list val)) l dq (Some [v%MLV])) (at level 20, format "l ↦M{ dq } v") : bi_scope. Notation "l ↦M□ v" := (mapsto (L:=loc) (V:=option (list val)) l DfracDiscarded (Some [v%MLV])) (at level 20, format "l ↦M□ v") : bi_scope. Notation "l ↦M{# q } v" := (mapsto (L:=loc) (V:=option (list val)) l (DfracOwn q) (Some [v%MLV])) (at level 20, format "l ↦M{# q } v") : bi_scope. Notation "l ↦M v" := (mapsto (L:=loc) (V:=option (list val)) l (DfracOwn 1) (Some [v%MLV])) (at level 20, format "l ↦M v") : bi_scope. Notation "l ↦M/{ dq }" := (mapsto (L:=loc) (V:=option (list val)) l dq None) (at level 20, format "l ↦M/{ dq } ") : bi_scope. Notation "l ↦M/□" := (mapsto (L:=loc) (V:=option (list val)) l DfracDiscarded None) (at level 20, format "l ↦M/□") : bi_scope. Notation "l ↦M/{# q }" := (mapsto (L:=loc) (V:=option (list val)) l (DfracOwn q) None) (at level 20, format "l ↦M/{# q }") : bi_scope. Notation "l ↦M/" := (mapsto (L:=loc) (V:=option (list val)) l (DfracOwn 1) None) (at level 20, format "l ↦M/") : bi_scope. Notation "l ↦∗{ dq } vs" := (mapsto (L:=loc) (V:=option (list val)) l dq (Some vs)) (at level 20, format "l ↦∗{ dq } vs") : bi_scope. Notation "l ↦∗□ vs" := (mapsto (L:=loc) (V:=option (list val)) l DfracDiscarded (Some vs)) (at level 20, format "l ↦∗□ vs") : bi_scope. Notation "l ↦∗{# q } vs" := (mapsto (L:=loc) (V:=option (list val)) l (DfracOwn q) (Some vs)) (at level 20, format "l ↦∗{# q } vs") : bi_scope. Notation "l ↦∗ vs" := (mapsto (L:=loc) (V:=option (list val)) l (DfracOwn 1) (Some vs)) (at level 20, format "l ↦∗ vs") : bi_scope. Global Instance: Params (@inv_mapsto_own) 5 := {}. Global Instance: Params (@inv_mapsto) 4 := {}. Notation inv_heap_inv := (inv_heap_inv loc (option (list val))). Notation "l '↦∗_' I □" := (inv_mapsto l I%stdpp%type) (at level 20, I at level 9, format "l '↦∗_' I '□'") : bi_scope. Notation "l ↦∗_ I vs" := (inv_mapsto_own l vs I%stdpp%type) (at level 20, I at level 9, format "l ↦∗_ I vs") : bi_scope. Section lifting. Context `{SI: indexT}. Context `{!heapG_ML Σ, !invG Σ}. Implicit Types P Q : iProp Σ. Implicit Types Φ Ψ : val → iProp Σ. Implicit Types σ : state. Implicit Types v : val. Implicit Types vs : list val. Implicit Types l : loc. Implicit Types pe : prog_environ ML_lang Σ. (** Recursive functions: we do not use this lemmas as it is easier to use Löb induction directly, but this demonstrates that we can state the expected reasoning principle for recursive functions, without any visible ▷. *) Lemma wp_rec_löb pe E f x e Φ Ψ : □ ( □ (∀ v, Ψ v -∗ WP (rec: f x := e)%MLV v @ pe; E {{ Φ }}) -∗ ∀ v, Ψ v -∗ WP (subst' x v (subst' f (rec: f x := e)%MLV e))%MLE @ pe; E {{ Φ }}) -∗ ∀ v, Ψ v -∗ WP (rec: f x := e)%MLV v @ pe; E {{ Φ }}. Proof. iIntros "#Hrec". iLöb as "IH". iIntros (v) "HΨ". iApply lifting.wp_pure_step_later; first eauto. iIntros "!>". iApply ("Hrec" with "[] HΨ"). iIntros "!>" (w) "HΨ". iApply ("IH" with "HΨ"). Qed. (** Heap *) (** We need to adjust the [gen_heap] and [gen_inv_heap] lemmas because of our value type being [val]. *) Lemma mapsto_valid l dq v : l ↦M{dq} v -∗ ⌜✓ dq⌝. Proof. apply mapsto_valid. Qed. Lemma mapsto_valid_2 l dq1 dq2 v1 v2 : l ↦M{dq1} v1 -∗ l ↦M{dq2} v2 -∗ ⌜✓ (dq1 ⋅ dq2) ∧ v1 = v2⌝. Proof. iIntros "H1 H2". iDestruct (mapsto_valid_2 with "H1 H2") as %[? [=?]]. done. Qed. Lemma mapsto_agree l dq1 dq2 v1 v2 : l ↦M{dq1} v1 -∗ l ↦M{dq2} v2 -∗ ⌜v1 = v2⌝. Proof. iIntros "H1 H2". iDestruct (mapsto_agree with "H1 H2") as %[=?]. done. Qed. Lemma mapsto_combine l dq1 dq2 v1 v2 : l ↦M{dq1} v1 -∗ l ↦M{dq2} v2 -∗ l ↦M{dq1 ⋅ dq2} v1 ∗ ⌜v1 = v2⌝. Proof. iIntros "Hl1 Hl2". iDestruct (mapsto_combine with "Hl1 Hl2") as "[$ Heq]". by iDestruct "Heq" as %[= ->]. Qed. Lemma mapsto_frac_ne l1 l2 dq1 dq2 v1 v2 : ¬ ✓(dq1 ⋅ dq2) → l1 ↦M{dq1} v1 -∗ l2 ↦M{dq2} v2 -∗ ⌜l1 ≠ l2⌝. Proof. apply mapsto_frac_ne. Qed. Lemma mapsto_ne l1 l2 dq2 v1 v2 : l1 ↦M v1 -∗ l2 ↦M{dq2} v2 -∗ ⌜l1 ≠ l2⌝. Proof. apply mapsto_ne. Qed. Lemma mapsto_persist l dq v : l ↦M{dq} v ==∗ l ↦M□ v. Proof. apply mapsto_persist. Qed. Lemma wp_allocN pe E v n : (0 ≤ n)%Z → {{{ True }}} AllocN (Val $ LitV $ LitInt n) (Val v) @ pe; E {{{ l, RET LitV (LitLoc l); l ↦∗ (replicate (Z.to_nat n) v) ∗ meta_token l ⊤ }}}. Proof. iIntros (Hn Φ) "_ HΦ". iApply wp_lift_atomic_head_step; first done. iIntros (σ1) "Hσ". iModIntro. iSplit; first (destruct n; eauto with lia head_step). iIntros (v2 σ2 Hstep). inv_head_step; last lia. iModIntro. iMod (gen_heap_alloc _ l (Some (replicate (Z.to_nat n) v)) with "Hσ") as "(Hσ & Hl & Hm)". { by apply not_elem_of_dom. } iModIntro. iFrame. iApply "HΦ"; iFrame. Qed. Lemma wp_alloc pe E v : {{{ True }}} Alloc (Val v) @ pe; E {{{ l, RET LitV (LitLoc l); l ↦M v ∗ meta_token l ⊤ }}}. Proof. iIntros (HΦ) "_ HΦ". by iApply wp_allocN. Qed. Lemma wp_allocN_wrong_size pe E v n : (n < 0)%Z → {{{ True }}} AllocN (Val $ LitV $ LitInt n) (Val v) @ pe; E {{{ RET v; False }}}. Proof. iIntros (Hn Φ) "_ HΦ". iLöb as "IH". iApply wp_lift_step_fupd; first done. iIntros (σ1) "Hσ !>". iSplit. { iPureIntro. eapply head_prim_reducible. eexists _, _. by eapply AllocNWrongSizeS. } iIntros (v2 σ2 Hstep). eapply head_reducible_prim_step in Hstep; first (inv_head_step; first lia). 2: { eexists _, _. by eapply AllocNWrongSizeS. } do 4 iModIntro. iFrame. by iApply "IH". Qed. Lemma wp_loadN pe E l i dq vs v : (0 ≤ i)%Z → vs !! Z.to_nat i = Some v → {{{ ▷ l ↦∗{dq} vs }}} LoadN (Val $ LitV $ LitLoc l) (Val $ LitV $ LitInt i) @ pe; E {{{ RET v; l ↦∗{dq} vs }}}. Proof. iIntros (Hi Hv Φ) ">Hl HΦ". iApply wp_lift_atomic_head_step; first done. iIntros (σ1) "Hσ !>". iDestruct (gen_heap_valid with "Hσ Hl") as %?. assert (σ1 !! l.[i] = Some v). { rewrite store_lookup_eq. case_bool_decide; [|done]. by simplify_map_eq/=. } iSplit; first by eauto with head_step. iIntros (v2 σ2 Hstep); inv_head_step. iNext. iModIntro. iFrame. by iApply "HΦ". Qed. Lemma wp_loadN_oob pe E l i dq vs : (i < 0 ∨ length vs ≤ i)%Z → {{{ ▷ l ↦∗{dq} vs }}} LoadN (Val $ LitV $ LitLoc l) (Val $ LitV $ LitInt i) @ pe; E {{{ v, RET v; False }}}. Proof. iIntros (Hi Φ) ">Hl HΦ". iLöb as "IH". iApply wp_lift_step_fupd; first done. iIntros (σ1) "Hσ !>". iDestruct (gen_heap_valid with "Hσ Hl") as %?. assert (σ1 !! l.[i] = None). { rewrite store_lookup_eq. case_bool_decide; [|done]. simplify_map_eq/=. destruct Hi; try lia. apply lookup_ge_None_2; lia. } iSplit. { iPureIntro. eapply head_prim_reducible. eexists _, _. by eapply LoadNOobS. } iIntros (v2 σ2 Hstep). eapply head_reducible_prim_step in Hstep; first inv_head_step. 2: { eexists _, _; by eapply LoadNOobS. } do 4 iModIntro. iFrame. by iApply ("IH" with "[$] [$]"). Qed. Lemma wp_load pe E l dq v : {{{ ▷ l ↦M{dq} v }}} Load (Val $ LitV $ LitLoc l) @ pe; E {{{ RET v; l ↦M{dq} v }}}. Proof. iIntros (Φ) ">Hl HΦ". iApply (wp_loadN with "Hl"); try done. Qed. Lemma wp_storeN pe E l i vs w : (0 ≤ i < length vs)%Z → {{{ ▷ l ↦∗ vs }}} StoreN (Val $ LitV $ LitLoc l) (Val $ LitV $ LitInt i) (Val w) @ pe; E {{{ RET LitV LitUnit; l ↦∗ <[ Z.to_nat i := w ]> vs }}}. Proof. iIntros (Hi Φ) ">Hl HΦ". iApply wp_lift_atomic_head_step; first done. iIntros (σ1) "Hσ !>". iDestruct (gen_heap_valid with "Hσ Hl") as %?. assert (is_Some (σ1 !! l.[i])) as [? ?]. { rewrite store_lookup_eq. case_bool_decide; [|lia]. simplify_map_eq. apply lookup_lt_is_Some. lia. } iSplit; first by eauto with head_step. iIntros (v2 σ2 Hstep); inv_head_step. iModIntro. iMod (gen_heap_update with "Hσ Hl") as "[Hσ Hl]". rewrite (store_insert_offset _ _ _ vs); auto; []. iModIntro. iFrame "Hσ". iApply "HΦ". iApply "Hl". Qed. Lemma wp_storeN_oob pe E l i vs w : (i < 0 ∨ length vs ≤ i)%Z → {{{ ▷ l ↦∗ vs }}} StoreN (Val $ LitV $ LitLoc l) (Val $ LitV $ LitInt i) (Val w) @ pe; E {{{ v, RET v; False }}}. Proof. iIntros (Hi Φ) ">Hl HΦ". iLöb as "IH". iApply wp_lift_step_fupd; first done. iIntros (σ1) "Hσ !>". iDestruct (gen_heap_valid with "Hσ Hl") as %?. assert (σ1 !! l.[i] = None). { rewrite store_lookup_eq. case_bool_decide; [|done]. simplify_map_eq/=. destruct Hi; try lia. apply lookup_ge_None_2; lia. } iSplit. { iPureIntro. eapply head_prim_reducible. eexists _, _. by eapply StoreNOobS. } iIntros (v2 σ2 Hstep). eapply head_reducible_prim_step in Hstep; first inv_head_step. 2: { eexists _, _; by eapply StoreNOobS. } do 4 iModIntro. iFrame. iApply ("IH" with "[$] [$]"). Qed. Lemma wp_store pe E l v w : {{{ ▷ l ↦M v }}} Store (Val $ LitV $ LitLoc l) (Val w) @ pe; E {{{ RET LitV LitUnit; l ↦M w }}}. Proof. iIntros (Φ) "Hl HΦ". by iApply (wp_storeN with "Hl"). Qed. Lemma wp_length pe E l dq vs : {{{ ▷ l ↦∗{dq} vs }}} Length (Val $ LitV $ LitLoc l) @ pe; E {{{ RET LitV $ LitInt (length vs); l ↦∗{dq} vs }}}. Proof. iIntros (Φ) ">Hl HΦ". iApply wp_lift_atomic_head_step; first done. iIntros (σ1) "Hσ !>". iDestruct (gen_heap_valid with "Hσ Hl") as %?. iSplit; first by eauto with head_step. iIntros (v2 σ2 Hstep); inv_head_step. do 2 iModIntro. iFrame. by iApply "HΦ". Qed. (* TODO: rules to allow splitting the ownership of an array, and having the knowledge of the length of an array be persistent, following what is done in Cosmo. *) End lifting.
Module M. Module Type SIG. Parameter T : Set. Parameter x : T. End SIG. Module N : SIG. Definition T := nat. Definition x := 0. End N. End M. Module N := M. Module Type SPRYT. Module N. Definition T := M.N.T. Parameter x : T. End N. End SPRYT. Module K : SPRYT := N. Module K' : SPRYT := M. Module Type SIG. Definition T : Set := M.N.T. Parameter x : T. End SIG. Module J : SIG := M.N.
Mathews returned to the African mainland territories once more in 1884 when he landed with a force which intended to establish further garrisons there to dissuade German territorial claims . This attempt ultimately failed when five German warships steamed into Zanzibar Town harbour and threatened the Sultan into signing away the territories which would later form German East Africa . Further territories were ceded to the German East Africa Company in 1888 but unrest amongst the locals against them prevented them from taking control and Mathews was dispatched with 100 men to restore order . Finding around 8 @,@ 000 people gathered against the German administrators Mathews was forced to return with his men to Zanzibar . He landed once again with more troops but found himself subject to death threats and that his troops would not obey his orders and so returned again to Zanzibar .
module Legacy.Base {-# DEPRECATED "Use Vector instead" #-} where import Data.Complex import Data.Either import Data.List import Control.Applicative newtype StateVector = StateVector [Complex Double] deriving (Eq, Show) newtype TransformTensor = TransformTensor [[Complex Double]] deriving (Eq, Show) {-| integerLog2 determines if an integer is a power of 2 If it is, the log base 2 of the integer will be wrapped by Right constructor; if not, Left constructor with corresponding error will be returned. The function takes 1 argument of type 'Int' -} integerLog2 :: Int -> Either String Int integerLog2 x | x < 1 = Left "Input less than 0" | x == 1 = Right 0 | y * 2 == x = (+1) <$> integerLog2 y | otherwise = Left "Input is not a power of 2" where y = quot x 2 initQubit :: Complex Double -> Complex Double -> Either String StateVector initQubit a b | magnitude a ** 2 + magnitude b ** 2 == 1 = Right $ StateVector [a, b] | otherwise = Left "Magnitude Error" initQubit0 :: StateVector initQubit0 = StateVector [1:+0, 0:+0] initNumQubits :: Int -> Either String StateVector initNumQubits n | n < 1 = Left "Number of Qubits Must be Greater than 1" | otherwise = Right $ foldr mergeState (StateVector [1 :+ 0]) $ replicate n initQubit0 initState :: [Complex Double] -> Either String StateVector initState q | isLeft numQubits = Left "Input State Dimension Invalid" | otherwise = Right $ StateVector q where numQubits = integerLog2 $ length q mergeState :: StateVector -> StateVector -> StateVector mergeState (StateVector x) (StateVector y) = StateVector $ liftA2 (*) x y mergeTensor :: TransformTensor -> TransformTensor -> TransformTensor mergeTensor (TransformTensor x) (TransformTensor y) = TransformTensor $ fmap ((<*>) . fmap (*)) x <*> y tensorAdd :: TransformTensor -> TransformTensor -> Either String TransformTensor tensorAdd (TransformTensor i) (TransformTensor j) | m == x && n == y = Right $ TransformTensor $ zipWith (zipWith (+)) i j | otherwise = Left "Adding Two Tensors with Different Dimensions" where m = length i n = length $ head i x = length j y = length $ head j doubleBindEither :: Either String TransformTensor -> Either String TransformTensor -> (TransformTensor -> TransformTensor -> Either String TransformTensor) -> Either String TransformTensor doubleBindEither x y f | isLeft x && isRight y = Left $ fromLeft [] x ++ "\n" ++ fromLeft [] y | isLeft x = x | isLeft y = y | otherwise = f (fromRight (TransformTensor [[]]) x) (fromRight (TransformTensor [[]]) y) applyTensorToState :: TransformTensor -> StateVector -> Either String StateVector applyTensorToState (TransformTensor g) (StateVector q) | length f == length q && length q == length g = Right $ StateVector $ foldr (zipWith (+)) acc $ zipWith fmap (fmap (*) q) f | otherwise = Left "Transformation Matrix Dimension Mismatch" where acc = replicate (length q) $0:+0 f = transpose g -- The qubits are 1-indexed applyGateToQubit :: TransformTensor -> Int -> StateVector -> Either String StateVector applyGateToQubit g n (StateVector q) = t >>= (`applyTensorToState` StateVector q) where numQubits = integerLog2 $ length q t = numQubits >>= flip (genTensor g) n -- Gate to insert -> Number of Qubits -> Index of Qubit genTensor :: TransformTensor -> Int -> Int -> Either String TransformTensor genTensor g n i | n < i || i < 1 = Left "Index Out of Range" | otherwise = Right $ foldr mergeTensor (TransformTensor [[1:+0]]) expGate where expGate = fstId ++ [g] ++ lstId fstId = replicate (i - 1) pauliId lstId = replicate (n - i) pauliId getQubitState :: Int -> StateVector -> Either String (Double, Double) getQubitState x (StateVector q) | x < 1 = Left "Index Out of Bounds" | otherwise = Right (zeroP, oneP) where numRow = 2 ^ (x - 1) q2 = fmap (** 2) q zeroP = magnitude $ sum $ takeHalf q2 numRow oneP = magnitude $ sum $ takeHalf (drop numRow q2) numRow takeHalf :: [Complex Double] -> Int -> [Complex Double] takeHalf xs n | length xs < n = [] | otherwise = take n xs ++ takeHalf (drop (2 * n) xs) n -- Gate to Apply -> Control Bit Index -> Application Bit Index -> Circuit To Apply applyControlToQubits :: TransformTensor -> Int -> Int -> StateVector -> Either String StateVector applyControlToQubits g m n (StateVector q) | m < n = t m n mask1 g >>= (`applyTensorToState` StateVector q) | m > n = t n m g mask1 >>= (`applyTensorToState` StateVector q) | otherwise = Left "Control and Application Qubit Cannot be Identical" where zeroMask = numQubits >>= flip (genTensor mask0) m numQubits = integerLog2 $ length q t :: Int -> Int -> TransformTensor -> TransformTensor -> Either String TransformTensor t i j fstGate sndGate = doubleBindEither (fmap mergeTensor fstTensor <*> sndTensor) zeroMask tensorAdd where fstTensor = genTensor fstGate i i sndTensor = numQubits >>= flip (genTensor sndGate) (j - i) . flip (-) i pauliX :: TransformTensor pauliX = TransformTensor [[0 :+ 0, 1 :+ 0], [1 :+ 0, 0 :+ 0]] pauliY :: TransformTensor pauliY = TransformTensor [[0 :+ 0, 0 :+ (-1)], [0 :+ 1, 0 :+ 0]] pauliZ :: TransformTensor pauliZ = TransformTensor [[1 :+ 0, 0 :+ 0], [0 :+ 0, (-1) :+ 0]] pauliId :: TransformTensor pauliId = TransformTensor [[1 :+ 0, 0 :+ 0], [0 :+ 0, 1 :+ 0]] hadamard :: TransformTensor hadamard = TransformTensor [[1 / sqrt 2 :+ 0, 1 / sqrt 2 :+ 0], [1 / sqrt 2 :+ 0, (-1) / sqrt 2 :+ 0]] mask0 :: TransformTensor mask0 = TransformTensor [[1 :+ 0, 0 :+ 0], [0 :+ 0, 0 :+ 0]] mask1 :: TransformTensor mask1 = TransformTensor [[0 :+ 0, 0 :+ 0], [0 :+ 0, 1 :+ 0]] -- main :: IO() -- main = print result -- where q0 = initQubit0 -- crt = mergeState q0 q0 -- flip1 = applyGateToQubit hadamard 1 crt -- flip2 = flip1 >>= applyControlToQubits pauliY 1 2 -- --result = flip2 >>= (getQubitState 2) -- result = TransformTensor [[0 :+ 0, 0 :+ 0], -- [0 :+ 0, 1 :+ 0]] -- Linear algebra versions -- safeMultiply :: Num a => T.Tensor a -> T.Tensor a -> Either String (T.Tensor a) -- safeMultiply (T.Tensor x) (T.Tensor y) -- | T.isSquare (T.Tensor x) -- && T.isSquare (T.Tensor y) -- && length x == length y = Right $ T.Tensor x * T.Tensor y -- | otherwise = Left "Dimension mismatch" -- safeMultiply x y = Right $ x * y -- -- combine two qubit circuits -- addQubit :: Num a => T.Tensor a -- ^ first half statevector -- -> T.Tensor a -- ^ second half statevector -- -> T.Tensor a -- addQubit (T.Tensor x) (T.Tensor y) -- | T.rank (T.Tensor x) /= 1 || T.rank (T.Tensor y) /= 1 = error "One of the elements is not a valid statevector" -- | otherwise = T.Tensor $ liftA2 (*) x y -- addQubit _ _ = error "One of the elements is not a valid statevector" -- Applies input gate to qubit of index -- -- Builds a transformation tensor to apply input gate to selected qubit -- build :: RealFloat a => Int -- ^ Number of qubits this tensor applies to -- -> [(Int, T.Tensor (Complex a))]-- ^ Index / Gate pair (Pre-sorted) -- -> T.Tensor (Complex a)-- ^ Default Gate -- -> T.Tensor (Complex a) -- build len lst dft = T.flatten2d $ foldr T.product (T.fromList [1]) (go len lst 0) -- where -- go l (x:xs) offset -- | fst x >= l = go l [] offset -- | otherwise = replicate (fst x - offset) dft ++ [snd x] ++ go l xs (fst x + 1) -- go l [] offset = replicate (l - offset) dft -- applyGate :: RealFloat a => T.Tensor (Complex a) -- ^ Gate tensor -- -> Int -- ^ Index -- -> T.Tensor (Complex a) -- ^ State vector -- -> Either String (T.Tensor (Complex a)) -- applyGate (T.Tensor xs) i (T.Tensor ys) -- | T.rank x /= 2 || not (T.isSquare x) || numT == 0 = Left "Invalid Gate Tensor" -- | T.rank y /= 1 || numV == 0 = Left "Invalid Statevector" -- | i < 0 || i >= numV = Left "Index out of bounds" -- | otherwise = Right $ build numV [(i, x)] pauliId * y -- where -- x = T.Tensor xs -- y = T.Tensor ys -- numT = fromRight 0 $ integralLog 2 (length xs) -- numV = fromRight 0 $ integralLog 2 (length ys) -- applyGate _ _ _ = Left "Input is not a Tensor" -- applyGateAll :: RealFloat a => T.Tensor (Complex a) -> T.Tensor (Complex a) -> Either String (T.Tensor (Complex a)) -- applyGateAll (T.Tensor xs) (T.Tensor ys) -- | T.rank x /= 2 || not (T.isSquare x) || numT == 0 = Left "Invalid Gate Tensor" -- | T.rank y /= 1 || numV == 0 = Left "Invalid Statevector" -- | otherwise = Right $ build numV [] x * y -- where -- x = T.Tensor xs -- y = T.Tensor ys -- numT = fromRight 0 $ integralLog 2 (length xs) -- numV = fromRight 0 $ integralLog 2 (length ys) -- applyGateAll _ _ = Left "Input is not a Tensor" -- applyControl :: RealFloat a => T.Tensor (Complex a) -- ^ Gate tensor -- -> Int -- ^ Control qubit index -- -> Int -- ^ Apply qubit index -- -> T.Tensor (Complex a) -- ^ State vector -- -> Either String (T.Tensor (Complex a)) -- applyControl (T.Tensor xs) ctl i (T.Tensor ys) -- | T.rank x /= 2 || not (T.isSquare x) || numT == 0 = Left "Invalid Gate Tensor" -- | T.rank y /= 1 || numV == 0 = Left "Invalid Statevector" -- | i < 0 || i >= numV = Left "Application qubit index out of bounds" -- | ctl < 0 || ctl >= numV = Left "Control qubit index out of bounds" -- | ctl == i = Left "Control and application qubit cannot be the same" -- | otherwise = Right $ (build numV [(ctl, mask0)] pauliId -- + build numV (sortBy (compare `on` fst) [(ctl, mask1), (i, x)]) pauliId) * y -- where -- x = T.Tensor xs -- y = T.Tensor ys -- numT = fromRight 0 $ integralLog 2 (length xs) -- numV = fromRight 0 $ integralLog 2 (length ys) -- applyControl _ _ _ _ = Left "Input is not a Tensor"
------------------------------------------------------------------------ -- Some derivable properties ------------------------------------------------------------------------ open import Algebra module Algebra.Props.AbelianGroup (g : AbelianGroup) where open AbelianGroup g import Relation.Binary.EqReasoning as EqR; open EqR setoid open import Data.Function open import Data.Product private lemma : ∀ x y → x ∙ y ∙ x ⁻¹ ≈ y lemma x y = begin x ∙ y ∙ x ⁻¹ ≈⟨ comm _ _ ⟨ ∙-pres-≈ ⟩ refl ⟩ y ∙ x ∙ x ⁻¹ ≈⟨ assoc _ _ _ ⟩ y ∙ (x ∙ x ⁻¹) ≈⟨ refl ⟨ ∙-pres-≈ ⟩ proj₂ inverse _ ⟩ y ∙ ε ≈⟨ proj₂ identity _ ⟩ y ∎ -‿∙-comm : ∀ x y → x ⁻¹ ∙ y ⁻¹ ≈ (x ∙ y) ⁻¹ -‿∙-comm x y = begin x ⁻¹ ∙ y ⁻¹ ≈⟨ comm _ _ ⟩ y ⁻¹ ∙ x ⁻¹ ≈⟨ sym $ lem ⟨ ∙-pres-≈ ⟩ refl ⟩ x ∙ (y ∙ (x ∙ y) ⁻¹ ∙ y ⁻¹) ∙ x ⁻¹ ≈⟨ lemma _ _ ⟩ y ∙ (x ∙ y) ⁻¹ ∙ y ⁻¹ ≈⟨ lemma _ _ ⟩ (x ∙ y) ⁻¹ ∎ where lem = begin x ∙ (y ∙ (x ∙ y) ⁻¹ ∙ y ⁻¹) ≈⟨ sym $ assoc _ _ _ ⟩ x ∙ (y ∙ (x ∙ y) ⁻¹) ∙ y ⁻¹ ≈⟨ sym $ assoc _ _ _ ⟨ ∙-pres-≈ ⟩ refl ⟩ x ∙ y ∙ (x ∙ y) ⁻¹ ∙ y ⁻¹ ≈⟨ proj₂ inverse _ ⟨ ∙-pres-≈ ⟩ refl ⟩ ε ∙ y ⁻¹ ≈⟨ proj₁ identity _ ⟩ y ⁻¹ ∎
module index where -- You probably want to start with this module: import README -- For a brief presentation of every single module, head over to import Everything -- Otherwise, here is an exhaustive, stern list of all the available modules:
lemma diameter_closed_interval [simp]: "diameter {a..b} = (if b < a then 0 else b-a)"
This is a three-tier certification level which aims at providing IP skills development and assessment for typical job positions in the Datacom area. This certification is aimed for those who desire to acquire specific technical skills, such as application, installation, configuration and troubleshooting of Huawei products and solutions. Specialist Certification is based on the job role of Sales Representative, Solution Manager and Field Engineer.
(* (C) Copyright 2010, COQTAIL team Project Info: http://sourceforge.net/projects/coqtail/ This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *) Require Import Ctacfield. Require Import Cbase. Require Import Cprop_base. Require Import Cfunctions. Require Import Cpow. Open Scope C_scope. Lemma binom_add_INC : forall n k : nat, (n>= k)%nat -> - INC (fact n) / INC (fact (n-k) * fact k) + INC (fact (S n)) / INC (fact k * fact (S (n - k))) = INC (k * fact n) / INC ( fact k * fact (S (n-k))). Proof. intros n k H. do 2 rewrite fact_simpl. replace (INC (fact k * (S (n - k) * fact (n - k)))) with (INC (S (n-k)) * INC (fact k * fact (n-k))) by (rewrite mult_comm ; symmetry ; rewrite mult_comm ; rewrite <- mult_INC ; rewrite mult_assoc ; reflexivity). replace (INC (S n * fact n)) with (INC (S n) * INC (fact n)) by (rewrite mult_INC ; reflexivity). unfold Cdiv. rewrite Cinv_mult_distr. apply (Cmult_eq_reg_l (INC (S (n - k)))). apply not_0_INC. intuition. rewrite Cmult_add_distr_l. repeat rewrite mult_INC. field_simplify. rewrite Cmult_comm. rewrite <- Cmult_add_distr_l. unfold Cdiv. repeat rewrite Cmult_assoc. apply Cmult_eq_compat_l. rewrite Cadd_comm. replace (INC (S n) + - INC (S (n - k))) with (INC (S n) - INC (S (n - k))) by intuition. rewrite <- minus_INC. intuition. intuition. split. apply not_0_INC. apply fact_neq_0. split. apply not_0_INC. apply fact_neq_0. apply not_0_INC. intuition. split. apply not_0_INC. apply fact_neq_0. split. apply not_0_INC. apply fact_neq_0. apply not_0_INC. intuition. apply not_0_INC. intuition. apply not_0_INC. intro Habs. apply mult_is_O in Habs. elim Habs; apply fact_neq_0. Qed. (* begin hide *) Lemma equi_binom_add : forall zR zI : R, forall n n0 : nat, (n0 <= n)%nat -> ((zR +i 0%R) + (0%R +i zI)) * ((zR +i 0%R) ^ n0 * (0%R +i zI) ^ (n - n0) * INC (fact n) * / INC (fact n0 * fact (n - n0))) - (zR +i 0%R) ^ n0 * (0%R +i zI) ^ (S n - n0) * INC (fact (S n)) * / INC (fact n0 * fact (S n - n0)) = (zR +i 0%R) ^ (S n0) * (0%R +i zI) ^ (n - n0) * INC (fact n) * / INC (fact n0 * fact (n - n0)) - (zR +i 0%R) ^ n0 * (0%R +i zI) ^ (S n - n0) * INC (n0 * fact n)/ INC ( (fact n0) * fact (n-n0+1)). Proof. intros zR zI n k Hinf. apply Cminus_diag_uniq. rewrite Cmult_add_distr_r. repeat rewrite <- Cmult_assoc. assert (H : ( forall a b c d : C, a + b - c - d = a + (b - c) - d)). intros ; ring. rewrite H. (*replace*) replace ((0%R +i zI) * (zR +i 0%R) ^ k * (0%R +i zI) ^ (n - k) ) with ( (zR +i 0%R) ^ k * (0%R +i zI) ^ (S n - k)) by (symmetry ; rewrite Cmult_comm ; rewrite <- Cmult_assoc ; rewrite Cmult_comm ; rewrite <- Cpow_S ; rewrite minus_Sn_m ; intuition ;apply Hinf). (*end replace*) replace ((zR +i 0%R) ^ k * (0%R +i zI) ^ (S n - k) * INC (fact n) * / INC (fact k * fact (n - k)) - (zR +i 0%R) ^ k * (0%R +i zI) ^ (S n - k) * INC (fact (S n)) * / INC (fact k * fact (S n - k))) with ((zR +i 0%R) ^ k * (0%R +i zI) ^ (S n - k) * (INC (fact n) * / INC (fact k * fact (n - k)) - INC (fact (S n)) * / INC (fact k * fact (S n - k)))) by ring. (* replace *) replace (INC (fact n) * / INC (fact k * fact (n - k)) - INC (fact (S n)) * / INC (fact k * fact (S n - k))) with (-(INC (k * fact n) / INC ( fact k * fact (S (n-k))))). Focus 2. rewrite <- binom_add_INC. rewrite minus_Sn_m. unfold Cdiv. rewrite Copp_add_distr. rewrite Copp_mult_distr_l_reverse. rewrite Copp_invol. replace (fact k * fact (n-k))%nat with (fact (n-k) * fact k)%nat by ring. reflexivity. apply Hinf. apply Hinf. (* end replace*) assert (H1 : (forall a b c d : C, a + b - (c - d) = (a -c) + (b + d))). intros. ring. rewrite H1. rewrite Cpow_S. ring_simplify. replace ((n- k +1)%nat) with (S(n-k))%nat by ring. field. apply not_0_INC. intro Habs. apply mult_is_O in Habs. elim Habs. apply fact_neq_0. apply fact_neq_0. Qed. Lemma fun_prop_bin_add_INC : forall (n : nat) (zR zI : R), (sum_f_C0 (fun n0 : nat => (zR +i zI) * ((zR +i 0%R) ^ n0 * (0%R +i zI) ^ (n - n0) * INC (fact n) / INC (fact n0 * fact (n - n0))) - (zR +i 0%R) ^ n0 * (0%R +i zI) ^ (S n - n0) * INC (fact (S n)) / INC (fact n0 * fact (S n - n0))) n) = (sum_f_C0 (fun n0 : nat => (zR +i0%R)^ S n0 * (0%R +i zI) ^ (n-n0) * INC (fact n) /INC (fact n0 * fact (n - n0)) - (zR +i 0%R) ^ n0 * (0%R +i zI)^ (S n-n0) * INC (n0*fact n) / INC (fact n0 * fact (n-n0 + 1))) n ). Proof. intros n zR zI. apply sum_f_C0_eq_seq. intros n0 H. replace (zR +i zI) with ((zR, 0%R) + (0%R, zI)) by (rewrite <- Ceq ; simpl ; intuition). generalize equi_binom_add. intro Hn1. unfold Cdiv in *. apply Hn1. exact H. Qed. (* end hide *) Lemma Cpow_add_dev : forall z : C, forall n : nat, ((z ^ n)%C = (sum_f_C0 (fun k => (Cre z +i 0%R)^k * (0%R +i Cim z) ^ (n-k) * INC (fact n)/INC ((fact k) * fact (n-k))) n))%C. Proof. intros z. induction n. simpl. CusingR_f. destruct z as (zR, zI). replace ((zR, zI) ^ S n) with ((zR, zI) * (zR, zI) ^ n) by (simpl; reflexivity). rewrite IHn. replace (Cre (zR, zI)) with zR by (simpl; reflexivity). replace (Cim (zR, zI)) with zI by (simpl; reflexivity). rewrite sum_f_C0_mult. rewrite sum_f_C0_simpl. apply Cminus_diag_uniq. assert (H4 : ( forall a b c : C, a - (b + c) = (a - b) - c)). intros; ring. rewrite H4. rewrite <- sum_f_C0_minus_compat. replace (zR, zI) with (zR +i zI) by reflexivity. replace (sum_f_C0 (fun n0 : nat => (zR +i zI) * ((zR +i 0%R) ^ n0 * (0%R +i zI) ^ (n - n0) * INC (fact n) / INC (fact n0 * fact (n - n0))) - (zR +i 0%R) ^ n0 * (0%R +i zI) ^ (S n - n0) * INC (fact (S n)) / INC (fact n0 * fact (S n - n0))) n) with (sum_f_C0 (fun n0 : nat => (zR +i0%R)^ S n0 * (0%R +i zI) ^ (n-n0) * INC (fact n) /INC (fact n0 * fact (n - n0)) - (zR +i 0%R) ^ n0 * (0%R +i zI)^ (S n-n0) * INC (n0 * fact n) / INC (fact n0 * fact (n-n0 + 1))) n ) by (rewrite fun_prop_bin_add_INC ; reflexivity). rewrite sum_f_C0_minus_compat. destruct n. CusingR_f. rewrite sum_f_C0_simpl. rewrite <- sum_f_C0_reindex. (* begin replace *) replace (sum_f_C0 (fun n0 : nat => (zR +i 0%R) ^ S n0 * (0%R +i zI) ^ (S n - n0) * INC (fact (S n)) / INC (fact n0 * fact (S n - n0))) n) with (sum_f_C0 (fun k : nat => (zR +i 0%R) ^ S k * (0%R +i zI) ^ (S (S n) - S k) * INC (S k * fact (S n)) / INC (fact (S k) * fact (S n - S k + 1))) n). Focus 2. apply sum_f_C0_eq_seq. intros m H. repeat rewrite fact_simpl. repeat rewrite mult_INC. replace (S n - S m + 1)%nat with (S n - m)%nat by intuition. replace (S (S n) - S m)%nat with (S n - m)%nat by intuition. field. split ; try split ; apply not_0_INC ; try apply fact_neq_0 ; intuition. (* end replace *) ring_simplify. replace (S n - S n)%nat with O by intuition. replace (S (S n) - S (S n))%nat with O by intuition. repeat rewrite fact_simpl. repeat rewrite mult_INC. simpl (INC 0). field. split ; try split ; try split ; try split ; try apply not_0_INC ; try apply fact_neq_0 ; intuition. Qed.
After all , young people are always searching for the beauty in love . They want their love to be beautiful . If they give in to weakness , following the models of behavior that can rightly be considered a ' scandal in the contemporary world ' ( and these are , unfortunately , widely diffused models ) , in the depths of their hearts they still desire a beautiful and pure love . This is as true of boys as it is of girls . Ultimately , they know that only God can give them this love . As a result , they are willing to follow Christ , without caring about the sacrifices this may entail .
# Relax and hold steady ## Stokes flow This notebook presents the coding assignment for **Module 5** of the course [*"Practical Numerical Methods with Python.*](https://github.com/numerical-mooc/numerical-mooc) Your mission is to solve Stokes flow in a square cavity, using the vorticity-streamfunction formulation. Stokes flow, also known as *creeping flow*, refers to flows that are dominated by viscous forces and not by the advective/convective forces. The Stokes-flow assumption works well for flows that have very low Reynolds number, much smaller than 1: very slow, highly viscous or flows at microscopic length scales. Stokes flow allows us to simplify the Navier-Stokes equations, eliminating the non-linearity. Let's run through a quick derivation of the vorticity-transport equation with Stokes-flow assumptions. ### Vorticity We start with the Navier-Stokes equations for incompressible flow: \begin{equation} \frac{\partial u}{\partial t} + u \cdot \nabla u = -\frac{1}{\rho}\nabla p + \nu\nabla^2 u \end{equation} If we scale Equation $(1)$ to make it non-dimensional, we can rewrite it as \begin{equation} Re \left(\frac{\partial u^*}{\partial t} + u^* \cdot \nabla u^* \right) = -\nabla p^* + \nabla^2 u^* \end{equation} Where $u^*$ and $p^*$ are the non-dimensional velocity and pressure, respectively. To obtain Stokes flow, we assume that the Reynolds number approaches zero. Applying that assumption to Equation $(2)$ and dropping the stars, yields \begin{equation} 0 = - \nabla p + \nabla^2 u \end{equation} That simplified things! Now, we apply the curl operator on both sides of the equation: \begin{equation} \nabla \times 0 = \nabla \times \left( - \nabla p + \nabla^2 u\right) \end{equation} The left-hand side remains zero, while the first term on the right-hand side is \begin{equation} \nabla \times - \nabla p = 0 \end{equation} because $\nabla \times \nabla \phi = 0$ where $\phi$ is a scalar. Finally, \begin{equation} \nabla \times \nabla^2 u =\nabla^2\omega \end{equation} where $\nabla \times u = \omega$ is the vorticity. Combining all of these equations, we arrive at the simplified vorticity transport equation for Stokes flow: \begin{equation} \nabla ^2 \omega = 0 \end{equation} Look familiar? ### Stream function Define the stream function $\psi$, such that \begin{equation} u = \frac{\partial \psi}{\partial y} \text{ and } v = - \frac{\partial \psi}{\partial x} \end{equation} In 2D, we can write out the vorticity as \begin{equation} \omega = \frac{\partial v}{\partial x} - \frac{\partial u}{\partial y} \end{equation} which, combined with the previous equation yields another familiar looking equation: \begin{equation} \nabla^2 \psi = -\omega \end{equation} We have a system of two coupled equations that can describe the fluid flow in a lid-driven cavity at very low Reynolds numbers. \begin{equation} \nabla^2 \omega = 0 \end{equation} \begin{equation} \nabla^2 \psi = -\omega \end{equation} Note that by substituting Equation $(12)$ into $(11)$, we arrive at a new equation: the *biharmonic equation*: \begin{equation} \nabla^4 \psi= 0 \end{equation} ### Solving the biharmonic equation Is it possible to discretize a 4th-order partial differential equation? Of course! Are we going to? No! There's nothing wrong with a 4th-order equation, but in this course module we learned about the Poisson equation and that's what we're going to use. ## Cavity flow You will solve a problem called *lid-driven cavity flow*. This is a common test problem for Navier-Stokes solvers—we'll be using it to examine Stokes flow. Assume that the lid of a square cavity moves at a constant velocity of $u=1$, with no fluid leaking out past the moving lid. We we want to visualize what the flow field inside the cavity looks like at steady state. All of the surfaces, including the lid, are assumed to have no-slip boundary conditions. The boundary conditions are all specified in terms of the streamfunction $\psi$, as shown below in Figure $(1)$. #### Figure 1. Lid-driven Cavity Flow ### Boundary conditions One of the major hurdles with the vorticity-streamfunction formulation is the treatment of boundary conditions. The boundary conditions are all specified in terms of $\psi$ and its derivatives, but the Laplace equation $$\nabla \omega^2 = 0$$ has no $\psi$ value. Instead, we need a way to represent the boundary conditions for $\omega$ in terms of $\psi$. Consider the equation $\nabla ^2 \psi = -\omega$ along the top surface of the cavity (the moving surface). There can't be any velocity in the $y$-direction because the surface is solid, so $\frac{\partial ^2 \psi}{\partial x^2}$ goes to zero and the equation simplifies to \begin{equation} \frac{\partial ^2 \psi}{\partial y^2} = -\omega \end{equation} A 2nd-order central difference discretization gives \begin{equation} \omega_j = - \left(\frac{\psi_{j+1} - 2\psi_j + \psi_{j-1}}{\Delta y^2}\right) \end{equation} but the value $\psi_{j+1}$ is outside of the domain. Now take a 3rd-order discretization of $\frac{\partial \psi}{\partial y}$ evaluated along the top edge. \begin{equation} \left.\frac{\partial \psi}{\partial y}\right|_j = \frac{2\psi_{j+1} + 3\psi_j - 6\psi_{j-1} + \psi_{j-2}}{6 \Delta y} \end{equation} $\frac{\partial \psi}{\partial y}$ is a given boundary value in the problem along the top edge \begin{equation} \left.\frac{\partial \psi}{\partial y}\right|_j = u_j \end{equation} which leaves us with a value for $\psi_{j+1}$ that consists only of points within the domain. \begin{equation} \psi_{j+1} = \frac{6\Delta y u_j - 3\psi_j + 6 \psi_{j-1} - \psi_{j-2}}{2} \end{equation} Plug in that result into the initial discretization from Equation $(16)$ and we have a boundary condition for $\omega$ along the top surface in terms of $\psi$: \begin{equation} \omega_{i,j} = -\frac{1}{2 \Delta y^2} (8\psi_{i, j-1} - \psi_{i, j-2}) - \frac{3u_j}{\Delta y} + \mathcal{O}(\Delta y^2) \end{equation} ### Coding assignment Solve Stokes flow in a lid-driven cavity using the parameters given below. You should iteratively solve for both $\omega$ and $\psi$ until the L1 norm of the difference between successive iterations is less than $1$$\tt{E}$$^-6$ for **both** quantities. ```python nx = 41 ny = 41 l = 1. h = 1. dx = l/(nx-1) dy = h/(ny-1) l1_target = 1e-6 ``` ```python def L1norm(new, old): norm = numpy.sum(numpy.abs(new-old)) return norm ``` The final result should resemble the plot shown in Figure $(2)$. ##### Hint The boundary conditions for $\omega$ depend upon the current value of $\psi$. The two equations are *coupled*. If you try to solve them in a *uncoupled* way, things will go poorly. #### Figure 2. Contour plot of streamfunction at steady state ### References * Fletcher, C. A. (1988). Computational Techniques for Fluid Dynamics: Volume 2: Specific Techniques for Different Flow Categories. * Ghia, U. K. N. G., Ghia, K. N., & Shin, C. T. (1982). High-Re solutions for incompressible flow using the Navier-Stokes equations and a multigrid method. Journal of computational physics, 48(3), 387-411. * Greenspan, D. (1974). Discrete numerical methods in physics and engineering (Vol. 312). New York: Academic Press. * Heil, Matthias (Year unknown). [Viscous Fluid Flow Vorticity Handout (pdf)](http://www.maths.manchester.ac.uk/~mheil/Lectures/Fluids/Material/Vorticity.pdf) * Non-dimensionalization and scaling of the Navier Stokes equations. (n.d.). In *Wikipedia*. Retrieved January 30, 2015 [http://en.wikipedia.org/w/index.php?title=Non-dimensionalization_and_scaling_of_the_Navier-Stokes_equations](http://en.wikipedia.org/w/index.php?title=Non-dimensionalization_and_scaling_of_the_Navier%E2%80%93Stokes_equations&oldid=641860920) ```python from IPython.core.display import HTML css_file = '../../styles/numericalmoocstyle.css' HTML(open(css_file, "r").read()) ``` <link href='http://fonts.googleapis.com/css?family=Alegreya+Sans:100,300,400,500,700,800,900,100italic,300italic,400italic,500italic,700italic,800italic,900italic' rel='stylesheet' type='text/css'> <link href='http://fonts.googleapis.com/css?family=Arvo:400,700,400italic' rel='stylesheet' type='text/css'> <link href='http://fonts.googleapis.com/css?family=PT+Mono' rel='stylesheet' type='text/css'> <link href='http://fonts.googleapis.com/css?family=Shadows+Into+Light' rel='stylesheet' type='text/css'> <link href='http://fonts.googleapis.com/css?family=Nixie+One' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Source+Code+Pro' rel='stylesheet' type='text/css'> <style> @font-face { font-family: "Computer Modern"; src: url('http://mirrors.ctan.org/fonts/cm-unicode/fonts/otf/cmunss.otf'); } #notebook_panel { /* main background */ background: rgb(245,245,245); } div.cell { /* set cell width */ width: 750px; } div #notebook { /* centre the content */ background: #fff; /* white background for content */ width: 1000px; margin: auto; padding-left: 0em; } #notebook li { /* More space between bullet points */ margin-top:0.8em; } /* draw border around running cells */ div.cell.border-box-sizing.code_cell.running { border: 1px solid #111; } /* Put a solid color box around each cell and its output, visually linking them*/ div.cell.code_cell { background-color: rgb(256,256,256); border-radius: 0px; padding: 0.5em; margin-left:1em; margin-top: 1em; } div.text_cell_render{ font-family: 'Alegreya Sans' sans-serif; line-height: 140%; font-size: 125%; font-weight: 400; width:600px; margin-left:auto; margin-right:auto; } /* Formatting for header cells */ .text_cell_render h1 { font-family: 'Nixie One', serif; font-style:regular; font-weight: 400; font-size: 45pt; line-height: 100%; color: rgb(0,51,102); margin-bottom: 0.5em; margin-top: 0.5em; display: block; } .text_cell_render h2 { font-family: 'Nixie One', serif; font-weight: 400; font-size: 30pt; line-height: 100%; color: rgb(0,51,102); margin-bottom: 0.1em; margin-top: 0.3em; display: block; } .text_cell_render h3 { font-family: 'Nixie One', serif; margin-top:16px; font-size: 22pt; font-weight: 600; margin-bottom: 3px; font-style: regular; color: rgb(102,102,0); } .text_cell_render h4 { /*Use this for captions*/ font-family: 'Nixie One', serif; font-size: 14pt; text-align: center; margin-top: 0em; margin-bottom: 2em; font-style: regular; } .text_cell_render h5 { /*Use this for small titles*/ font-family: 'Nixie One', sans-serif; font-weight: 400; font-size: 16pt; color: rgb(163,0,0); font-style: italic; margin-bottom: .1em; margin-top: 0.8em; display: block; } .text_cell_render h6 { /*use this for copyright note*/ font-family: 'PT Mono', sans-serif; font-weight: 300; font-size: 9pt; line-height: 100%; color: grey; margin-bottom: 1px; margin-top: 1px; } .CodeMirror{ font-family: "Source Code Pro"; font-size: 90%; } .alert-box { padding:10px 10px 10px 36px; margin:5px; } .success { color:#666600; background:rgb(240,242,229); } </style>
Brooke Kemper guides her horse, Thanks for the Memories, through a course on her family farm near Harrisonburg, Virginia. Jeremy Martin runs past his A's teammates holding his gold medal after winning the North Roanoke Minor League Championship game against the Pirates. Kristi Glakus believes God played a major factor in her being titled Miss Virginia 2005 and feels very blessed to have the opportunity. Grant Gustin, 15 practices dance moves before the beginning of the Miss Virginia 2005 Pageant at the Roanoke Civic Center in Roanoke, Virginia on Saturday, 25 2005. Gloria Baker lifts her head towards the sky while praying before the beginning of Sunday church service in the William Fleming High School auditorium. Virginia National Guardsmen and Roanoke Police attempt to arrest a role-playing rioter. The officers and guardsmen were participating in a full-speed civil disturbance training exercise that �got a little more out of hand then we expected,� said an officer. Guardsmen and role-playing rioters both sustained several injuries during the full-speed drill. Roger Bolling drinks through a straw offered by his brother-in-law, Farley Bomar. Bolling, now weighing less than 90 pounds, lost all use of his arms and legs after suffering several strokes in the past year. The lights of night are some of the most beautiful gifts our world has to offer. We are blessed to be surrounded by them every night. �In the right light, at the right time, everything is extraordinary.� -Aaron Rose The Empire State building peeks from the horizon through the walls of a New Jersey Transit terminal. Elizabeth �Lizzy� Hall, 11, is the oldest of seven children, living with her family at a Holiday Inn in Salem, Virginia. Her parents, Chuck and Mary Hall, have moved the family around for Chuck Hall�s masonry work and whenever they felt God�s call. Lizzy has been a mother figure to her siblings, changing her first diaper when she was 5. But she dreams of a future that is very different from that of her parents, and is proud of the makeup and platform heels she wears. �Some boys think I look 13,� Lizzy says. Lizzie bends her knees as she strains to support her youngest sister Gracie, 2, in her arms. 'The first time we came here, he thought we were going to stay for a few days, and we stayed for a few months,' Lizzy said of her father. Chuck and Mary Hall exchange a kiss after reading scripture together before Mr. Hall leaves for a day of masonry work. Lizzy�s parents base their decisions on when and where the family will move next on where Chuck Hall can get work and on messages they say they receive from God. He is spiritually counseling a man who is supposed to be painting the family van. But because the man has procrastinated on the job, the family�s anticipated departure date has been repeatedly delayed and kept the family living in the hotel for the past three months. Lizzy�s sister, Deborah, watches as Lizzy hands over a $20 bill to her mother in a Burger King drive-thru in Salem to pay for hamburgers for the family. Lizzy said that her parents sometimes have to borrow money from her but they always pay her back. In the hotel room kitchen, Lizzy�s mother kneels down on the air mattress Lizzy shares with her youngest sister, Gracie, to say their prayers. 'Gracie's always telling me every night, 'play Mommy!'' Lizzy said.
function Base.sort!(df::DataFrame; cols=Any[], alg=nothing, lt=isless, by=identity, rev=false, order=Forward) if !(isa(by, Function) || eltype(by) <: Function) msg = "'by' must be a Function or a vector of Functions. Perhaps you wanted 'cols'." throw(ArgumentError(msg)) end ord = ordering(df, cols, lt, by, rev, order) _alg = Sort.defalg(df, ord; alg=alg, cols=cols) sort!(df, _alg, ord) end function Base.sort!(df::DataFrame, a::Base.Sort.Algorithm, o::Base.Sort.Ordering) p = sortperm(df, a, o) pp = similar(p) c = columns(df) for (i,col) in enumerate(c) # Check if this column has been sorted already if any(j -> c[j]===col, 1:i-1) continue end copy!(pp,p) Base.permute!!(col, pp) end df end
data = map(x->split(x, " -> "),split(strip(read(joinpath(@__DIR__, "./5.txt"), String)), '\n')) data = map(y->map(x->parse.(Int,split(x,",")),y),data) data = map(z->reduce(vcat,z),data) line_plot = zeros(Int,1000,1000) function points_on_line(x1,y1,x2,y2) if x1 > x2 x1, y1, x2, y2 = x2, y2, x1, y1 end slope = (y2-y1)/(x2-x1) y_intercept = y1-slope*x1 [(x,Int(x*slope+y_intercept)) for x in range(x1, x2) if Int(x*slope) == x*slope] end function plotline(x1,y1,x2,y2) global line_plot if x1 == x2 if y1 < y2 line_plot[x1,y1:y2] .+= 1 else line_plot[x1,y2:y1] .+= 1 end elseif y1 == y2 if x1 < x2 line_plot[x1:x2,y1] .+= 1 else line_plot[x2:x1,y1] .+= 1 end else # this is for part2 of the problem points = points_on_line(x2,y2,x1,y1) for (x,y) in points line_plot[x,y] += 1 end end end function solve(data) global line_plot for d in data plotline(d...) end length(filter(i->i>=2,line_plot)) end solve(data)
-- vim: set ft=idris sw=2 ts=2: -- -- fibonacci.idr -- Calculate Fibonacci numbers in the Idris programming language -- module Fibonacci -- Naive implementation export fib_naive : Int -> Int fib_naive 0 = 0 fib_naive 1 = 1 fib_naive n = fib_naive (n - 1) + fib_naive (n - 2) -- Tail-call friendly version export fib : Nat -> Nat fib n = fib_aux Z (S Z) n where fib_aux : Nat -> Nat -> Nat -> Nat fib_aux a b Z = a fib_aux a b (S n) = fib_aux b (plus a b) n
import Mathlib import SciLean.Mathlib.Algebra.Module.Basic class Symbolic {Repr : Type} (R : Repr → Repr → Prop) where RedForm : Repr → Prop NormForm : Repr → Prop norm_red : ∀ x, NormForm x → RedForm x R_norm : ∀ x y, R x y → NormForm x → NormForm y → x = y namespace Symbolic -- define Hom -- preserves relation -- define RedHom -- preserving RefForm -- define NormHom -- preserving RefForm -- define their Hom₂ variants section Hom variable {Repr Repr'} (R : Repr → Repr → Prop) [Symbolic R] (R' : Repr' → Repr' → Prop) [Symbolic R'] (f : Repr → Repr') structure Hom : Prop where is_hom : ∀ x y : Repr, R x y → R' (f x) (f y) structure RedHom : Prop where is_hom : ∀ x y : Repr, R x y → R' (f x) (f y) preserve_red : ∀ x : Repr, RedForm R x → RedForm R' (f x) structure NormHom : Prop where is_hom : ∀ x y : Repr, R x y → R' (f x) (f y) preserve_red : ∀ x : Repr, RedForm R x → RedForm R' (f x) preserve_norm : ∀ x : Repr, NormForm R x → NormForm R' (f x) end Hom structure SHom {Repr Repr'} (R : Repr → Repr → Prop) [Symbolic R] (R' : Repr' → Repr' → Prop) [Symbolic R'] (f : Repr → Repr') : Prop where is_hom : ∀ x y : Repr, R x y → R' (f x) (f y) preserve_red : ∀ x : Repr, RedForm R x → RedForm R' (f x) preserve_norm : ∀ x : Repr, NormForm R x → NormForm R' (f x) structure SHom₂ {Repr Repr' Repr''} (R : Repr → Repr → Prop) [Symbolic R] (R' : Repr' → Repr' → Prop) [Symbolic R'] (R'' : Repr'' → Repr'' → Prop) [Symbolic R''] (f : Repr → Repr' → Repr'') : Prop where is_hom₂ : ∀ (x y : Repr) (x' y' : Repr'), R x y → R' x' y' → R'' (f x x') (f y y') preserve_red : ∀ x x', RedForm R x → RedForm R' x' → RedForm R'' (f x x') preserve_norm : ∀ x x', NormForm R x → NormForm R' x' → NormForm R'' (f x x') class SReduce {Repr} (R : Repr → Repr → Prop) [Symbolic R] where reduce : Repr → Repr is_reduce : ∀ x, RedForm R (reduce x) R_reduce : ∀ x, R x (reduce x) reduce_of_norm : ∀ x, NormForm R x → NormForm R (reduce x) -- does not destroy norm form -- symbolic reduction on quotient will be identity class Reduce (X : Type u) where reduce : X → X id_reduce : ∀ x : X, reduce x = x class SNormalize {Repr} (R : Repr → Repr → Prop) [Symbolic R] where normalize : Repr → Repr is_normalize : ∀ x, NormForm R (normalize x) R_normalize : ∀ x, R x (normalize x) -- symbolic normalization on quotient will be identity class Normalize (X : Type u) where normalize : X → X id_normalize : ∀ x : X, normalize x = x -- This just tags `Repr` in which form they are inductive SRepr {Repr : Type} (R : Repr → Repr → Prop) [Symbolic R] where | raw (x : Repr) : SRepr R | red (x : Repr) (h : RedForm R x) : SRepr R | norm (x : Repr) (h : NormForm R x) : SRepr R namespace SRepr variable {Repr} {R : Repr → Repr → Prop} [Symbolic R] def repr (x : SRepr R) : Repr := match x with | raw x => x | red x _ => x | norm x _ => x -- instance : Coe (SRepr R) Repr := ⟨λ x => x.repr⟩ @[simp] theorem raw_repr (x : Repr) : (raw x : SRepr R).repr = x := by simp[repr] done @[simp] theorem red_repr (x : Repr) (h : RedForm R x) : (red x h : SRepr R).repr = x := by simp[repr] done @[simp] theorem norm_repr (x : Repr) (h : NormForm R x) : (norm x h : SRepr R).repr = x := by simp[repr] done def isReduced (x : SRepr R) : Bool := match x with | raw x => false | _ => true def isNormalized (x : SRepr R) : Bool := match x with | norm x _ => true | _ => false variable {Repr' } {R' : Repr' → Repr' → Prop} [Symbolic R'] variable {Repr''} {R'' : Repr'' → Repr'' → Prop} [Symbolic R''] def lift (f : Repr → Repr') (x : SRepr R) : SRepr R' := raw (f x.repr) def lift₂ (f : Repr → Repr' → Repr'') (x : SRepr R) (x' : SRepr R') : SRepr R'' := raw (f x.repr x'.repr) def liftHom (f : Repr → Repr') (h : SHom R R' f) (x : SRepr R) : SRepr R' := match x with | raw x => raw (f x) | red x h' => red (f x) (h.preserve_red x h') | norm x h' => norm (f x) (h.preserve_norm x h') @[simp] theorem lift_hom_repr (f : Repr → Repr') (h : SHom R R' f) (x : SRepr R) : (liftHom f h x).repr = f x.repr := by induction x repeat simp[liftHom] done def liftHom₂ (f : Repr → Repr' → Repr'') (h : SHom₂ R R' R'' f) (x : SRepr R) (y : SRepr R') : SRepr R'' := match x, y with | red x hx, red y hy => red (f x y) (h.preserve_red x y hx hy) | norm x hx, norm y hy => norm (f x y) (h.preserve_norm x y hx hy) | x, y => raw (f x.repr y.repr) def reduce (x : SRepr R) [SReduce R] : SRepr R := match x with | raw x => red (SReduce.reduce R x) (SReduce.is_reduce x) | x => x def normalize (x : SRepr R) [SNormalize R] : SRepr R := match x with | raw x => norm (SNormalize.normalize R x) (SNormalize.is_normalize x) | red x _ => norm (SNormalize.normalize R x) (SNormalize.is_normalize x) | x => x end SRepr def SQuot {Repr} (R : Repr → Repr → Prop) [Symbolic R] := Quot (λ x y : SRepr R => R x.repr y.repr) variable {Repr} {R : Repr → Repr → Prop} [Symbolic R] variable {Repr'} {R' : Repr' → Repr' → Prop} [Symbolic R'] variable {Repr''} {R'' : Repr'' → Repr'' → Prop} [Symbolic R''] -- Not sure about these two with the coercion from SRepr to Repr def SQuot.mk (x : SRepr R) : SQuot R := Quot.mk _ x def SQuot.rmk (x : Repr) : SQuot R := Quot.mk _ (SRepr.raw x) def SQuot.mkRed (x : Repr) (h : RedForm R x) : SQuot R := Quot.mk _ (SRepr.red x h) def SQuot.mkNorm (x : Repr) (h : NormForm R x) : SQuot R := Quot.mk _ (SRepr.norm x h) def SQuot.lift {α : Sort u} (f : Repr → α) (h : ∀ x x' : Repr, R x x' → f x = f x') : SQuot R → α := Quot.lift (λ x => f x.repr) (by intros a b induction a repeat( induction b repeat( simp[SRepr.repr] apply h))) def SQuot.slift {α : Sort u} (f : SRepr R → α) (h : ∀ x x' : SRepr R, R x.repr x'.repr → f x = f x') : SQuot R → α := Quot.lift (λ x => f x) h def SQuot.liftHom (f : Repr → Repr') (h : SHom R R' f) : SQuot R → SQuot R' := Quot.lift (λ x' => Quot.mk _ (SRepr.liftHom f h x')) (by intro a b req apply Quot.sound induction a repeat (induction b repeat (simp at req apply h.is_hom assumption)) done) def SQuot.lift₂ (f : Repr → Repr' → Repr'') (h : ∀ (x y : Repr) (x' y' : Repr'), R x y → R' x' y' → R'' (f x x') (f y y')) : SQuot R → SQuot R' → SQuot R'' := Quot.lift (λ x' => Quot.lift (λ y' => Quot.mk _ (SRepr.lift₂ f x' y')) sorry) sorry def SQuot.slift₂ (f : SRepr R → SRepr R' → SRepr R'') (h : ∀ (x y : SRepr R) (x' y' : SRepr R'), R x.repr y.repr → R' x'.repr y'.repr → R'' (f x x').repr (f y y').repr) : SQuot R → SQuot R' → SQuot R'' := Quot.lift (λ x' => Quot.lift (λ y' => Quot.mk _ (f x' y')) sorry) sorry def SQuot.liftHom₂ (f : Repr → Repr' → Repr'') (h : SHom₂ R R' R'' f) : SQuot R → SQuot R' → SQuot R'' := Quot.lift (λ x' => Quot.lift (λ y' => Quot.mk _ (SRepr.liftHom₂ f h x' y')) sorry) sorry instance [SReduce R] : Reduce (SQuot R) := { reduce := SQuot.slift (λ x => Quot.mk _ x.reduce) sorry id_reduce := sorry } instance [SNormalize R] : Normalize (SQuot R) := { normalize := SQuot.slift (λ x => Quot.mk _ x.normalize) sorry id_normalize := sorry } -- variable {Repr : Type} {RedForm : Repr → Prop} {NormForm : Repr → Prop} -- instance : Coe (Symbolic Repr RedForm NormForm) Repr := ⟨repr⟩ -- def isReduced (x : Symbolic Repr RedForm NormForm) : Bool := -- match x with -- | raw _ => false -- | _ => true -- def isNormalized (x : Symbolic Repr RedForm NormForm) : Bool := -- match x with -- | norm _ _ => true -- | _ => false -- -- Lift reduction preserving function `Repr → Repr'` to Symbolic -- def liftHom {Repr' : Type} {RedForm' NormForm' : Repr' → Prop} -- (f : Repr → Repr') -- (h : ∀ x : Repr, RedForm x → RedForm' (f x)) -- (h' : ∀ x : Repr, NormForm x → NormForm' (f x)) -- (x : Symbolic Repr RedForm NormForm) -- : Symbolic Repr' RedForm' NormForm' -- := -- match x with -- | raw x => raw (f x) -- | red x g => red (f x) (h x g) -- | norm x g => norm (f x) (h' x g) -- def Symb {Repr} (R : Repr → Repr → Prop) (RedForm NormForm : Repr → Prop) -- (h : ∀ x y : Repr, R x y → NormForm x → NormForm y → x = y) -- := Quot (λ x y : Symbolic Repr RedForm NormForm => R x y) -- variable {R : outParam $ Repr → Repr → Prop} -- {RedForm NormForm : outParam $ Repr → Prop} -- {H : outParam $ ∀ x y : Repr, R x y → NormForm x → NormForm y → x = y} -- def Symb.lift {α : Sort u} (f : Repr → α) (h : ∀ x y : Repr, R x y → f x = f y) -- (x : Symb R RedForm NormForm H) : α -- := Quot.lift (λ x => f x) (by intro a b; induction a; induction b; -- repeat (simp; apply h) -- done) x -- def Symb.liftSnd -- {α : Sort u} {β : Sort v} (f : β → Repr → α) (h : ∀ b (x y : Repr), R x y → f b x = f b y) (b : β) -- : Symb R RedForm NormForm H → α -- := Quot.lift (λ x => f b x) (by intro x y; induction x; induction y; -- repeat (simp; apply (h b)) -- done) -- def Symb.lift₂ {α : Sort u} (f : Repr → Repr → α) -- (h : ∀ x y y' : Repr, R y y' → f x y = f x y') -- (h' : ∀ (x x' : Repr), R x x' → liftSnd (RedForm := RedForm) (NormForm := NormForm) (H := H) f h x = liftSnd f h x') -- (x y : Symb R RedForm NormForm H) : α -- := lift (liftSnd f h) h' x y -- constant toString [ToString Repr] (x : Symb R RedForm NormForm H) : String -- := Symb.lift (λ r => toString r) sorry (x) -- -- `reduce` function should send representative to its reduced form -- class Reduce (X : Type) where -- reduce : X → X -- reduce_id : ∀ x, reduce x = x -- def lift_reduce (reduce : Repr → Repr) -- (h : ∀ x, RedForm (reduce x)) (h' : ∀ x, NormForm x → RedForm x) -- (x : Symbolic Repr RedForm NormForm) : (Symbolic Repr RedForm NormForm) -- := -- match x with -- | raw x => red (reduce x) (h x) -- | x => x -- -- `normalize` function should send representative to its normal form -- class Normalize (X : Type) where -- normalize : X → X -- normalize_id : ∀ x, normalize x = x -- def lift_normalize (normalize : Repr → Repr) -- (h : ∀ x, NormForm (normalize x)) -- (x : Symbolic Repr RedForm NormForm) : (Symbolic Repr RedForm NormForm) -- := -- match x with -- | raw x => norm (normalize x) (h x) -- | red x _ => norm (normalize x) (h x) -- | x => x end Symbolic inductive List.Sorted {X : Type u} [LE X] : List X → Prop where | empty : Sorted [] | singl (x : X) : Sorted [x] | head (x y : X) (ys : List X) (h : x ≤ y) (h' : Sorted (y :: ys)) : Sorted (x :: y :: ys) inductive List.StrictlySorted {X : Type u} [LT X] : List X → Prop where | empty : StrictlySorted [] | singl (x : X) : StrictlySorted [x] | head (x y : X) (ys : List X) (h : x < y) (h' : StrictlySorted (y :: ys)) : StrictlySorted (x :: y :: ys) structure FreeMonoid (X : Type u) where vars : List X namespace FreeMonoid instance {X} : Mul (FreeMonoid X) := ⟨λ x y => ⟨x.1.append y.1⟩⟩ instance {X} : One (FreeMonoid X) := ⟨⟨[]⟩⟩ def rank {X} (x : FreeMonoid X) : Nat := x.1.length inductive SymmMonoidEq {X} : FreeMonoid X → FreeMonoid X → Prop where | mul_comm (x y : FreeMonoid X) : SymmMonoidEq (x*y) (y*x) end FreeMonoid namespace Monomial structure Repr (X : Type u) (K : Type v) where coef : K base : FreeMonoid X instance {X K} [Mul K] : Mul (Repr X K) := ⟨λ x y => ⟨x.coef * y.coef, x.base * y.base⟩⟩ instance {X K} [Mul K] : HMul K (Repr X K) (Repr X K) := ⟨λ a x => ⟨a * x.coef, x.base⟩⟩ def Repr.rank {X K} (x : Repr X K) : Nat := x.base.rank inductive SymMonomialEq {X K : Type} [One K] [Neg K] [Mul K] [HPow K Nat K] : Repr X K → Repr X K → Prop where | refl (x : Repr X K) : SymMonomialEq x x | mul_comm (x y : Repr X K) : SymMonomialEq (x * y) (y * x) inductive AltMonomialEq {X K : Type} [One K] [Neg K] [Mul K] [HPow K Nat K] : Repr X K → Repr X K → Prop where | refl (x : Repr X K) : AltMonomialEq x x | mul_alt (x y : Repr X K) : AltMonomialEq (x * y) ((-1 : K)^(x.rank + y.rank) * y * x) instance {X K} [LT X] [CommRing K] : Symbolic (SymMonomialEq (X := X) (K := K)) := { RedForm := λ x => x.base.1.StrictlySorted NormForm := λ x => (x.base.1.StrictlySorted) ∧ (x.coef = 0 → x.base.1 = []) norm_red := λ x h => h.left R_norm := sorry -- this is probably hard as I need CommRing for it } instance {X K} [LT X] [CommRing K] : Symbolic (AltMonomialEq (X := X) (K := K)) := { RedForm := λ x => x.base.1.StrictlySorted NormForm := λ x => (x.base.1.StrictlySorted) ∧ (x.coef = 0 → x.base.1 = []) norm_red := λ x h => h.left R_norm := sorry -- this is probably hard as I need CommRing for it } end Monomial open Symbolic Monomial in def SymMonomial (X K) [LT X] [CommRing K] := SQuot (SymMonomialEq (X := X) (K := K)) open Symbolic Monomial in def AltMonomial (X K) [LT X] [CommRing K] := SQuot (AltMonomialEq (X := X) (K := K)) inductive DecComparison {X : Type u} [LT X] (x y : X) where | cpEq (h : x = y) : DecComparison x y | cpLt (h : x < y) : DecComparison x y | cpGt (h : x > y) : DecComparison x y export DecComparison (cpEq cpLt cpGt) class DecCompar (X : Type u) [LT X] where compare (x y : X) : DecComparison x y abbrev compare {X} [LT X] [DecCompar X] (x y : X) : DecComparison x y := DecCompar.compare x y namespace AltMonomial open Symbolic variable {X K} [LT X] [DecCompar X] [CommRing K] instance [DecCompar X] : Reduce (AltMonomial X K) := { reduce := sorry id_reduce := sorry } instance [DecCompar X] [DecidableEq K] : Normalize (AltMonomial X K) := { normalize := sorry id_normalize := sorry } -- TODO: change these definitions -- add reduction instance : Mul (AltMonomial X K) := ⟨λ x' y' => (SQuot.lift₂ (λ x y => (x * y)) sorry) x' y' |> Reduce.reduce⟩ instance [Mul K] : HMul K (AltMonomial X K) (AltMonomial X K) := ⟨λ c => SQuot.lift (λ x => SQuot.rmk (c * x)) sorry⟩ instance : One (AltMonomial X K) := ⟨SQuot.mkNorm ⟨1,1⟩ sorry⟩ instance : Zero (AltMonomial X K) := ⟨SQuot.mkNorm ⟨0,1⟩ sorry⟩ instance : Monoid (AltMonomial X K) := { mul_assoc := sorry mul_one := sorry one_mul := sorry npow_zero' := sorry npow_succ' := sorry } instance : MulAction K (AltMonomial X K) := { one_smul := sorry mul_smul := sorry } end AltMonomial
############################################################################# ## ## Functions.gi JConvex package ## Martin Bies ## ## Copyright 2021 University of Pennsylvania ## ## A Gap package to do convex geometry by Polymake ## ## Chapter: Polytopes ## ############################################################################# #################################### ## ## Attributes of polyopes ## #################################### InstallMethod( ExternalPolymakePolytope, "for polyopes", [ IsPolytope ], function( poly ) if IsBound( poly!.input_points ) then return Polymake_PolytopeByGenerators( poly!.input_points ); fi; # otherwise our fallback is poly from inequalities return Polymake_PolytopeFromInequalities( poly!.input_ineqs ); end ); InstallMethod( VerticesOfPolytope, "for polyopes", [ IsPolytope ], function( poly ) return Set( Polymake_V_Rep( ExternalPolymakePolytope( poly ) )!.vertices ); end ); InstallMethod( DefiningInequalities, "for polyopes", [ IsPolytope ], function( poly ) local ineqs, eqs; ineqs := Polymake_Inequalities( ExternalPolymakePolytope( poly ) ); eqs := Polymake_Equalities( ExternalPolymakePolytope( poly ) ); return Set( Concatenation( eqs, (-1) * eqs, ineqs ) ); end ); InstallMethod( FacetInequalities, " for external polyopes", [ IsExternalPolytopeRep ], function( poly ) return Polymake_Inequalities( ExternalPolymakePolytope( poly ) ); end ); InstallMethod( IsBounded, " for external polyopes.", [ IsPolytope ], function( poly ) return Polymake_IsBounded( ExternalPolymakePolytope( poly ) ); end ); InstallMethod( LatticePoints, [ IsPolytope ], function( poly ) return Polymake_LatticePoints( ExternalPolymakePolytope( poly ) ); end ); InstallMethod( Dimension, [ IsPolytope ], function( poly ) return Polymake_Dimension( ExternalPolymakePolytope( poly ) ); end ); InstallMethod( IntersectionOfPolytopes, [ IsPolytope, IsPolytope ], function( poly1, poly2 ) local poly, ext_polytope; if not Rank( ContainingGrid( poly1 ) ) = Rank( ContainingGrid( poly2 ) ) then Error( "polytopes are not of the same dimension" ); fi; # compute the intersection ext_polytope:= Polymake_Intersection( ExternalPolymakePolytope( poly1 ), ExternalPolymakePolytope( poly2 ) ); # find the generating vertices of this new polytope and construct the polytope # currently, this ignores the lineality space Polymake_Linealities( ext_polytope ) completely! poly := Polytope( Polymake_Vertices( ext_polytope ) ); # set properties SetExternalPolymakePolytope( poly, ext_polytope ); SetContainingGrid( poly, ContainingGrid( poly1 ) ); SetAmbientSpaceDimension( poly, AmbientSpaceDimension( poly1 ) ); # return the result return poly; end );
Men who worked for farmers or psychiatric hospitals received regular wages , which they were required to give to the federal government . Objections to this practice developed immediately because the men felt they were helping to fund the war . A compromise was reached where the wages were put into a special fund that was unused until after the end of the war . At one point , church representatives attempted unsuccessfully to have these funds used for providing a living allowance for the men 's dependents .
lemma numeral_monom: "numeral n = monom (numeral n) 0"
[STATEMENT] lemma real_ereal_id: "real_of_ereal \<circ> ereal = id" [PROOF STATE] proof (prove) goal (1 subgoal): 1. real_of_ereal \<circ> ereal = id [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. real_of_ereal \<circ> ereal = id [PROOF STEP] { [PROOF STATE] proof (state) goal (1 subgoal): 1. real_of_ereal \<circ> ereal = id [PROOF STEP] fix x [PROOF STATE] proof (state) goal (1 subgoal): 1. real_of_ereal \<circ> ereal = id [PROOF STEP] have "(real_of_ereal \<circ> ereal) x = id x" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (real_of_ereal \<circ> ereal) x = id x [PROOF STEP] by auto [PROOF STATE] proof (state) this: (real_of_ereal \<circ> ereal) x = id x goal (1 subgoal): 1. real_of_ereal \<circ> ereal = id [PROOF STEP] } [PROOF STATE] proof (state) this: (real_of_ereal \<circ> ereal) ?x2 = id ?x2 goal (1 subgoal): 1. real_of_ereal \<circ> ereal = id [PROOF STEP] then [PROOF STATE] proof (chain) picking this: (real_of_ereal \<circ> ereal) ?x2 = id ?x2 [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: (real_of_ereal \<circ> ereal) ?x2 = id ?x2 goal (1 subgoal): 1. real_of_ereal \<circ> ereal = id [PROOF STEP] using ext [PROOF STATE] proof (prove) using this: (real_of_ereal \<circ> ereal) ?x2 = id ?x2 (\<And>x. ?f x = ?g x) \<Longrightarrow> ?f = ?g goal (1 subgoal): 1. real_of_ereal \<circ> ereal = id [PROOF STEP] by blast [PROOF STATE] proof (state) this: real_of_ereal \<circ> ereal = id goal: No subgoals! [PROOF STEP] qed
-- Caracterizacion_de_maximo_comun_divisor_igual_al_primer_numero.lean -- Caracterización de máximo común divisor igual al primer número. -- José A. Alonso Jiménez -- Sevilla, 25 de agosto de 2020 -- --------------------------------------------------------------------- -- --------------------------------------------------------------------- -- Ejercicio. Demostrar que si a y b son números naturales, entonces -- a ∣ b ↔ gcd a b = a -- ---------------------------------------------------------------------- import data.nat.gcd open nat variables (a b : ℕ) -- 1ª demostración -- =============== example : a ∣ b ↔ gcd a b = a := begin have h1 : gcd a b ∣ a ∧ gcd a b ∣ b, { exact gcd_dvd a b, }, split, { intro h2, apply dvd_antisymm h1.left, rw dvd_gcd_iff, exact ⟨dvd_refl a, h2⟩, }, { intro h3, rw ← h3, exact h1.right, }, end -- Comentarios: -- + La orden (open nat) abre el es espacio de nombre de los naturales. -- + La relación (a ∣ b) se verifica si a divide a b. -- + (gcd a b) es el máximo común divisor de a y b. -- + Si h es la conjunción (P ∧ Q), entonces h.letf es P y h.right es -- Q. -- + Se han usado los lemas -- + dvd_refl : a ∣ a -- + dvd_antisymm : a ∣ b → b ∣ a → a = b -- + dvd_gcd_iff : c ∣ gcd a b ↔ c ∣ a ∧ c ∣ b -- + gcd_dvd : gcd a b ∣ a ∧ gcd a b ∣ b -- 2ª demostración -- =============== example : a ∣ b ↔ gcd a b = a := gcd_eq_left_iff_dvd -- Comentario: Se ha usado el lema -- + gcd_eq_left_iff_dvd : a ∣ b ↔ gcd a b = a
[STATEMENT] lemma continuous_on_e2ennreal: "continuous_on A e2ennreal" [PROOF STATE] proof (prove) goal (1 subgoal): 1. continuous_on A e2ennreal [PROOF STEP] proof (rule continuous_on_subset) [PROOF STATE] proof (state) goal (2 subgoals): 1. continuous_on ?s e2ennreal 2. A \<subseteq> ?s [PROOF STEP] show "continuous_on ({0..} \<union> {..0}) e2ennreal" [PROOF STATE] proof (prove) goal (1 subgoal): 1. continuous_on ({0..} \<union> {..0}) e2ennreal [PROOF STEP] proof (rule continuous_on_closed_Un) [PROOF STATE] proof (state) goal (4 subgoals): 1. closed {0..} 2. closed {..0} 3. continuous_on {0..} e2ennreal 4. continuous_on {..0} e2ennreal [PROOF STEP] show "continuous_on {0 ..} e2ennreal" [PROOF STATE] proof (prove) goal (1 subgoal): 1. continuous_on {0..} e2ennreal [PROOF STEP] by (rule continuous_onI_mono) (auto simp add: less_eq_ennreal.abs_eq eq_onp_def enn2ereal_range) [PROOF STATE] proof (state) this: continuous_on {0..} e2ennreal goal (3 subgoals): 1. closed {0..} 2. closed {..0} 3. continuous_on {..0} e2ennreal [PROOF STEP] show "continuous_on {.. 0} e2ennreal" [PROOF STATE] proof (prove) goal (1 subgoal): 1. continuous_on {..0} e2ennreal [PROOF STEP] by (subst continuous_on_cong[OF refl, of _ _ "\<lambda>_. 0"]) (auto simp add: e2ennreal_neg continuous_on_const) [PROOF STATE] proof (state) this: continuous_on {..0} e2ennreal goal (2 subgoals): 1. closed {0..} 2. closed {..0} [PROOF STEP] qed auto [PROOF STATE] proof (state) this: continuous_on ({0..} \<union> {..0}) e2ennreal goal (1 subgoal): 1. A \<subseteq> {0..} \<union> {..0} [PROOF STEP] show "A \<subseteq> {0..} \<union> {..0::ereal}" [PROOF STATE] proof (prove) goal (1 subgoal): 1. A \<subseteq> {0..} \<union> {..0} [PROOF STEP] by auto [PROOF STATE] proof (state) this: A \<subseteq> {0..} \<union> {..0} goal: No subgoals! [PROOF STEP] qed
------------------------------------------------------------------------------ -- Testing the translation of logical schemata with 11-ary predicates symbols ------------------------------------------------------------------------------ {-# OPTIONS --exact-split #-} {-# OPTIONS --no-sized-types #-} {-# OPTIONS --no-universe-polymorphism #-} {-# OPTIONS --without-K #-} module P11 where postulate D : Set P-refl : {P : D → D → D → D → D → D → D → D → D → D → D → Set} → ∀ {x₁ x₂ x₃ x₄ x₅ x₆ x₇ x₈ x₉ x₁₀ x₁₁} → P x₁ x₂ x₃ x₄ x₅ x₆ x₇ x₈ x₉ x₁₀ x₁₁ → P x₁ x₂ x₃ x₄ x₅ x₆ x₇ x₈ x₉ x₁₀ x₁₁ {-# ATP prove P-refl #-}