Datasets:
AI4M
/

text
stringlengths
0
3.34M
(** Calculation of an abstract machine for the call-by-value lambda calculus. The resulting abstract machine coincides with the CEK machine. *) Require Import List. Require Import ListIndex. Require Import Tactics. (** * Syntax *) Inductive Expr : Set := | Var : nat -> Expr | Abs : Expr -> Expr | App : Expr -> Expr -> Expr. (** * Semantics *) (** The evaluator for this language is given as follows: << type Env = [Value] data Value = Fun (Value -> Value) eval :: Expr -> Env -> Value eval (Var i) e = e !! i eval (Abs x) e = Fun (\v -> eval x (v:e)) eval (App x y) e = case eval x e of Fun f -> f (eval y e) >> After defunctionalisation and translation into relational form we obtain the semantics below. *) Inductive Value : Set := | Clo : Expr -> list Value -> Value. Definition Env := list Value. Reserved Notation "x ⇓[ e ] y" (at level 80, no associativity). Inductive eval : Expr -> Env -> Value -> Prop := | eval_var e i v : nth e i = Some v -> Var i ⇓[e] v | eval_abs e x : Abs x ⇓[e] Clo x e | eval_app e e' x x' w y v : x ⇓[e] Clo x' e' -> y ⇓[e] v -> x' ⇓[v :: e'] w -> App x y ⇓[e] w where "x ⇓[ e ] y" := (eval x e y). (** * Abstract machine *) Inductive CONT : Set := | FUN : Expr -> Env -> CONT -> CONT | ARG : Expr -> Env -> CONT -> CONT | HALT : CONT . Inductive Conf : Set := | eval'' : Expr -> Env -> CONT -> Conf | apply : CONT -> Value -> Conf. Notation "⟨ x , e , c ⟩" := (eval'' x e c). Notation "⟪ c , v ⟫" := (apply c v). Reserved Notation "x ==> y" (at level 80, no associativity). Inductive AM : Conf -> Conf -> Prop := | am_var i e c v : nth e i = Some v -> ⟨Var i, e, c⟩ ==> ⟪c, v⟫ | am_abs x e c : ⟨Abs x, e, c⟩ ==> ⟪c, Clo x e⟫ | am_app x y e c : ⟨App x y, e, c⟩ ==> ⟨x, e, ARG y e c⟩ | am_FUN x' e' c v : ⟪FUN x' e' c, v⟫ ==> ⟨x', v::e', c⟩ | am_ARG y e c x' e' : ⟪ARG y e c, Clo x' e'⟫ ==> ⟨y, e, FUN x' e' c⟩ where "x ==> y" := (AM x y). (** * Calculation *) (** Boilerplate to import calculation tactics *) Module AM <: Preorder. Definition Conf := Conf. Definition VM := AM. End AM. Module AMCalc := Calculation AM. Import AMCalc. (** Specification of the abstract machine *) Theorem spec x e r c : x ⇓[e] r -> ⟨x, e, c⟩ =>> ⟪c, r⟫. (** Setup the induction proof *) Proof. intros. generalize dependent c. induction H;intros. (** Calculation of the abstract machine *) (** - [Var i ⇓[e] v] *) begin ⟪c, v ⟫. <== {apply am_var} ⟨Var i, e, c ⟩. []. (** - [Abs x ⇓[e] Clo x e] *) begin ⟪c, Clo x e⟫. <== { apply am_abs } ⟨Abs x, e, c⟩. []. (** - [App x y ⇓[e] w] *) begin ⟪c, w⟫. <<= { apply IHeval3 } ⟨x', (v::e'), c⟩. <== { apply am_FUN } ⟪FUN x' e' c, v⟫. <<= {apply IHeval2} ⟨y, e, FUN x' e' c⟩. <== {apply am_ARG} ⟪ARG y e c, Clo x' e'⟫. <<= {apply IHeval1} ⟨x, e, ARG y e c⟩. <== {apply am_app} ⟨App x y, e, c⟩. []. Qed. (** * Soundness *) Lemma determ_am : determ AM. intros C c1 c2 V. induction V; intro V'; inversion V'; subst; congruence. Qed. Definition terminates (p : Expr) : Prop := exists r, p ⇓[nil] r. Theorem sound x C : terminates x -> ⟨x, nil, HALT⟩ =>>! C -> exists r, C = ⟪HALT, r⟫ /\ x ⇓[nil] r. Proof. unfold terminates. intros. destruct H as [r T]. pose (spec x nil r HALT) as H'. exists r. split. pose (determ_trc determ_am) as D. unfold determ in D. eapply D. eassumption. split. eauto. intro. destruct H. inversion H. assumption. Qed.
[STATEMENT] lemma [simp]: "v < length astDom \<Longrightarrow> (abs_ast_initial_state v) = Some (astI ! v)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. v < length astDom \<Longrightarrow> abs_ast_initial_state v = Some (astI ! v) [PROOF STEP] using wf_initial(1)[simplified numVars_def, symmetric] [PROOF STATE] proof (prove) using this: length astDom = length astI goal (1 subgoal): 1. v < length astDom \<Longrightarrow> abs_ast_initial_state v = Some (astI ! v) [PROOF STEP] by (auto simp add: map_of_zip_Some abs_ast_initial_state_def split: prod.splits)
import Data.Vect my_plusCommutes : (n : Nat) -> (m : Nat) -> n + m = m + n my_plusCommutes Z m = rewrite plusZeroRightNeutral m in Refl my_plusCommutes (S k) m = rewrite my_plusCommutes k m in rewrite plusSuccRightSucc m k in Refl my_reverse : Vect n elem -> Vect n elem my_reverse [] = [] my_reverse (x :: xs) = reverseProof (my_reverse xs ++ [x]) where reverseProof : Vect (plus k 1) elem -> Vect (S k) elem reverseProof {k} result = rewrite my_plusCommutes 1 k in result my_reverse' : Vect n elem -> Vect n elem my_reverse' xs = reverse' [] xs where reverseProof_nil : Vect n1 a -> Vect (plus n1 0) a reverseProof_nil {n1} acc = rewrite plusZeroRightNeutral n1 in acc reverseProof_xs : Vect ((S n) + k) a -> Vect (plus n (S k)) a reverseProof_xs {n} {k} xs = rewrite sym (plusSuccRightSucc n k) in xs reverse' : Vect n a -> Vect m a -> Vect (n + m) a reverse' acc [] = reverseProof_nil acc reverse' acc (x::xs) = reverseProof_xs (reverse' (x::acc) xs)
Require Import List. Notation "[]" := nil. Notation "[ a ]" := (cons a nil). Notation "[ x , .. , y ]" := (cons x .. (cons y nil) ..). Infix "::" := cons. Require Import Arith. Infix "===" := eq_nat_dec (at level 50). Inductive term : Set := | var : nat -> term | Pi : term -> term -> term | abs : term -> term -> term | app : term -> term -> term | star : term | box : term. Coercion var : nat >-> term. Fixpoint open_rec (k:nat) (t:term) (u:term) : term := match t with | var n => match (k === n) with | left Hr => u | right Hr => t end | Pi A B => Pi (open_rec k A u) (open_rec (S k) B u) | abs A B => abs (open_rec k A u) (open_rec (S k) B u) | app A B => app (open_rec k A u) (open_rec k B u) | star => star | box => box end. Definition open := open_rec 0. Inductive beta_eq : term -> term -> Prop := | beta_eq_base : forall A B C, beta_eq (app (abs A B) C) (open B C) | beta_eq_refl : forall A, beta_eq A A | beta_eq_sym : forall A B, beta_eq A B -> beta_eq B A | beta_eq_trans : forall A B C, beta_eq A B -> beta_eq B C -> beta_eq A C. Infix "=b=" := beta_eq (at level 50). Inductive cube : term -> term -> Prop := | cube_s_s : cube star star | cube_b_b : cube box box | cube_s_b : cube box star. Infix "~>" := cube (at level 50). Fixpoint reduce (t:term) : term := match t with | var n => var n | Pi A B => Pi A B | abs A B => abs A B | app (abs A B) C => (open B C) | app A B => app (reduce A) B | star => star | box => box end. Definition context := list (nat * term). Reserved Notation "G |- x ;; T" (at level 55). Inductive turnstile : context -> term -> term -> Set := | star_intro : [] |- star ;; box | var_intro : forall x T G, In (x,T) G -> G |- x ;; T | app_intro : forall f a A A' B G, G |- f ;; (Pi A B) -> G |- a ;; A' -> A =b= A' -> G |- (app f a) ;; (open B a) | lam_intro : forall x b A B G t, ([(x,A)] ++ G) |- b ;; B -> G |- (Pi A B) ;; t -> G |- (abs A b) ;; (Pi A B) | pi_intro : forall x A B t s, G |- A ;; s -> ([(x,A)] ++ G) |- B ;; t -> s ~> t -> G |- (Pi A B) ;; t where "G |- x ;; T" := (turnstile G x T). Definition varin (n:nat) (c:context) : {t | In (n,t) c} + {forall t, ~ In (n,t) c}. Proof. intros. induction c. (*nil*) right ; intros ; simpl ; auto. (*cons*) destruct a. simpl. case_eq (n0 === n). (* n0 = n *) intros e He. rewrite e in *. left. exists t. auto. (* n0 <> n *) intros ne Hne. case_eq IHc. (* In next *) intros e He. left. inversion e. exists x. auto. (* not In next *) intros Hni Hnew. right. intros. unfold not. intros. inversion H. (* left *) inversion H0. congruence. (* right *) unfold not in * ; eapply Hni. eauto. Defined. Infix "@" := varin (at level 55).
State Before: 𝕂 : Type u_2 𝔸 : Type u_1 inst✝³ : NontriviallyNormedField 𝕂 inst✝² : NormedDivisionRing 𝔸 inst✝¹ : NormedAlgebra 𝕂 𝔸 inst✝ : CompleteSpace 𝔸 x : 𝔸 hx : x ∈ EMetric.ball 0 (FormalMultilinearSeries.radius (expSeries 𝕂 𝔸)) ⊢ HasSum (fun n => x ^ n / ↑n !) (exp 𝕂 x) State After: 𝕂 : Type u_2 𝔸 : Type u_1 inst✝³ : NontriviallyNormedField 𝕂 inst✝² : NormedDivisionRing 𝔸 inst✝¹ : NormedAlgebra 𝕂 𝔸 inst✝ : CompleteSpace 𝔸 x : 𝔸 hx : x ∈ EMetric.ball 0 (FormalMultilinearSeries.radius (expSeries 𝕂 𝔸)) ⊢ HasSum (fun n => ↑(expSeries 𝕂 𝔸 n) fun x_1 => x) (exp 𝕂 x) Tactic: rw [← expSeries_apply_eq_div' (𝕂 := 𝕂) x] State Before: 𝕂 : Type u_2 𝔸 : Type u_1 inst✝³ : NontriviallyNormedField 𝕂 inst✝² : NormedDivisionRing 𝔸 inst✝¹ : NormedAlgebra 𝕂 𝔸 inst✝ : CompleteSpace 𝔸 x : 𝔸 hx : x ∈ EMetric.ball 0 (FormalMultilinearSeries.radius (expSeries 𝕂 𝔸)) ⊢ HasSum (fun n => ↑(expSeries 𝕂 𝔸 n) fun x_1 => x) (exp 𝕂 x) State After: no goals Tactic: exact expSeries_hasSum_exp_of_mem_ball x hx
||| Properties of Ackermann functions module Data.Nat.Ack %default total -- Primitive recursive functions are functions that can be calculated -- by programs that don't use unbounded loops. Almost all common -- mathematical functions are primitive recursive. -- Uncomputable functions are functions that can't be calculated by -- any programs at all. One example is the Busy Beaver function: -- BB(k) = the maximum number of steps that can be executed by a -- halting Turing machine with k states. -- The values of the Busy Beaver function are unimaginably large for -- any but the smallest inputs. -- The Ackermann function is the most well-known example of a total -- computable function that is not primitive recursive, i.e. a general -- recursive function. It grows strictly faster than any primitive -- recursive function, but also strictly slower than a function like -- the Busy Beaver. -- There are many variations of the Ackermann function. Here is one -- common definition -- (see https://sites.google.com/site/pointlesslargenumberstuff/home/2/ackermann) -- that uses nested recursion: ackRec : Nat -> Nat -> Nat -- Base rule ackRec Z m = S m -- Prime rule ackRec (S k) Z = ackRec k 1 -- Catastrophic rule ackRec (S k) (S j) = ackRec k $ ackRec (S k) j -- The so-called "base rule" and "prime rule" work together to ensure -- termination. Happily, the Idris totality checker has no issues. -- An unusual "repeating" defintion of the function is given in the -- book The Little Typer: ackRep : Nat -> Nat -> Nat ackRep Z = (+) 1 ackRep (S k) = repeat (ackRep k) where repeat : (Nat -> Nat) -> Nat -> Nat repeat f Z = f 1 repeat f (S k) = f (repeat f k) -- These two definitions don't look like they define the same -- function, but they do: ackRepRec : (n, m : Nat) -> ackRep n m = ackRec n m ackRepRec Z _ = Refl ackRepRec (S k) Z = ackRepRec k 1 ackRepRec (S k) (S j) = rewrite sym $ ackRepRec (S k) j in ackRepRec k $ ackRep (S k) j
JSR Corporation and its subsidiaries (“JSR Group”) consider the protection for personal information (hereafter inclusive of specific personal information) under the advanced information-telecommunication society to be of the utmost importance, and in order to comply with the Act on the Protection of Personal Information in Japan (Act No. 57 of May 30, 2003) and other laws, regulations and guidelines related to the protection of personal information, will make efforts to observe the following policy for protection of all personal information. JSR Group will clarify the purpose of use and will acquire personal information to the extent necessary to achieve the purpose, in 2 below by legitimate and fair means. JSR Group will acquire personal information for the following purpose and will use the personal information, based on consent of the data subject or where the use is necessary for the performance of a contract. Except as otherwise provided under the following cases, JSR Group will not disclose or provide personal information to any third party. -1. JSR Group will make efforts to treat personal information appropriately in the day-to-day business by means of forming the organization/framework for the appropriate control of personal information, keeping every officer/employee informed about this Policy and implementing this Policy. -2. JSR Group set up a personal information protection management officer who controls protection and management of personal information and JSR Group clarifies the role. -3. JSR Group will take necessary and appropriate measures for security of personal information against illegal access and/or computer viruses in order to prevent personal information from any damage, loss, destruction, falsification and divulgation. -4. When JSR Group entrust a certain subcontractor to handle personal information, JSR Group will strictly control and supervise such subcontractor. When a data subject requests JSR Group to disclose, correct, disuse or erase its personal information retained by JSR Group, or lodges complaints with JSR Group, JSR Group will appropriately respond to such requests and complaints in accordance with applicable laws/regulations and procedures set out by JSR Group. Also, regarding the using of personal information, a data subject can lodge complaints with the Personal Information Protection Committee and other supervisory authorities.
function disp(F) %DISP Display a SPHEREFUNV. % % See also SPHEREFUNV/DISPLAY. % Copyright 2017 by The University of Oxford and The Chebfun Developers. % See http://www.chebfun.org/ for Chebfun information. loose = strcmp(get(0,'FormatSpacing'),'loose'); % Compact version: if ( isempty(F) ) fprintf('empty spherefunv\n\n') return end if ( F.isTransposed ) tString = 'Row vector'; else tString = 'Column vector'; end disp([' spherefunv object ' '(' tString ') containing' ]) if ( loose ) fprintf('\n'); end % Display its two SPHERFUN halves. for j = 1:3 disp( F.components{j} ); end end
module Drv { enum SendStatus { SEND_OK = 0 @< Send worked as expected SEND_RETRY = 1 @< Data send should be retried SEND_ERROR = 2 @< Send error occurred retrying may succeed } port ByteStreamSend( ref sendBuffer: Fw.Buffer ) -> SendStatus enum RecvStatus { RECV_OK = 0 @< Receive worked as expected RECV_ERROR = 1 @< Receive error occurred retrying may succeed } port ByteStreamRecv( ref recvBuffer: Fw.Buffer recvStatus: RecvStatus ) enum PollStatus { POLL_OK = 0 @< Poll successfully received data POLL_RETRY = 1 @< No data available, retry later POLL_ERROR = 2 @< Error received when polling } port ByteStreamPoll( ref pollBuffer: Fw.Buffer ) -> PollStatus port ByteStreamReady() passive component ByteStreamDriverModel { output port ready: Drv.ByteStreamReady output port $recv: Drv.ByteStreamRecv guarded input port send: Drv.ByteStreamSend guarded input port poll: Drv.ByteStreamPoll output port allocate: Fw.BufferGet output port deallocate: Fw.BufferSend } }
# https://juliamolsim.github.io/DFTK.jl/stable/guide/tutorial/ using ASEPotential using DFTK using Unitful using UnitfulAtomic lattice = austrip(5.431u"Å") / 2 * [[0 1 1.]; [1 0 1.]; [1 1 0.]] Si = ElementCoulomb(:Si) dftk_atoms = [Si => [ones(3)/8, -ones(3)/8]] atoms = ase_atoms(lattice, dftk_atoms) parameters = DFTKCalculatorParameters( ecut=7u"hartree", kpts=[4,4,4], scftol=1e-8 ) @time println(get_potential_energy(atoms, parameters)) @time println(get_forces(atoms, parameters))
function [w,s]=fram2wav(x,tt,mode) %FRAM2WAV converts frame values to a continuous waveform [W]=(X,TT,MODE) % Inputs: % x(nf,p) is the input signal: one row per frame % tt(nf,3) specifies the frames. Each row has the form [start_sample end_sample flag] % where flag = 1 for the start of a new spurt. % If tt(:,3) is omitted, a new spurt will be started whenever there is a gap % of more than one between the end of one frame and the beginning or the next. % A new spurt is automatically started if x() = NaN. % mode consists of one or more of the following letters: % z for zero-order hold interpolation (i.e. constant within each frame) % l for linear interpolation within each spurt [default] % % Outputs: % w(n,p) contains the interpolated waveforms. Their length is n = tt(nf,2) % s(ns,2) gives the starting and ending sample numbers of each spurt (excluding NaN spurts) % % This routine converts frame-based values to continuous waveforms by performing % a chosen method of interpolation. Interpolation is restarted at the beginning of each spurt. % Bugs/Suggestions % (1) Additional mode option for cubic interpolation % (2) Additional mode option for interpolation in log domain % (3) Additional mode option for x values being % frame averages rather than mid-frame values. % Copyright (C) Mike Brookes 1997 % Version: $Id: fram2wav.m,v 1.4 2007/05/04 07:01:38 dmb Exp $ % % VOICEBOX is a MATLAB toolbox for speech processing. % Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You can obtain a copy of the GNU General Public License from % http://www.gnu.org/copyleft/gpl.html or by writing to % Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if nargin<3 mode='l'; end [nf,m]=size(x); n=round(tt(end,2)); w=repmat(NaN,n,m); nt=size(tt,2); ix1=ceil(tt(:,1)); % start of frame sample ix2=floor(tt(:,2)); % end of frame sample % determine the start and end of spurts if nt>2 ty=tt(:,3)>0; % frame type set by user else ty=zeros(nf,1); ty(2:end)=ix1(2:end)>ix2(1:end-1)+1; % new spurt whenever a gap end ty(1)=1; % first frame always starts a spurt ty(isnan(x))=1; % NaN always ends previous spurt ty(1+find(isnan(x(1:end-1))))=1; % NaN always forces a new spurt ty=double(ty); ty(1:end-1)=ty(1:end-1)+2*ty(2:end); ty(end)=ty(end)+2; % last frame always ends a spurtw=repmat(NaN,n,m); % initialize output to all NaN nx=ix2-ix1+1; if any(mode=='z') % zero-order hold for i=1:nf if nx(i) w(ix1(i):ix2(i),:)=repmat(x(i,:),nx(i),1); end end else % linear interpolation is the default ttm=(tt(:,1)+tt(:,2))/2; % mid point of frame ixm=floor(ttm); % end of first half of frame for i=1:nf if i==176 i end if nx(i) tyi=ty(i); if tyi==3 % use a zero order hold w(ix1(i):ix2(i),:)=repmat(x(i,:),nx(i),1); else nxm=ixm(i)-ix1(i)+1; if nxm if tyi==1 grad=(x(i+1,:)-x(i,:))/(ttm(i+1)-ttm(i)); else grad=(x(i,:)-x(i-1,:))/(ttm(i)-ttm(i-1)); end w(ix1(i):ixm(i),:)=repmat(x(i,:),nxm,1)+((ix1(i):ixm(i))'-ttm(i))*grad; end if nx(i)>nxm if tyi==2 grad=(x(i,:)-x(i-1,:))/(ttm(i)-ttm(i-1)); else grad=(x(i+1,:)-x(i,:))/(ttm(i+1)-ttm(i)); end w(ixm(i)+1:ix2(i),:)=repmat(x(i,:),ix2(i)-ixm(i),1)+((ixm(i)+1:ix2(i))'-ttm(i))*grad; end end end end end % now sort out the start and end spurt positions ty(isnan(x))=0; % Don't count NaN spurts s=repmat(ix1(bitand(ty,1)>0),1,2); s(:,2)=ix2(bitand(ty,2)>0); if ~nargout tw=(1:n)'; for i=size(s,1):-1:2 j=s(i,1); % start of new spurt tw=[tw(1:j-1); tw(j); tw(j:end)]; w=[w(1:j-1); NaN; w(j:end)]; % insert a NaN to force a plotting break end plot(tt(:,1:2)',repmat(x(:)',2,1),'r-+',tw,w,'b-'); end
""" Main module for `GigaSOM.jl` - Huge-scale, high-performance flow cytometry clustering The documentation is here: http://LCSB-BioCore.github.io/GigaSOM.jl """ module GigaSOM using CSV using DataFrames using Distances using Distributed using DistributedData using Distributions using FCSFiles using FileIO using DistributedArrays using NearestNeighbors using Serialization using StableRNGs include("base/structs.jl") include("base/dataops.jl") include("base/trainutils.jl") include("analysis/core.jl") include("analysis/embedding.jl") include("io/input.jl") include("io/process.jl") include("io/splitting.jl") #core export initGigaSOM, trainGigaSOM, mapToGigaSOM #trainutils export linearRadius, expRadius, gaussianKernel, bubbleKernel, thresholdKernel, distMatrix #embedding export embedGigaSOM # structs export Som #io/input export readFlowset, readFlowFrame, loadFCS, loadFCSHeader, getFCSSize, loadFCSSizes, loadFCSSet, selectFCSColumns, distributeFCSFileVector, distributeFileVector, getCSVSize, loadCSV, loadCSVSizes, loadCSVSet #io/splitting export slicesof, vcollectSlice, collectSlice #io/process export cleanNames!, getMetaData, getMarkerNames #dataops (higher-level operations on data) export dtransform_asinh end # module
(******************************************************************************) (* Project: Isabelle/UTP Toolkit *) (* File: Injection_Universe.thy *) (* Authors: Simon Foster and Frank Zeyda *) (* Emails: [email protected] and [email protected] *) (******************************************************************************) section \<open> Injection Universes \<close> theory Injection_Universe imports "HOL-Library.Countable" "Optics.Lenses" begin text \<open> An injection universe shows how one type @{typ "'a"} can be injected into another type, @{typ "'u"}. They are applied in UTP to provide local variables which require that we can injection a variety of different datatypes into a unified stack type. \<close> record ('a, 'u) inj_univ = to_univ :: "'a \<Rightarrow> 'u" ("to-univ\<index>") locale inj_univ = fixes I :: "('a, 'u) inj_univ" (structure) assumes inj_to_univ: "inj to-univ" begin definition from_univ :: "'u \<Rightarrow> 'a" ("from-univ") where "from_univ = inv to-univ" lemma to_univ_inv [simp]: "from-univ (to-univ x) = x" by (simp add: from_univ_def inv_f_f inj_to_univ) text \<open> Lens-based view on universe injection and projection. \<close> definition to_univ_lens :: "'a \<Longrightarrow> 'u" ("to-univ\<^sub>L") where "to_univ_lens = \<lparr> lens_get = from-univ, lens_put = (\<lambda> s v. to-univ v) \<rparr>" lemma mwb_to_univ_lens [simp]: "mwb_lens to_univ_lens" by (unfold_locales, simp_all add: to_univ_lens_def) end text \<open> Example universe based on natural numbers. Any countable type can be injected into it. \<close> definition nat_inj_univ :: "('a::countable, nat) inj_univ" ("\<U>\<^sub>\<nat>") where "nat_inj_univ = \<lparr> to_univ = to_nat \<rparr>" lemma nat_inj_univ: "inj_univ nat_inj_univ" by (unfold_locales, simp add: nat_inj_univ_def) end
/- Copyright (c) 2021 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies ! This file was ported from Lean 3 source module data.pi.interval ! leanprover-community/mathlib commit d101e93197bb5f6ea89bd7ba386b7f7dff1f3903 ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathlib.Data.Finset.LocallyFinite import Mathlib.Data.Fintype.BigOperators /-! # Intervals in a pi type This file shows that (dependent) functions to locally finite orders equipped with the pointwise order are locally finite and calculates the cardinality of their intervals. -/ open Finset Fintype open BigOperators variable {ι : Type _} {α : ι → Type _} namespace Pi section LocallyFinite variable [DecidableEq ι] [Fintype ι] [∀ i, DecidableEq (α i)] [∀ i, PartialOrder (α i)] [∀ i, LocallyFiniteOrder (α i)] instance : LocallyFiniteOrder (∀ i, α i) := LocallyFiniteOrder.ofIcc _ (fun a b => piFinset fun i => Icc (a i) (b i)) fun a b x => by simp_rw [mem_piFinset, mem_Icc, le_def, forall_and] variable (a b : ∀ i, α i) theorem Icc_eq : Icc a b = piFinset fun i => Icc (a i) (b i) := rfl #align pi.Icc_eq Pi.Icc_eq theorem card_Icc : (Icc a b).card = ∏ i, (Icc (a i) (b i)).card := card_piFinset _ #align pi.card_Icc Pi.card_Icc theorem card_Ico : (Ico a b).card = (∏ i, (Icc (a i) (b i)).card) - 1 := by rw [card_Ico_eq_card_Icc_sub_one, card_Icc] #align pi.card_Ico Pi.card_Ico theorem card_Ioc : (Ioc a b).card = (∏ i, (Icc (a i) (b i)).card) - 1 := by rw [card_Ioc_eq_card_Icc_sub_one, card_Icc] #align pi.card_Ioc Pi.card_Ioc theorem card_Ioo : (Ioo a b).card = (∏ i, (Icc (a i) (b i)).card) - 2 := by rw [card_Ioo_eq_card_Icc_sub_two, card_Icc] #align pi.card_Ioo Pi.card_Ioo end LocallyFinite section Bounded variable [DecidableEq ι] [Fintype ι] [∀ i, DecidableEq (α i)] [∀ i, PartialOrder (α i)] section Bot variable [∀ i, LocallyFiniteOrderBot (α i)] (b : ∀ i, α i) instance : LocallyFiniteOrderBot (∀ i, α i) := LocallyFiniteOrderTop.ofIic _ (fun b => piFinset fun i => Iic (b i)) fun b x => by simp_rw [mem_piFinset, mem_Iic, le_def] theorem card_Iic : (Iic b).card = ∏ i, (Iic (b i)).card := card_piFinset _ #align pi.card_Iic Pi.card_Iic theorem card_Iio : (Iio b).card = (∏ i, (Iic (b i)).card) - 1 := by rw [card_Iio_eq_card_Iic_sub_one, card_Iic] #align pi.card_Iio Pi.card_Iio end Bot section Top variable [∀ i, LocallyFiniteOrderTop (α i)] (a : ∀ i, α i) instance : LocallyFiniteOrderTop (∀ i, α i) := LocallyFiniteOrderTop.ofIci _ (fun a => piFinset fun i => Ici (a i)) fun a x => by simp_rw [mem_piFinset, mem_Ici, le_def] theorem card_Ici : (Ici a).card = ∏ i, (Ici (a i)).card := card_piFinset _ #align pi.card_Ici Pi.card_Ici theorem card_Ioi : (Ioi a).card = (∏ i, (Ici (a i)).card) - 1 := by rw [card_Ioi_eq_card_Ici_sub_one, card_Ici] #align pi.card_Ioi Pi.card_Ioi end Top end Bounded end Pi
[STATEMENT] lemma closed_path_image: fixes g :: "real \<Rightarrow> 'a::t2_space" shows "path g \<Longrightarrow> closed(path_image g)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. path g \<Longrightarrow> closed (path_image g) [PROOF STEP] by (metis compact_path_image compact_imp_closed)
Formal statement is: lemma prime_int_nat_transfer: "prime k \<longleftrightarrow> k \<ge> 0 \<and> prime (nat k)" Informal statement is: A natural number $k$ is prime if and only if $k \geq 0$ and $k$ is prime as an integer.
The centre of a ball is in the ball if and only if the radius is positive.
## LLE pressure solver function x0_LLE_pressure(model::EoSModel,T,x) xx = 1 .-x pure = split_model(model) eachx = eachcol(Diagonal(ones(eltype(x),length(x)))) sat = sat_pure.(pure,T) P_sat = [tup[1] for tup in sat] V_l_sat = [tup[2] for tup in sat] V0_l = sum(x.*V_l_sat) V0_ll = sum(xx.*V_l_sat) prepend!(xx,log10.([V0_l,V0_ll])) return xx end function LLE_pressure(model::EoSModel, T, x; v0 =nothing) TYPE = promote_type(eltype(T),eltype(x)) # lb_v = lb_volume(model,x) ts = T_scales(model,x) pmix = p_scale(model,x) if v0 === nothing v0 = x0_LLE_pressure(model,T,x) end len = length(v0[1:end-1]) #xcache = zeros(eltype(x0),len) Fcache = zeros(eltype(v0[1:end-1]),len) f! = (F,z) -> Obj_bubble_pressure(model, F, T, exp10(z[1]), exp10(z[2]), x,z[3:end],ts,pmix) r =Solvers.nlsolve(f!,v0[1:end-1],LineSearch(Newton())) sol = Solvers.x_sol(r) v_l = exp10(sol[1]) v_ll = exp10(sol[2]) xx = FractionVector(sol[3:end]) P_sat = pressure(model,v_l,T,x) return (P_sat, v_l, v_ll, xx) end
[STATEMENT] lemma (in lbisimulation) lstutter_extend: "lbisimulation R (stutter_extend A) (stutter_extend B)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. lbisimulation R (stutter_extend A) (stutter_extend B) [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. lbisimulation R (stutter_extend A) (stutter_extend B) [PROOF STEP] interpret se: bisimulation R "stutter_extend A" "stutter_extend B" [PROOF STATE] proof (prove) goal (1 subgoal): 1. bisimulation R (stutter_extend A) (stutter_extend B) [PROOF STEP] by (rule stutter_extend) [PROOF STATE] proof (state) goal (1 subgoal): 1. lbisimulation R (stutter_extend A) (stutter_extend B) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) goal (1 subgoal): 1. lbisimulation R (stutter_extend A) (stutter_extend B) [PROOF STEP] by (unfold_locales, auto simp: s1.labeling_consistent) [PROOF STATE] proof (state) this: lbisimulation R (stutter_extend A) (stutter_extend B) goal: No subgoals! [PROOF STEP] qed
println("===============================================") println("Testing definition.jl") println("===============================================") function _RheoTimeData_explicit_nolog() a = Vector{RheoFloat}(1.0:1.0:3.0) b = Vector{RheoFloat}(4.0:1.0:6.0) c = Vector{RheoFloat}(7.0:1.0:9.0) data = RheoTimeData(a, b, c, nothing) data.σ==a && data.ϵ==b && data.t==c && isnothing(data.log) end @test _RheoTimeData_explicit_nolog() function _RheoTimeData_const_nolog() eps = Vector{RheoFloat}(1.0:1.0:3.0) sig = Vector{RheoFloat}(4.0:1.0:6.0) t = Vector{RheoFloat}(7.0:1.0:9.0) data = RheoTimeData(strain=eps, stress=sig, t=t, savelog=false) showlog(data) getstress(data)==sig && getstrain(data)==eps && gettime(data)==t && isnothing(data.log) end @test _RheoTimeData_const_nolog() function _RheoTimeData_const_nostrain() sig = Vector{RheoFloat}(4.0:1.0:6.0) t = Vector{RheoFloat}(7.0:1.0:9.0) data = RheoTimeData(σ=sig, t=t) showlog(data) data.σ==sig && data.ϵ==RheoFloat[] && data.t==t && data.log[1].info.type == stress_only::TimeDataType end @test _RheoTimeData_const_nostrain() function _operators_logs() d1=strainfunction(timeline(0:0.5:10),t->exp(-t)) d2=strainfunction(timeline(0:0.5:10),t->1-exp(-t)) d=2*d1 - (-d2) + d2 d3=rheologrun(d.log) (d3.ϵ == d.ϵ) && all([ abs(e-2.)<=eps(RheoFloat) for e in d.ϵ ]) end @test _operators_logs() function _RheoFreqData_explicit_nolog() a = Vector{RheoFloat}(1.0:1.0:3.0) b = Vector{RheoFloat}(4.0:1.0:6.0) c = Vector{RheoFloat}(7.0:1.0:9.0) data = RheoFreqData(a, b, c, nothing) data.Gp==a && data.Gpp==b && data.ω==c && isnothing(data.log) end @test _RheoFreqData_explicit_nolog() function _RheoFreqData_const_nolog() a = Vector{RheoFloat}(1.0:1.0:3.0) b = Vector{RheoFloat}(4.0:1.0:6.0) c = Vector{RheoFloat}(7.0:1.0:9.0) data = RheoFreqData(omega=a, Gp=b, Gpp=c , savelog=false) showlog(data) getfreq(data)==a && getstorage(data)==b && getloss(data)==c && isnothing(data.log) end @test _RheoFreqData_const_nolog() function _rheoconvert() vi64=Int64(1) ai64=[vi64,vi64] arf=Vector{RheoFloat}([1,2,3]) rheoconvert(RheoFloat(1.0))===rheoconvert(vi64) && typeof(rheoconvert(ai64)) == Vector{RheoFloat} && arf === rheoconvert(arf) && ai64 !== rheoconvert(ai64) end @test _rheoconvert() function _union_strain1stress2() time_instance = timeline(t_start=0.0, t_end=15.0, step=0.2) imposed_strain = strainfunction(time_instance, sawtooth(offset=5.0, amp=2, period=5)) imposed_stress = stressfunction(time_instance, stairs(offset=3.0, amp=0.5, width=4.0)) combined = imposed_strain|imposed_stress (combined.σ==imposed_stress.σ) && (combined.ϵ==imposed_strain.ϵ) && (combined.t==imposed_stress.t) end @test _union_strain1stress2() function _union_stress1strain2() time_instance = timeline(t_start=0.0, t_end=15.0, step=0.2) imposed_strain = strainfunction(time_instance, sawtooth(offset=5.0, amp=2, period=5)) imposed_stress = stressfunction(time_instance, stairs(offset=3.0, amp=0.5, width=4.0)) combined = imposed_stress|imposed_strain (combined.σ==imposed_stress.σ) && (combined.ϵ==imposed_strain.ϵ) && (combined.t==imposed_stress.t) end @test _union_stress1strain2() function _freeze_params() SLS2_mod = freeze_params( SLS2, G₀=2, η₂=3.5) relaxmod(SLS2, 1, [2,1,2,3,3.5]) == relaxmod(SLS2_mod, 1, [1,2,3]) end @test _freeze_params() function _getparams() m = RheoModel(Maxwell, k=1, eta=2) p1 = getparams(m) p2 = getparams(m,unicode=false) (p1.k==1.0) && (p1.η==2.0) && (p2.k==1.0) && (p2.eta==2.0) end @test _getparams() function _getparams_dict() m = RheoModel(Maxwell, k=1, eta=2) p = dict(getparams(m,unicode=false)) (p[:k]==1.0) && (p[:eta]==2.0) end @test _getparams_dict() # # The moduli functions on arrays are extensively tested as part of the model tests # function _scalar_moduli() m=RheoModel(Spring, k=2) (relaxmod(m))(1) == relaxmod(m, 1) == relaxmod(Spring, k=2, 1) == 2. && (creepcomp(m))(1) == creepcomp(m, 1) == creepcomp(Spring, k=2, 1) == 0.5 && (storagemod(m))(1) == storagemod(m, 1) == storagemod(Spring, k=2, 1) == 2. && (lossmod(m))(1) == lossmod(m, 1) == lossmod(Spring, k=2, 1) == 0.0 && (dynamicmod(m))(1) == dynamicmod(m, 1) == dynamicmod(Spring, k=2, 1) == 2.0 + 0.0*im end @test _scalar_moduli()
theory T61 imports Main begin lemma "( (\<forall> x::nat. \<forall> y::nat. meet(x, y) = meet(y, x)) & (\<forall> x::nat. \<forall> y::nat. join(x, y) = join(y, x)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, meet(y, z)) = meet(meet(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(x, join(y, z)) = join(join(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. meet(x, join(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. join(x, meet(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, join(y, z)) = join(mult(x, y), mult(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(join(x, y), z) = join(mult(x, z), mult(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, over(join(mult(x, y), z), y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(y, undr(x, join(mult(x, y), z))) = y) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(over(x, y), y), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(y, undr(y, x)), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, meet(y, z)) = meet(mult(x, y), mult(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(x, join(y, z)) = join(undr(x, y), undr(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(join(x, y), z) = join(over(x, z), over(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(x, meet(y, z)) = join(over(x, y), over(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(meet(x, y), z) = join(undr(x, z), undr(y, z))) & (\<forall> x::nat. \<forall> y::nat. invo(join(x, y)) = meet(invo(x), invo(y))) & (\<forall> x::nat. \<forall> y::nat. invo(meet(x, y)) = join(invo(x), invo(y))) & (\<forall> x::nat. invo(invo(x)) = x) ) \<longrightarrow> (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(meet(x, y), z) = meet(mult(x, z), mult(y, z))) " nitpick[card nat=8,timeout=86400] oops end
/- Copyright (c) 2022 Mantas Bakšys. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mantas Bakšys -/ import algebra.order.module import data.prod.lex import group_theory.perm.support import order.monovary import tactic.abel /-! # Rearrangement inequality This file proves the rearrangement inequality and deduces the conditions for equality and strict inequality. The rearrangement inequality tells you that for two functions `f g : ι → α`, the sum `∑ i, f i * g (σ i)` is maximized over all `σ : perm ι` when `g ∘ σ` monovaries with `f` and minimized when `g ∘ σ` antivaries with `f`. The inequality also tells you that `∑ i, f i * g (σ i) = ∑ i, f i * g i` if and only if `g ∘ σ` monovaries with `f` when `g` monovaries with `f`. The above equality also holds if and only if `g ∘ σ` antivaries with `f` when `g` antivaries with `f`. From the above two statements, we deduce that the inequality is strict if and only if `g ∘ σ` does not monovary with `f` when `g` monovaries with `f`. Analogously, the inequality is strict if and only if `g ∘ σ` does not antivary with `f` when `g` antivaries with `f`. ## Implementation notes In fact, we don't need much compatibility between the addition and multiplication of `α`, so we can actually decouple them by replacing multiplication with scalar multiplication and making `f` and `g` land in different types. As a bonus, this makes the dual statement trivial. The multiplication versions are provided for convenience. The case for `monotone`/`antitone` pairs of functions over a `linear_order` is not deduced in this file because it is easily deducible from the `monovary` API. -/ open equiv equiv.perm finset function order_dual open_locale big_operators variables {ι α β : Type*} /-! ### Scalar multiplication versions -/ section smul variables [linear_ordered_ring α] [linear_ordered_add_comm_group β] [module α β] [ordered_smul α β] {s : finset ι} {σ : perm ι} {f : ι → α} {g : ι → β} /-- **Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g` is maximized when `f` and `g` monovary together. Stated by permuting the entries of `g`. -/ lemma monovary_on.sum_smul_comp_perm_le_sum_smul (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i • g (σ i) ≤ ∑ i in s, f i • g i := begin classical, revert hσ σ hfg, apply finset.induction_on_max_value (λ i, to_lex (g i, f i)) s, { simp only [le_rfl, finset.sum_empty, implies_true_iff] }, intros a s has hamax hind σ hfg hσ, set τ : perm ι := σ.trans (swap a (σ a)) with hτ, have hτs : {x | τ x ≠ x} ⊆ s, { intros x hx, simp only [ne.def, set.mem_set_of_eq, equiv.coe_trans, equiv.swap_comp_apply] at hx, split_ifs at hx with h₁ h₂ h₃, { obtain rfl | hax := eq_or_ne x a, { contradiction }, { exact mem_of_mem_insert_of_ne (hσ $ λ h, hax $ h.symm.trans h₁) hax } }, { exact (hx $ σ.injective h₂.symm).elim }, { exact mem_of_mem_insert_of_ne (hσ hx) (ne_of_apply_ne _ h₂) } }, specialize hind (hfg.subset $ subset_insert _ _) hτs, simp_rw sum_insert has, refine le_trans _ (add_le_add_left hind _), obtain hσa | hσa := eq_or_ne a (σ a), { rw [hτ, ←hσa, swap_self, trans_refl] }, have h1s : σ⁻¹ a ∈ s, { rw [ne.def, ←inv_eq_iff_eq] at hσa, refine mem_of_mem_insert_of_ne (hσ $ λ h, hσa _) hσa, rwa [apply_inv_self, eq_comm] at h }, simp only [← s.sum_erase_add _ h1s, add_comm], rw [← add_assoc, ← add_assoc], simp only [hτ, swap_apply_left, function.comp_app, equiv.coe_trans, apply_inv_self], refine add_le_add (smul_add_smul_le_smul_add_smul' _ _) (sum_congr rfl $ λ x hx, _).le, { specialize hamax (σ⁻¹ a) h1s, rw prod.lex.le_iff at hamax, cases hamax, { exact hfg (mem_insert_of_mem h1s) (mem_insert_self _ _) hamax }, { exact hamax.2 } }, { specialize hamax (σ a) (mem_of_mem_insert_of_ne (hσ $ σ.injective.ne hσa.symm) hσa.symm), rw prod.lex.le_iff at hamax, cases hamax, { exact hamax.le }, { exact hamax.1.le } }, { rw [mem_erase, ne.def, eq_inv_iff_eq] at hx, rw swap_apply_of_ne_of_ne hx.1 (σ.injective.ne _), rintro rfl, exact has hx.2 } end /-- **Equality case of Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which monovary together, is unchanged by a permutation if and only if `f` and `g ∘ σ` monovary together. Stated by permuting the entries of `g`. -/ lemma monovary_on.sum_smul_comp_perm_eq_sum_smul_iff (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i • g (σ i) = ∑ i in s, f i • g i ↔ monovary_on f (g ∘ σ) s := begin classical, refine ⟨not_imp_not.1 $ λ h, _, λ h, (hfg.sum_smul_comp_perm_le_sum_smul hσ).antisymm _⟩, { rw monovary_on at h, push_neg at h, obtain ⟨x, hx, y, hy, hgxy, hfxy⟩ := h, set τ : perm ι := (swap x y).trans σ, have hτs : {x | τ x ≠ x} ⊆ s, { refine (set_support_mul_subset σ $ swap x y).trans (set.union_subset hσ $ λ z hz, _), obtain ⟨_, rfl | rfl⟩ := swap_apply_ne_self_iff.1 hz; assumption }, refine ((hfg.sum_smul_comp_perm_le_sum_smul hτs).trans_lt' _).ne, obtain rfl | hxy := eq_or_ne x y, { cases lt_irrefl _ hfxy }, simp only [←s.sum_erase_add _ hx, ←(s.erase x).sum_erase_add _ (mem_erase.2 ⟨hxy.symm, hy⟩), add_assoc, equiv.coe_trans, function.comp_app, swap_apply_right, swap_apply_left], refine add_lt_add_of_le_of_lt (finset.sum_congr rfl $ λ z hz, _).le (smul_add_smul_lt_smul_add_smul hfxy hgxy), simp_rw mem_erase at hz, rw swap_apply_of_ne_of_ne hz.2.1 hz.1 }, { convert h.sum_smul_comp_perm_le_sum_smul ((set_support_inv_eq _).subset.trans hσ) using 1, simp_rw [function.comp_app, apply_inv_self] } end /-- **Strict inequality case of Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which monovary together, is strictly decreased by a permutation if and only if `f` and `g ∘ σ` do not monovary together. Stated by permuting the entries of `g`. -/ lemma monovary_on.sum_smul_comp_perm_lt_sum_smul_iff (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i • g (σ i) < ∑ i in s, f i • g i ↔ ¬ monovary_on f (g ∘ σ) s := by simp [←hfg.sum_smul_comp_perm_eq_sum_smul_iff hσ, lt_iff_le_and_ne, hfg.sum_smul_comp_perm_le_sum_smul hσ] /-- **Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g` is maximized when `f` and `g` monovary together. Stated by permuting the entries of `f`. -/ lemma monovary_on.sum_comp_perm_smul_le_sum_smul (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f (σ i) • g i ≤ ∑ i in s, f i • g i := begin convert hfg.sum_smul_comp_perm_le_sum_smul (show {x | σ⁻¹ x ≠ x} ⊆ s, by simp only [set_support_inv_eq, hσ]) using 1, exact σ.sum_comp' s (λ i j, f i • g j) hσ, end /-- **Equality case of Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which monovary together, is unchanged by a permutation if and only if `f ∘ σ` and `g` monovary together. Stated by permuting the entries of `f`. -/ lemma monovary_on.sum_comp_perm_smul_eq_sum_smul_iff (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f (σ i) • g i = ∑ i in s, f i • g i ↔ monovary_on (f ∘ σ) g s := begin have hσinv : {x | σ⁻¹ x ≠ x} ⊆ s := (set_support_inv_eq _).subset.trans hσ, refine (iff.trans _ $ hfg.sum_smul_comp_perm_eq_sum_smul_iff hσinv).trans ⟨λ h, _, λ h, _⟩, { simpa only [σ.sum_comp' s (λ i j, f i • g j) hσ] }, { convert h.comp_right σ, { rw [comp.assoc, inv_def, symm_comp_self, comp.right_id] }, { rw [σ.eq_preimage_iff_image_eq, set.image_perm hσ] } }, { convert h.comp_right σ.symm, { rw [comp.assoc, self_comp_symm, comp.right_id] }, { rw σ.symm.eq_preimage_iff_image_eq, exact set.image_perm hσinv } } end /-- **Strict inequality case of Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which monovary together, is strictly decreased by a permutation if and only if `f ∘ σ` and `g` do not monovary together. Stated by permuting the entries of `f`. -/ lemma monovary_on.sum_comp_perm_smul_lt_sum_smul_iff (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f (σ i) • g i < ∑ i in s, f i • g i ↔ ¬ monovary_on (f ∘ σ) g s := by simp [←hfg.sum_comp_perm_smul_eq_sum_smul_iff hσ, lt_iff_le_and_ne, hfg.sum_comp_perm_smul_le_sum_smul hσ] /-- **Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g` is minimized when `f` and `g` antivary together. Stated by permuting the entries of `g`. -/ lemma antivary_on.sum_smul_le_sum_smul_comp_perm (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i • g i ≤ ∑ i in s, f i • g (σ i) := hfg.dual_right.sum_smul_comp_perm_le_sum_smul hσ /-- **Equality case of the Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which antivary together, is unchanged by a permutation if and only if `f` and `g ∘ σ` antivary together. Stated by permuting the entries of `g`. -/ lemma antivary_on.sum_smul_eq_sum_smul_comp_perm_iff (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i • g (σ i) = ∑ i in s, f i • g i ↔ antivary_on f (g ∘ σ) s := (hfg.dual_right.sum_smul_comp_perm_eq_sum_smul_iff hσ).trans monovary_on_to_dual_right /-- **Strict inequality case of the Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which antivary together, is strictly decreased by a permutation if and only if `f` and `g ∘ σ` do not antivary together. Stated by permuting the entries of `g`. -/ lemma antivary_on.sum_smul_lt_sum_smul_comp_perm_iff (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i • g i < ∑ i in s, f i • g (σ i) ↔ ¬ antivary_on f (g ∘ σ) s := by simp [←hfg.sum_smul_eq_sum_smul_comp_perm_iff hσ, lt_iff_le_and_ne, eq_comm, hfg.sum_smul_le_sum_smul_comp_perm hσ] /-- **Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g` is minimized when `f` and `g` antivary together. Stated by permuting the entries of `f`. -/ lemma antivary_on.sum_smul_le_sum_comp_perm_smul (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i • g i ≤ ∑ i in s, f (σ i) • g i := hfg.dual_right.sum_comp_perm_smul_le_sum_smul hσ /-- **Equality case of the Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which antivary together, is unchanged by a permutation if and only if `f ∘ σ` and `g` antivary together. Stated by permuting the entries of `f`. -/ lemma antivary_on.sum_smul_eq_sum_comp_perm_smul_iff (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f (σ i) • g i = ∑ i in s, f i • g i ↔ antivary_on (f ∘ σ) g s := (hfg.dual_right.sum_comp_perm_smul_eq_sum_smul_iff hσ).trans monovary_on_to_dual_right /-- **Strict inequality case of the Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which antivary together, is strictly decreased by a permutation if and only if `f ∘ σ` and `g` do not antivary together. Stated by permuting the entries of `f`. -/ lemma antivary_on.sum_smul_lt_sum_comp_perm_smul_iff (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i • g i < ∑ i in s, f (σ i) • g i ↔ ¬ antivary_on (f ∘ σ) g s := by simp [←hfg.sum_smul_eq_sum_comp_perm_smul_iff hσ, eq_comm, lt_iff_le_and_ne, hfg.sum_smul_le_sum_comp_perm_smul hσ] variables [fintype ι] /-- **Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g` is maximized when `f` and `g` monovary together. Stated by permuting the entries of `g`. -/ lemma monovary.sum_smul_comp_perm_le_sum_smul (hfg : monovary f g) : ∑ i, f i • g (σ i) ≤ ∑ i, f i • g i := (hfg.monovary_on _).sum_smul_comp_perm_le_sum_smul $ λ i _, mem_univ _ /-- **Equality case of Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which monovary together, is unchanged by a permutation if and only if `f` and `g ∘ σ` monovary together. Stated by permuting the entries of `g`. -/ lemma monovary.sum_smul_comp_perm_eq_sum_smul_iff (hfg : monovary f g) : ∑ i, f i • g (σ i) = ∑ i, f i • g i ↔ monovary f (g ∘ σ) := by simp [(hfg.monovary_on _).sum_smul_comp_perm_eq_sum_smul_iff (λ i _, mem_univ _)] /-- **Strict inequality case of Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which monovary together, is strictly decreased by a permutation if and only if `f` and `g ∘ σ` do not monovary together. Stated by permuting the entries of `g`. -/ lemma monovary.sum_smul_comp_perm_lt_sum_smul_iff (hfg : monovary f g) : ∑ i, f i • g (σ i) < ∑ i, f i • g i ↔ ¬ monovary f (g ∘ σ) := by simp [(hfg.monovary_on _).sum_smul_comp_perm_lt_sum_smul_iff (λ i _, mem_univ _)] /-- **Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g` is maximized when `f` and `g` monovary together. Stated by permuting the entries of `f`. -/ lemma monovary.sum_comp_perm_smul_le_sum_smul (hfg : monovary f g) : ∑ i, f (σ i) • g i ≤ ∑ i, f i • g i := (hfg.monovary_on _).sum_comp_perm_smul_le_sum_smul $ λ i _, mem_univ _ /-- **Equality case of Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which monovary together, is unchanged by a permutation if and only if `f ∘ σ` and `g` monovary together. Stated by permuting the entries of `g`. -/ lemma monovary.sum_comp_perm_smul_eq_sum_smul_iff (hfg : monovary f g) : ∑ i, f (σ i) • g i = ∑ i, f i • g i ↔ monovary (f ∘ σ) g := by simp [(hfg.monovary_on _).sum_comp_perm_smul_eq_sum_smul_iff (λ i _, mem_univ _)] /-- **Strict inequality case of Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which monovary together, is strictly decreased by a permutation if and only if `f` and `g ∘ σ` do not monovary together. Stated by permuting the entries of `g`. -/ lemma monovary.sum_comp_perm_smul_lt_sum_smul_iff (hfg : monovary f g) : ∑ i, f (σ i) • g i < ∑ i, f i • g i ↔ ¬ monovary (f ∘ σ) g := by simp [(hfg.monovary_on _).sum_comp_perm_smul_lt_sum_smul_iff (λ i _, mem_univ _)] /-- **Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g` is minimized when `f` and `g` antivary together. Stated by permuting the entries of `g`. -/ lemma antivary.sum_smul_le_sum_smul_comp_perm (hfg : antivary f g) : ∑ i, f i • g i ≤ ∑ i, f i • g (σ i) := (hfg.antivary_on _).sum_smul_le_sum_smul_comp_perm $ λ i _, mem_univ _ /-- **Equality case of the Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which antivary together, is unchanged by a permutation if and only if `f` and `g ∘ σ` antivary together. Stated by permuting the entries of `g`. -/ lemma antivary.sum_smul_eq_sum_smul_comp_perm_iff (hfg : antivary f g) : ∑ i, f i • g (σ i) = ∑ i, f i • g i ↔ antivary f (g ∘ σ) := by simp [(hfg.antivary_on _).sum_smul_eq_sum_smul_comp_perm_iff (λ i _, mem_univ _)] /-- **Strict inequality case of the Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which antivary together, is strictly decreased by a permutation if and only if `f` and `g ∘ σ` do not antivary together. Stated by permuting the entries of `g`. -/ lemma antivary.sum_smul_lt_sum_smul_comp_perm_iff (hfg : antivary f g) : ∑ i, f i • g i < ∑ i, f i • g (σ i) ↔ ¬ antivary f (g ∘ σ) := by simp [(hfg.antivary_on _).sum_smul_lt_sum_smul_comp_perm_iff (λ i _, mem_univ _)] /-- **Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g` is minimized when `f` and `g` antivary together. Stated by permuting the entries of `f`. -/ lemma antivary.sum_smul_le_sum_comp_perm_smul (hfg : antivary f g) : ∑ i, f i • g i ≤ ∑ i, f (σ i) • g i := (hfg.antivary_on _).sum_smul_le_sum_comp_perm_smul $ λ i _, mem_univ _ /-- **Equality case of the Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which antivary together, is unchanged by a permutation if and only if `f ∘ σ` and `g` antivary together. Stated by permuting the entries of `f`. -/ lemma antivary.sum_smul_eq_sum_comp_perm_smul_iff (hfg : antivary f g) : ∑ i, f (σ i) • g i = ∑ i, f i • g i ↔ antivary (f ∘ σ) g := by simp [(hfg.antivary_on _).sum_smul_eq_sum_comp_perm_smul_iff (λ i _, mem_univ _)] /-- **Strict inequality case of the Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which antivary together, is strictly decreased by a permutation if and only if `f ∘ σ` and `g` do not antivary together. Stated by permuting the entries of `f`. -/ lemma antivary.sum_smul_lt_sum_comp_perm_smul_iff (hfg : antivary f g) : ∑ i, f i • g i < ∑ i, f (σ i) • g i ↔ ¬ antivary (f ∘ σ) g := by simp [(hfg.antivary_on _).sum_smul_lt_sum_comp_perm_smul_iff (λ i _, mem_univ _)] end smul /-! ### Multiplication versions Special cases of the above when scalar multiplication is actually multiplication. -/ section mul variables [linear_ordered_ring α] {s : finset ι} {σ : perm ι} {f g : ι → α} /-- **Rearrangement Inequality**: Pointwise multiplication of `f` and `g` is maximized when `f` and `g` monovary together. Stated by permuting the entries of `g`. -/ lemma monovary_on.sum_mul_comp_perm_le_sum_mul (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i * g (σ i) ≤ ∑ i in s, f i * g i := hfg.sum_smul_comp_perm_le_sum_smul hσ /-- **Equality case of Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which monovary together, is unchanged by a permutation if and only if `f` and `g ∘ σ` monovary together. Stated by permuting the entries of `g`. -/ lemma monovary_on.sum_mul_comp_perm_eq_sum_mul_iff (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i * g (σ i) = ∑ i in s, f i * g i ↔ monovary_on f (g ∘ σ) s := hfg.sum_smul_comp_perm_eq_sum_smul_iff hσ /-- **Strict inequality case of Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which monovary together, is strictly decreased by a permutation if and only if `f` and `g ∘ σ` do not monovary together. Stated by permuting the entries of `g`. -/ lemma monovary_on.sum_mul_comp_perm_lt_sum_mul_iff (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i • g (σ i) < ∑ i in s, f i • g i ↔ ¬ monovary_on f (g ∘ σ) s := hfg.sum_smul_comp_perm_lt_sum_smul_iff hσ /-- **Rearrangement Inequality**: Pointwise multiplication of `f` and `g` is maximized when `f` and `g` monovary together. Stated by permuting the entries of `f`. -/ lemma monovary_on.sum_comp_perm_mul_le_sum_mul (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f (σ i) * g i ≤ ∑ i in s, f i * g i := hfg.sum_comp_perm_smul_le_sum_smul hσ /-- **Equality case of Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which monovary together, is unchanged by a permutation if and only if `f ∘ σ` and `g` monovary together. Stated by permuting the entries of `f`. -/ lemma monovary_on.sum_comp_perm_mul_eq_sum_mul_iff (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f (σ i) * g i = ∑ i in s, f i * g i ↔ monovary_on (f ∘ σ) g s := hfg.sum_comp_perm_smul_eq_sum_smul_iff hσ /-- **Strict inequality case of Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which monovary together, is strictly decreased by a permutation if and only if `f ∘ σ` and `g` do not monovary together. Stated by permuting the entries of `f`. -/ lemma monovary_on.sum_comp_perm_mul_lt_sum_mul_iff (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f (σ i) * g i < ∑ i in s, f i * g i ↔ ¬ monovary_on (f ∘ σ) g s := hfg.sum_comp_perm_smul_lt_sum_smul_iff hσ /-- **Rearrangement Inequality**: Pointwise multiplication of `f` and `g` is minimized when `f` and `g` antivary together. Stated by permuting the entries of `g`. -/ lemma antivary_on.sum_mul_le_sum_mul_comp_perm (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i * g i ≤ ∑ i in s, f i * g (σ i) := hfg.sum_smul_le_sum_smul_comp_perm hσ /-- **Equality case of the Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which antivary together, is unchanged by a permutation if and only if `f` and `g ∘ σ` antivary together. Stated by permuting the entries of `g`. -/ lemma antivary_on.sum_mul_eq_sum_mul_comp_perm_iff (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i * g (σ i) = ∑ i in s, f i * g i ↔ antivary_on f (g ∘ σ) s := hfg.sum_smul_eq_sum_smul_comp_perm_iff hσ /-- **Strict inequality case of the Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which antivary together, is strictly decreased by a permutation if and only if `f` and `g ∘ σ` do not antivary together. Stated by permuting the entries of `g`. -/ lemma antivary_on.sum_mul_lt_sum_mul_comp_perm_iff (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i * g i < ∑ i in s, f i * g (σ i) ↔ ¬ antivary_on f (g ∘ σ) s := hfg.sum_smul_lt_sum_smul_comp_perm_iff hσ /-- **Rearrangement Inequality**: Pointwise multiplication of `f` and `g` is minimized when `f` and `g` antivary together. Stated by permuting the entries of `f`. -/ lemma antivary_on.sum_mul_le_sum_comp_perm_mul (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i * g i ≤ ∑ i in s, f (σ i) * g i := hfg.sum_smul_le_sum_comp_perm_smul hσ /-- **Equality case of the Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which antivary together, is unchanged by a permutation if and only if `f ∘ σ` and `g` antivary together. Stated by permuting the entries of `f`. -/ lemma antivary_on.sum_mul_eq_sum_comp_perm_mul_iff (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f (σ i) * g i = ∑ i in s, f i * g i ↔ antivary_on (f ∘ σ) g s := hfg.sum_smul_eq_sum_comp_perm_smul_iff hσ /-- **Strict inequality case of the Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which antivary together, is strictly decreased by a permutation if and only if `f ∘ σ` and `g` do not antivary together. Stated by permuting the entries of `f`. -/ lemma antivary_on.sum_mul_lt_sum_comp_perm_mul_iff (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i * g i < ∑ i in s, f (σ i) * g i ↔ ¬ antivary_on (f ∘ σ) g s := hfg.sum_smul_lt_sum_comp_perm_smul_iff hσ variables [fintype ι] /-- **Rearrangement Inequality**: Pointwise multiplication of `f` and `g` is maximized when `f` and `g` monovary together. Stated by permuting the entries of `g`. -/ lemma monovary.sum_mul_comp_perm_le_sum_mul (hfg : monovary f g) : ∑ i, f i * g (σ i) ≤ ∑ i, f i * g i := hfg.sum_smul_comp_perm_le_sum_smul /-- **Equality case of Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which monovary together, is unchanged by a permutation if and only if `f` and `g ∘ σ` monovary together. Stated by permuting the entries of `g`. -/ lemma monovary.sum_mul_comp_perm_eq_sum_mul_iff (hfg : monovary f g) : ∑ i, f i * g (σ i) = ∑ i, f i * g i ↔ monovary f (g ∘ σ) := hfg.sum_smul_comp_perm_eq_sum_smul_iff /-- **Strict inequality case of Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which monovary together, is strictly decreased by a permutation if and only if `f` and `g ∘ σ` do not monovary together. Stated by permuting the entries of `g`. -/ lemma monovary.sum_mul_comp_perm_lt_sum_mul_iff (hfg : monovary f g) : ∑ i, f i * g (σ i) < ∑ i, f i * g i ↔ ¬ monovary f (g ∘ σ) := hfg.sum_smul_comp_perm_lt_sum_smul_iff /-- **Rearrangement Inequality**: Pointwise multiplication of `f` and `g` is maximized when `f` and `g` monovary together. Stated by permuting the entries of `f`. -/ lemma monovary.sum_comp_perm_mul_le_sum_mul (hfg : monovary f g) : ∑ i, f (σ i) * g i ≤ ∑ i, f i * g i := hfg.sum_comp_perm_smul_le_sum_smul /-- **Equality case of Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which monovary together, is unchanged by a permutation if and only if `f ∘ σ` and `g` monovary together. Stated by permuting the entries of `g`. -/ lemma monovary.sum_comp_perm_mul_eq_sum_mul_iff (hfg : monovary f g) : ∑ i, f (σ i) * g i = ∑ i, f i * g i ↔ monovary (f ∘ σ) g := hfg.sum_comp_perm_smul_eq_sum_smul_iff /-- **Strict inequality case of Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which monovary together, is strictly decreased by a permutation if and only if `f` and `g ∘ σ` do not monovary together. Stated by permuting the entries of `g`. -/ lemma monovary.sum_comp_perm_mul_lt_sum_mul_iff (hfg : monovary f g) : ∑ i, f (σ i) * g i < ∑ i, f i * g i ↔ ¬ monovary (f ∘ σ) g := hfg.sum_comp_perm_smul_lt_sum_smul_iff /-- **Rearrangement Inequality**: Pointwise multiplication of `f` and `g` is minimized when `f` and `g` antivary together. Stated by permuting the entries of `g`. -/ lemma antivary.sum_mul_le_sum_mul_comp_perm (hfg : antivary f g) : ∑ i, f i * g i ≤ ∑ i, f i * g (σ i) := hfg.sum_smul_le_sum_smul_comp_perm /-- **Equality case of the Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which antivary together, is unchanged by a permutation if and only if `f` and `g ∘ σ` antivary together. Stated by permuting the entries of `g`. -/ lemma antivary.sum_mul_eq_sum_mul_comp_perm_iff (hfg : antivary f g) : ∑ i, f i * g (σ i) = ∑ i, f i * g i ↔ antivary f (g ∘ σ) := hfg.sum_smul_eq_sum_smul_comp_perm_iff /-- **Strict inequality case of the Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which antivary together, is strictly decreased by a permutation if and only if `f` and `g ∘ σ` do not antivary together. Stated by permuting the entries of `g`. -/ lemma antivary.sum_mul_lt_sum_mul_comp_perm_iff (hfg : antivary f g) : ∑ i, f i • g i < ∑ i, f i • g (σ i) ↔ ¬ antivary f (g ∘ σ) := hfg.sum_smul_lt_sum_smul_comp_perm_iff /-- **Rearrangement Inequality**: Pointwise multiplication of `f` and `g` is minimized when `f` and `g` antivary together. Stated by permuting the entries of `f`. -/ lemma antivary.sum_mul_le_sum_comp_perm_mul (hfg : antivary f g) : ∑ i, f i * g i ≤ ∑ i, f (σ i) * g i := hfg.sum_smul_le_sum_comp_perm_smul /-- **Equality case of the Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which antivary together, is unchanged by a permutation if and only if `f ∘ σ` and `g` antivary together. Stated by permuting the entries of `f`. -/ lemma antivary.sum_mul_eq_sum_comp_perm_mul_iff (hfg : antivary f g) : ∑ i, f (σ i) * g i = ∑ i, f i * g i ↔ antivary (f ∘ σ) g := hfg.sum_smul_eq_sum_comp_perm_smul_iff /-- **Strict inequality case of the Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which antivary together, is strictly decreased by a permutation if and only if `f ∘ σ` and `g` do not antivary together. Stated by permuting the entries of `f`. -/ lemma antivary.sum_mul_lt_sum_comp_perm_mul_iff (hfg : antivary f g) : ∑ i, f i * g i < ∑ i, f (σ i) * g i ↔ ¬ antivary (f ∘ σ) g := hfg.sum_smul_lt_sum_comp_perm_smul_iff end mul
<unk> , Bas ( review of Beyond Chutzpah ) , NRC Handelsblad , February 24 , 2006 .
#!/usr/bin/env python # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: from __future__ import print_function # Python 2/3 compatibility __doc__ = \ """ Example of a script that crates a 'hierarchical roi' structure from the blob model of an image Needs matplotlib Author: Bertrand Thirion, 2008-2009 """ print(__doc__) import numpy as np try: import matplotlib.pyplot as plt except ImportError: raise RuntimeError("This script needs the matplotlib library") import nipy.labs.spatial_models.hroi as hroi import nipy.labs.utils.simul_multisubject_fmri_dataset as simul from nipy.labs.spatial_models.discrete_domain import domain_from_binary_array ############################################################################## # simulate the data shape = (60, 60) pos = np.array([[12, 14], [20, 20], [30, 20]]) ampli = np.array([3, 4, 4]) dataset = simul.surrogate_2d_dataset(n_subj=1, shape=shape, pos=pos, ampli=ampli, width=10.0).squeeze() # create a domain descriptor associated with this domain = domain_from_binary_array(dataset ** 2 > 0) nroi = hroi.HROI_as_discrete_domain_blobs(domain, dataset.ravel(), threshold=2., smin=5) n1 = nroi.copy() nroi.reduce_to_leaves() td = n1.make_forest().depth_from_leaves() root = np.argmax(td) lv = n1.make_forest().get_descendants(root) u = nroi.make_graph().cc() flat_data = dataset.ravel() activation = [flat_data[nroi.select_id(id, roi=False)] for id in nroi.get_id()] nroi.set_feature('activation', activation) label = np.reshape(n1.label, shape) label_ = np.reshape(nroi.label, shape) # make a figure plt.figure(figsize=(10, 4)) plt.subplot(1, 3, 1) plt.imshow(np.squeeze(dataset)) plt.title('Input map') plt.axis('off') plt.subplot(1, 3, 2) plt.title('Nested Rois') plt.imshow(label, interpolation='Nearest') plt.axis('off') plt.subplot(1, 3, 3) plt.title('Leave Rois') plt.imshow(label_, interpolation='Nearest') plt.axis('off') plt.show()
[STATEMENT] lemma NSLIMSEQ_add: "X \<longlonglongrightarrow>\<^sub>N\<^sub>S a \<Longrightarrow> Y \<longlonglongrightarrow>\<^sub>N\<^sub>S b \<Longrightarrow> (\<lambda>n. X n + Y n) \<longlonglongrightarrow>\<^sub>N\<^sub>S a + b" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>X \<longlonglongrightarrow>\<^sub>N\<^sub>S a; Y \<longlonglongrightarrow>\<^sub>N\<^sub>S b\<rbrakk> \<Longrightarrow> (\<lambda>n. X n + Y n) \<longlonglongrightarrow>\<^sub>N\<^sub>S a + b [PROOF STEP] by (auto intro: approx_add simp add: NSLIMSEQ_def)
import chapter_1 import tactic.simps namespace surreal /- This chapter is mostly about the protagonists trying to make sense of the text they found my defining some cleaner mathematical notation. They define surreals concisely like this: `x = (Xₗ, Xᵣ) where Xₗ ≱ Xᵣ` Here by `Xₗ ≱ Xᵣ` they mean that every `xₗ ≱ xᵣ` where `xₗ ∈ Xₗ` and `xᵣ ∈ Xᵣ`. Capitals are generally used to denote sets, and the same lowercase letters denote elements from those sets. In our case, the equivalent of `Xₗ` is simply `x.left`, and `Xᵣ` is `x.right`. For elements of those sets, we tend to call them `xl` and `xr`, because it's just more confortable to read and write without those tiny subscripts. -/ /- We'll not take a small pause to define ≱ both for surreals and sets of surreals, since Lean's `has_le` doesn't include this variant automatically, and it is used extensively moving forward. Note that < might not strictly equivalent to ≱, we might prove it later on, but we shouldn't take it for granted. -/ @[notation_class] class has_nge (α β: Type*) := (nge : α → β → Prop) /- Left-binding power 50 is the same as other inequality operators. https://leanprover.github.io/theorem_proving_in_lean/interacting_with_lean.html#notation https://github.com/leanprover/lean/blob/master/library/init/core.lean#L50 -/ infix ` ≱ `:50 := has_nge.nge def nge_num_num (x y: surreal): Prop := ¬(x ≥ y) @[simps] instance has_nge_num_num : has_nge surreal surreal := ⟨nge_num_num⟩ def nge_set_set (X Y: set surreal): Prop := ∀ x ∈ X, ∀ y ∈ Y, x ≱ y @[simps] instance has_nge_set_set : has_nge (set surreal) (set surreal) := ⟨nge_set_set⟩ /- Let's take a moment to consider `x = (Xₗ, Xᵣ) where Xₗ ≱ Xᵣ`. It is nice and concise, but in my opinion it doesn't exactly match the wording from the rules. It says: `no member of the left is greater than or equal to any member of the right set` This, to me, literally translates to something like: there doesn't exist a pair of members of the left and right sets that are greater than or equal to each other. Or in mathematical notation: `¬∃ xl ∈ x.left, ∃ xr ∈ x.right, xl ≥ xr`, which is our definition for `valid`. Whereas `Xₗ ≱ Xᵣ` here implies `∀ xl ∈ x.left, ∀ xr ∈ x.right, xl ≱ xr`, which is intuitively equivalent, but we should prove it is, just to be safe. -/ lemma rule_1_nge (x: surreal): valid x.left x.right ↔ x.left ≱ x.right := begin simp [valid, nge_num_num, nge_set_set], end /- Then they redefine the numbers with the new notation: `0 = (∅,∅)`, `-1 = (∅, {0})`, `1 = ({0}, ∅)` Then they check if they are valid, and they find out that: > If Xₗ or Xᵣ is empty, the condition Xₗ ≱ Xᵣ is true no matter what is in the other set. -/ lemma valid_empty (L R: set surreal): L = ∅ ∨ R = ∅ → valid L R := begin simp [valid], intro h0, apply or.elim h0, begin intro L0, intros l lL r rR hge, rw L0 at lL, exact lL, end, begin intro R0, intros l lL r rR hge, rw R0 at rR, exact rR, end end /- They also express `rule_2` with the new notation: `x ≤ y means Xₗ ≱ y and x ≱ Yᵣ` -/ /- They have now introduced ≱ between sets and numbers and viceversa. Let's define those then. -/ def nge_set_num (X: set surreal) (y: surreal) := ∀ x ∈ X, x ≱ y @[simps] instance has_nge_set_num : has_nge (set surreal) surreal := ⟨nge_set_num⟩ def nge_num_set (x: surreal) (Y: set surreal) := ∀ y ∈ Y, x ≱ y @[simps] instance has_nge_num_set : has_nge surreal (set surreal) := ⟨nge_num_set⟩ /- Again, the semantics differ somewhat from the original wording, so let's check that they are indeed equivalent to our original definition from `rule_2`. -/ lemma rule_2_nge (x y: surreal): x ≤ y ↔ x.left ≱ y ∧ x ≱ y.right := begin rw rule_2, simp [nge_set_num, nge_num_set, nge_num_num], end end surreal
-- Andreas, 2018-06-19, issue #3130 -- Produce parenthesized dot pattern .(p) instead of .p -- when is a projection. -- {-# OPTIONS -v reify.pat:80 #-} record R : Set₁ where field p : Set open R data D : (R → Set) → Set₁ where c : D p test : (f : R → Set) (x : D f) → Set₁ test f x = {!x!} -- split on x -- Expected: -- test .(p) c = ?
function b = mv_st ( m, n, nz_num, row, col, a, x ) %*****************************************************************************80 % %% MV_ST multiplies a sparse triple matrix times a vector. % % Licensing: % % This code is distributed under the GNU LGPL license. % % Modified: % % 04 June 2014 % % Author: % % John Burkardt % % Parameters: % % Input, integer M, N, the number of rows and columns. % % Input, integer NZ_NUM, the number of nonzero values. % % Input, integer ROW(NZ_NUM), COL(NZ_NUM), the row and column indices. % % Input, real A(NZ_NUM), the nonzero values in the M by N matrix. % % Input, real X(N), the vector to be multiplied. % % Output, real B(M), the product A*X. % b = zeros ( m, 1 ); for k = 1 : nz_num b(row(k)) = b(row(k)) + a(k) * x(col(k)); end return end
#' Baffle: Waffle graphs with base graphics #' #' The package provides functions to make waffle graphs in the base graphics. #' #' @docType package #' @name baffle NULL #> NULL
If $N'$ is a sub-$\sigma$-algebra of $N$ and $M'$ is a super-$\sigma$-algebra of $M$, then any $N$-measurable $M$-measurable set is $N'$-measurable $M'$-measurable.
1 -> 2 4 -> 1 3 -> 4
Formal statement is: lemma Inf_insert: fixes S :: "real set" shows "bounded S \<Longrightarrow> Inf (insert x S) = (if S = {} then x else min x (Inf S))" Informal statement is: If $S$ is a bounded set, then $\inf(S \cup \{x\}) = \min\{x, \inf S\}$.
lemma continuous_at_avoid: fixes f :: "'a::metric_space \<Rightarrow> 'b::t1_space" assumes "continuous (at x) f" and "f x \<noteq> a" shows "\<exists>e>0. \<forall>y. dist x y < e \<longrightarrow> f y \<noteq> a"
-- @@stderr -- dtrace: failed to compile script test/unittest/clauses/err.D_IDENT_UNDEF.both.d: [D_IDENT_UNDEF] line 17: failed to resolve x: Unknown variable name
module Test.Main import Data.List import Data.String import Hedgehog import System import System.Console.GetOpt import System.File import Test.Lexer import Test.Parser import Text.WebIDL.Codegen as Codegen import Text.WebIDL.Types import Text.WebIDL.Parser import Text.PrettyPrint.Prettyprinter -------------------------------------------------------------------------------- -- Command line options -------------------------------------------------------------------------------- record Config where constructor MkConfig numTests : TestLimit files : List String init : List String -> Config init = MkConfig 100 setTests : String -> Config -> Either (List String) Config setTests s c = maybe (Left ["Not a natural number: " ++ s]) (\n => Right $ record { numTests = MkTagged n} c) (parsePositive {a = Nat} s) descs : List $ OptDescr (Config -> Either (List String) Config) descs = [ MkOpt ['n'] ["testlimit"] (ReqArg setTests "<tests>") "number of tests to be passed by each property" ] applyArgs : List String -> Either (List String) Config applyArgs args = case getOpt RequireOrder descs args of MkResult opts n [] [] => foldl (>>=) (Right $ init n) opts MkResult _ _ u e => Left $ map unknown u ++ e where unknown : String -> String unknown = ("Unknown option: " ++) adjust : Config -> Group -> Group adjust (MkConfig t _) = withTests t -------------------------------------------------------------------------------- -- Main Function -------------------------------------------------------------------------------- run : Config -> IO () run cfg = do ignore . checkGroup $ adjust cfg Test.Lexer.props ignore . checkGroup $ adjust cfg Test.Parser.props main : IO () main = do (pn :: args) <- getArgs | Nil => putStrLn "Missing executable name. Aborting..." Right config <- pure $ applyArgs args | Left es => traverse_ putStrLn es run config
Outgoing Links ..
State Before: α : Type u_1 E : Type u_2 F : Type ?u.245931 m0 : MeasurableSpace α inst✝⁶ : NormedAddCommGroup E inst✝⁵ : NormedSpace ℝ E inst✝⁴ : CompleteSpace E inst✝³ : NormedAddCommGroup F inst✝² : NormedSpace ℝ F inst✝¹ : CompleteSpace F μ : MeasureTheory.Measure α s : Set E t : Set α f : α → E g : E → ℝ C : ℝ inst✝ : IsFiniteMeasure μ hs : Convex ℝ s hsc : IsClosed s hμ : μ ≠ 0 hfs : ∀ᵐ (x : α) ∂μ, f x ∈ s hfi : Integrable f ⊢ (⨍ (x : α), f x ∂μ) ∈ s State After: α : Type u_1 E : Type u_2 F : Type ?u.245931 m0 : MeasurableSpace α inst✝⁶ : NormedAddCommGroup E inst✝⁵ : NormedSpace ℝ E inst✝⁴ : CompleteSpace E inst✝³ : NormedAddCommGroup F inst✝² : NormedSpace ℝ F inst✝¹ : CompleteSpace F μ : MeasureTheory.Measure α s : Set E t : Set α f : α → E g : E → ℝ C : ℝ inst✝ : IsFiniteMeasure μ hs : Convex ℝ s hsc : IsClosed s hμ : μ ≠ 0 hfs : ∀ᵐ (x : α) ∂μ, f x ∈ s hfi : Integrable f this : IsProbabilityMeasure ((↑↑μ univ)⁻¹ • μ) ⊢ (⨍ (x : α), f x ∂μ) ∈ s Tactic: have : IsProbabilityMeasure ((μ univ)⁻¹ • μ) := isProbabilityMeasureSmul hμ State Before: α : Type u_1 E : Type u_2 F : Type ?u.245931 m0 : MeasurableSpace α inst✝⁶ : NormedAddCommGroup E inst✝⁵ : NormedSpace ℝ E inst✝⁴ : CompleteSpace E inst✝³ : NormedAddCommGroup F inst✝² : NormedSpace ℝ F inst✝¹ : CompleteSpace F μ : MeasureTheory.Measure α s : Set E t : Set α f : α → E g : E → ℝ C : ℝ inst✝ : IsFiniteMeasure μ hs : Convex ℝ s hsc : IsClosed s hμ : μ ≠ 0 hfs : ∀ᵐ (x : α) ∂μ, f x ∈ s hfi : Integrable f this : IsProbabilityMeasure ((↑↑μ univ)⁻¹ • μ) ⊢ (⨍ (x : α), f x ∂μ) ∈ s State After: α : Type u_1 E : Type u_2 F : Type ?u.245931 m0 : MeasurableSpace α inst✝⁶ : NormedAddCommGroup E inst✝⁵ : NormedSpace ℝ E inst✝⁴ : CompleteSpace E inst✝³ : NormedAddCommGroup F inst✝² : NormedSpace ℝ F inst✝¹ : CompleteSpace F μ : MeasureTheory.Measure α s : Set E t : Set α f : α → E g : E → ℝ C : ℝ inst✝ : IsFiniteMeasure μ hs : Convex ℝ s hsc : IsClosed s hμ : μ ≠ 0 hfs : ∀ᵐ (x : α) ∂μ, f x ∈ s hfi : Integrable f this : IsProbabilityMeasure ((↑↑μ univ)⁻¹ • μ) ⊢ (↑↑μ univ)⁻¹ • μ ≪ μ Tactic: refine' hs.integral_mem hsc (ae_mono' _ hfs) hfi.to_average State Before: α : Type u_1 E : Type u_2 F : Type ?u.245931 m0 : MeasurableSpace α inst✝⁶ : NormedAddCommGroup E inst✝⁵ : NormedSpace ℝ E inst✝⁴ : CompleteSpace E inst✝³ : NormedAddCommGroup F inst✝² : NormedSpace ℝ F inst✝¹ : CompleteSpace F μ : MeasureTheory.Measure α s : Set E t : Set α f : α → E g : E → ℝ C : ℝ inst✝ : IsFiniteMeasure μ hs : Convex ℝ s hsc : IsClosed s hμ : μ ≠ 0 hfs : ∀ᵐ (x : α) ∂μ, f x ∈ s hfi : Integrable f this : IsProbabilityMeasure ((↑↑μ univ)⁻¹ • μ) ⊢ (↑↑μ univ)⁻¹ • μ ≪ μ State After: no goals Tactic: exact AbsolutelyContinuous.smul (refl _) _
{-# OPTIONS --without-K --safe #-} open import Categories.Category -- Equalizers in a Category C module Categories.Diagram.Equalizer {o ℓ e} (C : Category o ℓ e) where open Category C open HomReasoning open import Level open import Data.Product as Σ open import Function using (_$_) open import Categories.Morphism C open import Categories.Morphism.Reasoning C private variable A B X : Obj h i j k : A ⇒ B record Equalizer (f g : A ⇒ B) : Set (o ⊔ ℓ ⊔ e) where field {obj} : Obj arr : obj ⇒ A equality : f ∘ arr ≈ g ∘ arr equalize : ∀ {h : X ⇒ A} → f ∘ h ≈ g ∘ h → X ⇒ obj universal : ∀ {eq : f ∘ h ≈ g ∘ h} → h ≈ arr ∘ equalize eq unique : ∀ {eq : f ∘ h ≈ g ∘ h} → h ≈ arr ∘ i → i ≈ equalize eq unique′ : (eq eq′ : f ∘ h ≈ g ∘ h) → equalize eq ≈ equalize eq′ unique′ eq eq′ = unique universal id-equalize : id ≈ equalize equality id-equalize = unique (sym identityʳ) equalize-resp-≈ : ∀ {eq : f ∘ h ≈ g ∘ h} {eq′ : f ∘ i ≈ g ∘ i} → h ≈ i → equalize eq ≈ equalize eq′ equalize-resp-≈ {h = h} {i = i} {eq = eq} {eq′ = eq′} h≈i = unique $ begin i ≈˘⟨ h≈i ⟩ h ≈⟨ universal ⟩ arr ∘ equalize eq ∎ equalize-resp-≈′ : (eq : f ∘ h ≈ g ∘ h) → (eq′ : f ∘ i ≈ g ∘ i) → h ≈ i → j ≈ equalize eq → k ≈ equalize eq′ → j ≈ k equalize-resp-≈′ {j = j} {k = k} eq eq′ h≈i eqj eqk = begin j ≈⟨ eqj ⟩ equalize eq ≈⟨ equalize-resp-≈ h≈i ⟩ equalize eq′ ≈˘⟨ eqk ⟩ k ∎ equality-∘ : f ∘ arr ∘ h ≈ g ∘ arr ∘ h equality-∘ {h = h} = begin f ∘ arr ∘ h ≈⟨ pullˡ equality ⟩ (g ∘ arr) ∘ h ≈⟨ assoc ⟩ g ∘ arr ∘ h ∎ unique-diagram : arr ∘ h ≈ arr ∘ i → h ≈ i unique-diagram {h = h} {i = i} eq = begin h ≈⟨ unique (sym eq) ⟩ equalize (extendʳ equality) ≈˘⟨ unique refl ⟩ i ∎ Equalizer⇒Mono : (e : Equalizer h i) → Mono (Equalizer.arr e) Equalizer⇒Mono e f g eq = equalize-resp-≈′ equality-∘ equality-∘ eq (unique refl) (unique refl) where open Equalizer e
Formal statement is: proposition compact_def: \<comment> \<open>this is the definition of compactness in HOL Light\<close> "compact (S :: 'a::metric_space set) \<longleftrightarrow> (\<forall>f. (\<forall>n. f n \<in> S) \<longrightarrow> (\<exists>l\<in>S. \<exists>r::nat\<Rightarrow>nat. strict_mono r \<and> (f \<circ> r) \<longlonglongrightarrow> l))" Informal statement is: A set $S$ is compact if and only if every sequence in $S$ has a convergent subsequence.
theory T28 imports Main begin lemma "( (\<forall> x::nat. \<forall> y::nat. meet(x, y) = meet(y, x)) & (\<forall> x::nat. \<forall> y::nat. join(x, y) = join(y, x)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, meet(y, z)) = meet(meet(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(x, join(y, z)) = join(join(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. meet(x, join(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. join(x, meet(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, join(y, z)) = join(mult(x, y), mult(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(join(x, y), z) = join(mult(x, z), mult(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, over(join(mult(x, y), z), y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(y, undr(x, join(mult(x, y), z))) = y) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(over(x, y), y), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(y, undr(y, x)), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(meet(x, y), z) = meet(mult(x, z), mult(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(join(x, y), z) = join(over(x, z), over(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(x, meet(y, z)) = join(over(x, y), over(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(meet(x, y), z) = join(undr(x, z), undr(y, z))) & (\<forall> x::nat. \<forall> y::nat. invo(join(x, y)) = meet(invo(x), invo(y))) & (\<forall> x::nat. \<forall> y::nat. invo(meet(x, y)) = join(invo(x), invo(y))) & (\<forall> x::nat. invo(invo(x)) = x) ) \<longrightarrow> (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, meet(y, z)) = meet(mult(x, y), mult(x, z))) " nitpick[card nat=4,timeout=86400] oops end
[GOAL] G : Type u_1 inst✝ : Group G a b : G n m : ℤ ⊢ a * b ^ n * b ^ m = a * b ^ (n + m) [PROOFSTEP] rw [mul_assoc, ← zpow_add] [GOAL] G : Type u_1 inst✝ : Group G a b : G m : ℤ ⊢ a * b * b ^ m = a * b ^ (m + 1) [PROOFSTEP] rw [mul_assoc, mul_self_zpow] [GOAL] G : Type u_1 inst✝ : Group G a b : G n : ℤ ⊢ a * b ^ n * b = a * b ^ (n + 1) [PROOFSTEP] rw [mul_assoc, mul_zpow_self]
If a set of vectors is pairwise orthogonal, then it is finite.
# read_marker.r # # Copyright (c) 2020 VIB (Belgium) & Babraham Institute (United Kingdom) # # Software written by Carlos P. Roca, as research funded by the European Union. # # This software may be modified and distributed under the terms of the MIT # license. See the LICENSE file for details. #' Read markers in a set of flow controls #' #' Returns a dataframe and writes a csv file with the common set of markers in a #' set of single-color controls, together with corrected names in case of #' presence of forbidden characters. #' #' @param control.dir Character string with the directory with the set of #' single-color controls or an object of class \code{cytoset}. #' @param control.def.file Character string with the CSV file or a #' \code{data.frame} defining the names and channels of the single-color #' controls. #' @param asp List with AutoSpill parameters. #' #' @return Dataframe with the original and corrected names of markers. #' #' @references Roca \emph{et al}: AutoSpill: A method for calculating spillover #' coefficients to compensate or unmix high-parameter flow cytometry data. #' \emph{bioRxiv} 2020.06.29.177196; #' \href{https://doi.org/10.1101/2020.06.29.177196}{doi:10.1101/2020.06.29.177196} #' (2020). #' #' @seealso \code{\link{get.autospill.param}}. #' #' @export read.marker <- function( control.dir, control.def.file, asp ) { # read markers from file if available if ( ! is.null( asp$marker.file.name ) && file.exists( asp$marker.file.name ) ) return( read.table( asp$marker.file.name, sep = ",", stringsAsFactors = FALSE ) ) # read definition of controls if(is.null(dim(control.def.file))) { control <- read.csv( control.def.file, stringsAsFactors = FALSE ) } else { control <- control.def.file } check.critical( anyDuplicated( control$file.name ) == 0, "duplicated filenames in fcs data" ) # get common set of markers from controls flow.set.marker.all <- lapply( control$filename, function( cf ) { if(is(control.dir, "flowSet")) { colnames( control.dir[[cf]] ) } else { colnames( read.FCS( file.path(control.dir, cf), transformation = NULL ) ) } }) flow.set.marker <- flow.set.marker.all[[ 1 ]] for( fsm in flow.set.marker.all[ -1 ] ) flow.set.marker <- intersect( flow.set.marker, fsm ) # correct marker names flow.set.marker.corrected <- flow.set.marker for ( fmfc.idx in 1 : nchar( asp$marker.forbidden.char ) ) { fmfc <- substr( asp$marker.forbidden.char, fmfc.idx, fmfc.idx ) flow.set.marker.corrected <- gsub( fmfc, asp$marker.substitution.char, flow.set.marker.corrected, fixed = TRUE ) } # save list of markers flow.set.marker.table <- data.frame( flow.set.marker, flow.set.marker.corrected, stringsAsFactors = FALSE ) if ( ! is.null( asp$marker.file.name ) ) write.table( flow.set.marker.table, file = asp$marker.file.name, row.names = FALSE, col.names = FALSE, sep = "," ) flow.set.marker.table }
= = = Places of interest = = =
[STATEMENT] lemma Liminf_llist_ltl: "\<not> lnull (ltl Xs) \<Longrightarrow> Liminf_llist Xs = Liminf_llist (ltl Xs)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<not> lnull (ltl Xs) \<Longrightarrow> Liminf_llist Xs = Liminf_llist (ltl Xs) [PROOF STEP] by (metis Liminf_llist_LCons lhd_LCons_ltl lnull_ltlI)
[GOAL] α : Type u β : Type v γ : Type w R : Type x inst✝ : NonUnitalNonAssocRing R a b : R h : Commute a b ⊢ a * a - b * b = (a + b) * (a - b) [PROOFSTEP] rw [add_mul, mul_sub, mul_sub, h.eq, sub_add_sub_cancel] [GOAL] α : Type u β : Type v γ : Type w R : Type x inst✝ : NonUnitalNonAssocRing R a b : R h : Commute a b ⊢ a * a - b * b = (a - b) * (a + b) [PROOFSTEP] rw [mul_add, sub_mul, sub_mul, h.eq, sub_add_sub_cancel] [GOAL] α : Type u β : Type v γ : Type w R : Type x inst✝¹ : NonUnitalNonAssocRing R inst✝ : NoZeroDivisors R a b : R h : Commute a b ⊢ a * a = b * b ↔ a = b ∨ a = -b [PROOFSTEP] rw [← sub_eq_zero, h.mul_self_sub_mul_self_eq, mul_eq_zero, or_comm, sub_eq_zero, add_eq_zero_iff_eq_neg] [GOAL] α : Type u β : Type v γ : Type w R : Type x inst✝ : NonAssocRing R a : R ⊢ a * a - 1 = (a + 1) * (a - 1) [PROOFSTEP] rw [← (Commute.one_right a).mul_self_sub_mul_self_eq, mul_one] [GOAL] α : Type u β : Type v γ : Type w R : Type x inst✝¹ : NonAssocRing R inst✝ : NoZeroDivisors R a : R ⊢ a * a = 1 ↔ a = 1 ∨ a = -1 [PROOFSTEP] rw [← (Commute.one_right a).mul_self_eq_mul_self_iff, mul_one] [GOAL] α : Type u β : Type v γ : Type w R : Type x inst✝¹ : Ring R inst✝ : NoZeroDivisors R u : Rˣ ⊢ u⁻¹ = u ↔ u = 1 ∨ u = -1 [PROOFSTEP] rw [inv_eq_iff_mul_eq_one] [GOAL] α : Type u β : Type v γ : Type w R : Type x inst✝¹ : Ring R inst✝ : NoZeroDivisors R u : Rˣ ⊢ u * u = 1 ↔ u = 1 ∨ u = -1 [PROOFSTEP] simp only [ext_iff] [GOAL] α : Type u β : Type v γ : Type w R : Type x inst✝¹ : Ring R inst✝ : NoZeroDivisors R u : Rˣ ⊢ ↑(u * u) = ↑1 ↔ ↑u = ↑1 ∨ ↑u = ↑(-1) [PROOFSTEP] push_cast [GOAL] α : Type u β : Type v γ : Type w R : Type x inst✝¹ : Ring R inst✝ : NoZeroDivisors R u : Rˣ ⊢ ↑u * ↑u = 1 ↔ ↑u = 1 ∨ ↑u = -1 [PROOFSTEP] exact mul_self_eq_one_iff
theory T150 imports Main begin lemma "( (\<forall> x::nat. \<forall> y::nat. meet(x, y) = meet(y, x)) & (\<forall> x::nat. \<forall> y::nat. join(x, y) = join(y, x)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, meet(y, z)) = meet(meet(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(x, join(y, z)) = join(join(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. meet(x, join(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. join(x, meet(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, join(y, z)) = join(mult(x, y), mult(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(join(x, y), z) = join(mult(x, z), mult(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, over(join(mult(x, y), z), y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(y, undr(x, join(mult(x, y), z))) = y) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(over(x, y), y), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(y, undr(y, x)), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, meet(y, z)) = meet(mult(x, y), mult(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(meet(x, y), z) = meet(mult(x, z), mult(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(x, join(y, z)) = join(undr(x, y), undr(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(meet(x, y), z) = join(undr(x, z), undr(y, z))) & (\<forall> x::nat. \<forall> y::nat. invo(join(x, y)) = meet(invo(x), invo(y))) & (\<forall> x::nat. \<forall> y::nat. invo(meet(x, y)) = join(invo(x), invo(y))) & (\<forall> x::nat. invo(invo(x)) = x) ) \<longrightarrow> (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(x, meet(y, z)) = join(over(x, y), over(x, z))) " nitpick[card nat=4,timeout=86400] oops end
[GOAL] α : Type u β : Type v γ : Type w R : Type x inst✝² : Mul R inst✝¹ : Add R inst✝ : RightDistribClass R a b c d : R ⊢ (a + b + c) * d = a * d + b * d + c * d [PROOFSTEP] simp [right_distrib] [GOAL] α : Type u β : Type v γ : Type w R : Type x inst✝² : Add α inst✝¹ : MulOneClass α inst✝ : RightDistribClass α a b : α ⊢ (a + 1) * b = a * b + b [PROOFSTEP] rw [add_mul, one_mul] [GOAL] α : Type u β : Type v γ : Type w R : Type x inst✝² : Add α inst✝¹ : MulOneClass α inst✝ : LeftDistribClass α a b : α ⊢ a * (b + 1) = a * b + a [PROOFSTEP] rw [mul_add, mul_one] [GOAL] α : Type u β : Type v γ : Type w R : Type x inst✝² : Add α inst✝¹ : MulOneClass α inst✝ : RightDistribClass α a b : α ⊢ (1 + a) * b = b + a * b [PROOFSTEP] rw [add_mul, one_mul] [GOAL] α : Type u β : Type v γ : Type w R : Type x inst✝² : Add α inst✝¹ : MulOneClass α inst✝ : LeftDistribClass α a b : α ⊢ a * (1 + b) = a + a * b [PROOFSTEP] rw [mul_add, mul_one] [GOAL] α : Type u β : Type v γ : Type w R : Type x inst✝ : NonAssocSemiring α n : α ⊢ 1 * n + 1 * n = n + n [PROOFSTEP] rw [one_mul] [GOAL] α : Type u β : Type v γ : Type w R : Type x inst✝ : NonAssocSemiring α n : α ⊢ n * 1 + n * 1 = n + n [PROOFSTEP] rw [mul_one] [GOAL] α✝ : Type u β : Type v γ : Type w R : Type x α : Type u_1 inst✝¹ : Mul α P : Prop inst✝ : Decidable P a b c : α ⊢ (a * if P then b else c) = if P then a * b else a * c [PROOFSTEP] split_ifs [GOAL] case pos α✝ : Type u β : Type v γ : Type w R : Type x α : Type u_1 inst✝¹ : Mul α P : Prop inst✝ : Decidable P a b c : α h✝ : P ⊢ a * b = a * b [PROOFSTEP] rfl [GOAL] case neg α✝ : Type u β : Type v γ : Type w R : Type x α : Type u_1 inst✝¹ : Mul α P : Prop inst✝ : Decidable P a b c : α h✝ : ¬P ⊢ a * c = a * c [PROOFSTEP] rfl [GOAL] α✝ : Type u β : Type v γ : Type w R : Type x α : Type u_1 inst✝¹ : Mul α P : Prop inst✝ : Decidable P a b c : α ⊢ (if P then a else b) * c = if P then a * c else b * c [PROOFSTEP] split_ifs [GOAL] case pos α✝ : Type u β : Type v γ : Type w R : Type x α : Type u_1 inst✝¹ : Mul α P : Prop inst✝ : Decidable P a b c : α h✝ : P ⊢ a * c = a * c [PROOFSTEP] rfl [GOAL] case neg α✝ : Type u β : Type v γ : Type w R : Type x α : Type u_1 inst✝¹ : Mul α P : Prop inst✝ : Decidable P a b c : α h✝ : ¬P ⊢ b * c = b * c [PROOFSTEP] rfl [GOAL] α✝ : Type u β : Type v γ : Type w R : Type x α : Type u_1 inst✝¹ : MulZeroOneClass α P : Prop inst✝ : Decidable P a : α ⊢ (a * if P then 1 else 0) = if P then a else 0 [PROOFSTEP] simp [GOAL] α✝ : Type u β : Type v γ : Type w R : Type x α : Type u_1 inst✝¹ : MulZeroOneClass α P : Prop inst✝ : Decidable P a : α ⊢ (if P then 1 else 0) * a = if P then a else 0 [PROOFSTEP] simp [GOAL] α✝ : Type u β : Type v γ : Type w R : Type x α : Type u_1 inst✝¹ : MulZeroClass α P : Prop inst✝ : Decidable P a b : α ⊢ (if P then a * b else 0) = (if P then a else 0) * b [PROOFSTEP] by_cases h : P [GOAL] case pos α✝ : Type u β : Type v γ : Type w R : Type x α : Type u_1 inst✝¹ : MulZeroClass α P : Prop inst✝ : Decidable P a b : α h : P ⊢ (if P then a * b else 0) = (if P then a else 0) * b [PROOFSTEP] simp [h] [GOAL] case neg α✝ : Type u β : Type v γ : Type w R : Type x α : Type u_1 inst✝¹ : MulZeroClass α P : Prop inst✝ : Decidable P a b : α h : ¬P ⊢ (if P then a * b else 0) = (if P then a else 0) * b [PROOFSTEP] simp [h] [GOAL] α✝ : Type u β : Type v γ : Type w R : Type x α : Type u_1 inst✝¹ : MulZeroClass α P : Prop inst✝ : Decidable P a b : α ⊢ (if P then a * b else 0) = a * if P then b else 0 [PROOFSTEP] by_cases h : P [GOAL] case pos α✝ : Type u β : Type v γ : Type w R : Type x α : Type u_1 inst✝¹ : MulZeroClass α P : Prop inst✝ : Decidable P a b : α h : P ⊢ (if P then a * b else 0) = a * if P then b else 0 [PROOFSTEP] simp [h] [GOAL] case neg α✝ : Type u β : Type v γ : Type w R : Type x α : Type u_1 inst✝¹ : MulZeroClass α P : Prop inst✝ : Decidable P a b : α h : ¬P ⊢ (if P then a * b else 0) = a * if P then b else 0 [PROOFSTEP] simp [h] [GOAL] α✝ : Type u β : Type v γ : Type w R : Type x α : Type u_1 inst✝² : MulZeroClass α P Q : Prop inst✝¹ : Decidable P inst✝ : Decidable Q a b : α ⊢ (if P ∧ Q then a * b else 0) = (if P then a else 0) * if Q then b else 0 [PROOFSTEP] simp only [← ite_and, ite_mul, mul_ite, mul_zero, zero_mul, and_comm] [GOAL] α : Type u β : Type v γ : Type w R : Type x inst✝ : CommSemiring α a✝ b✝ c a b : α ⊢ (a + b) * (a + b) = a * a + 2 * a * b + b * b [PROOFSTEP] simp only [two_mul, add_mul, mul_add, add_assoc, mul_comm b] [GOAL] α : Type u β : Type v γ : Type w R : Type x inst✝¹ : Mul α inst✝ : HasDistribNeg α a b : α ⊢ -a * -b = a * b [PROOFSTEP] simp [GOAL] α : Type u β : Type v γ : Type w R : Type x inst✝¹ : Mul α inst✝ : HasDistribNeg α a b : α ⊢ -a * b = a * -b [PROOFSTEP] simp [GOAL] α : Type u β : Type v γ : Type w R : Type x inst✝¹ : MulOneClass α inst✝ : HasDistribNeg α a : α ⊢ -a = -1 * a [PROOFSTEP] simp [GOAL] α : Type u β : Type v γ : Type w R : Type x inst✝¹ : MulOneClass α inst✝ : HasDistribNeg α a : α ⊢ a * -1 = -a [PROOFSTEP] simp [GOAL] α : Type u β : Type v γ : Type w R : Type x inst✝¹ : MulOneClass α inst✝ : HasDistribNeg α a : α ⊢ -1 * a = -a [PROOFSTEP] simp [GOAL] α : Type u β : Type v γ : Type w R : Type x inst✝¹ : MulZeroClass α inst✝ : HasDistribNeg α src✝¹ : Zero α := inferInstanceAs (Zero α) src✝ : InvolutiveNeg α := inferInstanceAs (InvolutiveNeg α) ⊢ -0 = 0 [PROOFSTEP] rw [← zero_mul (0 : α), ← neg_mul, mul_zero, mul_zero] [GOAL] α : Type u β : Type v γ : Type w R : Type x inst✝ : NonUnitalNonAssocRing α a b : α ⊢ -a * b + a * b = 0 [PROOFSTEP] rw [← right_distrib, add_left_neg, zero_mul] [GOAL] α : Type u β : Type v γ : Type w R : Type x inst✝ : NonUnitalNonAssocRing α a b : α ⊢ a * -b + a * b = 0 [PROOFSTEP] rw [← left_distrib, add_left_neg, mul_zero] [GOAL] α : Type u β : Type v γ : Type w R : Type x inst✝ : NonUnitalNonAssocRing α a b c : α ⊢ a * (b - c) = a * b - a * c [PROOFSTEP] simpa only [sub_eq_add_neg, neg_mul_eq_mul_neg] using mul_add a b (-c) [GOAL] α : Type u β : Type v γ : Type w R : Type x inst✝ : NonUnitalNonAssocRing α a b c : α ⊢ (a - b) * c = a * c - b * c [PROOFSTEP] simpa only [sub_eq_add_neg, neg_mul_eq_neg_mul] using add_mul a (-b) c [GOAL] α : Type u β : Type v γ : Type w R : Type x inst✝ : NonUnitalNonAssocRing α a b c d e : α ⊢ a * e + c = b * e + d ↔ a * e + c = d + b * e [PROOFSTEP] simp [add_comm] [GOAL] α : Type u β : Type v γ : Type w R : Type x inst✝ : NonUnitalNonAssocRing α a b c d e : α h : a * e + c = d + b * e ⊢ a * e + c - b * e = d [PROOFSTEP] rw [h] [GOAL] α : Type u β : Type v γ : Type w R : Type x inst✝ : NonUnitalNonAssocRing α a b c d e : α h : a * e + c = d + b * e ⊢ d + b * e - b * e = d [PROOFSTEP] simp [GOAL] α : Type u β : Type v γ : Type w R : Type x inst✝ : NonUnitalNonAssocRing α a b c d e : α h : a * e + c - b * e = d ⊢ a * e + c = d + b * e [PROOFSTEP] rw [← h] [GOAL] α : Type u β : Type v γ : Type w R : Type x inst✝ : NonUnitalNonAssocRing α a b c d e : α h : a * e + c - b * e = d ⊢ a * e + c = a * e + c - b * e + b * e [PROOFSTEP] simp [GOAL] α : Type u β : Type v γ : Type w R : Type x inst✝ : NonUnitalNonAssocRing α a b c d e : α ⊢ a * e + c - b * e = d ↔ (a - b) * e + c = d [PROOFSTEP] simp [sub_mul, sub_add_eq_add_sub] [GOAL] α : Type u β : Type v γ : Type w R : Type x inst✝ : NonUnitalNonAssocRing α a b c d e : α h : a * e + c = b * e + d ⊢ (a - b) * e + c = a * e + c - b * e [PROOFSTEP] simp [sub_mul, sub_add_eq_add_sub] [GOAL] α : Type u β : Type v γ : Type w R : Type x inst✝ : NonUnitalNonAssocRing α a b c d e : α h : a * e + c = b * e + d ⊢ a * e + c - b * e = d [PROOFSTEP] rw [h] [GOAL] α : Type u β : Type v γ : Type w R : Type x inst✝ : NonUnitalNonAssocRing α a b c d e : α h : a * e + c = b * e + d ⊢ b * e + d - b * e = d [PROOFSTEP] simp [@add_sub_cancel α] [GOAL] α : Type u β : Type v γ : Type w R : Type x inst✝ : NonAssocRing α a b : α ⊢ (a - 1) * b = a * b - b [PROOFSTEP] rw [sub_mul, one_mul] [GOAL] α : Type u β : Type v γ : Type w R : Type x inst✝ : NonAssocRing α a b : α ⊢ a * (b - 1) = a * b - a [PROOFSTEP] rw [mul_sub, mul_one] [GOAL] α : Type u β : Type v γ : Type w R : Type x inst✝ : NonAssocRing α a b : α ⊢ (1 - a) * b = b - a * b [PROOFSTEP] rw [sub_mul, one_mul] [GOAL] α : Type u β : Type v γ : Type w R : Type x inst✝ : NonAssocRing α a b : α ⊢ a * (1 - b) = a - a * b [PROOFSTEP] rw [mul_sub, mul_one] [GOAL] α : Type u β : Type v γ : Type w R : Type x inst✝ : Ring α a✝ b c d e : α src✝ : Ring α := inst✝ a : α ⊢ 0 * a + 0 * a = 0 * a + 0 [PROOFSTEP] rw [← add_mul, zero_add, add_zero] [GOAL] α : Type u β : Type v γ : Type w R : Type x inst✝ : Ring α a✝ b c d e : α src✝ : Ring α := inst✝ a : α ⊢ a * 0 + a * 0 = a * 0 + 0 [PROOFSTEP] rw [← mul_add, add_zero, add_zero] [GOAL] α : Type u β : Type v γ : Type w R : Type x inst✝ : Ring α a✝ b c d e : α src✝ : Ring α := inst✝ a : α ⊢ 0 * a + 0 * a = 0 * a + 0 [PROOFSTEP] rw [← add_mul, zero_add, add_zero] [GOAL] α : Type u β : Type v γ : Type w R : Type x inst✝ : Ring α a✝ b c d e : α src✝ : Ring α := inst✝ a : α ⊢ a * 0 + a * 0 = a * 0 + 0 [PROOFSTEP] rw [← mul_add, add_zero, add_zero]
State Before: α : Type u_1 inst✝ : LinearOrderedField α x y : α ⊢ const x ≤ const y ↔ x ≤ y State After: α : Type u_1 inst✝ : LinearOrderedField α x y : α ⊢ const x ≤ const y ↔ x < y ∨ x = y Tactic: rw [le_iff_lt_or_eq] State Before: α : Type u_1 inst✝ : LinearOrderedField α x y : α ⊢ const x ≤ const y ↔ x < y ∨ x = y State After: no goals Tactic: exact or_congr const_lt const_equiv
(* Title: HOL/Auth/n_germanSimp_lemma_inv__44_on_rules.thy Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences *) header{*The n_germanSimp Protocol Case Study*} theory n_germanSimp_lemma_inv__44_on_rules imports n_germanSimp_lemma_on_inv__44 begin section{*All lemmas on causal relation between inv__44*} lemma lemma_inv__44_on_rules: assumes b1: "r \<in> rules N" and b2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__44 p__Inv4)" shows "invHoldForRule s f r (invariants N)" proof - have c1: "(\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvReqS N i)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvReqE__part__0 N i)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvReqE__part__1 N i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendInvAck i)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendGntS i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendGntE N i)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvGntS i)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvGntE i)" apply (cut_tac b1, auto) done moreover { assume d1: "(\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_StoreVsinv__44) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqS N i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvReqSVsinv__44) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqE__part__0 N i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvReqE__part__0Vsinv__44) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqE__part__1 N i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvReqE__part__1Vsinv__44) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendInv__part__0Vsinv__44) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendInv__part__1Vsinv__44) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInvAck i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendInvAckVsinv__44) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvInvAckVsinv__44) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendGntS i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendGntSVsinv__44) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendGntE N i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendGntEVsinv__44) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntS i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvGntSVsinv__44) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntE i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvGntEVsinv__44) done } ultimately show "invHoldForRule s f r (invariants N)" by satx qed end
Formal statement is: lemma DERIV_pow2: "DERIV (\<lambda>x. x ^ Suc n) x :> real (Suc n) * (x ^ n)" Informal statement is: The derivative of $x^{n+1}$ is $(n+1)x^n$.
(** CoLoR, a Coq library on rewriting and termination. See the COPYRIGHTS and LICENSE files. - Adam Koprowski, 2004-09-06 - William Delobel, 2005-10-07 This file provides some basic results concerning relations that were missing in the standard library. *) Set Implicit Arguments. From Coq Require Export Relations. From Coq Require Import Max Arith Setoid Morphisms Basics. From CoLoR Require Import LogicUtil RelUtil. (***********************************************************************) (** strict order *) Section StrictOrder. Variables (A : Type) (R : relation A). Record strict_order : Prop := { sord_trans : transitive R; sord_irrefl : irreflexive R }. Variable so : strict_order. Lemma so_not_symmetric : forall a b, R a b -> R b a -> False. Proof. unfold not; intros a b Rab Rba. exact (sord_irrefl so (sord_trans so Rab Rba)). Qed. Variables (eq : relation A) (Req_compat : Proper (eq ==> eq ==> impl) R) (eq_Equivalence : Equivalence eq). Existing Instance eq_Equivalence. Existing Instance Req_compat. Lemma so_strict : forall x y, eq x y -> ~R x y. Proof. intros x y xy. rewrite xy. apply sord_irrefl. hyp. Qed. End StrictOrder. (***********************************************************************) (** module types for setoids with decidable equality *) Module Type SetA. Parameter A : Type. End SetA. Module Type Eqset. Parameter A : Type. Parameter eqA : relation A. Notation "X =A= Y" := (eqA X Y) (at level 70). Declare Instance eqA_Equivalence : Equivalence eqA. Hint Resolve (Seq_refl A eqA eqA_Equivalence) : sets. Hint Resolve (Seq_trans A eqA eqA_Equivalence) : sets. Hint Resolve (Seq_sym A eqA eqA_Equivalence) : sets. End Eqset. Module Type Eqset_dec. Declare Module Export Eq : Eqset. Parameter eqA_dec : forall x y, {x =A= y} + {~x =A= y}. End Eqset_dec. Module Eqset_def (A : SetA) <: Eqset. Definition A := A.A. Definition eqA := eq (A:=A). Instance eqA_Equivalence : Equivalence eqA. Proof. unfold eqA. class. Qed. Hint Resolve (Seq_refl A eqA eqA_Equivalence) : sets. Hint Resolve (Seq_trans A eqA eqA_Equivalence) : sets. Hint Resolve (Seq_sym A eqA eqA_Equivalence) : sets. End Eqset_def. (***********************************************************************) (** module types for ordered setoids *) Section Eqset_def_gtA_eqA_compat. Variables (A : Type) (gtA : relation A). Instance Eqset_def_gtA_eqA_compat : Proper (eq ==> eq ==> impl) gtA. Proof. intros x x' x_x' y y' y_y' x_y. rewrite <- x_x', <- y_y'; trivial. Qed. End Eqset_def_gtA_eqA_compat. Module Type Ord. Parameter A : Type. Declare Module Export S : Eqset with Definition A := A. Parameter gtA : relation A. Notation "X >A Y" := (gtA X Y) (at level 70). Declare Instance gtA_eqA_compat : Proper (eqA ==> eqA ==> impl) gtA. Hint Resolve gtA_eqA_compat : sets. End Ord. Module OrdLemmas (Export P : Ord). Definition ltA := transp gtA. Definition geA x y := ~ ltA x y. Definition leA x y := ~ gtA x y. Definition AccA := Acc ltA. Notation "X <A Y" := (ltA X Y) (at level 70). Notation "X >=A Y" := (geA X Y) (at level 70). Notation "X <=A Y" := (leA X Y) (at level 70). Hint Unfold ltA geA leA AccA : sets. (*REMOVE?*) Instance gtA_morph : Proper (eqA ==> eqA ==> iff) gtA. Proof. intros a b ab c d cd. split; apply gtA_eqA_compat; (hyp||sym;hyp). Qed. (*REMOVE?*) Instance ltA_morph : Proper (eqA ==> eqA ==> iff) ltA. Proof. intros a b ab c d cd. split; apply gtA_eqA_compat; (hyp||sym;hyp). Qed. Instance AccA_morph : Proper (eqA ==> iff) AccA. Proof. intros a b eq_ab. split. intro acc_a. inversion acc_a. constructor. intros. apply H. rewrite eq_ab. hyp. intros acc_b. inversion acc_b. constructor. intros. apply H. rewrite <- eq_ab. hyp. Qed. End OrdLemmas. Module Type Poset. Parameter A : Type. Declare Module Export O : Ord with Definition A := A. Parameter gtA_so : strict_order gtA. Hint Resolve (sord_trans gtA_so) : sets. Hint Resolve (sord_irrefl gtA_so) : sets. Hint Resolve (so_not_symmetric gtA_so) : sets. Hint Resolve (so_strict gtA_so gtA_eqA_compat eqA_Equivalence) : sets. End Poset. Module nat_ord <: Ord. Module natSet <: SetA. Definition A := nat. Definition eqA_dec := eq_nat_dec. End natSet. Module S := Eqset_def natSet. Definition A := nat. Definition gtA := gt. Instance gtA_eqA_compat : Proper (eq ==> eq ==> impl) gt. Proof. fo. Qed. End nat_ord. (***********************************************************************) (** specification *) Section Specif. Inductive sigPS2 (A : Type) (P : A -> Prop) (Q : A -> Set) : Type := existPS2 : forall x, P x -> Q x -> sigPS2 (A:=A) P Q. Notation "{ x : A # P & Q }" := (sigPS2 (fun x : A => P) (fun x : A => Q)) : type_scope. Variables (A : Type) (P Q : A -> Prop). Definition proj1_sig2 (e: sig2 P Q) := match e with | exist2 _ _ a p q => a end. End Specif. (***********************************************************************) (** tactics *) Ltac rewrite_lr term := apply (proj1 term). Ltac rewrite_rl term := apply (proj2 term). Ltac try_solve := simpl in *; try (intros; solve [ contr | discr | auto with terms | tauto | congruence ]).
The convex hull of a set $p$ is the set of all points that can be written as a convex combination of at most $n+1$ points of $p$, where $n$ is the dimension of the space.
The new kidextractor site is now online, the site is evolving so content will arrive with new photos and videos. you will be constantly updated on all the events and news regarding kidextractor, you can also subscribe to our newsletters. Good navigation.
[STATEMENT] lemma q_min: "0 \<le> t \<Longrightarrow> s0 \<le> q t" [PROOF STATE] proof (prove) goal (1 subgoal): 1. 0 \<le> t \<Longrightarrow> s0 \<le> q t [PROOF STEP] unfolding q_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. 0 \<le> t \<Longrightarrow> s0 \<le> s0 + v * t [PROOF STEP] using nonneg_vel [PROOF STATE] proof (prove) using this: 0 \<le> v goal (1 subgoal): 1. 0 \<le> t \<Longrightarrow> s0 \<le> s0 + v * t [PROOF STEP] by auto
Inductive susp (A: Type): Type := | F : A -> susp A. Implicit Arguments F [A]. Definition force {A} (x: susp A): A := match x with | F a => a end. Inductive StreamCell (A: Type): Type := | Nil : StreamCell A | Cons : A -> susp (StreamCell A) -> StreamCell A. Implicit Arguments Nil [A]. Implicit Arguments Cons [A]. Definition Stream (A: Type): Type := susp (StreamCell A). Definition FNil {A}: Stream A := F Nil. Definition FCons {A} (x: A) (s: Stream A): Stream A := F (Cons x s). Infix "::" := FCons (at level 60, right associativity). Definition length {A} (s: Stream A): nat := (fix length' (c: StreamCell A): nat := match c with | Nil => 0 | Cons _ xs => S (length' (force xs)) end ) (force s). Fixpoint take_cps {A B} (n: nat) (s: Stream A) (cont: Stream A -> B): B := match n, s with | _, F Nil => cont FNil | 0, _ => cont FNil | S m, F (Cons x xs) => take_cps m xs (fun s' => cont (x :: s')) end. Definition insertBy_cps {A B} (cmp: A -> A -> comparison) (a: A) (s: Stream A) (cont: Stream A -> B): B := (fix insertBy' (c: StreamCell A) (cont': Stream A -> B): B := match c with | Nil => cont' (a :: FNil) | Cons x xs => match cmp a x with | Eq | Lt => cont' (a :: F c) | Gt => insertBy' (force xs) (fun s' => cont' (x :: s')) end end ) (force s) cont. Definition foldr_cps {A B C} (f: A -> B -> B) (b: B) (s: Stream A) (cont: B -> C): C := (fix foldr' (c: StreamCell A) (cont': B -> C): C := match c with | Nil => cont' b | Cons x xs => foldr' (force xs) (fun b' => cont' (f x b')) end ) (force s) cont. (* つかってみる *) Definition I {A} (a: A) := a. Definition isort {A} (cmp: A -> A -> comparison) (s: Stream A): Stream A := foldr_cps (fun a s => insertBy_cps cmp a s I) FNil s I. Require Import Arith. (* TODO: 計算コスト関数を定義する *) Definition d_take_cost {A} (n m: nat) (s: Stream A): nat := let take_cont := length in take_cps m s (fun s' => take_cps n s take_cont). Definition isort_ord {A} (cmp: A -> A -> comparison) (s: Stream A): nat := let ins_cont := I in let fold_cont := length in foldr_cps (fun a s' => insertBy_cps cmp a s' ins_cont) FNil s fold_cont.
State Before: 𝕜 : Type u inst✝⁸ : NontriviallyNormedField 𝕜 E : Type uE inst✝⁷ : NormedAddCommGroup E inst✝⁶ : NormedSpace 𝕜 E F : Type uF inst✝⁵ : NormedAddCommGroup F inst✝⁴ : NormedSpace 𝕜 F G : Type uG inst✝³ : NormedAddCommGroup G inst✝² : NormedSpace 𝕜 G X : Type uX inst✝¹ : NormedAddCommGroup X inst✝ : NormedSpace 𝕜 X s s₁ t u : Set E f f₁ : E → F g : F → G x x₀ : E c : F m n✝ : ℕ∞ p : E → FormalMultilinearSeries 𝕜 E F n : ℕ hs : UniqueDiffOn 𝕜 s hx : x ∈ s ⊢ iteratedFDerivWithin 𝕜 (n + 1) f s x = (↑(continuousMultilinearCurryRightEquiv' 𝕜 n E F) ∘ iteratedFDerivWithin 𝕜 n (fun y => fderivWithin 𝕜 f s y) s) x State After: case H 𝕜 : Type u inst✝⁸ : NontriviallyNormedField 𝕜 E : Type uE inst✝⁷ : NormedAddCommGroup E inst✝⁶ : NormedSpace 𝕜 E F : Type uF inst✝⁵ : NormedAddCommGroup F inst✝⁴ : NormedSpace 𝕜 F G : Type uG inst✝³ : NormedAddCommGroup G inst✝² : NormedSpace 𝕜 G X : Type uX inst✝¹ : NormedAddCommGroup X inst✝ : NormedSpace 𝕜 X s s₁ t u : Set E f f₁ : E → F g : F → G x x₀ : E c : F m✝ n✝ : ℕ∞ p : E → FormalMultilinearSeries 𝕜 E F n : ℕ hs : UniqueDiffOn 𝕜 s hx : x ∈ s m : Fin (n + 1) → E ⊢ ↑(iteratedFDerivWithin 𝕜 (n + 1) f s x) m = ↑((↑(continuousMultilinearCurryRightEquiv' 𝕜 n E F) ∘ iteratedFDerivWithin 𝕜 n (fun y => fderivWithin 𝕜 f s y) s) x) m Tactic: ext m State Before: case H 𝕜 : Type u inst✝⁸ : NontriviallyNormedField 𝕜 E : Type uE inst✝⁷ : NormedAddCommGroup E inst✝⁶ : NormedSpace 𝕜 E F : Type uF inst✝⁵ : NormedAddCommGroup F inst✝⁴ : NormedSpace 𝕜 F G : Type uG inst✝³ : NormedAddCommGroup G inst✝² : NormedSpace 𝕜 G X : Type uX inst✝¹ : NormedAddCommGroup X inst✝ : NormedSpace 𝕜 X s s₁ t u : Set E f f₁ : E → F g : F → G x x₀ : E c : F m✝ n✝ : ℕ∞ p : E → FormalMultilinearSeries 𝕜 E F n : ℕ hs : UniqueDiffOn 𝕜 s hx : x ∈ s m : Fin (n + 1) → E ⊢ ↑(iteratedFDerivWithin 𝕜 (n + 1) f s x) m = ↑((↑(continuousMultilinearCurryRightEquiv' 𝕜 n E F) ∘ iteratedFDerivWithin 𝕜 n (fun y => fderivWithin 𝕜 f s y) s) x) m State After: case H 𝕜 : Type u inst✝⁸ : NontriviallyNormedField 𝕜 E : Type uE inst✝⁷ : NormedAddCommGroup E inst✝⁶ : NormedSpace 𝕜 E F : Type uF inst✝⁵ : NormedAddCommGroup F inst✝⁴ : NormedSpace 𝕜 F G : Type uG inst✝³ : NormedAddCommGroup G inst✝² : NormedSpace 𝕜 G X : Type uX inst✝¹ : NormedAddCommGroup X inst✝ : NormedSpace 𝕜 X s s₁ t u : Set E f f₁ : E → F g : F → G x x₀ : E c : F m✝ n✝ : ℕ∞ p : E → FormalMultilinearSeries 𝕜 E F n : ℕ hs : UniqueDiffOn 𝕜 s hx : x ∈ s m : Fin (n + 1) → E ⊢ ↑(↑(iteratedFDerivWithin 𝕜 n (fun y => fderivWithin 𝕜 f s y) s x) (init m)) (m (last n)) = ↑((↑(continuousMultilinearCurryRightEquiv' 𝕜 n E F) ∘ iteratedFDerivWithin 𝕜 n (fun y => fderivWithin 𝕜 f s y) s) x) m Tactic: rw [iteratedFDerivWithin_succ_apply_right hs hx] State Before: case H 𝕜 : Type u inst✝⁸ : NontriviallyNormedField 𝕜 E : Type uE inst✝⁷ : NormedAddCommGroup E inst✝⁶ : NormedSpace 𝕜 E F : Type uF inst✝⁵ : NormedAddCommGroup F inst✝⁴ : NormedSpace 𝕜 F G : Type uG inst✝³ : NormedAddCommGroup G inst✝² : NormedSpace 𝕜 G X : Type uX inst✝¹ : NormedAddCommGroup X inst✝ : NormedSpace 𝕜 X s s₁ t u : Set E f f₁ : E → F g : F → G x x₀ : E c : F m✝ n✝ : ℕ∞ p : E → FormalMultilinearSeries 𝕜 E F n : ℕ hs : UniqueDiffOn 𝕜 s hx : x ∈ s m : Fin (n + 1) → E ⊢ ↑(↑(iteratedFDerivWithin 𝕜 n (fun y => fderivWithin 𝕜 f s y) s x) (init m)) (m (last n)) = ↑((↑(continuousMultilinearCurryRightEquiv' 𝕜 n E F) ∘ iteratedFDerivWithin 𝕜 n (fun y => fderivWithin 𝕜 f s y) s) x) m State After: no goals Tactic: rfl
From iris.algebra Require Import lib.frac_auth numbers auth. From iris.proofmode Require Import proofmode. From iris.base_logic.lib Require Export invariants. From iris.program_logic Require Export weakestpre. From iris.heap_lang Require Export lang. From iris.heap_lang Require Import proofmode notation. From iris.prelude Require Import options. Definition newcounter : val := λ: <>, ref #0. Definition incr : val := rec: "incr" "l" := let: "n" := !"l" in if: CAS "l" "n" (#1 + "n") then #() else "incr" "l". Definition read : val := λ: "l", !"l". (** Monotone counter *) Class mcounterG Σ := MCounterG { mcounter_inG : inG Σ (authR max_natUR) }. Local Existing Instance mcounter_inG. Definition mcounterΣ : gFunctors := #[GFunctor (authR max_natUR)]. Global Instance subG_mcounterΣ {Σ} : subG mcounterΣ Σ → mcounterG Σ. Proof. solve_inG. Qed. Section mono_proof. Context `{!heapGS Σ, !mcounterG Σ} (N : namespace). Definition mcounter_inv (γ : gname) (l : loc) : iProp Σ := ∃ n, own γ (● (MaxNat n)) ∗ l ↦ #n. Definition mcounter (l : loc) (n : nat) : iProp Σ := ∃ γ, inv N (mcounter_inv γ l) ∧ own γ (◯ (MaxNat n)). (** The main proofs. *) Global Instance mcounter_persistent l n : Persistent (mcounter l n). Proof. apply _. Qed. Lemma newcounter_mono_spec : {{{ True }}} newcounter #() {{{ l, RET #l; mcounter l 0 }}}. Proof. iIntros (Φ) "_ HΦ". rewrite /newcounter /=. wp_lam. wp_alloc l as "Hl". iMod (own_alloc (● (MaxNat O) ⋅ ◯ (MaxNat O))) as (γ) "[Hγ Hγ']"; first by apply auth_both_valid_discrete. iMod (inv_alloc N _ (mcounter_inv γ l) with "[Hl Hγ]"). { iNext. iExists 0. by iFrame. } iModIntro. iApply "HΦ". rewrite /mcounter; eauto 10. Qed. Lemma incr_mono_spec l n : {{{ mcounter l n }}} incr #l {{{ RET #(); mcounter l (S n) }}}. Proof. iIntros (Φ) "Hl HΦ". iLöb as "IH". wp_rec. iDestruct "Hl" as (γ) "[#? Hγf]". wp_bind (! _)%E. iInv N as (c) ">[Hγ Hl]". wp_load. iModIntro. iSplitL "Hl Hγ"; [iNext; iExists c; by iFrame|]. wp_pures. wp_bind (CmpXchg _ _ _). iInv N as (c') ">[Hγ Hl]". destruct (decide (c' = c)) as [->|]. - iCombine "Hγ Hγf" gives %[?%max_nat_included _]%auth_both_valid_discrete. iMod (own_update_2 with "Hγ Hγf") as "[Hγ Hγf]". { apply auth_update, (max_nat_local_update _ _ (MaxNat (S c))). simpl. auto. } wp_cmpxchg_suc. iModIntro. iSplitL "Hl Hγ". { iNext. iExists (S c). rewrite Nat2Z.inj_succ Z.add_1_l. by iFrame. } wp_pures. iApply "HΦ". iModIntro. iExists γ; repeat iSplit; eauto. iApply (own_mono with "Hγf"). (* FIXME: FIXME(Coq #6294): needs new unification *) apply: auth_frag_mono. by apply max_nat_included, le_n_S. - wp_cmpxchg_fail; first (by intros [= ?%Nat2Z.inj]). iModIntro. iSplitL "Hl Hγ"; [iNext; iExists c'; by iFrame|]. wp_pures. iApply ("IH" with "[Hγf] [HΦ]"); last by auto. rewrite {3}/mcounter; eauto 10. Qed. Lemma read_mono_spec l j : {{{ mcounter l j }}} read #l {{{ i, RET #i; ⌜j ≤ i⌝ ∧ mcounter l i }}}. Proof. iIntros (ϕ) "Hc HΦ". iDestruct "Hc" as (γ) "[#Hinv Hγf]". rewrite /read /=. wp_lam. iInv N as (c) ">[Hγ Hl]". wp_load. iCombine "Hγ Hγf" gives %[?%max_nat_included _]%auth_both_valid_discrete. iMod (own_update_2 with "Hγ Hγf") as "[Hγ Hγf]". { apply auth_update, (max_nat_local_update _ _ (MaxNat c)); auto. } iModIntro. iSplitL "Hl Hγ"; [iNext; iExists c; by iFrame|]. iApply ("HΦ" with "[-]"). rewrite /mcounter; eauto 10. Qed. End mono_proof. (** Counter with contributions *) Class ccounterG Σ := CCounterG { ccounter_inG : inG Σ (frac_authR natR) }. Local Existing Instance ccounter_inG. Definition ccounterΣ : gFunctors := #[GFunctor (frac_authR natR)]. Global Instance subG_ccounterΣ {Σ} : subG ccounterΣ Σ → ccounterG Σ. Proof. solve_inG. Qed. Section contrib_spec. Context `{!heapGS Σ, !ccounterG Σ} (N : namespace). Definition ccounter_inv (γ : gname) (l : loc) : iProp Σ := ∃ n, own γ (●F n) ∗ l ↦ #n. Definition ccounter_ctx (γ : gname) (l : loc) : iProp Σ := inv N (ccounter_inv γ l). Definition ccounter (γ : gname) (q : frac) (n : nat) : iProp Σ := own γ (◯F{q} n). (** The main proofs. *) Lemma ccounter_op γ q1 q2 n1 n2 : ccounter γ (q1 + q2) (n1 + n2) ⊣⊢ ccounter γ q1 n1 ∗ ccounter γ q2 n2. Proof. by rewrite /ccounter frac_auth_frag_op -own_op. Qed. Lemma newcounter_contrib_spec (R : iProp Σ) : {{{ True }}} newcounter #() {{{ γ l, RET #l; ccounter_ctx γ l ∗ ccounter γ 1 0 }}}. Proof. iIntros (Φ) "_ HΦ". rewrite /newcounter /=. wp_lam. wp_alloc l as "Hl". iMod (own_alloc (●F O ⋅ ◯F 0)) as (γ) "[Hγ Hγ']"; first by apply auth_both_valid_discrete. iMod (inv_alloc N _ (ccounter_inv γ l) with "[Hl Hγ]"). { iNext. iExists 0. by iFrame. } iModIntro. iApply "HΦ". rewrite /ccounter_ctx /ccounter; eauto 10. Qed. Lemma incr_contrib_spec γ l q n : {{{ ccounter_ctx γ l ∗ ccounter γ q n }}} incr #l {{{ RET #(); ccounter γ q (S n) }}}. Proof. iIntros (Φ) "[#? Hγf] HΦ". iLöb as "IH". wp_rec. wp_bind (! _)%E. iInv N as (c) ">[Hγ Hl]". wp_load. iModIntro. iSplitL "Hl Hγ"; [iNext; iExists c; by iFrame|]. wp_pures. wp_bind (CmpXchg _ _ _). iInv N as (c') ">[Hγ Hl]". destruct (decide (c' = c)) as [->|]. - iMod (own_update_2 with "Hγ Hγf") as "[Hγ Hγf]". { apply frac_auth_update, (nat_local_update _ _ (S c) (S n)); lia. } wp_cmpxchg_suc. iModIntro. iSplitL "Hl Hγ". { iNext. iExists (S c). rewrite Nat2Z.inj_succ Z.add_1_l. by iFrame. } wp_pures. by iApply "HΦ". - wp_cmpxchg_fail; first (by intros [= ?%Nat2Z.inj]). iModIntro. iSplitL "Hl Hγ"; [iNext; iExists c'; by iFrame|]. wp_pures. by iApply ("IH" with "[Hγf] [HΦ]"); auto. Qed. Lemma read_contrib_spec γ l q n : {{{ ccounter_ctx γ l ∗ ccounter γ q n }}} read #l {{{ c, RET #c; ⌜n ≤ c⌝ ∧ ccounter γ q n }}}. Proof. iIntros (Φ) "[#? Hγf] HΦ". rewrite /read /=. wp_lam. iInv N as (c) ">[Hγ Hl]". wp_load. iCombine "Hγ Hγf" gives % ?%frac_auth_included_total%nat_included. iModIntro. iSplitL "Hl Hγ"; [iNext; iExists c; by iFrame|]. iApply ("HΦ" with "[-]"); rewrite /ccounter; eauto 10. Qed. Lemma read_contrib_spec_1 γ l n : {{{ ccounter_ctx γ l ∗ ccounter γ 1 n }}} read #l {{{ RET #n; ccounter γ 1 n }}}. Proof. iIntros (Φ) "[#? Hγf] HΦ". rewrite /read /=. wp_lam. iInv N as (c) ">[Hγ Hl]". wp_load. iCombine "Hγ Hγf" gives % <-%frac_auth_agree_L. iModIntro. iSplitL "Hl Hγ"; [iNext; iExists c; by iFrame|]. by iApply "HΦ". Qed. End contrib_spec.
module StructureLearner using LogicCircuits using ..Utils using ..Probabilistic using ..IO export # ChowLiuTree learn_chow_liu_tree, parent_vector, print_tree, CLT, # CircuitBuilder compile_prob_circuit_from_clt, learn_probabilistic_circuit, BaseCache, ⊤, LitCache, # PSDDInitializer learn_struct_prob_circuit, learn_vtree_from_clt, compile_psdd_from_clt include("ChowLiuTree.jl") include("CircuitBuilder.jl") include("PSDDInitializer.jl") end
STANFORD, Calif. - Santa Clara University men's water polo fell to top-ranked Stanford 16-4 this morning to open play at the Northern California Invitational. It followed with an afternoon 11-3 loss to seventh-ranked UC San Diego. Hosted by Stanford University, this weekend's event is taking place at the Avery Aquatic Center. With the losses, Santa Clara falls to 6-8 on the season. Against Stanford Santa Clara's goals were scored by senior Jay Moorhead, junior Dan Figoni and sophomore J.P Doucette. Sophomore Gareth Owens recorded five saves at goalkeeper. The Broncos added goals by freshman Grant Allison and seniors Bryan Failing and Dan O'Connell in the afternoon match against UCSD. Owens recorded one block while freshman Peter Moore registered six in goal. The Broncos continue play at the Northern California Invitational through Sunday.
theory T48 imports Main begin lemma "( (\<forall> x::nat. \<forall> y::nat. meet(x, y) = meet(y, x)) & (\<forall> x::nat. \<forall> y::nat. join(x, y) = join(y, x)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, meet(y, z)) = meet(meet(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(x, join(y, z)) = join(join(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. meet(x, join(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. join(x, meet(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, join(y, z)) = join(mult(x, y), mult(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(join(x, y), z) = join(mult(x, z), mult(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, over(join(mult(x, y), z), y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(y, undr(x, join(mult(x, y), z))) = y) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(over(x, y), y), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(y, undr(y, x)), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, meet(y, z)) = meet(mult(x, y), mult(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(x, join(y, z)) = join(undr(x, y), undr(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(meet(x, y), z) = join(undr(x, z), undr(y, z))) & (\<forall> x::nat. \<forall> y::nat. invo(join(x, y)) = meet(invo(x), invo(y))) & (\<forall> x::nat. \<forall> y::nat. invo(meet(x, y)) = join(invo(x), invo(y))) & (\<forall> x::nat. invo(invo(x)) = x) ) \<longrightarrow> (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(meet(x, y), z) = meet(mult(x, z), mult(y, z))) " nitpick[card nat=4,timeout=86400] oops end
{-# OPTIONS --show-implicit #-} data Bool : Set where true : Bool false : Bool data D : Set where d : D data E : Set where e : E HSet : Set₁ HSet = {b : Bool} → Set -- Here HA is HSet -- The output of this function is the set E, for input HSet G. ⊨_ : HSet → Set ⊨_ HA = HA {true} G : HSet G {true} = E G {false} = D noo : ⊨ G {false} noo = {!!} boo : ⊨ λ {b} → G {b} boo = {!!}
lemma dependent_biggerset: fixes S :: "'a::euclidean_space set" shows "(finite S \<Longrightarrow> card S > DIM('a)) \<Longrightarrow> dependent S"
C ********************************************************* C * * C * TEST NUMBER: 09.02.03/08 * C * TEST TITLE : Error indicator = 114 * C * * C * PHIGS Validation Tests, produced by NIST * C * * C ********************************************************* COMMON /GLOBNU/ CTLHND, ERRSIG, ERRFIL, IERRCT, UNERR, 1 TESTCT, IFLERR, PASSSW, ERRSW, MAXLIN, 2 CONID, MEMUN, WKID, WTYPE, GLBLUN, INDLUN, 3 DUMINT, DUMRL INTEGER CTLHND, ERRSIG, ERRFIL, IERRCT, UNERR, 1 TESTCT, IFLERR, PASSSW, ERRSW, MAXLIN, 2 CONID, MEMUN, WKID, WTYPE, GLBLUN, INDLUN, 3 DUMINT(20), ERRIND REAL DUMRL(20) COMMON /ERRINF/ ERRCOM,FUNCOM,FILCOM, ERNMSW, EXPSIZ,EXPERR, 1 USRERR, ERRSAV, FUNSAV, FILSAV, 2 EFCNT, EFID INTEGER ERRCOM,FUNCOM,FILCOM, ERNMSW, EXPSIZ,EXPERR(10), 1 USRERR, ERRSAV(200), FUNSAV(200), FILSAV(200), 2 EFCNT, EFID(100) COMMON /ERRCHR/ CURCON, ERRSRS, ERRMRK, ERFLNM, 1 CONTAB CHARACTER CURCON*200, ERRSRS*40, ERRMRK*20, ERFLNM*80, 1 CONTAB(40)*150 INTEGER IVAL1, IVAL2, IVAL3, SPECWT REAL RA44(4,4), RB44(4,4), RA6(6) CALL INITGL ('09.02.03/08') CALL XPOPPH (ERRFIL, MEMUN) CURCON = 'the view index value is less than zero' ERRSRS = '8' CALL SETVS ('114', EXPERR, EXPSIZ) CALL POPWK (WKID, CONID, WTYPE) CALL PQWKC (WKID, ERRIND, CONID, SPECWT) CALL CHKINQ ('pqwkc', ERRIND) CALL RQVWR (WKID, -1, 0, ERRIND, IVAL1, RA44, RB44, RA6, IVAL2, 1 IVAL2, IVAL3) CALL RQPVWR (SPECWT, -10, ERRIND, RA44, RB44, RA6, IVAL1, 1 IVAL2, IVAL3) CALL ENDIT END
lemma real_affinity_eq: "m \<noteq> 0 \<Longrightarrow> m * x + c = y \<longleftrightarrow> x = inverse m * y + - (c / m)" for m :: "'a::linordered_field"
// Copyright 2018 Jeremy Mason // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. //! \file matrix.c //! Contains functions to manipulate matrices. Intended as a relatively less //! painful wrapper around Level 2 and 3 CBLAS. Column-major order is likely //! slightly faster than row-major order because of the underlying FORTRAN //! routines. #include <cblas.h> // daxpy #include <math.h> // exp #include <stdbool.h> // bool #include <stddef.h> // size_t #include <stdio.h> // EOF #include <stdlib.h> // abort #include <string.h> // memcpy #include "sb_structs.h" // sb_mat #include "sb_matrix.h" #include "sb_utility.h" // SB_CHK_ERR #include "sb_vector.h" // sb_vec_is_finite #include "safety.h" /// Constructs a matrix with the required capacity. /// /// # Parameters /// - `n_rows`: number of rows of the matrix /// - `n_cols`: number of columns of the matrix /// /// # Returns /// A `sb_mat` pointer to the allocated matrix, or `NULL` if the allocation /// fails /// /// # Examples /// ``` /// #include "sb_matrix.h" /// #include "sb_structs.h" /// /// int main(void) { /// sb_mat * A = sb_mat_malloc(3, 3); /// /// // Fill the matrix with some values and print /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.}; /// sb_mat_subcpy(A, 0, a, 9); /// sb_mat_print(A, "A: ", "%g"); /// /// SB_MAT_FREE_ALL(A); /// } /// ``` sb_mat * sb_mat_malloc(size_t n_rows, size_t n_cols) { sb_mat * out = malloc(sizeof(sb_mat)); SB_CHK_ERR(!out, return NULL, "sb_mat_malloc: failed to allocate matrix"); size_t n_elem = n_rows * n_cols; double * data = malloc(n_elem * sizeof(double)); SB_CHK_ERR(!data, free(out); return NULL, "sb_mat_malloc: failed to allocate data"); out->n_rows = n_rows; out->n_cols = n_cols; out->n_elem = n_elem; out->data = data; return out; } /// Constructs a matrix with the required capacity and initializes all elements /// to zero. Requires support for the IEC 60559 standard. /// /// # Parameters /// - `n_rows`: number of rows of the matrix /// - `n_cols`: number of columns of the matrix /// /// # Returns /// A `sb_mat` pointer to the allocated matrix, or `NULL` if the allocation /// fails /// /// # Examples /// ``` /// #include "sb_matrix.h" /// #include "sb_structs.h" /// /// int main(void) { /// sb_mat * A = sb_mat_calloc(3, 3); /// /// // Initialized to zeros /// sb_mat_print(A, "A before: ", "%g"); /// /// // Fill the matrix with some values and print /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.}; /// sb_mat_subcpy(A, 0, a, 9); /// sb_mat_print(A, "A after: ", "%g"); /// /// SB_MAT_FREE_ALL(A); /// } /// ``` sb_mat * sb_mat_calloc(size_t n_rows, size_t n_cols) { sb_mat * out = malloc(sizeof(sb_mat)); SB_CHK_ERR(!out, return NULL, "sb_mat_calloc: failed to allocate matrix"); size_t n_elem = n_rows * n_cols; double * data = calloc(n_elem, sizeof(double)); SB_CHK_ERR(!data, free(out); return NULL, "sb_mat_calloc: failed to allocate data"); out->n_rows = n_rows; out->n_cols = n_cols; out->n_elem = n_elem; out->data = data; return out; } /// Constructs a matrix with the required capacity and initializes elements to /// the first `n_rows * n_cols` elements of array `a`. The array must contain /// at least `n_rows * n_cols` elements. /// /// # Parameters /// - `a`: array to be copied into the matrix /// - `n_rows`: number of rows of the matrix /// - `n_cols`: number of columns of the matrix /// /// # Returns /// A `sb_mat` pointer to the allocated matrix, or `NULL` if the allocation /// fails /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `a` is not `NULL` /// /// # Examples /// ``` /// #include "sb_matrix.h" /// #include "sb_structs.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.}; /// /// // Construct a matrix from the array /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// sb_mat_print(A, "A: ", "%g"); /// /// SB_MAT_FREE_ALL(A); /// } /// ``` sb_mat * sb_mat_of_arr(const double * a, size_t n_rows, size_t n_cols) { #ifdef SAFE_MEMORY SB_CHK_ERR(!a, abort(), "sb_mat_of_arr: a cannot be NULL"); #endif sb_mat * out = malloc(sizeof(sb_mat)); SB_CHK_ERR(!out, return NULL, "sb_mat_of_arr: failed to allocate matrix"); size_t n_elem = n_rows * n_cols; double * data = malloc(n_elem * sizeof(double)); SB_CHK_ERR(!data, free(out); return NULL, "sb_mat_of_arr: failed to allocate data"); out->n_rows = n_rows; out->n_cols = n_cols; out->n_elem = n_elem; out->data = memcpy(data, a, n_elem * sizeof(double)); return out; } /// Constructs a matrix as a deep copy of an existing matrix. The state of the /// existing matrix must be valid. /// /// # Parameters /// - `A`: pointer to the matrix to be copied /// /// # Returns /// A `sb_mat` pointer to the allocated matrix, or `NULL` if the allocation /// fails /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `A` is not `NULL` /// /// # Examples /// ``` /// #include "sb_matrix.h" /// #include "sb_structs.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// /// // `A` and `B` contain the same elements /// sb_mat_c * B = sb_mat_clone(A); /// sb_mat_print(B, "B before: ", "%g"); /// /// // Fill `B` with some values and print /// sb_mat_subcpy(B, 0, a + 1, 3); /// sb_mat_print(B, "B after: ", "%g"); /// /// // `A` is unchanged /// sb_mat_print(A, "A after: ", "%g"); /// /// SB_MAT_FREE_ALL(A, B); /// } /// ``` sb_mat * sb_mat_clone(const sb_mat * A) { #ifdef SAFE_MEMORY SB_CHK_ERR(!A, abort(), "sb_mat_clone: A cannot be NULL"); #endif sb_mat * out = malloc(sizeof(sb_mat)); SB_CHK_ERR(!out, return NULL, "sb_mat_clone: failed to allocate matrix"); size_t n_elem = A->n_elem; double * data = malloc(n_elem * sizeof(double)); SB_CHK_ERR(!data, free(out); return NULL, "sb_mat_clone: failed to allocate data"); *out = *A; out->data = memcpy(data, A->data, n_elem * sizeof(double)); return out; } /// Deconstructs a matrix. /// /// # Parameters /// - `A`: pointer to the matrix /// /// # Returns /// No return value /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `A` is not `NULL` /// /// # Examples /// ``` /// #include "sb_matrix.h" /// #include "sb_structs.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.}; /// /// // Allocates a pointer to mat /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// sb_mat_print(A, "A: ", "%g"); /// /// sb_mat_free(A); /// // Pointer to `A` is now invalid /// } /// ``` void sb_mat_free(sb_mat * A) { #ifdef SAFE_MEMORY SB_CHK_ERR(!A, abort(), "sb_mat_free: A cannot be NULL"); #endif free(A->data); free(A); } /// Sets all elements of `A` to zero. Requires support for the IEC 60559 /// standard. /// /// # Parameters /// - `A`: pointer to the matrix /// /// # Returns /// A copy of `A` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `A` is not `NULL` /// /// # Examples /// ``` /// #include "sb_matrix.h" /// #include "sb_structs.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// /// // Set all elements to zero /// sb_mat_print(A, "A before: ", "%g"); /// sb_mat_set_zero(A); /// sb_mat_print(A, "A after: ", "%g"); /// /// SB_MAT_FREE_ALL(A); /// } /// ``` sb_mat * sb_mat_set_zero(sb_mat * A) { #ifdef SAFE_MEMORY SB_CHK_ERR(!A, abort(), "sb_mat_set_zero: A cannot be NULL"); #endif return memset(A->data, 0, A->n_elem * sizeof(double)); } /// Sets all elements of `A` to `x`. /// /// # Parameters /// - `A`: pointer to the matrix /// - `x`: value for the elements /// /// # Returns /// A copy of `A` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `A` is not `NULL` /// /// # Examples /// ``` /// #include "sb_matrix.h" /// #include "sb_structs.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// /// // Set all elements to 8. /// sb_mat_print(A, "A before: ", "%g"); /// sb_mat_set_all(A, 8.); /// sb_mat_print(A, "A after: ", "%g"); /// /// SB_MAT_FREE_ALL(A); /// } /// ``` sb_mat * sb_mat_set_all(sb_mat * A, double x) { #ifdef SAFE_MEMORY SB_CHK_ERR(!A, abort(), "sb_mat_set_all: A cannot be NULL"); #endif double * data = A->data; for (size_t a = 0; a < A->n_elem; ++a) { data[a] = x; } return A; } /// Sets all elements of `A` to zero, except for elements on the main diagonal /// which are set to one. `A` must be a square matrix. Requires support for the /// IEC 60559 standard. /// /// # Parameters /// - `A`: pointer to the matrix /// /// # Returns /// A copy of `A` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `A` is not `NULL` /// - `SAFE_LENGTH`: `A` is a square matrix /// /// # Examples /// ``` /// #include "sb_matrix.h" /// #include "sb_structs.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// /// // Set `A` to the identity /// sb_mat_print(A, "A before: ", "%g"); /// sb_mat_set_ident(A); /// sb_mat_print(A, "A after: ", "%g"); /// /// SB_MAT_FREE_ALL(A); /// } /// ``` sb_mat * sb_mat_set_ident(sb_mat * A) { #ifdef SAFE_MEMORY SB_CHK_ERR(!A, abort(), "sb_mat_set_ident: A cannot be NULL"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(A->n_rows != A->n_cols, abort(), "sb_mat_set_ident: A must be square"); #endif double * data = A->data; size_t n_elem = A->n_elem; memset(data, 0, n_elem * sizeof(double)); for (size_t a = 0; a < n_elem; a += A->n_rows + 1) { data[a] = 1.; } return A; } /// Copies the `i`th row of the matrix `A` into the row vector `v`. `v` and `A` /// must not overlap in memory. /// /// # Parameters /// - `v`: pointer to the vector /// - `A`: pointer to the matrix /// - `i`: index of the row to be copied /// /// # Returns /// A copy of `v` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` and `A` are not `NULL` /// - `SAFE_LAYOUT`: `v` is a row vector /// - `SAFE_LENGTH`: `v` and `A` have the same number of columns and `i` is a /// valid row index /// /// # Examples /// ``` /// #include "sb_matrix.h" /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// sb_vec * v = sb_vec_malloc(3, 'r'); /// /// // Set v to the first row /// sb_mat_print(A, "A: ", "%g"); /// sb_mat_get_row(v, A, 1); /// sb_vec_print(v, "v: ", "%g"); /// /// SB_MAT_FREE_ALL(A); /// SB_VEC_FREE_ALL(v); /// } /// ``` sb_vec * sb_mat_get_row(sb_vec * restrict v, const sb_mat * restrict A, size_t i) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_mat_get_row: v cannot be NULL"); SB_CHK_ERR(!A, abort(), "sb_mat_get_row: A cannot be NULL"); #endif #ifdef SAFE_LAYOUT SB_CHK_ERR(v->layout != 'r', abort(), "sb_mat_get_row: v must be a row vector"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(v->n_elem != A->n_cols, abort(), "sb_mat_get_row: v and A must have same number of columns"); SB_CHK_ERR(i >= A->n_rows, abort(), "sb_mat_get_row: invalid row index"); #endif cblas_dcopy(A->n_cols, A->data + i, A->n_rows, v->data, 1); return v; } /// Copies the `i`th column of the matrix `A` into the column vector `v`. `v` /// and `A` must not overlap in memory. /// /// # Parameters /// - `v`: pointer to the vector /// - `A`: pointer to the matrix /// - `j`: index of the column to be copied /// /// # Returns /// A copy of `v` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` and `A` are not `NULL` /// - `SAFE_LAYOUT`: `v` is a column vector /// - `SAFE_LENGTH`: `v` and `A` have the same number of rows and `j` is a /// valid row index /// /// # Examples /// ``` /// #include "sb_matrix.h" /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// sb_vec * v = sb_vec_malloc(3, 'c'); /// /// // Set v to the first column /// sb_mat_print(A, "A: ", "%g"); /// sb_mat_get_col(v, A, 1); /// sb_vec_print(v, "v: ", "%g"); /// /// SB_MAT_FREE_ALL(A); /// SB_VEC_FREE_ALL(v); /// } /// ``` sb_vec * sb_mat_get_col(sb_vec * restrict v, const sb_mat * restrict A, size_t j) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_mat_get_col: v cannot be NULL"); SB_CHK_ERR(!A, abort(), "sb_mat_get_col: A cannot be NULL"); #endif #ifdef SAFE_LAYOUT SB_CHK_ERR(v->layout != 'c', abort(), "sb_mat_get_col: v must be a column vector"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(v->n_elem != A->n_rows, abort(), "sb_mat_get_col: v and A must have same number of rows"); SB_CHK_ERR(j >= A->n_cols, abort(), "sb_mat_get_col: invalid column index"); #endif size_t n_rows = A->n_rows; memcpy(v->data, A->data + j * n_rows, n_rows * sizeof(double)); return v; } /// Copies the diagonal of the matrix `A` into the vector `v`. `A` must be a /// square matrix, and `v` and `A` must not overlap in memory. /// /// # Parameters /// - `v`: pointer to the vector /// - `A`: pointer to the matrix /// /// # Returns /// A copy of `v` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` and `A` are not `NULL` /// - `SAFE_LENGTH`: `A` is square, and the number of elements in `v` is the /// same as the number of rows in `A` /// /// # Examples /// ``` /// #include "sb_matrix.h" /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// sb_vec * v = sb_vec_malloc(3, 'c'); /// /// // Set v to the main diagonal /// sb_mat_print(A, "A: ", "%g"); /// sb_mat_get_diag(v, A); /// sb_vec_print(v, "v: ", "%g"); /// /// SB_MAT_FREE_ALL(A); /// SB_VEC_FREE_ALL(v); /// } /// ``` sb_vec * sb_mat_get_diag(sb_vec * restrict v, const sb_mat * restrict A) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_mat_get_diag: v cannot be NULL"); SB_CHK_ERR(!A, abort(), "sb_mat_get_diag: A cannot be NULL"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(A->n_rows != A->n_cols, abort(), "sb_mat_get_diag: A must be square"); SB_CHK_ERR(v->n_elem != A->n_rows, abort(), "sb_mat_get_diag: number of elements in v should equal number of rows of A"); #endif size_t n_rows = A->n_rows; cblas_dcopy(n_rows, A->data, n_rows + 1, v->data, 1); return v; } /// Copies the row vector `v` into the `i`th row of the matrix `A`. `v` and `A` /// must not overlap in memory. /// /// # Parameters /// - `A`: pointer to the matrix /// - `i`: index of the row to be written /// - `v`: pointer to the vector /// /// # Returns /// A copy of `A` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` and `A` are not `NULL` /// - `SAFE_LAYOUT`: `v` is a row vector /// - `SAFE_LENGTH`: `v` and `A` have the same number of columns and `i` is a /// valid row index /// /// # Examples /// ``` /// #include "sb_matrix.h" /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// sb_vec * v = sb_vec_of_arr(a + 2, 3, 'r'); /// /// // Set the first row to v /// sb_mat_print(A, "A before: ", "%g"); /// sb_vec_print(v, "v: ", "%g"); /// sb_mat_set_row(A, 1, v); /// sb_mat_print(A, "A after: ", "%g"); /// /// SB_MAT_FREE_ALL(A); /// SB_VEC_FREE_ALL(v); /// } /// ``` sb_mat * sb_mat_set_row(sb_mat * restrict A, size_t i, const sb_vec * restrict v) { #ifdef SAFE_MEMORY SB_CHK_ERR(!A, abort(), "sb_mat_set_row: A cannot be NULL"); SB_CHK_ERR(!v, abort(), "sb_mat_set_row: v cannot be NULL"); #endif #ifdef SAFE_LAYOUT SB_CHK_ERR(v->layout != 'r', abort(), "sb_mat_set_row: v must be a row vector"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(v->n_elem != A->n_cols, abort(), "sb_mat_set_row: v and A must have same number of columns"); SB_CHK_ERR(i >= A->n_rows, abort(), "sb_mat_set_row: invalid row index"); #endif cblas_dcopy(A->n_cols, v->data, 1, A->data + i, A->n_rows); return A; } /// Copies the column vector `v` into the `i`th column of the matrix `A`. `v` /// and `A` must not overlap in memory. /// /// # Parameters /// - `A`: pointer to the matrix /// - `j`: index of the column to be written /// - `v`: pointer to the vector /// /// # Returns /// A copy of `v` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` and `A` are not `NULL` /// - `SAFE_LAYOUT`: `v` is a column vector /// - `SAFE_LENGTH`: `v` and `A` have the same number of rows and `j` is a /// valid row index /// /// # Examples /// ``` /// #include "sb_matrix.h" /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// sb_vec * v = sb_vec_of_arr(a + 2, 3, 'c'); /// /// // Set the first column to v /// sb_mat_print(A, "A before: ", "%g"); /// sb_vec_print(v, "v: ", "%g"); /// sb_mat_set_col(A, 1, v); /// sb_mat_print(A, "A after: ", "%g"); /// /// SB_MAT_FREE_ALL(A); /// SB_VEC_FREE_ALL(v); /// } /// ``` sb_mat * sb_mat_set_col(sb_mat * restrict A, size_t j, const sb_vec * restrict v) { #ifdef SAFE_MEMORY SB_CHK_ERR(!A, abort(), "sb_mat_set_col: A cannot be NULL"); SB_CHK_ERR(!v, abort(), "sb_mat_set_col: v cannot be NULL"); #endif #ifdef SAFE_LAYOUT SB_CHK_ERR(v->layout != 'c', abort(), "sb_mat_set_col: v must be a column vector"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(v->n_elem != A->n_rows, abort(), "sb_mat_set_col: v and A must have same number of rows"); SB_CHK_ERR(j >= A->n_cols, abort(), "sb_mat_set_col: invalid column index"); #endif size_t n_rows = A->n_rows; memcpy(A->data + j * n_rows, v->data, n_rows * sizeof(double)); return A; } /// Copies the vector `v` into the diagonal of the matrix `A`. `A` must be a /// square matrix, and `v` and `A` must not overlap in memory. /// /// # Parameters /// - `v`: pointer to the vector /// - `A`: pointer to the matrix /// /// # Returns /// A copy of `v` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` and `A` are not `NULL` /// - `SAFE_LENGTH`: `A` is square, and the number of elements in `v` is the /// same as the number of rows in `A` /// /// # Examples /// ``` /// #include "sb_matrix.h" /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// sb_vec * v = sb_vec_of_arr(a + 2, 3, 'c'); /// /// // Set the main diagonal to v /// sb_mat_print(A, "A before: ", "%g"); /// sb_vec_print(v, "v: ", "%g"); /// sb_mat_set_diag(A, v); /// sb_mat_print(A, "A after: ", "%g"); /// /// SB_MAT_FREE_ALL(A); /// SB_VEC_FREE_ALL(v); /// } /// ``` sb_mat * sb_mat_set_diag(sb_mat * restrict A, const sb_vec * restrict v) { #ifdef SAFE_MEMORY SB_CHK_ERR(!A, abort(), "sb_mat_get_diag: A cannot be NULL"); SB_CHK_ERR(!v, abort(), "sb_mat_get_diag: v cannot be NULL"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(A->n_rows != A->n_cols, abort(), "sb_mat_get_diag: A must be square"); SB_CHK_ERR(v->n_elem != A->n_rows, abort(), "sb_mat_get_diag: number of elements in v should equal number of rows of A"); #endif size_t n_rows = A->n_rows; cblas_dcopy(n_rows, v->data, 1, A->data, n_rows + 1); return A; } /// Copies contents of the `src` matrix into the `dest` matrix. `src` and `dest` /// must have the same number of rows and columns and not overlap in memory. /// /// # Parameters /// - `dest`: pointer to destination matrix /// - `src`: const pointer to source matrix /// /// # Returns /// A copy of `dest` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `src` and `dest` are not `NULL` /// - `SAFE_LENGTH`: `src` and `dest` have same number of rows and columns /// /// # Examples /// ``` /// #include "sb_matrix.h" /// #include "sb_structs.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2., 8.}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// sb_mat * B = sb_mat_of_arr(a + 1, 3, 3); /// /// // Overwrite elements of `A` and print /// sb_mat_print(A, "A before: ", "%g"); /// sb_mat_print(B, "B before: ", "%g"); /// sb_mat_memcpy(A, B); /// sb_mat_print(A, "A after: ", "%g"); /// sb_mat_print(B, "B after: ", "%g"); /// /// SB_MAT_FREE_ALL(A, B); /// } /// ``` sb_mat * sb_mat_memcpy(sb_mat * restrict dest, const sb_mat * restrict src) { #ifdef SAFE_MEMORY SB_CHK_ERR(!dest, abort(), "sb_mat_memcpy: dest cannot be NULL"); SB_CHK_ERR(!src, abort(), "sb_mat_memcpy: src cannot be NULL"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(dest->n_rows != src->n_rows, abort(), "sb_mat_memcpy: dest and src must have same number of rows"); SB_CHK_ERR(dest->n_cols != src->n_cols, abort(), "sb_mat_memcpy: dest and src must have same number of columns"); #endif memcpy(dest->data, src->data, src->n_elem * sizeof(double)); return dest; } /// Copies `n` elements of array `a` into the memory of matrix `A` starting at /// index `i`. `A` must have enough capacity, `a` must contain at least `n` /// elements, and `A` and `a` must not overlap in memory. /// /// # Parameters /// - `A`: pointer to destination matrix /// - `i`: index of `A` where the copy will start /// - `a`: pointer to elements that will be copied /// - `n`: number of elements to copy /// /// # Returns /// A copy of `A` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `A` and `a` are not `NULL` /// - `SAFE_LENGTH`: `A` has enough capacity /// /// # Examples /// ``` /// #include "sb_matrix.h" /// #include "sb_structs.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// /// // Overwrite elements of `A` and print /// sb_mat_print(A, "A before: ", "%g"); /// sb_mat_subcpy(A, 0, a + 1, 3); /// sb_mat_print(A, "A after: ", "%g"); /// /// SB_MAT_FREE_ALL(A); /// } /// ``` sb_mat * sb_mat_subcpy( sb_mat * restrict A, size_t i, const double * restrict a, size_t n) { #ifdef SAFE_MEMORY SB_CHK_ERR(!A, abort(), "sb_mat_subcpy: A cannot be NULL"); SB_CHK_ERR(!a, abort(), "sb_mat_subcpy: a cannot be NULL"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(A->n_elem - i < n, abort(), "sb_mat_subcpy: A does not have enough capacity"); #endif memcpy(A->data + i, a, n * sizeof(double)); return A; } /// Swaps the contents of `A` and `B` by exchanging data pointers. Matrices must /// have the same number of rows and columns and not overlap in memory. /// /// # Parameters /// - `A`: pointer to the first matrix /// - `B`: pointer to the second matrix /// /// # Returns /// No return value /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `A` and `B` are not `NULL` /// - `SAFE_LENGTH`: `A` and `B` have the same numbers of rows and columns /// /// # Examples /// ``` /// #include "matrix.h" /// #include "sb_structs.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2., 8.}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// sb_mat * B = sb_mat_of_arr(a + 1, 3, 3); /// /// // Print matrices before and after /// sb_mat_print(A, "A before: ", "%g"); /// sb_mat_print(B, "B before: ", "%g"); /// /// sb_mat_swap(A, B); /// /// sb_mat_print(A, "A after: ", "%g"); /// sb_mat_print(B, "B after: ", "%g"); /// /// SB_MAT_FREE_ALL(A, B); /// } /// ``` void sb_mat_swap(sb_mat * restrict A, sb_mat * restrict B) { #ifdef SAFE_MEMORY SB_CHK_ERR(!A, abort(), "sb_mat_swap: A cannot be NULL"); SB_CHK_ERR(!B, abort(), "sb_mat_swap: B cannot be NULL"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(A->n_rows != B->n_rows, abort(), "sb_mat_swap: A and B must have same number of rows"); SB_CHK_ERR(A->n_cols != B->n_cols, abort(), "sb_mat_swap: A and B must have same number of columns"); #endif double * scratch; SB_SWAP(A->data, B->data, scratch); } /// Swaps the `i`th and `j`th rows of the matrix `A`. /// /// # Parameters /// - `A`: pointer to the matrix /// /// # Returns /// A copy of `A` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `A` is not `NULL` /// - `SAFE_LENGTH`: `i` and `j` are valid row indices /// /// # Examples /// ``` /// #include "sb_matrix.h" /// #include "sb_structs.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// /// // Print matrix before and after /// sb_mat_print(A, "A before: ", "%g"); /// sb_mat_swap_row(A, 0, 1); /// sb_mat_print(A, "A after: ", "%g"); /// /// SB_MAT_FREE_ALL(A); /// } /// ``` sb_mat * sb_mat_swap_row(sb_mat * A, size_t i, size_t j) { #ifdef SAFE_MEMORY SB_CHK_ERR(!A, abort(), "sb_mat_swap_row: A cannot be NULL"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(i >= A->n_rows, abort(), "sb_mat_swap_row: i must be a valid row index"); SB_CHK_ERR(j >= A->n_rows, abort(), "sb_mat_swap_row: j must be a valid row index"); #endif double * data = A->data; size_t n_rows = A->n_rows; cblas_dswap(A->n_cols, data + i, n_rows, data + j, n_rows); return A; } /// Swaps the `i`th and `j`th columns of the matrix `A`. /// /// # Parameters /// - `A`: pointer to the matrix /// /// # Returns /// A copy of `A` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `A` is not `NULL` /// - `SAFE_LENGTH`: `i` and `j` are valid column indices /// /// # Examples /// ``` /// #include "sb_matrix.h" /// #include "sb_structs.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// /// // Print matrix before and after /// sb_mat_print(A, "A before: ", "%g"); /// sb_mat_swap_col(A, 0, 1); /// sb_mat_print(A, "A after: ", "%g"); /// /// SB_MAT_FREE_ALL(A); /// } /// ``` sb_mat * sb_mat_swap_col(sb_mat * A, size_t i, size_t j) { #ifdef SAFE_MEMORY SB_CHK_ERR(!A, abort(), "sb_mat_swap_row: A cannot be NULL"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(i >= A->n_cols, abort(), "sb_mat_swap_row: i must be a valid column index"); SB_CHK_ERR(j >= A->n_cols, abort(), "sb_mat_swap_row: j must be a valid column index"); #endif double * data = A->data; size_t n_rows = A->n_rows; cblas_dswap(n_rows, data + i * n_rows, 1, data + j * n_rows, 1); return A; } /// Writes the matrix `A` to `stream` in a binary format. The data is written /// in the native binary format of the architecture, and may not be portable. /// /// # Parameters /// - `stream`: an open I/O stream /// - `A`: pointer to the matrix /// /// # Returns /// `0` on success, or `1` if the write fails /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `A` is not `NULL` /// /// # Examples /// ``` /// #include <stdio.h> /// #include "sb_matrix.h" /// #include "sb_structs.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// /// // Write the matrix to file /// FILE * f = fopen("matrix.bin", "wb"); /// sb_mat_fwrite(f, A); /// fclose(f); /// /// // Read the matrix from file /// FILE * g = fopen("matrix.bin", "rb"); /// sb_mat * B = sb_mat_fread(g); /// fclose(g); /// /// // Matrices have the same contents /// sb_mat_print(A, "A: ", "%g"); /// sb_mat_print(B, "B: ", "%g"); /// /// SB_MAT_FREE_ALL(A, B); /// } /// ``` int sb_mat_fwrite(FILE * stream, const sb_mat * A) { #ifdef SAFE_MEMORY SB_CHK_ERR(!A, abort(), "sb_mat_fwrite: A cannot be NULL"); #endif size_t n_write; n_write = fwrite(&(A->n_rows), sizeof(size_t), 1, stream); SB_CHK_ERR(n_write != 1, return 1, "sb_mat_fwrite: fwrite failed"); n_write = fwrite(&(A->n_cols), sizeof(size_t), 1, stream); SB_CHK_ERR(n_write != 1, return 1, "sb_mat_fwrite: fwrite failed"); size_t n_elem = A->n_elem; n_write = fwrite(A->data, sizeof(double), n_elem, stream); SB_CHK_ERR(n_write != n_elem, return 1, "sb_mat_fwrite: fwrite failed"); return 0; } /// Writes the matrix `A` to `stream`. The number of elements and elements are /// written in a human readable format. /// /// # Parameters /// - `stream`: an open I/O stream /// - `A`: pointer to the matrix /// - `format`: a format specifier for the elements /// /// # Returns /// `0` on success, or `1` if the write fails /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `A` is not `NULL` /// /// # Examples /// ``` /// #include <stdio.h> /// #include "sb_matrix.h" /// #include "sb_structs.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// /// // Write the matrix to file /// FILE * f = fopen("matrix.txt", "w"); /// sb_mat_fprintf(f, A, "%lg"); /// fclose(f); /// /// // Read the matrix from file /// FILE * g = fopen("matrix.txt", "r"); /// sb_mat * B = sb_mat_fscanf(g); /// fclose(g); /// /// // Matrices have the same contents /// sb_mat_print(A, "A: ", "%g"); /// sb_mat_print(B, "B: ", "%g"); /// /// SB_MAT_FREE_ALL(A, B); /// } /// ``` int sb_mat_fprintf(FILE * stream, const sb_mat * A, const char * format) { #ifdef SAFE_MEMORY SB_CHK_ERR(!A, abort(), "sb_mat_fprintf: A cannot be NULL"); #endif int status; status = fprintf(stream, "%zu %zu", A->n_rows, A->n_cols); SB_CHK_ERR(status < 0, return 1, "sb_mat_fprintf: fprintf failed"); double * data = A->data; for (size_t a = 0; a < A->n_elem; ++a) { status = putc(' ', stream); SB_CHK_ERR(status == EOF, return 1, "sb_mat_fprintf: putc failed"); status = fprintf(stream, format, data[a]); SB_CHK_ERR(status < 0, return 1, "sb_mat_fprintf: fprintf failed"); } status = putc('\n', stream); SB_CHK_ERR(status == EOF, return 1, "sb_mat_fprintf: putc failed"); return 0; } /// Prints the matrix `A` to stdout. Output is slightly easier to read than for /// `sb_mat_fprintf()`. Mainly indended for debugging. /// /// # Parameters /// - `A`: pointer to the matrix /// - `str`: a string to describe the matrix /// - `format`: a format specifier for the elements /// /// # Returns /// `0` on success, or `1` if the print fails /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `A` is not `NULL` /// /// # Examples /// ``` /// #include "sb_matrix.h" /// #include "sb_structs.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4.}; /// sb_mat * A = sb_mat_of_arr(a, 2, 4); /// sb_mat * B = sb_mat_of_arr(a, 4, 2); /// /// // Prints the contents of `A` and `B` to stdout /// sb_mat_print(A, "A: ", "%g"); /// sb_mat_print(B, "B: ", "%g"); /// /// SB_MAT_FREE_ALL(A, B); /// } /// ``` int sb_mat_print(const sb_mat * A, const char * str, const char * format) { #ifdef SAFE_MEMORY SB_CHK_ERR(!A, abort(), "sb_mat_print: A cannot be NULL"); #endif int status; status = printf("%s\n", str); SB_CHK_ERR(status < 0, return 1, "sb_mat_print: printf failed"); size_t n_elem = A->n_elem; double * data = A->data; char buffer[128]; char * dec; bool dec_mark[n_elem]; bool any_mark = false; unsigned char length; unsigned char len_head[n_elem]; unsigned char max_head = 0; unsigned char len_tail[n_elem]; unsigned char max_tail = 0; for (size_t a = 0; a < n_elem; ++a) { status = snprintf(buffer, 128, format, data[a]); SB_CHK_ERR(status < 0, return 1, "sb_mat_print: snprintf failed"); dec = strchr(buffer, '.'); if (dec) { dec_mark[a] = true; any_mark = true; length = (unsigned char)(dec - buffer); len_head[a] = length; if (length > max_head) { max_head = length; } length = strlen(buffer) - length - 1; if (length > max_tail) { max_tail = length; } len_tail[a] = length; } else { dec_mark[a] = false; length = strlen(buffer); len_head[a] = length; if (length > max_head) { max_head = length; } len_tail[a] = 0; } } size_t n_rows = A->n_rows; size_t n_cols = A->n_cols; size_t index; for (size_t r = 0; r < n_rows; ++r) { for (size_t c = 0; c < n_cols; ++c) { index = c * n_rows + r; for (unsigned char s = 0; s < max_head - len_head[index]; ++s) { status = putchar(' '); SB_CHK_ERR(status == EOF, return 1, "sb_mat_print: putchar failed"); } status = printf(format, data[index]); SB_CHK_ERR(status < 0, return 1, "sb_mat_print: printf failed"); if (any_mark && !dec_mark[index]) { status = putchar(' '); SB_CHK_ERR(status == EOF, return 1, "sb_mat_print: putchar failed"); } for (unsigned char s = 0; s < max_tail - len_tail[index] + 1; ++s) { status = putchar(' '); SB_CHK_ERR(status == EOF, return 1, "sb_mat_print: putchar failed"); } } status = putchar('\n'); SB_CHK_ERR(status == EOF, return 1, "sb_mat_print: putchar failed"); } return 0; } /// Reads binary data from `stream` into the matrix returned by the function. /// The data must be written in the native binary format of the architecture, /// preferably by `sb_mat_fwrite()`. /// /// # Parameters /// - `stream`: an open I/O stream /// /// # Returns /// A `sb_mat` pointer to the matrix read from `stream`, or `NULL` if the read /// or memory allocation fails /// /// # Examples /// ``` /// #include <stdio.h> /// #include "sb_matrix.h" /// #include "sb_structs.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// /// // Write the matrix to file /// FILE * f = fopen("matrix.bin", "wb"); /// sb_mat_fwrite(f, A); /// fclose(f); /// /// // Read the matrix from file /// FILE * g = fopen("matrix.bin", "rb"); /// sb_mat * B = sb_mat_fread(g); /// fclose(g); /// /// // Matrices have the same contents /// sb_mat_print(A, "A: ", "%g"); /// sb_mat_print(B, "B: ", "%g"); /// /// SB_MAT_FREE_ALL(A, B); /// } /// ``` sb_mat * sb_mat_fread(FILE * stream) { size_t n_read; size_t n_rows; n_read = fread(&n_rows, sizeof(size_t), 1, stream); SB_CHK_ERR(n_read != 1, return NULL, "sb_mat_fread: fread failed"); size_t n_cols; n_read = fread(&n_cols, sizeof(size_t), 1, stream); SB_CHK_ERR(n_read != 1, return NULL, "sb_mat_fread: fread failed"); sb_mat * out = sb_mat_malloc(n_rows, n_cols); SB_CHK_ERR(!out, return NULL, "sb_mat_fread: sb_mat_malloc failed"); size_t n_elem = out->n_elem; n_read = fread(out->data, sizeof(double), n_elem, stream); SB_CHK_ERR(n_read != n_elem, sb_mat_free(out); return NULL, "sb_mat_fread: fread failed"); return out; } /// Reads formatted data from `stream` into the matrix returned by the function. /// /// # Parameters /// - `stream`: an open I/O stream /// /// # Returns /// A `sb_mat` pointer to the matrix read from `stream`, or `NULL` if the scan /// or memory allocation fails /// /// # Examples /// ``` /// #include <stdio.h> /// #include "sb_matrix.h" /// #include "sb_structs.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// /// // Write the matrix to file /// FILE * f = fopen("matrix.txt", "w"); /// sb_mat_fprintf(f, A, "%lg"); /// fclose(f); /// /// // Read the matrix from file /// FILE * g = fopen("matrix.txt", "r"); /// sb_mat * B = sb_mat_fscanf(g); /// fclose(g); /// /// // Matrices have the same contents /// sb_mat_print(A, "A: ", "%g"); /// sb_mat_print(B, "B: ", "%g"); /// /// SB_MAT_FREE_ALL(A, B); /// } /// ``` sb_mat * sb_mat_fscanf(FILE * stream) { int n_scan; size_t n_rows; size_t n_cols; n_scan = fscanf(stream, "%zu %zu", &n_rows, &n_cols); SB_CHK_ERR(n_scan != 2, return NULL, "sb_mat_fscanf: fscanf failed"); sb_mat * out = sb_mat_malloc(n_rows, n_cols); SB_CHK_ERR(!out, return NULL, "sb_mat_fscanf: sb_mat_malloc failed"); double * data = out->data; for (size_t a = 0; a < out->n_elem; ++a) { n_scan = fscanf(stream, "%lg", data + a); SB_CHK_ERR(n_scan != 1, sb_mat_free(out); return NULL, "sb_mat_fscanf: fscanf failed"); } return out; } /// Takes the absolute value of every element of the matrix. /// /// # Parameters /// - `A`: pointer to the matrix /// /// # Returns /// A copy of `A` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `A` is not `NULL` /// - `SAFE_FINITE`: elements of `A` are finite /// /// # Examples /// ``` /// #include "sb_matrix.h" /// #include "sb_structs.h" /// /// int main(void) { /// double a[] = {1., -4., 2., 8., 5., -7., -1., 4., 2.}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// /// // Take absolute value /// sb_mat_print(A, "A before: ", "%g"); /// sb_mat_abs(A); /// sb_mat_print(A, "A after: ", "%g"); /// /// SB_MAT_FREE_ALL(A); /// } /// ``` sb_mat * sb_mat_abs(sb_mat * A) { #ifdef SAFE_MEMORY SB_CHK_ERR(!A, abort(), "sb_mat_abs: A cannot be NULL"); #endif double * data = A->data; for (size_t a = 0; a < A->n_elem; ++a) { data[a] = fabs(data[a]); } #ifdef SAFE_FINITE SB_CHK_ERR(!sb_mat_is_finite(A), abort(), "sb_mat_abs: element not finite"); #endif return A; } /// Takes the exponent base `e` of every element of the matrix. /// /// # Parameters /// - `A`: pointer to the matrix /// /// # Returns /// A copy of `A` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `A` is not `NULL` /// - `SAFE_FINITE`: elements of `A` are finite /// /// # Examples /// ``` /// #include <math.h> /// #include "sb_matrix.h" /// #include "sb_structs.h" /// /// int main(void) { /// double a[] = {log(1.), log(4.), log(2.), /// log(8.), log(5.), log(7.), /// log(1.), log(4.), log(2.)}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// /// // Take exponent base e /// sb_mat_print(A, "A before: ", "%g"); /// sb_mat_exp(A); /// sb_mat_print(A, "A after: ", "%g"); /// /// SB_MAT_FREE_ALL(A); /// } /// ``` sb_mat * sb_mat_exp(sb_mat * A) { #ifdef SAFE_MEMORY SB_CHK_ERR(!A, abort(), "sb_mat_exp: A cannot be NULL"); #endif double * data = A->data; for (size_t a = 0; a < A->n_elem; ++a) { data[a] = exp(data[a]); } #ifdef SAFE_FINITE SB_CHK_ERR(!sb_mat_is_finite(A), abort(), "sb_mat_exp: element not finite"); #endif return A; } /// Takes the logarithm base `e` of every element of the matrix. /// /// # Parameters /// - `A`: pointer to the matrix /// /// # Returns /// A copy of `A` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `A` is not `NULL` /// - `SAFE_FINITE`: elements of `A` are finite /// /// # Examples /// ``` /// #include <math.h> /// #include "sb_matrix.h" /// #include "sb_structs.h" /// /// int main(void) { /// double a[] = {exp(1.), exp(4.), exp(2.), /// exp(8.), exp(5.), exp(7.), /// exp(1.), exp(4.), exp(2.)}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// /// // Take exponent base e /// sb_mat_print(A, "A before: ", "%g"); /// sb_mat_log(A); /// sb_mat_print(A, "A after: ", "%g"); /// /// SB_MAT_FREE_ALL(A); /// } /// ``` sb_mat * sb_mat_log(sb_mat * A) { #ifdef SAFE_MEMORY SB_CHK_ERR(!A, abort(), "sb_mat_log: A cannot be NULL"); #endif double * data = A->data; for (size_t a = 0; a < A->n_elem; ++a) { data[a] = log(data[a]); } #ifdef SAFE_FINITE SB_CHK_ERR(!sb_mat_is_finite(A), abort(), "sb_mat_log: element not finite"); #endif return A; } /// Exponentiates every element of the matrix `A` by `x`. /// /// # Parameters /// - `A`: pointer to the matrix /// - `x`: scalar exponent of the elements /// /// # Returns /// A copy of `A` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `A` is not `NULL` /// - `SAFE_FINITE`: elements of `A` are finite /// /// # Examples /// ``` /// #include "sb_matrix.h" /// #include "sb_structs.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// /// // Exponentiate every element by -1. /// sb_mat_print(A, "A before: ", "%g"); /// sb_mat_pow(A, -1.); /// sb_mat_print(A, "A after: ", "%g"); /// /// SB_MAT_FREE_ALL(A); /// } /// ``` sb_mat * sb_mat_pow(sb_mat * A, double x) { #ifdef SAFE_MEMORY SB_CHK_ERR(!A, abort(), "sb_mat_pow: A cannot be NULL"); #endif double * data = A->data; for (size_t a = 0; a < A->n_elem; ++a) { data[a] = pow(data[a], x); } #ifdef SAFE_FINITE SB_CHK_ERR(!sb_mat_is_finite(A), abort(), "sb_mat_pow: element not finite"); #endif return A; } /// Takes the square root of every element of the matrix `A`. /// /// # Parameters /// - `A`: pointer to the matrix /// - `x`: scalar exponent of the elements /// /// # Returns /// A copy of `A` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `A` is not `NULL` /// - `SAFE_FINITE`: elements of `A` are finite /// /// # Examples /// ``` /// #include "sb_matrix.h" /// #include "sb_structs.h" /// /// int main(void) { /// double a[] = {1., 16., 4., 64., 25., 49., 1., 16., 4.}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// /// // Take the square root of every element /// sb_mat_print(A, "A before: ", "%g"); /// sb_mat_sqrt(A); /// sb_mat_print(A, "A after: ", "%g"); /// /// SB_MAT_FREE_ALL(A); /// } /// ``` sb_mat * sb_mat_sqrt(sb_mat * A) { #ifdef SAFE_MEMORY SB_CHK_ERR(!A, abort(), "sb_mat_sqrt: A cannot be NULL"); #endif double * data = A->data; for (size_t a = 0; a < A->n_elem; ++a) { data[a] = sqrt(data[a]); } #ifdef SAFE_FINITE SB_CHK_ERR(!sb_mat_is_finite(A), abort(), "sb_mat_sqrt: element not finite"); #endif return A; } /// Scalar addition of `x` to every element of the matrix `A`. /// /// # Parameters /// - `A`: pointer to the matrix /// - `x`: scalar added to the elements /// /// # Returns /// A copy of `A` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `A` is not `NULL` /// - `SAFE_FINITE`: elements of `A` are finite /// /// # Examples /// ``` /// #include "sb_matrix.h" /// #include "sb_structs.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// /// // Add 2. to every element /// sb_mat_print(A, "A before: ", "%g"); /// sb_mat_sadd(A, 2.); /// sb_mat_print(A, "A after: ", "%g"); /// /// SB_MAT_FREE_ALL(A); /// } /// ``` sb_mat * sb_mat_sadd(sb_mat * A, double x) { #ifdef SAFE_MEMORY SB_CHK_ERR(!A, abort(), "sb_mat_sadd: A cannot be NULL"); #endif double * data = A->data; for (size_t a = 0; a < A->n_elem; ++a) { data[a] += x; } #ifdef SAFE_FINITE SB_CHK_ERR(!sb_mat_is_finite(A), abort(), "sb_mat_sadd: element not finite"); #endif return A; } /// Scalar multiplication of `x` with every element of the matrix `A`. /// /// # Parameters /// - `A`: pointer to the matrix /// - `x`: scalar mutiplier for the elements /// /// # Returns /// A copy of `A` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `A` is not `NULL` /// - `SAFE_FINITE`: elements of `A` are finite /// /// # Examples /// ``` /// #include "sb_matrix.h" /// #include "sb_structs.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// /// // Multiply every element by -1. /// sb_mat_print(A, "A before: ", "%g"); /// sb_mat_smul(A, -1.); /// sb_mat_print(A, "A after: ", "%g"); /// /// SB_MAT_FREE_ALL(A); /// } /// ``` sb_mat * sb_mat_smul(sb_mat * A, double x) { #ifdef SAFE_MEMORY SB_CHK_ERR(!A, abort(), "sb_mat_smul: A cannot be NULL"); #endif cblas_dscal(A->n_elem, x, A->data, 1); #ifdef SAFE_FINITE SB_CHK_ERR(!sb_mat_is_finite(A), abort(), "sb_mat_smul: elements not finite"); #endif return A; } /// Adds to every row or column of the matrix `A` the corresponding element of /// the vector `v`. `A` and `v` must not overlap in memory. /// /// # Parameters /// - `A`: pointer to the matrix /// - `v`: pointer to the vector /// - `dir`: one of 'r' or 'c' /// /// # Returns /// A copy of `A` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `A` and `v` are not `NULL` /// - `SAFE_LAYOUT`: the layout of `v` is compatible with `dir` /// - `SAFE_LENGTH`: `A` and `v` have compatible dimensions /// - `SAFE_FINITE`: elements of `A` are finite /// /// # Examples /// ``` /// #include "sb_matrix.h" /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// /// // Add v to every column of A /// sb_vec_print(v, "v: ", "%g"); /// sb_mat_print(A, "A before: ", "%g"); /// sb_mat_vadd(A, v, 'c'); /// sb_mat_print(A, "A after: ", "%g"); /// /// SB_MAT_FREE_ALL(A); /// SB_VEC_FREE_ALL(v); /// } /// ``` sb_mat * sb_mat_vadd(sb_mat * restrict A, const sb_vec * restrict v, char dir) { #ifdef SAFE_MEMORY SB_CHK_ERR(!A, abort(), "sb_mat_vadd: A cannot be NULL"); SB_CHK_ERR(!v, abort(), "sb_mat_vadd: v cannot be NULL"); #endif size_t n_rows = A->n_rows; size_t n_cols = A->n_cols; double * A_data = A->data; double * v_data = v->data; switch (dir) { case 'c': #ifdef SAFE_LAYOUT SB_CHK_ERR(v->layout != 'r', abort(), "sb_mat_vadd: v must be a row vector"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(A->n_cols != v->n_elem, abort(), "sb_mat_vadd: A and v must have same number of columns"); #endif for (size_t a = 0; a < n_rows; ++a) { cblas_daxpy(n_cols, 1., v_data, 1, A_data + a, n_rows); } break; case 'r': #ifdef SAFE_LAYOUT SB_CHK_ERR(v->layout != 'c', abort(), "sb_mat_radd: v must be a column vector"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(A->n_rows != v->n_elem, abort(), "sb_mat_radd: A and v must have same number of rows"); #endif for (size_t a = 0; a < n_cols; ++a) { cblas_daxpy(n_rows, 1., v_data, 1, A_data + a * n_rows, 1); } break; default: SB_CHK_ERR(true, abort(), "sb_mat_vadd: dir must 'c' or 'r'"); break; } #ifdef SAFE_FINITE SB_CHK_ERR(!sb_mat_is_finite(A), abort(), "sb_mat_vadd: elements not finite"); #endif return A; } /// Subtracts from every row or column of the matrix `A` the corresponding /// element of the vector `v`. `A` and `v` must not overlap in memory. /// /// # Parameters /// - `A`: pointer to the matrix /// - `v`: pointer to the vector /// - `dir`: one of 'r' or 'c' /// /// # Returns /// A copy of `A` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `A` and `v` are not `NULL` /// - `SAFE_LAYOUT`: the layout of `v` is compatible with `dir` /// - `SAFE_LENGTH`: `A` and `v` have compatible dimensions /// - `SAFE_FINITE`: elements of `A` are finite /// /// # Examples /// ``` /// #include "sb_matrix.h" /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// /// // Subtracts v from every column of A /// sb_vec_print(v, "v: ", "%g"); /// sb_mat_print(A, "A before: ", "%g"); /// sb_mat_vsub(A, v, 'c'); /// sb_mat_print(A, "A after: ", "%g"); /// /// SB_MAT_FREE_ALL(A); /// SB_VEC_FREE_ALL(v); /// } /// ``` sb_mat * sb_mat_vsub(sb_mat * restrict A, const sb_vec * restrict v, char dir) { #ifdef SAFE_MEMORY SB_CHK_ERR(!A, abort(), "sb_mat_vsub: A cannot be NULL"); SB_CHK_ERR(!v, abort(), "sb_mat_vsub: v cannot be NULL"); #endif size_t n_rows = A->n_rows; size_t n_cols = A->n_cols; double * A_data = A->data; double * v_data = v->data; switch (dir) { case 'c': #ifdef SAFE_LAYOUT SB_CHK_ERR(v->layout != 'r', abort(), "sb_mat_vsub: v must be a row vector"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(A->n_cols != v->n_elem, abort(), "sb_mat_vsub: A and v must have same number of columns"); #endif for (size_t a = 0; a < n_rows; ++a) { cblas_daxpy(n_cols, -1., v_data, 1, A_data + a, n_rows); } break; case 'r': #ifdef SAFE_LAYOUT SB_CHK_ERR(v->layout != 'c', abort(), "sb_mat_rsub: v must be a column vector"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(A->n_rows != v->n_elem, abort(), "sb_mat_rsub: A and v must have same number of rows"); #endif for (size_t a = 0; a < n_cols; ++a) { cblas_daxpy(n_rows, -1., v_data, 1, A_data + a * n_rows, 1); } break; default: SB_CHK_ERR(true, abort(), "sb_mat_vsub: dir must 'c' or 'r'"); break; } #ifdef SAFE_FINITE SB_CHK_ERR(!sb_mat_is_finite(A), abort(), "sb_mat_vsub: elements not finite"); #endif return A; } /// Multiplies every row or column of the matrix `A` by the corresonding /// element of the vector `v`. `A` and `v` must not overlap in memory. /// /// # Parameters /// - `A`: pointer to the matrix /// - `v`: pointer to the vector /// - `dir`: one of 'r' or 'c' /// /// # Returns /// A copy of `A` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `A` and `v` are not `NULL` /// - `SAFE_LAYOUT`: the layout of `v` is compatible with `dir` /// - `SAFE_LENGTH`: `A` and `v` have compatible dimensions /// - `SAFE_FINITE`: elements of `A` are finite /// /// # Examples /// ``` /// #include "sb_matrix.h" /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// /// // Multiplies every column of A by corresponding element of v /// sb_vec_print(v, "v: ", "%g"); /// sb_mat_print(A, "A before: ", "%g"); /// sb_mat_vmul(A, v, 'c'); /// sb_mat_print(A, "A after: ", "%g"); /// /// SB_MAT_FREE_ALL(A); /// SB_VEC_FREE_ALL(v); /// } /// ``` sb_mat * sb_mat_vmul(sb_mat * restrict A, const sb_vec * restrict v, char dir) { #ifdef SAFE_MEMORY SB_CHK_ERR(!A, abort(), "sb_mat_vmul: A cannot be NULL"); SB_CHK_ERR(!v, abort(), "sb_mat_vmul: v cannot be NULL"); #endif size_t n_rows = A->n_rows; size_t n_cols = A->n_cols; double * A_data = A->data; double * v_data = v->data; switch (dir) { case 'c': #ifdef SAFE_LAYOUT SB_CHK_ERR(v->layout != 'r', abort(), "sb_mat_vmul: v must be a row vector"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(A->n_cols != v->n_elem, abort(), "sb_mat_vmul: A and v must have same number of columns"); #endif for (size_t a = 0; a < n_cols; ++a) { cblas_dscal(n_rows, v_data[a], A_data + a * n_rows, 1); } break; case 'r': #ifdef SAFE_LAYOUT SB_CHK_ERR(v->layout != 'c', abort(), "sb_mat_vmul: v must be a column vector"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(A->n_rows != v->n_elem, abort(), "sb_mat_vmul: A and v must have same number of rows"); #endif for (size_t a = 0; a < n_rows; ++a) { cblas_dscal(n_cols, v_data[a], A_data + a, n_rows); } break; default: SB_CHK_ERR(true, abort(), "sb_mat_vmul: dir must 'c' or 'r'"); break; } #ifdef SAFE_FINITE SB_CHK_ERR(!sb_mat_is_finite(A), abort(), "sb_mat_vmul: elements not finite"); #endif return A; } /// Divides every column or row of the matrix `A` by the corresonding element /// of the vector `v`. `A` and `v` must not overlap in memory. /// /// # Parameters /// - `A`: pointer to the matrix /// - `v`: pointer to the vector /// - `dir`: one of 'r' or 'c' /// /// # Returns /// A copy of `A` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `A` and `v` are not `NULL` /// - `SAFE_LAYOUT`: the layout of `v` is compatible with `dir` /// - `SAFE_LENGTH`: `A` and `v` have compatible dimensions /// - `SAFE_FINITE`: elements of `A` are finite /// /// # Examples /// ``` /// #include "sb_matrix.h" /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// /// // Divides every column of A by corresponding element of v /// sb_vec_print(v, "v: ", "%g"); /// sb_mat_print(A, "A before: ", "%g"); /// sb_mat_vdiv(A, v, 'c'); /// sb_mat_print(A, "A after: ", "%g"); /// /// SB_MAT_FREE_ALL(A); /// SB_VEC_FREE_ALL(v); /// } /// ``` sb_mat * sb_mat_vdiv(sb_mat * restrict A, const sb_vec * restrict v, char dir) { #ifdef SAFE_MEMORY SB_CHK_ERR(!A, abort(), "sb_mat_vdiv: A cannot be NULL"); SB_CHK_ERR(!v, abort(), "sb_mat_vdiv: v cannot be NULL"); #endif size_t n_rows = A->n_rows; size_t n_cols = A->n_cols; double * A_data = A->data; double * v_data = v->data; switch (dir) { case 'c': #ifdef SAFE_LAYOUT SB_CHK_ERR(v->layout != 'r', abort(), "sb_mat_vdiv: v must be a row vector"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(A->n_cols != v->n_elem, abort(), "sb_mat_vdiv: A and v must have same number of columns"); #endif for (size_t a = 0; a < n_cols; ++a) { cblas_dscal(n_rows, 1. / v_data[a], A_data + a * n_rows, 1); } break; case 'r': #ifdef SAFE_LAYOUT SB_CHK_ERR(v->layout != 'c', abort(), "sb_mat_rdiv: v must be a column vector"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(A->n_rows != v->n_elem, abort(), "sb_mat_rdiv: A and v must have same number of rows"); #endif for (size_t a = 0; a < n_rows; ++a) { cblas_dscal(n_cols, 1. / v_data[a], A_data + a, n_rows); } break; default: SB_CHK_ERR(true, abort(), "sb_mat_vdiv: dir must 'c' or 'r'"); break; } #ifdef SAFE_FINITE SB_CHK_ERR(!sb_mat_is_finite(A), abort(), "sb_mat_vdiv: elements not finite"); #endif return A; } /// Pointwise addition of elements of the matrix `B` to elements of the matrix /// `A`. `A` and `B` must not overlap in memory. /// /// # Parameters /// - `A`: pointer to the first matrix /// - `B`: pointer to the second matrix /// /// # Returns /// A copy of `A` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `A` and `B` are not `NULL` /// - `SAFE_LENGTH`: `A` and `B` have the same number of rows and columns /// - `SAFE_FINITE`: elements of `A` are finite /// /// # Examples /// ``` /// #include "sb_matrix.h" /// #include "sb_structs.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2., 8.}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// sb_mat * B = sb_mat_of_arr(a + 1, 3, 3); /// /// // Add B to A /// sb_mat_print(A, "A: ", "%g"); /// sb_mat_print(B, "B: ", "%g"); /// sb_mat_padd(A, B); /// sb_mat_print(A, "A after: ", "%g"); /// /// SB_MAT_FREE_ALL(A, B); /// } /// ``` sb_mat * sb_mat_padd(sb_mat * restrict A, const sb_mat * restrict B) { #ifdef SAFE_MEMORY SB_CHK_ERR(!A, abort(), "sb_mat_padd: A cannot be NULL"); SB_CHK_ERR(!B, abort(), "sb_mat_padd: B cannot be NULL"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(A->n_rows != B->n_rows, abort(), "sb_mat_padd: A and B must have same number of rows"); SB_CHK_ERR(A->n_cols != B->n_cols, abort(), "sb_mat_padd: A and B must have same number of columns"); #endif cblas_daxpy(A->n_elem, 1., B->data, 1, A->data, 1); #ifdef SAFE_FINITE SB_CHK_ERR(!sb_mat_is_finite(A), abort(), "sb_mat_padd: elements not finite"); #endif return A; } /// Pointwise subtraction of elements of the matrix `B` from elements of the /// matrix `A`. `A` and `B` must not overlap in memory. /// /// # Parameters /// - `A`: pointer to the first matrix /// - `B`: pointer to the second matrix /// /// # Returns /// A copy of `A` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `A` and `B` are not `NULL` /// - `SAFE_LENGTH`: `A` and `B` have the same number of rows and columns /// - `SAFE_FINITE`: elements of `A` are finite /// /// # Examples /// ``` /// #include "sb_matrix.h" /// #include "sb_structs.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2., 8.}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// sb_mat * B = sb_mat_of_arr(a + 1, 3, 3); /// /// // Subtract B from A /// sb_mat_print(A, "A: ", "%g"); /// sb_mat_print(B, "B: ", "%g"); /// sb_mat_psub(A, B); /// sb_mat_print(A, "A after: ", "%g"); /// /// SB_MAT_FREE_ALL(A, B); /// } /// ``` sb_mat * sb_mat_psub(sb_mat * restrict A, const sb_mat * restrict B) { #ifdef SAFE_MEMORY SB_CHK_ERR(!A, abort(), "sb_mat_psub: A cannot be NULL"); SB_CHK_ERR(!B, abort(), "sb_mat_psub: B cannot be NULL"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(A->n_rows != B->n_rows, abort(), "sb_mat_psub: A and B must have same number of rows"); SB_CHK_ERR(A->n_cols != B->n_cols, abort(), "sb_mat_psub: A and B must have same number of columns"); #endif cblas_daxpy(A->n_elem, -1., B->data, 1, A->data, 1); #ifdef SAFE_FINITE SB_CHK_ERR(!sb_mat_is_finite(A), abort(), "sb_mat_psub: elements not finite"); #endif return A; } /// Pointwise multiplication of elements of the matrix `A` with elements of the /// matrix `B`. `A` and `B` must not overlap in memory. /// /// # Parameters /// - `A`: pointer to the first matrix /// - `B`: pointer to the second matrix /// /// # Returns /// A copy of `A` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `A` and `B` are not `NULL` /// - `SAFE_LENGTH`: `A` and `B` have the same number of rows and columns /// - `SAFE_FINITE`: elements of `A` are finite /// /// # Examples /// ``` /// #include "sb_matrix.h" /// #include "sb_structs.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2., 8.}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// sb_mat * B = sb_mat_of_arr(a + 1, 3, 3); /// /// // Multiply elements of A by elements of B /// sb_mat_print(A, "A: ", "%g"); /// sb_mat_print(B, "B: ", "%g"); /// sb_mat_pmul(A, B); /// sb_mat_print(A, "A after: ", "%g"); /// /// SB_MAT_FREE_ALL(A, B); /// } /// ``` sb_mat * sb_mat_pmul(sb_mat * restrict A, const sb_mat * restrict B) { #ifdef SAFE_MEMORY SB_CHK_ERR(!A, abort(), "sb_mat_pmul: A cannot be NULL"); SB_CHK_ERR(!B, abort(), "sb_mat_pmul: B cannot be NULL"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(A->n_rows != B->n_rows, abort(), "sb_mat_pmul: A and B must have same number of rows"); SB_CHK_ERR(A->n_cols != B->n_cols, abort(), "sb_mat_pmul: A and B must have same number of columns"); #endif double * A_data = A->data; double * B_data = B->data; for (size_t a = 0; a < A->n_elem; ++a) { A_data[a] *= B_data[a]; } #ifdef SAFE_FINITE SB_CHK_ERR(!sb_mat_is_finite(A), abort(), "sb_mat_pmul: element not finite"); #endif return A; } /// Pointwise division of elements of the matrix `A` by elements of the matrix /// `B`. `A` and `B` must not overlap in memory. /// /// # Parameters /// - `A`: pointer to the first matrix /// - `B`: pointer to the second matrix /// /// # Returns /// A copy of `A` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `A` and `B` are not `NULL` /// - `SAFE_LENGTH`: `A` and `B` have the same number of rows and columns /// - `SAFE_FINITE`: elements of `A` are finite /// /// # Examples /// ``` /// #include "sb_matrix.h" /// #include "sb_structs.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2., 8.}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// sb_mat * B = sb_mat_of_arr(a + 1, 3, 3); /// /// // Divide elements of A by elements of B /// sb_mat_print(A, "A: ", "%g"); /// sb_mat_print(B, "B: ", "%g"); /// sb_mat_pdiv(A, B); /// sb_mat_print(A, "A after: ", "%g"); /// /// SB_MAT_FREE_ALL(A, B); /// } /// ``` sb_mat * sb_mat_pdiv(sb_mat * restrict A, const sb_mat * restrict B) { #ifdef SAFE_MEMORY SB_CHK_ERR(!A, abort(), "sb_mat_pdiv: A cannot be NULL"); SB_CHK_ERR(!B, abort(), "sb_mat_pdiv: B cannot be NULL"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(A->n_rows != B->n_rows, abort(), "sb_mat_pdiv: A and B must have same number of rows"); SB_CHK_ERR(A->n_cols != B->n_cols, abort(), "sb_mat_pdiv: A and B must have same number of columns"); #endif double * A_data = A->data; double * B_data = B->data; for (size_t a = 0; a < A->n_elem; ++a) { A_data[a] /= B_data[a]; } #ifdef SAFE_FINITE SB_CHK_ERR(!sb_mat_is_finite(A), abort(), "sb_mat_pdiv: element not finite"); #endif return A; } /// Matrix-vector multiplication of `op(A)` and `w`, where `op` can be nothing /// or a transpose. The result is stored in the vector `v`, and any previous /// values in `v` are overwritten. `v`, `A` and `w` must not overlap in memory. /// /// # Parameters /// - `v`: pointer to the resulting vector /// - `A`: pointer to the left matrix /// - `w`: pointer to the right vector /// - `op`: 'n' or 't' /// /// # Returns /// A copy of `v` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v`, `A` and `w` are not `NULL` /// - `SAFE_LAYOUT`: `v` and `w` must be column vectors /// - `SAFE_LENGTH`: `v`, `A` and `w` have compatible dimensions /// - `SAFE_FINITE`: elements of `v` are finite /// /// # Examples /// ``` /// #include "sb_matrix.h" /// #include "sb_structs.h" /// #Include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.}; /// sb_vec * v = sb_vec_malloc(3, 'c'); /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// sb_vec * w = sb_vec_of_arr(a + 1, 3, 'c'); /// /// // Multiply A by w and store in v /// sb_mat_print(A, "A: ", "%g"); /// sb_vec_print(w, "w: ", "%g"); /// sb_mat_mv_mul(v, A, w, 'n'); /// sb_vec_print(v, "v: ", "%g"); /// /// SB_MAT_FREE_ALL(A); /// SB_VEC_FREE_ALL(v, w); /// } /// ``` sb_vec * sb_mat_mv_mul( sb_vec * restrict v, const sb_mat * restrict A, const sb_vec * restrict w, char op) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_mat_mv_mul: v cannot be NULL"); SB_CHK_ERR(!A, abort(), "sb_mat_mv_mul: A cannot be NULL"); SB_CHK_ERR(!w, abort(), "sb_mat_mv_mul: w cannot be NULL"); #endif #ifdef SAFE_LAYOUT SB_CHK_ERR(v->layout != 'c', abort(), "sb_mat_mv_mul: v must be a column vector"); SB_CHK_ERR(w->layout != 'c', abort(), "sb_mat_mv_mul: w must be a column vector"); #endif switch (op) { case 'n': #ifdef SAFE_LENGTH SB_CHK_ERR(v->n_elem != A->n_rows, abort(), "sb_mat_mv_mul: v and A must have same number of rows"); SB_CHK_ERR(A->n_cols != w->n_elem, abort(), "sb_mat_mv_mul: A and w must have compatible inner dimensions"); #endif cblas_dgemv(CblasColMajor, CblasNoTrans, A->n_rows, A->n_cols, 1., A->data, A->n_rows, w->data, 1, 0., v->data, 1); break; case 't': #ifdef SAFE_LENGTH SB_CHK_ERR(v->n_elem != A->n_cols, abort(), "sb_mat_mv_mul: v and A^T must have same number of rows"); SB_CHK_ERR(A->n_rows != w->n_elem, abort(), "sb_mat_mv_mul: A^T and w must have compatible inner dimensions"); #endif cblas_dgemv(CblasColMajor, CblasTrans, A->n_rows, A->n_cols, 1., A->data, A->n_rows, w->data, 1, 0., v->data, 1); break; default: SB_CHK_ERR(true, abort(), "sb_mat_mv_mul: op must 'n' or 't'"); break; } #ifdef SAFE_FINITE SB_CHK_ERR(!sb_vec_is_finite(v), abort(), "sb_mat_mv_mul: elements not finite"); #endif return v; } /// Vector-matrix multiplication of `w` and `op(A)`, where `op` can be nothing /// or a transpose. The result is stored in the vector `v`, and any previous /// values in `v` are overwritten. `v`, `w` and `A` must not overlap in memory. /// /// # Parameters /// - `v`: pointer to the resulting vector /// - `w`: pointer to the left vector /// - `A`: pointer to the right matrix /// - `op`: 'n' or 't' /// /// # Returns /// A copy of `v` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v`, `w` and `A` are not `NULL` /// - `SAFE_LAYOUT`: `v` and `w` must be row vectors /// - `SAFE_LENGTH`: `v`, `w` and `A` have compatible dimensions /// - `SAFE_FINITE`: elements of `v` are finite /// /// # Examples /// ``` /// #include "sb_matrix.h" /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.}; /// sb_vec * v = sb_vec_malloc(3, 'r'); /// sb_vec * w = sb_vec_of_arr(a + 1, 3, 'r'); /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// /// // Multiply w by A and store in v /// sb_vec_print(w, "w: ", "%g"); /// sb_mat_print(A, "A: ", "%g"); /// sb_mat_vm_mul(v, w, A, 'n'); /// sb_vec_print(v, "v: ", "%g"); /// /// SB_MAT_FREE_ALL(A); /// SB_VEC_FREE_ALL(v, w); /// } /// ``` sb_vec * sb_mat_vm_mul( sb_vec * restrict v, const sb_vec * restrict w, const sb_mat * restrict A, char op) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_mat_vm_mul: v cannot be NULL"); SB_CHK_ERR(!w, abort(), "sb_mat_vm_mul: w cannot be NULL"); SB_CHK_ERR(!A, abort(), "sb_mat_vm_mul: A cannot be NULL"); #endif #ifdef SAFE_LAYOUT SB_CHK_ERR(v->layout != 'r', abort(), "sb_mat_vm_mul: v must be a row vector"); SB_CHK_ERR(w->layout != 'r', abort(), "sb_mat_vm_mul: w must be a row vector"); #endif switch (op) { case 'n': #ifdef SAFE_LENGTH SB_CHK_ERR(v->n_elem != A->n_cols, abort(), "sb_mat_vm_mul: v and A must have same number of columns"); SB_CHK_ERR(A->n_rows != w->n_elem, abort(), "sb_mat_vm_mul: A and w must have compatible inner dimensions"); #endif cblas_dgemv(CblasColMajor, CblasTrans, A->n_rows, A->n_cols, 1., A->data, A->n_rows, w->data, 1, 0., v->data, 1); break; case 't': #ifdef SAFE_LENGTH SB_CHK_ERR(v->n_elem != A->n_rows, abort(), "sb_mat_vm_mul: v and A^T must have same number of columns"); SB_CHK_ERR(A->n_cols != w->n_elem, abort(), "sb_mat_vm_mul: A^T and w must have compatible inner dimensions"); #endif cblas_dgemv(CblasColMajor, CblasNoTrans, A->n_rows, A->n_cols, 1., A->data, A->n_rows, w->data, 1, 0., v->data, 1); break; default: SB_CHK_ERR(true, abort(), "sb_mat_vm_mul: op must 'n' or 't'"); break; } #ifdef SAFE_FINITE SB_CHK_ERR(!sb_vec_is_finite(v), abort(), "sb_mat_vm_mul: elements not finite"); #endif return v; } /// Matrix multiplication of `op(B)` and `op(C)`, where `op` can be nothing or /// a transpose. The result is stored in `A`, and any previous values in `A` /// are overwritten. `A` must not overlap `B` or `C` in memory. /// /// # Parameters /// - `A`: pointer to the resulting matrix /// - `B`: pointer to the left matrix /// - `C`: pointer to the right matrix /// - `ops`: one of "nn", "nt", "tn", or "tt" /// /// # Returns /// A copy of `A` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `A`, `B` and `C` are not `NULL` /// - `SAFE_LENGTH`: `A`, `B` and `C` have compatible dimensions /// - `SAFE_FINITE`: elements of `A` are finite /// /// # Examples /// ``` /// #include "sb_matrix.h" /// #include "sb_structs.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2., 8.}; /// sb_mat * A = sb_mat_malloc(3, 3); /// sb_mat * B = sb_mat_of_arr(a, 3, 3); /// sb_mat * C = sb_mat_of_arr(a + 1, 3, 3); /// /// // Multiply B by C and store in A /// sb_mat_print(B, "B: ", "%g"); /// sb_mat_print(C, "C: ", "%g"); /// sb_mat_mm_mul(A, B, C, "nn"); /// sb_mat_print(A, "A: ", "%g"); /// /// SB_MAT_FREE_ALL(A, B, C); /// } /// ``` sb_mat * sb_mat_mm_mul( sb_mat * restrict A, const sb_mat * restrict B, const sb_mat * restrict C, const char * restrict ops) { #ifdef SAFE_MEMORY SB_CHK_ERR(!A, abort(), "sb_mat_mm_mul: A cannot be NULL"); SB_CHK_ERR(!B, abort(), "sb_mat_mm_mul: B cannot be NULL"); SB_CHK_ERR(!C, abort(), "sb_mat_mm_mul: C cannot be NULL"); #endif switch ((*ops << 8) + *(ops + 1)) { case 0x6E6E: // "nn" #ifdef SAFE_LENGTH SB_CHK_ERR(A->n_rows != B->n_rows, abort(), "sb_mat_mm_mul: A and B must have same number of rows"); SB_CHK_ERR(A->n_cols != C->n_cols, abort(), "sb_mat_mm_mul: A and C must have same number of columns"); SB_CHK_ERR(B->n_cols != C->n_rows, abort(), "sb_mat_mm_mul: B and C must have compatible inner dimensions"); #endif cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, A->n_rows, A->n_cols, B->n_cols, 1., B->data, B->n_rows, C->data, C->n_rows, 0., A->data, A->n_rows); break; case 0x6E74: // "nt" #ifdef SAFE_LENGTH SB_CHK_ERR(A->n_rows != B->n_rows, abort(), "sb_mat_mm_mul: A and B must have same number of rows"); SB_CHK_ERR(A->n_cols != C->n_rows, abort(), "sb_mat_mm_mul: A and C^T must have same number of columns"); SB_CHK_ERR(B->n_cols != C->n_cols, abort(), "sb_mat_mm_mul: B and C^T must have compatible inner dimensions"); #endif cblas_dgemm(CblasColMajor, CblasNoTrans, CblasTrans, A->n_rows, A->n_cols, B->n_cols, 1., B->data, B->n_rows, C->data, C->n_rows, 0., A->data, A->n_rows); break; case 0x746E: // "tn" #ifdef SAFE_LENGTH SB_CHK_ERR(A->n_rows != B->n_cols, abort(), "sb_mat_mm_mul: A and B^T must have same number of rows"); SB_CHK_ERR(A->n_cols != C->n_cols, abort(), "sb_mat_mm_mul: A and C must have same number of columns"); SB_CHK_ERR(B->n_rows != C->n_rows, abort(), "sb_mat_mm_mul: B^T and C must have compatible inner dimensions"); #endif cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans, A->n_rows, A->n_cols, B->n_rows, 1., B->data, B->n_rows, C->data, C->n_rows, 0., A->data, A->n_rows); break; case 0x7474: // "tt" #ifdef SAFE_LENGTH SB_CHK_ERR(A->n_rows != B->n_cols, abort(), "sb_mat_mm_mul: A and B^T must have same number of rows"); SB_CHK_ERR(A->n_cols != C->n_rows, abort(), "sb_mat_mm_mul: A and C^T must have same number of columns"); SB_CHK_ERR(B->n_rows != C->n_cols, abort(), "sb_mat_mm_mul: B^T and C^T must have compatible inner dimensions"); #endif cblas_dgemm(CblasColMajor, CblasTrans, CblasTrans, A->n_rows, A->n_cols, B->n_rows, 1., B->data, B->n_rows, C->data, C->n_rows, 0., A->data, A->n_rows); break; default: SB_CHK_ERR(true, abort(), "sb_mat_mm_mul: ops must be one of \"nn\", \"nt\", \"tn\", or \"tt\""); break; } #ifdef SAFE_FINITE SB_CHK_ERR(!sb_mat_is_finite(A), abort(), "sb_mat_mm_mul: elements not finite"); #endif return A; } /// Sums over the rows or columns of the matrix `A`. The result is stored in /// `v`, and any previous values in `v` are overwritten. `v` and `A` must not /// overlap in memory. /// /// # Parameters /// - `v`: pointer to the resulting vector /// - `A`: pointer to the matrix to be summed /// - `dir`: one of 'r' or 'c' /// /// # Returns /// A copy of `v` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` and `A` are not `NULL` /// - `SAFE_LAYOUT`: the layout of `v` is consistent with `dir` /// - `SAFE_LENGTH`: `v` and `A` have compatible dimensions /// - `SAFE_FINITE`: elements of `v` are finite /// /// # Examples /// ``` /// #include "sb_matrix.h" /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.}; /// sb_vec * v = sb_vec_malloc(3, 'c'); /// sb_vec * w = sb_vec_malloc(3, 'r'); /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// /// sb_mat_print(A, "A: ", "%g"); /// // Sum over the rows of A /// sb_mat_sum(v, A, 'r'); /// sb_vec_print(v, "v: ", "%g"); /// // Sum over the cols of A /// sb_mat_sum(w, A, 'c'); /// sb_vec_print(w, "w: ", "%g"); /// /// SB_MAT_FREE_ALL(A); /// SB_VEC_FREE_ALL(v, w); /// } /// ``` sb_vec * sb_mat_sum(sb_vec * restrict v, const sb_mat * restrict A, const char dir) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_mat_sum: v cannot be NULL"); SB_CHK_ERR(!A, abort(), "sb_mat_sum: A cannot be NULL"); #endif size_t n_rows = A->n_rows; size_t n_cols = A->n_cols; double * A_data = A->data; double * v_data = v->data; switch (dir) { case 'c': #ifdef SAFE_LAYOUT SB_CHK_ERR(v->layout != 'r', abort(), "sb_mat_sum: v must be a row vector"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(v->n_elem != A->n_cols, abort(), "sb_mat_sum: v and A must have same number of columns"); #endif sb_vec_set_zero(v); for (size_t a = 0; a < n_rows; ++a) { cblas_daxpy(n_cols, 1., A_data + a, n_rows, v_data, 1); } break; case 'r': #ifdef SAFE_LAYOUT SB_CHK_ERR(v->layout != 'c', abort(), "sb_mat_sum: v must be a column vector"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(v->n_elem != A->n_rows, abort(), "sb_mat_sum: v and A must have same number of rows"); #endif sb_vec_set_zero(v); for (size_t a = 0; a < n_cols; ++a) { cblas_daxpy(n_rows, 1., A_data + a * n_rows, 1, v_data, 1); } break; default: SB_CHK_ERR(true, abort(), "sb_mat_sum: dir must 'c' or 'r'"); break; } #ifdef SAFE_FINITE SB_CHK_ERR(!sb_vec_is_finite(v), abort(), "sb_mat_sum: elements not finite"); #endif return v; } /// Converts the column vector `*v` into a matrix with the indicated number of /// rows and columns. The number of elements is preserved. NOTE: `*v` is freed /// before the function returns and is set to `NULL`. The returned matrix /// should be freed as usual. /// /// # Parameters /// - `v`: pointer to pointer to the vector /// - `n_rows`: number of rows of the returned matrix /// - `n_cols`: number of columns of the returned matrix /// /// # Returns /// A pointer to a matrix containing the elements of `*v` in column-major order /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `*v` is not `NULL` /// - `SAFE_LAYOUT`: `*v` is a column vector /// - `SAFE_LENGTH`: the number of elements in `*v` is `n_rows * n_cols` /// /// # Examples /// ``` /// #include <assert.h> /// #include "sb_matrix.h" /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.}; /// sb_vec * v = sb_vec_of_arr(a, 9, 'c'); /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// /// // A is equal to B /// sb_mat * B = sb_vec_to_mat(&v, 3, 3); /// assert(sb_mat_is_equal(A, B)); /// /// SB_MAT_FREE_ALL(A, B); /// //SB_VEC_FREE_ALL(v); // <-- double free /// } /// ``` sb_mat * sb_vec_to_mat(sb_vec ** v, size_t n_rows, size_t n_cols) { #ifdef SAFE_MEMORY SB_CHK_ERR(!(*v), abort(), "sb_vec_to_mat: *v cannot be NULL"); #endif #ifdef SAFE_LAYOUT SB_CHK_ERR((*v)->layout != 'c', abort(), "sb_vec_to_mat: *v must be a column vector"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR((*v)->n_elem != n_rows * n_cols, abort(), "sb_vec_to_mat: number of elements must be preserved"); #endif sb_mat * out = malloc(sizeof(sb_mat)); SB_CHK_ERR(!out, return NULL, "sb_vec_to_mat: failed to allocate matrix"); out->n_rows = n_rows; out->n_cols = n_cols; out->n_elem = (*v)->n_elem; out->data = (*v)->data; free(*v); *v = NULL; return out; } /// Converts the matrix `A` into a column vector. The number of elements is /// preserved. NOTE: `*A` is freed before the function returns and is set to /// `NULL`, but the returned vector should be freed as usual. /// /// # Parameters /// - `A`: pointer to pointer to the matrix /// /// # Returns /// A pointer to a vector containing the elements of `*A` in column-major order /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `*A` is not `NULL` /// /// # Examples /// ``` /// #include <assert.h> /// #include "sb_matrix.h" /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// sb_vec * v = sb_vec_of_arr(a, 9, 'c'); /// /// // v is equal to w /// sb_vec * w = sb_mat_to_sb_vec(&A); /// assert(sb_vec_is_equal(v, w)); /// /// SB_VEC_FREE_ALL(v, w); /// //SB_MAT_FREE_ALL(A); // <-- double free /// } /// ``` sb_vec * sb_mat_to_vec(sb_mat ** A) { #ifdef SAFE_MEMORY SB_CHK_ERR(!(*A), abort(), "sb_mat_to_vec: *A cannot be NULL"); #endif sb_vec * out = malloc(sizeof(sb_vec)); SB_CHK_ERR(!out, return NULL, "sb_mat_to_vec: failed to allocate vector"); out->n_elem = (*A)->n_elem; out->data = (*A)->data; out->layout = 'c'; free(*A); *A = NULL; return out; } /// Reshapes the matrix `A` to have the indicated number of rows and columns /// with the elements in column-major order. The number of elements must be /// preserved. /// /// # Parameters /// - `A`: pointer to the matrix /// - `n_rows`: number of rows in the returned matrix /// - `n_cols`: number of columns in the returned matrix /// /// # Returns /// A copy of `A` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `A` is not `NULL` /// - `SAFE_LENGTH`: the number of elements in `A` is `n_rows * n_cols` /// /// # Examples /// ``` /// #include "sb_matrix.h" /// #include "sb_structs.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4.}; /// sb_mat * A = sb_mat_of_arr(a, 4, 2); /// sb_mat * B = sb_mat_of_arr(a, 2, 4); /// /// // A is reshaped to equal B /// sb_mat_reshape(A, 2, 4); /// assert(sb_mat_is_equal(A, B)); /// /// SB_MAT_FREE_ALL(A, B); /// } /// ``` sb_mat * sb_mat_reshape(sb_mat * A, size_t n_rows, size_t n_cols) { #ifdef SAFE_MEMORY SB_CHK_ERR(!A, abort(), "sb_mat_reshape: A cannot be NULL"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(A->n_elem != n_rows * n_cols, abort(), "sb_mat_reshape: number of elements must be preserved"); #endif A->n_rows = n_rows; A->n_cols = n_cols; return A; } /// Transposes the matrix `A` using a memory allocation for scratch space. NOTE: /// Since the matrix multiplication functions allow the matrix to be transposed /// at lower cost, this function is usually unnecesary. /// /// # Parameters /// - `A`: pointer to the matrix /// /// # Returns /// A copy of `A` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `A` is not `NULL` /// /// # Examples /// ``` /// #include "sb_matrix.h" /// #include "sb_structs.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4.}; /// sb_mat * A = sb_mat_of_arr(a, 4, 2); /// /// // A is transposed /// sb_mat_print(A, "A before: ", "%g"); /// sb_mat_trans(A); /// sb_mat_print(A, "A after: ", "%g"); /// /// SB_MAT_FREE_ALL(A); /// } /// ``` sb_mat * sb_mat_trans(sb_mat * A) { #ifdef SAFE_MEMORY SB_CHK_ERR(!A, abort(), "sb_mat_trans: A cannot be NULL"); #endif size_t n_elem = A->n_elem; double * T_data = malloc(n_elem * sizeof(double)); SB_CHK_ERR(!T_data, return A, "sb_mat_trans: failed to allocate memory"); size_t n_rows = A->n_rows; size_t n_cols = A->n_cols; double * A_data = A->data; for (size_t a = 0; a < n_rows; ++a) { cblas_dcopy(n_cols, A_data + a, n_rows, T_data + a * n_cols, 1); } A->n_rows = n_cols; A->n_cols = n_rows; A->data = T_data; free(A_data); return A; } /// Checks the matrices `A` and `B` for equality of elements. Matrices must /// have the same number of rows and columns. /// /// # Parameters /// - `A`: pointer to the first matrix /// - `B`: pointer to the second matrix /// /// # Returns /// `1` if `A` and `B` are equal, and `0` otherwise /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `A` and `B` are not `NULL` /// - `SAFE_LENGTH`: `A` and `B` have the same number of rows and columns /// - `SAFE_FINITE`: elements of `A` and `B` are finite /// /// # Examples /// ``` /// #include <assert.h> /// #include "sb_matrix.h" /// #include "sb_structs.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2., 8.}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// sb_mat * B = sb_mat_of_arr(a + 1, 3, 3); /// /// // A and B are equal after sb_mat_memcpy /// assert(!sb_mat_is_equal(A, B)); /// sb_mat_memcpy(B, A); /// assert(sb_mat_is_equal(A, B)); /// /// SB_MAT_FREE_ALL(A, B); /// } /// ``` int sb_mat_is_equal(const sb_mat * restrict A, const sb_mat * restrict B) { #ifdef SAFE_MEMORY SB_CHK_ERR(!A, abort(), "sb_mat_is_equal: A cannot be NULL"); SB_CHK_ERR(!B, abort(), "sb_mat_is_equal: B cannot be NULL"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(A->n_rows != B->n_rows, abort(), "sb_mat_is_equal: A and B must have same number of rows"); SB_CHK_ERR(A->n_cols != B->n_cols, abort(), "sb_mat_is_equal: A and B must have same number of columns"); #endif double * A_data = A->data; double * B_data = B->data; for (size_t a = 0; a < A->n_elem; ++a) { #ifdef SAFE_FINITE SB_CHK_ERR(!isfinite(A_data[a]), abort(), "sb_mat_is_equal: A is not finite"); SB_CHK_ERR(!isfinite(B_data[a]), abort(), "sb_mat_is_equal: B is not finite"); #endif if (A_data[a] != B_data[a]) { return 0; } } return 1; } /// Checks if all elements of the matrix `A` are zero. /// /// # Parameters /// - `A`: pointer to the matrix /// /// # Returns /// `1` if all elements of `A` are zero, and `0` otherwise /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `A` is not `NULL` /// /// # Examples /// ``` /// #include <assert.h> /// #include "sb_matrix.h" /// #include "sb_structs.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// /// // A is zero after sb_mat_set_zero /// assert(!sb_mat_is_zero(A)); /// sb_mat_set_zero(A); /// assert(sb_mat_is_zero(A)); /// /// SB_MAT_FREE_ALL(A); /// } /// ``` int sb_mat_is_zero(const sb_mat * A) { #ifdef SAFE_MEMORY SB_CHK_ERR(!A, abort(), "sb_mat_is_zero: A cannot be NULL"); #endif double * data = A->data; for (size_t a = 0; a < A->n_elem; ++a) { if (data[a] != 0.) { return 0; } } return 1; } /// Checks if all elements of the matrix `A` are positive. /// /// # Parameters /// - `A`: pointer to the matrix /// /// # Returns /// `1` if all elements of `A` are positive, and `0` otherwise /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `A` is not `NULL` /// - `SAFE_FINITE`: elements of `A` are finite /// /// # Examples /// ``` /// #include <assert.h> /// #include "sb_matrix.h" /// #include "sb_structs.h" /// /// int main(void) { /// double a[] = {1., -4., 2., -8., 5., 7., 1., 4., -2.}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// /// // A is positive after sb_mat_abs /// assert(!sb_mat_is_pos(A)); /// sb_mat_abs(A); /// assert(sb_mat_is_pos(A)); /// /// SB_MAT_FREE_ALL(A); /// } /// ``` int sb_mat_is_pos(const sb_mat * A) { #ifdef SAFE_MEMORY SB_CHK_ERR(!A, abort(), "sb_mat_is_pos: A cannot be NULL"); #endif double * data = A->data; for (size_t a = 0; a < A->n_elem; ++a) { #ifdef SAFE_FINITE SB_CHK_ERR(!isfinite(data[a]), abort(), "sb_mat_is_pos: A is not finite"); #endif if (data[a] <= 0.) { return 0; } } return 1; } /// Checks if all elements of the matrix `A` are negative. /// /// # Parameters /// - `A`: pointer to the matrix /// /// # Returns /// `1` if all elements of `A` are negative, and `0` otherwise /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `A` is not `NULL` /// - `SAFE_FINITE`: elements of `A` are finite /// /// # Examples /// ``` /// #include <assert.h> /// #include "sb_matrix.h" /// #include "sb_structs.h" /// /// int main(void) { /// double a[] = {1., -4., 2., -8., 5., 7., 1., 4., -2.}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// /// // A is negative after /// assert(!sb_mat_is_neg(A)); /// sb_mat_smul(sb_mat_abs(A), -1.); /// assert(sb_mat_is_neg(A)); /// /// SB_MAT_FREE_ALL(A); /// } /// ``` int sb_mat_is_neg(const sb_mat * A) { #ifdef SAFE_MEMORY SB_CHK_ERR(!A, abort(), "sb_mat_is_neg: A cannot be NULL"); #endif double * data = A->data; for (size_t a = 0; a < A->n_elem; ++a) { #ifdef SAFE_FINITE SB_CHK_ERR(!isfinite(data[a]), abort(), "sb_mat_is_neg: A is not finite"); #endif if (data[a] >= 0.) { return 0; } } return 1; } /// Checks if all elements of the matrix `A` are nonnegative. /// /// # Parameters /// - `A`: pointer to the matrix /// /// # Returns /// `1` if all elements of `A` are nonnegative, and `0` otherwise /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `A` is not `NULL` /// - `SAFE_FINITE`: elements of `A` are finite /// /// # Examples /// ``` /// #include <assert.h> /// #include "sb_matrix.h" /// #include "sb_structs.h" /// /// int main(void) { /// double a[] = {0., -4., 2., -8., 5., 7., 1., 4., -2.}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// /// // A is nonnegative after /// assert(!sb_mat_is_nonneg(A)); /// sb_mat_abs(A); /// assert( sb_mat_is_nonneg(A)); /// /// SB_MAT_FREE_ALL(A); /// } /// ``` int sb_mat_is_nonneg(const sb_mat * A) { #ifdef SAFE_MEMORY SB_CHK_ERR(!A, abort(), "sb_mat_is_nonneg: A cannot be NULL"); #endif double * data = A->data; for (size_t a = 0; a < A->n_elem; ++a) { #ifdef SAFE_FINITE SB_CHK_ERR(!isfinite(data[a]), abort(), "sb_mat_is_nonneg: A is not finite"); #endif if (data[a] < 0.) { return 0; } } return 1; } /// Checks if all elements of the matrix `A` are not infinite or `NaN`. /// /// # Parameters /// - `A`: pointer to the matrix /// /// # Returns /// `1` if all elements of `A` are not infinite or `NaN`, and `0` otherwise /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `A` is not `NULL` /// /// # Examples /// ``` /// #include <assert.h> /// #include <math.h> /// #include "sb_matrix.h" /// #include "sb_structs.h" /// /// int main(void) { /// double a[] = {1., INFINITY, 2., 8., 5., 7., 1., 4., 2.}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// /// assert(!sb_mat_is_finite(A)); /// sb_mat_set(A, 1, 0, NAN); /// assert(!sb_mat_is_finite(A)); /// sb_mat_set(A, 1, 0, 4.); /// assert( sb_mat_is_finite(A)); /// /// SB_MAT_FREE_ALL(A); /// } /// ``` int sb_mat_is_finite(const sb_mat * A) { #ifdef SAFE_MEMORY SB_CHK_ERR(!A, abort(), "sb_mat_is_finite: A cannot be NULL"); #endif double * data = A->data; for (size_t a = 0; a < A->n_elem; ++a) { if (!isfinite(data[a])) { return 0; } } return 1; } /// Finds the value of the maximum element of `A`. /// /// # Parameters /// - `A`: pointer to the matrix /// /// # Returns /// Value of the maximum element /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `A` is not `NULL` /// - `SAFE_LENGTH`: number of elements is nonzero /// - `SAFE_FINITE`: elements of `A` are finite /// /// # Examples /// ``` /// #include <assert.h> /// #include "sb_matrix.h" /// #include "sb_structs.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// /// // maximum value of A is 8. /// assert(sb_mat_max(A) == 8.); /// /// SB_MAT_FREE_ALL(A); /// } /// ``` double sb_mat_max(const sb_mat * A) { #ifdef SAFE_MEMORY SB_CHK_ERR(!A, abort(), "sb_mat_max: A cannot be NULL"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(A->n_elem == 0, abort(), "sb_mat_max: n_elem must be nonzero"); #endif double * data = A->data; double max_val = -INFINITY; for (size_t a = 0; a < A->n_elem; ++a) { #ifdef SAFE_FINITE SB_CHK_ERR(!isfinite(data[a]), abort(), "sb_mat_max: A is not finite"); #endif if (data[a] > max_val) { max_val = data[a]; } } return max_val; } /// Finds the value of the minimum element of `A`. /// /// # Parameters /// - `A`: pointer to the matrix /// /// # Returns /// Value of the minimum element /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `A` is not `NULL` /// - `SAFE_LENGTH`: number of elements is nonzero /// - `SAFE_FINITE`: elements of `A` are finite /// /// # Examples /// ``` /// #include <assert.h> /// #include "sb_matrix.h" /// #include "sb_structs.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// /// // value of min is 1 /// assert(sb_mat_min(A) == 1.); /// /// SB_MAT_FREE_ALL(A); /// } /// ``` double sb_mat_min(const sb_mat * A) { #ifdef SAFE_MEMORY SB_CHK_ERR(!A, abort(), "sb_mat_min: A cannot be NULL"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(A->n_elem == 0, abort(), "sb_mat_min: n_elem must be nonzero"); #endif double * data = A->data; double min_val = INFINITY; for (size_t a = 0; a < A->n_elem; ++a) { #ifdef SAFE_FINITE SB_CHK_ERR(!isfinite(data[a]), abort(), "sb_mat_min: A is not finite"); #endif if (data[a] < min_val) { min_val = data[a]; } } return min_val; } /// Finds the maximum absolute value of the elements of `A`. /// /// # Parameters /// - `A`: pointer to the matrix /// /// # Returns /// Maximum absolute value of the elements /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `A` is not `NULL` /// - `SAFE_LENGTH`: number of elements is nonzero /// - `SAFE_FINITE`: elements of `A` are finite /// /// # Examples /// ``` /// #include <assert.h> /// #include "sb_matrix.h" /// #include "sb_structs.h" /// /// int main(void) { /// double a[] = {1., -4., 2., -8., 5., -7., 1., -4., 2.}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// /// // maximum absolute value of A is 8. /// assert(sb_mat_abs_max(A) == 8.); /// /// SB_MAT_FREE_ALL(A); /// } /// ``` double sb_mat_abs_max(const sb_mat * A) { #ifdef SAFE_MEMORY SB_CHK_ERR(!A, abort(), "sb_mat_abs_max: A cannot be NULL"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(A->n_elem == 0, abort(), "sb_mat_abs_max: n_elem must be nonzero"); #endif double * data = A->data; size_t index = cblas_idamax(A->n_elem, data, 1); #ifdef SAFE_FINITE SB_CHK_ERR(!isfinite(data[index]), abort(), "sb_mat_abs_max: A is not finite"); #endif return fabs(data[index]); } /// Finds the index of the maximum element of `A`. /// /// # Parameters /// - `A`: pointer to the matrix /// /// # Returns /// Index of the maximum element /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `A` is not `NULL` /// - `SAFE_LENGTH`: number of elements is nonzero /// - `SAFE_FINITE`: elements of `A` are finite /// /// # Examples /// ``` /// #include <assert.h> /// #include "sb_matrix.h" /// #include "sb_structs.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// /// // index of max is 3 /// assert(sb_mat_max_index(A) == 3); /// /// SB_MAT_FREE_ALL(A); /// } /// ``` size_t sb_mat_max_index(const sb_mat * A) { #ifdef SAFE_MEMORY SB_CHK_ERR(!A, abort(), "sb_mat_max_index: A cannot be NULL"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(A->n_elem == 0, abort(), "sb_mat_max_index: n_elem must be nonzero"); #endif double * data = A->data; double max_val = -INFINITY; size_t max_ind = 0; for (size_t a = 0; a < A->n_elem; ++a) { #ifdef SAFE_FINITE SB_CHK_ERR(!isfinite(data[a]), abort(), "sb_mat_max_index: A is not finite"); #endif if (data[a] > max_val) { max_val = data[a]; max_ind = a; } } return max_ind; } /// Finds the index of the minimum element of `A`. /// /// # Parameters /// - `A`: pointer to the matrix /// /// # Returns /// Index of the minimum element /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `A` is not `NULL` /// - `SAFE_LENGTH`: number of elements is nonzero /// - `SAFE_FINITE`: elements of `A` are finite /// /// # Examples /// ``` /// #include <assert.h> /// #include "sb_matrix.h" /// #include "sb_structs.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7., 1., 4., 2.}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// /// // index of min is 0 /// assert(sb_mat_min_index(A) == 0); /// /// SB_MAT_FREE_ALL(A); /// } /// ``` size_t sb_mat_min_index(const sb_mat * A) { #ifdef SAFE_MEMORY SB_CHK_ERR(!A, abort(), "sb_mat_min_index: A cannot be NULL"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(A->n_elem == 0, abort(), "sb_mat_min_index: n_elem must be nonzero"); #endif double * data = A->data; double min_val = INFINITY; size_t min_ind = 0; for (size_t a = 0; a < A->n_elem; ++a) { #ifdef SAFE_FINITE SB_CHK_ERR(!isfinite(data[a]), abort(), "sb_mat_min_index: A is not finite"); #endif if (data[a] < min_val) { min_val = data[a]; min_ind = a; } } return min_ind; } /// Finds the index of the maximum absolute value of the elements of `A`. /// /// # Parameters /// - `A`: pointer to the matrix /// /// # Returns /// Index of the maximum absolute value of the elements /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `A` is not `NULL` /// - `SAFE_LENGTH`: number of elements is nonzero /// /// # Examples /// ``` /// #include <assert.h> /// #include "sb_matrix.h" /// #include "sb_structs.h" /// /// int main(void) { /// double a[] = {1., -4., 2., -8., 5., -7., 1., -4., 2.}; /// sb_mat * A = sb_mat_of_arr(a, 3, 3); /// /// // index of the maximum absolute value of A is 3 /// assert(sb_mat_abs_max_index(A) == 3); /// /// SB_MAT_FREE_ALL(A); /// } /// ``` size_t sb_mat_abs_max_index(const sb_mat * A) { #ifdef SAFE_MEMORY SB_CHK_ERR(!A, abort(), "sb_mat_abs_max_index: A cannot be NULL"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(A->n_elem == 0, abort(), "sb_mat_abs_max_index: n_elem must be nonzero"); #endif return cblas_idamax(A->n_elem, A->data, 1); } extern inline double sb_mat_get(const sb_mat * A, size_t i, size_t j); extern inline void sb_mat_set(sb_mat * A, size_t i, size_t j, double x); extern inline double * sb_mat_ptr(sb_mat * A, size_t i, size_t j);
[STATEMENT] lemma subst_compose1: assumes "good X" and "good Y1" and "good Y2" shows "((X #[Y1 / y]_ys) #[Y2 / y]_ys) = (X #[(Y1 #[Y2 / y]_ys) / y]_ys)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. X #[Y1 / y]_ys #[Y2 / y]_ys = X #[Y1 #[Y2 / y]_ys / y]_ys [PROOF STEP] proof- [PROOF STATE] proof (state) goal (1 subgoal): 1. X #[Y1 / y]_ys #[Y2 / y]_ys = X #[Y1 #[Y2 / y]_ys / y]_ys [PROOF STEP] have "goodEnv (idEnv [y \<leftarrow> Y1]_ys) \<and> goodEnv (idEnv [y \<leftarrow> Y2]_ys)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. goodEnv (idEnv [y \<leftarrow> Y1]_ys) \<and> goodEnv (idEnv [y \<leftarrow> Y2]_ys) [PROOF STEP] using assms [PROOF STATE] proof (prove) using this: good X good Y1 good Y2 goal (1 subgoal): 1. goodEnv (idEnv [y \<leftarrow> Y1]_ys) \<and> goodEnv (idEnv [y \<leftarrow> Y2]_ys) [PROOF STEP] by simp [PROOF STATE] proof (state) this: goodEnv (idEnv [y \<leftarrow> Y1]_ys) \<and> goodEnv (idEnv [y \<leftarrow> Y2]_ys) goal (1 subgoal): 1. X #[Y1 / y]_ys #[Y2 / y]_ys = X #[Y1 #[Y2 / y]_ys / y]_ys [PROOF STEP] thus ?thesis [PROOF STATE] proof (prove) using this: goodEnv (idEnv [y \<leftarrow> Y1]_ys) \<and> goodEnv (idEnv [y \<leftarrow> Y2]_ys) goal (1 subgoal): 1. X #[Y1 / y]_ys #[Y2 / y]_ys = X #[Y1 #[Y2 / y]_ys / y]_ys [PROOF STEP] using \<open>good X\<close> [PROOF STATE] proof (prove) using this: goodEnv (idEnv [y \<leftarrow> Y1]_ys) \<and> goodEnv (idEnv [y \<leftarrow> Y2]_ys) good X goal (1 subgoal): 1. X #[Y1 / y]_ys #[Y2 / y]_ys = X #[Y1 #[Y2 / y]_ys / y]_ys [PROOF STEP] unfolding subst_def substEnv_def [PROOF STATE] proof (prove) using this: goodEnv (idEnv [y \<leftarrow> Y1]_ys) \<and> goodEnv (idEnv [y \<leftarrow> Y2]_ys) good X goal (1 subgoal): 1. X #[idEnv [y \<leftarrow> Y1]_ys] #[idEnv [y \<leftarrow> Y2]_ys] = X #[idEnv [y \<leftarrow> Y1 #[idEnv [y \<leftarrow> Y2]_ys]]_ys] [PROOF STEP] by(simp add: psubst_compose psubstEnv_updEnv) [PROOF STATE] proof (state) this: X #[Y1 / y]_ys #[Y2 / y]_ys = X #[Y1 #[Y2 / y]_ys / y]_ys goal: No subgoals! [PROOF STEP] qed
Formal statement is: lemma limitin_sequentially_offset: "limitin X f l sequentially \<Longrightarrow> limitin X (\<lambda>i. f (i + k)) l sequentially" Informal statement is: If $f$ converges to $l$ in $X$ along a subsequence of the natural numbers, then $f(n + k)$ converges to $l$ in $X$ along the same subsequence.
[STATEMENT] lemma (in padic_integers) p_residue_ring_car_memI: assumes "(m::int) \<ge>0" assumes "m < p^k" shows "m \<in> carrier (Zp_res_ring k)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. m \<in> carrier (residue_ring (p ^ k)) [PROOF STEP] using residue_ring_def[of "p^k"] assms(1) assms(2) [PROOF STATE] proof (prove) using this: residue_ring (p ^ k) = \<lparr>carrier = {0..p ^ k - 1}, monoid.mult = \<lambda>x y. x * y mod p ^ k, one = 1, zero = 0, add = \<lambda>x y. (x + y) mod p ^ k\<rparr> 0 \<le> m m < p ^ k goal (1 subgoal): 1. m \<in> carrier (residue_ring (p ^ k)) [PROOF STEP] by auto
\name{normalize_comb_mat} \alias{normalize_comb_mat} \title{ Normalize a list of combination matrice } \description{ Normalize a list of combination matrice } \usage{ normalize_comb_mat(...) } \arguments{ \item{...}{If it is a single argument, the value should be a list of combination matrices.} } \details{ It normalizes a list of combination matrice to make them have same number and order of sets and combination sets. The sets (by \code{\link{set_name}}) from all combination matrice should be the same. } \examples{ # There is no example NULL }
\section{Sequence Diagrams} \label{sec:sequence-diagrams}
Aman Ullah is with Ro Nay San Lwin and 93 others. The UN Security Council has issued a presidential statement on Myanmar complimenting and criticising the country over its stance on the Rohingya crisis and it also gave the government a month to “get its act together”. The 1,300- word statement was read out by the sitting President of UNSC Sebastiano Cardi, the Ambassador of Italy, at a formal UNSC session on Monday ( November 6, 2017) . A presidential statement is a statement made by the President of the Security Council on behalf of the Council, adopted at a formal meeting of the Council and issued as an official document of the Council. A Presidential Statement is often created when the United Nations Security Council cannot reach consensus or are prevented from passing a resolution by a permanent member’s veto, or threat thereof. Such statements are similar in content, format, and tone to resolutions, but are not legally binding. The adoption of a Presidential Statement requires consensus, although Security Council members may abstain. The Statement is signed by the sitting Security Council President. It was the first presidential statement in 10 years on Myanmar. The Security Council has adopted such statements against Myanmar only three times, with the last one coming a decade ago. Diplomats hailed the move as a unified international stand against a humanitarian crisis that has been called “ethnic cleansing” by the U.N., U.S., France and the U.K. It strongly condemned attacks against the Myanmar security forces carried out by the Arakan Rohingya Salvation Army (ARSA) on August 25, and then expressed “grave concern” over the government’s response, the alleged burning of villages and threats to villagers to flee, among others. It called for reform in Myanmar’s security and justice sectors and urged the government to work with Bangladesh and the UN to allow the voluntary return of refugees to their homes, on the basis of an October 24 memorandum of understanding between the two country. The panel welcomed a “union enterprise mechanism” for humanitarian assistance, resettlement and development in Rakhine. It recommended the government ensure the mechanism supported such return and allow UN agencies full access, urging governments and all humanitarian partners to pay special attention to the needs of women, particular survivors of sexual violence. The council said the government’s primary responsibility is the protection of Myanmar’s population, citizens or not. The statement reiterated concerns and demands previously laid out: an end to excessive military force in Rakhine province, a lack of humanitarian access for the U.N., a right of return for refugees, and steps to address the root causes of the conflict. The statement included most of the demands contained in a draft resolution presented last month by Britain and France, but that measure ran into strong opposition from China, a supporter of Myanmar’s former ruling junta. It is said that, China had indicated it was willing to resort to its veto power to block a resolution, but Beijing finally agreed to a statement during negotiations. The action is one step below a Security Council resolution in diplomatic significance, but a step above the Council’s previous action, a “press statement,” in September. The statement requires the U.N. Secretary General António Guterres to report back to the Council within 30 days on Myanmar’s progress in addressing the Council’s demands. The statement isn’t as binding as a resolution would be, and carries no punitive measures, such as sanctions, if corrective steps aren’t taken. The Security Council has held a series of meetings on Myanmar since September, including a briefing attended by high-level officials on the sidelines of the U.N. General Assembly gathering. But efforts to respond forcefully have stalled despite widespread reports of deaths, rapes and torture of Rohingya Muslim minorities, including women and children, at the hands of the country’s military. Violence erupted in August after a Rohingya militant group attacked Myanmar security forces. Since late August, more than 600,000 Rohingya have been driven from their homes by an army campaign that the United Nations has described as ethnic cleansing. During negotiations with China, language on citizenship rights was watered down in the statement as was a demand that Myanmar allow a UN human rights mission into the country, diplomats said. The statement calls on Myanmar to cooperate with the United Nations and encourages UN Secretary-General Antonio Guterres to appoint a special advisor on Myanmar. The council statement was agreed as Guterres prepares to travel to Manila this week to join leaders of the Southeast Asian (ASEAN) bloc for a summit. The council also welcomed the Myanmar government’s public support for recommendations by the Advisory Commission on Rakhine State chaired by former UN Secretary-General Kofi Annan and called for their full implementation. It urged UN Secretary-General Antonio Guterres to consider appointing a special advisor on Myanmar. Since the August attacks, over 604,000 Rohingya have fled to Bangladesh. Some fled by land, others in boats over an inlet of the Bay of Bengal. In the last two weeks, 4,000 refugees entered Bangladesh while four people drowned in a shipwreck while fleeing, officials said. U.K Foreign Secretary Boris Johnson said: I am pleased that today (6 November) the United Nations Security Council (UNSC) has spoken with one voice on the appalling situation in Rakhine State, Burma. The UK has repeatedly called on the Burmese security forces to protect all civilians and act now to stop the violence and allow humanitarian aid to urgently reach all those who need it. The UNSC has today joined us in that call, with this historic Presidential Statement on Burma. I am encouraged to see State Counsellor Aung San Suu Kyi making important steps forward, including establishing a domestic body to deliver humanitarian and development assistance in Rakhine, and making efforts to promote interfaith and intercommunal harmony, including a recent visit to northern Rakhine. The UK will be watching closely to ensure that the Burmese security forces do not attempt to frustrate these efforts. The U.K. and France initially circulated a proposed Security Council resolution on Myanmar in late October, but China and Russia refused to engage and negotiate, diplomats said. China finally agreed to a similar text with minor changes as a presidential statement—which carries less weight than a resolution—and Russia followed suit. Mr. Guterres has been outspoken about the Myanmar crisis and urged the Security Council to prevent continued bloodshed and curb the refugee flow. Mr. Guterres will be among the world leaders attending the Association of Southeast Asian Nations (Asean) summit later this week in Manila. The Rohingya refugee crisis is expected to be a top issue of discussion at the summit, to be attended by US President Donald Trump, who will dispatch US Secretary of State Rex Tillerson to Myanmar later this month. Daw Aung San Suu Kyi will also attend that summit.
Formal statement is: lemma analytic_iff_power_series: "f analytic_on ball z r \<longleftrightarrow> (\<forall>w \<in> ball z r. (\<lambda>n. (deriv ^^ n) f z / (fact n) * (w - z)^n) sums f w)" Informal statement is: A function $f$ is analytic on a ball $B(z,r)$ if and only if its Taylor series converges to $f$ on $B(z,r)$.
[GOAL] C : Type u inst✝² : Category.{v, u} C X Y : C inst✝¹ : HasTerminal C inst✝ : HasBinaryProducts C X✝ X'✝ Y✝ Y'✝ : C f : X✝ ⟶ Y✝ g : X'✝ ⟶ Y'✝ ⊢ (f ⊗ g) ≫ ((fun X Y => prod.braiding X Y) Y✝ Y'✝).hom = ((fun X Y => prod.braiding X Y) X✝ X'✝).hom ≫ (g ⊗ f) [PROOFSTEP] dsimp [tensorHom] [GOAL] C : Type u inst✝² : Category.{v, u} C X Y : C inst✝¹ : HasTerminal C inst✝ : HasBinaryProducts C X✝ X'✝ Y✝ Y'✝ : C f : X✝ ⟶ Y✝ g : X'✝ ⟶ Y'✝ ⊢ prod.map f g ≫ prod.lift prod.snd prod.fst = prod.lift prod.snd prod.fst ≫ prod.map g f [PROOFSTEP] simp [GOAL] C : Type u inst✝² : Category.{v, u} C X✝ Y✝ : C inst✝¹ : HasTerminal C inst✝ : HasBinaryProducts C X Y Z : C ⊢ (α_ X Y Z).hom ≫ ((fun X Y => prod.braiding X Y) X (Y ⊗ Z)).hom ≫ (α_ Y Z X).hom = (((fun X Y => prod.braiding X Y) X Y).hom ⊗ 𝟙 Z) ≫ (α_ Y X Z).hom ≫ (𝟙 Y ⊗ ((fun X Y => prod.braiding X Y) X Z).hom) [PROOFSTEP] dsimp [monoidalOfHasFiniteProducts.associator_hom] [GOAL] C : Type u inst✝² : Category.{v, u} C X✝ Y✝ : C inst✝¹ : HasTerminal C inst✝ : HasBinaryProducts C X Y Z : C ⊢ prod.lift (prod.fst ≫ prod.fst) (prod.lift (prod.fst ≫ prod.snd) prod.snd) ≫ prod.lift prod.snd prod.fst ≫ prod.lift (prod.fst ≫ prod.fst) (prod.lift (prod.fst ≫ prod.snd) prod.snd) = prod.map (prod.lift prod.snd prod.fst) (𝟙 Z) ≫ prod.lift (prod.fst ≫ prod.fst) (prod.lift (prod.fst ≫ prod.snd) prod.snd) ≫ prod.map (𝟙 Y) (prod.lift prod.snd prod.fst) [PROOFSTEP] simp [GOAL] C : Type u inst✝² : Category.{v, u} C X✝ Y✝ : C inst✝¹ : HasTerminal C inst✝ : HasBinaryProducts C X Y Z : C ⊢ (α_ X Y Z).inv ≫ ((fun X Y => prod.braiding X Y) (X ⊗ Y) Z).hom ≫ (α_ Z X Y).inv = (𝟙 X ⊗ ((fun X Y => prod.braiding X Y) Y Z).hom) ≫ (α_ X Z Y).inv ≫ (((fun X Y => prod.braiding X Y) X Z).hom ⊗ 𝟙 Y) [PROOFSTEP] dsimp [monoidalOfHasFiniteProducts.associator_inv] [GOAL] C : Type u inst✝² : Category.{v, u} C X✝ Y✝ : C inst✝¹ : HasTerminal C inst✝ : HasBinaryProducts C X Y Z : C ⊢ prod.lift (prod.lift prod.fst (prod.snd ≫ prod.fst)) (prod.snd ≫ prod.snd) ≫ prod.lift prod.snd prod.fst ≫ prod.lift (prod.lift prod.fst (prod.snd ≫ prod.fst)) (prod.snd ≫ prod.snd) = prod.map (𝟙 X) (prod.lift prod.snd prod.fst) ≫ prod.lift (prod.lift prod.fst (prod.snd ≫ prod.fst)) (prod.snd ≫ prod.snd) ≫ prod.map (prod.lift prod.snd prod.fst) (𝟙 Y) [PROOFSTEP] simp [GOAL] C : Type u inst✝² : Category.{v, u} C X✝ Y✝ : C inst✝¹ : HasTerminal C inst✝ : HasBinaryProducts C X Y : C ⊢ (β_ X Y).hom ≫ (β_ Y X).hom = 𝟙 (X ⊗ Y) [PROOFSTEP] dsimp [GOAL] C : Type u inst✝² : Category.{v, u} C X✝ Y✝ : C inst✝¹ : HasTerminal C inst✝ : HasBinaryProducts C X Y : C ⊢ prod.lift prod.snd prod.fst ≫ prod.lift prod.snd prod.fst = 𝟙 (X ⨯ Y) [PROOFSTEP] simp [GOAL] C : Type u inst✝² : Category.{v, u} C X Y : C inst✝¹ : HasInitial C inst✝ : HasBinaryCoproducts C X✝ X'✝ Y✝ Y'✝ : C f : X✝ ⟶ Y✝ g : X'✝ ⟶ Y'✝ ⊢ (f ⊗ g) ≫ (coprod.braiding Y✝ Y'✝).hom = (coprod.braiding X✝ X'✝).hom ≫ (g ⊗ f) [PROOFSTEP] dsimp [tensorHom] [GOAL] C : Type u inst✝² : Category.{v, u} C X Y : C inst✝¹ : HasInitial C inst✝ : HasBinaryCoproducts C X✝ X'✝ Y✝ Y'✝ : C f : X✝ ⟶ Y✝ g : X'✝ ⟶ Y'✝ ⊢ coprod.map f g ≫ coprod.desc coprod.inr coprod.inl = coprod.desc coprod.inr coprod.inl ≫ coprod.map g f [PROOFSTEP] simp [GOAL] C : Type u inst✝² : Category.{v, u} C X✝ Y✝ : C inst✝¹ : HasInitial C inst✝ : HasBinaryCoproducts C X Y Z : C ⊢ (α_ X Y Z).hom ≫ (coprod.braiding X (Y ⊗ Z)).hom ≫ (α_ Y Z X).hom = ((coprod.braiding X Y).hom ⊗ 𝟙 Z) ≫ (α_ Y X Z).hom ≫ (𝟙 Y ⊗ (coprod.braiding X Z).hom) [PROOFSTEP] dsimp [monoidalOfHasFiniteCoproducts.associator_hom] [GOAL] C : Type u inst✝² : Category.{v, u} C X✝ Y✝ : C inst✝¹ : HasInitial C inst✝ : HasBinaryCoproducts C X Y Z : C ⊢ coprod.desc (coprod.desc coprod.inl (coprod.inl ≫ coprod.inr)) (coprod.inr ≫ coprod.inr) ≫ coprod.desc coprod.inr coprod.inl ≫ coprod.desc (coprod.desc coprod.inl (coprod.inl ≫ coprod.inr)) (coprod.inr ≫ coprod.inr) = coprod.map (coprod.desc coprod.inr coprod.inl) (𝟙 Z) ≫ coprod.desc (coprod.desc coprod.inl (coprod.inl ≫ coprod.inr)) (coprod.inr ≫ coprod.inr) ≫ coprod.map (𝟙 Y) (coprod.desc coprod.inr coprod.inl) [PROOFSTEP] simp [GOAL] C : Type u inst✝² : Category.{v, u} C X✝ Y✝ : C inst✝¹ : HasInitial C inst✝ : HasBinaryCoproducts C X Y Z : C ⊢ (α_ X Y Z).inv ≫ (coprod.braiding (X ⊗ Y) Z).hom ≫ (α_ Z X Y).inv = (𝟙 X ⊗ (coprod.braiding Y Z).hom) ≫ (α_ X Z Y).inv ≫ ((coprod.braiding X Z).hom ⊗ 𝟙 Y) [PROOFSTEP] dsimp [monoidalOfHasFiniteCoproducts.associator_inv] [GOAL] C : Type u inst✝² : Category.{v, u} C X✝ Y✝ : C inst✝¹ : HasInitial C inst✝ : HasBinaryCoproducts C X Y Z : C ⊢ coprod.desc (coprod.inl ≫ coprod.inl) (coprod.desc (coprod.inr ≫ coprod.inl) coprod.inr) ≫ coprod.desc coprod.inr coprod.inl ≫ coprod.desc (coprod.inl ≫ coprod.inl) (coprod.desc (coprod.inr ≫ coprod.inl) coprod.inr) = coprod.map (𝟙 X) (coprod.desc coprod.inr coprod.inl) ≫ coprod.desc (coprod.inl ≫ coprod.inl) (coprod.desc (coprod.inr ≫ coprod.inl) coprod.inr) ≫ coprod.map (coprod.desc coprod.inr coprod.inl) (𝟙 Y) [PROOFSTEP] simp [GOAL] C : Type u inst✝² : Category.{v, u} C X✝ Y✝ : C inst✝¹ : HasInitial C inst✝ : HasBinaryCoproducts C X Y : C ⊢ (β_ X Y).hom ≫ (β_ Y X).hom = 𝟙 (X ⊗ Y) [PROOFSTEP] dsimp [GOAL] C : Type u inst✝² : Category.{v, u} C X✝ Y✝ : C inst✝¹ : HasInitial C inst✝ : HasBinaryCoproducts C X Y : C ⊢ coprod.desc coprod.inr coprod.inl ≫ coprod.desc coprod.inr coprod.inl = 𝟙 (X ⨿ Y) [PROOFSTEP] simp
In this study, the reinforcement of wooden beams with fiber-reinforced plastics (FRP) for restorative and constructive purposes was investigated. Two application-oriented processes were developed and evaluated for the production of static as well as dynamic highly stressed fiber reinforced wood composites (FRWC). For that purpose, spruce wood (Picea abies Karst.) was reinforced with carbon fiber and basalt fiber rovings and the static short-run behavior was tested by a four-point bending test. The results show a significant increase in bending stiffness (66%) and bending strength (54%) even for a small degree of reinforcement (3% and 6% by cross section). A parametric simulation model of the four-point bending test was established to predict the bending stiffness as well as to simulate both material and geometry parameters. The simulated and experimental results show good correlations. Bergner, K. ; Tosch, M. ; Zauer, M. ; Spickenheuer, A. ; Wagenführ, A. ; Heinrich, G.
A function $f$ converges to $l$ at $a$ if and only if for every $\epsilon > 0$, there exists a $\delta > 0$ such that for all $x$, if $0 < |x - a| < \delta$, then $|f(x) - l| < \epsilon$.
[STATEMENT] lemma (in trivial) dense: "P dense" [PROOF STATE] proof (prove) goal (1 subgoal): 1. P dense [PROOF STEP] by auto
import tactic namespace vilnius /- ### implication -/ example (P Q : Prop) : P → Q → P := begin sorry end /- ### not -/ example (P Q : Prop) : (P → ¬ Q) → (Q → ¬ P) := begin sorry end /- ### and -/ example (P Q : Prop) : P ∧ Q → Q := begin sorry end example (P Q : Prop) : P → Q → P ∧ Q := begin sorry, end example (P Q : Prop) : P ∧ Q → Q ∧ P := begin sorry end example (P : Prop) : P ∧ ¬ P → false := begin sorry, end /- ## Or -/ example (P Q : Prop) : ¬ P ∨ Q → P → Q := begin sorry, end example (P Q R : Prop) : P ∨ (Q ∧ R) → ¬ P → ¬ Q → false := begin sorry, end end vilnius
theory T137 imports Main begin lemma "( (\<forall> x::nat. \<forall> y::nat. meet(x, y) = meet(y, x)) & (\<forall> x::nat. \<forall> y::nat. join(x, y) = join(y, x)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, meet(y, z)) = meet(meet(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(x, join(y, z)) = join(join(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. meet(x, join(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. join(x, meet(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, join(y, z)) = join(mult(x, y), mult(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(join(x, y), z) = join(mult(x, z), mult(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, over(join(mult(x, y), z), y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(y, undr(x, join(mult(x, y), z))) = y) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(over(x, y), y), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(y, undr(y, x)), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(x, join(y, z)) = join(undr(x, y), undr(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(meet(x, y), z) = join(undr(x, z), undr(y, z))) & (\<forall> x::nat. \<forall> y::nat. invo(join(x, y)) = meet(invo(x), invo(y))) & (\<forall> x::nat. \<forall> y::nat. invo(meet(x, y)) = join(invo(x), invo(y))) & (\<forall> x::nat. invo(invo(x)) = x) ) \<longrightarrow> (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(x, meet(y, z)) = join(over(x, y), over(x, z))) " nitpick[card nat=4,timeout=86400] oops end
theory Div imports Main begin fun div2 :: "nat \<Rightarrow> nat" where "div2 0 = 0" | "div2 (Suc 0) = 0" | "div2 (Suc(Suc n)) = Suc(div2 n)" lemma "div2(n) = n div 2" apply(induction n rule: div2.induct) end
module Void %default total {- data Void : Type where -} twoPlusTwoNotFive : 2 + 2 = 5 -> Void twoPlusTwoNotFive Refl impossible valueNotSucc : (x : Nat) -> x = S x -> Void valueNotSucc _ Refl impossible {- data Dec : (prop : Type) -> Type where Yes : (prf : prop) -> Dec prop No : (contra : prop -> Void) -> Dec prop -} -- more precise implementation of checkEqNat zeroNotSucc : Z = S k -> Void zeroNotSucc Refl impossible succNotZero : S k = Z -> Void succNotZero Refl impossible noRec : (k = j -> Void) -> S k = S j -> Void noRec contra Refl = contra Refl checkEqNat : (num1 : Nat) -> (num2 : Nat) -> Dec (num1 = num2) checkEqNat Z Z = Yes Refl checkEqNat Z (S k) = No zeroNotSucc checkEqNat (S k) Z = No succNotZero checkEqNat (S k) (S j) = case checkEqNat k j of Yes prf => Yes (cong S prf) No contra => No (noRec contra)
lemma in_components_connected: "c \<in> components s \<Longrightarrow> connected c"
Formal statement is: lemma contour_integrable_inversediff: assumes g: "valid_path g" and notin: "z \<notin> path_image g" shows "(\<lambda>w. 1 / (w-z)) contour_integrable_on g" Informal statement is: If $g$ is a valid path and $z$ is not in the image of $g$, then the function $1/(w-z)$ is contour-integrable along $g$.
// // posix_main.cpp // ~~~~~~~~~~~~~~ // // Copyright (c) 2003-2011 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <iostream> #include <string> #include <boost/asio.hpp> #include <boost/thread.hpp> #include <boost/bind.hpp> #include <boost/lexical_cast.hpp> #include "server.hpp" #if !defined(_WIN32) #include <pthread.h> #include <signal.h> int main(int argc, char* argv[]) { try { // Check command line arguments. if (argc != 5) { std::cerr << "Usage: http_server <address> <port> <threads> <doc_root>\n"; std::cerr << " For IPv4, try:\n"; std::cerr << " receiver 0.0.0.0 80 1 .\n"; std::cerr << " For IPv6, try:\n"; std::cerr << " receiver 0::0 80 1 .\n"; return 1; } // Block all signals for background thread. sigset_t new_mask; sigfillset(&new_mask); sigset_t old_mask; pthread_sigmask(SIG_BLOCK, &new_mask, &old_mask); // Run server in background thread. std::size_t num_threads = boost::lexical_cast<std::size_t>(argv[3]); http::server3::server s(argv[1], argv[2], argv[4], num_threads); boost::thread t(boost::bind(&http::server3::server::run, &s)); // Restore previous signals. pthread_sigmask(SIG_SETMASK, &old_mask, 0); // Wait for signal indicating time to shut down. sigset_t wait_mask; sigemptyset(&wait_mask); sigaddset(&wait_mask, SIGINT); sigaddset(&wait_mask, SIGQUIT); sigaddset(&wait_mask, SIGTERM); pthread_sigmask(SIG_BLOCK, &wait_mask, 0); int sig = 0; sigwait(&wait_mask, &sig); // Stop the server. s.stop(); t.join(); } catch (std::exception& e) { std::cerr << "exception: " << e.what() << "\n"; } return 0; } #endif // !defined(_WIN32)
/- Copyright (c) 2022 Chris Birkbeck. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Birkbeck, David Loeffler -/ import algebra.module.submodule.basic import analysis.complex.upper_half_plane.basic import order.filter.zero_and_bounded_at_filter /-! # Bounded at infinity For complex valued functions on the upper half plane, this file defines the filter `at_im_infty` required for defining when functions are bounded at infinity and zero at infinity. Both of which are relevant for defining modular forms. -/ open complex filter open_locale topology upper_half_plane noncomputable theory namespace upper_half_plane /-- Filter for approaching `i∞`. -/ def at_im_infty := filter.at_top.comap upper_half_plane.im lemma at_im_infty_basis : (at_im_infty).has_basis (λ _, true) (λ (i : ℝ), im ⁻¹' set.Ici i) := filter.has_basis.comap upper_half_plane.im filter.at_top_basis lemma at_im_infty_mem (S : set ℍ) : S ∈ at_im_infty ↔ (∃ A : ℝ, ∀ z : ℍ, A ≤ im z → z ∈ S) := begin simp only [at_im_infty, filter.mem_comap', filter.mem_at_top_sets, ge_iff_le, set.mem_set_of_eq, upper_half_plane.coe_im], refine ⟨λ ⟨a, h⟩, ⟨a, (λ z hz, h (im z) hz rfl)⟩, _⟩, rintro ⟨A, h⟩, refine ⟨A, λ b hb x hx, h x _⟩, rwa hx, end /-- A function ` f : ℍ → α` is bounded at infinity if it is bounded along `at_im_infty`. -/ def is_bounded_at_im_infty {α : Type*} [has_norm α] (f : ℍ → α) : Prop := bounded_at_filter at_im_infty f /-- A function ` f : ℍ → α` is zero at infinity it is zero along `at_im_infty`. -/ def is_zero_at_im_infty {α : Type*} [has_zero α] [topological_space α] (f : ℍ → α) : Prop := zero_at_filter at_im_infty f lemma zero_form_is_bounded_at_im_infty {α : Type*} [normed_field α] : is_bounded_at_im_infty (0 : ℍ → α) := const_bounded_at_filter at_im_infty (0:α) /-- Module of functions that are zero at infinity. -/ def zero_at_im_infty_submodule (α : Type*) [normed_field α] : submodule α (ℍ → α) := zero_at_filter_submodule at_im_infty /-- ubalgebra of functions that are bounded at infinity. -/ def bounded_at_im_infty_subalgebra (α : Type*) [normed_field α] : subalgebra α (ℍ → α) := bounded_filter_subalgebra at_im_infty lemma is_bounded_at_im_infty.mul {f g : ℍ → ℂ} (hf : is_bounded_at_im_infty f) (hg : is_bounded_at_im_infty g) : is_bounded_at_im_infty (f * g) := by simpa only [pi.one_apply, mul_one, norm_eq_abs] using hf.mul hg lemma bounded_mem (f : ℍ → ℂ) : is_bounded_at_im_infty f ↔ ∃ (M A : ℝ), ∀ z : ℍ, A ≤ im z → abs (f z) ≤ M := by simp [is_bounded_at_im_infty, bounded_at_filter, asymptotics.is_O_iff, filter.eventually, at_im_infty_mem] lemma zero_at_im_infty (f : ℍ → ℂ) : is_zero_at_im_infty f ↔ ∀ ε : ℝ, 0 < ε → ∃ A : ℝ, ∀ z : ℍ, A ≤ im z → abs (f z) ≤ ε := begin rw [is_zero_at_im_infty, zero_at_filter, tendsto_iff_forall_eventually_mem], split, { simp_rw [filter.eventually, at_im_infty_mem], intros h ε hε, simpa using (h (metric.closed_ball (0 : ℂ) ε) (metric.closed_ball_mem_nhds (0 : ℂ) hε))}, { simp_rw metric.mem_nhds_iff, intros h s hs, simp_rw [filter.eventually, at_im_infty_mem], obtain ⟨ε, h1, h2⟩ := hs, have h11 : 0 < (ε/2), by {linarith,}, obtain ⟨A, hA⟩ := (h (ε/2) h11), use A, intros z hz, have hzs : f z ∈ s, { apply h2, simp only [mem_ball_zero_iff, norm_eq_abs], apply lt_of_le_of_lt (hA z hz), linarith }, apply hzs,} end end upper_half_plane
State Before: α : Type ua β : Type ub γ : Type uc δ : Type ud ι : Sort ?u.77892 inst✝ : UniformSpace α x : α g : Set α → Filter β hg : Monotone g ⊢ Filter.lift (𝓝 x) g = Filter.lift (𝓤 α) fun s => g {y | (y, x) ∈ s} State After: α : Type ua β : Type ub γ : Type uc δ : Type ud ι : Sort ?u.77892 inst✝ : UniformSpace α x : α g : Set α → Filter β hg : Monotone g ⊢ Filter.lift (𝓤 α) (g ∘ preimage fun y => (y, x)) = Filter.lift (𝓤 α) fun s => g {y | (y, x) ∈ s} Tactic: rw [nhds_eq_comap_uniformity', comap_lift_eq2 hg] State Before: α : Type ua β : Type ub γ : Type uc δ : Type ud ι : Sort ?u.77892 inst✝ : UniformSpace α x : α g : Set α → Filter β hg : Monotone g ⊢ Filter.lift (𝓤 α) (g ∘ preimage fun y => (y, x)) = Filter.lift (𝓤 α) fun s => g {y | (y, x) ∈ s} State After: no goals Tactic: rfl
#coding=utf-8 ''' Created on 2014年4月13日 @author: Wangliaofan ''' import random import numpy def alpha_errorrate(errornum,totalnum): error=float(errornum)/float(totalnum) return 0.5*numpy.log((1-error)/(error)) #从n个数中随机选出m个数 def genknuth(m,n): for i in range(0,n): if ( random.randint(0,n)%(n-i) )< m: print i m=m-1 return if __name__ == '__main__': genknuth(20,100) al=alpha_errorrate(10,100) print al pass
module Data.GIS.Verified import Control.Algebra import Data.GIS %access public export interface GIS space ivls => VerifiedGIS space ivls | space where conditionA : (r, s, t : space) -> int r s <+> int s t = int r t conditionB : (s : space) -> (i : ivls) -> (int s t = i, int s t' = i) -> t = t'
# Copyright 2021 Huawei Technologies Co., Ltd # # 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. # ============================================================================ """Export""" import os import numpy as np from mindspore.context import set_context, GRAPH_MODE from mindspore.train.serialization import export from mindspore import Tensor from mindspore import load_checkpoint, load_param_into_net from src.model_utils.device_adapter import get_device_id from src.model.net import TSM from src.model_utils.config import config def main(): args = config set_context(mode=GRAPH_MODE, device_target=args.device_target, device_id=get_device_id()) num_class = 174 base_model = args.arch tsm = TSM(num_class, args.num_segments, args.modality, base_model=base_model, consensus_type=args.consensus_type, dropout=args.dropout, img_feature_dim=args.img_feature_dim, partial_bn=not args.no_partialbn, pretrain=args.pretrain, is_shift=args.shift, shift_div=args.shift_div, shift_place=args.shift_place, fc_lr5=not (args.tune_from and args.dataset in args.tune_from), temporal_pool=args.temporal_pool, non_local=args.non_local) tsm.set_train(False) check_point = os.path.join(args.checkpoint_path, args.test_filename) param_dict = load_checkpoint(check_point) load_param_into_net(tsm, param_dict) input_shp = [1, 24, 224, 224] input_array = Tensor(np.random.uniform(-1.0, 1.0, size=input_shp).astype(np.float32)) if args.enable_modelarts: import moxing as mox export(tsm, input_array, file_name='./export_model/tsm', file_format='MINDIR') mox.file.copy_parallel(src_url='./export_model/', dst_url=args.train_url) else: export(tsm, input_array, file_name='tsm', file_format='MINDIR') if __name__ == '__main__': main()
lemma enum_strict_mono: "i \<le> n \<Longrightarrow> j \<le> n \<Longrightarrow> enum i < enum j \<longleftrightarrow> i < j"
module TyTTP import public TyTTP.Core.Error import public TyTTP.Core.Promise import public TyTTP.Core.Request import public TyTTP.Core.Response import public TyTTP.Core.Routing import public TyTTP.Core.Step import public TyTTP.Core.Stream
module AbstractPatterns export spec_gen, RedyFlavoured, TypeObject export and, or, literal, and, wildcard, decons, guard, effect export PatternCompilationError, Target, PatternImpl, PComp export APP, NoncachablePre, NoPre export ChainDict, for_chaindict, child, for_chaindict_dup export BasicPatterns export P_bind, P_tuple, P_type_of, P_vector, P_capture, P_vector3, P_slow_view, P_fast_view export P_svec, P_svec3 export SimpleCachablePre, see_captured_vars, see_captured_vars! export CFGSpec, CFGJump, CFGLabel, CFGItem, init_cfg mutable struct CFGSpec exp :: Expr end struct CFGItem kind :: Symbol name :: Symbol end CFGJump(x::Symbol) = CFGItem(Symbol("@goto"), x) CFGLabel(x::Symbol) = CFGItem(Symbol("@label"), x) init_cfg(ex::Expr) = init_cfg(CFGSpec(ex)) function init_cfg(cfg::CFGSpec) exp = copy(cfg.exp) cfg_info = Dict{Symbol, Symbol}() init_cfg!(exp, cfg_info) exp end const _const_lineno = LineNumberNode(32, "<codegen>") function init_cfg!(ex::Expr, cf_info::Dict{Symbol, Symbol}) args = ex.args for i in eachindex(args) @inbounds arg = args[i] if arg isa CFGItem label = get!(cf_info, arg.name) do gensym(arg.name) end @inbounds args[i] = Expr(:macrocall, arg.kind, _const_lineno, label) elseif arg isa Expr init_cfg!(arg, cf_info) elseif arg isa CFGSpec @inbounds args[i] = init_cfg(arg) end end end include("DataStructure.jl") include("Target.jl") include("PatternSignature.jl") # include("Print.jl") # maybe use one day # include("structures/Print.jl") # maybe use one day include("structures/TypeTagExtraction.jl") include("ADT.jl") include("CaseMerge.jl") include("UserSignature.jl") include("Retagless.jl") include("impl/RedyFlavoured.jl") include("impl/BasicPatterns.jl") using .BasicPatterns const _points_of_view = Dict{Function, Int}(tag_extract => 1, untagless => 2) function spec_gen(branches :: Vector{Pair{Function, Tuple{LineNumberNode, Int}}}) cores = Branch[] for (tf, ln_and_cont) in branches impls = (tag_extract(_points_of_view), untagless(_points_of_view)) type, pat = tf(impls) push!(cores, PatternInfo(pat::TagfulPattern, type::TypeObject) => ln_and_cont) end split_cores = Branch[] case_split!(split_cores, cores) case_merge(split_cores) end end # module
(* Title: Labeled Lifting to Non-Ground Calculi of the Saturation Framework * Author: Sophie Tourret <stourret at mpi-inf.mpg.de>, 2019-2020 *) section \<open>Labeled Liftings\<close> text \<open>This section formalizes the extension of the lifting results to labeled calculi. This corresponds to section 3.4 of the report.\<close> theory Labeled_Lifting_to_Non_Ground_Calculi imports Lifting_to_Non_Ground_Calculi begin subsection \<open>Labeled Lifting with a Family of Well-founded Orderings\<close> locale labeled_lifting_w_wf_ord_family = lifting_with_wf_ordering_family Bot_F Inf_F Bot_G entails_G Inf_G Red_Inf_G Red_F_G \<G>_F \<G>_Inf Prec_F for Bot_F :: "'f set" and Inf_F :: "'f inference set" and Bot_G :: "'g set" and entails_G :: "'g set \<Rightarrow> 'g set \<Rightarrow> bool" (infix "\<Turnstile>G" 50) and Inf_G :: "'g inference set" and Red_Inf_G :: "'g set \<Rightarrow> 'g inference set" and Red_F_G :: "'g set \<Rightarrow> 'g set" and \<G>_F :: "'f \<Rightarrow> 'g set" and \<G>_Inf :: "'f inference \<Rightarrow> 'g inference set option" and Prec_F :: "'g \<Rightarrow> 'f \<Rightarrow> 'f \<Rightarrow> bool" (infix "\<sqsubset>" 50) + fixes l :: \<open>'l itself\<close> and Inf_FL :: \<open>('f \<times> 'l) inference set\<close> assumes Inf_F_to_Inf_FL: \<open>\<iota>\<^sub>F \<in> Inf_F \<Longrightarrow> length (Ll :: 'l list) = length (prems_of \<iota>\<^sub>F) \<Longrightarrow> \<exists>L0. Infer (zip (prems_of \<iota>\<^sub>F) Ll) (concl_of \<iota>\<^sub>F, L0) \<in> Inf_FL\<close> and Inf_FL_to_Inf_F: \<open>\<iota>\<^sub>F\<^sub>L \<in> Inf_FL \<Longrightarrow> Infer (map fst (prems_of \<iota>\<^sub>F\<^sub>L)) (fst (concl_of \<iota>\<^sub>F\<^sub>L)) \<in> Inf_F\<close> begin definition to_F :: \<open>('f \<times> 'l) inference \<Rightarrow> 'f inference\<close> where \<open>to_F \<iota>\<^sub>F\<^sub>L = Infer (map fst (prems_of \<iota>\<^sub>F\<^sub>L)) (fst (concl_of \<iota>\<^sub>F\<^sub>L))\<close> definition Bot_FL :: \<open>('f \<times> 'l) set\<close> where \<open>Bot_FL = Bot_F \<times> UNIV\<close> definition \<G>_F_L :: \<open>('f \<times> 'l) \<Rightarrow> 'g set\<close> where \<open>\<G>_F_L CL = \<G>_F (fst CL)\<close> definition \<G>_Inf_L :: \<open>('f \<times> 'l) inference \<Rightarrow> 'g inference set option\<close> where \<open>\<G>_Inf_L \<iota>\<^sub>F\<^sub>L = \<G>_Inf (to_F \<iota>\<^sub>F\<^sub>L)\<close> (* lem:labeled-grounding-function *) sublocale labeled_standard_lifting: standard_lifting where Bot_F = Bot_FL and Inf_F = Inf_FL and \<G>_F = \<G>_F_L and \<G>_Inf = \<G>_Inf_L proof show "Bot_FL \<noteq> {}" unfolding Bot_FL_def using Bot_F_not_empty by simp next show "B\<in>Bot_FL \<Longrightarrow> \<G>_F_L B \<noteq> {}" for B unfolding \<G>_F_L_def Bot_FL_def using Bot_map_not_empty by auto next show "B\<in>Bot_FL \<Longrightarrow> \<G>_F_L B \<subseteq> Bot_G" for B unfolding \<G>_F_L_def Bot_FL_def using Bot_map by force next fix CL show "\<G>_F_L CL \<inter> Bot_G \<noteq> {} \<longrightarrow> CL \<in> Bot_FL" unfolding \<G>_F_L_def Bot_FL_def using Bot_cond by (metis SigmaE UNIV_I UNIV_Times_UNIV mem_Sigma_iff prod.sel(1)) next fix \<iota> assume i_in: \<open>\<iota> \<in> Inf_FL\<close> and ground_not_none: \<open>\<G>_Inf_L \<iota> \<noteq> None\<close> then show "the (\<G>_Inf_L \<iota>) \<subseteq> Red_Inf_G (\<G>_F_L (concl_of \<iota>))" unfolding \<G>_Inf_L_def \<G>_F_L_def to_F_def using inf_map Inf_FL_to_Inf_F by fastforce qed abbreviation Labeled_Empty_Order :: \<open> ('f \<times> 'l) \<Rightarrow> ('f \<times> 'l) \<Rightarrow> bool\<close> where "Labeled_Empty_Order C1 C2 \<equiv> False" sublocale labeled_lifting_w_empty_ord_family : lifting_with_wf_ordering_family Bot_FL Inf_FL Bot_G entails_G Inf_G Red_Inf_G Red_F_G \<G>_F_L \<G>_Inf_L "\<lambda>g. Labeled_Empty_Order" proof show "po_on Labeled_Empty_Order UNIV" unfolding po_on_def by (simp add: transp_onI wfp_on_imp_irreflp_on) show "wfp_on Labeled_Empty_Order UNIV" unfolding wfp_on_def by simp qed notation "labeled_standard_lifting.entails_\<G>" (infix "\<Turnstile>\<G>L" 50) (* lem:labeled-consequence *) lemma labeled_entailment_lifting: "NL1 \<Turnstile>\<G>L NL2 \<longleftrightarrow> fst ` NL1 \<Turnstile>\<G> fst ` NL2" unfolding labeled_standard_lifting.entails_\<G>_def \<G>_F_L_def entails_\<G>_def by auto lemma (in-) subset_fst: "A \<subseteq> fst ` AB \<Longrightarrow> \<forall>x \<in> A. \<exists>y. (x,y) \<in> AB" by fastforce lemma red_inf_impl: "\<iota> \<in> labeled_lifting_w_empty_ord_family.Red_Inf_\<G> NL \<Longrightarrow> to_F \<iota> \<in> Red_Inf_\<G> (fst ` NL)" unfolding labeled_lifting_w_empty_ord_family.Red_Inf_\<G>_def Red_Inf_\<G>_def \<G>_Inf_L_def \<G>_F_L_def to_F_def using Inf_FL_to_Inf_F by auto (* lem:labeled-saturation *) lemma labeled_saturation_lifting: "labeled_lifting_w_empty_ord_family.lifted_calculus_with_red_crit.saturated NL \<Longrightarrow> empty_order_lifting.lifted_calculus_with_red_crit.saturated (fst ` NL)" unfolding labeled_lifting_w_empty_ord_family.lifted_calculus_with_red_crit.saturated_def empty_order_lifting.lifted_calculus_with_red_crit.saturated_def labeled_standard_lifting.Non_ground.Inf_from_def Non_ground.Inf_from_def proof clarify fix \<iota> assume subs_Red_Inf: "{\<iota> \<in> Inf_FL. set (prems_of \<iota>) \<subseteq> NL} \<subseteq> labeled_lifting_w_empty_ord_family.Red_Inf_\<G> NL" and i_in: "\<iota> \<in> Inf_F" and i_prems: "set (prems_of \<iota>) \<subseteq> fst ` NL" define Lli where "Lli i \<equiv> (SOME x. ((prems_of \<iota>)!i,x) \<in> NL)" for i have [simp]:"((prems_of \<iota>)!i,Lli i) \<in> NL" if "i < length (prems_of \<iota>)" for i using that subset_fst[OF i_prems] unfolding Lli_def by (meson nth_mem someI_ex) define Ll where "Ll \<equiv> map Lli [0..<length (prems_of \<iota>)]" have Ll_length: "length Ll = length (prems_of \<iota>)" unfolding Ll_def by auto have subs_NL: "set (zip (prems_of \<iota>) Ll) \<subseteq> NL" unfolding Ll_def by (auto simp:in_set_zip) obtain L0 where L0: "Infer (zip (prems_of \<iota>) Ll) (concl_of \<iota>, L0) \<in> Inf_FL" using Inf_F_to_Inf_FL[OF i_in Ll_length] .. define \<iota>_FL where "\<iota>_FL = Infer (zip (prems_of \<iota>) Ll) (concl_of \<iota>, L0)" then have "set (prems_of \<iota>_FL) \<subseteq> NL" using subs_NL by simp then have "\<iota>_FL \<in> {\<iota> \<in> Inf_FL. set (prems_of \<iota>) \<subseteq> NL}" unfolding \<iota>_FL_def using L0 by blast then have "\<iota>_FL \<in> labeled_lifting_w_empty_ord_family.Red_Inf_\<G> NL" using subs_Red_Inf by fast moreover have "\<iota> = to_F \<iota>_FL" unfolding to_F_def \<iota>_FL_def using Ll_length by (cases \<iota>) auto ultimately show "\<iota> \<in> Red_Inf_\<G> (fst ` NL)" by (auto intro:red_inf_impl) qed (* lem:labeled-static-ref-compl *) lemma stat_ref_comp_to_labeled_sta_ref_comp: "static_refutational_complete_calculus Bot_F Inf_F (\<Turnstile>\<G>) Red_Inf_\<G> Red_F_\<G> \<Longrightarrow> static_refutational_complete_calculus Bot_FL Inf_FL (\<Turnstile>\<G>L) labeled_lifting_w_empty_ord_family.Red_Inf_\<G> labeled_lifting_w_empty_ord_family.Red_F_\<G>" unfolding static_refutational_complete_calculus_def proof (rule conjI impI; clarify) interpret calculus_with_red_crit Bot_FL Inf_FL labeled_standard_lifting.entails_\<G> labeled_lifting_w_empty_ord_family.Red_Inf_\<G> labeled_lifting_w_empty_ord_family.Red_F_\<G> by (simp add: labeled_lifting_w_empty_ord_family.lifted_calculus_with_red_crit.calculus_with_red_crit_axioms) show "calculus_with_red_crit Bot_FL Inf_FL (\<Turnstile>\<G>L) labeled_lifting_w_empty_ord_family.Red_Inf_\<G> labeled_lifting_w_empty_ord_family.Red_F_\<G>" by standard next assume calc: "calculus_with_red_crit Bot_F Inf_F (\<Turnstile>\<G>) Red_Inf_\<G> Red_F_\<G>" and static: "static_refutational_complete_calculus_axioms Bot_F Inf_F (\<Turnstile>\<G>) Red_Inf_\<G>" show "static_refutational_complete_calculus_axioms Bot_FL Inf_FL (\<Turnstile>\<G>L) labeled_lifting_w_empty_ord_family.Red_Inf_\<G>" unfolding static_refutational_complete_calculus_axioms_def proof (intro conjI impI allI) fix Bl :: \<open>'f \<times> 'l\<close> and Nl :: \<open>('f \<times> 'l) set\<close> assume Bl_in: \<open>Bl \<in> Bot_FL\<close> and Nl_sat: \<open>labeled_lifting_w_empty_ord_family.lifted_calculus_with_red_crit.saturated Nl\<close> and Nl_entails_Bl: \<open>Nl \<Turnstile>\<G>L {Bl}\<close> have static_axioms: "B \<in> Bot_F \<longrightarrow> empty_order_lifting.lifted_calculus_with_red_crit.saturated N \<longrightarrow> N \<Turnstile>\<G> {B} \<longrightarrow> (\<exists>B'\<in>Bot_F. B' \<in> N)" for B N using static[unfolded static_refutational_complete_calculus_axioms_def] by fast define B where "B = fst Bl" have B_in: "B \<in> Bot_F" using Bl_in Bot_FL_def B_def SigmaE by force define N where "N = fst ` Nl" have N_sat: "empty_order_lifting.lifted_calculus_with_red_crit.saturated N" using N_def Nl_sat labeled_saturation_lifting by blast have N_entails_B: "N \<Turnstile>\<G> {B}" using Nl_entails_Bl unfolding labeled_entailment_lifting N_def B_def by force have "\<exists>B' \<in> Bot_F. B' \<in> N" using B_in N_sat N_entails_B static_axioms[of B N] by blast then obtain B' where in_Bot: "B' \<in> Bot_F" and in_N: "B' \<in> N" by force then have "B' \<in> fst ` Bot_FL" unfolding Bot_FL_def by fastforce obtain Bl' where in_Nl: "Bl' \<in> Nl" and fst_Bl': "fst Bl' = B'" using in_N unfolding N_def by blast have "Bl' \<in> Bot_FL" unfolding Bot_FL_def using fst_Bl' in_Bot vimage_fst by fastforce then show \<open>\<exists>Bl'\<in>Bot_FL. Bl' \<in> Nl\<close> using in_Nl by blast qed qed end subsection \<open>Labeled Lifting with a Family of Redundancy Criteria\<close> locale labeled_lifting_with_red_crit_family = no_labels: standard_lifting_with_red_crit_family Inf_F Bot_G Inf_G Q entails_q Red_Inf_q Red_F_q Bot_F \<G>_F_q \<G>_Inf_q "\<lambda>g. Empty_Order" for Bot_F :: "'f set" and Inf_F :: "'f inference set" and Bot_G :: "'g set" and Q :: "'q itself" and entails_q :: "'q \<Rightarrow> 'g set \<Rightarrow> 'g set \<Rightarrow> bool" and Inf_G :: "'g inference set" and Red_Inf_q :: "'q \<Rightarrow> 'g set \<Rightarrow> 'g inference set" and Red_F_q :: "'q \<Rightarrow> 'g set \<Rightarrow> 'g set" and \<G>_F_q :: "'q \<Rightarrow> 'f \<Rightarrow> 'g set" and \<G>_Inf_q :: "'q \<Rightarrow> 'f inference \<Rightarrow> 'g inference set option" + fixes l :: "'l itself" and Inf_FL :: \<open>('f \<times> 'l) inference set\<close> assumes Inf_F_to_Inf_FL: \<open>\<iota>\<^sub>F \<in> Inf_F \<Longrightarrow> length (Ll :: 'l list) = length (prems_of \<iota>\<^sub>F) \<Longrightarrow> \<exists>L0. Infer (zip (prems_of \<iota>\<^sub>F) Ll) (concl_of \<iota>\<^sub>F, L0) \<in> Inf_FL\<close> and Inf_FL_to_Inf_F: \<open>\<iota>\<^sub>F\<^sub>L \<in> Inf_FL \<Longrightarrow> Infer (map fst (prems_of \<iota>\<^sub>F\<^sub>L)) (fst (concl_of \<iota>\<^sub>F\<^sub>L)) \<in> Inf_F\<close> begin definition to_F :: \<open>('f \<times> 'l) inference \<Rightarrow> 'f inference\<close> where \<open>to_F \<iota>\<^sub>F\<^sub>L = Infer (map fst (prems_of \<iota>\<^sub>F\<^sub>L)) (fst (concl_of \<iota>\<^sub>F\<^sub>L))\<close> definition Bot_FL :: \<open>('f \<times> 'l) set\<close> where \<open>Bot_FL = Bot_F \<times> UNIV\<close> definition \<G>_F_L_q :: \<open>'q \<Rightarrow> ('f \<times> 'l) \<Rightarrow> 'g set\<close> where \<open>\<G>_F_L_q q CL = \<G>_F_q q (fst CL)\<close> definition \<G>_Inf_L_q :: \<open>'q \<Rightarrow> ('f \<times> 'l) inference \<Rightarrow> 'g inference set option\<close> where \<open>\<G>_Inf_L_q q \<iota>\<^sub>F\<^sub>L = \<G>_Inf_q q (to_F \<iota>\<^sub>F\<^sub>L)\<close> definition \<G>_set_L_q :: "'q \<Rightarrow> ('f \<times> 'l) set \<Rightarrow> 'g set" where "\<G>_set_L_q q N \<equiv> \<Union> (\<G>_F_L_q q ` N)" definition Red_Inf_\<G>_L_q :: "'q \<Rightarrow> ('f \<times> 'l) set \<Rightarrow> ('f \<times> 'l) inference set" where "Red_Inf_\<G>_L_q q N = {\<iota> \<in> Inf_FL. ((\<G>_Inf_L_q q \<iota>) \<noteq> None \<and> the (\<G>_Inf_L_q q \<iota>) \<subseteq> Red_Inf_q q (\<G>_set_L_q q N)) \<or> ((\<G>_Inf_L_q q \<iota> = None) \<and> \<G>_F_L_q q (concl_of \<iota>) \<subseteq> (\<G>_set_L_q q N \<union> Red_F_q q (\<G>_set_L_q q N)))}" definition Red_Inf_\<G>_L_Q :: "('f \<times> 'l) set \<Rightarrow> ('f \<times> 'l) inference set" where "Red_Inf_\<G>_L_Q N = \<Inter> {X N |X. X \<in> (Red_Inf_\<G>_L_q ` UNIV)}" definition Labeled_Empty_Order :: \<open> ('f \<times> 'l) \<Rightarrow> ('f \<times> 'l) \<Rightarrow> bool\<close> where "Labeled_Empty_Order C1 C2 \<equiv> False" definition Red_F_\<G>_empty_L_q :: "'q \<Rightarrow> ('f \<times> 'l) set \<Rightarrow> ('f \<times> 'l) set" where "Red_F_\<G>_empty_L_q q N = {C. \<forall>D \<in> \<G>_F_L_q q C. D \<in> Red_F_q q (\<G>_set_L_q q N) \<or> (\<exists>E \<in> N. Labeled_Empty_Order E C \<and> D \<in> \<G>_F_L_q q E)}" definition Red_F_\<G>_empty_L :: "('f \<times> 'l) set \<Rightarrow> ('f \<times> 'l) set" where "Red_F_\<G>_empty_L N = \<Inter> {X N |X. X \<in> (Red_F_\<G>_empty_L_q ` UNIV)}" definition entails_\<G>_L_q :: "'q \<Rightarrow> ('f \<times> 'l) set \<Rightarrow> ('f \<times> 'l) set \<Rightarrow> bool" where "entails_\<G>_L_q q N1 N2 \<equiv> entails_q q (\<G>_set_L_q q N1) (\<G>_set_L_q q N2)" definition entails_\<G>_L_Q :: "('f \<times> 'l) set \<Rightarrow> ('f \<times> 'l) set \<Rightarrow> bool" (infix "\<Turnstile>\<inter>L" 50) where "entails_\<G>_L_Q N1 N2 \<equiv> \<forall>q. entails_\<G>_L_q q N1 N2" lemma lifting_q: "labeled_lifting_w_wf_ord_family Bot_F Inf_F Bot_G (entails_q q) Inf_G (Red_Inf_q q) (Red_F_q q) (\<G>_F_q q) (\<G>_Inf_q q) (\<lambda>g. Empty_Order) Inf_FL" proof - fix q show "labeled_lifting_w_wf_ord_family Bot_F Inf_F Bot_G (entails_q q) Inf_G (Red_Inf_q q) (Red_F_q q) (\<G>_F_q q) (\<G>_Inf_q q) (\<lambda>g. Empty_Order) Inf_FL" using no_labels.standard_lifting_family Inf_F_to_Inf_FL Inf_FL_to_Inf_F by (simp add: labeled_lifting_w_wf_ord_family_axioms_def labeled_lifting_w_wf_ord_family_def) qed lemma lifted_q: "standard_lifting Bot_FL Inf_FL Bot_G Inf_G (entails_q q) (Red_Inf_q q) (Red_F_q q) (\<G>_F_L_q q) (\<G>_Inf_L_q q)" proof - fix q interpret q_lifting: labeled_lifting_w_wf_ord_family Bot_F Inf_F Bot_G "entails_q q" Inf_G "Red_Inf_q q" "Red_F_q q" "\<G>_F_q q" "\<G>_Inf_q q" "\<lambda>g. Empty_Order" l Inf_FL using lifting_q . have "\<G>_F_L_q q = q_lifting.\<G>_F_L" unfolding \<G>_F_L_q_def q_lifting.\<G>_F_L_def by simp moreover have "\<G>_Inf_L_q q = q_lifting.\<G>_Inf_L" unfolding \<G>_Inf_L_q_def q_lifting.\<G>_Inf_L_def to_F_def q_lifting.to_F_def by simp moreover have "Bot_FL = q_lifting.Bot_FL" unfolding Bot_FL_def q_lifting.Bot_FL_def by simp ultimately show "standard_lifting Bot_FL Inf_FL Bot_G Inf_G (entails_q q) (Red_Inf_q q) (Red_F_q q) (\<G>_F_L_q q) (\<G>_Inf_L_q q)" using q_lifting.labeled_standard_lifting.standard_lifting_axioms by simp qed lemma ord_fam_lifted_q: "lifting_with_wf_ordering_family Bot_FL Inf_FL Bot_G (entails_q q) Inf_G (Red_Inf_q q) (Red_F_q q) (\<G>_F_L_q q) (\<G>_Inf_L_q q) (\<lambda>g. Labeled_Empty_Order)" proof - fix q interpret standard_q_lifting: standard_lifting Bot_FL Inf_FL Bot_G Inf_G "entails_q q" "Red_Inf_q q" "Red_F_q q" "\<G>_F_L_q q" "\<G>_Inf_L_q q" using lifted_q . have "minimal_element Labeled_Empty_Order UNIV" unfolding Labeled_Empty_Order_def by (simp add: minimal_element.intro po_on_def transp_onI wfp_on_imp_irreflp_on) then show "lifting_with_wf_ordering_family Bot_FL Inf_FL Bot_G (entails_q q) Inf_G (Red_Inf_q q) (Red_F_q q) (\<G>_F_L_q q) (\<G>_Inf_L_q q) (\<lambda>g. Labeled_Empty_Order)" using standard_q_lifting.standard_lifting_axioms by (simp add: lifting_with_wf_ordering_family_axioms.intro lifting_with_wf_ordering_family_def) qed lemma all_lifted_red_crit: "calculus_with_red_crit Bot_FL Inf_FL (entails_\<G>_L_q q) (Red_Inf_\<G>_L_q q) (Red_F_\<G>_empty_L_q q)" proof - fix q interpret ord_q_lifting: lifting_with_wf_ordering_family Bot_FL Inf_FL Bot_G "entails_q q" Inf_G "Red_Inf_q q" "Red_F_q q" "\<G>_F_L_q q" "\<G>_Inf_L_q q" "\<lambda>g. Labeled_Empty_Order" using ord_fam_lifted_q . have "entails_\<G>_L_q q = ord_q_lifting.entails_\<G>" unfolding entails_\<G>_L_q_def \<G>_set_L_q_def ord_q_lifting.entails_\<G>_def by simp moreover have "Red_Inf_\<G>_L_q q = ord_q_lifting.Red_Inf_\<G>" unfolding Red_Inf_\<G>_L_q_def ord_q_lifting.Red_Inf_\<G>_def \<G>_set_L_q_def by simp moreover have "Red_F_\<G>_empty_L_q q = ord_q_lifting.Red_F_\<G>" unfolding Red_F_\<G>_empty_L_q_def ord_q_lifting.Red_F_\<G>_def \<G>_set_L_q_def by simp ultimately show "calculus_with_red_crit Bot_FL Inf_FL (entails_\<G>_L_q q) (Red_Inf_\<G>_L_q q) (Red_F_\<G>_empty_L_q q)" using ord_q_lifting.lifted_calculus_with_red_crit.calculus_with_red_crit_axioms by argo qed lemma all_lifted_cons_rel: "consequence_relation Bot_FL (entails_\<G>_L_q q)" proof - fix q interpret q_red_crit: calculus_with_red_crit Bot_FL Inf_FL "entails_\<G>_L_q q" "Red_Inf_\<G>_L_q q" "Red_F_\<G>_empty_L_q q" using all_lifted_red_crit . show "consequence_relation Bot_FL (entails_\<G>_L_q q)" using q_red_crit.consequence_relation_axioms . qed sublocale labeled_cons_rel_family: consequence_relation_family Bot_FL Q entails_\<G>_L_q using all_lifted_cons_rel no_labels.lifted_calc_w_red_crit_family.Bot_not_empty unfolding Bot_FL_def by (simp add: consequence_relation_family.intro) sublocale with_labels: calculus_with_red_crit_family Bot_FL Inf_FL Q entails_\<G>_L_q Red_Inf_\<G>_L_q Red_F_\<G>_empty_L_q using calculus_with_red_crit_family.intro[OF labeled_cons_rel_family.consequence_relation_family_axioms] all_lifted_cons_rel by (simp add: all_lifted_red_crit calculus_with_red_crit_family_axioms_def) notation "no_labels.entails_\<G>_Q" (infix "\<Turnstile>\<inter>" 50) (* lem:labeled-consequence-intersection *) lemma labeled_entailment_lifting: "NL1 \<Turnstile>\<inter>L NL2 \<longleftrightarrow> fst ` NL1 \<Turnstile>\<inter> fst ` NL2" unfolding no_labels.entails_\<G>_Q_def no_labels.entails_\<G>_q_def no_labels.\<G>_set_q_def entails_\<G>_L_Q_def entails_\<G>_L_q_def \<G>_set_L_q_def \<G>_F_L_q_def by force lemma subset_fst: "A \<subseteq> fst ` AB \<Longrightarrow> \<forall>x \<in> A. \<exists>y. (x,y) \<in> AB" by fastforce lemma red_inf_impl: "\<iota> \<in> with_labels.Red_Inf_Q NL \<Longrightarrow> to_F \<iota> \<in> no_labels.empty_ord_lifted_calc_w_red_crit_family.Red_Inf_Q (fst ` NL)" unfolding no_labels.empty_ord_lifted_calc_w_red_crit_family.Red_Inf_Q_def with_labels.Red_Inf_Q_def proof clarify fix X Xa q assume i_in_inter: "\<iota> \<in> \<Inter> {X NL |X. X \<in> Red_Inf_\<G>_L_q ` UNIV}" have i_in_q: "\<iota> \<in> Red_Inf_\<G>_L_q q NL" using i_in_inter image_eqI by blast then have i_in: "\<iota> \<in> Inf_FL" unfolding Red_Inf_\<G>_L_q_def by blast have to_F_in: "to_F \<iota> \<in> Inf_F" unfolding to_F_def using Inf_FL_to_Inf_F[OF i_in] . have rephrase1: "(\<Union>CL\<in>NL. \<G>_F_q q (fst CL)) = (\<Union> (\<G>_F_q q ` fst ` NL))" by blast have rephrase2: "fst (concl_of \<iota>) = concl_of (to_F \<iota>)" unfolding concl_of_def to_F_def by simp have subs_red: "((\<G>_Inf_L_q q \<iota>) \<noteq> None \<and> the (\<G>_Inf_L_q q \<iota>) \<subseteq> Red_Inf_q q (\<G>_set_L_q q NL)) \<or> ((\<G>_Inf_L_q q \<iota> = None) \<and> \<G>_F_L_q q (concl_of \<iota>) \<subseteq> (\<G>_set_L_q q NL \<union> Red_F_q q (\<G>_set_L_q q NL)))" using i_in_q unfolding Red_Inf_\<G>_L_q_def by blast then have to_F_subs_red: "((\<G>_Inf_q q (to_F \<iota>)) \<noteq> None \<and> the (\<G>_Inf_q q (to_F \<iota>)) \<subseteq> Red_Inf_q q (no_labels.\<G>_set_q q (fst ` NL))) \<or> ((\<G>_Inf_q q (to_F \<iota>) = None) \<and> \<G>_F_q q (concl_of (to_F \<iota>)) \<subseteq> (no_labels.\<G>_set_q q (fst ` NL) \<union> Red_F_q q (no_labels.\<G>_set_q q (fst ` NL))))" unfolding \<G>_Inf_L_q_def \<G>_set_L_q_def no_labels.\<G>_set_q_def \<G>_F_L_q_def using rephrase1 rephrase2 by metis then show "to_F \<iota> \<in> no_labels.Red_Inf_\<G>_q q (fst ` NL)" using to_F_in unfolding no_labels.Red_Inf_\<G>_q_def by simp qed (* lem:labeled-saturation-intersection *) lemma labeled_family_saturation_lifting: "with_labels.inter_red_crit_calculus.saturated NL \<Longrightarrow> no_labels.lifted_calc_w_red_crit_family.inter_red_crit_calculus.saturated (fst ` NL)" unfolding with_labels.inter_red_crit_calculus.saturated_def no_labels.lifted_calc_w_red_crit_family.inter_red_crit_calculus.saturated_def with_labels.Inf_from_def no_labels.Non_ground.Inf_from_def proof clarify fix \<iota>F assume labeled_sat: "{\<iota> \<in> Inf_FL. set (prems_of \<iota>) \<subseteq> NL} \<subseteq> with_labels.Red_Inf_Q NL" and iF_in: "\<iota>F \<in> Inf_F" and iF_prems: "set (prems_of \<iota>F) \<subseteq> fst ` NL" define Lli where "Lli i \<equiv> (SOME x. ((prems_of \<iota>F)!i,x) \<in> NL)" for i have [simp]:"((prems_of \<iota>F)!i,Lli i) \<in> NL" if "i < length (prems_of \<iota>F)" for i using that subset_fst[OF iF_prems] nth_mem someI_ex unfolding Lli_def by metis define Ll where "Ll \<equiv> map Lli [0..<length (prems_of \<iota>F)]" have Ll_length: "length Ll = length (prems_of \<iota>F)" unfolding Ll_def by auto have subs_NL: "set (zip (prems_of \<iota>F) Ll) \<subseteq> NL" unfolding Ll_def by (auto simp:in_set_zip) obtain L0 where L0: "Infer (zip (prems_of \<iota>F) Ll) (concl_of \<iota>F, L0) \<in> Inf_FL" using Inf_F_to_Inf_FL[OF iF_in Ll_length] .. define \<iota>FL where "\<iota>FL = Infer (zip (prems_of \<iota>F) Ll) (concl_of \<iota>F, L0)" then have "set (prems_of \<iota>FL) \<subseteq> NL" using subs_NL by simp then have "\<iota>FL \<in> {\<iota> \<in> Inf_FL. set (prems_of \<iota>) \<subseteq> NL}" unfolding \<iota>FL_def using L0 by blast then have "\<iota>FL \<in> with_labels.Red_Inf_Q NL" using labeled_sat by fast moreover have "\<iota>F = to_F \<iota>FL" unfolding to_F_def \<iota>FL_def using Ll_length by (cases \<iota>F) auto ultimately show "\<iota>F \<in> no_labels.empty_ord_lifted_calc_w_red_crit_family.Red_Inf_Q (fst ` NL)" by (auto intro:red_inf_impl) qed (* thm:labeled-static-ref-compl-intersection *) theorem labeled_static_ref: "static_refutational_complete_calculus Bot_F Inf_F (\<Turnstile>\<inter>) no_labels.empty_ord_lifted_calc_w_red_crit_family.Red_Inf_Q no_labels.empty_ord_lifted_calc_w_red_crit_family.Red_F_Q \<Longrightarrow> static_refutational_complete_calculus Bot_FL Inf_FL (\<Turnstile>\<inter>L) with_labels.Red_Inf_Q with_labels.Red_F_Q" unfolding static_refutational_complete_calculus_def proof (rule conjI impI; clarify) show "calculus_with_red_crit Bot_FL Inf_FL (\<Turnstile>\<inter>L) with_labels.Red_Inf_Q with_labels.Red_F_Q" using with_labels.inter_red_crit_calculus.calculus_with_red_crit_axioms unfolding labeled_cons_rel_family.entails_Q_def entails_\<G>_L_Q_def . next assume calc: "calculus_with_red_crit Bot_F Inf_F (\<Turnstile>\<inter>) no_labels.empty_ord_lifted_calc_w_red_crit_family.Red_Inf_Q no_labels.empty_ord_lifted_calc_w_red_crit_family.Red_F_Q" and static: "static_refutational_complete_calculus_axioms Bot_F Inf_F (\<Turnstile>\<inter>) no_labels.empty_ord_lifted_calc_w_red_crit_family.Red_Inf_Q" show "static_refutational_complete_calculus_axioms Bot_FL Inf_FL (\<Turnstile>\<inter>L) with_labels.Red_Inf_Q" unfolding static_refutational_complete_calculus_axioms_def proof (intro conjI impI allI) fix Bl :: \<open>'f \<times> 'l\<close> and Nl :: \<open>('f \<times> 'l) set\<close> assume Bl_in: \<open>Bl \<in> Bot_FL\<close> and Nl_sat: \<open>with_labels.inter_red_crit_calculus.saturated Nl\<close> and Nl_entails_Bl: \<open>Nl \<Turnstile>\<inter>L {Bl}\<close> have static_axioms: "B \<in> Bot_F \<longrightarrow> no_labels.lifted_calc_w_red_crit_family.inter_red_crit_calculus.saturated N \<longrightarrow> N \<Turnstile>\<inter> {B} \<longrightarrow> (\<exists>B'\<in>Bot_F. B' \<in> N)" for B N using static[unfolded static_refutational_complete_calculus_axioms_def] by fast define B where "B = fst Bl" have B_in: "B \<in> Bot_F" using Bl_in Bot_FL_def B_def SigmaE by force define N where "N = fst ` Nl" have N_sat: "no_labels.lifted_calc_w_red_crit_family.inter_red_crit_calculus.saturated N" using N_def Nl_sat labeled_family_saturation_lifting by blast have N_entails_B: "N \<Turnstile>\<inter> {B}" using Nl_entails_Bl unfolding labeled_entailment_lifting N_def B_def by force have "\<exists>B' \<in> Bot_F. B' \<in> N" using B_in N_sat N_entails_B static_axioms[of B N] by blast then obtain B' where in_Bot: "B' \<in> Bot_F" and in_N: "B' \<in> N" by force then have "B' \<in> fst ` Bot_FL" unfolding Bot_FL_def by fastforce obtain Bl' where in_Nl: "Bl' \<in> Nl" and fst_Bl': "fst Bl' = B'" using in_N unfolding N_def by blast have "Bl' \<in> Bot_FL" unfolding Bot_FL_def using fst_Bl' in_Bot vimage_fst by fastforce then show \<open>\<exists>Bl'\<in>Bot_FL. Bl' \<in> Nl\<close> using in_Nl by blast qed qed end end
lemma INF_Lim: fixes X :: "nat \<Rightarrow> 'a::{complete_linorder,linorder_topology}" assumes dec: "decseq X" and l: "X \<longlonglongrightarrow> l" shows "(INF n. X n) = l"
function P=perimeter(r,N) % find perimeter of the polygon n=1:N-1; r1=r(:,n); % current points r2=r(:,n+1); % next points dr=r1-r2; % difference dr2=sum(dr.^2); % squared lenghts drl=sqrt(dr2); % lenghts P=sum(drl); % perimeter % last and first: r1=r(:,N); % current points r2=r(:,1); % next points dr=r1-r2; % difference dr2=sum(dr.^2); % squared lenghts drl=sqrt(dr2); % lenghts P=P+drl; % perimeter
The design of the wine room was created utilizing a reclaimed door and wood from a barn located on the property. We were able to use the reclaimed door's existing hardware to provide rustic charm and appeal. In addition the wood was used to create the "X" pattern shelving with accent lighting to provide warm ambient light that enhances the overall look.
(* * Copyright 2020, Data61, CSIRO (ABN 41 687 119 230) * * SPDX-License-Identifier: BSD-2-Clause *) theory ArchArraysMemInstance imports ArraysMemInstance begin (* Showing arrays are in mem_type requires maximum sizes for objects, and maximum counts for elements *) class array_outer_max_size = mem_type + assumes array_outer_max_size_ax: "size_of TYPE('a::c_type) < 2 ^ 19" class array_max_count = finite + assumes array_max_count_ax: "CARD ('a) <= 2 ^ 13" instance array :: (array_outer_max_size, array_max_count) mem_type apply intro_classes apply simp apply (subgoal_tac "addr_card = 2 ^ (addr_bitsize - 19) * 2 ^ 19") apply (erule ssubst) apply (rule less_le_trans[where y = "card (UNIV::'b set) * 2 ^ 19"]) apply (rule mult_less_mono2) apply (rule array_outer_max_size_ax) apply simp apply (rule mult_le_mono1) apply (rule le_trans[where j = "2 ^ 13"]) apply (rule array_max_count_ax) apply simp apply simp apply (simp add: addr_card) done class array_inner_max_size = array_outer_max_size + assumes array_inner_max_size_ax: "size_of TYPE('a::c_type) < 2 ^ 6" instance array :: (array_inner_max_size, array_max_count) array_outer_max_size apply intro_classes apply simp apply (rule order_less_le_trans) apply (rule mult_le_less_imp_less) apply (rule array_max_count_ax) apply (rule array_inner_max_size_ax) apply simp apply simp apply simp done instance word :: (len8) array_outer_max_size apply intro_classes apply(simp add: size_of_def) apply(subgoal_tac "len_of TYPE('a) \<le> 128") apply simp apply(rule len8_width) done instance word :: (len8) array_inner_max_size apply intro_classes apply(simp add: size_of_def) apply(subgoal_tac "len_of TYPE('a) \<le> 128") apply simp apply(rule len8_width) done instance ptr :: (c_type) array_outer_max_size apply intro_classes apply (simp add: size_of_def) done instance ptr :: (c_type) array_inner_max_size apply intro_classes apply (simp add: size_of_def) done class lt12 = finite + assumes lt12_ax: "CARD ('a) < 2 ^ 12" class lt11 = lt12 + assumes lt11_ax: "CARD ('a) < 2 ^ 11" class lt10 = lt11 + assumes lt10_ax: "CARD ('a) < 2 ^ 10" class lt9 = lt10 + assumes lt9_ax: "CARD ('a) < 2 ^ 9" class lt8 = lt9 + assumes lt8_ax: "CARD ('a) < 2 ^ 8" class lt7 = lt8 + assumes lt7_ax: "CARD ('a) < 2 ^ 7" class lt6 = lt7 + assumes lt6_ax: "CARD ('a) < 2 ^ 6" class lt5 = lt6 + assumes lt5_ax: "CARD ('a) < 2 ^ 5" class lt4 = lt5 + assumes lt4_ax: "CARD ('a) < 2 ^ 4" class lt3 = lt4 + assumes lt3_ax: "CARD ('a) < 2 ^ 3" class lt2 = lt3 + assumes lt2_ax: "CARD ('a) < 2 ^ 2" class lt1 = lt2 + assumes lt1_ax: "CARD ('a) < 2 ^ 1" instance bit0 :: (lt12) array_max_count using lt12_ax[where 'a='a] by intro_classes simp instance bit1 :: (lt12) array_max_count using lt12_ax[where 'a='a] by intro_classes simp instance bit0 :: (lt11) lt12 using lt11_ax[where 'a='a] by intro_classes simp instance bit1 :: (lt11) lt12 using lt11_ax[where 'a='a] by intro_classes simp instance bit0 :: (lt10) lt11 using lt10_ax[where 'a='a] by intro_classes simp instance bit1 :: (lt10) lt11 using lt10_ax[where 'a='a] by intro_classes simp instance bit0 :: (lt9) lt10 using lt9_ax[where 'a='a] by intro_classes simp instance bit1 :: (lt9) lt10 using lt9_ax[where 'a='a] by intro_classes simp instance bit0 :: (lt8) lt9 using lt8_ax[where 'a='a] by intro_classes simp instance bit1 :: (lt8) lt9 using lt8_ax[where 'a='a] by intro_classes simp instance bit0 :: (lt7) lt8 using lt7_ax[where 'a='a] by intro_classes simp instance bit1 :: (lt7) lt8 using lt7_ax[where 'a='a] by intro_classes simp instance bit0 :: (lt6) lt7 using lt6_ax[where 'a='a] by intro_classes simp instance bit1 :: (lt6) lt7 using lt6_ax[where 'a='a] by intro_classes simp instance bit0 :: (lt5) lt6 using lt5_ax[where 'a='a] by intro_classes simp instance bit1 :: (lt5) lt6 using lt5_ax[where 'a='a] by intro_classes simp instance bit0 :: (lt4) lt5 using lt4_ax[where 'a='a] by intro_classes simp instance bit1 :: (lt4) lt5 using lt4_ax[where 'a='a] by intro_classes simp instance bit0 :: (lt3) lt4 using lt3_ax[where 'a='a] by intro_classes simp instance bit1 :: (lt3) lt4 using lt3_ax[where 'a='a] by intro_classes simp instance bit0 :: (lt2) lt3 using lt2_ax[where 'a='a] by intro_classes simp instance bit1 :: (lt2) lt3 using lt2_ax[where 'a='a] by intro_classes simp instance bit0 :: (lt1) lt2 using lt1_ax[where 'a='a] by intro_classes simp instance bit1 :: (lt1) lt2 using lt1_ax[where 'a='a] by intro_classes simp instance num1 :: lt1 by (intro_classes, simp_all) (* don't understand why this also seems to be necessary *) instance num1 :: array_max_count by (intro_classes, simp) (* introduce hackish handling of 8192 type by making a copy of the type under a constructor, and then manually showing that it is an instance of array_max_count *) datatype array_max_count_ty = array_max_count_ty "8192" (* ML c-parser code also needs to know at which array size to use this type *) ML \<open> structure ArchArrayMaxCount = struct val array_max_count = 8192 end \<close> lemma univ_array_max_count_ty: "(UNIV::array_max_count_ty set) = image array_max_count_ty (UNIV::8192 set)" apply (simp add: set_eq_iff image_iff) apply (rule_tac allI) apply (rule_tac array_max_count_ty.induct) apply simp done instance "array_max_count_ty" :: finite apply intro_classes apply (simp add: univ_array_max_count_ty) done lemma card_array_max_count_ty[simp]: "CARD(array_max_count_ty) = CARD(8192)" apply (simp add: univ_array_max_count_ty card_image inj_on_def) done instance "array_max_count_ty" :: array_max_count by intro_classes simp end
From Test Require Import tactic. Section FOFProblem. Variable Universe : Set. Variable UniverseElement : Universe. Variable wd_ : Universe -> Universe -> Prop. Variable col_ : Universe -> Universe -> Universe -> Prop. Variable col_swap1_1 : (forall A B C : Universe, (col_ A B C -> col_ B A C)). Variable col_swap2_2 : (forall A B C : Universe, (col_ A B C -> col_ B C A)). Variable col_triv_3 : (forall A B : Universe, col_ A B B). Variable wd_swap_4 : (forall A B : Universe, (wd_ A B -> wd_ B A)). Variable col_trans_5 : (forall P Q A B C : Universe, ((wd_ P Q /\ (col_ P Q A /\ (col_ P Q B /\ col_ P Q C))) -> col_ A B C)). Theorem pipo_6 : (forall O A B Aprime Bprime : Universe, ((wd_ A B /\ (wd_ Aprime Bprime /\ (wd_ O A /\ (wd_ O Aprime /\ (wd_ A Aprime /\ (wd_ B Bprime /\ (wd_ A Bprime /\ (wd_ B Aprime /\ (col_ O A B /\ (col_ O Aprime Bprime /\ (col_ A Aprime Bprime /\ col_ B Aprime Bprime))))))))))) -> col_ O A Aprime)). Proof. time tac. Qed. End FOFProblem.
Egyptian writings describe the gods ' bodies in detail . They are made of precious materials ; their flesh is gold , their bones are silver , and their hair is lapis lazuli . They give off a scent that the Egyptians likened to the incense used in rituals . Some texts give precise descriptions of particular deities , including their height and eye color . Yet these characteristics are not fixed ; in myths , gods change their appearances to suit their own purposes . Egyptian texts often refer to deities ' true , underlying forms as " mysterious " . The Egyptians ' visual representations of their gods are therefore not literal . They symbolize specific aspects of each deity 's character , functioning much like the ideograms in hieroglyphic writing . For this reason , the funerary god Anubis is commonly shown in Egyptian art as a dog or jackal , a creature whose scavenging habits threaten the preservation of buried mummies , in an effort to counter this threat and employ it for protection . His black coloring alludes to the color of mummified flesh and to the fertile black soil that Egyptians saw as a symbol of resurrection .
module State import Terminal import Document import Data.Vect %default total public export data State : Type where MkState : Document -> State export showState : State -> IO () showState (MkState doc) = do clearScreen showDocument doc export initState : Document -> State initState doc = MkState doc export saveDocument : State -> IO () saveDocument (MkState doc) = do saveDocument doc pure ()